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([coalesce-fallback-provider-failure-storm]): address claude+codex review — cache coherency + cleanup-branch rejection

[._.]/ Adam Eivy6864882b1894
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 63bb54567d..34a7d6d397 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -127,16 +127,30 @@ export function createProviderService(config = {}) {
// simultaneous burst of callers shares one disk read instead of each
// racing its own. Per-service-instance (the toolkit builds one), so the
// cache is process-wide for the single-user server.
+ //
+ // `cacheGeneration` is bumped on every cache mutation (refresh or
+ // invalidate). A cold read captures it before reading disk and only
+ // adopts its result if the generation is unchanged on resolve — so a
+ // slow stale read can't clobber a fresher snapshot a concurrent
+ // `saveProviders` wrote while it was in flight.
let providersCache = null;
let providersCacheAt = -Infinity;
let providersLoadInFlight = null;
+ let cacheGeneration = 0;
function refreshProvidersCache(data) {
providersCache = data;
providersCacheAt = Date.now();
+ cacheGeneration += 1;
return data;
}
+ function invalidateProvidersCache() {
+ providersCache = null;
+ providersCacheAt = -Infinity;
+ cacheGeneration += 1;
+ }
+
// JSON.parse with a corrupt-file rescue. A garbled providers.json (truncated
// write, hand-edit typo, disk corruption) would otherwise crash server boot.
// Rename the bad file to <path>.corrupt + start from empty so the CLI can
@@ -196,16 +210,28 @@ export function createProviderService(config = {}) {
return providersCache;
}
if (providersLoadInFlight) return providersLoadInFlight;
+ const gen = cacheGeneration;
providersLoadInFlight = readProvidersFromDisk()
- .then(refreshProvidersCache)
+ .then(data => {
+ // Adopt this read only if no write/invalidate landed while it was
+ // in flight; otherwise that newer snapshot is fresher — return it
+ // rather than clobbering the cache with our stale parse.
+ if (cacheGeneration === gen) return refreshProvidersCache(data);
+ return providersCache ?? data;
+ })
.finally(() => { providersLoadInFlight = null; });
return providersLoadInFlight;
}
async function saveProviders(data) {
+ // Drop the cache BEFORE the write: mutators read → mutate the cached
+ // object in place → save, so the warm cache already holds the unsaved
+ // mutation. Invalidating first means a failed `atomicWrite` leaves no
+ // cache to serve the un-persisted change (the next read re-reads disk),
+ // and refreshing only after success keeps the cache consistent with
+ // what actually landed on disk.
+ invalidateProvidersCache();
await atomicWrite(PROVIDERS_PATH, data);
- // Keep the cache warm + consistent with disk after a write so the next
- // read reflects the mutation without a re-read or a stale-TTL window.
refreshProvidersCache(data);
}
diff --git a/server/lib/aiToolkit/providersCache.test.js b/server/lib/aiToolkit/providersCache.test.js
index 4aee19f776..6cef501ea2 100644
--- a/server/lib/aiToolkit/providersCache.test.js
+++ b/server/lib/aiToolkit/providersCache.test.js
@@ -17,6 +17,7 @@ vi.mock('./internal/atomicWrite.js', () => ({
}));
const { createProviderService } = await import('./providers.js');
+const { atomicWrite } = await import('./internal/atomicWrite.js');
const seed = (providers, active) => JSON.stringify({ activeProvider: active, providers });
const cli = (id) => ({ id, name: id, type: 'cli', command: 'x' });
@@ -74,4 +75,61 @@ describe('loadProviders — TTL cache + in-flight coalescing', () => {
expect(readCount).toBe(1);
expect(all.providers.map((p) => p.id).sort()).toEqual(['a', 'b']);
});
+
+ it('does not leave an unsaved mutation in the cache when the write fails', async () => {
+ const svc = createProviderService({ dataDir: '/x', providersFile: 'p.json' });
+ await svc.getAllProviders(); // warm cache with just 'a', read 1
+ expect(readCount).toBe(1);
+
+ // The mutator mutates the warm cache object in place, then the write
+ // throws. Because saveProviders invalidates the cache before writing,
+ // the un-persisted 'b' must not survive — the next read re-reads disk
+ // (still only 'a') rather than serving the poisoned cache.
+ atomicWrite.mockRejectedValueOnce(new Error('disk full'));
+ await expect(
+ svc.createProvider({ id: 'b', name: 'B', type: 'cli', command: 'y' })
+ ).rejects.toThrow('disk full');
+
+ const all = await svc.getAllProviders();
+ expect(all.providers.map((p) => p.id)).toEqual(['a']);
+ expect(readCount).toBe(2); // cache was invalidated → fresh disk read
+ });
+
+ it('a stale in-flight read does not clobber a fresher snapshot written mid-read', async () => {
+ const fsp = await import('fs/promises');
+ const svc = createProviderService({ dataDir: '/x', providersFile: 'p.json' });
+
+ await svc.getAllProviders(); // warm cache with {a}
+
+ // Gate the write so the cache stays invalidated while a cold read runs.
+ let releaseWrite;
+ atomicWrite.mockImplementationOnce(async () => {
+ await new Promise((res) => { releaseWrite = res; });
+ });
+ const createP = svc.createProvider({ id: 'b', name: 'B', type: 'cli', command: 'y' });
+ await new Promise((r) => setTimeout(r, 0)); // let it invalidate + park at the gated write
+
+ // Cache is now invalidated; start a cold read and gate it mid-flight.
+ let releaseRead;
+ fsp.readFile.mockImplementationOnce(async () => {
+ readCount += 1;
+ await new Promise((res) => { releaseRead = res; });
+ return diskContent; // stale snapshot — disk still only has {a}
+ });
+ const staleRead = svc.getAllProviders();
+ await new Promise((r) => setTimeout(r, 0)); // let the read start
+
+ // The write lands and refreshes the cache to {a, b} FIRST...
+ releaseWrite();
+ await createP;
+
+ // ...then the stale read resolves. Its older snapshot must NOT overwrite
+ // the fresher cache (the generation guard skips the adoption).
+ releaseRead();
+ const staleResult = await staleRead;
+ expect(staleResult.providers.map((p) => p.id).sort()).toEqual(['a', 'b']);
+
+ const all = await svc.getAllProviders();
+ expect(all.providers.map((p) => p.id).sort()).toEqual(['a', 'b']);
+ });
});
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 7b2006ee5a..a9b8e38e77 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -351,9 +351,14 @@ function coalesceFallbackMarkAndPick(failed, firstError) {
// While `work` is in flight, concurrent callers return it without
// overwriting the slot, so this entry is only ever cleared by its own
- // settle — a plain delete is safe.
+ // settle — a plain delete is safe. Use `then(cleanup, cleanup)` rather
+ // than `finally`: `finally` re-raises a `work` rejection on the derived
+ // promise, which nothing awaits → unhandledRejection. The two-arm `then`
+ // handles both settle paths and swallows the cleanup branch's copy of the
+ // rejection; the caller's own `await work` still sees the original reject.
+ const clearSlot = () => { _fallbackMarkAndPickInFlight.delete(failed.id); };
_fallbackMarkAndPickInFlight.set(failed.id, work);
- work.finally(() => _fallbackMarkAndPickInFlight.delete(failed.id));
+ work.then(clearSlot, clearSlot);
return work;
}