import { type ChildProcess, spawn } from "node:child_process"; import { mkdir, statfs } from "node:fs/promises"; import { join } from "node:path"; import { and, eq, inArray } from "drizzle-orm"; import { db } from "@/lib/db/client"; import { type JobErrorCode, type JobState, type ModelFileState, jobFiles, jobs, modelFiles, models, settings, } from "@/lib/db/schema"; import { parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit"; import { coreEnv } from "@/lib/env"; import { formatBytes } from "@/lib/format"; import { escapeGlob } from "@/lib/selection"; import { bytesOnDisk, type ExpectedFile, listIncomplete, fileSize, modelDir, removeLocalFile, removeStaleIncomplete, } from "./hf-layout"; import { JobLog } from "./job-log"; import { log } from "./log"; import { settleModelStatus } from "./model-status"; import type { Runner } from "./runner"; import { SpeedMeter } from "./speed"; import { Throttle } from "./throttle"; const SAMPLE_MS = 1_000; const KILL_GRACE_MS = 10_000; const THROTTLE_MS = 250; const LIMIT_REFRESH_MS = 5_000; /** SIGSTOP/SIGCONT; not on Windows (dev only), where the limit is ignored. */ const CAN_PAUSE = process.platform !== "win32"; /** Running downloads; the speed limit is the total, split evenly between them. */ const running = new Set(); /** Environment variables passed through to hf (everything else, e.g. AUTH_SECRET, is withheld). */ const PASSTHROUGH_ENV = [ "PATH", "HOME", "USER", "LANG", "LC_ALL", "TZ", "TMPDIR", "SYSTEMROOT", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "TEMP", "TMP", "PATHEXT", "COMSPEC", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "HF_ENDPOINT", ]; type Job = typeof jobs.$inferSelect; type Model = typeof models.$inferSelect; type FileRow = { modelFileId: string; path: string; expectedBytes: number; doneBytes: number; lfsSha256: string | null; blobOid: string | null; /** Last known state of the file (deep verify may have found a hash mismatch). */ state: ModelFileState; }; type Outcome = | { state: "completed" } | { state: "cancelled" | "interrupted"; message: string } | { state: "failed"; code: JobErrorCode; message: string; exitCode?: number | null }; export class DownloadRunner implements Runner { private child?: ChildProcess; private stopReason?: "cancelled" | "interrupted"; private killTimer?: NodeJS.Timeout; private jobLog: JobLog; private paused = false; constructor( private job: Job, private model: Model, private files: FileRow[], ) { this.jobLog = new JobLog(job.id, [coreEnv().HF_TOKEN ?? ""]); } get jobId() { return this.job.id; } get modelId() { return this.model.id; } get kind() { return this.job.kind; } /** User cancel: stop hf, keep completed files. */ cancel() { this.stop("cancelled"); } /** Worker shutdown: stop hf, job can be resumed later. */ interrupt() { this.stop("interrupted"); } private stop(reason: "cancelled" | "interrupted") { if (this.stopReason) return; this.stopReason = reason; this.jobLog.system(reason === "cancelled" ? "Cancel requested, stopping hf…" : "Worker shutting down, stopping hf…"); if (!this.child || this.child.exitCode !== null) return; this.resume(); // a stopped process only handles SIGTERM once it runs again killTree(this.child, "SIGTERM"); this.killTimer = setTimeout(() => { if (this.child && this.child.exitCode === null) killTree(this.child, "SIGKILL"); }, KILL_GRACE_MS); } async run(): Promise { const outcome = await this.execute().catch( (err): Outcome => ({ state: "failed", code: "unknown", message: `Internal worker error: ${err instanceof Error ? err.message : String(err)}`, }), ); clearTimeout(this.killTimer); if (outcome.state !== "completed") await this.removePartials(); await this.finish(outcome); } /** hf can't resume partial files, so free their space as soon as hf has exited. */ private async removePartials() { if (this.child && this.child.exitCode === null && this.child.signalCode === null) return; // still running try { const dir = modelDir(coreEnv().MODELS_DIR, this.model.localPath); const removed = await removeStaleIncomplete(dir); if (removed.count > 0) { this.jobLog.system( `Removed ${removed.count} partial file(s) (${formatBytes(removed.bytes)}); hf restarts unfinished files from the beginning.`, ); } } catch (err) { log.error(`could not remove partial files for job ${this.job.id}`, err); } } private async execute(): Promise { const env = coreEnv(); const dir = modelDir(env.MODELS_DIR, this.model.localPath); const expected: ExpectedFile[] = this.files.map((f) => ({ path: f.path, size: f.expectedBytes, etags: [f.lfsSha256, f.blobOid].filter((x): x is string => !!x), })); await mkdir(dir, { recursive: true }); this.jobLog.system( `Attempt ${this.job.attempt}: ${this.model.repoId} @ ${this.job.targetSha}, ${this.files.length} file(s), ${formatBytes(this.job.totalBytes)}`, ); // hf never resumes a partial file; leftovers from earlier runs only waste space. const stale = await removeStaleIncomplete(dir); if (stale.count > 0) { this.jobLog.system(`Removed ${stale.count} partial file(s) from an earlier run (${formatBytes(stale.bytes)}).`); } // hf skips a file whose metadata matches without looking at its content or size, so broken // files (wrong size, or a hash mismatch found by deep verify) have to go first. const broken: string[] = []; for (const f of this.files) { const size = await fileSize(join(dir, f.path)); const wrong = size != null && (size !== f.expectedBytes || f.state === "hash_mismatch"); if (wrong && (await removeLocalFile(dir, f.path))) broken.push(f.path); } if (broken.length > 0) { this.jobLog.system(`Deleted ${broken.length} broken file(s) so hf downloads them again: ${broken.slice(0, 5).join(", ")}${broken.length > 5 ? ", …" : ""}`); } const initial = await this.sample(dir, expected); const remaining = expected.reduce((s, f, i) => s + (initial[i].complete ? 0 : f.size), 0); const doneCount = initial.filter((p) => p.complete).length; if (doneCount > 0) { this.jobLog.system( `${doneCount} file(s) already on disk with the right size. hf skips the ones it downloaded itself and checks the others by hash (slow for large files), downloading them again if they differ.`, ); } const free = await freeBytes(dir); if (free != null && remaining > free) { return { state: "failed", code: "disk_full", message: `Not enough disk space: ${formatBytes(remaining)} still needed, ${formatBytes(free)} free on the models volume.`, }; } if (this.stopReason) return { state: this.stopReason, message: "Stopped before hf started." }; const exit = await this.spawnHf(dir, expected); if (this.stopReason) { return { state: this.stopReason, message: this.stopReason === "cancelled" ? "Cancelled by user." : "Interrupted by worker shutdown.", }; } if (exit.error) { return { state: "failed", code: "unknown", message: exit.error, exitCode: exit.code }; } if (exit.code !== 0) { const tail = this.jobLog.stderrTail.slice(-8).join("\n"); return { state: "failed", code: "unknown", exitCode: exit.code, message: `hf exited with code ${exit.code}${exit.signal ? ` (${exit.signal})` : ""}.${tail ? `\n${tail}` : ""}`, }; } // hf exits 0 even if e.g. a pattern matched nothing, so check every expected file. await this.setState("verifying"); const final = await this.sample(dir, expected); await this.markFiles(final.map((p, i) => ({ id: this.files[i].modelFileId, complete: p.complete }))); const bad = expected.filter((_, i) => !final[i].complete); if (bad.length > 0) { return { state: "failed", code: "size_mismatch", exitCode: 0, message: `hf finished, but ${bad.length} file(s) are missing or have the wrong size: ${bad .slice(0, 5) .map((f) => f.path) .join(", ")}${bad.length > 5 ? ", …" : ""}`, }; } // Update: files the new revision no longer has (or that are no longer selected). const remove = (this.job.result?.removePaths ?? []).filter((p) => !this.files.some((f) => f.path === p)); let removed = 0; for (const path of remove) if (await removeLocalFile(dir, path)) removed++; if (removed > 0) this.jobLog.system(`Deleted ${removed} file(s) that are no longer part of the selection: ${remove.slice(0, 5).join(", ")}`); return { state: "completed" }; } private spawnHf( dir: string, expected: ExpectedFile[], ): Promise<{ code: number | null; signal: NodeJS.Signals | null; error?: string }> { const env = coreEnv(); const args = [ "download", this.model.repoId, "--revision", this.job.targetSha, "--local-dir", dir, ...expected.flatMap((f) => ["--include", escapeGlob(f.path)]), ]; const childEnv: Record = {}; for (const k of PASSTHROUGH_ENV) { const v = process.env[k]; if (v !== undefined) childEnv[k] = v; } Object.assign(childEnv, { HF_HUB_DISABLE_XET: env.HF_HUB_DISABLE_XET ? "1" : "0", HF_HUB_DISABLE_PROGRESS_BARS: "1", HF_HUB_DISABLE_TELEMETRY: "1", NO_COLOR: "1", PYTHONUNBUFFERED: "1", }); if (env.HF_HOME) childEnv.HF_HOME = env.HF_HOME; if (env.HF_TOKEN) childEnv.HF_TOKEN = env.HF_TOKEN; // via env, never argv this.jobLog.system( `$ hf download ${this.model.repoId} --revision ${this.job.targetSha} --local-dir ${dir} ` + `(${expected.length} --include pattern(s); xet ${env.HF_HUB_DISABLE_XET ? "off" : "on"}; token ${env.HF_TOKEN ? "set" : "not set"})`, ); return new Promise((resolve) => { let settled = false; const done = (r: { code: number | null; signal: NodeJS.Signals | null; error?: string }) => { if (settled) return; settled = true; clearInterval(timer); clearInterval(throttleTimer); running.delete(this); this.jobLog.end(); resolve(r); }; const child = spawn("hf", args, { env: childEnv as NodeJS.ProcessEnv, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }); this.child = child; child.stdout.on("data", (d) => this.jobLog.chunk("stdout", d)); child.stderr.on("data", (d) => this.jobLog.chunk("stderr", d)); child.on("error", (err: NodeJS.ErrnoException) => done({ code: null, signal: null, error: err.code === "ENOENT" ? "The hf CLI was not found on PATH. Install huggingface_hub[hf_xet] in the worker environment." : `Could not start hf: ${err.message}`, }), ); child.on("close", (code, signal) => done({ code, signal })); running.add(this); const throttleTimer = this.throttle(dir, expected); // Progress from bytes on disk, written to the DB once per second. const speed = new SpeedMeter(); let busy = false; const timer = setInterval(async () => { if (busy) return; busy = true; try { const progress = await this.sample(dir, expected); const doneBytes = progress.reduce((s, p) => s + p.done, 0); speed.add(Date.now(), doneBytes); await this.writeProgress(progress, doneBytes, speed); await this.jobLog.flush(); } catch (err) { log.error(`progress sample failed for job ${this.job.id}`, err); } finally { busy = false; } }, SAMPLE_MS); }); } /** * Enforce Settings → Downloads → Speed limit by pausing hf while it is ahead of the budget * (see Throttle). The limit is re-read every few seconds, so changes apply to running downloads. */ private throttle(dir: string, expected: ExpectedFile[]): NodeJS.Timeout { let total: number | null = null; let readAt = 0; let bucket: Throttle | null = null; let busy = false; let warned = false; return setInterval(async () => { if (busy || this.stopReason) return; busy = true; try { const now = Date.now(); if (now - readAt >= LIMIT_REFRESH_MS) { readAt = now; const row = await db().query.settings.findFirst({ where: eq(settings.key, SPEED_LIMIT_KEY) }); const next = parseSpeedLimit(row?.value); if (next !== total) { this.jobLog.system(next ? `Speed limit: ${formatBytes(next)}/s${running.size > 1 ? ` shared by ${running.size} downloads` : ""}.` : "No speed limit."); if (next && !CAN_PAUSE && !warned) { warned = true; this.jobLog.system("The speed limit only works on Linux (the worker pauses hf); ignored here."); } total = next; } } if (!total || !CAN_PAUSE) { bucket = null; this.resume(); return; } const limit = total / Math.max(1, running.size); if (!bucket) bucket = new Throttle(limit); bucket.limit = limit; const bytes = (await this.sample(dir, expected)).reduce((s, p) => s + p.done, 0); if (bucket.update(Date.now(), bytes)) this.pause(); else this.resume(); } catch (err) { log.error(`speed limit check failed for job ${this.job.id}`, err); this.resume(); } finally { busy = false; } }, THROTTLE_MS); } private pause() { if (this.paused || !this.child || this.child.exitCode !== null) return; if (this.child.kill("SIGSTOP")) this.paused = true; } private resume() { if (!this.paused || !this.child) return; this.paused = false; if (this.child.exitCode === null) this.child.kill("SIGCONT"); } private async sample(dir: string, expected: ExpectedFile[]) { const incomplete = await listIncomplete(dir); return Promise.all(expected.map((f) => bytesOnDisk(dir, f, incomplete))); } private async writeProgress( progress: { done: number; complete: boolean }[], doneBytes: number, speed: SpeedMeter, ) { const d = db(); const fileUpdates = []; for (let i = 0; i < this.files.length; i++) { const f = this.files[i]; if (f.doneBytes === progress[i].done) continue; f.doneBytes = progress[i].done; fileUpdates.push( d .update(jobFiles) .set({ doneBytes: f.doneBytes, state: progress[i].complete ? "done" : "downloading" }) .where(and(eq(jobFiles.jobId, this.job.id), eq(jobFiles.modelFileId, f.modelFileId))), ); } const bps = speed.bytesPerSecond(); await d.batch([ d .update(jobs) .set({ doneBytes, speedBps: bps == null ? null : Math.round(bps), etaSeconds: speed.eta(this.job.totalBytes - doneBytes), }) .where(eq(jobs.id, this.job.id)), ...fileUpdates, ]); } private async markFiles(results: { id: string; complete: boolean }[]) { const d = db(); const now = new Date(); const statements = []; for (const [ids, fileState, jobFileState] of [ [results.filter((r) => r.complete).map((r) => r.id), "present", "done"], [results.filter((r) => !r.complete).map((r) => r.id), "missing", "failed"], ] as const) { if (ids.length === 0) continue; statements.push( d.update(modelFiles).set({ state: fileState, checkedAt: now }).where(inArray(modelFiles.id, ids)), d .update(jobFiles) .set({ state: jobFileState }) .where(and(eq(jobFiles.jobId, this.job.id), inArray(jobFiles.modelFileId, ids))), ); } if (statements.length > 0) await d.batch(statements as [(typeof statements)[number], ...typeof statements]); } private async setState(state: JobState) { await db().update(jobs).set({ state }).where(eq(jobs.id, this.job.id)); } private async finish(outcome: Outcome) { const now = new Date(); const d = db(); switch (outcome.state) { case "completed": this.jobLog.system("Download complete, all files verified (size)."); await d.batch([ d .update(jobs) .set({ state: "completed", finishedAt: now, speedBps: null, etaSeconds: 0, doneBytes: this.job.totalBytes }) .where(eq(jobs.id, this.job.id)), d.update(models).set({ downloadedAt: now }).where(eq(models.id, this.model.id)), ]); break; case "failed": this.jobLog.system(`Failed: ${outcome.message}`); await d .update(jobs) .set({ state: "failed", finishedAt: now, speedBps: null, etaSeconds: null, errorCode: outcome.code, errorMessage: outcome.message, exitCode: outcome.exitCode ?? null, }) .where(eq(jobs.id, this.job.id)); break; default: this.jobLog.system(outcome.message); await d .update(jobs) .set({ state: outcome.state, finishedAt: now, speedBps: null, etaSeconds: null }) .where(eq(jobs.id, this.job.id)); } await this.jobLog.close(); await settleModelStatus(this.model.id, outcome.state === "failed" ? "failed" : undefined); log.info(`job ${this.job.id} (${this.model.repoId}) ${outcome.state}`); } } async function freeBytes(dir: string): Promise { try { const s = await statfs(dir); return s.bavail * s.bsize; } catch { return null; } } function killTree(child: ChildProcess, signal: NodeJS.Signals) { if (process.platform === "win32" && child.pid) { // hf.exe is a launcher for python; kill the whole tree. spawn("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }); return; } child.kill(signal); }