From d69dfc9759a29cecdf796f85b95ea30f36a43f3e Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 03:01:19 +0900 Subject: [PATCH 1/3] fix(responses): attribute local native continuation refusals --- .../docs/es/guides/codex-integration.md | 2 + .../content/docs/guides/codex-integration.md | 5 ++ .../docs/ko/guides/codex-integration.md | 5 ++ src/server/responses/request-prepare.ts | 9 ++- .../transports/response-turn-membership.md | 2 + .../issue-702-expired-replay-state.test.ts | 80 +++++++++++++++++++ 6 files changed, 101 insertions(+), 2 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/codex-integration.md b/docs-site/src/content/docs/es/guides/codex-integration.md index 546219b31b3..922deb4d3c6 100644 --- a/docs-site/src/content/docs/es/guides/codex-integration.md +++ b/docs-site/src/content/docs/es/guides/codex-integration.md @@ -228,6 +228,8 @@ El proxy admite hasta 128 conexiones Responses WebSocket orientadas al cliente. Si una continuación canónica hacia adelante ChatGPT hace referencia a un estado de repetición local caducado o faltante, opencodex devuelve `previous_response_not_found` antes de enviar cualquier cosa aguas arriba. El cliente Codex de WebSocket reconoce este error y puede volver a conectarse con su contexto completo retenido, incluyendo llamadas de herramientas completadas y sus resultados, dentro de su presupuesto de reintento de flujo normal. Por lo tanto, una tarea inactiva no necesita una tarea nueva únicamente porque la caché de reproducción del proxy expiró. El estado de continuación reproducido se conserva durante 24 horas y permanece limitado por su memoria, disco y límites de entrada existentes; esto no recupera el historial que el cliente ya no tiene. HTTP clientes deben manejar el error explícitamente y volver a enviar su contexto completo sin `previous_response_id`. Volver a intentar solo el mismo ID no puede recuperar el estado faltante. +Si el proxy ya ha seleccionado la ruta de reenvío a ChatGPT, `usage.jsonl` registra el proveedor y el modelo seleccionados junto con `errorCode: "previous_response_not_found"` y `failureCause: "local-refusal"`. La solicitud rechazada no consume cuota del modelo. El reenvío del contexto completo por parte del cliente se registra como una solicitud aparte y puede consumir cuota. + El mismo rechazo se aplica cuando el estado referenciado pertenece a un ámbito de tarea cliente diferente, incluso cuando la nueva solicitud parece llevar entrada completa. El proxy no puede probar que la entrada está completa, por lo que no elimina silenciosamente `previous_response_id` ni revela si existe un estado coincidente. Cuando está activado el modo `v2-plaintext` o la opción `plaintextV2AgentMessages`, la reproducción local exige el mismo principal de OpenCodex admitido y el `thread-id` propio y no vacío de la solicitud. Un hilo principal, una dirección de loopback, una credencial del proveedor o una clave de relleno no constituyen esa identidad. Sin principal admitido o sin hilo propio, envía la conversación completa sin `previous_response_id`. Las configuraciones predeterminadas de Codex y DSH en loopback no establecen esa identidad. El estado conservado mientras cualquiera de las dos opciones está activada permanece vinculado al desactivarlas. El modo predeterminado `v1` conserva la continuación por hilo principal para el estado no vinculado, también en loopback. Esto es independiente de los ID de Responses gestionados por el proveedor nativo. La misma señal de recuperación se aplica a cada destino enrutado, porque solo el paso a través nativo Responses puede responder a un giro cuya historia perdió este proxy: reenvía `previous_response_id` a un backend que almacenó la cadena. Cada uno de los otros cables reconstruye la conversación a partir de la propia entrada de cada solicitud, por lo que una expansión perdida allí enviaría el giro actual solo y perdería silenciosamente la conversación. Eso incluye los tres que parecen con estado: Devin vuelve a enviar toda la conversación a cada paso, la referencia de punto de control de Cursor vive en la misma tienda vencida y vuelve a la reproducción completa sin ella, y Kiro reconstruye su historial de conversaciones a partir de los turnos en que se entregó. También se aplica a los proveedores enrutados Responses configurados con `statelessResponses: true`, y a las solicitudes enrutadas donde una herramienta personalizada se redujo a una función pero un resultado delta no tiene llamada local para establecer su tipo original. La reproducción completa conserva la llamada, el resultado y el razonamiento juntos; opencodex no adivina el tipo de resultado ni lo descarta. Los proveedores estatales todavía resuelven la función nativa y las continuaciones personalizadas nativas por sí mismos. Estas comprobaciones siguen el protocolo de cable seleccionado y las declaraciones de la herramienta, no el nombre del modelo. Para una puerta de enlace que no puede resolver los ID de respuesta almacenados, habilite `statelessResponses` en ese proveedor; otros proveedores mantienen sus valores predeterminados. diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index cb140ca3438..d0e6c6cee07 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -512,6 +512,11 @@ disk, and entry ceilings; this does not recover history the client no longer has must handle the error explicitly and resend their full context without `previous_response_id`. Retrying only the same ID cannot recover missing state. +When the proxy has already selected the ChatGPT forward route, `usage.jsonl` records the +selected provider and model with `errorCode: "previous_response_not_found"` and +`failureCause: "local-refusal"`. The refused request uses no model quota. A client resend with +the full context is logged separately and can use quota. + The same refusal applies when the referenced state belongs to a different client task scope, including when the new request appears to carry complete input. The proxy cannot prove that input is complete, so it does not silently remove `previous_response_id` or reveal whether matching state diff --git a/docs-site/src/content/docs/ko/guides/codex-integration.md b/docs-site/src/content/docs/ko/guides/codex-integration.md index b5631d2aa98..e33410300aa 100644 --- a/docs-site/src/content/docs/ko/guides/codex-integration.md +++ b/docs-site/src/content/docs/ko/guides/codex-integration.md @@ -249,6 +249,11 @@ upstream 요청 전에 `previous_response_not_found`를 반환합니다. Codex W HTTP 클라이언트는 이 오류를 직접 처리하고 `previous_response_id` 없이 전체 컨텍스트를 다시 보내야 합니다. 같은 ID만 재시도해서는 누락된 상태를 복구할 수 없습니다. +프록시가 이미 ChatGPT 전달 경로를 선택했다면 `usage.jsonl`에 선택된 공급자와 모델, 그리고 +`errorCode: "previous_response_not_found"`, `failureCause: "local-refusal"`이 기록됩니다. +거부된 요청은 모델 사용량 한도를 소모하지 않습니다. 클라이언트가 전체 컨텍스트를 다시 +보내면 별도 요청으로 기록되며 모델 사용량 한도를 소모할 수 있습니다. + 참조한 상태의 client task scope가 현재 요청과 다를 때도 같은 거부 응답을 반환합니다. 새 요청이 전체 입력처럼 보여도 프록시는 그것이 완전한 대화인지 증명할 수 없으므로 `previous_response_id`를 조용히 제거하거나 일치하는 상태의 존재 여부를 노출하지 않습니다. diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index fcfef6ad345..02e9b29b9d3 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -90,7 +90,7 @@ import { anthropicSessionKeyFromParts } from "../../oauth/anthropic-routing"; import { configuredAnthropicInstance } from "../../providers/anthropic-instance"; import { isTranslatorBudgetExceededError } from "../../lib/translator-budget"; import { bindTurnTerminationScope, rememberDeliveredFinalAnswer } from "../../responses/turn-termination"; -import { noteCodexSelectionAffinity, observeCacheDiagnosticInbound, rebindCacheDiagnosticBody, requestLogSpeedLabel, readConfiguredCodexServiceTier } from "../request-log"; +import { markLocalRequestLogRefusal, noteCodexSelectionAffinity, observeCacheDiagnosticInbound, rebindCacheDiagnosticBody, requestLogSpeedLabel, readConfiguredCodexServiceTier } from "../request-log"; import type { RouteResult } from "../../router"; import { captureRouteStaticPolicy, @@ -1455,9 +1455,14 @@ export async function prepareResponsesRequest( && isCanonicalOpenAiForwardProvider(route.provider) ) { markLinkTurnMissing(logCtx); + const code = "previous_response_not_found"; + logCtx.provider = route.providerName; + logCtx.model = route.modelId; + logCtx.errorCode = code; + markLocalRequestLogRefusal(logCtx, code); return markProxyError(formatErrorResponse( 400, - "previous_response_not_found", + code, "Continuation state is unavailable or corrupt; resend the full conversation without previous_response_id.", )); } diff --git a/structure/transports/response-turn-membership.md b/structure/transports/response-turn-membership.md index 2eb0cddf887..5614aab9a2b 100644 --- a/structure/transports/response-turn-membership.md +++ b/structure/transports/response-turn-membership.md @@ -61,3 +61,5 @@ settlement or provider-opaque replay scope. The route-independent Claude bridge pool key agrees with final Codex selection; see [Claude affinity](../data-planes/inbound-compat.md#claude-affinity-at-final-go-dispatch). Right after continuation expansion, and only for a request that carries a Remote Link turn observer (a link WebSocket turn, or a relayed request with the link relay's internal token header), `request-prepare.ts` reports the expanded input to `src/server/link-turn.ts`; an expansion miss reports a failure. A request without an observer runs no code there, and the header is removed before anything is forwarded (`structure/remote-link.md`). The same seam receives the chain outcome (expanded, unexpanded or none) and, at the two refusals of an unexpanded continuation, marks the row's link continuation as a miss with reason missing. + +When the selected route targets canonical ChatGPT and its continuation cannot be expanded, request preparation logs the selected provider and model with `previous_response_not_found`, `local-refusal`, and synthetic provenance. The refusal precedes inference dispatch and has no physical attempt. A client resend carrying the full history is a separate request. diff --git a/tests/codex-integration/issue-702-expired-replay-state.test.ts b/tests/codex-integration/issue-702-expired-replay-state.test.ts index 242c93fa83e..362e46b8452 100644 --- a/tests/codex-integration/issue-702-expired-replay-state.test.ts +++ b/tests/codex-integration/issue-702-expired-replay-state.test.ts @@ -17,8 +17,10 @@ import { type ResponseStateMetrics, } from "../../src/responses/state"; import { responseSpillDirectory } from "../../src/responses/spill-store"; +import { PLAINTEXT_V2_COLLABORATION_NAMESPACE } from "../../src/responses/plaintext-v2-agent-messages"; import { startServer } from "../../src/server"; import type { OcxConfig } from "../../src/types"; +import { readRecentUsageEntries } from "../../src/usage/log"; import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; import { INTERNAL_DEADLINE_MS, SERVER_BUDGET_MS } from "../helpers/test-budget"; @@ -779,6 +781,84 @@ describe("Issue #702 expired forward replay state", () => { } }, SERVER_BUDGET_MS); + test.each(["high", "max"] as const)("keyless native Sol in v2-plaintext logs its local continuation refusal (%s)", async effort => { + const upstreamRequests: Record[] = []; + const config = forwardConfig(); + config.apiKeys = []; + config.websockets = true; + config.multiAgentMode = "v2-plaintext"; + config.plaintextV2AgentMessages = false; + config.providers.openai!.upstreamWebsocket = false; + saveConfig(config); + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (url.hostname === "127.0.0.1") return originalFetch(input, init); + expect(url.href).toBe("https://chatgpt.com/backend-api/codex/responses"); + upstreamRequests.push(JSON.parse(String(init?.body))); + return new Response(completedSse(`resp_sol_${upstreamRequests.length}`, HISTORICAL_ASSISTANT_SENTINEL), { + headers: { "content-type": "text/event-stream" }, + }); + }) as typeof fetch; + const server = startServer(0); + let socket: WebSocket | undefined; + try { + const headers = { + "thread-id": "native-sol-plaintext-fixture", + originator: "Codex Desktop", + authorization: `Bearer ${fakeChatGptJwt({ chatgpt_account_id: "acct-sol-plaintext-fixture" })}`, + "chatgpt-account-id": "acct-sol-plaintext-fixture", + }; + const turn = { model: "gpt-6.1-sol", reasoning: { effort }, store: false, tools: [{ + type: "namespace", name: "collaboration", tools: [{ type: "function", name: "spawn_agent", + parameters: { type: "object", properties: { message: { type: "string", encrypted: true } } } }], + }] }; + const history = [inputMessage(HISTORICAL_USER_SENTINEL), { + type: "agent_message", author: "earlier-child", recipient: "main-task", + content: [{ type: "encrypted_content", encrypted_content: "Earlier plaintext agent reply." }], + }, { type: "reasoning", summary: [], encrypted_content: "fixture-opaque-reasoning" }]; + const delta = [inputMessage(CURRENT_USER_SENTINEL)]; + socket = await openResponseSocket(server.url, headers); + const first = await sendSocketTurn(socket, { ...turn, input: history }); + expect(first).toMatchObject({ type: "response.completed", response: { id: "resp_sol_1" } }); + const refused = await sendSocketTurn(socket, { ...turn, previous_response_id: "resp_sol_1", input: delta }); + expect(refused).toMatchObject({ type: "error", status: 400, error: LOCAL_REPLAY_UNAVAILABLE }); + expect(upstreamRequests).toHaveLength(1); + + socket.close(); + socket = await openResponseSocket(server.url, headers); + const recovered = await sendSocketTurn(socket, { ...turn, input: [...history, ...delta] }); + expect(recovered).toMatchObject({ type: "response.completed", response: { id: "resp_sol_2" } }); + expect(upstreamRequests).toHaveLength(2); + expect(upstreamRequests[1]!.previous_response_id).toBeUndefined(); + expect(upstreamRequests[1]).toMatchObject({ + model: "gpt-6.1-sol", + reasoning: { effort }, + tools: [{ name: PLAINTEXT_V2_COLLABORATION_NAMESPACE }], + }); + // The proxy may prepend catalog guidance before the client's conversation. + expect((upstreamRequests[1]!.input as unknown[]).slice(-4)).toEqual([ + history[0], inputMessage("Earlier plaintext agent reply."), history[2], ...delta, + ]); + + const rows = readRecentUsageEntries(3, testHome); + expect(rows.map(row => row.status)).toEqual([200, 400, 200]); + const refusalRow = rows[1]!; + expect(refusalRow).toMatchObject({ + client: "codex_desktop", admissionKind: "loopback", inboundProtocol: "responses", + requestedModel: "gpt-6.1-sol", requestedEffort: effort, + model: "gpt-6.1-sol", provider: "openai", errorCode: "previous_response_not_found", + terminalSource: "synthetic", failureStage: "headers-only", failureCause: "local-refusal", usageStatus: "unreported", + routeDecision: { routeKind: "native", selected: { provider: "openai", model: "gpt-6.1-sol", reason: "native-family" } }, + }); + expect(refusalRow.attempts ?? []).toEqual([]); + expect(refusalRow.usage).toBeUndefined(); + expect(rows[2]!.attempts).toMatchObject([{ sendCount: 1, recoveryKinds: [] }]); + } finally { + socket?.close(); + await server.stop(true); + } + }, SERVER_BUDGET_MS); + test("forward mode expands fresh replay state before continuing upstream", async () => { const scenario = await runForwardScenario("fresh"); From c888f10c2b40ef887e7f097afbaef58e1d4de030 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 03:28:46 +0900 Subject: [PATCH 2/3] fix(responses): preserve recovery sends on continuation refusal Record physical encrypted-task recovery attempts when native fallback refuses a continuation. Reserve zero-dispatch attribution for requests that made no inference send. Refs #8858 --- .../docs/es/guides/codex-integration.md | 4 +- .../content/docs/guides/codex-integration.md | 12 ++-- .../docs/ko/guides/codex-integration.md | 12 ++-- src/server/responses/agent-task-recovery.ts | 55 ++++++++++++--- src/server/responses/request-prepare.ts | 34 ++++++++-- structure/subagents.md | 6 +- .../transports/response-turn-membership.md | 2 +- .../issue-702-expired-replay-state.test.ts | 68 +++++++++++++++++++ 8 files changed, 161 insertions(+), 32 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/codex-integration.md b/docs-site/src/content/docs/es/guides/codex-integration.md index 922deb4d3c6..fe4d8442b24 100644 --- a/docs-site/src/content/docs/es/guides/codex-integration.md +++ b/docs-site/src/content/docs/es/guides/codex-integration.md @@ -226,9 +226,9 @@ En el modo de proveedor dedicado, `requires_openai_auth = true` mantiene Codex A El proxy admite hasta 128 conexiones Responses WebSocket orientadas al cliente. Cuando una nueva conexión encuentra las 128 ranuras ocupadas, cierra la conexión inactiva menos recientemente utilizada para hacer espacio. Las conexiones con una respuesta activa, una herramienta de cliente pendiente o resultados de aprobación, una sesión de dirección/inyección nativa o una salida almacenada en búfer están protegidas. Si no se puede liberar ninguna conexión inactiva, la nueva conexión recibe la respuesta de capacidad `503` existente. Un cliente reclamado puede volver a conectarse para solicitudes posteriores utilizando el manejo de continuación existente. Esto sucede solo bajo presión de conexión, no necesita configuración y no cambia las conexiones de voz o la reutilización de la conexión ascendente. -Si una continuación canónica hacia adelante ChatGPT hace referencia a un estado de repetición local caducado o faltante, opencodex devuelve `previous_response_not_found` antes de enviar cualquier cosa aguas arriba. El cliente Codex de WebSocket reconoce este error y puede volver a conectarse con su contexto completo retenido, incluyendo llamadas de herramientas completadas y sus resultados, dentro de su presupuesto de reintento de flujo normal. Por lo tanto, una tarea inactiva no necesita una tarea nueva únicamente porque la caché de reproducción del proxy expiró. El estado de continuación reproducido se conserva durante 24 horas y permanece limitado por su memoria, disco y límites de entrada existentes; esto no recupera el historial que el cliente ya no tiene. HTTP clientes deben manejar el error explícitamente y volver a enviar su contexto completo sin `previous_response_id`. Volver a intentar solo el mismo ID no puede recuperar el estado faltante. +Si una continuación canónica hacia adelante ChatGPT hace referencia a un estado de repetición local caducado o faltante, opencodex devuelve `previous_response_not_found` antes de reenviar la continuación. El cliente Codex de WebSocket reconoce este error y puede volver a conectarse con su contexto completo retenido, incluyendo llamadas de herramientas completadas y sus resultados, dentro de su presupuesto de reintento de flujo normal. Por lo tanto, una tarea inactiva no necesita una tarea nueva únicamente porque la caché de reproducción del proxy expiró. El estado de continuación reproducido se conserva durante 24 horas y permanece limitado por su memoria, disco y límites de entrada existentes; esto no recupera el historial que el cliente ya no tiene. HTTP clientes deben manejar el error explícitamente y volver a enviar su contexto completo sin `previous_response_id`. Volver a intentar solo el mismo ID no puede recuperar el estado faltante. -Si el proxy ya ha seleccionado la ruta de reenvío a ChatGPT, `usage.jsonl` registra el proveedor y el modelo seleccionados junto con `errorCode: "previous_response_not_found"` y `failureCause: "local-refusal"`. La solicitud rechazada no consume cuota del modelo. El reenvío del contexto completo por parte del cliente se registra como una solicitud aparte y puede consumir cuota. +`usage.jsonl` registra el proveedor y el modelo seleccionados de ChatGPT junto con `errorCode: "previous_response_not_found"`. Si la preparación no envió ninguna solicitud de inferencia, la entrada incluye `failureCause: "local-refusal"` y la solicitud no consume cuota del modelo. Si se habilita la recuperación de tareas cifradas, esta puede enviar una solicitud de inferencia antes de que se seleccione la ruta nativa de respaldo. La entrada registra ese intento, que puede consumir cuota. El reenvío del contexto completo por parte del cliente se registra como una solicitud aparte y puede consumir cuota. El mismo rechazo se aplica cuando el estado referenciado pertenece a un ámbito de tarea cliente diferente, incluso cuando la nueva solicitud parece llevar entrada completa. El proxy no puede probar que la entrada está completa, por lo que no elimina silenciosamente `previous_response_id` ni revela si existe un estado coincidente. Cuando está activado el modo `v2-plaintext` o la opción `plaintextV2AgentMessages`, la reproducción local exige el mismo principal de OpenCodex admitido y el `thread-id` propio y no vacío de la solicitud. Un hilo principal, una dirección de loopback, una credencial del proveedor o una clave de relleno no constituyen esa identidad. Sin principal admitido o sin hilo propio, envía la conversación completa sin `previous_response_id`. Las configuraciones predeterminadas de Codex y DSH en loopback no establecen esa identidad. El estado conservado mientras cualquiera de las dos opciones está activada permanece vinculado al desactivarlas. El modo predeterminado `v1` conserva la continuación por hilo principal para el estado no vinculado, también en loopback. Esto es independiente de los ID de Responses gestionados por el proveedor nativo. diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index d0e6c6cee07..217b4545e1c 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -503,7 +503,7 @@ later requests using the existing continuation handling. This happens only under pressure, needs no setting, and does not change voice connections or upstream connection reuse. If a canonical ChatGPT forward continuation references expired or missing local replay state, -opencodex returns `previous_response_not_found` before sending anything upstream. Codex's +opencodex returns `previous_response_not_found` before forwarding the continuation. Codex's WebSocket client recognizes this error and can reconnect with its full retained context, including completed tool calls and their results, within its normal stream retry budget. An idle task therefore does not need a new task solely because the proxy's replay cache expired. @@ -512,10 +512,12 @@ disk, and entry ceilings; this does not recover history the client no longer has must handle the error explicitly and resend their full context without `previous_response_id`. Retrying only the same ID cannot recover missing state. -When the proxy has already selected the ChatGPT forward route, `usage.jsonl` records the -selected provider and model with `errorCode: "previous_response_not_found"` and -`failureCause: "local-refusal"`. The refused request uses no model quota. A client resend with -the full context is logged separately and can use quota. +`usage.jsonl` records the selected ChatGPT provider and model with +`errorCode: "previous_response_not_found"`. If preparation made no inference send, the row has +`failureCause: "local-refusal"` and the request uses no model quota. Opt-in encrypted-task +recovery can send an inference request before native fallback is selected. The row records that +attempt, which may use quota. A client resend with the full context is logged separately and can +use quota. The same refusal applies when the referenced state belongs to a different client task scope, including when the new request appears to carry complete input. The proxy cannot prove that input diff --git a/docs-site/src/content/docs/ko/guides/codex-integration.md b/docs-site/src/content/docs/ko/guides/codex-integration.md index e33410300aa..3cfa116ec0b 100644 --- a/docs-site/src/content/docs/ko/guides/codex-integration.md +++ b/docs-site/src/content/docs/ko/guides/codex-integration.md @@ -241,7 +241,7 @@ WebSocket으로 연결하면 상류 응답 전에 연결 승인이 끝나므로, 나중에 추가할 수는 없습니다. 네이티브 ChatGPT forward 요청의 로컬 재생 상태가 만료되었거나 없으면 opencodex는 -upstream 요청 전에 `previous_response_not_found`를 반환합니다. Codex WebSocket 클라이언트는 +후속 요청을 ChatGPT에 전달하기 전에 `previous_response_not_found`를 반환합니다. Codex WebSocket 클라이언트는 일반 스트림 재시도 한도 안에서 다시 연결하고, 완료된 도구 호출과 결과를 포함한 현재 보유 컨텍스트 전체를 다시 보낼 수 있습니다. 따라서 프록시의 재생 캐시가 만료되었다는 이유만으로 새 작업을 만들 필요는 없습니다. 재생 상태는 24시간 보존하며 기존 메모리·디스크·항목 수 @@ -249,10 +249,12 @@ upstream 요청 전에 `previous_response_not_found`를 반환합니다. Codex W HTTP 클라이언트는 이 오류를 직접 처리하고 `previous_response_id` 없이 전체 컨텍스트를 다시 보내야 합니다. 같은 ID만 재시도해서는 누락된 상태를 복구할 수 없습니다. -프록시가 이미 ChatGPT 전달 경로를 선택했다면 `usage.jsonl`에 선택된 공급자와 모델, 그리고 -`errorCode: "previous_response_not_found"`, `failureCause: "local-refusal"`이 기록됩니다. -거부된 요청은 모델 사용량 한도를 소모하지 않습니다. 클라이언트가 전체 컨텍스트를 다시 -보내면 별도 요청으로 기록되며 모델 사용량 한도를 소모할 수 있습니다. +`usage.jsonl`에는 선택된 ChatGPT 공급자와 모델 및 `errorCode: "previous_response_not_found"`가 +기록됩니다. 요청 준비 중 추론 요청을 보내지 않았다면 `failureCause: "local-refusal"`이 기록되며 +모델 사용량 한도를 소모하지 않습니다. 암호화된 작업 복구를 활성화한 경우 네이티브 대체 모델을 +선택하기 전에 복구용 추론 요청을 보낼 수 있습니다. 이 시도는 같은 항목에 기록되며 모델 사용량 +한도를 소모할 수 있습니다. 클라이언트가 전체 컨텍스트를 다시 보내면 별도 요청으로 기록되며 +모델 사용량 한도를 소모할 수 있습니다. 참조한 상태의 client task scope가 현재 요청과 다를 때도 같은 거부 응답을 반환합니다. 새 요청이 전체 입력처럼 보여도 프록시는 그것이 완전한 대화인지 증명할 수 없으므로 diff --git a/src/server/responses/agent-task-recovery.ts b/src/server/responses/agent-task-recovery.ts index 159ed7abd03..83557ed9008 100644 --- a/src/server/responses/agent-task-recovery.ts +++ b/src/server/responses/agent-task-recovery.ts @@ -60,6 +60,20 @@ export type AgentTaskRecoveryResult = | { readonly recovered: true } | { readonly recovered: false; readonly reason: AgentTaskRecoveryFailureReason }; +interface RecoverySend { + model: string; + status: number | undefined; + durationMs: number; + usage: unknown; +} + +interface AgentTaskRecoveryContext { + parentThreadId?: string | null; + abortSignal?: AbortSignal; + /** Only the caller that starts a flight observes its sends. */ + onSend?: (send: RecoverySend) => void; +} + export function agentTaskRecoveryConfig(config: OcxConfig): AgentTaskRecoveryOptions | null { const raw = config.agentTaskRecovery; if (!raw || raw.enabled !== true) return null; @@ -400,8 +414,9 @@ function sseDataPayloads(raw: string): string[] { return payloads; } -function assignmentFromRecoverySse(raw: string, envelope: AgentEnvelope): string | null { +function parseRecoverySse(raw: string, envelope: AgentEnvelope): { assignment: string | null; usage: unknown } { let assignment: string | null = null; + let usage: unknown; let completed = false; let terminalFailure = false; let conflictingAssignments = false; @@ -419,6 +434,9 @@ function assignmentFromRecoverySse(raw: string, envelope: AgentEnvelope): string || event?.type === "response.incomplete" || event?.type === "error" ) terminalFailure = true; + if (event?.type === "response.completed" || event?.type === "response.failed" || event?.type === "response.incomplete") { + usage = event.response?.usage ?? usage; + } if (event?.type === "response.completed" && event.response?.status === "completed") { completed = true; } @@ -453,9 +471,12 @@ function assignmentFromRecoverySse(raw: string, envelope: AgentEnvelope): string else if (assignment !== candidate) conflictingAssignments = true; } } - return completed && !terminalFailure && !conflictingAssignments && !malformedEvent && !invalidAssignment - ? assignment - : null; + return { + assignment: completed && !terminalFailure && !conflictingAssignments && !malformedEvent && !invalidAssignment + ? assignment + : null, + usage, + }; } interface RecoveryAttempt { @@ -471,19 +492,26 @@ async function attemptRecovery( signal: AbortSignal, abortSignal: AbortSignal | undefined, deadlineSignal: AbortSignal, + onSend: AgentTaskRecoveryContext["onSend"], ): Promise { const terminal = (resolution: AgentTaskRecoveryResolution): RecoveryAttempt => ({ resolution, retryable: false, }); + const model = options.model ?? "gpt-5.6-sol"; + const bodyPayload = recoveryPayload(envelope, model); + const startedAt = Date.now(); + let status: number | undefined; + let usage: unknown; try { const response = await fetch(RECOVERY_ENDPOINT, { method: "POST", headers: admission.headers, - body: recoveryPayload(envelope, options.model ?? "gpt-5.6-sol"), + body: bodyPayload, signal, redirect: "error", }); + status = response.status; if (!response.ok) { // A rejected or never-settling cancellation must not extend the recovery deadline. try { void response.body?.cancel().catch(() => undefined); } catch { /* already closed */ } @@ -506,7 +534,9 @@ async function attemptRecovery( if (abortSignal?.aborted) return terminal({ recovered: false, reason: "recovery_aborted" }); if (deadlineSignal.aborted || body.timedOut) return terminal({ recovered: false, reason: "recovery_timeout" }); if (body.truncated || body.oversized || !body.displaySafe) return terminal({ recovered: false, reason: "recovery_invalid_output" }); - const assignment = assignmentFromRecoverySse(body.text, envelope); + const result = parseRecoverySse(body.text, envelope); + usage = result.usage; + const { assignment } = result; return terminal(assignment === null ? { recovered: false, reason: "recovery_invalid_output" } : { recovered: true, assignment }); @@ -517,6 +547,8 @@ async function attemptRecovery( return decodeFailure === "invalid_utf8" ? terminal({ recovered: false, reason: "recovery_invalid_output" }) : { resolution: { recovered: false, reason: "recovery_transport_error" }, retryable: true }; + } finally { + onSend?.({ model, status, durationMs: Date.now() - startedAt, usage }); } } @@ -524,7 +556,8 @@ async function requestRecovery( admission: RecoveryAdmission, envelope: AgentEnvelope, options: AgentTaskRecoveryOptions, - abortSignal?: AbortSignal, + abortSignal: AbortSignal | undefined, + onSend: AgentTaskRecoveryContext["onSend"], ): Promise { const controller = new AbortController(); const timeoutMs = options.timeoutMs ?? 45_000; @@ -544,7 +577,7 @@ async function requestRecovery( : 0; for (let attempt = 0; ; attempt += 1) { const { resolution, retryable, retryHeaders } = await attemptRecovery( - admission, envelope, options, signal, abortSignal, controller.signal, + admission, envelope, options, signal, abortSignal, controller.signal, onSend, ); if (resolution.recovered || !retryable || attempt >= retries) return resolution; // Retry-After is the provider's floor, not something our backoff cap may shorten. @@ -575,7 +608,7 @@ export async function recoverEncryptedAgentTask( input: unknown, options: AgentTaskRecoveryOptions, config: OcxConfig, - context: { parentThreadId?: string | null; abortSignal?: AbortSignal } = {}, + context: AgentTaskRecoveryContext = {}, ): Promise { return (await recoverEncryptedAgentTaskWithResult(req, input, options, config, context)).recovered; } @@ -586,7 +619,7 @@ export async function recoverEncryptedAgentTaskWithResult( input: unknown, options: AgentTaskRecoveryOptions, config: OcxConfig, - context: { parentThreadId?: string | null; abortSignal?: AbortSignal } = {}, + context: AgentTaskRecoveryContext = {}, ): Promise { // Admission is deliberately checked before cache access. A cache hit must not // turn this process into a plaintext oracle for an unauthenticated caller. @@ -596,7 +629,7 @@ export async function recoverEncryptedAgentTaskWithResult( const result = await resolveCachedAgentTaskRecoveryWithResult( cacheKey, options.cacheEntries ?? 200, - signal => requestRecovery(admission, envelope, options, signal), + signal => requestRecovery(admission, envelope, options, signal, context.onSend), context.abortSignal, ); if (!result.recovered) { diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index 02e9b29b9d3..9eef9980554 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -1,6 +1,7 @@ import { responseReplayOwnerKey } from "../../responses/state/replay-owner"; import { isPlaintextV2AgentMessagesEnabled } from "../../config/multi-agent-surface"; import { projectLocalModelRefusalLog } from "../request-log-failure-detail"; +import { attributePhysicalAttempt } from "../request-log-failure-attribution"; import { failLinkTurnExpansion, markLinkTurnMissing, observeLinkTurnExpansion } from "../link-turn"; import { inputAdmissionRefusalMessage } from "./input-admission"; import { clientFacingModelLabel, clientFacingModelText } from "../../lib/error-destination"; @@ -90,7 +91,8 @@ import { anthropicSessionKeyFromParts } from "../../oauth/anthropic-routing"; import { configuredAnthropicInstance } from "../../providers/anthropic-instance"; import { isTranslatorBudgetExceededError } from "../../lib/translator-budget"; import { bindTurnTerminationScope, rememberDeliveredFinalAnswer } from "../../responses/turn-termination"; -import { markLocalRequestLogRefusal, noteCodexSelectionAffinity, observeCacheDiagnosticInbound, rebindCacheDiagnosticBody, requestLogSpeedLabel, readConfiguredCodexServiceTier } from "../request-log"; +import { beginRequestAttempt, finishRequestAttempt, markLocalRequestLogRefusal, noteAttemptSend, noteCodexSelectionAffinity, observeCacheDiagnosticInbound, rebindCacheDiagnosticBody, requestLogSpeedLabel, readConfiguredCodexServiceTier, usageFromResponsesPayload } from "../request-log"; +import type { PersistedUsageAttempt } from "../../usage/log"; import type { RouteResult } from "../../router"; import { captureRouteStaticPolicy, @@ -1145,6 +1147,7 @@ export async function prepareResponsesRequest( } let recoveryFailureReason: AgentTaskRecoveryFailureReason | undefined; + let recoveryAttempts: PersistedUsageAttempt[] | undefined; // Native fallback and explicitly trusted direct Responses routes can consume ciphertext, // so recover only after final route selection. // @@ -1177,7 +1180,24 @@ export async function prepareResponsesRequest( (body as { input?: unknown } | undefined)?.input, agentTaskRecovery, config, - { parentThreadId, abortSignal: options.abortSignal }, + { + parentThreadId, + abortSignal: options.abortSignal, + onSend: hasUnexpandedPreviousResponse ? ({ model, status, durationMs, usage }) => { + const attempts = recoveryAttempts ??= []; + const ordinal = (logCtx.attempts?.length ?? 0) + attempts.length + 1; + const attempt = beginRequestAttempt(ordinal, OPENAI_CODEX_PROVIDER_ID, model, "openai-responses"); + noteAttemptSend(attempt, undefined); + finishRequestAttempt(attempt, status ?? 502, durationMs, usageFromResponsesPayload(usage)); + if (status === undefined) { + attempt.failureStage = "pre-header"; + attempt.failureCause = "transport-ambiguous"; + } else { + attributePhysicalAttempt(attempt); + } + attempts.push(attempt); + } : undefined, + }, ); recovered = result.recovered; recoveryFailureReason = result.recovered ? undefined : result.reason; @@ -1446,8 +1466,8 @@ export async function prepareResponsesRequest( } // The canonical ChatGPT backend rejects previous_response_id, so a local replay miss leaves no - // safe way to recover the omitted history. Fail before auth, adapter construction, or upstream - // I/O instead of stripping the id and silently forwarding a context-free delta (#702). + // safe way to recover the omitted history. Fail before dispatching the continuation itself + // instead of stripping the id and silently forwarding a context-free delta (#702). // Codex recognizes previous_response_not_found on WebSocket errors and reconnects with its // full input. A generic invalid_request_error instead terminates the task after cache expiry. if ( @@ -1459,7 +1479,11 @@ export async function prepareResponsesRequest( logCtx.provider = route.providerName; logCtx.model = route.modelId; logCtx.errorCode = code; - markLocalRequestLogRefusal(logCtx, code); + // A recovery send already finished on its own model and status. Keep it off activeAttempt, + // which the log finalizer stamps with the continuation's terminal outcome. + if (recoveryAttempts) (logCtx.attempts ??= []).push(...recoveryAttempts); + if (logCtx.attempts?.some(attempt => attempt.sendCount > 0)) logCtx.terminalSource = "synthetic"; + else markLocalRequestLogRefusal(logCtx, code); return markProxyError(formatErrorResponse( 400, code, diff --git a/structure/subagents.md b/structure/subagents.md index b102bbd6e5a..bb304a81f17 100644 --- a/structure/subagents.md +++ b/structure/subagents.md @@ -152,9 +152,9 @@ recipient, sender, ciphertexts) rather than a delimiter-joined string, so no fie a boundary. One fixed-endpoint request forwards separate parts, and assignment replacement compares the complete original item snapshot before splicing the run. Recovery output is model-transcribed plaintext, not cryptographic fidelity proof. An opt-in `retries` bound — off -by default and capped at two extra sends — re-issues the same admitted request only on a transient -upstream status or a transport failure, inside the same deadline and shared flight; terminal -statuses, invalid output, and budget exhaustion keep the bounded refusal reasons unchanged. +by default and capped at two extra sends — re-issues the admitted request only on a transient status +or transport failure, within the same deadline and shared flight. The request that starts the flight +owns its [recovery attempt telemetry](transports/response-turn-membership.md). Cache hits and requests joining the flight do not claim its sends. Recovery recognises all four codex-rs message types (NEW_TASK, MESSAGE, FOLLOWUP_TASK, FINAL_ANSWER); a FINAL_ANSWER envelope may omit the Task name line, in which case the structured recipient is not cross-checked because the envelope names no recipient, and diff --git a/structure/transports/response-turn-membership.md b/structure/transports/response-turn-membership.md index 5614aab9a2b..d66cd7066ec 100644 --- a/structure/transports/response-turn-membership.md +++ b/structure/transports/response-turn-membership.md @@ -62,4 +62,4 @@ The route-independent Claude bridge pool key agrees with final Codex selection; Right after continuation expansion, and only for a request that carries a Remote Link turn observer (a link WebSocket turn, or a relayed request with the link relay's internal token header), `request-prepare.ts` reports the expanded input to `src/server/link-turn.ts`; an expansion miss reports a failure. A request without an observer runs no code there, and the header is removed before anything is forwarded (`structure/remote-link.md`). The same seam receives the chain outcome (expanded, unexpanded or none) and, at the two refusals of an unexpanded continuation, marks the row's link continuation as a miss with reason missing. -When the selected route targets canonical ChatGPT and its continuation cannot be expanded, request preparation logs the selected provider and model with `previous_response_not_found`, `local-refusal`, and synthetic provenance. The refusal precedes inference dispatch and has no physical attempt. A client resend carrying the full history is a separate request. +When the selected route targets canonical ChatGPT and its continuation cannot be expanded, request preparation logs the selected provider and model with `previous_response_not_found` and synthetic provenance. If preparation made no inference send, the row has `local-refusal` and no physical attempt. Opt-in encrypted-task recovery can send before a reroute to native fallback. In that case the row preserves the recovery attempts with their own model, status, and any reported usage. A client resend carrying the full history is a separate request. diff --git a/tests/codex-integration/issue-702-expired-replay-state.test.ts b/tests/codex-integration/issue-702-expired-replay-state.test.ts index 362e46b8452..0d70697a204 100644 --- a/tests/codex-integration/issue-702-expired-replay-state.test.ts +++ b/tests/codex-integration/issue-702-expired-replay-state.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { saveConfig } from "../../src/config"; import { + noteSubagentModelFailure, resetSubagentModelFallbackStateForTests, setSubagentQuotaPrimeForTests, } from "../../src/codex/subagent-model-fallback"; @@ -21,6 +22,7 @@ import { PLAINTEXT_V2_COLLABORATION_NAMESPACE } from "../../src/responses/plaint import { startServer } from "../../src/server"; import type { OcxConfig } from "../../src/types"; import { readRecentUsageEntries } from "../../src/usage/log"; +import { codexHeaders, encryptedInput } from "../helpers/agent-task-recovery"; import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; import { INTERNAL_DEADLINE_MS, SERVER_BUDGET_MS } from "../helpers/test-budget"; @@ -859,6 +861,72 @@ describe("Issue #702 expired forward replay state", () => { } }, SERVER_BUDGET_MS); + test("native fallback continuation refusal records the earlier encrypted-task recovery send", async () => { + const primary = "routed/test-model"; + const native = "gpt-6.1-sol"; + const recoveryModel = "gpt-5.6-sol"; + const upstreamRequests: { url: string; model: string; tool_choice?: { name: string } }[] = []; + const config = forwardConfig(); + config.apiKeys = []; + config.websockets = true; + config.agentTaskRecovery = { enabled: true, model: recoveryModel }; + config.subagentModelFallback = [native]; + config.providers.routed = { + adapter: "openai-chat", baseUrl: "https://example.invalid/v1", authMode: "key", + apiKey: "synthetic-key", models: ["test-model"], + }; + saveConfig(config); + setSubagentQuotaPrimeForTests(async () => {}); + noteSubagentModelFailure(native, "429", config); + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (url.hostname === "127.0.0.1") return originalFetch(input, init); + const { model, tool_choice } = JSON.parse(String(init?.body)); + upstreamRequests.push({ url: url.href, model, tool_choice }); + // The native fallback is unavailable on the ciphertext-only pass. Swap availability + // while recovery is in flight so route selection runs again and picks the native model. + resetSubagentModelFallbackStateForTests(); + noteSubagentModelFailure(primary, "429", config); + return new Response(`data: ${JSON.stringify({ + type: "response.completed", + response: { + status: "completed", + output: [{ type: "function_call", name: "capture_assignment", arguments: '{"assignment":"Recovered task"}' }], + usage: { input_tokens: 30, output_tokens: 5, total_tokens: 35 }, + }, + })}\n\n`, { headers: { "content-type": "text/event-stream" } }); + }) as typeof fetch; + + const server = startServer(0); + let socket: WebSocket | undefined; + try { + const headers = codexHeaders("acct-recovery-refusal", { "thread-id": "recovery-refusal-fixture" }); + socket = await openResponseSocket(server.url, Object.fromEntries(headers)); + const refused = await sendSocketTurn(socket, { + model: primary, previous_response_id: FIRST_RESPONSE_ID, input: encryptedInput(), store: false, + }); + expect(refused).toMatchObject({ type: "error", status: 400, error: LOCAL_REPLAY_UNAVAILABLE }); + expect(upstreamRequests).toEqual([{ + url: "https://chatgpt.com/backend-api/codex/responses", + model: recoveryModel, tool_choice: expect.objectContaining({ name: "capture_assignment" }), + }]); + + const [row] = readRecentUsageEntries(1, testHome); + expect(row).toMatchObject({ + status: 400, provider: "openai", model: native, errorCode: "previous_response_not_found", + terminalSource: "synthetic", spend: { sends: 1 }, + }); + expect(row?.attempts).toMatchObject([{ + provider: "openai", model: recoveryModel, status: 200, sendCount: 1, + usage: { inputTokens: 30, outputTokens: 5, totalTokens: 35 }, + }]); + expect(row?.failureCause).not.toBe("local-refusal"); + } finally { + socket?.close(); + await server.stop(true); + } + }, SERVER_BUDGET_MS); + test("forward mode expands fresh replay state before continuing upstream", async () => { const scenario = await runForwardScenario("fresh"); From b936b4a6e31688af390486abaa87677058ec0e7b Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 19 Nov 2026 03:50:52 +0900 Subject: [PATCH 3/3] fix(usage): account for detached recovery sends Include measured recovery usage on continuation refusals and use the sending model for daily telemetry. Keep a lost-before-headers recovery send unpriced even if another attempt reports usage. Refs #8858 --- .../content/docs/guides/codex-integration.md | 7 +-- .../src/content/docs/guides/telemetry.md | 2 +- src/server/request-log.ts | 10 ++-- src/telemetry/aggregate.ts | 9 ++-- src/usage/summary.ts | 9 ++-- structure/dashboard-and-usage.md | 4 +- structure/pricing.md | 2 +- structure/telemetry.md | 4 ++ .../issue-702-expired-replay-state.test.ts | 49 +++++++++++++++---- tests/usage/usage-telemetry-client.test.ts | 7 +++ 10 files changed, 74 insertions(+), 29 deletions(-) diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index 217b4545e1c..7b71939b186 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -515,9 +515,10 @@ Retrying only the same ID cannot recover missing state. `usage.jsonl` records the selected ChatGPT provider and model with `errorCode: "previous_response_not_found"`. If preparation made no inference send, the row has `failureCause: "local-refusal"` and the request uses no model quota. Opt-in encrypted-task -recovery can send an inference request before native fallback is selected. The row records that -attempt, which may use quota. A client resend with the full context is logged separately and can -use quota. +recovery can send an inference request before native fallback is selected. The Usage summary +includes reported recovery tokens under the recovery model. If a recovery send loses its +connection before headers, the request's full cost remains unknown even if a retry reports +tokens. A client resend with the full context is logged separately and can use quota. The same refusal applies when the referenced state belongs to a different client task scope, including when the new request appears to carry complete input. The proxy cannot prove that input diff --git a/docs-site/src/content/docs/guides/telemetry.md b/docs-site/src/content/docs/guides/telemetry.md index 0b6d8c85646..14c4a4c7a47 100644 --- a/docs-site/src/content/docs/guides/telemetry.md +++ b/docs-site/src/content/docs/guides/telemetry.md @@ -252,7 +252,7 @@ Here is a real example payload produced by `buildTelemetryPayloadV1` (`src/telem | `env.installChannel` | `"npm-global"`, `"pnpm-global"`, `"bun-global"`, `"mise"`, `"standalone"`, `"desktop"`, `"docker"`, `"source"`, or `"unknown"`. | | `activeMinutes` | Distinct UTC minutes (`0`–`1440`) during `day` in which at least one request was logged in `usage.jsonl`. | | `requests` | Request counts by closed outcome class: `completed`, `failed`, `incomplete`, and `aborted`. | -| `models` | Up to 64 rows per day, grouped by unique `(providerKind, modelFamily)` pairs from the closed rosters below (if more than 64 pairs occur in a day, the top 63 rows by requests and total tokens are kept and the remaining rows are merged into `"other"` / `"other"`). Multi-attempt `combo` requests attribute each attempt to the underlying provider and model, so `models[].requests` can sum to more than top-level `requests`. Each row reports `requests` and five disjoint token counters — `inputTokens` (uncached input), `cacheReadTokens`, `cacheWriteTokens`, `outputTokens` (non-reasoning output), and `reasoningTokens` — whose sum equals the request's displayed total tokens (`usageDisplayTotalTokens`). | +| `models` | Up to 64 rows per day, grouped by unique `(providerKind, modelFamily)` pairs from the closed rosters below (if more than 64 pairs occur in a day, the top 63 rows by requests and total tokens are kept and the remaining rows are merged into `"other"` / `"other"`). Combo attempts and token-bearing attempts routed to a different provider or model contribute under the provider and model that handled the send. As a result, `models[].requests` can sum to more than top-level `requests`. Each row reports `requests` and five disjoint token counters — `inputTokens` (uncached input), `cacheReadTokens`, `cacheWriteTokens`, `outputTokens` (non-reasoning output), and `reasoningTokens` — whose sum equals the displayed total for the attributed usage (`usageDisplayTotalTokens`). | | `errors` | Counts of non-completed requests keyed by the closed failure-cause roster (`transport-unsent`, `transport-ambiguous`, `upstream-declined`, `rate-limit`, `quota-exhausted`, `credential-rejected`, `policy-refusal`, `parameter-rejected`, `ciphertext-refusal`, `payload-too-large`, `payload-rejected`, `upstream-fault`, `empty-output`, `client-cancelled`, `local-refusal`). | Closed `providerKind` values (26): `openai`, `chatgpt`, `anthropic`, `claude-subscription`, `google`, `vertex`, `xai`, `deepseek`, `moonshot`, `qwen`, `zai`, `minimax`, `mistral`, `openrouter`, `groq`, `cerebras`, `together`, `fireworks`, `cursor`, `kiro`, `copilot`, `devin`, `ollama`, `lmstudio`, `local-other`, `other`. diff --git a/src/server/request-log.ts b/src/server/request-log.ts index 9dd16451996..e8cbdb54bf4 100644 --- a/src/server/request-log.ts +++ b/src/server/request-log.ts @@ -1559,11 +1559,11 @@ function writeFinalRequestLog( ...(attempt.deliverySummary ? { deliverySummary: { ...attempt.deliverySummary } } : {}), })); const isCombo = logCtx.comboId !== undefined && (attempts?.length ?? 0) > 0; - // A key or account rotation splits the attempt and clears `logCtx.usage`, so a multi-attempt - // request totals from its attempts, combo or not. One attempt keeps the request-level usage - // (and its input estimate); a locally answered row sent nothing and keeps its own. - const aggregate = isCombo || ((attempts?.length ?? 0) > 1 && logCtx.localTerminalReason === undefined) - ? aggregateAttemptUsage(attempts ?? []) + // Rotations split usage across attempts. A detached recovery can be the only send, with no + // active attempt or request-level usage. An ordinary single attempt keeps the row's usage. + const aggregate = attempts?.length && (isCombo || (logCtx.localTerminalReason === undefined + && (attempts.length > 1 || (!logCtx.activeAttempt && attempts[0]?.usage)))) + ? aggregateAttemptUsage(attempts) : null; const loggedUsage = aggregate?.usage ?? existing.usage; const usageStatus = aggregate?.status ?? existing.status; diff --git a/src/telemetry/aggregate.ts b/src/telemetry/aggregate.ts index e3fd5cff469..893af5c21bf 100644 --- a/src/telemetry/aggregate.ts +++ b/src/telemetry/aggregate.ts @@ -265,9 +265,12 @@ export function createDailyTelemetryAccumulator(day: string): DailyTelemetryAccu errors[cause as TelemetryFailureCause] = (errors[cause as TelemetryFailureCause] ?? 0) + 1; } - if (entry.provider === "combo" && entry.attempts && entry.attempts.length > 0) { - for (const attempt of entry.attempts) { - addModelAttribution(attempt.provider, attempt.model, attempt.usage); + const attempts = entry.attempts; + const isCombo = entry.provider === "combo"; + if (attempts?.length && (isCombo || attempts.some(attempt => attempt.usage + && (attempt.provider !== entry.provider || attempt.model !== entry.model)))) { + for (const attempt of attempts) { + if (isCombo || attempt.usage) addModelAttribution(attempt.provider, attempt.model, attempt.usage); } } else { addModelAttribution(entry.provider, entry.model, entry.usage); diff --git a/src/usage/summary.ts b/src/usage/summary.ts index 4884c59f294..43013650823 100644 --- a/src/usage/summary.ts +++ b/src/usage/summary.ts @@ -859,15 +859,16 @@ function blankRequestCounts(): UsageRequestCounts { /** * A usage-less attempt that provably cost nothing: it never reached upstream, or upstream refused it * with an HTTP error before any output (providers do not bill a pre-generation 429/401/5xx). One - * whose stream began, aborted, or ended without a status may have generated billed tokens, so it - * stays an unknown cost. A request made only of such zeros carries neither fact and counts unpriced. + * whose stream began, aborted, or lost the connection before a confirmed status may have billed + * tokens, so its cost stays unknown. A request made only of known zeros carries neither fact and counts unpriced. */ function spentNothing(attempt: NonNullable[number] | undefined): boolean { if (!attempt || attempt.usage) return false; if (attempt.sendCount === 0 || attempt.locallyAnswered === true) return true; - // A 499 is the client hanging up on a send upstream may already be generating for. + // A client cancellation or ambiguous disconnect may leave generation running upstream. return attempt.status >= 400 && attempt.status !== 499 - && attempt.streamAborted !== true && attempt.firstOutputMs === undefined; + && attempt.failureCause !== "transport-ambiguous" && attempt.streamAborted !== true + && attempt.firstOutputMs === undefined; } function bumpRequestCounts(counts: UsageRequestCounts, facts: number, amount = 1): void { diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 8c3df65ef39..ee7e1588e73 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -185,7 +185,7 @@ retains separate flat records when retries change keys, and isolates each record from parent combo totals and adapter-loop aggregation. Reported failure usage is retained; missing usage and historical identities remain unknown. Native wire snapshots replace only the current physical response contribution, preserving prior sends on the same key without counting -repeated inspections twice. A row with two or more attempts, combo or not, takes its request total from those attempts, so a key or account rotation is not reported as its last record alone; a single-attempt or locally answered row keeps its request-level usage. Consumers sum the flat attempts once and keep subscription quota +repeated inspections twice. Combo and multi-attempt requests take their totals from the flat attempts. A continuation refusal with a single detached recovery send also includes its measured usage. Ordinary single-attempt requests and non-combo local answers keep their request-level usage. Consumers sum the flat attempts once and keep subscription quota observations separate from token or API-equivalent cost totals. `src/server/hub-usage.ts` serves `GET /v1/usage` on hubs for an explicit configured data key. The authenticated key selects the aggregate; query parameters cannot select an API-key identity. Unscoped environment/admin credentials and loopback bypass are not admitted. The response projects only this client's numeric totals, provider/model/day rows and incomplete-history metadata through `src/remote/hub-usage.ts`; accounts, raw records and key IDs are omitted. Unknown fields are stripped at every object boundary and the serialized body is capped at 1 MiB. @@ -290,7 +290,7 @@ neither the old byte window nor the parsed-entry cap can discard an earlier pref surface filtering. `managementUsageMaxReadBytes` remains a recognized compatibility setting for bounded legacy readers, but it is not an accuracy limit or tuning knob for `GET /api/usage`. A Codex-surface response includes an `accounts` breakdown keyed by stable non-PII `accountLogLabel`; cards join it to the management account DTO for 30-day tokens, API-equivalent cost and coverage. New main-pool rows use `main`; legacy bare `openai` rows remain ambiguous. -A missing `usage.jsonl` returns a zeroed summary with 200 because a fresh install has no usage. Unmeasured requests remain distinct from measured zero through `measured / reported / unreported / unsupported / estimated` counts and their coverage totals. Cost estimates in `src/usage/cost.ts` price only `reported` or `estimated` usage, so a partly measured row is never given a confident, understated cost; per-row `pricedRequests` / `unpricedRequests` count a request once, unpriced when any attempt is unpriceable, while a usage-less attempt that made no physical send (`sendCount === 0` or `locallyAnswered`) or was refused with an HTTP status >= 400 other than a 499 client cancel before any output (no `streamAborted`, no `firstOutputMs`) is a known zero, and a row with any measured attempt counts priced or unpriced, never unmetered, whatever its aggregate status. A usage-less attempt whose response began, aborted, was cancelled by the client, or has no error status may have been billed and stays unpriced. +A missing `usage.jsonl` returns a zeroed summary with 200 because a fresh install has no usage. Unmeasured requests remain distinct from measured zero through `measured / reported / unreported / unsupported / estimated` counts and their coverage totals. Cost estimates in `src/usage/cost.ts` price only `reported` or `estimated` usage. Per-row `pricedRequests` and `unpricedRequests` count a request once. A row with any measured attempt qualifies for one of those counts regardless of its aggregate usage status. An attempt without usage is a known zero when it sent nothing or upstream refused it before output. A stream that began, aborted, or was cancelled may have incurred charges. A `transport-ambiguous` send without usage also leaves the request unpriced, including when a retry supplies measured tokens. Normal dashboard pages use the document as their vertical scroller. In `gui/src/styles.css`, body horizontal overflow is clipped without creating a second scrollport; the mobile open-drawer state also locks document overflow. The shared sidebar stays viewport-height through the end of Codex and Claude account pages. `gui/tests/shared-scroll-browser.ts` checks the built entry and App styles with short/long content, both themes, desktop chrome, collapsed navigation and mobile widths. The Usage tab renders that shape and the main Dashboard shows its 30-day summary. The 200-entry in-memory `requestLog` is not the aggregation source; the JSONL ledger is. Usage table scrollports in `gui/src/styles-usage-workspace.css` contain absolute screen-reader captions so long tables do not extend the outer document beyond the report; `gui/tests/usage-scroll-browser.ts` measures that boundary and last-row reachability at desktop and mobile widths. Ledger read failures instead return `500 { error: "read_failed" }`. Shared GUI usage admission reads that body before classifying HTTP failure and also rejects the legacy HTTP-200 envelope, so every shared cache retains its last valid report rather than fabricating zero totals. > Decision record: [ADR-0106](decisions/ADR-0106-usage-read-failure-contract.md) diff --git a/structure/pricing.md b/structure/pricing.md index 7d9cf8d0ec7..99ef1aea140 100644 --- a/structure/pricing.md +++ b/structure/pricing.md @@ -63,4 +63,4 @@ policy-only edits invalidate price memoization and usage caches; identical reloa `tests/server/model-costs-pricing-cache.test.ts` exercises warmed cache invalidation and reset. These settings affect estimates, not upstream billing or official catalog price lists. -Only reported or estimated usage is priced by `src/usage/cost.ts`. Partial tokens on an unreported or unsupported attempt do not establish its full cost. `src/usage/summary.ts` marks a multi-attempt request unpriced when any potentially billed attempt lacks measured usage, while a refusal before generation without usage remains a known zero. Measured attempts retain their individual estimates. +Only reported or estimated usage is priced by `src/usage/cost.ts`. Partial tokens on an unreported or unsupported attempt do not establish its full cost. `src/usage/summary.ts` marks a multi-attempt request unpriced when any potentially billed attempt lacks measured usage, including a `transport-ambiguous` send. A confirmed upstream refusal before generation without usage remains a known zero. Measured attempts retain their individual estimates. diff --git a/structure/telemetry.md b/structure/telemetry.md index 48b307216b3..316d1d34554 100644 --- a/structure/telemetry.md +++ b/structure/telemetry.md @@ -102,6 +102,10 @@ only without retaining ledger rows in memory, mapping providers to `PROVIDER_KIN via `src/usage/request-outcome.ts`, and decomposing usage into five disjoint token buckets (`inputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `outputTokens`, `reasoningTokens`) whose sum matches `usageDisplayTotalTokens` in `src/usage/totals.ts`. +Combo rows attribute each attempt to its own provider and model. When a non-combo attempt with +usage names a different provider or model from the request row, telemetry attributes each +token-bearing attempt separately. This includes recovery usage before a continuation refusal. +Top-level outcome counts still count each request once. `src/telemetry/payload.ts` resolves the install channel and validates the built payload with `validateTelemetryPayloadV1`. `src/telemetry/sender.ts` posts to the constant collector URL diff --git a/tests/codex-integration/issue-702-expired-replay-state.test.ts b/tests/codex-integration/issue-702-expired-replay-state.test.ts index 0d70697a204..13489138a8f 100644 --- a/tests/codex-integration/issue-702-expired-replay-state.test.ts +++ b/tests/codex-integration/issue-702-expired-replay-state.test.ts @@ -20,8 +20,10 @@ import { import { responseSpillDirectory } from "../../src/responses/spill-store"; import { PLAINTEXT_V2_COLLABORATION_NAMESPACE } from "../../src/responses/plaintext-v2-agent-messages"; import { startServer } from "../../src/server"; +import { aggregateTelemetryForDay } from "../../src/telemetry/aggregate"; import type { OcxConfig } from "../../src/types"; import { readRecentUsageEntries } from "../../src/usage/log"; +import { computeEntryCost, summarizeUsage } from "../../src/usage/summary"; import { codexHeaders, encryptedInput } from "../helpers/agent-task-recovery"; import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; @@ -861,7 +863,8 @@ describe("Issue #702 expired forward replay state", () => { } }, SERVER_BUDGET_MS); - test("native fallback continuation refusal records the earlier encrypted-task recovery send", async () => { + test.each(["single send", "ambiguous retry"] as const)("native fallback continuation refusal accounts for recovery usage: %s", async scenario => { + const retry = scenario === "ambiguous retry"; const primary = "routed/test-model"; const native = "gpt-6.1-sol"; const recoveryModel = "gpt-5.6-sol"; @@ -869,7 +872,7 @@ describe("Issue #702 expired forward replay state", () => { const config = forwardConfig(); config.apiKeys = []; config.websockets = true; - config.agentTaskRecovery = { enabled: true, model: recoveryModel }; + config.agentTaskRecovery = { enabled: true, model: recoveryModel, retries: retry ? 1 : 0 }; config.subagentModelFallback = [native]; config.providers.routed = { adapter: "openai-chat", baseUrl: "https://example.invalid/v1", authMode: "key", @@ -883,6 +886,7 @@ describe("Issue #702 expired forward replay state", () => { if (url.hostname === "127.0.0.1") return originalFetch(input, init); const { model, tool_choice } = JSON.parse(String(init?.body)); upstreamRequests.push({ url: url.href, model, tool_choice }); + if (retry && upstreamRequests.length === 1) throw new TypeError("connection lost before headers"); // The native fallback is unavailable on the ciphertext-only pass. Swap availability // while recovery is in flight so route selection runs again and picks the native model. resetSubagentModelFallbackStateForTests(); @@ -900,27 +904,52 @@ describe("Issue #702 expired forward replay state", () => { const server = startServer(0); let socket: WebSocket | undefined; try { - const headers = codexHeaders("acct-recovery-refusal", { "thread-id": "recovery-refusal-fixture" }); + const account = retry ? "acct-recovery-retry-refusal" : "acct-recovery-refusal"; + const headers = codexHeaders(account, { "thread-id": "recovery-refusal-fixture" }); socket = await openResponseSocket(server.url, Object.fromEntries(headers)); const refused = await sendSocketTurn(socket, { model: primary, previous_response_id: FIRST_RESPONSE_ID, input: encryptedInput(), store: false, }); expect(refused).toMatchObject({ type: "error", status: 400, error: LOCAL_REPLAY_UNAVAILABLE }); - expect(upstreamRequests).toEqual([{ + const recoverySend = { url: "https://chatgpt.com/backend-api/codex/responses", model: recoveryModel, tool_choice: expect.objectContaining({ name: "capture_assignment" }), - }]); + }; + expect(upstreamRequests).toEqual(retry ? [recoverySend, recoverySend] : [recoverySend]); - const [row] = readRecentUsageEntries(1, testHome); + const row = readRecentUsageEntries(1, testHome)[0]!; expect(row).toMatchObject({ status: 400, provider: "openai", model: native, errorCode: "previous_response_not_found", - terminalSource: "synthetic", spend: { sends: 1 }, + terminalSource: "synthetic", spend: { sends: retry ? 2 : 1 }, }); - expect(row?.attempts).toMatchObject([{ + const measured = { provider: "openai", model: recoveryModel, status: 200, sendCount: 1, usage: { inputTokens: 30, outputTokens: 5, totalTokens: 35 }, - }]); - expect(row?.failureCause).not.toBe("local-refusal"); + }; + expect(row.attempts).toMatchObject(retry ? [{ + provider: "openai", model: recoveryModel, status: 502, sendCount: 1, + failureStage: "pre-header", failureCause: "transport-ambiguous", usageStatus: "unreported", + }, measured] : [measured]); + expect(row.failureCause).not.toBe("local-refusal"); + + const { summary, models } = summarizeUsage([row], "30d", Date.now()); + const { costTotal } = computeEntryCost(row); + expect(costTotal).toBeGreaterThan(0); + const telemetry = await aggregateTelemetryForDay(new Date(row.timestamp).toISOString().slice(0, 10)); + expect({ summary, models, telemetry }).toMatchObject({ + summary: { + requests: 1, inputTokens: 30, outputTokens: 5, totalTokens: 35, + pricedRequests: retry ? 0 : 1, unpricedRequests: retry ? 1 : 0, + estimatedCostUsd: retry ? 0 : costTotal, + }, + models: [{ provider: "openai", model: recoveryModel, totalTokens: 35, + pricedRequests: retry ? 0 : 1, unpricedRequests: retry ? 1 : 0 }], + telemetry: { + requests: { completed: 0, failed: 1, incomplete: 0, aborted: 0 }, + models: [{ providerKind: "openai", modelFamily: "gpt-5", requests: 1, inputTokens: 30, outputTokens: 5 }], + }, + }); + expect(row).toMatchObject({ usageStatus: retry ? "unreported" : "reported", totalTokens: 35 }); } finally { socket?.close(); await server.stop(true); diff --git a/tests/usage/usage-telemetry-client.test.ts b/tests/usage/usage-telemetry-client.test.ts index 85fc988d47c..25ad4a2e56f 100644 --- a/tests/usage/usage-telemetry-client.test.ts +++ b/tests/usage/usage-telemetry-client.test.ts @@ -361,6 +361,13 @@ describe("install identity, aggregation, disjoint tokens, and scheduler", () => }, ]; + const ordinary = fixtureEntries[0]!; + ordinary.attempts = [{ + ordinal: 1, provider: ordinary.provider, model: ordinary.model, adapter: "anthropic", + status: 200, durationMs: ordinary.durationMs, sendCount: 1, recoveryKinds: [], + usageStatus: "reported", usage: ordinary.usage, + }]; + writeFileSync( join(home, "usage.jsonl"), fixtureEntries.map(row => JSON.stringify(row)).join("\n") + "\n",