From 7864a492c969655b3ab419d2229dd9677aa98936 Mon Sep 17 00:00:00 2001 From: Pascal Linxweiler Date: Tue, 6 Oct 2026 01:00:55 +0200 Subject: [PATCH] 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 --- .env.example | 2 +- CHANGELOG.md | 21 + README.md | 8 +- drizzle/0009_verify_update.sql | 2 + drizzle/meta/0009_snapshot.json | 1033 +++++++++++++++++ drizzle/meta/_journal.json | 7 + .../[org]/[repo]/delete-model-button.tsx | 99 ++ src/app/(app)/[org]/[repo]/download-card.tsx | 108 +- src/app/(app)/[org]/[repo]/hub-check.tsx | 5 +- src/app/(app)/[org]/[repo]/jobs-tab.tsx | 4 +- src/app/(app)/[org]/[repo]/page.tsx | 36 +- .../[org]/[repo]/remove-model-button.tsx | 57 - src/app/(app)/[org]/[repo]/update-banner.tsx | 121 ++ src/app/(app)/jobs/[id]/job-live.tsx | 3 +- src/app/(app)/library-view.tsx | 12 +- src/app/api/models/[id]/hub-check/route.ts | 4 +- src/app/api/models/[id]/repair/route.ts | 15 + src/app/api/models/[id]/route.ts | 10 +- src/app/api/models/[id]/update/route.ts | 15 + src/app/api/models/[id]/verify/route.ts | 16 + src/components/job-actions.ts | 14 + src/components/verify-result.tsx | 52 + src/lib/db/schema.ts | 29 +- src/lib/hub/availability.ts | 114 +- src/lib/job-labels.ts | 16 + src/lib/jobs.ts | 62 +- src/lib/library.ts | 4 +- src/lib/model-purge.ts | 20 + src/lib/models.ts | 119 +- src/lib/update-diff.test.ts | 34 + src/lib/update-diff.ts | 34 + src/worker/delete.ts | 107 ++ src/worker/download.ts | 31 +- src/worker/hf-layout.ts | 28 + src/worker/index.ts | 99 +- src/worker/runner.ts | 13 + src/worker/verify.ts | 202 ++++ 37 files changed, 2365 insertions(+), 191 deletions(-) create mode 100644 drizzle/0009_verify_update.sql create mode 100644 drizzle/meta/0009_snapshot.json create mode 100644 src/app/(app)/[org]/[repo]/delete-model-button.tsx delete mode 100644 src/app/(app)/[org]/[repo]/remove-model-button.tsx create mode 100644 src/app/(app)/[org]/[repo]/update-banner.tsx create mode 100644 src/app/api/models/[id]/repair/route.ts create mode 100644 src/app/api/models/[id]/update/route.ts create mode 100644 src/app/api/models/[id]/verify/route.ts create mode 100644 src/components/verify-result.tsx create mode 100644 src/lib/job-labels.ts create mode 100644 src/lib/model-purge.ts create mode 100644 src/lib/update-diff.test.ts create mode 100644 src/lib/update-diff.ts create mode 100644 src/worker/delete.ts create mode 100644 src/worker/runner.ts create mode 100644 src/worker/verify.ts diff --git a/.env.example b/.env.example index 842ad88..f5805d1 100644 --- a/.env.example +++ b/.env.example @@ -37,7 +37,7 @@ KANAME_VERSION= # --------------------------------------------------------------------------- MAX_CONCURRENT_DOWNLOADS=1 -# How often the worker checks every model on the Hub (still there? later: newer commits); 0 disables it +# How often the worker checks every model on the Hub (still there? newer commit?); 0 disables it UPDATE_CHECK_INTERVAL_HOURS=12 # 1 (default): hf downloads over plain HTTP, so progress can be measured from bytes on disk. # 0: use Xet (chunk-level dedup on updates), but progress only advances in large jumps. diff --git a/CHANGELOG.md b/CHANGELOG.md index b5f8310..1cdbe3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,27 @@ step 1 (Hugging Face downloader) is released as a minor version. ## [Unreleased] +### Added + +- **Delete** any model (also failed or incomplete ones), with confirmation. By default the worker + deletes its files from disk: only the repo's files and hf's `.cache`; files you put in the folder + yourself are kept, empty folders are removed. Unchecked, only the library entry goes and the folder + shows up under "Found in the models folder". +- **Verify** a model: every selected file is checked for existence, size and the version hf recorded; + reports missing files, size mismatches and extra files in the folder. **Deep verify** hashes every + file (SHA-256 for LFS files, git blob SHA-1 for small files) against the Hub, with progress. +- **Repair** re-downloads only what's missing or broken. Broken files are deleted before `hf` runs, + because `hf` skips a file whose metadata matches without checking its content or size. +- **Update checks:** the Hub check (every `UPDATE_CHECK_INTERVAL_HOURS` and "Check now") also + resolves the tracked revision. If there's a newer commit, the model shows "update available" (badge + in the library and a Status filter value, banner on the model page) with the selected files that + changed, were added or were removed. **Update** is a deliberate action: it pins the new commit (the + old one stays in the revision history), downloads changed and new files, and deletes files that are + no longer selected once the download succeeded. +- Download card: **Resume** for interrupted or cancelled downloads, **Retry** for failed ones. +- Job names in the job list and job page: Download, Download more, Import, Repair, Update, Verify, + Deep verify, Delete. + ## [0.5.0] - 2026-10-06 Hugging Face style model pages, file labels, recommended files, importing models already on disk, diff --git a/README.md b/README.md index 585c9fc..e2cdeb8 100644 --- a/README.md +++ b/README.md @@ -76,8 +76,12 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname "Found in the models folder"; **Import** matches them with the Hub repo and verifies the files instead of downloading them again. See the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Importing-existing-models). -- **Deleted on the Hub:** if a repo (or its pinned commit) disappears from Hugging Face, the model - is flagged and your local copy is kept. +- **Verify / repair:** Verify checks every file's presence and size, Deep verify hashes them against + the Hub; Repair downloads only what's missing or broken. +- **Updates:** Kaname checks the Hub regularly and shows which of your files a newer commit changes; + updating is always your click. If a repo (or its pinned commit) disappears from Hugging Face, the + model is flagged and your local copy is kept. +- **Delete:** removes the model and, if you want, its files from disk. - **Jobs:** each download has a page with per-file progress and the full `hf` log. ## How it works diff --git a/drizzle/0009_verify_update.sql b/drizzle/0009_verify_update.sql new file mode 100644 index 0000000..e2a478f --- /dev/null +++ b/drizzle/0009_verify_update.sql @@ -0,0 +1,2 @@ +ALTER TABLE `jobs` ADD `result` text;--> statement-breakpoint +ALTER TABLE `models` ADD `update_diff` text; \ No newline at end of file diff --git a/drizzle/meta/0009_snapshot.json b/drizzle/meta/0009_snapshot.json new file mode 100644 index 0000000..bdd1ea6 --- /dev/null +++ b/drizzle/meta/0009_snapshot.json @@ -0,0 +1,1033 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "b3b76363-6bde-4c57-b048-9d265bbcac6f", + "prevId": "0f393ca9-5120-4126-b68e-797c99b97ece", + "tables": { + "job_files": { + "name": "job_files", + "columns": { + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model_file_id": { + "name": "model_file_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expected_bytes": { + "name": "expected_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "done_bytes": { + "name": "done_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + } + }, + "indexes": {}, + "foreignKeys": { + "job_files_job_id_jobs_id_fk": { + "name": "job_files_job_id_jobs_id_fk", + "tableFrom": "job_files", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "job_files_model_file_id_model_files_id_fk": { + "name": "job_files_model_file_id_model_files_id_fk", + "tableFrom": "job_files", + "tableTo": "model_files", + "columnsFrom": [ + "model_file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "job_files_job_id_model_file_id_pk": { + "columns": [ + "job_id", + "model_file_id" + ], + "name": "job_files_job_id_model_file_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "job_logs": { + "name": "job_logs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "job_id": { + "name": "job_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ts": { + "name": "ts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stream": { + "name": "stream", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "line": { + "name": "line", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "job_logs_job_idx": { + "name": "job_logs_job_idx", + "columns": [ + "job_id", + "id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "job_logs_job_id_jobs_id_fk": { + "name": "job_logs_job_id_jobs_id_fk", + "tableFrom": "job_logs", + "tableTo": "jobs", + "columnsFrom": [ + "job_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "jobs": { + "name": "jobs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_sha": { + "name": "target_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "done_bytes": { + "name": "done_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "speed_bps": { + "name": "speed_bps", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "eta_seconds": { + "name": "eta_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "exit_code": { + "name": "exit_code", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cancel_requested_at": { + "name": "cancel_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "jobs_state_idx": { + "name": "jobs_state_idx", + "columns": [ + "state" + ], + "isUnique": false + }, + "jobs_model_idx": { + "name": "jobs_model_idx", + "columns": [ + "model_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "jobs_model_id_models_id_fk": { + "name": "jobs_model_id_models_id_fk", + "tableFrom": "jobs", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "local_folders": { + "name": "local_folders", + "columns": { + "path": { + "name": "path", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "files": { + "name": "files", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "file_count": { + "name": "file_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "commit": { + "name": "commit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scanned_at": { + "name": "scanned_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_files": { + "name": "model_files", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "blob_oid": { + "name": "blob_oid", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lfs_sha256": { + "name": "lfs_sha256", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "selected": { + "name": "selected", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "model_files_model_path_uq": { + "name": "model_files_model_path_uq", + "columns": [ + "model_id", + "path" + ], + "isUnique": true + } + }, + "foreignKeys": { + "model_files_model_id_models_id_fk": { + "name": "model_files_model_id_models_id_fk", + "tableFrom": "model_files", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_revisions": { + "name": "model_revisions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pinned_at": { + "name": "pinned_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "superseded_at": { + "name": "superseded_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "model_revisions_model_idx": { + "name": "model_revisions_model_idx", + "columns": [ + "model_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "model_revisions_model_id_models_id_fk": { + "name": "model_revisions_model_id_models_id_fk", + "tableFrom": "model_revisions", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "model_tags": { + "name": "model_tags", + "columns": { + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "model_tags_tag_idx": { + "name": "model_tags_tag_idx", + "columns": [ + "tag_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "model_tags_model_id_models_id_fk": { + "name": "model_tags_model_id_models_id_fk", + "tableFrom": "model_tags", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "model_tags_tag_id_tags_id_fk": { + "name": "model_tags_tag_id_tags_id_fk", + "tableFrom": "model_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "model_tags_model_id_tag_id_pk": { + "columns": [ + "model_id", + "tag_id" + ], + "name": "model_tags_model_id_tag_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "models": { + "name": "models", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "repo_type": { + "name": "repo_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'model'" + }, + "repo_id": { + "name": "repo_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tracked_revision": { + "name": "tracked_revision", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "pinned_sha": { + "name": "pinned_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "local_path": { + "name": "local_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "include_patterns": { + "name": "include_patterns", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "exclude_patterns": { + "name": "exclude_patterns", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "remote_sha": { + "name": "remote_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_state": { + "name": "hub_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_missing_since": { + "name": "hub_missing_since", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "update_diff": { + "name": "update_diff", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_verified_at": { + "name": "last_verified_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "downloaded_at": { + "name": "downloaded_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_models": { + "name": "base_models", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_relation": { + "name": "base_relation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "author_avatar_url": { + "name": "author_avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "architecture": { + "name": "architecture", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pipeline_tag": { + "name": "pipeline_tag", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "license": { + "name": "license", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_tags": { + "name": "hub_tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata_fetched_at": { + "name": "metadata_fetched_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "models_repo_uq": { + "name": "models_repo_uq", + "columns": [ + "repo_type", + "repo_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tags": { + "name": "tags", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "tags_slug_uq": { + "name": "tags_slug_uq", + "columns": [ + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "worker_state": { + "name": "worker_state", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "instance_id": { + "name": "instance_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pid": { + "name": "pid", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hf_version": { + "name": "hf_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "models_dir_free_bytes": { + "name": "models_dir_free_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "models_dir_total_bytes": { + "name": "models_dir_total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "heartbeat_at": { + "name": "heartbeat_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scan_requested_at": { + "name": "scan_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index ecb06f7..d0c66df 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -64,6 +64,13 @@ "when": 1791233749207, "tag": "0008_local_folders", "breakpoints": true + }, + { + "idx": 9, + "version": "6", + "when": 1791238659338, + "tag": "0009_verify_update", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/(app)/[org]/[repo]/delete-model-button.tsx b/src/app/(app)/[org]/[repo]/delete-model-button.tsx new file mode 100644 index 0000000..300e6bc --- /dev/null +++ b/src/app/(app)/[org]/[repo]/delete-model-button.tsx @@ -0,0 +1,99 @@ +"use client"; + +import { Trash2Icon } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { toast } from "sonner"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; + +/** + * Delete a model, whatever its state (failed, incomplete, ready, …). By default its files are + * deleted from disk too (by the worker); unchecked, only the library entry goes. + */ +export function DeleteModelButton({ + id, + repoId, + localPath, + mayHaveFiles, +}: { + id: string; + repoId: string; + localPath: string; + /** False if nothing was ever downloaded, so there's nothing on disk to ask about. */ + mayHaveFiles: boolean; +}) { + const router = useRouter(); + const [deleteFiles, setDeleteFiles] = useState(true); + const [pending, setPending] = useState(false); + + async function remove() { + setPending(true); + const res = await fetch(`/api/models/${id}${mayHaveFiles && deleteFiles ? "?files=1" : ""}`, { method: "DELETE" }); + if (res.ok) { + toast.success(res.status === 202 ? `Deleting ${repoId} and its files…` : `${repoId} removed from the library`); + router.push("/"); + router.refresh(); + } else { + const body = await res.json().catch(() => ({})); + toast.error(body.error?.message ?? `Delete failed (${res.status})`); + setPending(false); + } + } + + return ( + + + } + > + + Delete + + + + Delete {repoId}? + + {mayHaveFiles + ? "The model is removed from the library, including its tags and job history." + : "Nothing was downloaded yet, so this only removes the library entry."} + + + {mayHaveFiles && ( + + )} + + Cancel + + {mayHaveFiles && deleteFiles ? "Delete with files" : "Delete"} + + + + + ); +} diff --git a/src/app/(app)/[org]/[repo]/download-card.tsx b/src/app/(app)/[org]/[repo]/download-card.tsx index a768457..a963d7f 100644 --- a/src/app/(app)/[org]/[repo]/download-card.tsx +++ b/src/app/(app)/[org]/[repo]/download-card.tsx @@ -1,20 +1,23 @@ "use client"; -import { DownloadIcon } from "lucide-react"; +import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react"; import Link from "next/link"; import { useState } from "react"; -import { cancelJob, startDownload } from "@/components/job-actions"; +import { cancelJob, startDownload, startRepair, startVerify } from "@/components/job-actions"; import { JobProgress, JobStateBadge } from "@/components/job-progress"; import { Button } from "@/components/ui/button"; import { Progress } from "@/components/ui/progress"; +import { VerifyResult } from "@/components/verify-result"; import { useLive } from "@/hooks/use-live"; import type { ModelStatus } from "@/lib/db/schema"; import { groupJobFiles } from "@/lib/file-groups"; import { formatBytes, percent } from "@/lib/format"; +import { jobLabel } from "@/lib/job-labels"; const OPEN = ["queued", "downloading", "verifying"]; +const VERIFY_KINDS = ["verify", "deep_verify"]; -/** Sidebar card: current download state, actions and (while running) per-file progress. */ +/** Sidebar card: current job with progress, the last verify result, and the model's actions. */ export function DownloadCard({ modelId, status, @@ -27,11 +30,18 @@ export function DownloadCard({ }) { const { snapshot } = useLive({ model: modelId }); const [busy, setBusy] = useState(false); - const latest = snapshot?.jobs[0]; + const jobs = snapshot?.jobs ?? []; + const latest = jobs[0]; const open = latest && OPEN.includes(latest.state) ? latest : undefined; const files = open ? groupJobFiles(snapshot?.files ?? []) : []; + // The newest verify, unless a download ran after it (its result would be stale). + const lastCheck = jobs.find((j) => VERIFY_KINDS.includes(j.kind) || j.kind === "download"); + const verify = lastCheck && VERIFY_KINDS.includes(lastCheck.kind) && lastCheck.state === "completed" ? lastCheck : undefined; + const verifyProblems = verify?.result + ? (verify.result.missing?.length ?? 0) + (verify.result.sizeMismatch?.length ?? 0) + (verify.result.hashMismatch?.length ?? 0) + : 0; - async function run(fn: () => Promise) { + async function run(fn: () => Promise) { setBusy(true); try { await fn(); @@ -40,24 +50,40 @@ export function DownloadCard({ } } + const neverRan = jobs.length === 0; + const downloadLabel = neverRan + ? "Download" + : latest?.state === "interrupted" || latest?.state === "cancelled" + ? "Resume" + : latest?.state === "failed" && latest.kind === "download" + ? "Retry" + : "Download missing"; + const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot; + const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot; + const needsRepair = !open && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete"); + let hint = "Downloads the selected files at the pinned commit."; - if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free download slot." : "Queued, but the worker is offline."; + if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline."; else if (open) hint = "Runs in the background; you can close this page."; + else if (status === "deleting") hint = "Deleting…"; + else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept."; else if (status === "ready") hint = "All selected files are present."; - else if (hubMissing) hint = "Can't download: no longer available on Hugging Face. Local files are kept."; + + const showProgress = + latest && latest.kind !== "delete" && !(latest.state === "completed" && (status === "ready" || VERIFY_KINDS.includes(latest.kind))); return (

- Download + {open ? jobLabel(open) : "Download"}

{latest && }

{hint}

- {latest && !(latest.state === "completed" && status === "ready") && } + {showProgress && } {latest?.state === "failed" && latest.errorMessage && (
@@ -82,30 +108,58 @@ export function DownloadCard({
         
       )}
 
+      {verify?.result && !open && (
+        
+ +
+ )} +
{open ? ( - ) : ( - status !== "ready" && - !hubMissing && - snapshot && ( - - ) + <> + {needsRepair ? ( + + ) : ( + canDownload && ( + + ) + )} + {canVerify && ( + <> + + + + )} + )} - {latest && ( - + {latest && latest.kind !== "delete" && ( + View log )} diff --git a/src/app/(app)/[org]/[repo]/hub-check.tsx b/src/app/(app)/[org]/[repo]/hub-check.tsx index 44f943d..a65395c 100644 --- a/src/app/(app)/[org]/[repo]/hub-check.tsx +++ b/src/app/(app)/[org]/[repo]/hub-check.tsx @@ -7,7 +7,7 @@ import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; -/** Re-check right now whether the repo and pinned commit are still on the Hub. */ +/** Check the Hub right now: repo and pinned commit still there, newer commit on the tracked revision. */ export function HubCheckButton({ modelId, label = "Check now" }: { modelId: string; label?: string }) { const router = useRouter(); const [busy, setBusy] = useState(false); @@ -18,7 +18,8 @@ export function HubCheckButton({ modelId, label = "Check now" }: { modelId: stri const res = await fetch(`/api/models/${modelId}/hub-check`, { method: "POST" }); const json = await res.json().catch(() => ({})); if (!res.ok) toast.error(json.error?.message ?? `Check failed (${res.status})`); - else if (json.state === "available") toast.success("Still available on Hugging Face"); + else if (json.state === "available" && json.update) toast.info("Update available"); + else if (json.state === "available") toast.success(json.warning ?? "Up to date"); else if (json.state === "repo_missing") toast.warning("The repo is no longer on Hugging Face"); else if (json.state === "commit_missing") toast.warning("The pinned commit is no longer on Hugging Face"); else toast.error(`Could not check: ${json.error ?? "unknown error"}`); diff --git a/src/app/(app)/[org]/[repo]/jobs-tab.tsx b/src/app/(app)/[org]/[repo]/jobs-tab.tsx index 07a19d0..ff98e96 100644 --- a/src/app/(app)/[org]/[repo]/jobs-tab.tsx +++ b/src/app/(app)/[org]/[repo]/jobs-tab.tsx @@ -6,6 +6,7 @@ import { LocalTime } from "@/components/local-time"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { useLive } from "@/hooks/use-live"; import { formatBytes } from "@/lib/format"; +import { jobLabel } from "@/lib/job-labels"; /** Job history of one model (live). */ export function JobsTab({ modelId }: { modelId: string }) { @@ -35,8 +36,7 @@ export function JobsTab({ modelId }: { modelId: string }) { - {j.kind} - {j.purpose && j.purpose !== "initial" ? ` (${j.purpose})` : ""} + {jobLabel(j)} diff --git a/src/app/(app)/[org]/[repo]/page.tsx b/src/app/(app)/[org]/[repo]/page.tsx index be04f4f..9b19642 100644 --- a/src/app/(app)/[org]/[repo]/page.tsx +++ b/src/app/(app)/[org]/[repo]/page.tsx @@ -25,6 +25,7 @@ import { cn } from "@/lib/utils"; import { formatBytes, shortSha } from "@/lib/format"; import { fetchModelCard } from "@/lib/hub/client"; import { modelFamilies } from "@/lib/hub/metadata"; +import { listModelJobs } from "@/lib/jobs"; import { getModelByRepo, relatedModels } from "@/lib/library"; import { fileRole } from "@/lib/file-roles"; import { quantGroup } from "@/lib/selection"; @@ -35,8 +36,9 @@ import { FilesTab } from "./files-tab"; import { HubCheckButton } from "./hub-check"; import { JobsTab } from "./jobs-tab"; import { ModelCard } from "./model-card"; -import { RemoveModelButton } from "./remove-model-button"; +import { DeleteModelButton } from "./delete-model-button"; import { TagEditor } from "./tag-editor"; +import { UpdateBanner } from "./update-banner"; export const dynamic = "force-dynamic"; @@ -95,12 +97,17 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o const hubTags = model.hubTags ?? []; const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing"; - const [tags, related, card, worker] = await Promise.all([ + const [tags, related, card, worker, recentJobs] = await Promise.all([ modelTagList(model.id), relatedModels(model.id, baseModels), tab === "card" ? fetchModelCard(model.repoId, model.pinnedSha).catch(() => undefined) : Promise.resolve(undefined), getWorkerStatus(), + listModelJobs(model.id, 1), ]); + const update = + !hubMissing && model.updateDiff && model.updateDiff.sha === model.remoteSha && model.remoteSha !== model.pinnedSha + ? model.updateDiff + : null; const selected = files.filter((f) => f.selected); const others = files.filter((f) => !f.selected); @@ -130,8 +137,18 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o + {update && ( + + update available + + )}
- {model.status === "pending" && } + 0} + /> 🤗 Hugging Face
@@ -190,6 +207,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
)} + {update && ( + + )} +
{/* Content card with the tabs as a segmented control in its header */} @@ -305,9 +326,11 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o )}
On the Hub
- + {model.hubState === "available" - ? "Available" + ? update + ? "Update available" + : "Up to date" : model.hubState === "repo_missing" ? "Repo deleted" : model.hubState === "commit_missing" @@ -316,9 +339,10 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o {model.lastCheckedAt && ( - {model.lastCheckError ? "check failed" : "checked"} + checked )} + {model.lastCheckError && {model.lastCheckError}}
Added
diff --git a/src/app/(app)/[org]/[repo]/remove-model-button.tsx b/src/app/(app)/[org]/[repo]/remove-model-button.tsx deleted file mode 100644 index 204b1fe..0000000 --- a/src/app/(app)/[org]/[repo]/remove-model-button.tsx +++ /dev/null @@ -1,57 +0,0 @@ -"use client"; - -import { useRouter } from "next/navigation"; -import { useState } from "react"; -import { toast } from "sonner"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, - AlertDialogTrigger, -} from "@/components/ui/alert-dialog"; -import { Button } from "@/components/ui/button"; - -/** Removes a not-yet-downloaded model from the library (DB only, no files exist yet). */ -export function RemoveModelButton({ id }: { id: string }) { - const router = useRouter(); - const [busy, setBusy] = useState(false); - - async function remove() { - setBusy(true); - const res = await fetch(`/api/models/${id}`, { method: "DELETE" }); - if (res.ok) { - toast.success("Removed from library"); - router.push("/"); - router.refresh(); - } else { - const body = await res.json().catch(() => ({})); - toast.error(body.error?.message ?? `Remove failed (${res.status})`); - setBusy(false); - } - } - - return ( - - }>Remove - - - Remove from library? - - Nothing has been downloaded yet, so this only removes the entry. - - - - Cancel - - Remove - - - - - ); -} diff --git a/src/app/(app)/[org]/[repo]/update-banner.tsx b/src/app/(app)/[org]/[repo]/update-banner.tsx new file mode 100644 index 0000000..f8be6ce --- /dev/null +++ b/src/app/(app)/[org]/[repo]/update-banner.tsx @@ -0,0 +1,121 @@ +"use client"; + +import { ArrowUpCircleIcon } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { startUpdate } from "@/components/job-actions"; +import { LocalTime } from "@/components/local-time"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog"; +import { Button } from "@/components/ui/button"; +import type { UpdateDiff, UpdateDiffFile } from "@/lib/db/schema"; +import { formatBytes, shortSha } from "@/lib/format"; + +function FileGroup({ title, files, tone }: { title: string; files: UpdateDiffFile[]; tone: string }) { + if (files.length === 0) return null; + return ( +
+ + {title} ({files.length}) + +
    + {files.slice(0, 20).map((f) => ( +
  • + {f.path} + + {f.oldSize != null && f.oldSize !== f.size ? `${formatBytes(f.oldSize)} → ` : ""} + {formatBytes(f.size)} + +
  • + ))} + {files.length > 20 &&
  • … {files.length - 20} more
  • } +
+
+ ); +} + +/** "Update available": what would change in the selection, and the deliberate Update action. */ +export function UpdateBanner({ + modelId, + revision, + pinnedSha, + diff, + hubUrl, +}: { + modelId: string; + revision: string; + pinnedSha: string; + diff: UpdateDiff; + hubUrl: string; +}) { + const router = useRouter(); + const [busy, setBusy] = useState(false); + const changes = diff.changed.length + diff.added.length + diff.removed.length; + const download = [...diff.changed, ...diff.added].reduce((s, f) => s + f.size, 0); + + async function update() { + setBusy(true); + try { + if (await startUpdate(modelId)) router.refresh(); + } finally { + setBusy(false); + } + } + + return ( +
+
+ +
+

+ Update available: {revision} is at{" "} + + {shortSha(diff.sha)} + +

+

+ You have {shortSha(pinnedSha)}.{" "} + {changes === 0 + ? "None of your selected files changed; updating only moves the pin." + : `${changes} of your selected files would change (${formatBytes(download)} to download).`}{" "} + Checked . +

+
+ + }>Update + + + Update to {shortSha(diff.sha)}? + + The model is pinned to the new commit (the old one stays in the history) and changed or new files are + downloaded. Files that are no longer part of your selection are deleted after the download succeeded. + + + + Cancel + + Update + + + + +
+ {changes > 0 && ( +
+ + + +
+ )} +
+ ); +} diff --git a/src/app/(app)/jobs/[id]/job-live.tsx b/src/app/(app)/jobs/[id]/job-live.tsx index 3b4615b..d4db1b4 100644 --- a/src/app/(app)/jobs/[id]/job-live.tsx +++ b/src/app/(app)/jobs/[id]/job-live.tsx @@ -10,6 +10,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { useLive } from "@/hooks/use-live"; import { formatDuration } from "@/lib/format"; import { LocalTime } from "@/components/local-time"; +import { jobLabel } from "@/lib/job-labels"; import type { JobSnapshot } from "@/lib/jobs"; const OPEN = ["queued", "downloading", "verifying"]; @@ -40,7 +41,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {

- {job.kind === "download" ? "Download" : job.kind} ·{" "} + {jobLabel(job)} ·{" "} {job.repoId} diff --git a/src/app/(app)/library-view.tsx b/src/app/(app)/library-view.tsx index b5a8f49..25c94d6 100644 --- a/src/app/(app)/library-view.tsx +++ b/src/app/(app)/library-view.tsx @@ -56,7 +56,12 @@ function toSearchable(r: LibraryRow): SearchableModel { pipelineTag: r.pipelineTag, license: r.license, status: r.status, - hubStatus: r.hubState && r.hubState !== "available" ? HUB_STATE_LABEL[r.hubState].label : null, + hubStatus: + r.hubState && r.hubState !== "available" + ? HUB_STATE_LABEL[r.hubState].label + : r.updateAvailable + ? "update available" + : null, }; } @@ -223,6 +228,11 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) { + {r.updateAvailable && (r.hubState === "available" || !r.hubState) && ( + + update available + + )} )} diff --git a/src/app/api/models/[id]/hub-check/route.ts b/src/app/api/models/[id]/hub-check/route.ts index 0f8c5b9..a433190 100644 --- a/src/app/api/models/[id]/hub-check/route.ts +++ b/src/app/api/models/[id]/hub-check/route.ts @@ -1,12 +1,12 @@ import { NextResponse } from "next/server"; import { withAuth } from "@/lib/api-auth"; import { apiError } from "@/lib/api-errors"; -import { checkHubAvailability, getCheckedModel } from "@/lib/hub/availability"; +import { checkHub, getCheckedModel } from "@/lib/hub/availability"; /** Check right now whether the repo and pinned commit are still on the Hub. */ export const POST = withAuth>(async (_req, { params }) => { const { id } = await params; const model = await getCheckedModel(id); if (!model) return apiError(404, "not_found", "Model not found."); - return NextResponse.json(await checkHubAvailability(model)); + return NextResponse.json(await checkHub(model)); }); diff --git a/src/app/api/models/[id]/repair/route.ts b/src/app/api/models/[id]/repair/route.ts new file mode 100644 index 0000000..5108e4e --- /dev/null +++ b/src/app/api/models/[id]/repair/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { apiError } from "@/lib/api-errors"; +import { JobError, queueDownload } from "@/lib/jobs"; + +/** Download again what's missing or broken (the worker deletes broken files first). */ +export const POST = withAuth>(async (_req, { params }) => { + const { id } = await params; + try { + return NextResponse.json(await queueDownload(id, "repair"), { status: 201 }); + } catch (err) { + if (err instanceof JobError) return apiError(err.status, err.code, err.message); + throw err; + } +}); diff --git a/src/app/api/models/[id]/route.ts b/src/app/api/models/[id]/route.ts index aadfe53..7314ce4 100644 --- a/src/app/api/models/[id]/route.ts +++ b/src/app/api/models/[id]/route.ts @@ -1,13 +1,15 @@ import { NextResponse } from "next/server"; import { withAuth } from "@/lib/api-auth"; import { apiError } from "@/lib/api-errors"; -import { ModelError, removeModel } from "@/lib/models"; +import { deleteModel, ModelError } from "@/lib/models"; -export const DELETE = withAuth>(async (_req, { params }) => { +/** Delete a model; `?files=1` also deletes its files from disk (queued for the worker). */ +export const DELETE = withAuth>(async (req, { params }) => { const { id } = await params; try { - await removeModel(id); - return new NextResponse(null, { status: 204 }); + const deleteFiles = new URL(req.url).searchParams.get("files") === "1"; + const { queued } = await deleteModel(id, { deleteFiles }); + return queued ? NextResponse.json({ queued }, { status: 202 }) : new NextResponse(null, { status: 204 }); } catch (err) { if (err instanceof ModelError) return apiError(err.status, err.code, err.message); throw err; diff --git a/src/app/api/models/[id]/update/route.ts b/src/app/api/models/[id]/update/route.ts new file mode 100644 index 0000000..cc7461f --- /dev/null +++ b/src/app/api/models/[id]/update/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { apiError, handleApiError } from "@/lib/api-errors"; +import { applyUpdate, ModelError } from "@/lib/models"; + +/** Update to the newer commit found by the last Hub check (deliberate, never automatic). */ +export const POST = withAuth>(async (_req, { params }) => { + const { id } = await params; + try { + return NextResponse.json(await applyUpdate(id), { status: 201 }); + } catch (err) { + if (err instanceof ModelError) return apiError(err.status, err.code, err.message); + return handleApiError(err); + } +}); diff --git a/src/app/api/models/[id]/verify/route.ts b/src/app/api/models/[id]/verify/route.ts new file mode 100644 index 0000000..2024a15 --- /dev/null +++ b/src/app/api/models/[id]/verify/route.ts @@ -0,0 +1,16 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { apiError } from "@/lib/api-errors"; +import { JobError, queueVerify } from "@/lib/jobs"; + +/** Queue a verify (`?deep=1`: hash every file) of the model's selected files. */ +export const POST = withAuth>(async (req, { params }) => { + const { id } = await params; + try { + const deep = new URL(req.url).searchParams.get("deep") === "1"; + return NextResponse.json(await queueVerify(id, deep), { status: 201 }); + } catch (err) { + if (err instanceof JobError) return apiError(err.status, err.code, err.message); + throw err; + } +}); diff --git a/src/components/job-actions.ts b/src/components/job-actions.ts index f6d54eb..4169c06 100644 --- a/src/components/job-actions.ts +++ b/src/components/job-actions.ts @@ -17,3 +17,17 @@ export async function startDownload(modelId: string) { export async function cancelJob(jobId: string) { if (await post(`/api/jobs/${jobId}/cancel`)) toast.info("Cancelling…"); } + +export async function startVerify(modelId: string, deep: boolean) { + if (await post(`/api/models/${modelId}/verify${deep ? "?deep=1" : ""}`)) toast.success(deep ? "Deep verify queued" : "Verify queued"); +} + +export async function startRepair(modelId: string) { + if (await post(`/api/models/${modelId}/repair`)) toast.success("Repair queued"); +} + +export async function startUpdate(modelId: string): Promise { + const ok = await post(`/api/models/${modelId}/update`); + if (ok) toast.success("Update queued"); + return ok; +} diff --git a/src/components/verify-result.tsx b/src/components/verify-result.tsx new file mode 100644 index 0000000..0b2584c --- /dev/null +++ b/src/components/verify-result.tsx @@ -0,0 +1,52 @@ +import { CircleAlertIcon, CircleCheckIcon } from "lucide-react"; +import type { JobResult } from "@/lib/db/schema"; +import { formatBytes } from "@/lib/format"; +import { cn } from "@/lib/utils"; + +function PathList({ title, paths, tone }: { title: string; paths: string[]; tone: "bad" | "muted" }) { + if (paths.length === 0) return null; + return ( +
+ + {title} ({paths.length}) + +
    + {paths.slice(0, 50).map((p) => ( +
  • {p}
  • + ))} + {paths.length > 50 &&
  • … {paths.length - 50} more
  • } +
+
+ ); +} + +/** Outcome of a (deep) verify: problems per kind, plus extra files in the folder. */ +export function VerifyResult({ result, deep }: { result: JobResult; deep: boolean }) { + const missing = result.missing ?? []; + const sizeMismatch = result.sizeMismatch ?? []; + const hashMismatch = result.hashMismatch ?? []; + const extra = result.extra ?? []; + const problems = missing.length + sizeMismatch.length + hashMismatch.length; + const extraBytes = extra.reduce((s, e) => s + e.size, 0); + + return ( +
+

0 ? "text-destructive" : "text-emerald-700 dark:text-emerald-400")}> + {problems > 0 ? : } + {problems > 0 + ? `${problems} of ${result.checked ?? 0} files need repair` + : `All ${result.checked ?? 0} files OK${deep ? ", hashes match the Hub" : ""}`} +

+ + + + {extra.length > 0 && ( + (e.inRepo ? `${e.path} (repo file, not selected)` : e.path))} + tone="muted" + /> + )} +
+ ); +} diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index 18e24ac..53b6884 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -50,6 +50,30 @@ export type ModelStatus = (typeof MODEL_STATUSES)[number]; export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const; export type HubState = (typeof HUB_STATES)[number]; +export type UpdateDiffFile = { path: string; size: number; oldSize?: number }; +export type UpdateDiff = { + /** Commit the diff was computed against (the tracked revision's head on the Hub). */ + sha: string; + changed: UpdateDiffFile[]; + added: UpdateDiffFile[]; + removed: UpdateDiffFile[]; + checkedAt: string; +}; + +/** Outcome of a verify job, or extra instructions for a job (`removePaths` after an update). */ +export type JobResult = { + checked?: number; + missing?: string[]; + sizeMismatch?: string[]; + hashMismatch?: string[]; + /** Files in the model folder that aren't selected repo files. */ + extra?: { path: string; size: number; inRepo: boolean }[]; + /** Update jobs: files of the old revision to delete once the download succeeded. */ + removePaths?: string[]; + /** Delete jobs: files that were kept because they don't belong to the repo. */ + kept?: string[]; +}; + export const models = sqliteTable( "models", { @@ -81,6 +105,8 @@ export const models = sqliteTable( hubState: text("hub_state", { enum: HUB_STATES }), /** When the repo or pinned commit was first seen missing; cleared when it's back. */ hubMissingSince: ts("hub_missing_since"), + /** What updating to `remoteSha` would change in the selection; null when up to date. */ + updateDiff: text("update_diff", { mode: "json" }).$type(), lastVerifiedAt: ts("last_verified_at"), downloadedAt: ts("downloaded_at"), // Hub metadata (for search/filters), refreshed by the worker. Null until fetched. @@ -190,7 +216,7 @@ export const modelFiles = sqliteTable( // Jobs (executed by the worker) // --------------------------------------------------------------------------- -export const JOB_KINDS = ["download", "verify", "deep_verify"] as const; +export const JOB_KINDS = ["download", "verify", "deep_verify", "delete"] as const; export type JobKind = (typeof JOB_KINDS)[number]; export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as const; @@ -239,6 +265,7 @@ export const jobs = sqliteTable( exitCode: integer("exit_code"), errorCode: text("error_code", { enum: JOB_ERROR_CODES }), errorMessage: text("error_message"), + result: text("result", { mode: "json" }).$type(), /** Set by the web app; the worker picks it up and stops the job. */ cancelRequestedAt: ts("cancel_requested_at"), startedAt: ts("started_at"), diff --git a/src/lib/hub/availability.ts b/src/lib/hub/availability.ts index 4181662..8473f96 100644 --- a/src/lib/hub/availability.ts +++ b/src/lib/hub/availability.ts @@ -1,9 +1,28 @@ -import { asc, eq, isNull, lt, or } from "drizzle-orm"; -import { db } from "@/lib/db/client"; -import { models, type HubState } from "@/lib/db/schema"; -import { getRepoInfo, HubError } from "./client"; +// Hub checks per model: is the repo (and the pinned commit) still there, and is there a newer +// commit on the tracked revision? Run periodically by the worker and on "Check now". Results are +// stored on the model; nothing local is ever changed by a check. -type CheckedModel = Pick; +import { and, asc, eq, isNull, lt, or } from "drizzle-orm"; +import { db } from "@/lib/db/client"; +import { type HubState, modelFiles, models, type UpdateDiff } from "@/lib/db/schema"; +import { computeUpdateDiff } from "@/lib/update-diff"; +import { getRepoInfo, HubError, listFiles, SHA_RE } from "./client"; + +type CheckedModel = Pick< + typeof models.$inferSelect, + "id" | "repoId" | "pinnedSha" | "trackedRevision" | "hubMissingSince" | "updateDiff" | "includePatterns" | "excludePatterns" +>; + +const CHECKED_COLUMNS = { + id: models.id, + repoId: models.repoId, + pinnedSha: models.pinnedSha, + trackedRevision: models.trackedRevision, + hubMissingSince: models.hubMissingSince, + updateDiff: models.updateDiff, + includePatterns: models.includePatterns, + excludePatterns: models.excludePatterns, +}; /** Why new downloads are impossible, or null if the Hub still has the repo at the pinned commit. */ export function hubMissingMessage(model: { repoId: string; hubState: HubState | null }): string | null { @@ -16,25 +35,73 @@ export function hubMissingMessage(model: { repoId: string; hubState: HubState | return null; } -export type HubCheckResult = { state: HubState } | { state: null; error: string }; +export type HubCheckResult = + | { state: HubState; remoteSha: string | null; update: UpdateDiff | null; warning: string | null } + | { state: null; error: string }; + +const message = (err: unknown) => (err instanceof Error ? err.message : String(err)); +const isGated = (err: unknown) => err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access"); + +/** Resolve a revision to its commit; null if the Hub says the revision doesn't exist. */ +async function resolve(repoId: string, revision: string): Promise { + try { + return (await getRepoInfo(repoId, revision)).sha; + } catch (err) { + if (err instanceof HubError && err.code === "revision_not_found") return null; + throw err; + } +} + +async function run(model: CheckedModel): Promise { + // 1. Head of the tracked revision (a full SHA as revision means "pinned for good"). + let remoteSha: string | null; + let warning: string | null = null; + if (SHA_RE.test(model.trackedRevision)) { + remoteSha = model.trackedRevision; + } else { + remoteSha = await resolve(model.repoId, model.trackedRevision); + if (!remoteSha) warning = `Revision "${model.trackedRevision}" no longer exists on the Hub; can't check for updates.`; + } + + // 2. Is the pinned commit still there? (Known if it's the head.) + const pinnedExists = remoteSha === model.pinnedSha || (await resolve(model.repoId, model.pinnedSha)) !== null; + const state: HubState = pinnedExists ? "available" : "commit_missing"; + + // 3. Newer commit: what would change in the selection? Only recomputed when the head moved. + let update: UpdateDiff | null = null; + if (remoteSha && remoteSha !== model.pinnedSha) { + update = model.updateDiff?.sha === remoteSha ? model.updateDiff : null; + if (!update) { + const [next, current] = await Promise.all([ + listFiles(model.repoId, remoteSha), + db() + .select({ path: modelFiles.path, size: modelFiles.size, blobOid: modelFiles.blobOid, lfsSha256: modelFiles.lfsSha256 }) + .from(modelFiles) + .where(and(eq(modelFiles.modelId, model.id), eq(modelFiles.selected, true))), + ]); + update = computeUpdateDiff(remoteSha, current, next, { include: model.includePatterns, exclude: model.excludePatterns }); + } + } + return { state, remoteSha, update, warning }; +} /** - * Is the repo, and the pinned commit, still on the Hub? Stores the result on the model. Only a - * definite answer changes `hubState`; network errors, rate limits or a bad token are kept as - * `lastCheckError`. Never touches local files. + * Check one model against the Hub and store the result. Only a definite answer changes the stored + * state; network errors, rate limits or a bad token are kept as `lastCheckError`. */ -export async function checkHubAvailability(model: CheckedModel): Promise { +export async function checkHub(model: CheckedModel): Promise { let result: HubCheckResult; try { - await getRepoInfo(model.repoId, model.pinnedSha); - result = { state: "available" }; + result = await run(model); } catch (err) { - if (err instanceof HubError && err.code === "repo_not_found") result = { state: "repo_missing" }; - else if (err instanceof HubError && err.code === "revision_not_found") result = { state: "commit_missing" }; - // Gated repos exist; access is a download concern, not availability. - else if (err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access")) { - result = { state: "available" }; - } else result = { state: null, error: err instanceof Error ? err.message : String(err) }; + if (err instanceof HubError && err.code === "repo_not_found") { + result = { state: "repo_missing", remoteSha: null, update: null, warning: null }; + } else if (isGated(err)) { + // Gated repos exist; access is a download concern. + result = { state: "available", remoteSha: null, update: model.updateDiff ?? null, warning: message(err) }; + } else { + result = { state: null, error: message(err) }; + } } const now = new Date(); @@ -45,9 +112,10 @@ export async function checkHubAvailability(model: CheckedModel): Promise { const cutoff = new Date(Date.now() - intervalMs); return db() - .select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha, hubMissingSince: models.hubMissingSince }) + .select(CHECKED_COLUMNS) .from(models) .where(or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff))) .orderBy(asc(models.lastCheckedAt)) @@ -66,8 +134,6 @@ export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Prom } export async function getCheckedModel(id: string): Promise { - return db().query.models.findFirst({ - columns: { id: true, repoId: true, pinnedSha: true, hubMissingSince: true }, - where: eq(models.id, id), - }); + const [row] = await db().select(CHECKED_COLUMNS).from(models).where(eq(models.id, id)); + return row; } diff --git a/src/lib/job-labels.ts b/src/lib/job-labels.ts new file mode 100644 index 0000000..ff7ef8c --- /dev/null +++ b/src/lib/job-labels.ts @@ -0,0 +1,16 @@ +// Human-readable job names (shared by UI components). + +const DOWNLOAD_PURPOSE: Record = { + initial: "Download", + add: "Download more", + import: "Import", + repair: "Repair", + update: "Update", +}; + +const KIND: Record = { download: "Download", verify: "Verify", deep_verify: "Deep verify", delete: "Delete" }; + +export function jobLabel(job: { kind: string; purpose: string | null }): string { + if (job.kind === "download") return DOWNLOAD_PURPOSE[job.purpose ?? "initial"] ?? "Download"; + return KIND[job.kind] ?? job.kind; +} diff --git a/src/lib/jobs.ts b/src/lib/jobs.ts index 5cb4f13..8a8e41d 100644 --- a/src/lib/jobs.ts +++ b/src/lib/jobs.ts @@ -6,6 +6,7 @@ import { hubMissingMessage } from "@/lib/hub/availability"; import { ACTIVE_JOB_STATES, type JobPurpose, + type JobResult, jobFiles, jobLogs, jobs, @@ -26,19 +27,31 @@ export class JobError extends Error { const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const; const INSERT_CHUNK = 500; -/** Queue a download of all selected files of a model at its pinned SHA. */ -export async function queueDownload(modelId: string, purpose: JobPurpose = "initial"): Promise<{ jobId: string }> { +/** True if the model has a queued or running job (only one job per model at a time). */ +export async function hasOpenJob(modelId: string): Promise { + const open = await db().query.jobs.findFirst({ + columns: { id: true }, + where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])), + }); + return !!open; +} + +/** + * Queue a download of all selected files of a model at its pinned SHA. hf skips files that are + * already complete, so this also serves as resume and repair. `removePaths`: files of an older + * revision to delete once the download succeeded (updates). + */ +export async function queueDownload( + modelId: string, + purpose: JobPurpose = "initial", + options: { removePaths?: string[] } = {}, +): Promise<{ jobId: string }> { const d = db(); const model = await d.query.models.findFirst({ where: eq(models.id, modelId) }); if (!model) throw new JobError("not_found", "Model not found.", 404); const missing = hubMissingMessage(model); if (missing) throw new JobError("hub_missing", missing, 409); - - const open = await d.query.jobs.findFirst({ - columns: { id: true }, - where: and(eq(jobs.modelId, modelId), inArray(jobs.state, [...OPEN_STATES])), - }); - if (open) throw new JobError("busy", "This model already has a queued or running job.", 409); + if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409); const files = await d .select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size }) @@ -57,6 +70,7 @@ export async function queueDownload(modelId: string, purpose: JobPurpose = "init purpose, targetSha: model.pinnedSha, totalBytes: files.reduce((s, f) => s + f.size, 0), + result: options.removePaths?.length ? { removePaths: options.removePaths } : null, }), ...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)), d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)), @@ -64,6 +78,36 @@ export async function queueDownload(modelId: string, purpose: JobPurpose = "init return { jobId }; } +/** Queue a verify (size + hf metadata) or deep verify (hashes) of the selected files. Local only. */ +export async function queueVerify(modelId: string, deep: boolean): Promise<{ jobId: string }> { + const d = db(); + const model = await d.query.models.findFirst({ where: eq(models.id, modelId) }); + if (!model) throw new JobError("not_found", "Model not found.", 404); + if (await hasOpenJob(modelId)) throw new JobError("busy", "This model already has a queued or running job.", 409); + const files = await d + .select({ id: modelFiles.id, path: modelFiles.path, size: modelFiles.size }) + .from(modelFiles) + .where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true))) + .orderBy(asc(modelFiles.path)); + if (files.length === 0) throw new JobError("nothing_selected", "No files selected for this model.", 400); + + const jobId = ulid(); + await d.batch([ + d.insert(jobs).values({ + id: jobId, + modelId, + kind: deep ? "deep_verify" : "verify", + targetSha: model.pinnedSha, + totalBytes: files.reduce((s, f) => s + f.size, 0), + }), + ...chunk( + files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size })), + INSERT_CHUNK, + ).map((c) => d.insert(jobFiles).values(c)), + ]); + return { jobId }; +} + /** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */ export async function requestCancel(jobId: string): Promise { const res = await db() @@ -97,6 +141,7 @@ export type JobSnapshot = { exitCode: number | null; errorCode: string | null; errorMessage: string | null; + result: JobResult | null; cancelRequested: boolean; createdAt: number; startedAt: number | null; @@ -128,6 +173,7 @@ const jobColumns = { exitCode: jobs.exitCode, errorCode: jobs.errorCode, errorMessage: jobs.errorMessage, + result: jobs.result, cancelRequestedAt: jobs.cancelRequestedAt, createdAt: jobs.createdAt, startedAt: jobs.startedAt, diff --git a/src/lib/library.ts b/src/lib/library.ts index 55974a7..b7b2c08 100644 --- a/src/lib/library.ts +++ b/src/lib/library.ts @@ -21,6 +21,7 @@ export async function listLibrary() { remoteSha: models.remoteSha, status: models.status, hubState: models.hubState, + updateDiff: models.updateDiff, createdAt: models.createdAt, downloadedAt: models.downloadedAt, baseModels: models.baseModels, @@ -51,8 +52,9 @@ export async function listLibrary() { const tagsByModel = new Map(); for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]); - return rows.map((r) => ({ + return rows.map(({ updateDiff, ...r }) => ({ ...r, + updateAvailable: !!updateDiff && updateDiff.sha === r.remoteSha && r.remoteSha !== r.pinnedSha, author: r.repoId.split("/")[0], families: modelFamilies(r.repoId, r.baseModels), baseModels: r.baseModels ?? [], diff --git a/src/lib/model-purge.ts b/src/lib/model-purge.ts new file mode 100644 index 0000000..d6d369b --- /dev/null +++ b/src/lib/model-purge.ts @@ -0,0 +1,20 @@ +// Remove a model and everything that references it from the database (not its files). +// Shared by the web app and the worker, so no "server-only" import here. + +import { eq, inArray } from "drizzle-orm"; +import { db } from "@/lib/db/client"; +import { jobFiles, jobLogs, jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema"; + +export async function purgeModelRows(modelId: string): Promise { + const d = db(); + const jobIds = d.select({ id: jobs.id }).from(jobs).where(eq(jobs.modelId, modelId)); + await d.batch([ + d.delete(jobLogs).where(inArray(jobLogs.jobId, jobIds)), + d.delete(jobFiles).where(inArray(jobFiles.jobId, jobIds)), + d.delete(jobs).where(eq(jobs.modelId, modelId)), + d.delete(modelTags).where(eq(modelTags.modelId, modelId)), + d.delete(modelFiles).where(eq(modelFiles.modelId, modelId)), + d.delete(modelRevisions).where(eq(modelRevisions.modelId, modelId)), + d.delete(models).where(eq(models.id, modelId)), + ]); +} diff --git a/src/lib/models.ts b/src/lib/models.ts index 2ab7967..14ce754 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -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 { +/** + * 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`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`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(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)), ), diff --git a/src/lib/update-diff.test.ts b/src/lib/update-diff.test.ts new file mode 100644 index 0000000..055c0d8 --- /dev/null +++ b/src/lib/update-diff.test.ts @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { computeUpdateDiff, diffHasChanges } from "./update-diff"; + +const f = (path: string, oid: string, size = 10, lfs = true) => ({ + path, + size, + blobOid: `blob-${oid}`, + lfsSha256: lfs ? `sha-${oid}` : null, +}); + +describe("computeUpdateDiff", () => { + const current = [f("Q4_K_M.gguf", "a"), f("mmproj-F16.gguf", "b"), f("config.json", "c", 1, false)]; + const rule = { include: ["Q4_K_M.gguf", "mmproj-F16.gguf", "*.json"], exclude: [] }; + + it("finds changed, added and removed selected files", () => { + const next = [ + f("Q4_K_M.gguf", "a2", 12), // re-quantized + f("config.json", "c", 1, false), // unchanged + f("generation_config.json", "d", 1, false), // new, matches *.json + f("Q8_0.gguf", "e"), // new, not selected + ]; + const d = computeUpdateDiff("new", current, next, rule, new Date(0)); + assert.deepEqual(d.changed, [{ path: "Q4_K_M.gguf", size: 12, oldSize: 10 }]); + assert.deepEqual(d.added, [{ path: "generation_config.json", size: 1 }]); + assert.deepEqual(d.removed, [{ path: "mmproj-F16.gguf", size: 10 }]); + assert.ok(diffHasChanges(d)); + }); + + it("reports nothing when the selected files are identical", () => { + const d = computeUpdateDiff("new", current, [...current, f("README.md", "r", 1, false)], rule); + assert.ok(!diffHasChanges(d)); + }); +}); diff --git a/src/lib/update-diff.ts b/src/lib/update-diff.ts new file mode 100644 index 0000000..0559ad5 --- /dev/null +++ b/src/lib/update-diff.ts @@ -0,0 +1,34 @@ +// What updating a model to a newer commit would change in its selection. Pure; used by the worker +// (update checks) and the web app (applying an update). + +import type { UpdateDiff, UpdateDiffFile } from "@/lib/db/schema"; +import { isSelected, type SelectionRule } from "@/lib/selection"; + +type RepoFile = { path: string; size: number; blobOid: string | null; lfsSha256: string | null }; + +/** Content identity of a file: the LFS SHA-256, else the git blob SHA-1. */ +export const contentId = (f: { blobOid: string | null; lfsSha256: string | null }) => f.lfsSha256 ?? f.blobOid ?? ""; + +/** + * Compare the currently selected files with the files the same selection rule picks at the new + * commit: changed content, newly matching files, and selected files that are gone. + */ +export function computeUpdateDiff(sha: string, current: RepoFile[], next: RepoFile[], rule: SelectionRule, now = new Date()): UpdateDiff { + const before = new Map(current.map((f) => [f.path, f])); + const after = new Map(next.filter((f) => isSelected(f.path, rule)).map((f) => [f.path, f])); + const changed: UpdateDiffFile[] = []; + const added: UpdateDiffFile[] = []; + const removed: UpdateDiffFile[] = []; + for (const [path, f] of after) { + const old = before.get(path); + if (!old) added.push({ path, size: f.size }); + else if (contentId(old) !== contentId(f)) changed.push({ path, size: f.size, oldSize: old.size }); + } + for (const [path, f] of before) if (!after.has(path)) removed.push({ path, size: f.size }); + const byPath = (a: UpdateDiffFile, b: UpdateDiffFile) => a.path.localeCompare(b.path); + return { sha, changed: changed.sort(byPath), added: added.sort(byPath), removed: removed.sort(byPath), checkedAt: now.toISOString() }; +} + +/** True if updating would change anything in the selection. */ +export const diffHasChanges = (d: UpdateDiff | null | undefined) => + !!d && d.changed.length + d.added.length + d.removed.length > 0; diff --git a/src/worker/delete.ts b/src/worker/delete.ts new file mode 100644 index 0000000..460ba15 --- /dev/null +++ b/src/worker/delete.ts @@ -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 { + 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 { + 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); + } + } +} diff --git a/src/worker/download.ts b/src/worker/download.ts index 6f98b1f..0b83735 100644 --- a/src/worker/download.ts +++ b/src/worker/download.ts @@ -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" }; } diff --git a/src/worker/hf-layout.ts b/src/worker/hf-layout.ts index fca03b3..20ff466 100644 --- a/src/worker/hf-layout.ts +++ b/src/worker/hf-layout.ts @@ -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 { + 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)); +} diff --git a/src/worker/index.ts b/src/worker/index.ts index 64b50f7..49fb1d9 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -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(); +const runners = new Map(); 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>) { +function reportHubCheck(model: { repoId: string }, result: Awaited>) { 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); } diff --git a/src/worker/runner.ts b/src/worker/runner.ts new file mode 100644 index 0000000..ac5aa43 --- /dev/null +++ b/src/worker/runner.ts @@ -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; +} diff --git a/src/worker/verify.ts b/src/worker/verify.ts new file mode 100644 index 0000000..8da8236 --- /dev/null +++ b/src/worker/verify.ts @@ -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, + ) { + 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 { + const deep = this.job.kind === "deep_verify"; + const dir = modelDir(coreEnv().MODELS_DIR, this.model.localPath); + const result: Required> = { + 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): Promise { + 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): Promise { + 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]))), + ]); + } +}