Milestone (c): worker and downloads with live progress

- Worker queue with per-model exclusivity and MAX_CONCURRENT_DOWNLOADS,
  spawns `hf download --revision <sha> --local-dir ... --include <exact paths>`
  with HF_TOKEN via env only
- Progress from bytes on disk (final + .incomplete files matched by etag),
  per job and per file, with speed and ETA; post-download size/etag check
- Job logs (sanitized), cancel, graceful interrupt on shutdown,
  partial-file cleanup (hf 2.1.1 does not resume partials)
- Single-worker DB lease, free-space check
- SSE live updates for library, model and job pages
- Dockerfile + compose.yaml (web, worker, data/models volumes)
- HF_HUB_DISABLE_XET default on for measurable progress

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 16:57:12 +02:00
1 parent 8f7ac60ccf
commit 49440154a2
42 files changed
+2974 -110

No files matched your search

+402
View File
@@ -0,0 +1,402 @@
import { type ChildProcess, spawn } from "node:child_process";
import { mkdir, statfs } from "node:fs/promises";
import { and, eq, inArray } from "drizzle-orm";
import { db } from "@/lib/db/client";
import {
type JobErrorCode,
type JobState,
jobFiles,
jobs,
modelFiles,
models,
} from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format";
import { escapeGlob } from "@/lib/selection";
import {
bytesOnDisk,
type ExpectedFile,
listIncomplete,
modelDir,
removeStaleIncomplete,
} from "./hf-layout";
import { JobLog } from "./job-log";
import { log } from "./log";
import { settleModelStatus } from "./model-status";
import { SpeedMeter } from "./speed";
const SAMPLE_MS = 1_000;
const KILL_GRACE_MS = 10_000;
/** 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;
};
type Outcome =
| { state: "completed" }
| { state: "cancelled" | "interrupted"; message: string }
| { state: "failed"; code: JobErrorCode; message: string; exitCode?: number | null };
export class DownloadRunner {
private child?: ChildProcess;
private stopReason?: "cancelled" | "interrupted";
private killTimer?: NodeJS.Timeout;
private jobLog: JobLog;
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;
}
/** 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;
killTree(this.child, "SIGTERM");
this.killTimer = setTimeout(() => {
if (this.child && this.child.exitCode === null) killTree(this.child, "SIGKILL");
}, KILL_GRACE_MS);
}
async run(): Promise<void> {
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<Outcome> {
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)}).`);
}
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 complete, hf will skip them.`);
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 ? ", …" : ""}`,
};
}
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<string, string> = {};
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);
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 }));
// 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);
});
}
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<number | null> {
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);
}
+111
View File
@@ -0,0 +1,111 @@
// What `hf download --local-dir <dir>` writes to disk (verified against huggingface_hub 2.1.1):
//
// <dir>/<path> final file (moved in place when complete)
// <dir>/.cache/huggingface/download/<path>.metadata "<commit sha>\n<etag>\n<timestamp>\n"
// <dir>/.cache/huggingface/download/<path>.lock lock file, left behind
// <dir>/.cache/huggingface/download/**/<b64>.<etag>.<random>.incomplete partial download
// <dir>/.cache/huggingface/trees/<sha>.json cached file tree
//
// The etag is the LFS sha256 for LFS/Xet files and the git blob SHA-1 for small files.
// Partial files are NOT resumed: every run writes a new <random> name, and a killed run leaves
// its .incomplete file behind. We delete those before each run.
import { readdir, readFile, rm, stat } from "node:fs/promises";
import { join, resolve, sep } from "node:path";
export const HF_CACHE_DIR = join(".cache", "huggingface");
const DOWNLOAD_DIR = join(HF_CACHE_DIR, "download");
/** Absolute local dir for a model; refuses paths that would escape MODELS_DIR. */
export function modelDir(modelsDir: string, localPath: string): string {
const root = resolve(modelsDir);
const dir = resolve(root, localPath);
if (dir === root || !dir.startsWith(root + sep)) {
throw new Error(`Refusing model path outside MODELS_DIR: ${localPath}`);
}
return dir;
}
export type FileMetadata = { commit: string; etag: string };
export async function readMetadata(dir: string, path: string): Promise<FileMetadata | null> {
try {
const text = await readFile(join(dir, DOWNLOAD_DIR, `${path}.metadata`), "utf8");
const [commit, etag] = text.split("\n");
return commit && etag ? { commit: commit.trim(), etag: etag.trim() } : null;
} catch {
return null;
}
}
/** Size of a file, or null if it doesn't exist. */
export async function fileSize(path: string): Promise<number | null> {
try {
const s = await stat(path);
return s.isFile() ? s.size : null;
} catch {
return null;
}
}
/** Extract the etag (40 or 64 hex chars) from an .incomplete file name. */
export function etagFromIncompleteName(name: string): string | null {
if (!name.endsWith(".incomplete")) return null;
for (const part of name.split(".")) {
if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(part)) return part;
}
return null;
}
export type IncompleteFile = { path: string; etag: string | null; size: number };
/** All partial files under the local dir's download cache. */
export async function listIncomplete(dir: string): Promise<IncompleteFile[]> {
const root = join(dir, DOWNLOAD_DIR);
let entries;
try {
entries = await readdir(root, { recursive: true, withFileTypes: true });
} catch {
return [];
}
const out: IncompleteFile[] = [];
for (const e of entries) {
if (!e.isFile() || !e.name.endsWith(".incomplete")) continue;
const full = join(e.parentPath, e.name);
const size = await fileSize(full);
if (size == null) continue; // finished and moved between readdir and stat
out.push({ path: full, etag: etagFromIncompleteName(e.name), size });
}
return out;
}
/** Delete leftover partial files from earlier runs. Only call while no hf process uses the dir. */
export async function removeStaleIncomplete(dir: string): Promise<{ count: number; bytes: number }> {
const files = await listIncomplete(dir);
for (const f of files) await rm(f.path, { force: true });
return { count: files.length, bytes: files.reduce((s, f) => s + f.size, 0) };
}
export type ExpectedFile = { path: string; size: number; etags: string[] };
/**
* Bytes present for one expected file:
* - final file with the expected size and matching (or missing) metadata etag → complete
* - otherwise the size of its in-progress .incomplete file (matched by etag), else 0
*/
export async function bytesOnDisk(
dir: string,
file: ExpectedFile,
incomplete: IncompleteFile[],
): Promise<{ done: number; complete: boolean }> {
const size = await fileSize(join(dir, file.path));
if (size === file.size) {
const meta = await readMetadata(dir, file.path);
if (!meta || file.etags.includes(meta.etag)) return { done: file.size, complete: true };
}
let partial = 0;
for (const inc of incomplete) {
if (inc.etag && file.etags.includes(inc.etag)) partial = Math.max(partial, inc.size);
}
return { done: Math.min(partial, file.size), complete: false };
}
+233 -46
View File
@@ -1,44 +1,45 @@
import { execFile } from "node:child_process";
import { mkdir, statfs } from "node:fs/promises";
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 { inArray } from "drizzle-orm";
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, jobLogs, jobs, workerState } from "@/lib/db/schema";
import { ACTIVE_JOB_STATES, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { DownloadRunner } from "./download";
import { log } from "./log";
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;
/** 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<string, DownloadRunner>();
let hfVersion: string | null = null;
let stopping = false;
async function detectHfVersion(): Promise<string | null> {
try {
const { stdout } = await promisify(execFile)("hf", ["version"], { timeout: 30_000 });
return stdout.trim() || null;
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;
}
}
/** Jobs that were running when the worker last stopped can't still be running: mark them interrupted. */
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 });
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.",
})),
);
log.warn(`marked ${stale.length} job(s) as interrupted`);
}
async function diskSpace(dir: string) {
try {
const s = await statfs(dir);
@@ -48,48 +49,234 @@ async function diskSpace(dir: string) {
}
}
async function heartbeat(startedAt: Date, hfVersion: string | null) {
// ---------------------------------------------------------------------------
// Lease: only one worker may run, otherwise two processes would run the same jobs.
// ---------------------------------------------------------------------------
async function tryAcquireLease(): Promise<boolean> {
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,
startedAt,
heartbeatAt: now,
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 });
if (kept.length === 0) {
log.error("lost the worker lease to another process; exiting");
await shutdown("lease lost", 1);
return;
}
await writeFile(HEALTH_FILE, String(Date.now())).catch(() => {});
}
async function releaseLease() {
await db()
.insert(workerState)
.values({ id: "worker", ...values })
.onConflictDoUpdate({ target: workerState.id, set: values });
.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);
}
}
}
/** Claim the oldest queued download whose model has no running job. */
async function claimNextJob() {
const busyModels = [...runners.values()].map((r) => r.modelId);
const candidates = await db()
.select({ id: jobs.id, modelId: jobs.modelId })
.from(jobs)
.where(and(eq(jobs.state, "queued"), eq(jobs.kind, "download"), 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: "downloading", 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 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;
}
const files = await db()
.select({
modelFileId: jobFiles.modelFileId,
path: jobFiles.path,
expectedBytes: jobFiles.expectedBytes,
doneBytes: jobFiles.doneBytes,
lfsSha256: modelFiles.lfsSha256,
blobOid: modelFiles.blobOid,
})
.from(jobFiles)
.innerJoin(modelFiles, eq(modelFiles.id, jobFiles.modelFileId))
.where(eq(jobFiles.jobId, job.id));
await db().update(models).set({ status: "downloading" }).where(eq(models.id, model.id));
const runner = new DownloadRunner(job, model, files);
runners.set(job.id, runner);
log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`);
runner
.run()
.catch((err) => log.error(`job ${job.id} crashed`, err))
.finally(() => runners.delete(job.id));
}
let ticking = false;
async function tick() {
if (ticking || stopping) return;
ticking = true;
try {
await handleCancelRequests();
const max = coreEnv().MAX_CONCURRENT_DOWNLOADS;
while (runners.size < max && !stopping) {
const job = await claimNextJob();
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);
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}`);
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();
const hfVersion = await detectHfVersion();
if (hfVersion) log.info(`hf CLI: ${hfVersion}`);
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");
const startedAt = new Date();
await heartbeat(startedAt, hfVersion);
const timer = setInterval(() => {
heartbeat(startedAt, hfVersion).catch((err) => log.error("heartbeat failed", err));
}, HEARTBEAT_MS);
await heartbeat();
timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS));
timers.push(setInterval(() => void tick(), TICK_MS));
void tick();
}
const shutdown = (signal: string) => {
log.info(`received ${signal}, shutting down`);
clearInterval(timer);
process.exit(0);
};
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
function sleep(ms: number) {
return new Promise((r) => setTimeout(r, ms));
}
main().catch((err) => {
+86
View File
@@ -0,0 +1,86 @@
import { db } from "@/lib/db/client";
import { jobLogs, type LogStream } from "@/lib/db/schema";
const MAX_LINE = 4_000;
const MAX_LINES_PER_JOB = 20_000;
const ANSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
const HF_TOKEN_RE = /hf_[A-Za-z0-9]{20,}/g;
/** Remove ANSI color codes and anything that looks like an HF token. */
export function sanitizeLine(line: string, secrets: string[] = []): string {
let out = line.replace(ANSI, "").replace(HF_TOKEN_RE, "hf_***");
for (const s of secrets) if (s) out = out.split(s).join("***");
return out.length > MAX_LINE ? out.slice(0, MAX_LINE) + " …[truncated]" : out;
}
/**
* Buffers a job's stdout/stderr and writes it to job_logs in batches.
* Splits on \n and \r (progress bars), drops empty lines, keeps the last stderr lines for errors.
*/
export class JobLog {
private buffer: { stream: LogStream; line: string; ts: Date }[] = [];
private partial: Record<"stdout" | "stderr", string> = { stdout: "", stderr: "" };
private written = 0;
private dropped = 0;
readonly stderrTail: string[] = [];
constructor(
private jobId: string,
private secrets: string[] = [],
) {}
system(line: string) {
this.push("system", line);
}
chunk(stream: "stdout" | "stderr", data: Buffer | string) {
const text = this.partial[stream] + data.toString();
const lines = text.split(/\r\n|\r|\n/);
this.partial[stream] = lines.pop() ?? "";
for (const l of lines) this.push(stream, l);
}
/** Flush incomplete trailing lines (call when the process exits). */
end() {
for (const stream of ["stdout", "stderr"] as const) {
if (this.partial[stream]) this.push(stream, this.partial[stream]);
this.partial[stream] = "";
}
}
private push(stream: LogStream, raw: string) {
const line = sanitizeLine(raw, this.secrets);
if (!line.trim()) return;
if (stream === "stderr") {
this.stderrTail.push(line);
if (this.stderrTail.length > 30) this.stderrTail.shift();
}
if (this.written + this.buffer.length >= MAX_LINES_PER_JOB) {
this.dropped++;
return;
}
this.buffer.push({ stream, line, ts: new Date() });
}
async flush() {
if (this.buffer.length === 0) return;
const rows = this.buffer.splice(0, this.buffer.length);
await db()
.insert(jobLogs)
.values(rows.map((r) => ({ jobId: this.jobId, stream: r.stream, line: r.line, ts: r.ts })));
this.written += rows.length;
}
async close() {
this.end();
if (this.dropped > 0) {
this.buffer.push({
stream: "system",
line: `${this.dropped} further log lines were dropped (limit ${MAX_LINES_PER_JOB}).`,
ts: new Date(),
});
}
await this.flush();
}
}
+36
View File
@@ -0,0 +1,36 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { ACTIVE_JOB_STATES, jobs, type ModelStatus, modelFiles, models } from "@/lib/db/schema";
/**
* Recompute a model's status from its jobs and files:
* - an active job → downloading
* - all selected files present → ready
* - `failure` given (last job failed) → failed
* - some files present → incomplete, none → pending
*/
export async function settleModelStatus(modelId: string, failure?: "failed"): Promise<ModelStatus> {
const d = db();
const active = await d
.select({ n: sql<number>`count(*)` })
.from(jobs)
.where(and(eq(jobs.modelId, modelId), inArray(jobs.state, ["queued", ...ACTIVE_JOB_STATES])));
let status: ModelStatus;
if (active[0].n > 0) {
status = "downloading";
} else {
const [counts] = await d
.select({
total: sql<number>`count(*)`,
present: sql<number>`sum(case when ${modelFiles.state} in ('present', 'verified') then 1 else 0 end)`,
})
.from(modelFiles)
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true)));
const present = counts.present ?? 0;
if (counts.total > 0 && present === counts.total) status = "ready";
else if (failure) status = "failed";
else status = present > 0 ? "incomplete" : "pending";
}
await d.update(models).set({ status }).where(eq(models.id, modelId));
return status;
}
+32
View File
@@ -0,0 +1,32 @@
/**
* Download speed over a sliding time window, from periodic (time, totalBytes) samples.
* Using deltas means bytes that were already on disk before the job started never count as speed.
*/
export class SpeedMeter {
private samples: { t: number; bytes: number }[] = [];
constructor(private windowMs = 10_000) {}
add(t: number, bytes: number) {
this.samples.push({ t, bytes });
while (this.samples.length > 2 && t - this.samples[1].t >= this.windowMs) this.samples.shift();
}
/** Bytes per second, or null until there are two samples at least 1s apart. */
bytesPerSecond(): number | null {
if (this.samples.length < 2) return null;
const a = this.samples[0];
const b = this.samples[this.samples.length - 1];
const dt = (b.t - a.t) / 1000;
if (dt < 1) return null;
return Math.max(0, (b.bytes - a.bytes) / dt);
}
/** Seconds remaining, or null if unknown or stalled. */
eta(remainingBytes: number): number | null {
const bps = this.bytesPerSecond();
if (remainingBytes <= 0) return 0;
if (!bps || bps < 1) return null;
return Math.round(remainingBytes / bps);
}
}
+94
View File
@@ -0,0 +1,94 @@
import assert from "node:assert/strict";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, describe, it } from "node:test";
import {
bytesOnDisk,
etagFromIncompleteName,
listIncomplete,
modelDir,
removeStaleIncomplete,
} from "./hf-layout";
import { sanitizeLine } from "./job-log";
import { SpeedMeter } from "./speed";
const SHA256 = "e150ed544dfe6016930c026a93913a5e3184181ebfe6ab2223ae01dd0491784c";
const SHA1 = "de077778adaa4aa6e706209cd95a2a0d6049bc59";
describe("hf-layout", () => {
const dirs: string[] = [];
after(async () => {
for (const d of dirs) await rm(d, { recursive: true, force: true });
});
async function fixture() {
const dir = await mkdtemp(join(tmpdir(), "kaname-test-"));
dirs.push(dir);
const dl = join(dir, ".cache", "huggingface", "download");
await mkdir(join(dl, "Q4_K_M"), { recursive: true });
return { dir, dl };
}
it("parses the etag from real .incomplete names", () => {
assert.equal(etagFromIncompleteName(`3nJsnUdcCmdBOp4dLn_dEgZ50vw=.${SHA256}.cd150ce3.incomplete`), SHA256);
assert.equal(etagFromIncompleteName(`abc=.${SHA1}.0fa2cc3c.incomplete`), SHA1);
assert.equal(etagFromIncompleteName("model.gguf.metadata"), null);
});
it("modelDir refuses paths outside MODELS_DIR", () => {
assert.ok(modelDir("/models", "org/name").endsWith(join("org", "name")));
assert.throws(() => modelDir("/models", "../etc"));
assert.throws(() => modelDir("/models", "."));
});
it("counts partial bytes by etag, complete files by size + metadata", async () => {
const { dir, dl } = await fixture();
await writeFile(join(dl, `x=.${SHA256}.aaaa1111.incomplete`), Buffer.alloc(300));
await writeFile(join(dl, "Q4_K_M", `y=.${SHA1}.bbbb2222.incomplete`), Buffer.alloc(10));
const incomplete = await listIncomplete(dir);
assert.equal(incomplete.length, 2);
const big = { path: "big.gguf", size: 1000, etags: [SHA256] };
assert.deepEqual(await bytesOnDisk(dir, big, incomplete), { done: 300, complete: false });
// Final file present with matching metadata → complete
await writeFile(join(dir, "big.gguf"), Buffer.alloc(1000));
await writeFile(join(dl, "big.gguf.metadata"), `abc\n${SHA256}\n123.4\n`);
assert.deepEqual(await bytesOnDisk(dir, big, []), { done: 1000, complete: true });
// Same size but metadata from a different file version → not complete
await writeFile(join(dl, "big.gguf.metadata"), `abc\n${"0".repeat(64)}\n123.4\n`);
assert.equal((await bytesOnDisk(dir, big, [])).complete, false);
});
it("removes stale partial files", async () => {
const { dir, dl } = await fixture();
await writeFile(join(dl, `x=.${SHA256}.aaaa1111.incomplete`), Buffer.alloc(50));
await writeFile(join(dl, "keep.metadata"), "x");
assert.deepEqual(await removeStaleIncomplete(dir), { count: 1, bytes: 50 });
assert.equal((await listIncomplete(dir)).length, 0);
});
});
describe("SpeedMeter", () => {
it("measures deltas over the window and estimates ETA", () => {
const m = new SpeedMeter(10_000);
m.add(0, 5_000_000); // bytes already on disk at start don't count
assert.equal(m.bytesPerSecond(), null);
m.add(2_000, 7_000_000);
assert.equal(m.bytesPerSecond(), 1_000_000);
assert.equal(m.eta(10_000_000), 10);
m.add(30_000, 7_000_000); // stalled
assert.equal(m.bytesPerSecond(), 0);
assert.equal(m.eta(10_000_000), null);
});
});
describe("sanitizeLine", () => {
it("strips ANSI codes and hides tokens", () => {
assert.equal(sanitizeLine("\x1b[1m\x1b[31mError: boom\x1b[0m"), "Error: boom");
assert.equal(sanitizeLine("token hf_abcdefghijklmnopqrstuvwxyz123 used"), "token hf_*** used");
assert.equal(sanitizeLine("secret=s3cr3t-value", ["s3cr3t-value"]), "secret=***");
});
});