Worker: write only what changed, sample downloads less

- The models folder scan compared nothing and rewrote local_folders on every
  run (delete all, insert all, each folder's file list included), every 2
  minutes by default: ~1 MB of SQLite writes per scan with three large import
  folders. It now inserts new folders, updates changed ones and deletes gone
  ones; unchanged rows (compared by counts, commit and the stored JSON text)
  aren't written.
- Download progress and the speed limit share one ProgressSampler. A file found
  complete isn't stat'ed or its hf metadata re-read again during the run, and
  with every file complete the partial files aren't listed. Before, every
  sample looked at every file, 5 times a second with a speed limit set. The
  check after hf exits still looks at every file.
- A benchmark's phase is written when its step changes, not for every
  progress line BetterBench prints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
This commit is contained in:
Claude committed 2026-11-01 21:01:11 +00:00
1 parent d10a491042
commit d58bff3437
8 files changed
+260 -8

No files matched your search

+4
View File
@@ -26,6 +26,10 @@ step 1 (Hugging Face downloader) is released as a minor version.
loaded once and cached instead of being part of each page, the ⌘K search loads when you first
reach for it, and the endpoint pages no longer include database code. The painting is drawn once
per page view instead of twice, and at most once per frame while the window is resized.
- **Less disk activity**: the models folder scan writes only folders that changed (it rewrote
every found folder's file list each time, every 2 minutes by default), and download progress
no longer re-checks files that are already complete, which matters on network shares. A
benchmark's current step is written when it changes, not for every line BetterBench prints.
## [0.16.0] - 2026-10-30
+2 -1
View File
@@ -316,7 +316,7 @@ export type PcieLink = { gen: number | null; width: number | null };
/**
* Folders in MODELS_DIR (`<org>/<name>`, like `hf download --local-dir` layouts) that no model uses,
* found by the worker's scan. Rewritten on every scan; the web app offers them for import.
* found by the worker's scan, which writes only what changed; the web app offers them for import.
*/
export const localFolders = sqliteTable("local_folders", {
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-8B-GGUF". */
@@ -327,6 +327,7 @@ export const localFolders = sqliteTable("local_folders", {
totalBytes: integer("total_bytes").notNull(),
/** Commit from hf's download metadata, if the folder was written by `hf download`. */
commit: text("commit"),
/** When a scan last wrote this folder (found it, or found it changed). */
scannedAt: ts("scanned_at").notNull(),
});
+7 -1
View File
@@ -63,6 +63,8 @@ let starting = false;
const pending: { runId: string; stream: LogStream; line: string; ts: Date }[] = [];
const partial = new Map<string, string>();
const tails = new Map<string, string[]>();
/** The step last written to a run's `phase`: progress lines repeat it, a write per line isn't needed. */
const steps = new Map<string, string>();
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
@@ -84,7 +86,10 @@ function chunk(runId: string, stream: "stdout" | "stderr", data: Buffer, secrets
if (!p.trim()) continue;
addLog(runId, stream, p, secrets);
const step = stepOf(p);
if (step) void db().update(benchmarkRuns).set({ phase: step }).where(eq(benchmarkRuns.id, runId)).then(() => {}, () => {});
if (step && steps.get(runId) !== step) {
steps.set(runId, step);
void db().update(benchmarkRuns).set({ phase: step }).where(eq(benchmarkRuns.id, runId)).then(() => {}, () => {});
}
}
}
@@ -336,6 +341,7 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
partial.delete(`${id}:${stream}`);
}
steps.delete(id);
if (current === cur) current = null;
const dir = runDir(id);
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
+8 -4
View File
@@ -33,6 +33,7 @@ import { XetCounter } from "./hf-progress";
import { JobLog } from "./job-log";
import { log } from "./log";
import { settleModelStatus } from "./model-status";
import { ProgressSampler } from "./progress-sampler";
import type { Runner } from "./runner";
import { SpeedMeter } from "./speed";
import { Throttle } from "./throttle";
@@ -319,7 +320,9 @@ export class DownloadRunner implements Runner {
);
child.on("close", (code, signal) => done({ code, signal }));
running.add(this);
const throttleTimer = this.throttle(dir, expected);
// One sampler for progress and the speed limit; it skips files it already found complete.
const sampler = new ProgressSampler(dir, expected);
const throttleTimer = this.throttle(sampler);
// Progress from bytes on disk, written to the DB once per second.
const xetBytes = new XetCounter();
@@ -331,7 +334,7 @@ export class DownloadRunner implements Runner {
if (busy) return;
busy = true;
try {
const progress = steadyProgress(last, await this.sample(dir, expected));
const progress = steadyProgress(last, await sampler.sample());
last = progress;
const onDisk = progress.reduce((s, p) => s + p.done, 0);
const doneBytes = Math.min(this.job.totalBytes, Math.max(onDisk, alreadyDone + xetBytes.bytes));
@@ -351,7 +354,7 @@ export class DownloadRunner implements Runner {
* Enforce Settings → Downloads → Speed limit by pausing hf while it is ahead of the budget
* (see Throttle). The limit is re-read every few seconds, so changes apply to running downloads.
*/
private throttle(dir: string, expected: ExpectedFile[]): NodeJS.Timeout {
private throttle(sampler: ProgressSampler): NodeJS.Timeout {
let total: number | null = null;
let readAt = 0;
let bucket: Throttle | null = null;
@@ -383,7 +386,7 @@ export class DownloadRunner implements Runner {
const limit = total / Math.max(1, running.size);
if (!bucket) bucket = new Throttle(limit);
bucket.limit = limit;
const bytes = (await this.sample(dir, expected)).reduce((s, p) => s + p.done, 0);
const bytes = (await sampler.sample()).reduce((s, p) => s + p.done, 0);
if (bucket.update(Date.now(), bytes)) this.pause();
else this.resume();
} catch (err) {
@@ -406,6 +409,7 @@ export class DownloadRunner implements Runner {
if (this.child.exitCode === null) this.child.kill("SIGCONT");
}
/** Every file, looked at fresh (before hf starts and after it exits). */
private async sample(dir: string, expected: ExpectedFile[]) {
const incomplete = await listIncomplete(dir);
return Promise.all(expected.map((f) => bytesOnDisk(dir, f, incomplete)));
+69
View File
@@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import type { ExpectedFile, FileProgress } from "./hf-layout";
import { ProgressSampler, SHARE_MS } from "./progress-sampler";
const files: ExpectedFile[] = [
{ path: "a.gguf", size: 100, etags: ["a"] },
{ path: "b.gguf", size: 200, etags: ["b"] },
];
/** A fake disk: `done[path]` bytes per file; counts what the sampler looks at. */
function fakeDisk() {
const done: Record<string, number> = { "a.gguf": 0, "b.gguf": 0 };
const looked: string[] = [];
let listed = 0;
let clock = 0;
const measure = async (_dir: string, f: ExpectedFile): Promise<FileProgress> => {
looked.push(f.path);
return { done: done[f.path], complete: done[f.path] === f.size };
};
const listPartials = async () => {
listed++;
return [];
};
const sampler = new ProgressSampler("/models/x", files, measure, listPartials, () => clock);
return {
sampler,
done,
looked,
listed: () => listed,
later: (ms = SHARE_MS) => void (clock += ms),
};
}
describe("ProgressSampler", () => {
it("doesn't look at a file again once it is complete", async () => {
const d = fakeDisk();
d.done["a.gguf"] = 100;
d.done["b.gguf"] = 50;
assert.deepEqual(await d.sampler.sample(), [{ done: 100, complete: true }, { done: 50, complete: false }]);
d.later();
d.done["b.gguf"] = 120;
assert.deepEqual(await d.sampler.sample(), [{ done: 100, complete: true }, { done: 120, complete: false }]);
assert.deepEqual(d.looked, ["a.gguf", "b.gguf", "b.gguf"]);
});
it("stops listing partial files when everything is complete", async () => {
const d = fakeDisk();
d.done["a.gguf"] = 100;
d.done["b.gguf"] = 200;
await d.sampler.sample();
assert.equal(d.listed(), 1);
d.later();
assert.deepEqual(await d.sampler.sample(), [{ done: 100, complete: true }, { done: 200, complete: true }]);
assert.equal(d.listed(), 1);
assert.equal(d.looked.length, 2);
});
it("shares samples taken close together (progress and speed limit)", async () => {
const d = fakeDisk();
const [x, y] = await Promise.all([d.sampler.sample(), d.sampler.sample()]);
assert.equal(x, y);
d.later(SHARE_MS - 1);
assert.equal(await d.sampler.sample(), x);
d.later(1);
assert.notEqual(await d.sampler.sample(), x);
assert.equal(d.listed(), 2);
});
});
+52
View File
@@ -0,0 +1,52 @@
// Bytes on disk of a running download, for the progress timer (every second) and the speed limit
// (every 250 ms). Both used to look at every file each time: a stat per file, hf's .metadata for
// every file that already had its size, and the partial files, which on a network share added up to
// hundreds of operations a second. Now:
// - a file found complete isn't looked at again during the run (hf moves a finished file into
// place; it doesn't go back to partial),
// - with every file complete, the partial files aren't listed either,
// - samples asked for within SHARE_MS of each other are one sample.
// The check after hf exits doesn't use this: it looks at every file again.
import { bytesOnDisk, type ExpectedFile, type FileProgress, listIncomplete } from "./hf-layout";
export const SHARE_MS = 200;
export class ProgressSampler {
private complete: boolean[];
private last: { at: number; result: Promise<FileProgress[]> } | null = null;
constructor(
private dir: string,
private files: ExpectedFile[],
private measure: typeof bytesOnDisk = bytesOnDisk,
private listPartials: typeof listIncomplete = listIncomplete,
private now: () => number = Date.now,
) {
this.complete = files.map(() => false);
}
sample(): Promise<FileProgress[]> {
const at = this.now();
if (this.last && at - this.last.at < SHARE_MS) return this.last.result;
const result = this.take();
this.last = { at, result };
// A failed sample isn't handed out again.
result.catch(() => {
if (this.last?.result === result) this.last = null;
});
return result;
}
private async take(): Promise<FileProgress[]> {
const partials = this.complete.every(Boolean) ? [] : await this.listPartials(this.dir);
return Promise.all(
this.files.map(async (f, i) => {
if (this.complete[i]) return { done: f.size, complete: true };
const p = await this.measure(this.dir, f, partials);
if (p.complete) this.complete[i] = true;
return p;
}),
);
}
}
+77
View File
@@ -0,0 +1,77 @@
// The models-folder scan, on a temporary folder and SQLite database.
// Runs with `--conditions=react-server` (see package.json).
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { after, before, describe, it } from "node:test";
const dir = mkdtempSync(join(tmpdir(), "kaname-scan-"));
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
const modelsDir = join(dir, "models");
process.env.MODELS_DIR = modelsDir;
let scan: typeof import("./scan");
let D: typeof import("@/lib/db/client");
let S: typeof import("@/lib/db/schema");
before(async () => {
const { runMigrations } = await import("@/lib/db/migrate");
await runMigrations();
scan = await import("./scan");
D = await import("@/lib/db/client");
S = await import("@/lib/db/schema");
});
after(() => {
try {
rmSync(dir, { recursive: true, force: true });
} catch {}
});
function put(path: string, bytes = 3) {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, "x".repeat(bytes));
}
const tick = () => new Promise((r) => setTimeout(r, 5));
async function stored() {
const rows = await D.db().select().from(S.localFolders);
return Object.fromEntries(rows.map((r) => [r.path, r]));
}
describe("models folder scan", () => {
it("writes only new or changed folders and removes the ones that are gone", async () => {
put(join(modelsDir, "org", "a", "model.gguf"));
put(join(modelsDir, "org", "b", "shards", "x.safetensors"));
assert.equal(await scan.scanModelsDir(modelsDir), 2);
const first = await stored();
await tick();
assert.equal(await scan.scanModelsDir(modelsDir), 2);
const second = await stored();
assert.equal(second["org/a"].scannedAt.getTime(), first["org/a"].scannedAt.getTime(), "unchanged: not written");
assert.equal(second["org/b"].scannedAt.getTime(), first["org/b"].scannedAt.getTime(), "unchanged: not written");
await tick();
put(join(modelsDir, "org", "a", "extra.json"), 10);
rmSync(join(modelsDir, "org", "b"), { recursive: true });
assert.equal(await scan.scanModelsDir(modelsDir), 1);
const third = await stored();
assert.deepEqual(Object.keys(third), ["org/a"]);
assert.equal(third["org/a"].fileCount, 2);
assert.deepEqual(third["org/a"].files.map((f) => f.path), ["extra.json", "model.gguf"]);
assert.ok(third["org/a"].scannedAt.getTime() > first["org/a"].scannedAt.getTime(), "changed: written");
});
it("compares the file list, not only the counts", () => {
const at = new Date();
const found = { path: "o/m", files: [{ path: "b.gguf", size: 2 }], fileCount: 1, totalBytes: 2, commit: null, scannedAt: at };
const same = { path: "o/m", filesJson: JSON.stringify(found.files), fileCount: 1, totalBytes: 2, commit: null };
assert.deepEqual(scan.folderChanges([same], [found]), { insert: [], update: [], remove: [] });
const renamed = { ...same, filesJson: JSON.stringify([{ path: "a.gguf", size: 2 }]) };
assert.deepEqual(scan.folderChanges([renamed], [found]).update, [found]);
});
});
+41 -2
View File
@@ -4,6 +4,7 @@
import { readdir, readFile, stat } from "node:fs/promises";
import { join, relative, sep } from "node:path";
import { eq, inArray, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { localFolders, models } from "@/lib/db/schema";
import { HF_CACHE_DIR } from "./hf-layout";
@@ -65,7 +66,29 @@ async function hfCommit(folder: string): Promise<string | null> {
return null;
}
/** Scan MODELS_DIR and replace the `local_folders` table with folders no model uses. */
/** A stored folder, its file list as the JSON text it is stored as (compared, never parsed). */
export type StoredFolder = { path: string; filesJson: string; fileCount: number; totalBytes: number; commit: string | null };
/**
* What to write so `local_folders` matches a scan: new folders, changed ones, and the paths of
* folders that are gone. Unchanged folders aren't written: the scan runs every 2 minutes by
* default, and rewriting every folder's file list each time added up to hundreds of MB a day.
*/
export function folderChanges(stored: StoredFolder[], found: FoundFolder[]) {
const before = new Map(stored.map((s) => [s.path, s]));
const insert: FoundFolder[] = [];
const update: FoundFolder[] = [];
for (const f of found) {
const s = before.get(f.path);
if (!s) insert.push(f);
else if (s.fileCount !== f.fileCount || s.totalBytes !== f.totalBytes || s.commit !== (f.commit ?? null) || s.filesJson !== JSON.stringify(f.files)) update.push(f);
}
const seen = new Set(found.map((f) => f.path));
const remove = stored.filter((s) => !seen.has(s.path)).map((s) => s.path);
return { insert, update, remove };
}
/** Scan MODELS_DIR and update the `local_folders` table to the 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[] = [];
@@ -84,6 +107,22 @@ export async function scanModelsDir(modelsDir: string): Promise<number> {
}
}
const d = db();
await d.batch([d.delete(localFolders), ...found.map((f) => d.insert(localFolders).values(f))]);
const stored = await d
.select({
path: localFolders.path,
// The raw JSON text: comparing it is enough, parsing every list each scan isn't needed.
filesJson: sql<string>`${localFolders.files}`,
fileCount: localFolders.fileCount,
totalBytes: localFolders.totalBytes,
commit: localFolders.commit,
})
.from(localFolders);
const { insert, update, remove } = folderChanges(stored, found);
const writes = [
...(remove.length ? [d.delete(localFolders).where(inArray(localFolders.path, remove))] : []),
...insert.map((f) => d.insert(localFolders).values(f)),
...update.map((f) => d.update(localFolders).set(f).where(eq(localFolders.path, f.path))),
];
if (writes.length > 0) await d.batch(writes as [(typeof writes)[number], ...typeof writes]);
return found.length;
}