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

feat([coalesce-fallback-provider-failure-storm]): collapse N-way provider-failure storm to one read + one mark

[._.]/ Adam Eivy9844e337df47
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 2dad6d6d88..63bb54567d 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -109,11 +109,34 @@ export function createProviderService(config = {}) {
const {
dataDir = './data',
providersFile = 'providers.json',
- sampleFile = null
+ sampleFile = null,
+ // Short TTL cache on the parsed providers.json. The hot path is an
+ // N-way provider-failure storm: each failing call runs
+ // pickFallbackProvider → getAllProviders → loadProviders, which used
+ // to re-read providers.json from disk every time. A ~1s TTL collapses
+ // that storm to a single read without making config edits feel stale
+ // (provider config changes are human-paced; saveProviders refreshes
+ // the cache inline so a write is reflected immediately).
+ providersCacheTtlMs = 1000
} = config;
const PROVIDERS_PATH = join(dataDir, providersFile);
+ // Last successfully-loaded providers data + the wall-clock time it was
+ // cached. `providersLoadInFlight` coalesces concurrent cold reads so a
+ // 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.
+ let providersCache = null;
+ let providersCacheAt = -Infinity;
+ let providersLoadInFlight = null;
+
+ function refreshProvidersCache(data) {
+ providersCache = data;
+ providersCacheAt = Date.now();
+ return data;
+ }
+
// 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
@@ -129,7 +152,7 @@ export function createProviderService(config = {}) {
}
}
- async function loadProviders() {
+ async function readProvidersFromDisk() {
if (!existsSync(PROVIDERS_PATH)) {
if (sampleFile && existsSync(sampleFile)) {
const sample = await readFile(sampleFile, 'utf-8');
@@ -164,8 +187,26 @@ export function createProviderService(config = {}) {
return data;
}
+ // Cache-fronted read. Returns the cached snapshot while it's within the
+ // TTL; otherwise reads from disk, coalescing concurrent cold reads into
+ // a single `readProvidersFromDisk` so an N-way failure storm triggers at
+ // most one read per TTL window.
+ async function loadProviders() {
+ if (providersCache && (Date.now() - providersCacheAt) < providersCacheTtlMs) {
+ return providersCache;
+ }
+ if (providersLoadInFlight) return providersLoadInFlight;
+ providersLoadInFlight = readProvidersFromDisk()
+ .then(refreshProvidersCache)
+ .finally(() => { providersLoadInFlight = null; });
+ return providersLoadInFlight;
+ }
+
async function saveProviders(data) {
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);
}
return {
diff --git a/server/lib/aiToolkit/providersCache.test.js b/server/lib/aiToolkit/providersCache.test.js
new file mode 100644
index 0000000000..4aee19f776
--- /dev/null
+++ b/server/lib/aiToolkit/providersCache.test.js
@@ -0,0 +1,77 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Count disk reads + control file content so the TTL cache + in-flight
+// coalescing can be asserted precisely. existsSync is forced true so
+// loadProviders always takes the read path (never the sample-bootstrap
+// branch); atomicWrite is a no-op so saveProviders doesn't touch disk.
+let readCount = 0;
+let diskContent = '';
+
+vi.mock('fs', () => ({ existsSync: () => true }));
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async () => { readCount += 1; return diskContent; }),
+ rename: vi.fn(async () => {}),
+}));
+vi.mock('./internal/atomicWrite.js', () => ({
+ atomicWrite: vi.fn(async () => {}),
+}));
+
+const { createProviderService } = await import('./providers.js');
+
+const seed = (providers, active) => JSON.stringify({ activeProvider: active, providers });
+const cli = (id) => ({ id, name: id, type: 'cli', command: 'x' });
+
+beforeEach(() => {
+ readCount = 0;
+ diskContent = seed({ a: cli('a') }, 'a');
+});
+
+describe('loadProviders — TTL cache + in-flight coalescing', () => {
+ it('collapses a concurrent read storm into a single disk read', async () => {
+ const svc = createProviderService({ dataDir: '/x', providersFile: 'p.json' });
+
+ // 10 simultaneous readers (the N-way failure-storm shape) must share
+ // one disk read, not race 10 independent reads.
+ const results = await Promise.all(
+ Array.from({ length: 10 }, () => svc.getAllProviders())
+ );
+
+ expect(readCount).toBe(1);
+ for (const r of results) expect(r.providers).toHaveLength(1);
+ });
+
+ it('serves reads from cache within the TTL window, re-reads after it expires', async () => {
+ const svc = createProviderService({ dataDir: '/x', providersFile: 'p.json', providersCacheTtlMs: 50 });
+
+ await svc.getAllProviders();
+ await svc.getAllProviders();
+ expect(readCount).toBe(1); // second served from cache
+
+ // Mutate disk directly (bypassing saveProviders) — cache still serves
+ // the old snapshot until the TTL elapses.
+ diskContent = seed({ a: cli('a'), b: cli('b') }, 'a');
+ await svc.getAllProviders();
+ expect(readCount).toBe(1);
+
+ await new Promise((r) => setTimeout(r, 120)); // exceed the 50ms TTL
+ const after = await svc.getAllProviders();
+ expect(readCount).toBe(2);
+ expect(after.providers).toHaveLength(2);
+ });
+
+ it('refreshes the cache on write so a save is reflected without a re-read', async () => {
+ const svc = createProviderService({ dataDir: '/x', providersFile: 'p.json' });
+
+ await svc.getAllProviders(); // read 1, cache warm
+ expect(readCount).toBe(1);
+
+ const created = await svc.createProvider({ id: 'b', name: 'B', type: 'cli', command: 'y' });
+ expect(created.id).toBe('b');
+
+ const all = await svc.getAllProviders();
+ // createProvider mutated the cached snapshot and saveProviders refreshed
+ // the cache, so the new provider is visible with no extra disk read.
+ expect(readCount).toBe(1);
+ expect(all.providers.map((p) => p.id).sort()).toEqual(['a', 'b']);
+ });
+});
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index e26bc7c68c..fc9494d8e6 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -254,16 +254,18 @@ export async function runPromptThroughProvider(args) {
// `noteFallbackHandled` cancels the right queued task.
const failed = firstError.effectiveProvider;
const failedModel = firstError.effectiveModel || resolveEffectiveModel(failed, args.model);
- const picked = await pickFallbackProvider(failed);
+ // Coalesce the per-provider mark-and-pick during an N-way failure
+ // storm: the 2nd…Nth simultaneous failure for the same provider awaits
+ // the first's result instead of independently re-reading providers.json
+ // (pickFallbackProvider) and re-writing provider-status.json
+ // (markUnavailable). The fallback *run* below is NOT coalesced — each
+ // failed call still executes its own fallback to get its own result.
+ const picked = await coalesceFallbackMarkAndPick(failed, firstError);
if (!picked) {
throw stripFallbackContext(firstError);
}
const fallback = picked.provider;
- await markProviderUnavailableFromError(failed, firstError.message, firstError.errorAnalysis).catch(err => {
- console.error(`❌ markUnavailable failed for ${failed.id}: ${err.message}`);
- });
-
console.log(`⚡ Retrying ${args.source} with fallback ${fallback.name} (primary ${failed.name} failed: ${firstError.message})`);
// Run the fallback as a fresh attempt. Pass the configured `fallbackModel`
@@ -327,6 +329,52 @@ export async function runPromptThroughProvider(args) {
* `getFallbackProvider`; the system priority loop already excludes
* `failed.id` by construction.
*/
+// In-flight mark-and-pick work, keyed by the failed provider id. During an
+// N-way failure storm (one stuck provider, many simultaneous in-flight
+// calls) every failure would otherwise independently re-read providers.json
+// (pickFallbackProvider) and re-write provider-status.json (markUnavailable).
+// Sharing the first failure's promise collapses that to a single read +
+// single write. The entry is deleted as soon as it settles, so a genuinely
+// new failure after the storm re-picks against fresh provider status.
+const _fallbackMarkAndPickInFlight = new Map();
+
+/**
+ * Mark the failed provider unavailable and pick its fallback, coalescing
+ * concurrent calls for the same provider id onto one shared promise.
+ * Resolves to the same `{ provider, model }` shape as `pickFallbackProvider`
+ * (or null when no usable fallback exists). The mark is skipped when no
+ * fallback is available — matching the prior ordering where the original
+ * error is rethrown without benching a provider that has no recovery path.
+ *
+ * @param {object} failed — the provider that actually ran and failed
+ * @param {Error} firstError — the execution error (carries message + errorAnalysis)
+ * @returns {Promise<{ provider: object, model: string|null }|null>}
+ */
+function coalesceFallbackMarkAndPick(failed, firstError) {
+ const existing = _fallbackMarkAndPickInFlight.get(failed.id);
+ if (existing) return existing;
+
+ const work = (async () => {
+ const picked = await pickFallbackProvider(failed);
+ if (!picked) return null;
+ await markProviderUnavailableFromError(failed, firstError.message, firstError.errorAnalysis).catch(err => {
+ console.error(`❌ markUnavailable failed for ${failed.id}: ${err.message}`);
+ });
+ return picked;
+ })();
+
+ _fallbackMarkAndPickInFlight.set(failed.id, work);
+ work.finally(() => {
+ // Only clear if no newer entry replaced ours (it can't, given the
+ // synchronous set above, but guard anyway so a future caller can't be
+ // stranded on a deleted slot).
+ if (_fallbackMarkAndPickInFlight.get(failed.id) === work) {
+ _fallbackMarkAndPickInFlight.delete(failed.id);
+ }
+ });
+ return work;
+}
+
async function pickFallbackProvider(failed) {
const toolkit = getAIToolkitInstance();
const providerStatus = toolkit?.services?.providerStatus;
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index 15a0b4c2ae..d8d996f23c 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -1023,6 +1023,63 @@ describe('promptRunner — retry-with-fallback', () => {
}));
expect(status.markUnavailable).not.toHaveBeenCalled();
});
+
+ it('coalesces a 10-concurrent-failure storm into one provider-map read + one mark-unavailable', async () => {
+ // Acceptance for [coalesce-fallback-provider-failure-storm]: when a
+ // stuck provider has N simultaneous in-flight calls, the per-provider
+ // mark-and-pick (getAllProviders + markUnavailable) must run ONCE for
+ // the whole storm — not once per failing call — while every call still
+ // recovers via its own fallback run.
+ const status = mockToolkitWithFallback();
+ // clearAllMocks() resets call history but NOT mockImplementation, so a
+ // throwing noteFallbackHandled impl set by an earlier test would leak in
+ // here as best-effort-suppressed stderr. Reset it to a clean no-op.
+ autoFixer.noteFallbackHandled.mockImplementation(() => {});
+
+ // Gate the provider-map read so the first failure's mark-and-pick stays
+ // in-flight long enough for all 10 failures to pile onto it. Without
+ // this hold the first could settle before later calls reach their catch,
+ // defeating the coalescing the test means to assert.
+ let releaseGetAll;
+ const getAllGate = new Promise((resolve) => { releaseGetAll = resolve; });
+ providers.getAllProviders.mockReturnValue(
+ getAllGate.then(() => ({ activeProvider: null, providers: [primaryCli, primaryApi, fallbackApi] }))
+ );
+
+ runner.executeCliRun.mockImplementation(async (id, _p, _pr, _cwd, _onData, onComplete, _t) => {
+ onComplete({ success: false, error: 'storm boom' });
+ });
+ runner.executeApiRun.mockImplementation(async (id, _p, _m, _pr, _cwd, _ctx, onData, onComplete) => {
+ onData('fallback content');
+ onComplete({ success: true });
+ });
+
+ const calls = Array.from({ length: 10 }, () => runPromptThroughProvider({
+ provider: primaryCli,
+ prompt: 'p',
+ source: 'test',
+ }));
+
+ // Let every call fail its primary run and register on the shared
+ // in-flight mark-and-pick, THEN release the gated read.
+ await new Promise((r) => setTimeout(r, 0));
+ releaseGetAll();
+
+ const results = await Promise.all(calls);
+
+ // Every call recovered through its own fallback run.
+ expect(results).toHaveLength(10);
+ for (const out of results) {
+ expect(out.text).toBe('fallback content');
+ expect(out.usedFallback).toBe(true);
+ }
+ expect(runner.executeApiRun).toHaveBeenCalledTimes(10);
+
+ // ...but the storm read the provider map and benched the provider once.
+ expect(providers.getAllProviders).toHaveBeenCalledTimes(1);
+ expect(status.getFallbackProvider).toHaveBeenCalledTimes(1);
+ expect(status.markUnavailable).toHaveBeenCalledTimes(1);
+ });
});
describe('resolveProviderAndModel', () => {