Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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 src/adapters/openai-responses/passthrough.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,11 +329,11 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
outBody = stripUnsupportedReasoningSummaryDelivery(outBody, parsed.modelId);
// #4587: on a bridged provider, hand the destination back the search call and result the
// proxy executed on its behalf, in place of the hosted cell the caller replays. Scoped to
// this destination and recorded by the bridge itself, so a provider without the opt-in
// computes no identity and keeps the body reference it already had. This runs before the
// query backfill below because a restored cell is no longer a web_search_call to repair.
// its exact conversation and serving identity and recorded by the bridge itself, so a
// provider without the opt-in computes no identity and keeps the body reference it already
// had. This runs before query backfill because a restored cell is no longer one to repair.
if (provider.webSearchBridge?.enabled === true) {
outBody = restoreBridgedWebSearchCalls(outBody, bridgeSearchReplayScope(provider.baseUrl));
outBody = restoreBridgedWebSearchCalls(outBody, bridgeSearchReplayScope(parsed._reasoningReplayScope));
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
}
// Repair stored history from before the bridge emitted both keys, in either
// direction: a conversation that already recorded a web_search_call replays it
Expand Down
30 changes: 20 additions & 10 deletions src/responses/bridge-search-replay-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
* what `appendBridgeSearchTurn` would have written onto a continuation leg, so a replayed turn
* and a continued turn show the destination the same conversation.
*
* Scope. Entries are keyed by the upstream destination in addition to the cell id. The cell id is
* a v4 UUID minted here, so it cannot collide across conversations, but an unscoped key would let
* a history replayed against a DIFFERENT provider resurrect a call that provider never made.
* Scope. Entries are keyed by the exact conversation and serving identity in addition to the cell
* id. The cell id is a v4 UUID minted here, but possession of a client-visible id is not authority
* to recover result text under another provider, model, destination, or credential.
*
* Bounds and privacy. Result text is web content the caller already received, but it is still
* request-derived data: it lives in memory only, is never logged, serialized, or exported, and is
Expand All @@ -26,7 +26,7 @@
* alone. Neither re-running the search nor inventing a result is an acceptable recovery.
*/

import { reasoningReplayDestinationIdentity } from "./reasoning-replay-cache";
import type { OcxReasoningReplayScopeRef } from "../types";

const MAX_ENTRIES = 64;
const MAX_TOTAL_BYTES = 512 * 1024;
Expand Down Expand Up @@ -58,14 +58,24 @@ let clockForTests: (() => number) | null = null;
const now = (): number => clockForTests?.() ?? Date.now();

/**
* Identify the upstream destination a bridged search belongs to.
* Identify the exact conversation and upstream binding a bridged search belongs to.
*
* Reuses the salted process-local destination digest the reasoning replay cache already defines,
* so both stores agree on what "the same upstream" means and neither invents a second notion of
* destination identity.
* The serving route binds this holder only after provider, model, and physical credential
* selection. A missing conversation or binding fails closed: a cell id is client-visible and is
* not itself authority to recover another request's retained result.
*/
export function bridgeSearchReplayScope(baseUrl: string | undefined): string | undefined {
return reasoningReplayDestinationIdentity(baseUrl);
export function bridgeSearchReplayScope(scope: OcxReasoningReplayScopeRef | undefined): string | undefined {
const identity = scope?.current;
if (!scope?.clientPrincipalId || !scope.clientThreadId || !identity) return undefined;
return JSON.stringify([
scope.clientPrincipalId,
scope.clientThreadId,
identity.providerName,
identity.providerDestinationIdentity,
identity.adapterName,
identity.modelId,
identity.credentialIdentity,
]);
}

function keyFor(scope: string, cellItemId: string): string {
Expand Down
7 changes: 3 additions & 4 deletions src/server/responses/passthrough-delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,10 +417,9 @@ export async function deliverPassthroughResponse(
describeImages: requiresVisionPreprocessing(config, route.provider, route.modelId, route.providerName),
sidecar: config.webSearchSidecar,
}),
// Scope the executed-search memo to this exact upstream (#4587). The Responses adapter
// derives the same scope from the same base URL before the NEXT turn is dispatched, so
// a replayed hosted cell can be turned back into the destination's own call and result.
destinationScope: bridgeSearchReplayScope(route.provider.baseUrl),
// Snapshot the bound conversation, provider, model, destination, and credential. The
// next turn must match every dimension before its hosted cell can recover this result.
destinationScope: bridgeSearchReplayScope(parsed._reasoningReplayScope),
// Appending a search result can push the continuation past the ceiling the first leg
// was admitted under, so the same limit is re-applied before every later send.
checkOutboundBody: (continuationBody: string) => {
Expand Down
6 changes: 6 additions & 0 deletions src/server/responses/request-prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
sessionIdHeaderFromRequest,
reasoningReplayConversationIdFromResponsesRequest,
} from "../request-log-conversation";
import { contextPrincipalIdOf } from "../auth-cors";
import {
isShadowSourceModel,
shadowSourceModelPrefix,
Expand Down Expand Up @@ -407,6 +408,11 @@ export async function prepareResponsesRequest(
parsed._reasoningReplayScope = { clientThreadId: reasoningReplayConversationId };
}
}
if (parsed._reasoningReplayScope) {
const clientPrincipalId = contextPrincipalIdOf(options.admission)
?? (options.admission?.kind === "loopback" ? "loopback" : undefined);
parsed._reasoningReplayScope = { ...parsed._reasoningReplayScope, clientPrincipalId };
}
// Prefer a pre-populated id (routed Claude) over Responses headers that may be
// absent or synthetically injected (session_id from prompt_cache_key).
if (!logCtx.conversationId) {
Expand Down
7 changes: 5 additions & 2 deletions src/server/responses/request-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,11 @@ export async function prepareResponsesTransport(
return response;
}
const nextAdapter = await refreshDispatchAdapter(requestParsed);
// Rebind before rebuilding: the rebuild's bridged-search restore and continuation
// restore key on the serving identity, which must be the refreshed route's, not the
// credential whose selection just lapsed.
bindRouteReasoningReplayScope({ parsed: requestParsed, providerName: route.providerName, provider: route.provider,
adapterName: nextAdapter.name, oauthCredentialSnapshot: replayOAuthCredentialSnapshot });
const rebuilt = await nextAdapter.buildRequest(requestParsed, {
headers: requestState.selectedForwardHeaders, translatorBudget,
...(imageTierBias > 0 ? { imageTierBias } : {}),
Expand All @@ -467,8 +472,6 @@ export async function prepareResponsesTransport(
sameTargetToken = transportToken;
destination = rebuilt.url;
dispatchInit = { ...dispatchInit, method: rebuilt.method, headers, body: rebuilt.body };
bindRouteReasoningReplayScope({ parsed: requestParsed, providerName: route.providerName, provider: route.provider,
adapterName: nextAdapter.name, oauthCredentialSnapshot: replayOAuthCredentialSnapshot });
// The next iteration validates synchronously and calls fetch in that same turn.
}
throw new Error("OAuth account selection changed repeatedly before dispatch");
Expand Down
2 changes: 2 additions & 0 deletions src/types/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export interface OcxReasoningReplayIdentity {
* the holder, so late tool-call cache writes see the active physical identity.
*/
export interface OcxReasoningReplayScopeRef {
/** Process-local caller principal; `loopback` denotes the trusted local-only admission lane. */
readonly clientPrincipalId?: string;
/**
* Conversation namespace for replay state. Historically this was always the Codex parent-thread
* id; headerless Responses callers use a raw sanitized thread/Cursor/session fallback, never the
Expand Down
14 changes: 9 additions & 5 deletions structure/providers-and-adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,16 +172,20 @@ searches run, their hosted cells complete, the held client calls are released fo
execute, and the leg's own terminal closes the turn with no continuation sent upstream. The
destination therefore does not receive that search result during the turn. It gets it on the next
one: every search the bridge executes is recorded in `src/responses/bridge-search-replay-cache.ts`
under the hosted cell's proxy-minted id, scoped to the upstream destination and bounded by entry
count, total bytes, and a one-hour TTL. When the caller replays that cell,
under the hosted cell's proxy-minted id, scoped to the admitted caller principal, client
conversation, and exact provider, adapter, model, destination, and physical credential binding, and bounded by entry count, total
bytes, and a one-hour TTL. An unavailable scope fails closed. When the caller replays that cell,
`restoreBridgedWebSearchCalls` in `src/adapters/openai-responses/tool-output-recovery.ts` puts the
destination's own `function_call` and the executed `function_call_output` back in the cell's
position before the next turn's first leg is dispatched, recording exactly the text
`appendBridgeSearchTurn` would have sent on a continuation leg so a replayed turn and a continued
turn show the destination one consistent conversation. The rewrite runs only for a provider with
`webSearchBridge.enabled`, and a miss — unknown id, expired entry, a different destination, or a
`call_id` the body already carries — leaves the replayed item untouched. Re-running the search or
synthesizing result text is not a permitted recovery. The bridge finalizes request-scoped OpenAI sidecar authority on completion, failure, and client cancellation — cancellation releases immediately rather than waiting on an abandoned upstream read — so a recovery probe lease no search consumed is always returned.
`webSearchBridge.enabled`, and a miss — unknown id, expired entry, a different conversation or
serving binding, or a `call_id` the body already carries — leaves the replayed item untouched.
Re-running the search or synthesizing result text is not a permitted recovery. The bridge finalizes
request-scoped OpenAI sidecar authority on completion, failure, and client cancellation —
cancellation releases immediately rather than waiting on an abandoned upstream read — so a
recovery probe lease no search consumed is always returned.
`tests/web-search/web-search-bridge-replay.test.ts` pins the restore and each of those refusals.
A leg whose
upstream terminal is `response.failed` or `response.incomplete` runs no search at all and closes
Expand Down
117 changes: 116 additions & 1 deletion tests/server/server-key-failover-e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,16 @@ import { readUsageEntries, resetUsageReadCacheForTests } from "../../src/usage/l
import { loadConfig, saveConfig } from "../../src/config";
import { clearKeyCooldowns, getKeyCooldownUntil, rotateKeyOn429 } from "../../src/providers/key-failover";
import { deriveXaiConvId } from "../../src/providers/xai-transport";
import { clearReasoningReplayCacheForTests } from "../../src/responses/reasoning-replay-cache";
import {
clearReasoningReplayCacheForTests,
reasoningReplayDestinationIdentity,
reasoningReplayKeyCredentialIdentity,
} from "../../src/responses/reasoning-replay-cache";
import {
bridgeSearchReplayScope,
clearBridgeSearchReplayCacheForTests,
rememberBridgeSearchReplay,
} from "../../src/responses/bridge-search-replay-cache";
import { startServer } from "../../src/server";
import { handleResponses } from "../../src/server/responses";
import type { OcxConfig } from "../../src/types";
Expand All @@ -31,6 +40,7 @@ beforeEach(() => {
process.env.OPENCODEX_HOME = testDir;
clearKeyCooldowns();
clearReasoningReplayCacheForTests();
clearBridgeSearchReplayCacheForTests();
});

afterEach(() => {
Expand All @@ -43,6 +53,7 @@ afterEach(() => {
if (testDir) removeTreeWithRetry(testDir);
clearKeyCooldowns();
clearReasoningReplayCacheForTests();
clearBridgeSearchReplayCacheForTests();
});

describe("server 429 key failover (end-to-end)", () => {
Expand Down Expand Up @@ -1182,3 +1193,107 @@ test.each([false, true])("key refetch retains transient recovery metadata (strea
usage: { inputTokens: 12, outputTokens: 2 } });
} finally { await server.stop(true); }
});

test("a dispatch-time key switch rebuilds the bridged-search restore under the new credential", async () => {
// Regression for the oauthDispatch rebuild order: the Responses adapter restores a replayed
// web_search_call from the memo keyed by _reasoningReplayScope, so the rebuild must rebind
// that scope to the refreshed credential BEFORE buildRequest runs. Restoring under the key
// whose selection just lapsed, then sending under the newly selected key, would hand the
// first credential's recorded result to the second credential's upstream.
let now = 0;
let resumePacing: (() => void) | undefined;
const queued = Promise.withResolvers<void>();
setProviderRequestPacingRuntimeForTest({
now: () => now,
setTimer(callback, delayMs) {
resumePacing = () => { now += delayMs; callback(); };
queued.resolve();
return callback;
},
clearTimer() {},
enqueueMicrotask: queueMicrotask,
});
const seen: { authorization: string | null; input: Record<string, unknown>[] }[] = [];
upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) {
const body = await req.json() as { input?: unknown };
seen.push({
authorization: req.headers.get("authorization"),
input: Array.isArray(body.input) ? body.input as Record<string, unknown>[] : [],
});
return Response.json({
id: "resp_keyrace", object: "response", status: "completed", model: "test",
output: [{ type: "message", id: "msg_keyrace", role: "assistant", status: "completed",
content: [{ type: "output_text", text: "done", annotations: [] }] }],
usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
});
} });
const baseUrl = `http://127.0.0.1:${upstream.port}/v1`;
const config = { port: 0, hostname: "127.0.0.1", defaultProvider: "pooled", providers: { pooled: {
adapter: "openai-responses", baseUrl, allowPrivateNetwork: true,
authMode: "key", apiKey: "synthetic-first",
apiKeyPool: [{ id: "first", key: "synthetic-first" }, { id: "second", key: "synthetic-second" }],
webSearchBridge: { enabled: true, backend: "ollama" },
requestPacing: { enabled: true, minIntervalMs: 100 },
} } } as OcxConfig;
saveConfig(config);

// Seed the bridged-search memo under the identity the FIRST key binds: same loopback
// principal and thread the request below carries, but the lapsed credential.
const cellId = "ws_keyrace";
rememberBridgeSearchReplay(
bridgeSearchReplayScope({
clientPrincipalId: "loopback",
clientThreadId: "thread-keyrace",
current: {
providerName: "pooled",
providerDestinationIdentity: reasoningReplayDestinationIdentity(baseUrl),
adapterName: "openai-responses",
modelId: "test",
credentialIdentity: reasoningReplayKeyCredentialIdentity({ apiKey: "synthetic-first" }),
},
}),
cellId,
{ callId: "call_ws_1", name: "web_search",
argumentsText: "{\"query\":\"opencodex release\"}", output: "cached bridged result" },
);

const server = startServer(0);
const abort = new AbortController();
try {
await waitForProviderRequestSlot("pooled", config.providers.pooled);
const pending = fetch(new URL("/v1/responses", server.url), {
method: "POST",
headers: { "content-type": "application/json", "thread-id": "thread-keyrace" },
signal: abort.signal,
body: JSON.stringify({
model: "pooled/test", stream: false,
input: [
{ role: "user", content: [{ type: "input_text", text: "what is the latest release?" }] },
{ type: "web_search_call", id: cellId, status: "completed",
action: { type: "search", query: "opencodex release", queries: ["opencodex release"] } },
],
}),
});
await queued.promise;
const selected = await managementFetch(new URL("/api/providers/keys/active", server.url), {
method: "PUT", headers: { "content-type": "application/json" },
body: JSON.stringify({ name: "pooled", id: "second" }),
});
expect(selected.status).toBe(200);
await selected.text();
resumePacing!();
const response = await pending;
expect(response.status).toBe(200);
await response.text();
expect(seen).toHaveLength(1);
expect(seen[0]!.authorization).toBe("Bearer synthetic-second");
// Rebound before rebuild: the memo lookup misses under the new credential, so the hosted
// cell reaches the second key's upstream verbatim instead of the first key's result.
expect(seen[0]!.input.some(item => item.type === "web_search_call" && item.id === cellId)).toBe(true);
expect(seen[0]!.input.some(item => item.call_id === "call_ws_1")).toBe(false);
} finally {
abort.abort();
await server.stop(true);
resetProviderRequestPacingForTest();
}
});
Loading
Loading