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:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-06 01:00:55 +02:00
1 parent c2c239bf16
commit 7864a492c9
37 files changed
+2365 -191

No files matched your search

+97 -22
View File
@@ -1,18 +1,20 @@
import "server-only";
import { and, eq, inArray, sql } from "drizzle-orm";
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
import { ulid } from "ulid";
import { db } from "@/lib/db/client";
import { jobs, localFolders, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema";
import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from "@/lib/db/schema";
import { hubMissingMessage } from "@/lib/hub/availability";
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
import { metadataColumns } from "@/lib/hub/refresh";
import { queueDownload } from "@/lib/jobs";
import { getLocalFolder } from "@/lib/local-folders";
import { hasOpenJob, queueDownload } from "@/lib/jobs";
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
import { purgeModelRows } from "@/lib/model-purge";
import { contentId } from "@/lib/update-diff";
import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection";
export class ModelError extends Error {
constructor(
public code: "already_exists" | "empty_selection" | "not_found" | "not_removable" | "busy" | "hub_missing",
public code: "already_exists" | "empty_selection" | "not_found" | "busy" | "hub_missing" | "no_update",
message: string,
public status: number,
) {
@@ -88,28 +90,100 @@ export async function addModel(input: {
return { id: modelId };
}
/** Remove a model from the library. Only allowed before anything was downloaded (for now). */
export async function removeModel(id: string): Promise<void> {
/**
* Delete a model. With `deleteFiles` the worker removes its files from disk first (a "delete" job;
* files that aren't part of the repo are kept); without, only the library entry goes and the
* folder shows up under "Found in the models folder" again.
*/
export async function deleteModel(id: string, options: { deleteFiles: boolean }): Promise<{ queued: boolean }> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
if (!model) throw new ModelError("not_found", "Model not found.", 404);
const [{ n }] = await d
.select({ n: sql<number>`count(*)` })
.from(jobs)
.where(eq(jobs.modelId, id));
if (model.status !== "pending" || n > 0) {
throw new ModelError(
"not_removable",
"Only models that were never downloaded can be removed yet. Deleting downloaded models comes in a later milestone.",
409,
);
if (await hasOpenJob(id)) {
throw new ModelError("busy", "A job for this model is still queued or running. Cancel it first.", 409);
}
const [{ n }] = await d.select({ n: sql<number>`count(*)` }).from(jobs).where(eq(jobs.modelId, id));
const neverDownloaded = model.status === "pending" && n === 0;
if (!options.deleteFiles || neverDownloaded) {
await purgeModelRows(id);
if (!neverDownloaded) await requestFolderScan();
return { queued: false };
}
await d.batch([
d.delete(modelTags).where(eq(modelTags.modelId, id)),
d.delete(modelFiles).where(eq(modelFiles.modelId, id)),
d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)),
d.delete(models).where(eq(models.id, id)),
d.insert(jobs).values({ id: ulid(), modelId: id, kind: "delete", targetSha: model.pinnedSha }),
d.update(models).set({ status: "deleting" }).where(eq(models.id, id)),
]);
return { queued: true };
}
/**
* Update a model to the newer commit found by the last Hub check: pin it (the old commit stays in
* the revision history), refresh the file list, re-apply the selection rule and queue a download.
* Unchanged files are kept; changed ones are downloaded again; files that are no longer selected are
* deleted after the download succeeded.
*/
export async function applyUpdate(id: string): Promise<{ jobId: string; sha: string }> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, id) });
if (!model) throw new ModelError("not_found", "Model not found.", 404);
const missing = hubMissingMessage(model);
if (missing) throw new ModelError("hub_missing", missing, 409);
if (await hasOpenJob(id)) {
throw new ModelError("busy", "A job for this model is still queued or running. Try again when it has finished.", 409);
}
const target = model.updateDiff?.sha;
if (!target || target !== model.remoteSha || target === model.pinnedSha) {
throw new ModelError("no_update", "No update available. Check the Hub again.", 409);
}
const info = await getRepoInfo(model.repoId, target);
const files = await listFiles(model.repoId, info.sha);
const rule: SelectionRule = { include: model.includePatterns, exclude: model.excludePatterns };
const existing = await d.select().from(modelFiles).where(eq(modelFiles.modelId, id));
const byPath = new Map(existing.map((f) => [f.path, f]));
const next = new Set(files.map((f) => f.path));
const now = new Date();
const writes = [];
for (const f of files) {
const selected = isSelected(f.path, rule);
const old = byPath.get(f.path);
if (!old) {
writes.push(d.insert(modelFiles).values({ modelId: id, path: f.path, size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected }));
continue;
}
const same = contentId(old) === contentId(f);
if (same && old.selected === selected) continue;
writes.push(
d
.update(modelFiles)
.set({ size: f.size, blobOid: f.blobOid, lfsSha256: f.lfsSha256, selected, state: same ? old.state : "pending" })
.where(eq(modelFiles.id, old.id)),
);
}
// Files gone at the new commit: drop them (and their rows in old jobs' file lists).
const gone = existing.filter((f) => !next.has(f.path));
if (gone.length > 0) {
const ids = gone.map((f) => f.id);
writes.push(d.delete(jobFiles).where(inArray(jobFiles.modelFileId, ids)), d.delete(modelFiles).where(inArray(modelFiles.id, ids)));
}
// Selected before, not anymore (removed from the repo or no longer matching): delete after the download.
const removePaths = existing.filter((f) => f.selected && (!next.has(f.path) || !isSelected(f.path, rule))).map((f) => f.path);
await d.batch([
d
.update(models)
.set({ pinnedSha: info.sha, updateDiff: null, ...metadataColumns(info.metadata, model.authorAvatarUrl) })
.where(eq(models.id, id)),
d
.update(modelRevisions)
.set({ supersededAt: now })
.where(and(eq(modelRevisions.modelId, id), isNull(modelRevisions.supersededAt))),
d.insert(modelRevisions).values({ modelId: id, sha: info.sha }),
...writes,
]);
const { jobId } = await queueDownload(id, "update", { removePaths });
return { jobId, sha: info.sha };
}
function chunk<T>(items: T[], size: number): T[][] {
@@ -148,7 +222,8 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
await d.batch([
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude }).where(eq(models.id, modelId)),
// The selection changed, so a stored update diff is stale; the next Hub check recomputes it.
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
...changed.map((f) =>
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
),