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
@@ -0,0 +1,107 @@
|
||||
// Delete a model: its files on disk, then its database rows.
|
||||
// Only files that belong to the repo (any revision we know of) and hf's .cache folder are removed;
|
||||
// anything else in the folder is kept and logged, and the folder stays if it isn't empty.
|
||||
|
||||
import { readdir, rm, rmdir } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobs, modelFiles, models } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { purgeModelRows } from "@/lib/model-purge";
|
||||
import { HF_CACHE_DIR, listLocalFiles, modelDir, removeLocalFile } from "./hf-layout";
|
||||
import { JobLog } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
import type { Runner } from "./runner";
|
||||
|
||||
type Job = typeof jobs.$inferSelect;
|
||||
type Model = typeof models.$inferSelect;
|
||||
|
||||
/** Remove empty directories below `dir` (deepest first), then `dir` itself if empty. */
|
||||
async function removeEmptyDirs(dir: string): Promise<void> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const e of entries) if (e.isDirectory()) await removeEmptyDirs(join(dir, e.name));
|
||||
await rmdir(dir).catch(() => {}); // fails if not empty, which is fine
|
||||
}
|
||||
|
||||
export class DeleteRunner implements Runner {
|
||||
private jobLog: JobLog;
|
||||
|
||||
constructor(
|
||||
private job: Job,
|
||||
private model: Model,
|
||||
/** Every file path of the model's repo we know of. */
|
||||
private repoPaths: string[],
|
||||
) {
|
||||
this.jobLog = new JobLog(job.id);
|
||||
}
|
||||
|
||||
get jobId() {
|
||||
return this.job.id;
|
||||
}
|
||||
get modelId() {
|
||||
return this.model.id;
|
||||
}
|
||||
get kind() {
|
||||
return this.job.kind;
|
||||
}
|
||||
|
||||
// Deleting is quick and shouldn't stop halfway; cancel and shutdown wait for it.
|
||||
cancel() {}
|
||||
interrupt() {}
|
||||
|
||||
async run(): Promise<void> {
|
||||
const root = resolve(coreEnv().MODELS_DIR);
|
||||
const dir = modelDir(root, this.model.localPath);
|
||||
const deleted: string[] = [];
|
||||
try {
|
||||
const before = await listLocalFiles(dir);
|
||||
const sizes = new Map(before.map((f) => [f.path, f.size]));
|
||||
for (const path of this.repoPaths) if (await removeLocalFile(dir, path)) deleted.push(path);
|
||||
await rm(join(dir, HF_CACHE_DIR), { recursive: true, force: true });
|
||||
await rmdir(join(dir, ".cache")).catch(() => {});
|
||||
|
||||
const kept = (await listLocalFiles(dir)).map((f) => f.path);
|
||||
await removeEmptyDirs(dir);
|
||||
// The org folder too, if this was its last model (never MODELS_DIR itself).
|
||||
const parent = dirname(dir);
|
||||
if (parent !== root) await rmdir(parent).catch(() => {});
|
||||
|
||||
const bytes = deleted.reduce((s, p) => s + (sizes.get(p) ?? 0), 0);
|
||||
log.info(
|
||||
`deleted ${this.model.repoId}: ${deleted.length} file(s), ${formatBytes(bytes)}` +
|
||||
(kept.length > 0 ? `; kept ${kept.length} file(s) that aren't part of the repo: ${kept.slice(0, 5).join(", ")}` : ""),
|
||||
);
|
||||
// The job and its log go with the model; the worker log above is the record.
|
||||
await purgeModelRows(this.model.id);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.jobLog.system(`Failed after deleting ${deleted.length} file(s): ${message}`);
|
||||
await this.jobLog.close();
|
||||
const d = db();
|
||||
await d.batch([
|
||||
d
|
||||
.update(jobs)
|
||||
.set({ state: "failed", finishedAt: new Date(), errorCode: "unknown", errorMessage: message })
|
||||
.where(eq(jobs.id, this.job.id)),
|
||||
...(deleted.length > 0
|
||||
? [
|
||||
d
|
||||
.update(modelFiles)
|
||||
.set({ state: "missing", checkedAt: new Date() })
|
||||
.where(and(eq(modelFiles.modelId, this.model.id), inArray(modelFiles.path, deleted))),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
await settleModelStatus(this.model.id);
|
||||
log.error(`job ${this.job.id}: deleting ${this.model.repoId} failed`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-1
@@ -1,10 +1,12 @@
|
||||
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,
|
||||
@@ -17,12 +19,15 @@ 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";
|
||||
|
||||
const SAMPLE_MS = 1_000;
|
||||
@@ -45,6 +50,8 @@ type FileRow = {
|
||||
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 =
|
||||
@@ -52,7 +59,7 @@ type Outcome =
|
||||
| { state: "cancelled" | "interrupted"; message: string }
|
||||
| { state: "failed"; code: JobErrorCode; message: string; exitCode?: number | null };
|
||||
|
||||
export class DownloadRunner {
|
||||
export class DownloadRunner implements Runner {
|
||||
private child?: ChildProcess;
|
||||
private stopReason?: "cancelled" | "interrupted";
|
||||
private killTimer?: NodeJS.Timeout;
|
||||
@@ -74,6 +81,10 @@ export class DownloadRunner {
|
||||
return this.model.id;
|
||||
}
|
||||
|
||||
get kind() {
|
||||
return this.job.kind;
|
||||
}
|
||||
|
||||
/** User cancel: stop hf, keep completed files. */
|
||||
cancel() {
|
||||
this.stop("cancelled");
|
||||
@@ -144,6 +155,18 @@ export class DownloadRunner {
|
||||
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;
|
||||
@@ -199,6 +222,12 @@ export class DownloadRunner {
|
||||
.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" };
|
||||
}
|
||||
|
||||
|
||||
@@ -109,3 +109,31 @@ export async function bytesOnDisk(
|
||||
}
|
||||
return { done: Math.min(partial, file.size), complete: false };
|
||||
}
|
||||
|
||||
/** Delete a downloaded file and hf's metadata/lock for it, so the next `hf download` fetches it again. */
|
||||
export async function removeLocalFile(dir: string, path: string): Promise<boolean> {
|
||||
const full = join(dir, path);
|
||||
const existed = (await fileSize(full)) != null;
|
||||
await rm(full, { force: true });
|
||||
await rm(join(dir, DOWNLOAD_DIR, `${path}.metadata`), { force: true });
|
||||
await rm(join(dir, DOWNLOAD_DIR, `${path}.lock`), { force: true });
|
||||
return existed;
|
||||
}
|
||||
|
||||
/** All files under `dir` (relative, "/"-separated), skipping hf's .cache and .git folders. */
|
||||
export async function listLocalFiles(dir: string): Promise<{ path: string; size: number }[]> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const out: { path: string; size: number }[] = [];
|
||||
for (const e of entries) {
|
||||
if (!e.isFile()) continue;
|
||||
const rel = join(e.parentPath, e.name).slice(dir.length + 1).split(sep).join("/");
|
||||
if (rel.startsWith(".cache/") || rel.startsWith(".git/")) continue;
|
||||
out.push({ path: rel, size: (await fileSize(join(dir, rel))) ?? 0 });
|
||||
}
|
||||
return out.sort((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
+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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { JobKind } from "@/lib/db/schema";
|
||||
|
||||
/** A job the worker is executing (download, verify, delete). */
|
||||
export interface Runner {
|
||||
readonly jobId: string;
|
||||
readonly modelId: string;
|
||||
readonly kind: JobKind;
|
||||
/** User cancel. */
|
||||
cancel(): void;
|
||||
/** Worker shutdown; the job can be resumed later. */
|
||||
interrupt(): void;
|
||||
run(): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// Verify a model's local files against the file list of its pinned commit.
|
||||
// verify: existence, size, and hf's recorded etag (fast)
|
||||
// deep_verify: additionally hashes every file: SHA-256 for LFS files, git blob SHA-1 for small
|
||||
// files, compared with the hashes from the Hub API (slow, with progress)
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type JobResult, jobFiles, jobs, type ModelFileState, modelFiles, models } from "@/lib/db/schema";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import { fileSize, listLocalFiles, modelDir, readMetadata } 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";
|
||||
|
||||
const PROGRESS_MS = 1_000;
|
||||
|
||||
type Job = typeof jobs.$inferSelect;
|
||||
type Model = typeof models.$inferSelect;
|
||||
export type VerifyFile = { modelFileId: string; path: string; expectedBytes: number; lfsSha256: string | null; blobOid: string | null };
|
||||
|
||||
class Stopped extends Error {}
|
||||
|
||||
export class VerifyRunner implements Runner {
|
||||
private stopReason?: "cancelled" | "interrupted";
|
||||
private jobLog: JobLog;
|
||||
|
||||
constructor(
|
||||
private job: Job,
|
||||
private model: Model,
|
||||
private files: VerifyFile[],
|
||||
/** Every path of the repo at the pinned commit (selected or not), to classify extra files. */
|
||||
private repoPaths: Set<string>,
|
||||
) {
|
||||
this.jobLog = new JobLog(job.id);
|
||||
}
|
||||
|
||||
get jobId() {
|
||||
return this.job.id;
|
||||
}
|
||||
get modelId() {
|
||||
return this.model.id;
|
||||
}
|
||||
get kind() {
|
||||
return this.job.kind;
|
||||
}
|
||||
|
||||
cancel() {
|
||||
this.stopReason ??= "cancelled";
|
||||
}
|
||||
interrupt() {
|
||||
this.stopReason ??= "interrupted";
|
||||
}
|
||||
|
||||
async run(): Promise<void> {
|
||||
const deep = this.job.kind === "deep_verify";
|
||||
const dir = modelDir(coreEnv().MODELS_DIR, this.model.localPath);
|
||||
const result: Required<Pick<JobResult, "checked" | "missing" | "sizeMismatch" | "hashMismatch" | "extra">> = {
|
||||
checked: 0,
|
||||
missing: [],
|
||||
sizeMismatch: [],
|
||||
hashMismatch: [],
|
||||
extra: [],
|
||||
};
|
||||
this.jobLog.system(
|
||||
`${deep ? "Deep verify (hashing every file)" : "Verify (existence, size, hf metadata)"}: ${this.files.length} selected file(s), ${formatBytes(this.job.totalBytes)} in ${dir}`,
|
||||
);
|
||||
|
||||
const speed = new SpeedMeter();
|
||||
let doneBytes = 0;
|
||||
let lastWrite = 0;
|
||||
const writeProgress = async (force = false) => {
|
||||
if (!force && Date.now() - lastWrite < PROGRESS_MS) return;
|
||||
lastWrite = Date.now();
|
||||
speed.add(Date.now(), doneBytes);
|
||||
const bps = speed.bytesPerSecond();
|
||||
await db()
|
||||
.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));
|
||||
await this.jobLog.flush();
|
||||
};
|
||||
|
||||
let failure: string | null = null;
|
||||
try {
|
||||
for (const f of this.files) {
|
||||
if (this.stopReason) throw new Stopped();
|
||||
const state = await this.check(dir, f, deep, async (n) => {
|
||||
doneBytes += n;
|
||||
await writeProgress();
|
||||
});
|
||||
if (!deep) doneBytes += f.expectedBytes;
|
||||
result.checked++;
|
||||
if (state === "missing") result.missing.push(f.path);
|
||||
if (state === "size_mismatch") result.sizeMismatch.push(f.path);
|
||||
if (state === "hash_mismatch") result.hashMismatch.push(f.path);
|
||||
if (state !== "present" && state !== "verified") this.jobLog.system(`${state.replace("_", " ")}: ${f.path}`);
|
||||
await this.markFile(f, state);
|
||||
await writeProgress();
|
||||
}
|
||||
|
||||
// Anything else in the folder: unselected repo files, or files that aren't in the repo at all.
|
||||
const selected = new Set(this.files.map((f) => f.path));
|
||||
for (const local of await listLocalFiles(dir)) {
|
||||
if (!selected.has(local.path)) result.extra.push({ ...local, inRepo: this.repoPaths.has(local.path) });
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof Stopped)) failure = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const problems = result.missing.length + result.sizeMismatch.length + result.hashMismatch.length;
|
||||
if (this.stopReason) {
|
||||
this.jobLog.system(this.stopReason === "cancelled" ? "Cancelled by user." : "Interrupted by worker shutdown.");
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: this.stopReason, finishedAt: now, speedBps: null, etaSeconds: null, result })
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
} else if (failure) {
|
||||
this.jobLog.system(`Failed: ${failure}`);
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: "failed", finishedAt: now, speedBps: null, etaSeconds: null, errorCode: "unknown", errorMessage: failure, result })
|
||||
.where(eq(jobs.id, this.job.id));
|
||||
} else {
|
||||
const extraLine =
|
||||
result.extra.length > 0
|
||||
? ` ${result.extra.length} extra file(s) in the folder (${formatBytes(result.extra.reduce((s, e) => s + e.size, 0))}).`
|
||||
: "";
|
||||
this.jobLog.system(
|
||||
problems === 0
|
||||
? `All ${result.checked} file(s) OK${deep ? " (hashes match the Hub)" : ""}.${extraLine}`
|
||||
: `${problems} problem(s): ${result.missing.length} missing, ${result.sizeMismatch.length} size mismatch, ${result.hashMismatch.length} hash mismatch.${extraLine} Use Repair to download them again.`,
|
||||
);
|
||||
await db().batch([
|
||||
db()
|
||||
.update(jobs)
|
||||
.set({ state: "completed", finishedAt: now, speedBps: null, etaSeconds: 0, doneBytes: this.job.totalBytes, result })
|
||||
.where(eq(jobs.id, this.job.id)),
|
||||
db().update(models).set({ lastVerifiedAt: now }).where(eq(models.id, this.model.id)),
|
||||
]);
|
||||
}
|
||||
await this.jobLog.close();
|
||||
await settleModelStatus(this.model.id);
|
||||
log.info(`job ${this.job.id} (${this.job.kind} ${this.model.repoId}) ${this.stopReason ?? (failure ? "failed" : "completed")}`);
|
||||
}
|
||||
|
||||
private async check(dir: string, f: VerifyFile, deep: boolean, onBytes: (n: number) => Promise<void>): Promise<ModelFileState> {
|
||||
const full = join(dir, f.path);
|
||||
const size = await fileSize(full);
|
||||
if (size == null) return "missing";
|
||||
if (size !== f.expectedBytes) return "size_mismatch";
|
||||
if (!deep) {
|
||||
// hf records the etag it downloaded; a different one means another version of the file.
|
||||
const meta = await readMetadata(dir, f.path);
|
||||
const etags = [f.lfsSha256, f.blobOid].filter(Boolean);
|
||||
return meta && !etags.includes(meta.etag) ? "hash_mismatch" : "present";
|
||||
}
|
||||
const actual = await this.hash(full, f, onBytes);
|
||||
const expected = f.lfsSha256 ?? f.blobOid;
|
||||
return expected && actual === expected ? "verified" : "hash_mismatch";
|
||||
}
|
||||
|
||||
/** SHA-256 of the content (LFS files) or the git blob SHA-1 (small files stored in git). */
|
||||
private hash(full: string, f: VerifyFile, onBytes: (n: number) => Promise<void>): Promise<string> {
|
||||
const h = f.lfsSha256 ? createHash("sha256") : createHash("sha1").update(`blob ${f.expectedBytes}\0`);
|
||||
return new Promise((resolve, reject) => {
|
||||
const stream = createReadStream(full, { highWaterMark: 8 * 1024 * 1024 });
|
||||
stream.on("data", (chunk) => {
|
||||
if (this.stopReason) {
|
||||
stream.destroy(new Stopped());
|
||||
return;
|
||||
}
|
||||
h.update(chunk);
|
||||
stream.pause();
|
||||
onBytes(chunk.length).then(
|
||||
() => stream.resume(),
|
||||
(err) => stream.destroy(err),
|
||||
);
|
||||
});
|
||||
stream.on("error", reject);
|
||||
stream.on("end", () => resolve(h.digest("hex")));
|
||||
});
|
||||
}
|
||||
|
||||
private async markFile(f: VerifyFile, state: ModelFileState) {
|
||||
const now = new Date();
|
||||
const ok = state === "present" || state === "verified";
|
||||
await db().batch([
|
||||
db().update(modelFiles).set({ state, checkedAt: now }).where(eq(modelFiles.id, f.modelFileId)),
|
||||
db()
|
||||
.update(jobFiles)
|
||||
.set({ state: ok ? "done" : "failed", doneBytes: ok ? f.expectedBytes : 0 })
|
||||
.where(and(eq(jobFiles.jobId, this.job.id), inArray(jobFiles.modelFileId, [f.modelFileId]))),
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user