mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
fix(e2e): normalize remote admission failures without private diagnostics
Preserve typed HTTP and transport timeout classification while removing raw response bodies and causes from admission reports. Reject unknown failures and malformed JSON without weakening ownership or deadline checks. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
6ed490ee43
commit
812b9e1a65
6 files changed
+154
-27
No files matched your search
@@ -1361,8 +1361,10 @@ change saved evidence or start another poll. Missing reads
|
||||
cannot admit a lease; successful ownership/status reads are retained.
|
||||
Admission and observer setup failures save bounded, allowlisted read status,
|
||||
run-stage, lease-count and classified read-failure evidence;
|
||||
this evidence does not infer a provider-side cause. Persistent API failures retain
|
||||
their real cause and infrastructure classification. A recovered API failure does
|
||||
this evidence does not infer a provider-side cause. Admission GET failures are normalized once to fixed endpoint labels, generic
|
||||
messages and explicit failure classes. Typed HTTP status and pinned transport
|
||||
timeout shapes preserve infrastructure classification without response bodies,
|
||||
URLs or original cause chains in thrown errors. Malformed responses never admit. A recovered API failure does
|
||||
not reclassify a later successfully observed state timeout.
|
||||
The initial provider's instruction-file read window remains 20 seconds after
|
||||
provider startup, and no action is published before the observer is armed.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { APIRequestContext, APIResponse } from "@playwright/test";
|
||||
import { RunnerApi } from "./api.js";
|
||||
import { RunnerApi, RunnerApiHttpError } from "./api.js";
|
||||
const response = (status: number, data: unknown = {}): APIResponse => ({
|
||||
ok: () => status >= 200 && status < 300, status: () => status,
|
||||
json: async () => data, text: async () => JSON.stringify(data), url: () => "http://fixture.invalid/instructions",
|
||||
@@ -41,3 +41,13 @@ it("passes a bounded GET timeout to the request transport without changing its r
|
||||
await expect(api.get("/api/heartbeat-runs/run", { timeout: 1234 })).resolves.toEqual({ status: "running" });
|
||||
expect(get).toHaveBeenCalledExactlyOnceWith("/api/heartbeat-runs/run", { timeout: 1234 });
|
||||
});
|
||||
|
||||
|
||||
it("preserves GET HTTP status separately from diagnostic text", async () => {
|
||||
vi.stubEnv("PAPERCLIP_RUNNER_E2E_PORT", "3100");
|
||||
const api = new RunnerApi({ get: vi.fn(async () => response(503, { error: "PRIVATE" })) } as unknown as APIRequestContext);
|
||||
const error = await api.get("/api/environments/env/leases").catch(error => error);
|
||||
expect(error).toBeInstanceOf(RunnerApiHttpError);
|
||||
if (!(error instanceof RunnerApiHttpError)) throw new Error("Expected typed HTTP error");
|
||||
expect(error.status).toBe(503);
|
||||
});
|
||||
+17
-1
@@ -9,6 +9,22 @@ async function failureMessage(response: APIResponse, method: string) {
|
||||
return `${method} ${response.url()} returned ${response.status()}${text ? `: ${text}` : ""}`;
|
||||
}
|
||||
|
||||
/** Preserve HTTP status independently of diagnostic response text. */
|
||||
export class RunnerApiHttpError extends Error {
|
||||
constructor(readonly status: number, message: string) { super(message); this.name = "RunnerApiHttpError"; }
|
||||
}
|
||||
|
||||
/** Admission-only diagnostics. Never retain the rejected value or its cause. */
|
||||
export class RemoteAdmissionReadError extends Error {
|
||||
constructor(
|
||||
readonly endpoint: "issue" | "run" | "leases",
|
||||
readonly failureClass: "candidate_failure" | "transient_infrastructure" | "permanent_infrastructure",
|
||||
) {
|
||||
super(`Remote admission ${endpoint} read failed (${failureClass}); diagnostics withheld`);
|
||||
this.name = "RemoteAdmissionReadError";
|
||||
}
|
||||
}
|
||||
|
||||
export class RunnerApi {
|
||||
readonly baseURL: string;
|
||||
|
||||
@@ -20,7 +36,7 @@ export class RunnerApi {
|
||||
|
||||
async get<T>(path: string, options?: { timeout: number }): Promise<T> {
|
||||
const response = await (options ? this.request.get(path, options) : this.request.get(path));
|
||||
if (!response.ok()) throw new Error(await failureMessage(response, "GET"));
|
||||
if (!response.ok()) throw new RunnerApiHttpError(response.status(), await failureMessage(response, "GET"));
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ObservedStateTimeout } from "./api.js";
|
||||
import { ObservedStateTimeout, RemoteAdmissionReadError } from "./api.js";
|
||||
import type { FailureClass } from "./types.js";
|
||||
|
||||
const TRANSIENT =
|
||||
@@ -21,7 +21,7 @@ const SANDBOX_TRANSFER_TIMEOUT =
|
||||
/RPC call "environmentSync(?:In|Out)" timed out after \d+ms/i;
|
||||
|
||||
export function classifyFailure(error: unknown): FailureClass {
|
||||
if (error instanceof ObservedStateTimeout) return error.failureClass;
|
||||
if (error instanceof ObservedStateTimeout || error instanceof RemoteAdmissionReadError) return error.failureClass;
|
||||
const message =
|
||||
error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
||||
if (/browser bootstrap failed before task creation/i.test(message))
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { APIRequestContext, APIResponse } from "@playwright/test";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { classifyFailure } from "./failure-classifier.js";
|
||||
import { ObservedStateTimeout } from "./api.js";
|
||||
import { ObservedStateTimeout, RemoteAdmissionReadError, RunnerApi, RunnerApiHttpError } from "./api.js";
|
||||
import { createRemoteNativeBootstrap } from "./remote-native-bootstrap.js";
|
||||
import type { RemoteFixtureApi, RemoteNativeFixture } from "./remote-native-fixtures.js";
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
afterEach(() => { vi.useRealTimers(); vi.unstubAllEnvs(); });
|
||||
|
||||
function harness(timeoutMs = 60_000) {
|
||||
const order: string[] = [];
|
||||
@@ -192,7 +193,7 @@ it.each(["/api/issues/issue", "/api/heartbeat-runs/run", "/api/environments/env/
|
||||
const h = harness(43_000); h.bootstrap.prompt("missing-read");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => { if (path === failedPath) throw new Error("PRIVATE API ERROR"); return original(path); });
|
||||
const delivery = expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("PRIVATE API ERROR");
|
||||
const delivery = expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("diagnostics withheld");
|
||||
await vi.advanceTimersByTimeAsync(1000); await delivery;
|
||||
expect(h.bind).not.toHaveBeenCalled(); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).not.toContain("PRIVATE");
|
||||
@@ -257,15 +258,15 @@ it.each(["terminal", "run-owner", "issue-owner"])("rejects %s immediately with a
|
||||
expect(h.api.get).toHaveBeenCalledTimes(3); expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains permanent 503 reads as a typed infrastructure timeout with the real cause", async () => {
|
||||
it("retains persistent 503 classification without its raw cause", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(43_000); h.bootstrap.prompt("503");
|
||||
const cause = new Error("GET /api/environments/env/leases returned 503: PRIVATE BODY");
|
||||
const cause = new RunnerApiHttpError(503, "GET /api/environments/env/leases returned 503: PRIVATE BODY");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => { if (path.endsWith("/leases")) throw cause; return original(path); });
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1000); const error = await delivery;
|
||||
expect(error).toBeInstanceOf(ObservedStateTimeout); expect(error.cause).toBe(cause);
|
||||
expect(error).toBeInstanceOf(ObservedStateTimeout); expect(error.cause).toBeUndefined();
|
||||
expect(classifyFailure(error)).toBe("transient_infrastructure");
|
||||
expect(error.message).not.toContain("PRIVATE");
|
||||
expect(h.input.evidence.mock.calls[0]![1]).toMatchObject({ readFailureClass: "transient_infrastructure" });
|
||||
@@ -279,7 +280,7 @@ it.each([true, false])("clears a recovered 503 cause before %s admission or obse
|
||||
const original = h.api.get.getMockImplementation()!; let failed = false;
|
||||
h.api.get.mockImplementation(async path => {
|
||||
if (path.endsWith("/leases")) {
|
||||
if (!failed) { failed = true; throw new Error("503 PRIVATE BODY"); }
|
||||
if (!failed) { failed = true; throw new RunnerApiHttpError(503, "PRIVATE BODY"); }
|
||||
if (!admits) return [];
|
||||
}
|
||||
return original(path);
|
||||
@@ -300,3 +301,75 @@ it("bounds an unresponsive read at admission without launching replacement reads
|
||||
expect(classifyFailure(error)).toBe("transient_infrastructure");
|
||||
expect(h.api.get).toHaveBeenCalledTimes(3); expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
it.each([
|
||||
["Playwright TimeoutError", Object.assign(new Error("Timeout 1000ms exceeded. PRIVATE"), { name: "TimeoutError" }), "transient_infrastructure"],
|
||||
["Playwright fetch timeout", new Error("apiRequestContext.get: Timeout 1000ms exceeded. PRIVATE"), "transient_infrastructure"],
|
||||
["server fetch timeout", new Error("Timeout 1000ms exceeded PRIVATE"), "transient_infrastructure"],
|
||||
["connection reset", new Error("apiRequestContext.get: read ECONNRESET PRIVATE"), "transient_infrastructure"],
|
||||
["undefined", undefined, "candidate_failure"],
|
||||
["null", null, "candidate_failure"],
|
||||
["private string", "PRIVATE 503 TimeoutError", "candidate_failure"],
|
||||
["unknown object", { message: "PRIVATE", status: 503 }, "candidate_failure"],
|
||||
])("normalizes %s rejection without exposing transport diagnostics", async (_label, rejected, failureClass) => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(43_000); h.bootstrap.prompt("safe-errors");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => { if (path.endsWith("/leases")) throw rejected; return original(path); });
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1000); const error = await delivery;
|
||||
expect(classifyFailure(error)).toBe(failureClass);
|
||||
expect(error.cause).toBeUndefined();
|
||||
expect(error.message.length).toBeLessThan(1024);
|
||||
expect(error.stack).not.toContain("PRIVATE");
|
||||
expect(JSON.stringify(error)).not.toContain("PRIVATE");
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).not.toContain("PRIVATE");
|
||||
expect(h.input.evidence.mock.calls[0]![1]).toMatchObject({ leasesRead: "rejected", readFailureClass: failureClass });
|
||||
expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([[503, "transient_infrastructure"], [403, "permanent_infrastructure"], [400, "candidate_failure"]])(
|
||||
"normalizes actual RunnerApi HTTP %s status independently of its private body", async (status, failureClass) => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
vi.stubEnv("PAPERCLIP_RUNNER_E2E_PORT", "3100");
|
||||
const h = harness(43_000); h.bootstrap.prompt("actual-api");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
const secret = "PRIVATE body: forbidden secret plaintext 503 timeout ".repeat(10_000);
|
||||
const request = { get: vi.fn(async (path: string) => ({
|
||||
ok: () => !path.endsWith("/leases"), status: () => status,
|
||||
url: () => "http://PRIVATE.invalid/private", text: async () => secret,
|
||||
json: async () => original(path),
|
||||
} as APIResponse)) };
|
||||
const actual = new RunnerApi(request as unknown as APIRequestContext);
|
||||
h.api.get.mockImplementation(path => actual.get(path, { timeout: 1000 }));
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1000); const error = await delivery;
|
||||
expect(classifyFailure(error)).toBe(failureClass);
|
||||
expect(error.cause).toBeUndefined();
|
||||
expect(error.message.length).toBeLessThan(1024);
|
||||
expect(error.stack).not.toContain("PRIVATE");
|
||||
expect(JSON.stringify(error)).not.toContain("PRIVATE");
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).not.toContain("PRIVATE");
|
||||
if (status === 403) expect(error).toBeInstanceOf(RemoteAdmissionReadError);
|
||||
expect(h.bind).not.toHaveBeenCalled();
|
||||
vi.unstubAllEnvs();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["issue", null], ["run", []], ["leases", {}], ["leases", [null]],
|
||||
["leases", ["PRIVATE"]], ["leases", [[{}]]], ["leases", undefined],
|
||||
])("rejects malformed successful %s JSON without an unhandled continuation", async (endpoint, value) => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(43_000); h.bootstrap.prompt("malformed");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
const path = endpoint === "issue" ? "/api/issues/issue" : endpoint === "run" ? "/api/heartbeat-runs/run" : "/api/environments/env/leases";
|
||||
h.api.get.mockImplementation(async requested => requested === path ? value as never : original(requested));
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1000); const error = await delivery;
|
||||
expect(error).toBeInstanceOf(RemoteAdmissionReadError);
|
||||
expect(classifyFailure(error)).toBe("candidate_failure");
|
||||
expect(error.cause).toBeUndefined(); expect(error.stack).not.toContain("PRIVATE");
|
||||
expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -3,10 +3,34 @@ import { readFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { ObservedStateTimeout, pollUntil } from "./api.js";
|
||||
import { ObservedStateTimeout, RemoteAdmissionReadError, RunnerApiHttpError, pollUntil } from "./api.js";
|
||||
import { classifyFailure } from "./failure-classifier.js";
|
||||
import { REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS, bindRemoteNativeFixture, type RemoteFixtureApi, type RemoteFixtureDaytona, type RemoteNativeFixture } from "./remote-native-fixtures.js";
|
||||
|
||||
type AdmissionEndpoint = "issue" | "run" | "leases";
|
||||
|
||||
function admissionReadError(endpoint: AdmissionEndpoint, error: unknown): RemoteAdmissionReadError {
|
||||
let failureClass: RemoteAdmissionReadError["failureClass"] = "candidate_failure";
|
||||
// Only typed status or transport diagnostics classify the failure. In
|
||||
// particular, an HTTP body must not supply classification keywords.
|
||||
try {
|
||||
if (error instanceof RunnerApiHttpError) {
|
||||
if (error.status === 408 || error.status === 429 || (error.status >= 500 && error.status <= 599)) failureClass = "transient_infrastructure";
|
||||
else if (error.status === 401 || error.status === 403) failureClass = "permanent_infrastructure";
|
||||
} else if (error instanceof Error) {
|
||||
const message = error.message.slice(0, 256);
|
||||
if (error.name === "TimeoutError" || /^(?:apiRequestContext\.get: )?Timeout \d+ms exceeded\b/u.test(message)
|
||||
|| /\b(?:ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN)\b/u.test(message)) failureClass = "transient_infrastructure";
|
||||
}
|
||||
} catch { /* Unknown rejection values remain a bounded candidate failure. */ }
|
||||
return new RemoteAdmissionReadError(endpoint, failureClass);
|
||||
}
|
||||
|
||||
function admissionJson(endpoint: AdmissionEndpoint, value: unknown): boolean {
|
||||
const record = (item: unknown): item is Record<string, unknown> => item !== null && typeof item === "object" && !Array.isArray(item);
|
||||
return endpoint === "leases" ? Array.isArray(value) && value.every(record) : record(value);
|
||||
}
|
||||
|
||||
export interface RemoteNativeBootstrap {
|
||||
prompt(nonce: string): string;
|
||||
bindAndRelease(input: {
|
||||
@@ -67,12 +91,12 @@ export function createRemoteNativeBootstrap(input: {
|
||||
let lastState: Record<string, string | number | boolean> = { observed: false };
|
||||
const admissionDeadlineAt = input.deadlineAt - REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS;
|
||||
let fixture: RemoteNativeFixture;
|
||||
let lastReadError: unknown;
|
||||
let lastReadError: RemoteAdmissionReadError | undefined;
|
||||
try {
|
||||
const ready = await pollUntil({
|
||||
label: "owned native qualification lease", deadlineAt: admissionDeadlineAt, intervalMs: 100,
|
||||
load: async () => {
|
||||
type Read<T> = PromiseSettledResult<T> | { status: "pending" };
|
||||
type Read<T> = { status: "fulfilled"; value: T } | { status: "rejected"; reason: RemoteAdmissionReadError } | { status: "pending" };
|
||||
let issueRead: Read<Record<string, any>> = { status: "pending" };
|
||||
let runRead: Read<Record<string, any>> = { status: "pending" };
|
||||
let leasesRead: Read<Array<Record<string, any>>> = { status: "pending" };
|
||||
@@ -118,18 +142,19 @@ export function createRemoteNativeBootstrap(input: {
|
||||
finished = true; clearTimeout(timer); resolve(state);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
const failure = { status: "rejected" as const, reason: new Error("API connection timed out during remote admission") };
|
||||
if (issueRead.status === "pending") issueRead = failure;
|
||||
if (runRead.status === "pending") runRead = failure;
|
||||
if (leasesRead.status === "pending") leasesRead = failure;
|
||||
const failure = (endpoint: AdmissionEndpoint) => ({ status: "rejected" as const, reason: new RemoteAdmissionReadError(endpoint, "transient_infrastructure") });
|
||||
if (issueRead.status === "pending") issueRead = failure("issue");
|
||||
if (runRead.status === "pending") runRead = failure("run");
|
||||
if (leasesRead.status === "pending") leasesRead = failure("leases");
|
||||
finish(snapshot());
|
||||
}, remainingMs);
|
||||
function read<T>(path: string, save: (result: Read<T>) => void) {
|
||||
function read<T>(endpoint: AdmissionEndpoint, path: string, save: (result: Read<T>) => void) {
|
||||
// Both handlers are installed before dispatch. Late completion
|
||||
// is consumed but cannot mutate saved evidence or start a poll.
|
||||
void Promise.resolve().then(() => input.api.get<T>(path, { timeout })).then(
|
||||
value => settled({ status: "fulfilled", value }),
|
||||
reason => settled({ status: "rejected", reason }),
|
||||
value => settled(admissionJson(endpoint, value) ? { status: "fulfilled", value }
|
||||
: { status: "rejected", reason: admissionReadError(endpoint, undefined) }),
|
||||
reason => settled({ status: "rejected", reason: admissionReadError(endpoint, reason) }),
|
||||
);
|
||||
function settled(result: Read<T>) {
|
||||
if (finished) return;
|
||||
@@ -138,9 +163,9 @@ export function createRemoteNativeBootstrap(input: {
|
||||
if (state.rejection || [issueRead, runRead, leasesRead].every(read => read.status !== "pending")) finish(state);
|
||||
}
|
||||
}
|
||||
read<Record<string, any>>(`/api/issues/${request.issueId}`, result => { issueRead = result; });
|
||||
read<Record<string, any>>(`/api/heartbeat-runs/${request.runId}`, result => { runRead = result; });
|
||||
read<Array<Record<string, any>>>(`/api/environments/${input.environmentId}/leases`, result => { leasesRead = result; });
|
||||
read<Record<string, any>>("issue", `/api/issues/${request.issueId}`, result => { issueRead = result; });
|
||||
read<Record<string, any>>("run", `/api/heartbeat-runs/${request.runId}`, result => { runRead = result; });
|
||||
read<Array<Record<string, any>>>("leases", `/api/environments/${input.environmentId}/leases`, result => { leasesRead = result; });
|
||||
});
|
||||
lastState = state.evidence;
|
||||
lastReadError = state.rejection ? undefined : state.readError;
|
||||
@@ -162,7 +187,8 @@ export function createRemoteNativeBootstrap(input: {
|
||||
if (lastReadError !== undefined && lastState.phase === "lease_admission") {
|
||||
if (classifyFailure(lastReadError) === "transient_infrastructure") {
|
||||
const timeout = new ObservedStateTimeout("owned native qualification lease", "transient_infrastructure", JSON.stringify(lastState));
|
||||
timeout.cause = lastReadError;
|
||||
// The safe read classification is already in the bounded state.
|
||||
// Do not expose the rejected transport value through a cause chain.
|
||||
error = timeout;
|
||||
} else error = lastReadError;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user