import { execFile } from "node:child_process"; import { randomUUID } from "node:crypto"; import { mkdir, statfs, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; import { and, asc, eq, inArray, isNotNull, isNull, lt, or, sql } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { runMigrations } from "@/lib/db/migrate"; import { ACTIVE_JOB_STATES, type JobKind, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema"; import { coreEnv } from "@/lib/env"; import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability"; import { backfillMetadata } from "@/lib/hub/refresh"; import { DeleteRunner } from "./delete"; import { flushBenchmarkLogs, recoverBenchmarks, refreshSummaries, stopBenchmarks, tickBenchmarks } from "./benchmarks"; import { reportL80Status, tickPublications } from "./publish"; import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments"; import { DownloadRunner } from "./download"; import { log } from "./log"; import type { Runner } from "./runner"; import { docker, handlePullRequests, refreshDockerInfo, resetStalePulls, seedRuntimePresets, syncImageStates } from "./runtimes"; import { scanModelsDir } from "./scan"; import { VerifyRunner } from "./verify"; import { settleModelStatus } from "./model-status"; const HEARTBEAT_MS = 5_000; const TICK_MS = 1_000; /** A lease older than this is considered abandoned (worker crashed without releasing it). */ const LEASE_STALE_MS = 20_000; const SHUTDOWN_GRACE_MS = 8_000; /** How often to look for models whose Hub check is due (the check interval itself is configurable). */ const HUB_CHECK_SCAN_MS = 10 * 60_000; /** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */ const FOLDER_SCAN_MS = 2 * 60_000; const DOCKER_INFO_MS = 5 * 60_000; const IMAGE_SYNC_MS = 60_000; const PULL_CHECK_MS = 3_000; const DEPLOYMENT_TICK_MS = 2_000; const BENCHMARK_TICK_MS = 2_000; /** Touched on every heartbeat; the Docker healthcheck checks its age. */ const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive"); const instanceId = randomUUID(); const startedAt = new Date(); const runners = new Map(); let hfVersion: string | null = null; let stopping = false; async function detectHfVersion(): Promise { try { const { stdout } = await promisify(execFile)("hf", ["version"], { timeout: 30_000, env: { ...process.env, NO_COLOR: "1" }, }); const m = stdout.match(/version:\s*(\S+)/); return m ? `huggingface_hub ${m[1]}` : stdout.trim() || null; } catch { return null; } } async function diskSpace(dir: string) { try { const s = await statfs(dir); return { modelsDirFreeBytes: s.bavail * s.bsize, modelsDirTotalBytes: s.blocks * s.bsize }; } catch { return { modelsDirFreeBytes: null, modelsDirTotalBytes: null }; } } // --------------------------------------------------------------------------- // Lease: only one worker may run, otherwise two processes would run the same jobs. // --------------------------------------------------------------------------- async function tryAcquireLease(): Promise { const now = new Date(); await db() .insert(workerState) .values({ id: "worker", startedAt: now, heartbeatAt: new Date(0) }) .onConflictDoNothing(); const won = await db() .update(workerState) .set({ instanceId, pid: process.pid, startedAt, heartbeatAt: now }) .where( and( eq(workerState.id, "worker"), or( isNull(workerState.instanceId), eq(workerState.instanceId, instanceId), lt(workerState.heartbeatAt, new Date(now.getTime() - LEASE_STALE_MS)), ), ), ) .returning({ id: workerState.id }); return won.length > 0; } async function acquireLease() { let warned = false; while (!(await tryAcquireLease())) { if (!warned) { const other = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") }); log.warn(`another worker (pid ${other?.pid ?? "?"}) holds the lease; waiting until it stops or goes stale`); warned = true; } await sleep(5_000); } } async function heartbeat() { const values = { pid: process.pid, hfVersion, heartbeatAt: new Date(), ...(await diskSpace(coreEnv().MODELS_DIR)), }; const kept = await db() .update(workerState) .set(values) .where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId))) .returning({ id: workerState.id, scanRequestedAt: workerState.scanRequestedAt }); if (kept.length === 0) { log.error("lost the worker lease to another process; exiting"); await shutdown("lease lost", 1); return; } const requested = kept[0].scanRequestedAt; if (requested && requested.getTime() > lastScanStartedAt) void scanFolders(); await writeFile(HEALTH_FILE, String(Date.now())).catch(() => {}); } async function releaseLease() { await db() .update(workerState) .set({ heartbeatAt: new Date(0) }) .where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId))); } // --------------------------------------------------------------------------- // Jobs // --------------------------------------------------------------------------- /** Jobs that were running when the previous worker stopped can't still be running. */ async function recoverInterruptedJobs() { const stale = await db() .update(jobs) .set({ state: "interrupted", finishedAt: new Date(), speedBps: null, etaSeconds: null }) .where(inArray(jobs.state, [...ACTIVE_JOB_STATES])) .returning({ id: jobs.id, modelId: jobs.modelId }); if (stale.length === 0) return; await db() .insert(jobLogs) .values( stale.map((j) => ({ jobId: j.id, stream: "system" as const, line: "Worker restarted while this job was running. Marked as interrupted; resume to continue.", })), ); for (const j of stale) await settleModelStatus(j.modelId); log.warn(`marked ${stale.length} job(s) as interrupted`); } async function handleCancelRequests() { const requested = await db() .select({ id: jobs.id, state: jobs.state, modelId: jobs.modelId }) .from(jobs) .where(and(isNotNull(jobs.cancelRequestedAt), inArray(jobs.state, ["queued", ...ACTIVE_JOB_STATES]))); for (const j of requested) { const runner = runners.get(j.id); if (runner) { runner.cancel(); } else if (j.state === "queued") { await db() .update(jobs) .set({ state: "cancelled", finishedAt: new Date() }) .where(and(eq(jobs.id, j.id), eq(jobs.state, "queued"))); await settleModelStatus(j.modelId); } } } /** Downloads are limited by MAX_CONCURRENT_DOWNLOADS; verify and delete jobs by this. */ const MAX_LOCAL_JOBS = 2; const LOCAL_KINDS = ["verify", "deep_verify", "delete"] as const; const running = (local: boolean) => [...runners.values()].filter((r) => (r.kind === "download") !== local).length; /** Claim the oldest queued job of the given kinds whose model has no running job. */ async function claimNextJob(kinds: readonly JobKind[]) { const busyModels = [...runners.values()].map((r) => r.modelId); const candidates = await db() .select({ id: jobs.id, modelId: jobs.modelId, kind: jobs.kind }) .from(jobs) .where(and(eq(jobs.state, "queued"), inArray(jobs.kind, [...kinds]), isNull(jobs.cancelRequestedAt))) .orderBy(asc(jobs.createdAt)) .limit(20); const next = candidates.find((c) => !busyModels.includes(c.modelId)); if (!next) return null; const [job] = await db() .update(jobs) .set({ state: next.kind === "download" ? "downloading" : "verifying", startedAt: new Date(), finishedAt: null, attempt: sql`${jobs.attempt} + 1`, }) .where(and(eq(jobs.id, next.id), eq(jobs.state, "queued"))) .returning(); return job ?? null; } async function jobFileRows(jobId: string) { return db() .select({ modelFileId: jobFiles.modelFileId, path: jobFiles.path, expectedBytes: jobFiles.expectedBytes, doneBytes: jobFiles.doneBytes, lfsSha256: modelFiles.lfsSha256, blobOid: modelFiles.blobOid, state: modelFiles.state, }) .from(jobFiles) .innerJoin(modelFiles, eq(modelFiles.id, jobFiles.modelFileId)) .where(eq(jobFiles.jobId, jobId)); } async function startJob(job: typeof jobs.$inferSelect) { const model = await db().query.models.findFirst({ where: eq(models.id, job.modelId) }); if (!model) { await db() .update(jobs) .set({ state: "failed", errorCode: "unknown", errorMessage: "Model no longer exists.", finishedAt: new Date() }) .where(eq(jobs.id, job.id)); return; } let runner: Runner; if (job.kind === "download") { const files = await jobFileRows(job.id); await db().update(models).set({ status: "downloading" }).where(eq(models.id, model.id)); runner = new DownloadRunner(job, model, files); log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`); } else { const repoPaths = (await db().select({ path: modelFiles.path }).from(modelFiles).where(eq(modelFiles.modelId, model.id))).map( (f) => f.path, ); if (job.kind === "delete") { runner = new DeleteRunner(job, model, repoPaths); log.info(`job ${job.id}: deleting ${model.repoId}`); } else { runner = new VerifyRunner(job, model, await jobFileRows(job.id), new Set(repoPaths)); log.info(`job ${job.id}: ${job.kind === "deep_verify" ? "deep verify" : "verify"} ${model.repoId}`); } } runners.set(job.id, runner); runner .run() .then(async () => { if (job.kind !== "download") return; // A failed download may mean the repo or commit is gone from the Hub; find out right away. const done = await db().query.jobs.findFirst({ columns: { state: true }, where: eq(jobs.id, job.id) }); if (done?.state === "failed") reportHubCheck(model, await checkHub(model)); }) .catch((err) => log.error(`job ${job.id} crashed`, err)) .finally(() => runners.delete(job.id)); } // --------------------------------------------------------------------------- // Hub checks: repo/commit still there, newer commit on the tracked revision // --------------------------------------------------------------------------- function reportHubCheck(model: { repoId: string }, result: Awaited>) { if (result.state === null) log.warn(`Hub check for ${model.repoId} failed: ${result.error}`); else if (result.state !== "available") log.warn(`${model.repoId}: ${result.state.replace("_", " ")} on the Hub (local files kept)`); else if (result.update) log.info(`${model.repoId}: update available (${result.update.sha.slice(0, 7)})`); } let scanning = false; let lastScanStartedAt = 0; async function scanFolders() { if (scanning || stopping) return; scanning = true; lastScanStartedAt = Date.now(); try { const n = await scanModelsDir(coreEnv().MODELS_DIR); if (n > 0) log.info(`found ${n} folder(s) in the models dir that aren't in the library`); } catch (err) { log.error("models dir scan failed", err); } finally { scanning = false; } } let checkingHub = false; async function checkHubDue() { const hours = coreEnv().UPDATE_CHECK_INTERVAL_HOURS; if (checkingHub || stopping || hours <= 0) return; checkingHub = true; try { for (const model of await modelsDueForHubCheck(hours * 3_600_000)) { if (stopping) break; reportHubCheck(model, await checkHub(model)); await sleep(1_000); // be gentle with the Hub API } } catch (err) { log.error("Hub check failed", err); } finally { checkingHub = false; } } let ticking = false; async function tick() { if (ticking || stopping) return; ticking = true; try { await handleCancelRequests(); const max = coreEnv().MAX_CONCURRENT_DOWNLOADS; while (running(false) < max && !stopping) { const job = await claimNextJob(["download"]); if (!job) break; await startJob(job); } while (running(true) < MAX_LOCAL_JOBS && !stopping) { const job = await claimNextJob(LOCAL_KINDS); if (!job) break; await startJob(job); } } catch (err) { log.error("tick failed", err); } finally { ticking = false; } } // --------------------------------------------------------------------------- // Lifecycle // --------------------------------------------------------------------------- const timers: NodeJS.Timeout[] = []; async function shutdown(reason: string, code = 0) { if (stopping) return; stopping = true; log.info(`shutting down (${reason})`); timers.forEach(clearInterval); // Deployment containers keep running; the next worker re-attaches to them. stopFollowingLogs(); await flushDeploymentLogs().catch(() => {}); await stopBenchmarks().catch(() => {}); await flushBenchmarkLogs().catch(() => {}); if (runners.size > 0) { for (const r of runners.values()) r.interrupt(); const deadline = Date.now() + SHUTDOWN_GRACE_MS; while (runners.size > 0 && Date.now() < deadline) await sleep(200); } await releaseLease().catch(() => {}); process.exit(code); } async function main() { const env = coreEnv(); log.info(`starting (pid ${process.pid}), models dir: ${env.MODELS_DIR}, max concurrent: ${env.MAX_CONCURRENT_DOWNLOADS}`); await mkdir(env.MODELS_DIR, { recursive: true }); await runMigrations(); log.info("database migrated"); process.on("SIGINT", () => void shutdown("SIGINT")); process.on("SIGTERM", () => void shutdown("SIGTERM")); await acquireLease(); log.info("acquired worker lease"); await recoverInterruptedJobs(); hfVersion = await detectHfVersion(); if (hfVersion) log.info(`hf CLI: ${hfVersion}, xet ${env.HF_HUB_DISABLE_XET ? "disabled" : "enabled"}`); else log.warn("hf CLI not found on PATH; downloads will fail until it is installed"); // Models added before Hub metadata was stored (search/filters need it). backfillMetadata((repoId, err) => log.warn(`metadata for ${repoId} failed: ${err instanceof Error ? err.message : err}`)) .then((n) => n > 0 && log.info(`fetched Hub metadata for ${n} model(s)`)) .catch((err) => log.error("metadata backfill failed", err)); await heartbeat(); timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS)); timers.push(setInterval(() => void tick(), TICK_MS)); timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS)); timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS)); // Runtimes (Docker): presets, host facts, image states, pulls. await resetStalePulls(); await seedRuntimePresets().catch((err) => log.error("seeding runtime presets failed", err)); if (docker()) log.info(`Docker API: ${coreEnv().DOCKER_HOST}`); else log.info("DOCKER_HOST not set; runtimes are disabled"); const dockerInfo = () => refreshDockerInfo(instanceId).catch((err) => log.error("Docker info failed", err)); const imageSync = () => syncImageStates().catch((err) => log.error("image sync failed", err)); await dockerInfo(); void imageSync(); timers.push(setInterval(() => void dockerInfo(), DOCKER_INFO_MS)); timers.push(setInterval(() => void imageSync(), IMAGE_SYNC_MS)); timers.push(setInterval(() => void handlePullRequests().catch((err) => log.error("pull failed", err)), PULL_CHECK_MS)); // Deployments: re-attach to running containers, then keep them in line with the desired state. await adoptContainers(); timers.push(setInterval(() => void reconcileDeployments().catch((err) => log.error("deployments failed", err)), DEPLOYMENT_TICK_MS)); timers.push(setInterval(() => void flushDeploymentLogs().catch((err) => log.error("deployment logs failed", err)), LOG_FLUSH_INTERVAL_MS)); // Benchmarks: one BetterBench run at a time against a running deployment. await recoverBenchmarks(); void refreshSummaries(); void reportL80Status(); timers.push(setInterval(() => void tickPublications().catch((err) => log.error("publications failed", err)), BENCHMARK_TICK_MS)); timers.push(setInterval(() => void tickBenchmarks().catch((err) => log.error("benchmarks failed", err)), BENCHMARK_TICK_MS)); timers.push(setInterval(() => void flushBenchmarkLogs().catch((err) => log.error("benchmark logs failed", err)), LOG_FLUSH_INTERVAL_MS)); void scanFolders(); void tick(); setTimeout(() => void checkHubDue(), 15_000); } function sleep(ms: number) { return new Promise((r) => setTimeout(r, ms)); } main().catch((err) => { log.error("fatal", err); process.exit(1); });