mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(e2e): retry transient journey API read failures (#22917)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product journeys test real hiring and delegation on a hosted test
stack every day.
> - A journey reads the API many times. The Cloud provider also reads it
when it prepares the lead agent and when it records a new hire.
> - Those provider reads have no retry. One dropped connection fails the
whole journey with `api_request_failed`.
> - #22914 made the failure code visible. The next staging run showed
`api_request_failed` at the moment the hired agent first appeared.
> - This pull request makes `ConnectionApi` repeat a read after a
transient failure. It never repeats a write.
> - The benefit is that a single network failure does not fail a long,
paid journey.
## Linked Issues or Issue Description
Refs #22914
**What happened?**
The QA staging smoke ran `hire-delegate-reuse` alone on the harness pin
that contains #22914. The journey failed with `api_request_failed`,
while the lead agent's hiring run was still running. At that point the
observer records the new agent through `session.own`. In the Cloud
provider, that call reconciles the hire and prepares its budget, with
about 15 API reads and no retry. An earlier failure today was in setup,
during the lead agent's readiness poll. That path also has no retry.
**Expected behavior**
A dropped connection or a gateway error on a read is retried. A real
error, for example a 404, still fails at once. A write is never sent
twice.
**Steps to reproduce**
Run the new `connection-support` test against the previous code. A GET
that fails once with a socket error rejects with `api_request_failed`
instead of reading the next response.
**Paperclip version or commit**
Harness pin 0e4dcd9be8.
## What Changed
- `ConnectionApi.response` tries a GET up to three times when the
request throws or the status is 408, 429, 502, 503 or 504. It waits 250
ms, then 500 ms. Each attempt keeps the caller's timeout. Callers that
use `scopedApi` still stop at the lifecycle deadline.
- POST, PATCH, PUT and DELETE are sent once, as before.
- A note in `tests/runner-e2e/PRODUCT-JOURNEYS.md`.
## Verification
- Red: the new test failed on the previous code (`api_request_failed`
instead of the third response).
- Green: full runner-e2e Vitest suite, `npx vitest run --config
tests/runner-e2e/vitest.config.ts`: 693 files, 11,714 tests pass.
- `node scripts/typecheck-test-projects.mjs tests/runner-e2e` passes.
- SDK input pins refreshed. No change.
- After merge, I will pin `QA_SMOKE_HARNESS_SHA` to the merge commit and
run `hire-delegate-reuse` alone on staging.
## Risks
- Low risk. The change is test harness code only.
- A read that fails three times can take up to three times the caller's
timeout when the caller does not use a lifecycle scope. Journey callers
use `scopedApi`, which keeps the original deadline.
- A read repeated after a cancelled lifecycle can still reach the
server. It is a read, so it does not change state.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, GitHub CLI, read-only AWS S3 evidence access).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4622965a25
commit
87083fe982
8 files changed
+93
-19
No files matched your search
@@ -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`.
|
||||
@@ -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);
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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<void>(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<string, string> } | 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<ReturnType<APIRequestContext["fetch"]>> | 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<T = any>(route: string, options?: { timeoutMs?: number }): Promise<T> { return (await this.response(route, "GET", undefined, options)).json(); }
|
||||
async get<T = any>(route: string, options?: { timeoutMs?: number; retry?: boolean }): Promise<T> { return (await this.response(route, "GET", undefined, options)).json(); }
|
||||
async post<T = any>(route: string, data?: unknown, options?: { timeoutMs?: number }): Promise<T> { return (await this.response(route, "POST", data, options)).json(); }
|
||||
async patch<T = any>(route: string, data: unknown): Promise<T> { 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<T = any>(route: string, data: unknown, options: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<T> {
|
||||
const target = new URL(route, this.origin);
|
||||
|
||||
@@ -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 <T>(route: string): Promise<T> => {
|
||||
try { return await api.get<T>(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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<ConnectionApi, "get">, deadlineAt
|
||||
const expired = new Promise<never>((_resolve, reject) => {
|
||||
timer = setTimeout(() => reject(new JourneyError("failed", "observation_read_deadline")), remaining);
|
||||
});
|
||||
const value = await Promise.race([api.get<T>(route, { timeoutMs: Math.min(30_000, remaining) }), expired]);
|
||||
const value = await Promise.race([api.get<T>(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<ConnectionApi, "get">, 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)));
|
||||
}
|
||||
|
||||
@@ -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: <T>(route: string) => readObserved<T>(route), request: { get: (route: string) => api.response(route) } };
|
||||
const artifactApi = { get: <T>(route: string) => readObserved<T>(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`);
|
||||
|
||||
Reference in new issue
Block a user