diff --git a/tests/runner-e2e/PRODUCT-JOURNEYS.md b/tests/runner-e2e/PRODUCT-JOURNEYS.md index ac51dd4e3b7..4a5fb881869 100644 --- a/tests/runner-e2e/PRODUCT-JOURNEYS.md +++ b/tests/runner-e2e/PRODUCT-JOURNEYS.md @@ -577,3 +577,9 @@ lead and hired-agent runs. Its idle check still requires every run to succeed. A journey failure from a hosted API call keeps its fixed code, such as `api_status_500` or `api_request_failed`; other errors stay `journey_operation_failed`. + +`ConnectionApi` repeats a JSON read up to three times after a dropped connection +or a 408, 429, 502, 503 or 504 response, inside the caller's original timeout. It +honors a `Retry-After` of up to five seconds. It never repeats a write or a binary +download (`bytes`). The observed reader opts out, so its own retry loop records +every transient failure in `observation-read-failures.json`. diff --git a/tests/runner-e2e/connection-config.ts b/tests/runner-e2e/connection-config.ts index c38fbc14820..6b1e50ae3f0 100644 --- a/tests/runner-e2e/connection-config.ts +++ b/tests/runner-e2e/connection-config.ts @@ -63,6 +63,12 @@ export function parseConnectionConfig(input: unknown): ConnectionConfig { /** Only harness-owned error codes may enter a retained report. */ export class ConnectionFailure extends Error {} +/** A dropped connection or a gateway, throttling or timeout status. A read that + * failed this way is safe to repeat; nothing else is. */ +export function isTransientConnectionFailure(error: unknown): error is ConnectionFailure { + return error instanceof ConnectionFailure && /^(api_request_failed|api_status_(408|429|502|503|504))$/.test(error.message); +} + export class ConnectionBlock extends Error { constructor(readonly reason: "awaiting_user" | "missing_credential" | "blocked_target", readonly code: string) { super(code); diff --git a/tests/runner-e2e/connection-support.test.ts b/tests/runner-e2e/connection-support.test.ts index 7f5978eb56b..c83a21fb6e6 100644 --- a/tests/runner-e2e/connection-support.test.ts +++ b/tests/runner-e2e/connection-support.test.ts @@ -154,6 +154,51 @@ describe("target and selected credential boundaries", () => { await expect(api.get("/api/health", { timeoutMs: 0 })).rejects.toThrow("invalid_api_timeout"); expect(fetch).toHaveBeenCalledTimes(2); }); + it("retries a transient read failure but never repeats a write", async () => { + const ok = { ok: () => true, status: () => 200, json: async () => ({ id: "agent" }) }; + const unavailable = { ok: () => false, status: () => 503 }; + const fetch = vi.fn().mockRejectedValueOnce(new Error("socket hang up")).mockResolvedValueOnce(unavailable).mockResolvedValueOnce(ok); + const api = new ConnectionApi({ fetch } as any, "https://qa.test.paperclip.app"); + await expect(api.get("/api/agents/agent")).resolves.toEqual({ id: "agent" }); + expect(fetch).toHaveBeenCalledTimes(3); + fetch.mockReset().mockRejectedValue(new Error("socket hang up")); + await expect(api.get("/api/agents/agent")).rejects.toThrow("api_request_failed"); + expect(fetch).toHaveBeenCalledTimes(3); + fetch.mockReset().mockResolvedValue({ ok: () => false, status: () => 404 }); + await expect(api.get("/api/agents/agent")).rejects.toThrow("api_status_404"); + expect(fetch).toHaveBeenCalledTimes(1); + for (const method of ["post", "patch", "delete"] as const) { + fetch.mockReset().mockRejectedValueOnce(new Error("socket hang up")).mockResolvedValue(ok); + await expect((api as any)[method]("/api/agents/agent", {})).rejects.toThrow("api_request_failed"); + expect(fetch).toHaveBeenCalledTimes(1); + } + // Binary downloads and readers with their own retry ledger stay single attempts. + fetch.mockReset().mockResolvedValueOnce(unavailable).mockResolvedValue({ ...ok, body: async () => Buffer.from("x") }); + await expect(api.bytes("/api/attachments/file/content")).rejects.toThrow("api_status_503"); + expect(fetch).toHaveBeenCalledTimes(1); + fetch.mockReset().mockResolvedValueOnce(unavailable).mockResolvedValue(ok); + await expect(api.get("/api/agents/agent", { retry: false })).rejects.toThrow("api_status_503"); + expect(fetch).toHaveBeenCalledTimes(1); + }); + it("honors a bounded Retry-After and keeps every attempt inside the caller's timeout", async () => { + vi.useFakeTimers(); + try { + const ok = { ok: () => true, status: () => 200, json: async () => ({ id: "agent" }) }; + const throttled = { ok: () => false, status: () => 429, headers: () => ({ "retry-after": "2" }) }; + const fetch = vi.fn().mockResolvedValueOnce(throttled).mockResolvedValueOnce(ok); + const api = new ConnectionApi({ fetch } as any, "https://qa.test.paperclip.app"); + const read = api.get("/api/agents/agent", { timeoutMs: 10_000 }); + await vi.advanceTimersByTimeAsync(1_999); + expect(fetch).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + await expect(read).resolves.toEqual({ id: "agent" }); + expect((fetch.mock.calls[1]![1] as { timeout: number }).timeout).toBeLessThanOrEqual(8_000); + // No retry when the wait would leave no useful time before the caller's timeout. + fetch.mockReset().mockResolvedValue(throttled); + await expect(api.get("/api/agents/agent", { timeoutMs: 2_500 })).rejects.toThrow("api_status_429"); + expect(fetch).toHaveBeenCalledTimes(1); + } finally { vi.useRealTimers(); } + }); it("keeps scoped requests on tenant APIs and bounds extended probe timeouts", async () => { const fetch = vi.fn(async (_url: string, _options: unknown) => ({ ok: () => true, json: async () => ({ passed: true }) })); const api = new ConnectionApi({ fetch } as any, "https://qa.test.paperclip.app"); diff --git a/tests/runner-e2e/connection-target.ts b/tests/runner-e2e/connection-target.ts index e72cb30b16a..f03ca0c129a 100644 --- a/tests/runner-e2e/connection-target.ts +++ b/tests/runner-e2e/connection-target.ts @@ -7,33 +7,51 @@ import type { APIRequestContext } from "@playwright/test"; import { reserveRunnerE2EServerPort } from "./ports.js"; import { resolvePaperclipRunnerBinaryForHarness } from "./harness-env.js"; import { runnerE2ETypeScriptProcessArgs } from "./web-server-command.js"; -import { ConnectionBlock, ConnectionFailure, targetOrigin, type ConnectionConfig } from "./connection-config.js"; +import { ConnectionBlock, ConnectionFailure, isTransientConnectionFailure, targetOrigin, type ConnectionConfig } from "./connection-config.js"; import type { MatrixExecution } from "./types.js"; export const connectionDelay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +const maxRetryAfterMs = 5_000; +/** Bounded Retry-After in milliseconds (seconds form only), else the fixed backoff. */ +function retryDelay(response: { headers?: () => Record } | undefined, attempt: number) { + const seconds = Number(response?.headers?.()["retry-after"]); + return Number.isFinite(seconds) && seconds >= 0 ? Math.min(maxRetryAfterMs, seconds * 1000) : 250 * attempt; +} + /** No raw response bodies, callback URLs, headers, or Playwright diagnostics escape. */ export class ConnectionApi { constructor(readonly request: APIRequestContext, readonly origin: string) {} - async response(route: string, method = "GET", data?: unknown, options: { timeoutMs?: number } = {}) { + async response(route: string, method = "GET", data?: unknown, options: { timeoutMs?: number; retry?: boolean } = {}) { const target = new URL(route, this.origin); if (!route.startsWith("/api/") || target.origin !== this.origin || !target.pathname.startsWith("/api/")) throw new ConnectionFailure("invalid_api_route"); const timeout = options.timeoutMs ?? 30_000; if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 120_000) throw new ConnectionFailure("invalid_api_timeout"); - try { - const response = await this.request.fetch(`${this.origin}${route}`, { method, headers: { Origin: this.origin }, ...(data === undefined ? {} : { data }), maxRedirects: 0, timeout }); - if (!response.ok()) throw new ConnectionFailure(`api_status_${response.status()}`); - return response; - } catch (error) { - if (error instanceof Error && /^api_status_\d+$/.test(error.message)) throw error; - throw new ConnectionFailure("api_request_failed"); + // A read is safe to repeat: one dropped connection or gateway error must not + // fail a long journey. Writes, binary downloads and callers that keep their + // own retry ledger opt out. All attempts share the caller's timeout. + const deadline = Date.now() + timeout; + const attempts = method === "GET" && options.retry !== false ? 3 : 1; + for (let attempt = 1; ; attempt++) { + let failure: ConnectionFailure, response: Awaited> | undefined; + try { + response = await this.request.fetch(`${this.origin}${route}`, { method, headers: { Origin: this.origin }, ...(data === undefined ? {} : { data }), maxRedirects: 0, + timeout: attempt === 1 ? timeout : Math.max(1, deadline - Date.now()) }); + if (response.ok()) return response; + failure = new ConnectionFailure(`api_status_${response.status()}`); + } catch { + failure = new ConnectionFailure("api_request_failed"); + } + const wait = retryDelay(response, attempt); + if (attempt >= attempts || !isTransientConnectionFailure(failure) || Date.now() + wait + 1_000 > deadline) throw failure; + await connectionDelay(wait); } } - async get(route: string, options?: { timeoutMs?: number }): Promise { return (await this.response(route, "GET", undefined, options)).json(); } + async get(route: string, options?: { timeoutMs?: number; retry?: boolean }): Promise { return (await this.response(route, "GET", undefined, options)).json(); } async post(route: string, data?: unknown, options?: { timeoutMs?: number }): Promise { return (await this.response(route, "POST", data, options)).json(); } async patch(route: string, data: unknown): Promise { return (await this.response(route, "PATCH", data)).json(); } async delete(route: string) { await this.response(route, "DELETE"); } - async bytes(route: string) { return (await this.response(route)).body(); } + async bytes(route: string) { return (await this.response(route, "GET", undefined, { retry: false })).body(); } /** Keep fixture credentials out of Playwright request traces. */ async postSensitive(route: string, data: unknown, options: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise { const target = new URL(route, this.origin); diff --git a/tests/runner-e2e/product-journeys/hire-delegate-flow.ts b/tests/runner-e2e/product-journeys/hire-delegate-flow.ts index 4fc18a92542..f7f11003d20 100644 --- a/tests/runner-e2e/product-journeys/hire-delegate-flow.ts +++ b/tests/runner-e2e/product-journeys/hire-delegate-flow.ts @@ -6,7 +6,7 @@ import { expect, type Page } from "@playwright/test"; import { buildAgentMentionHref, buildProjectMentionHref, parseAgentMentionHref, parseProjectMentionHref } from "../../../packages/shared/src/project-mentions.js"; import { sendChatMessage, readChatOutputDocument, type ChatIssue, type ChatRun } from "../chat-flow.js"; import { assertChatHire, mutableIssueSnapshot } from "../chat-hardening.js"; -import { ConnectionFailure } from "../connection-config.js"; +import { isTransientConnectionFailure } from "../connection-config.js"; import { assertHireAuditCoverage, assertHireBinding, assertHireDocument, assertHireRuns, assertHireTaskCreation, hireDelegateNames, hireResultLinkMatches, hireRunIssueId, observedHireResources, readHireConnectionChoice, type HireScope } from "./hire-delegate-evidence.js"; import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js"; import { sendHireHandoffMessage } from "./hire-delegate-composer.js"; @@ -70,8 +70,7 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target const readObserved = async (route: string): Promise => { try { return await api.get(route); } catch (error) { - if (error instanceof ConnectionFailure && (error.message === "api_request_failed" - || /^api_status_(408|429|502|503|504)$/.test(error.message))) { + if (isTransientConnectionFailure(error)) { throw new HireReadTransportError("hire_observation_transport_unavailable"); } throw error; diff --git a/tests/runner-e2e/product-journeys/observation-read.test.ts b/tests/runner-e2e/product-journeys/observation-read.test.ts index 9cae6917f04..420ec1face7 100644 --- a/tests/runner-e2e/product-journeys/observation-read.test.ts +++ b/tests/runner-e2e/product-journeys/observation-read.test.ts @@ -32,7 +32,7 @@ describe("bounded observation reads", () => { expect(get.mock.calls[0]?.[1]?.timeoutMs).toBeGreaterThan(0); expect(get.mock.calls[0]?.[1]?.timeoutMs).toBeLessThanOrEqual(50); await createObservedReader({ get }, Date.now() + 100_000).get("/api/issues/owned"); - expect(get.mock.calls[1]?.[1]).toEqual({ timeoutMs: 30_000 }); + expect(get.mock.calls[1]?.[1]).toEqual({ timeoutMs: 30_000, retry: false }); }); it.each(["api_request_failed", "api_status_408", "api_status_429", "api_status_502", "api_status_503", "api_status_504"])("retains and retries %s without replaying work", async code => { vi.useFakeTimers(); diff --git a/tests/runner-e2e/product-journeys/observation-read.ts b/tests/runner-e2e/product-journeys/observation-read.ts index 935abdc5e3d..898ad61b622 100644 --- a/tests/runner-e2e/product-journeys/observation-read.ts +++ b/tests/runner-e2e/product-journeys/observation-read.ts @@ -1,6 +1,6 @@ import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; -import { ConnectionFailure } from "../connection-config.js"; +import { ConnectionFailure, isTransientConnectionFailure } from "../connection-config.js"; import type { ConnectionApi } from "../connection-target.js"; import { JourneyError } from "./types.js"; @@ -20,7 +20,7 @@ export function createObservedReader(api: Pick, deadlineAt const expired = new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new JourneyError("failed", "observation_read_deadline")), remaining); }); - const value = await Promise.race([api.get(route, { timeoutMs: Math.min(30_000, remaining) }), expired]); + const value = await Promise.race([api.get(route, { timeoutMs: Math.min(30_000, remaining), retry: false }), expired]); if (Date.now() >= deadline()) throw new JourneyError("failed", "observation_read_deadline"); return value; } @@ -28,7 +28,7 @@ export function createObservedReader(api: Pick, deadlineAt if (!(error instanceof ConnectionFailure)) throw error; const code = error.message; if (code === "api_request_failed" || /^api_status_[1-5][0-9]{2}$/.test(code)) failures.push({ route, code }); - if (!(code === "api_request_failed" || /^api_status_(408|429|502|503|504)$/.test(code))) throw error; + if (!isTransientConnectionFailure(error)) throw error; const remaining = deadline() - Date.now(); if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(1000, remaining))); } diff --git a/tests/runner-e2e/product-journeys/repository-continuation-flow.ts b/tests/runner-e2e/product-journeys/repository-continuation-flow.ts index ebeb43c4fc2..89b4db416df 100644 --- a/tests/runner-e2e/product-journeys/repository-continuation-flow.ts +++ b/tests/runner-e2e/product-journeys/repository-continuation-flow.ts @@ -70,7 +70,7 @@ export async function runRepositoryContinuation(context: JourneyContext, session && run.nativePhase === "committed" && run.resultJson?.finalizationPhase === "committed") && state.interactions.every(row => row.status !== "pending"), "repository_task_not_completed"); // Use the attached target's origin for the common registration/download oracle. - const artifactApi = { get: (route: string) => readObserved(route), request: { get: (route: string) => api.response(route) } }; + const artifactApi = { get: (route: string) => readObserved(route), request: { get: (route: string) => api.response(route, "GET", undefined, { retry: false }) } }; const bundle = async (name: string, runId: string) => { const [artifact] = await readRegisteredArtifacts(artifactApi, created.issueId, runId, [name]); const bytes = await api.bytes(`/api/attachments/${artifact!.attachmentId}/content?download=1`);