Skip to content

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

fix: cache LoRA metadata by mtime (#5125)

[._.]/ Adam Eivycfde93012d7f
diff --git a/server/services/loras.js b/server/services/loras.js
index 50dc47b790..6228206597 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -68,12 +68,21 @@ import { getSettings } from './settings.js';
const SIDECAR_SUFFIX = '.metadata.json';
+// listLoras() is called from several picker/setup paths. Cache the fully
+// normalized public entry by the weight file's path plus weight/sidecar mtimes
+// so repeated reads only pay the directory/stat pass, not one sidecar read (and
+// potentially one safetensors header parse) per installed LoRA.
+const loraMetadataCache = new Map();
+
// One install attempt per requested Civitai model version at a time. A duplicate
// submit shares the original result instead of racing it to the same destination
// files, while two explicitly different versions remain independent.
const civitaiInstalls = createSingleFlight();
const sidecarPath = (loraFilename) => join(PATHS.loras, `${loraFilename}${SIDECAR_SUFFIX}`);
+const invalidateLoraMetadataCache = (filename) => {
+ loraMetadataCache.delete(join(PATHS.loras, filename));
+};
// Reads the sidecar JSON next to a LoRA file. Returns `null` when the
// sidecar is absent — calling code can fall back to filename inference for
@@ -133,9 +142,13 @@ export const assertSafeLoraFilename = (filename) => {
// LoRAs without sidecars get a minimal "legacy" entry with sensible defaults
// so the manager UI can still render LoRAs the user dropped in pre-Civitai.
export const listLoras = async () => {
- if (!existsSync(PATHS.loras)) return [];
+ if (!existsSync(PATHS.loras)) {
+ loraMetadataCache.clear();
+ return [];
+ }
const lorasStat = await stat(PATHS.loras).catch(() => null);
if (!lorasStat || !lorasStat.isDirectory()) {
+ loraMetadataCache.clear();
console.log(`⚠️ PATHS.loras exists but is not a directory: ${PATHS.loras}`);
return [];
}
@@ -145,6 +158,12 @@ export const listLoras = async () => {
const out = await listDirectoryByExtension(PATHS.loras, {
extensions: ['.safetensors'],
mapEntry: async (filename, _fullPath, s) => {
+ const sidecarStat = await stat(sidecarPath(filename)).catch(() => null);
+ const cached = loraMetadataCache.get(_fullPath);
+ if (cached?.mtimeMs === s.mtimeMs && cached?.sidecarMtimeMs === sidecarStat?.mtimeMs) {
+ return cached.entry;
+ }
+
const sidecar = await readSidecar(filename);
const fallbackName = filename.replace(/^lora-/, '').replace(/\.safetensors$/, '');
// Re-derive runnerFamily from civitai.baseModel at read time so
@@ -199,7 +218,7 @@ export const listLoras = async () => {
// FLUX.2 → size-specific (or bare 'flux2' when size is unknown, so it
// still shows for both sizes); every other family → its runner id.
const loraCompatKey = composeCompatKey(runnerFamily, fluxVariant);
- return {
+ const entry = {
filename,
name: sidecar?.name || fallbackName,
sizeBytes: s.size,
@@ -239,8 +258,18 @@ export const listLoras = async () => {
// run the check, not as a verdict.
effectReport: readCachedLoraEffectReport(sidecar?.effectReport, { sizeBytes: s.size, mtimeMs: s.mtimeMs }),
};
+ loraMetadataCache.set(_fullPath, {
+ mtimeMs: s.mtimeMs,
+ sidecarMtimeMs: sidecarStat?.mtimeMs,
+ entry,
+ });
+ return entry;
},
});
+ const listedPaths = new Set(out.map(({ filename }) => join(PATHS.loras, filename)));
+ for (const cachedPath of loraMetadataCache.keys()) {
+ if (!listedPaths.has(cachedPath)) loraMetadataCache.delete(cachedPath);
+ }
return out.sort((a, b) => (b.installedAt || '').localeCompare(a.installedAt || ''));
};
@@ -298,13 +327,17 @@ export const deleteLora = async (filename) => {
const queueSidecarWrite = createKeyedFileWriteQueue();
// Replace a sidecar wholesale (the install paths), serialized against patches.
-const writeSidecar = (filename, sidecar) => queueSidecarWrite(filename, () =>
- atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n'));
+const writeSidecar = (filename, sidecar) => queueSidecarWrite(filename, async () => {
+ await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
+ invalidateLoraMetadataCache(filename);
+});
// Remove a sidecar, serialized so a queued patch can't recreate it after the
// LoRA is gone.
-const removeSidecar = (filename) => queueSidecarWrite(filename, () =>
- rm(sidecarPath(filename), { force: true }));
+const removeSidecar = (filename) => queueSidecarWrite(filename, async () => {
+ await rm(sidecarPath(filename), { force: true });
+ invalidateLoraMetadataCache(filename);
+});
export const patchLoraSidecar = async (filename, patch) => {
assertSafeLoraFilename(filename);
@@ -328,6 +361,7 @@ export const patchLoraSidecar = async (filename, patch) => {
const current = (await readSidecar(filename)) || { filename };
const next = { ...current, ...patch, filename };
await atomicWrite(sidecarPath(filename), JSON.stringify(next, null, 2) + '\n');
+ invalidateLoraMetadataCache(filename);
return next;
});
};
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index f348fbffb3..fc6ca726d5 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -86,6 +86,77 @@ describe('listLoras', () => {
expect(legacy.recommendedScale).toBe(1.0);
});
+ it('reuses cached metadata while the LoRA file mtime is unchanged', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, 'cached.safetensors'), 'weights');
+ await fs.writeFile(join(tmpLoras, 'cached.safetensors.metadata.json'), JSON.stringify({
+ filename: 'cached.safetensors', name: 'Cached', keyLayout: 'comfyui',
+ }));
+
+ const [first] = await lorasService.listLoras();
+ const [second] = await lorasService.listLoras();
+
+ expect(second).toBe(first);
+ });
+
+ it('invalidates cached metadata after a sidecar patch', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ await fs.writeFile(join(tmpLoras, 'patched.safetensors'), 'weights');
+ await fs.writeFile(join(tmpLoras, 'patched.safetensors.metadata.json'), JSON.stringify({
+ filename: 'patched.safetensors', name: 'Before', keyLayout: 'comfyui',
+ }));
+
+ const [before] = await lorasService.listLoras();
+ await lorasService.patchLoraSidecar('patched.safetensors', { name: 'After' });
+ const [after] = await lorasService.listLoras();
+
+ expect(after).not.toBe(before);
+ expect(after.name).toBe('After');
+ });
+
+ it('refreshes cached metadata when a sidecar is replaced outside this service', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ const filePath = join(tmpLoras, 'external.safetensors');
+ const sidecarPath = `${filePath}.metadata.json`;
+ await fs.writeFile(filePath, 'weights');
+ await fs.writeFile(sidecarPath, JSON.stringify({
+ filename: 'external.safetensors', name: 'Before', keyLayout: 'comfyui',
+ }));
+
+ const [before] = await lorasService.listLoras();
+ await fs.writeFile(sidecarPath, JSON.stringify({
+ filename: 'external.safetensors', name: 'After', keyLayout: 'comfyui',
+ }));
+ const future = new Date(Date.now() + 10_000);
+ await fs.utimes(sidecarPath, future, future);
+ const [after] = await lorasService.listLoras();
+
+ expect(after).not.toBe(before);
+ expect(after.name).toBe('After');
+ });
+
+ it('refreshes cached metadata when the LoRA file mtime changes', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ const filePath = join(tmpLoras, 'updated.safetensors');
+ await fs.writeFile(filePath, 'weights');
+ await fs.writeFile(`${filePath}.metadata.json`, JSON.stringify({
+ filename: 'updated.safetensors', name: 'Updated', keyLayout: 'comfyui',
+ }));
+
+ const [before] = await lorasService.listLoras();
+ await fs.writeFile(filePath, 'larger-weights');
+ const future = new Date(Date.now() + 10_000);
+ await fs.utimes(filePath, future, future);
+ const [after] = await lorasService.listLoras();
+
+ expect(after).not.toBe(before);
+ expect(after.sizeBytes).toBe(Buffer.byteLength('larger-weights'));
+ });
+
it('tags a flux2 LoRA size from the Civitai baseModel without reading the header', async () => {
const fs = await import('fs/promises');
await fs.mkdir(tmpLoras, { recursive: true });
@@ -284,6 +355,26 @@ describe('deleteLora', () => {
expect(existsSync(join(tmpLoras, 'lora-x.safetensors'))).toBe(false);
expect(existsSync(join(tmpLoras, 'lora-x.safetensors.metadata.json'))).toBe(false);
});
+ it('invalidates cached metadata before the same filename is reused', async () => {
+ const fs = await import('fs/promises');
+ await fs.mkdir(tmpLoras, { recursive: true });
+ const filePath = join(tmpLoras, 'reused.safetensors');
+ await fs.writeFile(filePath, 'old');
+ await fs.writeFile(`${filePath}.metadata.json`, JSON.stringify({
+ filename: 'reused.safetensors', name: 'Old', keyLayout: 'comfyui',
+ }));
+ const oldStat = await fs.stat(filePath);
+ expect((await lorasService.listLoras())[0].name).toBe('Old');
+
+ await lorasService.deleteLora('reused.safetensors');
+ await fs.writeFile(filePath, 'new');
+ await fs.utimes(filePath, oldStat.atime, oldStat.mtime);
+ await fs.writeFile(`${filePath}.metadata.json`, JSON.stringify({
+ filename: 'reused.safetensors', name: 'New', keyLayout: 'comfyui',
+ }));
+
+ expect((await lorasService.listLoras())[0].name).toBe('New');
+ });
it('rejects path traversal', async () => {
await expect(lorasService.deleteLora('../escape.safetensors')).rejects.toThrow(/Invalid LoRA filename/);
await expect(lorasService.deleteLora('foo/bar.safetensors')).rejects.toThrow(/Invalid LoRA filename/);