mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
## 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>
149 lines
10 KiB
TypeScript
149 lines
10 KiB
TypeScript
import { spawn, type ChildProcess } from "node:child_process";
|
|
import { randomBytes } from "node:crypto";
|
|
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
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, 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; 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");
|
|
// 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; 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, "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);
|
|
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");
|
|
const signal = AbortSignal.any([AbortSignal.timeout(timeout), ...(options.signal ? [options.signal] : [])]);
|
|
const { cookies } = await this.request.storageState();
|
|
const cookie = cookies.filter(c => (target.hostname === c.domain || c.domain.startsWith(".") && target.hostname.endsWith(c.domain))
|
|
&& (target.pathname === c.path || target.pathname.startsWith(c.path.endsWith("/") ? c.path : `${c.path}/`))
|
|
&& (!c.secure || target.protocol === "https:")
|
|
&& (c.expires === -1 || c.expires * 1000 > Date.now())).map(c => `${c.name}=${c.value}`).join("; ");
|
|
try {
|
|
signal.throwIfAborted();
|
|
const response = await fetch(target, { method: "POST", redirect: "error", signal,
|
|
headers: { "content-type": "application/json", Origin: this.origin, ...(cookie ? { Cookie: cookie } : {}) }, body: JSON.stringify(data) });
|
|
if (!response.ok) { await response.body?.cancel(); throw new ConnectionFailure(`api_status_${response.status}`); }
|
|
return await response.json() as T;
|
|
} catch (error) {
|
|
if (error instanceof ConnectionFailure) throw error;
|
|
throw new ConnectionFailure("sensitive_api_request_failed");
|
|
}
|
|
}
|
|
}
|
|
|
|
async function stopOwnedServer(child: ChildProcess) {
|
|
if (!child.pid) return;
|
|
const exited = () => child.exitCode !== null || child.signalCode !== null;
|
|
const kill = (signal: NodeJS.Signals) => {
|
|
try { process.kill(process.platform === "win32" ? child.pid! : -child.pid!, signal); }
|
|
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
|
|
};
|
|
kill("SIGTERM");
|
|
const deadline = Date.now() + 45_000;
|
|
while (!exited() && Date.now() < deadline) await connectionDelay(100);
|
|
// The group is exclusively the server this function spawned, never an attached target.
|
|
kill("SIGKILL");
|
|
}
|
|
|
|
export async function startConnectionTarget(config: ConnectionConfig, executions: readonly MatrixExecution[], repositoryRoot: string, signal?: AbortSignal) {
|
|
const assertActive = () => { if (signal?.aborted) throw new ConnectionBlock("blocked_target", "test_interrupted"); };
|
|
assertActive();
|
|
if (config.target.mode === "attach") return { origin: targetOrigin(config.target.baseURL), stop: async () => {} };
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-connection-e2e-"));
|
|
let child: ChildProcess | undefined;
|
|
const stop = async () => { if (child) await stopOwnedServer(child); await rm(root, { recursive: true, force: true }); };
|
|
try {
|
|
assertActive();
|
|
const home = path.join(root, "paperclip-home");
|
|
const instance = `connection-${randomBytes(6).toString("hex")}`;
|
|
const port = await reserveRunnerE2EServerPort();
|
|
await mkdir(home, { mode: 0o700 });
|
|
// Only bootstrap essentials are inherited. Selected provider keys enter via UI.
|
|
const env: NodeJS.ProcessEnv = Object.fromEntries(["PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "LANG", "LC_ALL", "NODE_EXTRA_CA_CERTS"].flatMap(key => process.env[key] ? [[key, process.env[key]!]] : []));
|
|
Object.assign(env, {
|
|
PAPERCLIP_HOME: home, PAPERCLIP_INSTANCE_ID: instance, PAPERCLIP_CONFIG: path.join(home, "instances", instance, "config.json"),
|
|
PAPERCLIP_RUNNER_E2E_TEMP_ROOT: root, PAPERCLIP_RUNNER_E2E_PORT: String(port), PAPERCLIP_RUNNER_E2E_SERVER_LOG: path.join(root, "server.log"),
|
|
PAPERCLIP_RUNNER_BINARY: resolvePaperclipRunnerBinaryForHarness(executions, repositoryRoot),
|
|
PAPERCLIP_VITE_CACHE_DIR: path.join(root, "vite-cache"), PAPERCLIP_ANNOUNCEMENTS_ENABLED: "false",
|
|
PAPERCLIP_AGENT_JWT_SECRET: randomBytes(48).toString("hex"), PAPERCLIP_DECISION_SIGNING_SECRET: randomBytes(48).toString("hex"),
|
|
PAPERCLIP_TOOL_ACTION_SIGNING_SECRET: randomBytes(48).toString("hex"), BETTER_AUTH_SECRET: randomBytes(48).toString("hex"),
|
|
});
|
|
assertActive();
|
|
child = spawn(process.execPath, runnerE2ETypeScriptProcessArgs(repositoryRoot, path.join(repositoryRoot, "tests/runner-e2e/server.ts")), { cwd: repositoryRoot, env, detached: process.platform !== "win32", stdio: "ignore" });
|
|
let failed = false;
|
|
child.once("error", () => { failed = true; });
|
|
const origin = `http://127.0.0.1:${port}`;
|
|
const deadline = Date.now() + 180_000;
|
|
while (Date.now() < deadline) {
|
|
assertActive();
|
|
if (failed || child.exitCode !== null) throw new ConnectionBlock("blocked_target", "managed_server_start_failed");
|
|
try {
|
|
const response = await fetch(`${origin}/api/health`, { redirect: "error", signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(1500)]) : AbortSignal.timeout(1500) });
|
|
if (response.ok) { assertActive(); return { origin, stop }; }
|
|
} catch { assertActive(); /* Bounded startup. */ }
|
|
await connectionDelay(500);
|
|
}
|
|
throw new ConnectionBlock("blocked_target", "managed_server_start_timeout");
|
|
} catch (error) { await stop(); throw error; }
|
|
}
|
|
|
|
export async function verifyConnectionTarget(origin: string, config: ConnectionConfig, request?: APIRequestContext) {
|
|
let health: any;
|
|
try {
|
|
const response = request
|
|
? await request.get(`${targetOrigin(origin)}/api/health`, { maxRedirects: 0, timeout: 15_000 })
|
|
: await fetch(`${targetOrigin(origin)}/api/health`, { redirect: "error", signal: AbortSignal.timeout(15_000) });
|
|
if (!(typeof response.ok === "function" ? response.ok() : response.ok)) throw new ConnectionFailure();
|
|
health = await response.json();
|
|
} catch { throw new ConnectionBlock("blocked_target", "target_health_unavailable_or_redirected"); }
|
|
if (typeof health.commit !== "string" || !/^[a-f0-9]{40}$/.test(health.commit)) throw new ConnectionBlock("blocked_target", "target_revision_unavailable");
|
|
if (config.target.mode === "attach" && (health.commit !== config.target.expectedCommit || health.deploymentMode !== config.target.deploymentMode)) throw new ConnectionBlock("blocked_target", "target_identity_mismatch");
|
|
return { commit: health.commit as string, deploymentMode: String(health.deploymentMode) };
|
|
}
|