Delete, verify/deep verify, repair and update checks
- Delete any model (incl. failed ones); the worker removes the repo's files (keeps foreign files and empty-folder cleanup), then the rows. - Verify (existence, size, hf metadata) and deep verify (SHA-256 / git blob SHA-1 against the Hub) with missing/mismatch/extra report. - Repair = download of the selection; broken files are deleted first because hf skips files whose metadata matches without checking them. - Hub check resolves the tracked revision and stores which selected files a newer commit changes/adds/removes; Update pins it (old commit kept in model_revisions), downloads, then removes dropped files. - Worker runs verify/delete jobs next to downloads (2 local slots). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c2c239bf16
commit
7864a492c9
37 files changed
+2365
-191
No files matched your search
+70
-29
@@ -7,13 +7,16 @@ 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, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
|
||||
import { ACTIVE_JOB_STATES, type JobKind, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { checkHubAvailability, modelsDueForHubCheck } from "@/lib/hub/availability";
|
||||
import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability";
|
||||
import { backfillMetadata } from "@/lib/hub/refresh";
|
||||
import { DeleteRunner } from "./delete";
|
||||
import { DownloadRunner } from "./download";
|
||||
import { log } from "./log";
|
||||
import type { Runner } from "./runner";
|
||||
import { scanModelsDir } from "./scan";
|
||||
import { VerifyRunner } from "./verify";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
|
||||
const HEARTBEAT_MS = 5_000;
|
||||
@@ -30,7 +33,7 @@ const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
|
||||
|
||||
const instanceId = randomUUID();
|
||||
const startedAt = new Date();
|
||||
const runners = new Map<string, DownloadRunner>();
|
||||
const runners = new Map<string, Runner>();
|
||||
let hfVersion: string | null = null;
|
||||
let stopping = false;
|
||||
|
||||
@@ -168,13 +171,19 @@ async function handleCancelRequests() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Claim the oldest queued download whose model has no running job. */
|
||||
async function claimNextJob() {
|
||||
/** 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 })
|
||||
.select({ id: jobs.id, modelId: jobs.modelId, kind: jobs.kind })
|
||||
.from(jobs)
|
||||
.where(and(eq(jobs.state, "queued"), eq(jobs.kind, "download"), isNull(jobs.cancelRequestedAt)))
|
||||
.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));
|
||||
@@ -182,12 +191,33 @@ async function claimNextJob() {
|
||||
|
||||
const [job] = await db()
|
||||
.update(jobs)
|
||||
.set({ state: "downloading", startedAt: new Date(), finishedAt: null, attempt: sql`${jobs.attempt} + 1` })
|
||||
.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) {
|
||||
@@ -197,41 +227,47 @@ async function startJob(job: typeof jobs.$inferSelect) {
|
||||
.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);
|
||||
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);
|
||||
log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`);
|
||||
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") await reportHubCheck(model, await checkHubAvailability(model));
|
||||
if (done?.state === "failed") reportHubCheck(model, await checkHub(model));
|
||||
})
|
||||
.catch((err) => log.error(`job ${job.id} crashed`, err))
|
||||
.finally(() => runners.delete(job.id));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hub availability: flags models whose repo or pinned commit disappeared from the Hub
|
||||
// Hub checks: repo/commit still there, newer commit on the tracked revision
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function reportHubCheck(model: { repoId: string }, result: Awaited<ReturnType<typeof checkHubAvailability>>) {
|
||||
function reportHubCheck(model: { repoId: string }, result: Awaited<ReturnType<typeof checkHub>>) {
|
||||
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;
|
||||
@@ -258,7 +294,7 @@ async function checkHubDue() {
|
||||
try {
|
||||
for (const model of await modelsDueForHubCheck(hours * 3_600_000)) {
|
||||
if (stopping) break;
|
||||
reportHubCheck(model, await checkHubAvailability(model));
|
||||
reportHubCheck(model, await checkHub(model));
|
||||
await sleep(1_000); // be gentle with the Hub API
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -275,8 +311,13 @@ async function tick() {
|
||||
try {
|
||||
await handleCancelRequests();
|
||||
const max = coreEnv().MAX_CONCURRENT_DOWNLOADS;
|
||||
while (runners.size < max && !stopping) {
|
||||
const job = await claimNextJob();
|
||||
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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user