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: dedupe explicit escalation + escalate on fallback pre-execution throw (#2342)

Adam Eivy828fed591981
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index be3c3f1e89..2d10ea394d 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -628,10 +628,14 @@ export async function runPromptThroughProvider(args) {
runId: undefined, // fresh runId so the failed primary's record stays intact
});
} catch (fallbackError) {
- // ── Tier 4 — escalate ──: every deterministic tier failed. The fallback
- // provider's OWN failure already queued its investigation task (its key
- // was never suppressed), so release the suppressed keys — one surviving
- // task — and rethrow.
+ // ── Tier 4 — escalate ──: every deterministic tier failed. If the
+ // fallback reached the execution layer, its OWN onRunFailed already
+ // queued an investigation task (its key was never suppressed), so just
+ // release the suppressed keys — one surviving task. But if the fallback
+ // threw BEFORE execution (e.g. createRun error), no task was queued and
+ // the suppressed primary/corrected keys would leave ZERO tasks — so
+ // escalate one explicitly first (deduped inside escalateProviderFailure).
+ if (!fallbackError?.effectiveProvider) await escalatePrimaryFailure();
await releaseAllUnresolved();
throw stripFallbackContext(fallbackError);
}
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index dc9be4bbbc..975e2b6e56 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -1384,6 +1384,28 @@ describe('promptRunner — Tier 1 config/env correction (issue #2342)', () => {
expect(autoFixer.noteFallbackStarted).toHaveBeenCalledWith({ provider: 'Primary API', model: 'primary-model' });
});
+ it('escalates explicitly when the Tier-3 fallback throws before execution (no fallback task queued)', async () => {
+ // A fallback that rejects in createRun (pre-execution) fires no onRunFailed,
+ // so no fallback task is queued. With the primary suppressed, that would be
+ // zero investigation tasks — the cascade must escalate one explicitly.
+ mockToolkitWithFallback();
+ const primary = apiProvider({ id: 'primary-api', name: 'Primary API', defaultModel: 'primary-model' }); // no models → Tier 1 declines
+
+ runner.createRun
+ .mockResolvedValueOnce({ runId: 'run-primary' }) // primary
+ .mockRejectedValueOnce(new Error('fallback disabled')); // fallback: pre-execution throw
+ runner.executeApiRun.mockImplementation(async ({ onComplete }) => {
+ onComplete({ success: false, error: 'model gone', errorAnalysis: { category: ERROR_CATEGORIES.MODEL_NOT_FOUND } });
+ });
+
+ await expect(runPromptThroughProvider({ provider: primary, prompt: 'p', source: 'test' }))
+ .rejects.toThrow(/fallback disabled/);
+
+ expect(autoFixer.escalateProviderFailure).toHaveBeenCalledWith(expect.objectContaining({
+ context: expect.objectContaining({ provider: 'Primary API', model: 'primary-model' }),
+ }));
+ });
+
it('keys the Tier-1 corrected-retry task on the run that actually ran when createRun proactively swaps', async () => {
// The corrected retry's createRun proactively swaps to a different provider,
// which then fails — its queued task is keyed on the SWAPPED provider/model,
diff --git a/server/services/autoFixer.js b/server/services/autoFixer.js
index c0c5a071dd..e36e57ec18 100644
--- a/server/services/autoFixer.js
+++ b/server/services/autoFixer.js
@@ -32,6 +32,12 @@ const deferredTasks = new Map(); // errorKey -> { timer }
// fallback's real outcome). Cleared by noteFallbackHandled (success → no task)
// and noteFallbackFailed (failure → the fallback's own task already covers it).
const inFlightFallbacks = new Set(); // errorKey
+// Error keys explicitly escalated via escalateProviderFailure, with the ms
+// timestamp of the escalation. Deduped on its own window (NOT recentErrors,
+// which the primary failure may already have populated) so a concurrent
+// no-fallback failure storm collapses to ONE escalated investigation task
+// instead of one per call. Pruned + reset alongside the other maps.
+const escalatedKeys = new Map(); // errorKey -> number (ms timestamp)
// Circuit breaker: if the SAME resource (errorKey) trips auto-fix more than
// CIRCUIT_MAX_FAILURES times within CIRCUIT_WINDOW_MS, stop creating
@@ -313,15 +319,34 @@ export function noteFallbackFailed({ provider, model }) {
export async function escalateProviderFailure(error) {
const ctx = error?.context || {};
const errorKey = aiProviderErrorKey(ctx.provider, ctx.model);
+ const now = Date.now();
- // Clear any lingering suppression/dedupe/timer for this key so the explicit
- // escalation isn't swallowed and a later failure isn't blocked.
+ // Cancel any pending backstop timer + drop the in-flight suppression for this
+ // key (the cascade already cancelled the timer; make sure it's gone).
inFlightFallbacks.delete(errorKey);
const pending = deferredTasks.get(errorKey);
if (pending) {
clearTimeout(pending.timer);
deferredTasks.delete(errorKey);
}
+
+ // Dedupe on the escalation window, checked+set synchronously (single-threaded)
+ // BEFORE the first await so a concurrent no-fallback failure storm collapses
+ // to ONE task. We can't use isDuplicateError/recentErrors here — the primary
+ // failure's handleAIProviderError may already hold a recentErrors entry for
+ // this key, which would make our FIRST escalation look like a duplicate and
+ // silently swallow it.
+ const lastEscalated = escalatedKeys.get(errorKey);
+ if (lastEscalated && now - lastEscalated < ERROR_DEDUPE_WINDOW) {
+ console.log(`⏭️ Skipping duplicate escalated AI provider failure: ${ctx.provider} (${ctx.model})`);
+ return null;
+ }
+ escalatedKeys.set(errorKey, now);
+ for (const [key, ts] of escalatedKeys.entries()) {
+ if (now - ts >= ERROR_DEDUPE_WINDOW) escalatedKeys.delete(key);
+ }
+ // Clear the primary's dedupe entry so a genuinely NEW failure after this
+ // window can still raise a task through the normal deferred path.
recentErrors.delete(errorKey);
if (tripCircuit(errorKey)) {
@@ -405,6 +430,7 @@ export function _resetAutoFixerForTests() {
inFlightFallbacks.clear();
recentErrors.clear();
failureTimestamps.clear();
+ escalatedKeys.clear();
pendingAutoFixTasks.length = 0;
}
diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.js
index d9762649dc..c5e76bce1f 100644
--- a/server/services/autoFixer.test.js
+++ b/server/services/autoFixer.test.js
@@ -646,12 +646,34 @@ describe('autoFixer — escalateProviderFailure (explicit Tier-4, issue #2342)',
expect(task).toBeTruthy();
});
+ it('dedupes concurrent identical escalations to a single task (no-fallback failure storm)', async () => {
+ const results = await Promise.all([
+ escalateProviderFailure(providerError('Ollama', 'command-r')),
+ escalateProviderFailure(providerError('Ollama', 'command-r')),
+ escalateProviderFailure(providerError('Ollama', 'command-r')),
+ ]);
+ // Only the first escalation creates a task; the rest are deduped within the
+ // window (returns null).
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ expect(results.filter(Boolean)).toHaveLength(1);
+ });
+
it('honors the per-resource circuit breaker (suppresses after >3 escalations in the window)', async () => {
- for (let i = 0; i < 3; i++) await escalateProviderFailure(providerError('Ollama', 'command-r'));
- expect(cos.addTask).toHaveBeenCalledTimes(3);
- // 4th escalation trips the circuit — no task created.
- const suppressed = await escalateProviderFailure(providerError('Ollama', 'command-r'));
- expect(suppressed).toBeNull();
- expect(cos.addTask).toHaveBeenCalledTimes(3);
+ vi.useFakeTimers();
+ try {
+ // Space escalations past the 60s dedupe window so each counts as a
+ // distinct task-worthy failure toward the circuit threshold.
+ for (let i = 0; i < 3; i++) {
+ await escalateProviderFailure(providerError('Ollama', 'command-r'));
+ await vi.advanceTimersByTimeAsync(61000);
+ }
+ expect(cos.addTask).toHaveBeenCalledTimes(3);
+ // 4th distinct escalation (still within the 1h circuit window) trips it.
+ const suppressed = await escalateProviderFailure(providerError('Ollama', 'command-r'));
+ expect(suppressed).toBeNull();
+ expect(cos.addTask).toHaveBeenCalledTimes(3);
+ } finally {
+ vi.useRealTimers();
+ }
});
});