Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,10 @@ different pointer, so every branch move and promotion dragged a diff.
Reference *clones* are gitignored: they are third-party source carrying their
own licenses and have no business in this repository's history.

Nothing in the build, typecheck, or test path reads from `devlog/`, so a
contributor who ignores it entirely still passes every gate. `privacy:scan` does
read it — that is deliberate, and it is what makes a public devlog safe rather
than merely visible.
Build and typecheck do not read `devlog/`. The test-layout membership oracle reads
`devlog/_fin/260905_test_modularization_and_windows/001_test_inventory.md`; sparse
checkouts running that test must materialize this tracked input. `privacy:scan`
also reads `devlog/` to keep public development notes safe to publish.

Two mechanical guards in `tests/ci-workflows/repo-hygiene.test.ts` back this up: no `160000`
gitlink may be tracked anywhere, and neither the vendored reference clones nor
Expand Down
67 changes: 33 additions & 34 deletions tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ import { resetNormalizeStateForTests } from "../../../src/adapters/anthropic-ima
import { sniffImageDimensions } from "../../../src/adapters/anthropic-image-guard";
import type { OcxConfig } from "../../../src/types";
import { installIsolatedCodexHome, type IsolatedCodexHome } from "../../helpers/isolated-codex-home";
import { removeTreeWithRetry } from "../../helpers/remove-tree";
import { BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS, removeTreeAfterBackgroundWork } from "../../helpers/remove-tree";

let testDir = "";
let previousHome: string | undefined;
let isolatedCodexHome: IsolatedCodexHome | null = null;
let upstream: ReturnType<typeof Bun.serve> | null = null;
let proxy: ReturnType<typeof startServer> | undefined;

beforeEach(() => {
previousHome = process.env.OPENCODEX_HOME;
Expand All @@ -25,16 +26,18 @@ beforeEach(() => {
resetNormalizeStateForTests();
});

afterEach(() => {
afterEach(async () => {
await proxy?.stop(true);
proxy = undefined;
upstream?.stop(true);
upstream = null;
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
else process.env.OPENCODEX_HOME = previousHome;
isolatedCodexHome?.restore();
isolatedCodexHome = null;
if (testDir) removeTreeWithRetry(testDir);
if (testDir) await removeTreeAfterBackgroundWork(testDir);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
clearKeyCooldowns();
});
}, BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS);

const ONE_PX_PNG =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
Expand Down Expand Up @@ -81,6 +84,7 @@ function anthropicConfig(baseUrl: string, pool = false): OcxConfig {
return {
port: 0,
hostname: "127.0.0.1",
clientIntegrations: { codex: false },
defaultProvider: "anthropic-test",
providers: {
"anthropic-test": {
Expand Down Expand Up @@ -121,14 +125,30 @@ async function postImageRequest(serverUrl: string, dataUrl: string): Promise<Res
});
}

function imageRetryScenario(
name: string, statuses: number[], pool: boolean,
verify: (res: Response, seen: SeenRequest[]) => void | Promise<void>,
): void {
describe(name, () => {
let seen: SeenRequest[];
let dataUrl: string;
// Real Windows config/ACL and server setup is separate from the 5s request assertions.
beforeEach(async () => {
seen = [];
upstream = scriptedUpstream(statuses, seen);
saveConfig(anthropicConfig(upstream.url.toString().replace(/\/$/, ""), pool));
proxy = startServer(0);
dataUrl = await realPngDataUrl(1500, 1000);
}, 10_000);
test("preserves the response and retry contract", async () => {
const res = await postImageRequest(String(proxy!.url), dataUrl);
await verify(res, seen);
});
});
}

describe("anthropic 413 tightened-retry (end-to-end)", () => {
test("R1: upstream 413 then 200 — exactly one biased rebuild, images re-encoded a tier lower", async () => {
const seen: SeenRequest[] = [];
upstream = scriptedUpstream([413, 200], seen);
saveConfig(anthropicConfig(upstream.url.toString().replace(/\/$/, "")));
const server = startServer(0);
try {
const res = await postImageRequest(String(server.url), await realPngDataUrl(1500, 1000));
imageRetryScenario("R1: upstream 413 then 200 — exactly one biased rebuild, images re-encoded a tier lower", [413, 200], false, async (res, seen) => {
expect(res.status).toBe(200);
expect(seen).toHaveLength(2);
// First attempt: 1500px PNG rides tier-0 pass-through.
Expand All @@ -139,18 +159,9 @@ describe("anthropic 413 tightened-retry (end-to-end)", () => {
expect(second?.media_type).toBe("image/jpeg");
const dims = sniffImageDimensions(second?.data ?? "");
expect(Math.max(dims!.width, dims!.height)).toBeLessThanOrEqual(1024);
} finally {
await server.stop(true);
}
});

test("R2: upstream 413 twice — exactly two calls, honest 413 surfaces, no spiral", async () => {
const seen: SeenRequest[] = [];
upstream = scriptedUpstream([413, 413], seen);
saveConfig(anthropicConfig(upstream.url.toString().replace(/\/$/, "")));
const server = startServer(0);
try {
const res = await postImageRequest(String(server.url), await realPngDataUrl(1500, 1000));
imageRetryScenario("R2: upstream 413 twice — exactly two calls, honest 413 surfaces, no spiral", [413, 413], false, async (res, seen) => {
expect(res.status).toBe(413);
expect(seen).toHaveLength(2);
expect(res.headers.get("content-type")).toContain("application/json");
Expand All @@ -160,18 +171,9 @@ describe("anthropic 413 tightened-retry (end-to-end)", () => {
type: "invalid_request_error",
code: "context_length_exceeded",
});
} finally {
await server.stop(true);
}
});

test("R4: 413 → biased retry → 429 → key rotation keeps the tightened tiers", async () => {
const seen: SeenRequest[] = [];
upstream = scriptedUpstream([413, 429, 200], seen);
saveConfig(anthropicConfig(upstream.url.toString().replace(/\/$/, ""), true));
const server = startServer(0);
try {
const res = await postImageRequest(String(server.url), await realPngDataUrl(1500, 1000));
imageRetryScenario("R4: 413 → biased retry → 429 → key rotation keeps the tightened tiers", [413, 429, 200], true, async (res, seen) => {
expect(res.status).toBe(200);
expect(seen).toHaveLength(3);
// Rotation happened after the biased 413 retry hit 429.
Expand All @@ -181,8 +183,5 @@ describe("anthropic 413 tightened-retry (end-to-end)", () => {
expect(third?.media_type).toBe("image/jpeg");
const dims = sniffImageDimensions(third?.data ?? "");
expect(Math.max(dims!.width, dims!.height)).toBeLessThanOrEqual(1024);
} finally {
await server.stop(true);
}
});
});
150 changes: 66 additions & 84 deletions tests/claude-integration/claude-529-mapping.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,53 @@ import { startServer } from "../../src/server";
import { getRequestLogEntries } from "../../src/server/request-log";
import type { OcxConfig } from "../../src/types";
import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home";
import { removeTreeWithRetry } from "../helpers/remove-tree";
import { BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS, removeTreeAfterBackgroundWork } from "../helpers/remove-tree";

let testDir = "";
let previousHome: string | undefined;
let isolatedCodexHome: IsolatedCodexHome | null = null;
let upstream: ReturnType<typeof Bun.serve> | undefined;
let proxy: ReturnType<typeof startServer> | undefined;
let calls = 0;
let upstreamResponse: () => Response;

beforeEach(() => {
previousHome = process.env.OPENCODEX_HOME;
isolatedCodexHome = installIsolatedCodexHome("ocx-claude-529-");
testDir = mkdtempSync(join(tmpdir(), "ocx-claude-529-"));
process.env.OPENCODEX_HOME = testDir;
});
calls = 0;
upstreamResponse = () => Response.json({ error: { message: "bad request shape" } }, { status: 400 });
upstream = Bun.serve({ port: 0, fetch() { calls++; return upstreamResponse(); } });
saveConfig(nativeConfig(`${upstream.url.toString().replace(/\/$/, "")}/v1`));
proxy = startServer(0);
}, 10_000);

afterEach(() => {
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
else process.env.OPENCODEX_HOME = previousHome;
isolatedCodexHome?.restore();
afterEach(async () => {
const codexHome = isolatedCodexHome;
isolatedCodexHome = null;
if (testDir) removeTreeWithRetry(testDir);
});
try {
try { await proxy?.stop(true); }
finally {
proxy = undefined;
await upstream?.stop(true);
upstream = undefined;
}
if (testDir) await removeTreeAfterBackgroundWork(testDir);
testDir = "";
} finally {
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
else process.env.OPENCODEX_HOME = previousHome;
codexHome?.restoreEnvironment();
}
// A failed drain leaves the owned tree for the wrapper; never delete under its writer.
codexHome?.removeAfterDrain();
}, BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS);

function nativeConfig(baseUrl: string): OcxConfig {
return {
port: 0,
clientIntegrations: { codex: false },
defaultProvider: "native",
providers: {
native: { adapter: "openai-responses", baseUrl, authMode: "forward", allowPrivateNetwork: true },
Expand All @@ -47,89 +70,48 @@ function messagesBody(): string {
}

test("transient upstream 502 -> client 529 overloaded_error; retry fired; log keeps upstream 502", async () => {
let calls = 0;
const upstream = Bun.serve({
port: 0,
fetch() {
calls++;
return Response.json(
{ error: { message: "An error occurred while processing your request. request ID test-42" } },
// Retry-After: 0 keeps the pre-stream retry backoff instant AND must win over the "2" fallback.
{ status: 502, headers: { "Retry-After": "0" } },
);
},
upstreamResponse = () => Response.json(
{ error: { message: "An error occurred while processing your request. request ID test-42" } },
// Retry-After: 0 keeps the pre-stream retry backoff instant AND must win over the "2" fallback.
{ status: 502, headers: { "Retry-After": "0" } },
);
const response = await fetch(new URL("/v1/messages", proxy!.url), {
method: "POST",
headers: { "content-type": "application/json" },
body: messagesBody(),
});
saveConfig(nativeConfig(`${upstream.url.toString().replace(/\/$/, "")}/v1`));
const server = startServer(0);
try {
const response = await fetch(new URL("/v1/messages", server.url), {
method: "POST",
headers: { "content-type": "application/json" },
body: messagesBody(),
});
// Pre-stream transient retry (010) exhausts its attempts against the persistent 502 …
expect(calls).toBe(3);
// … then the Claude envelope reclassifies the transient 5xx as retryable overload (020).
expect(response.status).toBe(529);
expect(response.headers.get("retry-after")).toBe("0");
const json = await response.json() as { type?: string; error?: { type?: string; message?: string } };
expect(json.error?.type).toBe("overloaded_error");
expect(json.error?.message).toBe("The provider failed to complete the request.");
// Diagnostics stay honest: the request log keeps the upstream status, not the client 529.
const entry = getRequestLogEntries().findLast(e => e.surface === "claude");
expect(entry?.status).toBe(502);
} finally {
await server.stop(true);
await upstream.stop(true);
}
// Pre-stream transient retry (010) exhausts its attempts against the persistent 502 …
expect(calls).toBe(3);
// … then the Claude envelope reclassifies the transient 5xx as retryable overload (020).
expect(response.status).toBe(529);
expect(response.headers.get("retry-after")).toBe("0");
const json = await response.json() as { type?: string; error?: { type?: string; message?: string } };
expect(json.error?.type).toBe("overloaded_error");
expect(json.error?.message).toBe("The provider failed to complete the request.");
// Diagnostics stay honest: the request log keeps the upstream status, not the client 529.
const entry = getRequestLogEntries().findLast(e => e.surface === "claude");
expect(entry?.status).toBe(502);
}, 15_000);

test("transient 502 without Retry-After -> fallback Retry-After 2 on the 529 response", async () => {
const upstream = Bun.serve({
port: 0,
fetch() {
return Response.json({ error: { message: "boom" } }, { status: 502 });
},
upstreamResponse = () => Response.json({ error: { message: "boom" } }, { status: 502 });
const response = await fetch(new URL("/v1/messages", proxy!.url), {
method: "POST",
headers: { "content-type": "application/json" },
body: messagesBody(),
});
saveConfig(nativeConfig(`${upstream.url.toString().replace(/\/$/, "")}/v1`));
const server = startServer(0);
try {
const response = await fetch(new URL("/v1/messages", server.url), {
method: "POST",
headers: { "content-type": "application/json" },
body: messagesBody(),
});
expect(response.status).toBe(529);
expect(response.headers.get("retry-after")).toBe("2");
} finally {
await server.stop(true);
await upstream.stop(true);
}
expect(response.status).toBe(529);
expect(response.headers.get("retry-after")).toBe("2");
}, 15_000);

test("non-transient upstream 400 stays 400 invalid_request_error; no retry", async () => {
let calls = 0;
const upstream = Bun.serve({
port: 0,
fetch() {
calls++;
return Response.json({ error: { message: "bad request shape" } }, { status: 400 });
},
const response = await fetch(new URL("/v1/messages", proxy!.url), {
method: "POST",
headers: { "content-type": "application/json" },
body: messagesBody(),
});
saveConfig(nativeConfig(`${upstream.url.toString().replace(/\/$/, "")}/v1`));
const server = startServer(0);
try {
const response = await fetch(new URL("/v1/messages", server.url), {
method: "POST",
headers: { "content-type": "application/json" },
body: messagesBody(),
});
expect(calls).toBe(1);
expect(response.status).toBe(400);
const json = await response.json() as { error?: { type?: string } };
expect(json.error?.type).toBe("invalid_request_error");
} finally {
await server.stop(true);
await upstream.stop(true);
}
expect(calls).toBe(1);
expect(response.status).toBe(400);
const json = await response.json() as { error?: { type?: string } };
expect(json.error?.type).toBe("invalid_request_error");
});
38 changes: 28 additions & 10 deletions tests/claude-integration/messages-error-contracts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,28 @@ for (const [size, cap, type, code] of [[1000, 250, "request_too_large", "transla
expect(error.type).toBe(type); expect(error.code).toBe(code);
});

type SourceUses = { path: string; constructors: boolean[]; writers: number };
let sourceUses: Promise<SourceUses[]> | undefined;
/** Scan every source once with bounded reads; retain only oracle facts, not all source text. */
function readSourceUses(): Promise<SourceUses[]> {
return sourceUses ??= (async () => {
const paths = [...new Bun.Glob("src/**/*.ts").scanSync(repoRoot())];
const uses = new Array<SourceUses>(paths.length);
let next = 0;
await Promise.all(Array.from({ length: Math.min(8, paths.length) }, async () => {
for (;;) {
const index = next++;
if (index >= paths.length) return;
const path = paths[index]!, source = await Bun.file(repoPath(path)).text();
uses[index] = { path: path.replaceAll("\\", "/"),
constructors: [...source.matchAll(/new AnthropicRequestError\(/g)].map(call => source.slice(0, call.index).endsWith("markProxyError(")),
writers: source.split("\n").filter(line => /anthropicError(Response|Body)\(/.test(line)).length };
}
}));
return uses.filter(row => row.constructors.length || row.writers);
})();
}

const ingressProducerRows: [string, number, string[]][] = [
["src/claude/inbound.ts", 10, ["File-backed images require native Anthropic passthrough", "tool_result requires tool_use_id", "tool_use requires id and name", "malformed ocxr1 reasoning signature", "OpenCodex reasoning continuity cannot be replayed as an Anthropic signature", "each message must be an object", "unsupported message role: unsupported", "request body must be a JSON object", "model is required", "messages must be a non-empty array"]],
["src/protocols/codecs/messages-ir.ts", 9, ["tool_result requires tool_use_id", "tool_use requires id and name", "MALFORMED_REASONING_SIGNATURE", "OpenCodex reasoning continuity cannot be replayed as an Anthropic signature", "each message must be an object", "unsupported message role: unsupported", "request body must be a JSON object", "model is required", "messages must be a non-empty array"]],
Expand All @@ -144,11 +166,9 @@ const ingressProducerRows: [string, number, string[]][] = [
];
test("C1/C2 ingress constructors have explicit producer rows and local identity", async () => {
const actual: Record<string, number> = {};
for (const path of new Bun.Glob("src/**/*.ts").scanSync(repoRoot())) {
const source = readFileSync(repoPath(path), "utf8");
const calls = [...source.matchAll(/new AnthropicRequestError\(/g)];
if (calls.length) actual[path.replaceAll("\\", "/")] = calls.length;
for (const call of calls) expect(source.slice(0, call.index).endsWith("markProxyError(")).toBe(true);
for (const { path, constructors } of await readSourceUses()) {
if (constructors.length) actual[path] = constructors.length;
for (const marked of constructors) expect(marked).toBe(true);
}
expect(actual).toEqual(Object.fromEntries(ingressProducerRows.map(([path, count]) => [path, count])));
for (const [path, , diagnostics] of ingressProducerRows) {
Expand All @@ -168,12 +188,10 @@ const envelopeWriterRows = [
["src/server/index/serve-options.ts", 4, "fixed endpoint auth/origin bypasses"],
["src/server/messages-native-tool-guard.ts", 1, "deferred local guard terminal"],
] as const;
test("W1/W3 envelope writers are covered by explicit dispositions", () => {
test("W1/W3 envelope writers are covered by explicit dispositions", async () => {
const actual: Record<string, number> = {};
for (const path of new Bun.Glob("src/**/*.ts").scanSync(repoRoot())) {
const lines = readFileSync(repoPath(path), "utf8").split("\n");
const count = lines.filter(line => /anthropicError(Response|Body)\(/.test(line)).length;
if (count) actual[path.replaceAll("\\", "/")] = count;
for (const { path, writers } of await readSourceUses()) {
if (writers) actual[path] = writers;
}
expect(actual).toEqual(Object.fromEntries(envelopeWriterRows.map(([path, count]) => [path, count])));
const bypassRows = [
Expand Down
Loading
Loading