Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: account for and free HF shared-blob-store weights in model storage
Adam Eivyd568e58f43f5
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.jsindex 56fdbe01c8..e871bf271a 100644--- a/server/lib/hfCache.js+++ b/server/lib/hfCache.js@@ -25,7 +25,7 @@ import { homedir } from 'node:os';import {join, dirname, resolve as resolvePath, relative, sep, posix, win32,} from 'node:path';-import { sha256File } from './fileUtils.js';+import { sha256File, rmGuarded } from './fileUtils.js';// HF cache root resolution mirrors huggingface_hub's own precedence:// HF_HUB_CACHE > HF_HOME/hub > $XDG_CACHE_HOME/huggingface/hub@@ -533,3 +533,92 @@ export function aggregateVerifies(verifies) {badFiles: list.flatMap((v) => v.files.filter((f) => !f.ok).map((f) => ({ repo: v.repoId, name: f.name, reason: f.reason }))),};}++// ---------------------------------------------------------------------------+// Shared blob store+//+// Newer huggingface_hub releases keep weight bytes in `<hub>/blobs/<xx>/<hash>`+// (marked by `.huggingface-shared-blobs`) and link each model's own+// `blobs/<hash>` / `snapshots/` entries at them, with a `<hash>.refs` sidecar+// naming the referrers. A model directory is therefore a handful of symlinks:+// `du`/`dirSize` on it reports kilobytes, and `rm -rf models--X` frees nothing+// because the bytes live outside it. These helpers make the store visible and+// let a delete release the blobs nothing else references.+// ---------------------------------------------------------------------------++const SHARED_BLOBS_DIR = 'blobs';+const REFS_SUFFIX = '.refs';++async function walkSymlinks(dir, onLink) {+ const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ const path = join(dir, entry.name);+ if (entry.isSymbolicLink()) await onLink(path);+ else if (entry.isDirectory()) await walkSymlinks(path, onLink);+ }+}++// Real paths (with sizes) of shared-store blobs one model directory links to.+export async function listLinkedSharedBlobs(hubDir, dirName) {+ const sharedRoot = join(await fs.realpath(hubDir).catch(() => hubDir), SHARED_BLOBS_DIR) + sep;+ const found = new Map();+ await walkSymlinks(join(hubDir, dirName), async (link) => {+ const target = await fs.realpath(link).catch(() => null);+ if (!target || !target.startsWith(sharedRoot) || found.has(target)) return;+ const info = await fs.stat(target).catch(() => null);+ if (info?.isFile()) found.set(target, info.size);+ });+ return found;+}++async function listModelDirNames(hubDir) {+ const entries = await fs.readdir(hubDir, { withFileTypes: true }).catch(() => []);+ return entries.filter((e) => e.isDirectory() && e.name.startsWith('models--')).map((e) => e.name);+}++async function referencedSharedBlobs(hubDir) {+ const referenced = new Set();+ for (const dirName of await listModelDirNames(hubDir)) {+ for (const target of (await listLinkedSharedBlobs(hubDir, dirName)).keys()) referenced.add(target);+ }+ return referenced;+}++// Size of the shared store: `{ bytes, files: Map<realPath,size> }`. The `.refs`+// sidecars and marker file are metadata, not weights.+export async function scanSharedBlobStore(hubDir) {+ const files = new Map();+ const walk = async (dir) => {+ const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) await walk(path);+ else if (entry.isFile() && !entry.name.endsWith(REFS_SUFFIX) && !entry.name.startsWith('.huggingface')) {+ const info = await fs.stat(path).catch(() => null);+ if (info) files.set(await fs.realpath(path).catch(() => path), info.size);+ }+ }+ };+ await walk(join(hubDir, SHARED_BLOBS_DIR));+ let bytes = 0;+ for (const size of files.values()) bytes += size;+ return { bytes, files };+}++// After a model directory is removed, delete the given shared blobs that no+// remaining model links to. Returns `{ removed, freedBytes }`. Blobs another+// model still uses are left alone, so a delete never breaks a sibling.+export async function releaseSharedBlobs(hubDir, candidates) {+ if (!candidates?.size) return { removed: 0, freedBytes: 0 };+ const referenced = await referencedSharedBlobs(hubDir);+ let removed = 0;+ let freedBytes = 0;+ for (const [target, size] of candidates) {+ if (referenced.has(target)) continue;+ await rmGuarded(target, { force: true });+ await rmGuarded(`${target}${REFS_SUFFIX}`, { force: true });+ removed += 1;+ freedBytes += size;+ }+ return { removed, freedBytes };+}diff --git a/server/lib/hfSharedBlobs.test.js b/server/lib/hfSharedBlobs.test.jsnew file mode 100644index 0000000000..812139599b--- /dev/null+++ b/server/lib/hfSharedBlobs.test.js@@ -0,0 +1,66 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import {+ listLinkedSharedBlobs, releaseSharedBlobs,+} from './hfCache.js';+import { listHfModelStorage } from '../services/mediaModelStorage.js';++// Layout mirrors huggingface_hub's shared store: bytes in hub/blobs/<xx>/<hash>,+// each model's blobs/<hash> and snapshots/<sha>/<file> are links at them.+let hub;+const addSharedBlob = (hash, bytes) => {+ const dir = join(hub, 'blobs', hash.slice(0, 2));+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, hash), Buffer.alloc(bytes, 1));+ writeFileSync(join(dir, `${hash}.refs`), 'refs');+ return join(dir, hash);+};+const addModel = (dirName, files) => {+ const snap = join(hub, dirName, 'snapshots', 'a'.repeat(40));+ mkdirSync(snap, { recursive: true });+ mkdirSync(join(hub, dirName, 'blobs'), { recursive: true });+ for (const [file, blobPath] of Object.entries(files)) {+ symlinkSync(blobPath, join(hub, dirName, 'blobs', file));+ symlinkSync(join(hub, dirName, 'blobs', file), join(snap, file));+ }+};++beforeEach(() => { hub = mkdtempSync(join(tmpdir(), 'hf-shared-')); });+afterEach(() => { rmSync(hub, { recursive: true, force: true }); });++describe('shared blob store', () => {+ it('counts bytes a model only links to, and frees only blobs no sibling uses', async () => {+ const exclusive = addSharedBlob('11aaaa', 100);+ const common = addSharedBlob('22bbbb', 50);+ addModel('models--org--a', { 'w1.safetensors': exclusive, 'w2.safetensors': common });+ addModel('models--org--b', { 'w2.safetensors': common });++ const linked = await listLinkedSharedBlobs(hub, 'models--org--a');+ expect([...linked.values()].sort((x, y) => x - y)).toEqual([50, 100]);++ rmSync(join(hub, 'models--org--a'), { recursive: true });+ const result = await releaseSharedBlobs(hub, linked);++ expect(result).toEqual({ removed: 1, freedBytes: 100 });+ expect(existsSync(exclusive)).toBe(false);+ expect(existsSync(`${exclusive}.refs`)).toBe(false);+ expect(existsSync(common)).toBe(true);+ });++ it('storage report counts shared bytes per model and flags leaked blobs once in the total', async () => {+ const kept = addSharedBlob('33cccc', 10);+ addSharedBlob('44dddd', 70);+ addModel('models--org--c', { 'w.safetensors': kept });+ const prev = process.env.HF_HUB_CACHE;+ process.env.HF_HUB_CACHE = hub;+ const report = await listHfModelStorage().finally(() => {+ if (prev === undefined) delete process.env.HF_HUB_CACHE; else process.env.HF_HUB_CACHE = prev;+ });++ expect(report.models[0]).toMatchObject({ id: 'models--org--c', sharedBytes: 10 });+ expect(report.sharedStore).toEqual({ bytes: 80, unreferencedBytes: 70 });+ expect(report.totalBytes).toBeGreaterThanOrEqual(80);+ });+});diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.jsindex 8c07c4a0ff..11e7a80096 100644--- a/server/routes/imageVideoModels.js+++ b/server/routes/imageVideoModels.js@@ -14,7 +14,7 @@ import { join } from 'path';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { PATHS, rmGuarded } from '../lib/fileUtils.js';-import { getHfCacheRoot } from '../lib/hfCache.js';+import { getHfCacheRoot, listLinkedSharedBlobs, releaseSharedBlobs } from '../lib/hfCache.js';import {getImageModels,setMediaModelEnabled,@@ -206,9 +206,14 @@ router.delete('/hf/:dirName', asyncHandler(async (req, res) => {const fullPath = join(HF_HUB_DIR(), dirName);if (!existsSync(fullPath)) throw new ServerError('Model not found', { status: 404, code: 'NOT_FOUND' });console.log(`🗑️ Deleting HF model cache: ${dirName}`);+ // The model dir may hold only links into the shared blob store, so note the+ // blobs first and release the ones no other model uses once it is gone.+ const sharedBlobs = await listLinkedSharedBlobs(HF_HUB_DIR(), dirName);await rmGuarded(fullPath, { recursive: true, force: true });+ const { removed, freedBytes } = await releaseSharedBlobs(HF_HUB_DIR(), sharedBlobs);+ if (removed) console.log(`🗑️ Released ${removed} shared HF blobs (${freedBytes} bytes) for ${dirName}`);await recordModelUninstall({ backend: 'huggingface', key: dirName });- res.json({ ok: true });+ res.json({ ok: true, freedSharedBytes: freedBytes });}));router.delete('/lora/:filename', asyncHandler(async (req, res) => {diff --git a/server/routes/imageVideoModels.test.js b/server/routes/imageVideoModels.test.jsindex 2b8f0ef90f..044c20ae34 100644--- a/server/routes/imageVideoModels.test.js+++ b/server/routes/imageVideoModels.test.js@@ -1,4 +1,7 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import express from 'express';import { request } from '../lib/testHelper.js';import { errorMiddleware, ServerError } from '../lib/errorHandler.js';@@ -58,6 +61,8 @@ vi.mock('../lib/videoTextEncoders.js', () => ({}),}));+vi.mock('../services/modelManifest.js', () => ({ recordModelUninstall: vi.fn(async () => {}) }));+// Avoid touching the real HF cache dir in GET / (not under test here).vi.mock('../lib/fileUtils.js', async (orig) => {const actual = await orig();@@ -182,3 +187,45 @@ describe('catalog availability and support requests', () => {expect(addTask).not.toHaveBeenCalled();});});++describe('DELETE /hf/:dirName', () => {+ let hub;+ let prevCache;+ beforeEach(() => {+ prevCache = process.env.HF_HUB_CACHE;+ hub = mkdtempSync(join(tmpdir(), 'hf-delete-'));+ process.env.HF_HUB_CACHE = hub;+ });+ afterEach(() => {+ if (prevCache === undefined) delete process.env.HF_HUB_CACHE; else process.env.HF_HUB_CACHE = prevCache;+ rmSync(hub, { recursive: true, force: true });+ });++ // Regression: a model whose weights live in the shared blob store is only+ // symlinks, so removing its directory freed no disk space.+ it('frees shared-store blobs the deleted model alone used, keeping a sibling\'s', async () => {+ const blob = (hash, bytes) => {+ mkdirSync(join(hub, 'blobs', hash.slice(0, 2)), { recursive: true });+ const path = join(hub, 'blobs', hash.slice(0, 2), hash);+ writeFileSync(path, Buffer.alloc(bytes, 1));+ return path;+ };+ const model = (dirName, files) => {+ const snap = join(hub, dirName, 'snapshots', 'b'.repeat(40));+ mkdirSync(snap, { recursive: true });+ for (const [file, target] of Object.entries(files)) symlinkSync(target, join(snap, file));+ };+ const mine = blob('aa11', 64);+ const common = blob('bb22', 32);+ model('models--org--gone', { 'a.safetensors': mine, 'b.safetensors': common });+ model('models--org--stays', { 'b.safetensors': common });++ const res = await request(makeApp()).delete('/api/image-video/models/hf/models--org--gone');++ expect(res.status).toBe(200);+ expect(res.body).toEqual({ ok: true, freedSharedBytes: 64 });+ expect(existsSync(join(hub, 'models--org--gone'))).toBe(false);+ expect(existsSync(mine)).toBe(false);+ expect(existsSync(common)).toBe(true);+ });+});diff --git a/server/services/mediaModelStorage.js b/server/services/mediaModelStorage.jsindex ed84a588d8..437b4802b4 100644--- a/server/services/mediaModelStorage.js+++ b/server/services/mediaModelStorage.js@@ -10,7 +10,9 @@ import { existsSync } from 'fs';import { readdir, stat } from 'fs/promises';import { join } from 'path';import { PATHS, dirSize, formatBytes } from '../lib/fileUtils.js';-import { getHfCacheRoot } from '../lib/hfCache.js';+import {+ getHfCacheRoot, listLinkedSharedBlobs, scanSharedBlobStore,+} from '../lib/hfCache.js';import { loadMediaModels } from '../lib/mediaModels.js';import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';@@ -50,11 +52,21 @@ export async function listHfModelStorage({ strict = false } = {}) {? (await readdir(hubDir)).filter((name) => name.startsWith('models--')): [];+ const linkedBlobs = new Set();const models = await mapWithConcurrency(entries, 4, async (dirName) => {const modelKey = dirName.replace('models--', '');const [org, ...nameParts] = modelKey.split('--');const name = nameParts.join('--');- const size = await dirSize(join(hubDir, dirName), { strict });+ // A model dir can be mostly links into the shared blob store; count those+ // bytes so the row reflects what deleting it frees (or at least what it uses).+ const [ownSize, linked] = await Promise.all([+ dirSize(join(hubDir, dirName), { strict }),+ listLinkedSharedBlobs(hubDir, dirName),+ ]);+ let sharedSize = 0;+ for (const bytes of linked.values()) sharedSize += bytes;+ const size = ownSize + sharedSize;+ for (const target of linked.keys()) linkedBlobs.add(target);return {id: dirName,org,@@ -63,14 +75,22 @@ export async function listHfModelStorage({ strict = false } = {}) {label: APP_MODELS[modelKey] || null,size,sizeHuman: formatBytes(size),+ sharedBytes: sharedSize,};});+ // Shared blobs can back several models, so the total counts each blob once:+ // the per-model own bytes plus the whole shared store (referenced or leaked).+ const store = hubPresent ? await scanSharedBlobStore(hubDir) : { bytes: 0, files: new Map() };+ let unreferencedBytes = 0;+ for (const [target, bytes] of store.files) if (!linkedBlobs.has(target)) unreferencedBytes += bytes;+models.sort((a, b) => b.size - a.size);return {hubDir,models,- totalBytes: models.reduce((sum, model) => sum + model.size, 0),+ sharedStore: { bytes: store.bytes, unreferencedBytes },+ totalBytes: models.reduce((sum, model) => sum + model.size - model.sharedBytes, 0) + store.bytes,};}