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: retry an HTTP/2 GOAWAY on a remote provider instead of failing the run

Adam Eivyc126ded89e0c
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.md
index a3c0aa3003..c68c47d342 100644
--- a/server/lib/aiToolkit/AGENTS.md
+++ b/server/lib/aiToolkit/AGENTS.md
@@ -30,6 +30,8 @@ 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.
+
**`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.
- **Stall bound** = `timeout || provider.timeout || DEFAULT_API_RUN_TIMEOUT_MS`, re-armed by every `reader.read()` that yields bytes. It is the hang detector, and it cuts a silent provider off at exactly the moment the single timer did — reinterpreting the field this way costs no protection, because catching a hung provider is the only job that timer ever actually did.
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.js
index 755a52ea5a..26daaefd8f 100644
--- a/server/lib/aiToolkit/errorDetection.js
+++ b/server/lib/aiToolkit/errorDetection.js
@@ -187,7 +187,13 @@ const ERROR_PATTERNS = [
suggestedFix: 'Check model name and availability in provider settings'
},
{
- pattern: /ECONNREFUSED|ENOTFOUND|network error|connection refused|timeout|ETIMEDOUT/i,
+ // `GOAWAY` / `UND_ERR_SOCKET` are undici's connection-level failures, which
+ // reach here as the flattened cause chain `describeTransportError` builds
+ // (the bare `TypeError: fetch failed` matches nothing). Without them a
+ // remote gateway retiring a pooled connection classified as UNKNOWN and was
+ // escalated to an open-ended tier-4 investigation, when the honest reading
+ // is a transient connectivity fault with a 2m bench.
+ pattern: /ECONNREFUSED|ENOTFOUND|network error|connection refused|timeout|ETIMEDOUT|GOAWAY|UND_ERR_SOCKET/i,
category: ERROR_CATEGORIES.NETWORK_ERROR,
requiresFallback: false,
actionable: false,
diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.js
index dc3315bfa8..75ea6e7b7c 100644
--- a/server/lib/aiToolkit/errorDetection.test.js
+++ b/server/lib/aiToolkit/errorDetection.test.js
@@ -169,6 +169,14 @@ describe('Error Detection', () => {
expect(result.category).toBe(ERROR_CATEGORIES.NETWORK_ERROR);
});
+ it('classifies an HTTP/2 GOAWAY that survived its replay as a network error', () => {
+ // A remote gateway retiring a pooled connection used to land in UNKNOWN,
+ // which escalated to an open-ended tier-4 investigation task.
+ const result = analyzeError('fetch failed: UND_ERR_SOCKET: HTTP/2: "GOAWAY" frame received with code 0');
+ expect(result.hasError).toBe(true);
+ expect(result.category).toBe(ERROR_CATEGORIES.NETWORK_ERROR);
+ });
+
it('should detect timeout errors', () => {
const result = analyzeError('Process timed out after 300000ms');
expect(result.hasError).toBe(true);
diff --git a/server/lib/aiToolkit/internal/preHeaderRetry.js b/server/lib/aiToolkit/internal/preHeaderRetry.js
index 7171d0d798..016651dc2f 100644
--- a/server/lib/aiToolkit/internal/preHeaderRetry.js
+++ b/server/lib/aiToolkit/internal/preHeaderRetry.js
@@ -1,3 +1,7 @@
+// One replay, because the second GOAWAY in a row is a host tearing every
+// connection down rather than one expiring socket — retrying past that only
+// delays the failure the caller has to handle anyway.
+const MAX_GOAWAY_REPLAYS = 1;
const TRANSIENT_GATEWAY_STATUSES = new Set([502, 503, 504, 520, 521, 522, 523, 524]);
const REPLAY_SAFE_TRANSPORT_CODES = new Set([
'ECONNREFUSED',
@@ -9,24 +13,36 @@ const REPLAY_SAFE_TRANSPORT_CODES = new Set([
]);
/**
- * Flatten a fetch rejection's cause chain for run metadata and classification.
- * Node/undici otherwise exposes every pre-header transport failure as the same
- * `TypeError: fetch failed`, with the actionable code nested under `.cause`.
- * Kept inside the vendored toolkit rather than importing PortOS's equivalent
- * helper, preserving this directory's self-contained contract.
+ * Walk a fetch rejection's `cause` chain — depth-bounded, cycle-guarded, and
+ * yielding the bare string a chain can bottom out in. Node/undici exposes every
+ * pre-header transport failure as the same `TypeError: fetch failed` with the
+ * actionable reason nested under `.cause`, so the description and both replay
+ * predicates below all have to look past the outer error.
*/
-export function describeTransportError(error) {
- const parts = [];
+function* causeChain(error) {
const seen = new Set();
let current = error;
for (let depth = 0; current && typeof current === 'object' && depth < 5; depth += 1) {
if (seen.has(current)) break;
seen.add(current);
- if (current.code) parts.push(String(current.code));
- if (current.message) parts.push(String(current.message));
+ yield current;
current = current.cause;
}
- if (typeof current === 'string') parts.push(current);
+ if (typeof current === 'string') yield current;
+}
+
+/**
+ * Flatten a fetch rejection's cause chain for run metadata and classification.
+ * Kept inside the vendored toolkit rather than importing PortOS's equivalent
+ * helper, preserving this directory's self-contained contract.
+ */
+export function describeTransportError(error) {
+ const parts = [];
+ for (const link of causeChain(error)) {
+ if (typeof link === 'string') { parts.push(link); continue; }
+ if (link.code) parts.push(String(link.code));
+ if (link.message) parts.push(String(link.message));
+ }
return parts.join(': ') || String(error);
}
@@ -34,14 +50,38 @@ export function isTransientGatewayStatus(status) {
return TRANSIENT_GATEWAY_STATUSES.has(Number(status));
}
+/**
+ * Is this an HTTP/2 `GOAWAY` — the remote retiring a pooled connection?
+ *
+ * This is the ONE transport failure that is replay-safe against a billable,
+ * remote provider, and the distinction is what `isReplaySafeTransportError`
+ * cannot make. A reset or a socket timeout may land *after* the upstream
+ * accepted the request, so replaying one can bill a second generation; that
+ * whole family therefore stays behind the local-and-keyless gate. A GOAWAY
+ * carries the opposite guarantee — HTTP/2 §6.8 defines it as the peer
+ * declaring it will not process streams above `lastStreamID`, so a request
+ * that dies this way was never handled and one replay produces exactly one
+ * generation.
+ *
+ * Without it a gateway that recycles idle connections on its own schedule
+ * (NVIDIA NIM does) fails a run in ~0ms with a bare `UND_ERR_SOCKET`, which
+ * classifies as UNKNOWN and escalates to a tier-4 investigation task — for a
+ * request that merely picked an expiring socket out of the pool.
+ *
+ * Matched on the message rather than the code: undici raises it as a
+ * `SocketError` (`UND_ERR_SOCKET`) today, and the GOAWAY text is the durable
+ * part of that contract.
+ */
+export function isUnprocessedGoawayError(error) {
+ for (const link of causeChain(error)) {
+ if (/GOAWAY/i.test(typeof link === 'string' ? link : String(link.message || ''))) return true;
+ }
+ return false;
+}
+
export function isReplaySafeTransportError(error) {
- const seen = new Set();
- let current = error;
- for (let depth = 0; current && typeof current === 'object' && depth < 5; depth += 1) {
- if (seen.has(current)) break;
- seen.add(current);
- if (REPLAY_SAFE_TRANSPORT_CODES.has(current.code)) return true;
- current = current.cause;
+ for (const link of causeChain(error)) {
+ if (typeof link !== 'string' && REPLAY_SAFE_TRANSPORT_CODES.has(link.code)) return true;
}
return false;
}
@@ -94,6 +134,17 @@ function abortableDelay(ms, signal) {
* response: before the caller has accepted an OK response and begun reading
* its body. Final responses/errors are returned unchanged so existing provider
* classification and fallback behavior remain authoritative.
+ *
+ * Two replay policies live here, and the narrower one is not optional:
+ *
+ * - `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`.
*/
export async function fetchWithPreHeaderRetry(fetchAttempt, {
signal,
@@ -105,6 +156,7 @@ export async function fetchWithPreHeaderRetry(fetchAttempt, {
delay = abortableDelay,
} = {}) {
const startedAt = now();
+ let goawayReplays = 0;
for (let attempt = 1; ; attempt += 1) {
try {
@@ -125,7 +177,14 @@ export async function fetchWithPreHeaderRetry(fetchAttempt, {
if (signal?.aborted) throw abortError(signal);
const delayMs = baseDelayMs * (2 ** (attempt - 1));
const hasBudget = attempt < maxAttempts && now() - startedAt + delayMs <= maxElapsedMs;
- if (!allowReplay || !isReplaySafeTransportError(error) || !hasBudget) throw error;
+ 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;
await delay(delayMs, signal);
}
}
diff --git a/server/lib/aiToolkit/internal/preHeaderRetry.test.js b/server/lib/aiToolkit/internal/preHeaderRetry.test.js
index bcd0489680..7d00a535fd 100644
--- a/server/lib/aiToolkit/internal/preHeaderRetry.test.js
+++ b/server/lib/aiToolkit/internal/preHeaderRetry.test.js
@@ -5,6 +5,7 @@ import {
isReplaySafeTransportError,
isReplaySafeLocalRequest,
isTransientGatewayStatus,
+ isUnprocessedGoawayError,
} from './preHeaderRetry.js';
const response = (status, cancel = vi.fn()) => ({ status, body: { cancel } });
@@ -74,6 +75,45 @@ describe('pre-header retry policy', () => {
expect(fetchAttempt).toHaveBeenCalledOnce();
});
+ it('replays a GOAWAY once even for a billable remote provider', async () => {
+ // The regression: a gateway recycling an idle pooled connection failed the
+ // run in ~0ms because GOAWAY was gated behind the local-and-keyless proof.
+ 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);
+
+ await expect(fetchWithPreHeaderRetry(fetchAttempt, { delay: vi.fn() })).resolves.toBe(ok);
+ expect(fetchAttempt).toHaveBeenCalledTimes(2);
+ });
+
+ it('gives up after the single GOAWAY replay a remote provider is allowed', 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, { delay: vi.fn() })).rejects.toBe(goaway);
+ expect(fetchAttempt).toHaveBeenCalledTimes(2);
+ });
+
+ 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.
+ const reset = Object.assign(new TypeError('fetch failed'), {
+ cause: Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' }),
+ });
+ const fetchAttempt = vi.fn().mockRejectedValue(reset);
+
+ await expect(fetchWithPreHeaderRetry(fetchAttempt, { delay: vi.fn() })).rejects.toBe(reset);
+ expect(fetchAttempt).toHaveBeenCalledOnce();
+ expect(isUnprocessedGoawayError(reset)).toBe(false);
+ expect(isUnprocessedGoawayError(Object.assign(new TypeError('fetch failed'), {
+ cause: Object.assign(new Error('HTTP/2: "GOAWAY" frame received with code 0'), { code: 'UND_ERR_SOCKET' }),
+ }))).toBe(true);
+ });
+
it('returns the final retryable response intact when the attempt budget is exhausted', async () => {
const final = response(504);
const fetchAttempt = vi.fn().mockResolvedValue(final);
diff --git a/server/lib/openAiChatStream.js b/server/lib/openAiChatStream.js
index c4b99a404b..eb6b4b496c 100644
--- a/server/lib/openAiChatStream.js
+++ b/server/lib/openAiChatStream.js
@@ -21,7 +21,7 @@
*/
import { readResponseJson } from './readResponseJson.js';
-import { fetchWithPreHeaderRetry, isReplaySafeLocalRequest } from './aiToolkit/internal/preHeaderRetry.js';
+import { describeTransportError, fetchWithPreHeaderRetry, isReplaySafeLocalRequest } from './aiToolkit/internal/preHeaderRetry.js';
/**
* Parse one OpenAI-style SSE `data:` line into its content/reasoning delta and,
@@ -294,7 +294,10 @@ export async function* iterateOpenAiChat({
}), {
signal: requestSignal,
allowReplay: isReplaySafeLocalRequest({ endpoint, apiKey }),
- }).catch((err) => ({ ok: false, status: 0, error: err.message }));
+ // `describeTransportError`, not `err.message`: undici reports every transport
+ // failure as the same opaque `TypeError: fetch failed`, with the actionable
+ // reason (a GOAWAY that survived its replay) only on the nested cause chain.
+ }).catch((err) => ({ ok: false, status: 0, error: describeTransportError(err) }));
try {
let response = await post(includeUsage);