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: stop a sick provider from burning its full timeout on every pinned call
[._.]/ Adam Eivy64a53a43f5e4
diff --git a/server/lib/providerCooldown.js b/server/lib/providerCooldown.jsindex 2f5e2fc3bc..f8bb142e1c 100644--- a/server/lib/providerCooldown.js+++ b/server/lib/providerCooldown.js@@ -31,7 +31,11 @@ import { ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';// work to drain before it can serve the same context again;// the endpoint itself is healthy, so this is a short bench// TIMEOUT/UNKNOWN — 1m: short enough to retry, long enough to skip-// while the immediate workload retries via fallback+// while the immediate workload retries via fallback. For a+// TIMEOUT this is only the FLOOR — see benchMsForTimeout:+// a run that burned its whole budget benches for at least+// that budget, because a shorter bench guarantees the next+// caller repeats the same full-length stall.export const COOLDOWN_MS_BY_CATEGORY = {[ERROR_CATEGORIES.RATE_LIMIT]: 5 * 60 * 1000,[ERROR_CATEGORIES.AUTH_ERROR]: 15 * 60 * 1000,@@ -63,6 +67,10 @@ const SCHEMA_TYPE_CATEGORIES = new Set([]);export const isSchemaTypeCategory = (category) => SCHEMA_TYPE_CATEGORIES.has(category);+// Every runner prints the budget it blew the same way: "CLI run timed out+// after 600000ms". Captured so `benchMsForTimeout` can bench for at least that.+const TIMEOUT_BUDGET_RE = /timed out after +([0-9]+) *ms/i;+/*** True when a failure is specific to the REQUEST or RESPONSE rather than the* provider, so benching the provider would take a healthy service offline for@@ -86,6 +94,34 @@ export function isRequestSpecificCategory(category) {|| isSchemaTypeCategory(category);}+/**+ * How long to bench a run that died on its own wall-clock timeout.+ *+ * A timeout is the one category whose cost is stated in its own message: the+ * run consumed the provider’s entire configured budget before failing.+ * Benching it for less than that budget is self-defeating — the provider+ * becomes eligible again long before the workload that just stalled could have+ * finished, so the next caller pays the same full-length stall. Observed on a+ * pinned local backend whose prompt had outgrown what it could serve: ten+ * consecutive 600s timeouts, each followed by a 60s bench.+ *+ * So take the larger of the category floor and the timeout the failure names,+ * clamped to {@link MAX_BENCH_MS}. Every runner spells the budget the same way+ * ("… timed out after 600000ms" — services/runner.js, aiToolkit/runner.js,+ * lib/cliProviderRun.js); a timeout message with no parsable budget (the TUI+ * retry-exhaustion form) keeps the plain category floor.+ *+ * @param {string|null} message — the failure message+ * @param {number} floorMs — the category’s table value+ * @returns {number} milliseconds+ */+function benchMsForTimeout(message, floorMs) {+ const match = typeof message === 'string' ? message.match(TIMEOUT_BUDGET_RE) : null;+ const budgetMs = match ? Number(match[1]) : NaN;+ if (!Number.isFinite(budgetMs) || budgetMs <= 0) return floorMs;+ return Math.min(Math.max(floorMs, budgetMs), MAX_BENCH_MS);+}+/*** Decide how a failed provider should be benched.*@@ -104,11 +140,12 @@ export function resolveProviderBench(analysis) {if (category === ERROR_CATEGORIES.USAGE_LIMIT) {return { marker: 'usage-limit', category, message, waitTime: analysis?.waitTime ?? null };}+ const floorMs = COOLDOWN_MS_BY_CATEGORY[category] ?? DEFAULT_COOLDOWN_MS;return {marker: 'unavailable',category,message,- waitTimeMs: COOLDOWN_MS_BY_CATEGORY[category] ?? DEFAULT_COOLDOWN_MS,+ waitTimeMs: category === ERROR_CATEGORIES.TIMEOUT ? benchMsForTimeout(message, floorMs) : floorMs,};}diff --git a/server/lib/providerCooldown.test.js b/server/lib/providerCooldown.test.jsindex 4a48ed6ad1..351c205adc 100644--- a/server/lib/providerCooldown.test.js+++ b/server/lib/providerCooldown.test.js@@ -74,6 +74,41 @@ describe('resolveProviderBench', () => {});});+ // A timeout states its own cost. Benching for the 60s floor after a run burned+ // 600s made the provider eligible again nine minutes before the stalled work+ // could have finished, so the next caller repeated the whole stall — ten+ // consecutive 600s timeouts on one local backend in a little over two hours.+ it('benches a timeout for at least the budget the run burned', () => {+ expect(resolveProviderBench({ category: ERROR_CATEGORIES.TIMEOUT, message: 'CLI run timed out after 600000ms' })).toMatchObject({+ marker: 'unavailable',+ waitTimeMs: 600_000,+ });+ });++ it('keeps the category floor when the timeout budget is shorter than it', () => {+ expect(resolveProviderBench({ category: ERROR_CATEGORIES.TIMEOUT, message: 'API execution timed out after 30000ms' })).toMatchObject({+ waitTimeMs: COOLDOWN_MS_BY_CATEGORY[ERROR_CATEGORIES.TIMEOUT],+ });+ });++ // The TUI runner reports retry exhaustion with no number in the message.+ it('keeps the category floor when the timeout message names no budget', () => {+ expect(resolveProviderBench({ category: ERROR_CATEGORIES.TIMEOUT, message: 'Provider request timed out after exhausting TUI retries' })).toMatchObject({+ waitTimeMs: COOLDOWN_MS_BY_CATEGORY[ERROR_CATEGORIES.TIMEOUT],+ });+ expect(resolveProviderBench({ category: ERROR_CATEGORIES.TIMEOUT })).toMatchObject({+ waitTimeMs: COOLDOWN_MS_BY_CATEGORY[ERROR_CATEGORIES.TIMEOUT],+ });+ });++ // provider.timeout is user-configurable, so the parsed budget is not trusted+ // to take a provider offline for longer than any bench may ever last.+ it('clamps an absurd timeout budget to the maximum bench', () => {+ expect(resolveProviderBench({ category: ERROR_CATEGORIES.TIMEOUT, message: 'timed out after 999999999999ms' })).toMatchObject({+ waitTimeMs: MAX_BENCH_MS,+ });+ });+it('treats a missing category as unknown rather than skipping the bench', () => {expect(resolveProviderBench(null)).toMatchObject({marker: 'unavailable',diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex d7ff7d49e5..b35b753188 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -570,6 +570,10 @@ export function assertVisionRunUsedImages(result, requestedProvider) {* @param {boolean} [args.allowFallback=true] — set false when provider/model* identity is part of the feature contract. Disables proactive provider* substitution and every model/provider retry tier after the first attempt.+ * It does NOT disable provider-health bookkeeping: a failure that benches the+ * provider still benches it, so the Providers page and every unpinned caller+ * learn that this provider is sick. The one exception is a usage limit, whose+ * observed-block ledger a pinned caller records itself.* @param {*} [args.responseSchema] — the caller's declared response schema* (issue #2350). A Zod-style schema (`.safeParse`/`.parse`) or a bare* predicate `(parsedValue) => boolean`. When set, the runner enables Tier-2@@ -682,6 +686,39 @@ export async function runPromptThroughProvider(rawArgs) {}if (rawArgs.allowFallback === false) {+ // A pinned caller takes no retry tier — but provider HEALTH is not routing.+ // Skipping the mark here left a provider that had failed every call for+ // hours still reading green on the Providers page, and every *other*+ // (unpinned) caller still routing to it, because the only code path that+ // benches lived inside the fallback cascade this caller opts out of.+ //+ // It also kept the pinned caller itself in a burn loop: the persistent mind+ // is pinned, so ten consecutive runs each spent the provider's full+ // configured timeout before failing. With the mark in place the next pinned+ // call is refused by createRun in milliseconds ("unavailable … and fallback+ // is disabled") until the cooldown expires, so a sick local backend costs+ // one timeout per cooldown window instead of one per wake.+ //+ // `resolveProviderBench` still declines request-specific categories (a+ // content refusal, a bad model id, an off-schema response), so a pinned+ // caller's prompt-specific failure never benches a healthy provider.+ //+ // Only the `unavailable` markers. A usage limit is left exactly as it is+ // today: `markProviderUsageLimit` writes the Usage page's observed-block+ // ledger, and the pinned caller that cares already calls it for this same+ // failure (persistentMindSupervisor autopauses and probes for recovery), so+ // benching it here would record the one block twice.+ if (firstError?.effectiveProvider) {+ await markProviderUnavailableFromError(+ firstError.effectiveProvider,+ firstError.message,+ firstError.errorAnalysis,+ firstError.effectiveModel ?? null,+ { skipUsageLimit: true },+ ).catch((err) => {+ console.error(`❌ markUnavailable failed for ${firstError.effectiveProvider.id}: ${err.message}`);+ });+ }throw stripFallbackContext(firstError);}@@ -1113,8 +1150,11 @@ async function pickFallbackProvider(failed, requestCapabilities) {* the provider unavailable inline (it does this for RATE_LIMIT and* USAGE_LIMIT before firing onComplete) — re-marking would double-* increment `failureCount` and re-write the status file for no gain.+ *+ * `skipUsageLimit` declines the usage-limit marker entirely (bench AND ledger),+ * for a caller that records that marker itself. Everything else still benches.*/-async function markProviderUnavailableFromError(failed, errorMessage, runnerAnalysis, runModel = null) {+async function markProviderUnavailableFromError(failed, errorMessage, runnerAnalysis, runModel = null, { skipUsageLimit = false } = {}) {const toolkit = getAIToolkitInstance();const providerStatus = toolkit?.services?.providerStatus;if (!providerStatus) return;@@ -1130,6 +1170,12 @@ async function markProviderUnavailableFromError(failed, errorMessage, runnerAnalif (!bench) return;if (bench.marker === 'usage-limit') {+ // `skipUsageLimit` callers own this marker themselves — see the pinned+ // branch in runPromptThroughProvider. Returning before the ledger write is+ // the point: recordLimitBlock is deliberately NOT deduped (a repeated+ // refusal refreshes "since last block"), so a second call for the same+ // failure would show up as a second observed block.+ if (skipUsageLimit) return;// Observed-block ledger for the Usage page's free-tier estimated-quota// signal — recorded even when the provider is already benched (a repeated// refusal refreshes "since last block"). Transient 429 retries never reachdiff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.jsindex f3c060b4e2..460e1c61a8 100644--- a/server/services/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -1032,11 +1032,73 @@ describe('promptRunner — retry-with-fallback', () => {})).rejects.toThrow('Pinned provider failed');expect(runner.createRun).toHaveBeenCalledWith(expect.objectContaining({ allowFallback: false }));- expect(status.markUnavailable).not.toHaveBeenCalled();expect(status.getFallbackProvider).not.toHaveBeenCalled();expect(autoFixer.escalateProviderFailure).not.toHaveBeenCalled();});+ // A pin opts out of ROUTING, not out of health reporting. Leaving the mark to+ // the fallback cascade let a provider fail every pinned call for hours while+ // the Providers page stayed green and unpinned callers kept choosing it.+ it('still benches the provider a pinned run failed on', async () => {+ const status = mockToolkitWithFallback();+ runner.executeCliRun.mockImplementation(async ({ onComplete }) => {+ onComplete({ success: false, error: 'CLI run timed out after 600000ms' });+ });++ await expect(runPromptThroughProvider({+ provider: primaryCli,+ prompt: 'p',+ source: 'test',+ allowFallback: false,+ })).rejects.toThrow('CLI run timed out after 600000ms');++ expect(status.markUnavailable).toHaveBeenCalledWith(primaryCli.id, expect.objectContaining({+ reason: 'timeout',+ // The bench covers the budget the run actually burned, so the next pinned+ // wake is refused cheaply instead of stalling for another ten minutes.+ waitTimeMs: 600000,+ }));+ });++ // A usage limit is the one marker a pinned run leaves alone: the caller that+ // cares (persistentMindSupervisor) calls markProviderUsageLimit for this same+ // failure, and its observed-block ledger write is deliberately not deduped, so+ // marking here too would record one block twice.+ it('leaves a pinned usage-limit failure to the caller that owns the marker', async () => {+ const status = mockToolkitWithFallback();+ runner.executeCliRun.mockImplementation(async ({ onComplete }) => {+ onComplete({ success: false, error: "You've hit your usage limit. Try again in 5 hours" });+ });++ await expect(runPromptThroughProvider({+ provider: primaryCli,+ prompt: 'p',+ source: 'test',+ allowFallback: false,+ })).rejects.toThrow(/usage limit/);++ expect(status.markUsageLimit).not.toHaveBeenCalled();+ expect(status.markUnavailable).not.toHaveBeenCalled();+ });++ // Request-specific categories resolve to "don't bench" in providerCooldown, so+ // a pinned caller's bad prompt can't take a healthy provider offline.+ it('does not bench a pinned run that failed for a request-specific reason', async () => {+ const status = mockToolkitWithFallback();+ runner.executeCliRun.mockImplementation(async ({ onComplete }) => {+ onComplete({ success: false, error: 'model not found: bogus-model' });+ });++ await expect(runPromptThroughProvider({+ provider: primaryCli,+ prompt: 'p',+ source: 'test',+ allowFallback: false,+ })).rejects.toThrow(/model not found/);++ expect(status.markUnavailable).not.toHaveBeenCalled();+ });+it('does not retry, bench, or escalate a canceled TUI run', async () => {const status = mockToolkitWithFallback();const primaryTui = tuiProvider({ id: 'primary-tui', name: 'Primary TUI', defaultModel: 'primary-model' });