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: replay an HTTP/2 GOAWAY even when the dead attempt spent the retry budget
Adam Eivy68b4c01bd860
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex f0ad41f491..da63799daa 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -30,7 +30,7 @@ Inheritance mirrors `withGatewayApiKey`: a gateway-backed wrapper with no policy- `createProviderStatusService({ prerequisitesMet })` — host gate for "can this provider run AT ALL?" (its CLI binary present). `getFallbackProvider` consults it on every candidate: task-level, configured, and system-priority alike. Injected rather than computed here because the answer needs host I/O (a PATH probe) and this directory stays self-contained; PortOS supplies `prerequisitesMetForRouting` from `services/providerPrerequisites.js` in `bootstrap.js`. It MUST be synchronous, and a missing / throwing / non-boolean answer deliberately reads as "yes" — an unknown answer has to route exactly as it did before, because emptying the fallback chain is a far worse failure than the late ENOENT the gate exists to prevent.- Time-based state transitions need read-side mirrors. `providerStatus.init()` clears expired `estimatedRecovery` entries; every reader (`getStatus`, `getAllStatuses`, `isAvailable`) must re-apply the same recovery check on read — otherwise providers stay "unavailable" past their recovery deadline until the next process restart.-**Pre-header replay has TWO policies, and the narrow one is not caller-optional** (`internal/preHeaderRetry.js`). `allowReplay` — which only `isReplaySafeLocalRequest` (loopback host, no API key) may grant — covers transient gateway statuses and the whole reset/timeout transport family, any of which the upstream may already have processed; replaying one against a billable provider can bill a second generation. An HTTP/2 `GOAWAY` is the one exception and is replayed **once regardless of `allowReplay`**, because HTTP/2 §6.8 defines the frame as the peer declaring it will not process streams above `lastStreamID` — the request provably never ran. Gating it behind `allowReplay` meant a remote gateway recycling an idle pooled connection on its own schedule (NVIDIA NIM does) killed the run in ~0ms with a bare `UND_ERR_SOCKET`. Adding another code to `REPLAY_SAFE_TRANSPORT_CODES` widens the LOCAL-only set; only a failure carrying GOAWAY's not-processed guarantee belongs in `isUnprocessedGoawayError`. `analyzeError` classifies both as `NETWORK_ERROR` (2m bench) rather than UNKNOWN, so a connection fault that survives its replay reads as connectivity instead of escalating as an unexplained one.+**Pre-header replay has TWO policies, and the narrow one is not caller-optional** (`internal/preHeaderRetry.js`). `allowReplay` — which only `isReplaySafeLocalRequest` (loopback host, no API key) may grant — covers transient gateway statuses and the whole reset/timeout transport family, any of which the upstream may already have processed; replaying one against a billable provider can bill a second generation. An HTTP/2 `GOAWAY` is the one exception and is replayed **once regardless of `allowReplay` and of `maxElapsedMs`**, because HTTP/2 §6.8 defines the frame as the peer declaring it will not process streams above `lastStreamID` — the request provably never ran. Gating it behind `allowReplay` meant a remote gateway recycling an idle pooled connection on its own schedule (NVIDIA NIM does) killed the run in ~0ms with a bare `UND_ERR_SOCKET`. **`maxElapsedMs` bounds the BROAD policy only** — it runs from the first attempt, so the dead attempt's own duration spends it, and charging the GOAWAY replay to it reinstated the same failure from the other end: a gateway draining a connection it had held open for ~5s blew the 2s budget, the one replay never fired, and a `nemotron` persistent-mind run died in 5.1s as a `network-error`. Time-to-GOAWAY is a property of the peer's drain schedule, so gating on it made recovery *less* likely the longer the peer held the stream; `MAX_GOAWAY_REPLAYS` and `maxAttempts` are the only bounds that replay answers to, and it logs a line when it fires, because a run that died on a GOAWAY otherwise reads identically whether the replay failed or never ran. Adding another code to `REPLAY_SAFE_TRANSPORT_CODES` widens the LOCAL-only set; only a failure carrying GOAWAY's not-processed guarantee belongs in `isUnprocessedGoawayError`. `analyzeError` classifies both as `NETWORK_ERROR` (2m bench) rather than UNKNOWN, so a connection fault that survives its replay reads as connectivity instead of escalating as an unexplained one.**`provider.timeout` is a NO-PROGRESS bound in `executeApiRun`, not a wall clock.** A streaming run carries two ceilings, and conflating them is what #7560 fixed: one wall-clock timer could not tell a provider that opened the stream and stalled from one that was actively streaming and merely slow, so a reasoning model spending its whole budget in the hidden channel (NVIDIA NIM's nemotron sends 126 of 128 frames as `reasoning_content`) was killed mid-generation at 300s alongside genuinely dead upstreams.diff --git a/server/lib/aiToolkit/internal/preHeaderRetry.js b/server/lib/aiToolkit/internal/preHeaderRetry.jsindex 016651dc2f..bc2fe4601f 100644--- a/server/lib/aiToolkit/internal/preHeaderRetry.js+++ b/server/lib/aiToolkit/internal/preHeaderRetry.js@@ -140,11 +140,13 @@ function abortableDelay(ms, signal) {* - `allowReplay` (caller-proven local + keyless) covers transient gateway* STATUSES and the whole reset/timeout transport family, any of which the* upstream may already have processed.- * - An HTTP/2 `GOAWAY` is replayed **once regardless of `allowReplay`**,- * because the frame itself proves the request was never processed. Gating it- * behind `allowReplay` meant a remote gateway recycling an idle pooled- * connection killed the run outright; see `isUnprocessedGoawayError`. Bounded- * to `MAX_GOAWAY_REPLAYS`.+ * - An HTTP/2 `GOAWAY` is replayed **once regardless of `allowReplay` and of+ * `maxElapsedMs`**, because the frame itself proves the request was never+ * processed. Gating it behind `allowReplay` meant a remote gateway recycling+ * an idle pooled connection killed the run outright; see+ * `isUnprocessedGoawayError`. Gating it behind the elapsed budget meant the+ * same thing whenever the peer drained a connection it had held open longer+ * than that budget. Bounded to `MAX_GOAWAY_REPLAYS` and to `maxAttempts`.*/export async function fetchWithPreHeaderRetry(fetchAttempt, {signal,@@ -176,15 +178,38 @@ export async function fetchWithPreHeaderRetry(fetchAttempt, {} catch (error) {if (signal?.aborted) throw abortError(signal);const delayMs = baseDelayMs * (2 ** (attempt - 1));- const hasBudget = attempt < maxAttempts && now() - startedAt + delayMs <= maxElapsedMs;const broadReplay = allowReplay && isReplaySafeTransportError(error);// Checked only when the broad policy declined, so a local provider's// GOAWAY keeps spending the broad budget rather than this narrower one.const goawayReplay = !broadReplay&& goawayReplays < MAX_GOAWAY_REPLAYS&& isUnprocessedGoawayError(error);- if ((!broadReplay && !goawayReplay) || !hasBudget) throw error;- if (goawayReplay) goawayReplays += 1;+ if (!broadReplay && !goawayReplay) throw error;+ // `maxElapsedMs` bounds the BROAD policy only. It runs from the first+ // attempt, so it is spent by however long the DEAD attempt took — the+ // right brake on re-dialing a slow, possibly-unhealthy host whose+ // failures may already have been processed. Charging the GOAWAY replay+ // to it made this file's header false in the one case that matters: a+ // remote gateway draining a connection it had held open for ~5s blew the+ // 2s budget, so the single replay never fired and a `nemotron` run died+ // in 5.1s as a `network-error` on a request the frame says was never+ // processed. Time-to-GOAWAY is a property of the gateway's drain+ // schedule, not of our willingness to replay, and gating on it made+ // recovery LESS likely the longer the peer held the stream. That replay+ // is already hard-bounded by MAX_GOAWAY_REPLAYS (and by `maxAttempts`+ // below), and refusing it does not even avoid a second generation — the+ // host reclassifies the run and its tier-3 retry re-issues the whole+ // thing, more expensively and with an investigation task attached.+ const outOfBudget = broadReplay && now() - startedAt + delayMs > maxElapsedMs;+ if (attempt >= maxAttempts || outOfBudget) throw error;+ if (goawayReplay) {+ goawayReplays += 1;+ // Logged because the two failure shapes are indistinguishable after the+ // fact otherwise: a run that died on a GOAWAY reads identically whether+ // the replay fired and failed or never fired at all, and that ambiguity+ // is what hid the budget bug above.+ console.log(`🔁 Replaying a request an HTTP/2 GOAWAY says was never processed (attempt ${attempt} died after ${now() - startedAt}ms)`);+ }await delay(delayMs, signal);}}diff --git a/server/lib/aiToolkit/internal/preHeaderRetry.test.js b/server/lib/aiToolkit/internal/preHeaderRetry.test.jsindex 7d00a535fd..56795cb8e5 100644--- a/server/lib/aiToolkit/internal/preHeaderRetry.test.js+++ b/server/lib/aiToolkit/internal/preHeaderRetry.test.js@@ -98,6 +98,44 @@ describe('pre-header retry policy', () => {expect(fetchAttempt).toHaveBeenCalledTimes(2);});+ it('replays a GOAWAY the dead attempt held past the elapsed budget', async () => {+ // The regression: `maxElapsedMs` runs from the first attempt, so a gateway+ // draining a connection it had held open for ~5s spent the whole 2s budget+ // before the rejection even landed and the one promised replay never fired.+ const goaway = Object.assign(new TypeError('fetch failed'), {+ cause: Object.assign(new Error('HTTP/2: "GOAWAY" frame received with code 0'), { code: 'UND_ERR_SOCKET' }),+ });+ const ok = response(200);+ const fetchAttempt = vi.fn().mockRejectedValueOnce(goaway).mockResolvedValueOnce(ok);+ const now = vi.fn().mockReturnValueOnce(0).mockReturnValue(5121);++ await expect(fetchWithPreHeaderRetry(fetchAttempt, { now, delay: vi.fn() })).resolves.toBe(ok);+ expect(fetchAttempt).toHaveBeenCalledTimes(2);+ });++ it('still refuses the broad transport replay once the elapsed budget is spent', async () => {+ // The other half of the carve-out: a reset may already have been processed,+ // so a slow-failing host keeps its brake even for a local, keyless caller.+ const reset = Object.assign(new TypeError('fetch failed'), {+ cause: Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' }),+ });+ const fetchAttempt = vi.fn().mockRejectedValue(reset);+ const now = vi.fn().mockReturnValueOnce(0).mockReturnValue(5121);++ await expect(fetchWithPreHeaderRetry(fetchAttempt, { allowReplay: true, now, delay: vi.fn() })).rejects.toBe(reset);+ expect(fetchAttempt).toHaveBeenCalledOnce();+ });++ it('never replays a GOAWAY past the caller attempt ceiling', async () => {+ const goaway = Object.assign(new TypeError('fetch failed'), {+ cause: Object.assign(new Error('HTTP/2: "GOAWAY" frame received with code 0'), { code: 'UND_ERR_SOCKET' }),+ });+ const fetchAttempt = vi.fn().mockRejectedValue(goaway);++ await expect(fetchWithPreHeaderRetry(fetchAttempt, { maxAttempts: 1, delay: vi.fn() })).rejects.toBe(goaway);+ expect(fetchAttempt).toHaveBeenCalledOnce();+ });+it('keeps the rest of the transport family behind the local-and-keyless proof', async () => {// A reset may land after the upstream accepted the request, so replaying it// against a billable provider could bill a second generation.