Import models that are already in the models folder
The worker scans MODELS_DIR (startup, every 2 min, on "Rescan") for <org>/<name> folders that no model uses and stores them in local_folders. The library lists them; Import opens Add model prefilled with the folder, the commit hf recorded and the files on disk preselected. The import job runs hf download into the existing folder: hf 2.1.1 hashes files it didn't download itself, keeps matching ones and re-downloads the rest (verified in Docker, including a corrupted file being replaced). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3603742637
commit
145818f149
16 files changed
+1418
-25
No files matched your search
@@ -147,7 +147,11 @@ export class DownloadRunner {
|
||||
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;
|
||||
if (doneCount > 0) this.jobLog.system(`${doneCount} file(s) already complete, hf will skip them.`);
|
||||
if (doneCount > 0) {
|
||||
this.jobLog.system(
|
||||
`${doneCount} file(s) already on disk with the right size. hf skips the ones it downloaded itself and checks the others by hash (slow for large files), downloading them again if they differ.`,
|
||||
);
|
||||
}
|
||||
|
||||
const free = await freeBytes(dir);
|
||||
if (free != null && remaining > free) {
|
||||
|
||||
+24
-1
@@ -13,6 +13,7 @@ import { checkHubAvailability, modelsDueForHubCheck } from "@/lib/hub/availabili
|
||||
import { backfillMetadata } from "@/lib/hub/refresh";
|
||||
import { DownloadRunner } from "./download";
|
||||
import { log } from "./log";
|
||||
import { scanModelsDir } from "./scan";
|
||||
import { settleModelStatus } from "./model-status";
|
||||
|
||||
const HEARTBEAT_MS = 5_000;
|
||||
@@ -22,6 +23,8 @@ const LEASE_STALE_MS = 20_000;
|
||||
const SHUTDOWN_GRACE_MS = 8_000;
|
||||
/** How often to look for models whose Hub check is due (the check interval itself is configurable). */
|
||||
const HUB_CHECK_SCAN_MS = 10 * 60_000;
|
||||
/** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */
|
||||
const FOLDER_SCAN_MS = 2 * 60_000;
|
||||
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
|
||||
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
|
||||
|
||||
@@ -103,12 +106,14 @@ async function heartbeat() {
|
||||
.update(workerState)
|
||||
.set(values)
|
||||
.where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)))
|
||||
.returning({ id: workerState.id });
|
||||
.returning({ id: workerState.id, scanRequestedAt: workerState.scanRequestedAt });
|
||||
if (kept.length === 0) {
|
||||
log.error("lost the worker lease to another process; exiting");
|
||||
await shutdown("lease lost", 1);
|
||||
return;
|
||||
}
|
||||
const requested = kept[0].scanRequestedAt;
|
||||
if (requested && requested.getTime() > lastScanStartedAt) void scanFolders();
|
||||
await writeFile(HEALTH_FILE, String(Date.now())).catch(() => {});
|
||||
}
|
||||
|
||||
@@ -229,6 +234,22 @@ function reportHubCheck(model: { repoId: string }, result: Awaited<ReturnType<ty
|
||||
else if (result.state !== "available") log.warn(`${model.repoId}: ${result.state.replace("_", " ")} on the Hub (local files kept)`);
|
||||
}
|
||||
|
||||
let scanning = false;
|
||||
let lastScanStartedAt = 0;
|
||||
async function scanFolders() {
|
||||
if (scanning || stopping) return;
|
||||
scanning = true;
|
||||
lastScanStartedAt = Date.now();
|
||||
try {
|
||||
const n = await scanModelsDir(coreEnv().MODELS_DIR);
|
||||
if (n > 0) log.info(`found ${n} folder(s) in the models dir that aren't in the library`);
|
||||
} catch (err) {
|
||||
log.error("models dir scan failed", err);
|
||||
} finally {
|
||||
scanning = false;
|
||||
}
|
||||
}
|
||||
|
||||
let checkingHub = false;
|
||||
async function checkHubDue() {
|
||||
const hours = coreEnv().UPDATE_CHECK_INTERVAL_HOURS;
|
||||
@@ -314,6 +335,8 @@ async function main() {
|
||||
timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS));
|
||||
timers.push(setInterval(() => void tick(), TICK_MS));
|
||||
timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS));
|
||||
timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS));
|
||||
void scanFolders();
|
||||
void tick();
|
||||
setTimeout(() => void checkHubDue(), 15_000);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// Finds model folders in MODELS_DIR that aren't in the library, so they can be imported.
|
||||
// Only the `<org>/<name>` layout is recognized (what Kaname and `hf download --local-dir` write).
|
||||
// Read-only: nothing on disk is changed.
|
||||
|
||||
import { readdir, readFile, stat } from "node:fs/promises";
|
||||
import { join, relative, sep } from "node:path";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { localFolders, models } from "@/lib/db/schema";
|
||||
import { HF_CACHE_DIR } from "./hf-layout";
|
||||
|
||||
/** Stop listing a folder's files after this many (the count stays exact). */
|
||||
const MAX_LISTED_FILES = 5_000;
|
||||
const SKIP_DIRS = new Set([".cache", ".git"]);
|
||||
|
||||
type FoundFolder = typeof localFolders.$inferInsert;
|
||||
|
||||
async function subdirs(dir: string): Promise<string[]> {
|
||||
try {
|
||||
const entries = await readdir(dir, { withFileTypes: true });
|
||||
return entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function walk(root: string, dir: string, out: { path: string; size: number }[], totals: { count: number; bytes: number }) {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const e of entries) {
|
||||
const full = join(dir, e.name);
|
||||
if (e.isDirectory()) {
|
||||
if (!SKIP_DIRS.has(e.name)) await walk(root, full, out, totals);
|
||||
} else if (e.isFile() && !e.name.endsWith(".incomplete")) {
|
||||
const size = (await stat(full).catch(() => null))?.size ?? 0;
|
||||
totals.count++;
|
||||
totals.bytes += size;
|
||||
if (out.length < MAX_LISTED_FILES) out.push({ path: relative(root, full).split(sep).join("/"), size });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The commit hf recorded for the first file it downloaded into this folder, if any. */
|
||||
async function hfCommit(folder: string): Promise<string | null> {
|
||||
const stack = [join(folder, HF_CACHE_DIR, "download")];
|
||||
while (stack.length > 0) {
|
||||
const dir = stack.pop()!;
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const e of entries) {
|
||||
if (e.isDirectory()) stack.push(join(dir, e.name));
|
||||
else if (e.name.endsWith(".metadata")) {
|
||||
const first = (await readFile(join(dir, e.name), "utf8").catch(() => "")).split("\n")[0].trim();
|
||||
if (/^[0-9a-f]{40}$/.test(first)) return first;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Scan MODELS_DIR and replace the `local_folders` table with folders no model uses. */
|
||||
export async function scanModelsDir(modelsDir: string): Promise<number> {
|
||||
const used = new Set((await db().select({ p: models.localPath }).from(models)).map((m) => m.p));
|
||||
const found: FoundFolder[] = [];
|
||||
const now = new Date();
|
||||
for (const org of await subdirs(modelsDir)) {
|
||||
for (const name of await subdirs(join(modelsDir, org))) {
|
||||
const path = `${org}/${name}`;
|
||||
if (used.has(path)) continue;
|
||||
const folder = join(modelsDir, org, name);
|
||||
const files: { path: string; size: number }[] = [];
|
||||
const totals = { count: 0, bytes: 0 };
|
||||
await walk(folder, folder, files, totals);
|
||||
if (totals.count === 0) continue;
|
||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
found.push({ path, files, fileCount: totals.count, totalBytes: totals.bytes, commit: await hfCommit(folder), scannedAt: now });
|
||||
}
|
||||
}
|
||||
const d = db();
|
||||
await d.batch([d.delete(localFolders), ...found.map((f) => d.insert(localFolders).values(f))]);
|
||||
return found.length;
|
||||
}
|
||||
Reference in new issue
Block a user