The Import form gets "Add as local model": every file in the folder, kept as it is, named after the folder. A new models.source column (hub | local) marks them; local models skip Hub checks, metadata, downloads, updates and deep verify, and Verify checks existence and size only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
204 lines
8.3 KiB
TypeScript
204 lines
8.3 KiB
TypeScript
// 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);
|
|
// Local models (no Hub repo) have no etags to compare with: existence and size is all.
|
|
return meta && etags.length > 0 && !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]))),
|
|
]);
|
|
}
|
|
}
|