Repository navigation
feat(proxy): add /backend-api/files upload protocol - #515
Conversation
Implements the upstream Codex CLI three-step file upload protocol so clients can attach large files (e.g. images, PDFs) without hitting the 16 MiB websocket message ceiling on /responses (issue #510). Files are registered against an Azure Blob SAS URL and referenced from /responses prompts as { type: input_file, file_id: ... } content items. - POST /backend-api/files registers a file ({file_name, file_size, use_case}) and returns the upstream {file_id, upload_url}. The 512 MiB upstream cap is enforced at the edge by FileCreateRequest. - POST /backend-api/files/{file_id}/uploaded finalizes; the client module mirrors the upstream Codex CLI 30 s / 250 ms retry-poll loop while status == retry. - ProxyService.create_file / finalize_file reuse the existing account-selection / freshness / 401-retry / request-log plumbing. Logs use synthetic models 'files-create' / 'files-finalize' for dashboard request-log filtering. - Stop rejecting input_file content items with file_id in ResponsesRequest / ResponsesCompactRequest. Helpers _has_input_file_id / _is_input_file_with_id stay for diagnostics.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bcf5b62047
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| while True: | ||
| try: | ||
| async with client_session.post( | ||
| url, | ||
| data=b"{}", |
There was a problem hiding this comment.
Stop finalize polling once deadline is reached
The finalize loop always issues a new POST /files/{id}/uploaded before checking whether the 30s deadline has already passed, so if the previous sleep crosses the deadline it still performs one extra poll. In slow-network cases that extra call can block for the per-request timeout and violate the documented 30s finalize budget. Check the deadline at the top of each loop iteration (before client_session.post) to avoid overshooting the budget.
Useful? React with 👍 / 👎.
| try: | ||
| return await invoke(access_token, account_id, filtered) | ||
| except FileProxyError as files_exc: |
There was a problem hiding this comment.
Bound file upstream calls by remaining request budget
This path computes remaining_budget but then invokes the file client without propagating that limit, unlike the transcribe flow that pushes per-call timeout overrides. Because create_file/finalize_file use a fixed 60s request timeout, a request with little budget left can still block well past transcription_request_budget_seconds, causing inconsistent budget enforcement for /backend-api/files routes.
Useful? React with 👍 / 👎.
P1: stop finalize polling once the deadline is reached.
`finalize_file` previously only checked the deadline before sleeping,
so if the inter-poll sleep crossed the budget boundary the loop still
issued one more `POST /files/{id}/uploaded` whose own request timeout
could block well past the documented 30 s budget. Re-check the
deadline immediately after the sleep so we never overshoot.
P2: bound file upstream calls by the remaining request budget.
`ProxyService._proxy_files_call` now pushes per-call timeout overrides
(mirroring `push_transcribe_timeout_overrides`) so `create_file` and
`finalize_file` inherit the per-request budget rather than the fixed
60 s default. The finalize budget is also clamped to the effective
per-poll total so a smaller request budget cannot let the poll loop
outlive the parent request.
Test update: `test_finalize_file_returns_last_retry_after_budget_exhaustion`
now asserts a single upstream call (the post-sleep deadline check
stops the loop before issuing another `POST`).
|
Pushed P1 — finalize polling overshoot
Re-check the deadline immediately after the sleep so we never overshoot: await asyncio.sleep(_FILE_FINALIZE_POLL_DELAY_SECONDS)
if time.monotonic() >= deadline:
return parsedUpdated regression: P2 — file upstream calls now respect remaining request budget Added timeout_tokens = push_files_timeout_overrides(
connect_timeout_seconds=remaining_budget,
total_timeout_seconds=remaining_budget,
)
Verification
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5f0be47480
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| timeout = aiohttp.ClientTimeout( | ||
| total=effective_per_poll_total, | ||
| sock_connect=effective_connect, |
There was a problem hiding this comment.
Derive finalize poll timeout from remaining deadline
In finalize_file, the aiohttp.ClientTimeout is computed once from the initial budget and reused for every retry poll. When upstream keeps returning {"status":"retry"}, a later iteration can start with only a small amount of time left before deadline but still issue another POST with the full original timeout, which can block well past both the 30s finalize budget and the parent request budget. This regresses the stated goal of bounding finalize calls by remaining request time; each poll timeout should be clamped to deadline - now before sending the request.
Useful? React with 👍 / 👎.
Codex review (5f0be47) flagged that the per-poll ClientTimeout was computed once before the loop and reused for every retry. A late retry could therefore begin with the full original timeout while only a few hundred ms remain until the 30 s finalize deadline, blowing past both budgets on slow networks. Recompute the per-poll timeout from `deadline - time.monotonic()` at the top of each iteration. When the remaining budget hits zero we surface the most recent payload (or a seeded status: retry placeholder if no poll has run yet) without issuing another POST. Tests still pass: 20 (9 unit + 11 integration).
|
Pushed The previous fix bounded the budget but the per-poll Now the per-poll timeout is recomputed from remaining = deadline - time.monotonic()
if remaining <= 0:
return parsed
per_poll_total = min(effective_per_poll_total, remaining)
timeout = aiohttp.ClientTimeout(
total=per_poll_total,
sock_connect=min(effective_connect, per_poll_total),
)
The other two line comments on @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 49c0b62032
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| result = await context.service.create_file( | ||
| payload.model_dump(mode="json", exclude_none=True), | ||
| request.headers, | ||
| api_key=api_key, | ||
| ) |
There was a problem hiding this comment.
Enforce API-key limits before forwarding file endpoints
/backend-api/files and /backend-api/files/{file_id}/uploaded forward directly to context.service without calling _enforce_request_limits, unlike other billable/abusable proxy routes such as _transcribe_request in the same file. In deployments that rely on API-key quotas/self-limits, this creates a bypass where a key can register/finalize unlimited upstream files without local limit reservation/accounting, which can exhaust shared upstream resources despite configured limits.
Useful? React with 👍 / 👎.
Codex review (49c0b62) flagged that the new `/backend-api/files` and `/backend-api/files/{file_id}/uploaded` endpoints forwarded directly to `context.service` without calling `_enforce_request_limits`, unlike other billable proxy routes (transcribe, responses, compact). For deployments that lean on API-key quotas / self-limits this was a clean bypass: a key could register and finalize unlimited upstream files without local accounting, exhausting shared upstream resources and skipping rate-limit reservations. Reserve a request limit slot before forwarding (using synthetic models `files-create` / `files-finalize` to match the request-log entries written from `ProxyService._proxy_files_call`) and release it in a `finally` once the upstream call settles, mirroring the `_compact_responses` pattern. Tests: `pytest tests/integration/test_proxy_files.py` -- 11 passed.
|
Pushed Real bypass: Now both file endpoints reserve before forwarding, using synthetic models reservation = await _enforce_request_limits(
api_key,
request_model=_FILES_CREATE_LIMIT_MODEL, # "files-create"
request_service_tier=None,
)
try:
...
finally:
await _release_reservation(reservation)The other two line comments on @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5f609a6145
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| selection = await self._select_account_with_budget_compatible( | ||
| deadline, | ||
| request_id=request_id, | ||
| kind=kind, | ||
| api_key=api_key, |
There was a problem hiding this comment.
Preserve account affinity across file protocol calls
_proxy_files_call does a new load-balancer selection for every /backend-api/files* request without any sticky key or file_id→account pinning, so create/finalize (and later /responses that references that file_id) are free to run on different upstream accounts. In multi-account deployments this is a real reliability break: default capacity-weighted routing is random, so a file created under one account token can be finalized/read under another and fail with upstream not-found/auth errors.
Useful? React with 👍 / 👎.
Codex review (5f609a6) flagged that `/backend-api/files` endpoints ran a fresh load-balancer selection per request without any `file_id` -> account binding, so create_file could go through one upstream account while the matching finalize_file ran on another. The upstream contract is account-scoped (chatgpt-account-id), so a finalize on a different account would fail with not-found / 401, and a follow-up `/responses` referencing that file_id would behave the same. Add an in-memory pin table on ProxyService: - `create_file`: on success, pin `file_id -> account_id` (5 min TTL). - `finalize_file`: look up the pin, pass it as `preferred_account_id` into the existing `_select_account_with_budget` plumbing (already supported by the load balancer for sticky-style preferences). - Pin TTL eviction runs opportunistically on each pin so the table stays bounded. `_proxy_files_call` now returns `(result, account_id)` instead of just `result` so create_file can record the pin without smuggling through the JSON body. Cross-instance handoff is best-effort: if finalize lands on a different replica with no pin, we fall back to a fresh load-balancer selection (this can fail upstream and the client will surface that, same as before). Tests: - New `test_backend_files_finalize_pins_to_create_account` (integration) imports two accounts, drives create_file -> finalize_file, and asserts the same upstream account_id was used for both calls. - 139 passed across the proxy / files / responses / transcriptions test families.
|
Pushed The upstream file protocol is account-scoped ( Fix shape (in-memory pin):
Regression test: Verification:
The other line comments on @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4527d66fce
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # ``input_file`` content items with a ``file_id`` are now allowed | ||
| # and forwarded verbatim. They reference uploads registered via | ||
| # ``POST /backend-api/files`` (see the file upload protocol), | ||
| # which lets large attachments bypass the 16 MiB websocket | ||
| # ceiling on `/responses`. | ||
| if isinstance(value, str): | ||
| normalized = _normalize_input_text(value) | ||
| if _has_input_file_id(normalized): | ||
| raise ValueError("input_file.file_id is not supported") | ||
| return _sanitize_input_items(normalized) | ||
| if is_json_list(value): | ||
| input_items = value | ||
| if _has_input_file_id(input_items): | ||
| raise ValueError("input_file.file_id is not supported") | ||
| return _sanitize_input_items(input_items) |
There was a problem hiding this comment.
Route file_id responses to the creating account
Allowing input_file.file_id in ResponsesRequest._validate_input_type makes /responses accept references to uploaded files, but the new account pinning is only consumed by ProxyService.finalize_file (via _resolve_file_account) and is not applied when selecting an account for /responses. In multi-account capacity-weighted deployments, a first /responses call that references a file_id can be routed to a different upstream account than the one that created/finalized the file, which produces the same not-found/401 failure mode the pinning logic was added to prevent.
Useful? React with 👍 / 👎.
Codex review (4527d66) flagged that the file_id pin from create_file was only consulted by finalize_file, while /v1/responses, /backend-api/codex/responses, and /responses/compact still ran a fresh load-balancer selection per request. Because the upstream file API is account-scoped (chatgpt-account-id), a /responses request referencing an input_file.file_id from one account routed through a different upstream account would fail with not-found / 401, even though the file itself exists. Fix shape: - Add extract_input_file_ids helper in app/core/openai/requests.py walking both top-level items and nested role-message content parts. - Add ProxyService._resolve_file_account_for_responses that consults _file_account_pins and returns None when stronger affinity signals are present (prompt_cache_key, session header, turn_state header, previous_response_id). Multi-file_id ties pick the most-recently-pinned with lexicographic tie-break for determinism. - Wire the resolver into the three /responses entry points: - _stream_with_retry (HTTP /v1/responses + /backend-api/codex/responses) - _stream_via_http_bridge (HTTP bridge variant) - compact_responses (/responses/compact) - The websocket path is intentionally not wired here. Codex CLI's websocket flow already uses codex_session_affinity (turn_state header) which is a stronger signal, so file_id-only affinity has no observable benefit there and would require parsing the request payload that is currently consumed as raw text. Tests: - Unit: extract_input_file_ids covers string input, top-level + nested file_ids, dedup, blank/missing ids, unrelated content types. - Integration: imports two accounts, verifies that POST /v1/responses with input_file.file_id is routed to the same account as the preceding POST /backend-api/files. A second test verifies that an explicit prompt_cache_key overrides the file_id pin. OpenSpec: appends a new MODIFIED Requirement (`Responses requests with input_file.file_id route to the upload's account`) plus two scenarios under add-backend-api-files-protocol/specs/responses-api-compat. Verification: - uv run ruff check app tests -- clean - uv run ruff format --check -- clean - uv run ty check (touched modules) -- clean - uv run pytest tests/integration/test_proxy_files.py tests/integration/test_proxy_responses.py tests/integration/test_openai_compat_features.py tests/integration/test_proxy_compact.py tests/unit/test_files_client.py tests/unit/test_openai_requests.py -- 182 passed
|
Pushed The previous round wired the file_id pin into create/finalize, but What changed:
Tests:
OpenSpec: new Verification:
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ce76d87169
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if _prompt_cache_key_from_request_model(payload) is not None: | ||
| return None |
There was a problem hiding this comment.
Distinguish explicit and derived prompt cache keys
_resolve_file_account_for_responses treats any prompt_cache_key as a stronger affinity signal, but _sticky_key_for_responses_request/_sticky_key_for_compact_request can auto-derive and write payload.prompt_cache_key for normal requests. In the default config (openai_cache_affinity enabled with derivation on), this condition is true even when the client did not set a cache key, so file-pin routing is skipped and /responses can still land on a different account than the upload (the same not-found/401 failure this change intends to prevent). The override should apply only to client-supplied/explicit cache keys, not derived ones.
Useful? React with 👍 / 👎.
Soju pointed out that Codex CLI/Desktop's typical flow is upload-an-image- then-converse, which is exactly the scenario where the file_id pin matters most for the websocket transport (the first turn after a `POST /backend-api/files` references the new file_id and has no other affinity signal yet -- no turn_state, no session, no prompt_cache_key). The previous round skipped the websocket path because the request payload there is consumed as raw text and re-parsing felt heavy, but `_prepare_websocket_response_create_request` already validates the inbound `response.create` into a ResponsesRequest model (`responses_payload`). Adding the pin lookup right after the affinity policy is computed is just three lines on the existing parse. Concretely: after the codex_session / prompt_cache affinity is wired into request_state.affinity_policy, look up the file_id pin and seed request_state.preferred_account_id when the helper resolves to an account. The helper itself enforces precedence: stronger affinity signals (prompt_cache_key, session header, turn_state header, previous_response_id) make it return `None`, so this never overrides existing routing. Test update: rewrote the `/v1/responses` integration regression to target the resolver helper directly (deterministic) and assert that the websocket prep path threads the same pin into `request_state.preferred_account_id`. Pin-via-route was previously flaky because the load balancer is capacity-weighted and pin state leaks across tests in the same pytest process; the helper-level test isolates the contract being verified. Tests: 218 passed across files/websocket/responses/compact/compat/units.
|
Pushed What changed:
if request_state.preferred_account_id is None:
request_state.preferred_account_id = await self._resolve_file_account_for_responses(\n responses_payload, headers,\n )Same precedence rule as the HTTP / compact paths -- the helper short-circuits to Test rewrite: the previous
That isolates the contract under verification and is deterministic. Verification:
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 30ab726967
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if _sticky_key_from_turn_state_header(headers) is not None: | ||
| return None |
There was a problem hiding this comment.
Allow file-id affinity despite synthetic turn-state headers
_resolve_file_account_for_responses currently bails out whenever x-codex-turn-state is present, but both websocket entrypoints always inject that header before calling proxy_responses_websocket (see app/modules/proxy/api.py websocket handlers). That means the new file-id pin is never applied on websocket response.create, so upload-then-converse requests that only carry input_file.file_id can still be routed to a different account and fail upstream with not-found/401 due to account scoping. This is most visible in the Codex CLI/Desktop websocket flow where the turn-state header is always present.
Useful? React with 👍 / 👎.
…ffinity
Codex review (round 7) flagged a real precedence bug in
_resolve_file_account_for_responses: it short-circuited to None
whenever payload.prompt_cache_key was non-empty, but
_sticky_key_for_responses_request can *derive* and assign a cache
key onto the payload when openai cache affinity is enabled. With
the default config (cache affinity on with derivation), the
condition was effectively always true even when the client did
*not* send a cache key, so file-pin routing was silently skipped
and /responses could land on a different account from the one that
registered the file -- exactly the symptom we set out to fix.
Use Pydantic's model_fields_set tracker to distinguish:
explicit_fields = getattr(payload, "model_fields_set", set())
if (
"prompt_cache_key" in explicit_fields
and _prompt_cache_key_from_request_model(payload) is not None
):
return None # client-supplied cache key wins
A derived prompt_cache_key (assigned by the affinity helper without
recording it in model_fields_set) no longer blocks file-pin
routing. The two existing precedence tests (explicit cache key
overrides pin) continue to pass; a new regression
(test_derived_prompt_cache_key_does_not_block_file_id_pin) pins the
contract.
Drive-by: replace payload.to_payload() | {"type": ...} with
explicit dict construction in the websocket prep test so ty
(currently blocking on dict union) stays green.
Tests: 219 passed across files / websocket / responses / compact /
compat / units.
|
Pushed Real bug -- not just stale review noise:
Fix: use Pydantic's explicit_fields = getattr(payload, "model_fields_set", set())
if (
"prompt_cache_key" in explicit_fields
and _prompt_cache_key_from_request_model(payload) is not None
):
return None # client-supplied wins
# A derived cache key falls through to the file-pin lookup.Tests:
Drive-by: replaced Verification:
The other line comments on @codex review |
|
Codex Review: Didn't find any major issues. Breezy! ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Codex review (round 8) flagged that the websocket entry points
always inject an x-codex-turn-state header before calling
proxy_responses_websocket (via ensure_downstream_turn_state
when the client did not supply one), and the HTTP path does the
same with ensure_http_downstream_turn_state. The file-pin
resolver was treating that synthesizer-generated placeholder as a
client-supplied continuation marker, so the new file_id pin was
silently never applied to first-turn upload-then-converse
requests -- the very scenario the resolver was wired in for.
Add _is_synthesized_turn_state(value) matching the
(?:http_)?turn_<32 hex> shape of the synthesizer's output, and
short-circuit the resolver only when the inbound turn-state value
does NOT match that pattern (i.e. is genuinely client-supplied).
Tests:
- Existing websocket-prep regression keeps passing -- the synthesizer
path now hits the pin instead of being shadowed by the empty
headers={} argument the test happened to use.
- New test_synthesized_turn_state_does_not_block_file_id_pin
verifies both branches: synthesized turn_state (does not block)
vs. client-supplied turn_state (still blocks).
220 tests passed across files / websocket / responses / compact /
compat / unit suites.
|
Pushed Real follow-up to my own incomplete first attempt at this. The websocket entry points (and the HTTP path) always inject an Fix: synthesizer outputs match turn_state_value = _sticky_key_from_turn_state_header(headers)
if turn_state_value is not None and not _is_synthesized_turn_state(turn_state_value):
return None # client-supplied continuation marker wins
# synthesizer placeholder falls through to file-pin lookupTests (
Verification:
The @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4cdcdf0cfc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # (large file PUT + finalize-poll, default 30 s + retries) and any | ||
| # follow-up ``/responses`` that references the file_id, but short | ||
| # enough that pins do not accumulate forever in long-lived workers. | ||
| _FILE_ACCOUNT_PIN_TTL_SECONDS: float = 5 * 60.0 |
There was a problem hiding this comment.
Extend file-account pin TTL for 512 MiB upload flows
The pin lifetime is fixed to 5 minutes, but this feature allows files up to 512 MiB, which often take longer than 5 minutes to upload on typical client uplinks. Once the pin expires, finalize_file and subsequent /responses file routing fall back to fresh account selection, and because upstream file access is account-scoped (chatgpt-account-id) and _proxy_files_call does not retry finalize across multiple accounts, valid upload-then-finalize flows can fail with 401/404 in multi-account setups. This should use a substantially longer lifetime (or a shared/persistent mapping) to cover realistic upload durations.
Useful? React with 👍 / 👎.
Codex review (round 9) flagged that the 5-minute pin TTL is too short for the 512 MiB upload ceiling we expose: a slow client uplink can keep PUTting blob bytes to the SAS URL for longer than 5 minutes, and the matching finalize / follow-up /responses then land on the wrong account because the pin has already expired. Bump to 30 minutes. That covers a 512 MiB upload at ~280 KiB/s, well below typical broadband uplink, and keeps the table size negligible (each pin is a short string tuple, opportunistic eviction runs on every write). No code-path change beyond the constant; all existing tests still pass.
|
Pushed Real point. The pin TTL was 5 minutes but the upload limit is 512 MiB. A slow client uplink can keep PUTting blob bytes to the SAS URL for longer than that, and the finalize / follow-up Bumped to 30 minutes. That covers a 512 MiB upload at ~280 KiB/s, well below typical broadband uplink, and keeps the table footprint negligible (each pin is a short string tuple; opportunistic eviction runs on every write). The other line comments on @codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b715170700
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # added by the affinity helper itself must not block file-pin | ||
| # routing for first-turn upload-then-converse flows. | ||
| explicit_fields = getattr(payload, "model_fields_set", set()) | ||
| if "prompt_cache_key" in explicit_fields and _prompt_cache_key_from_request_model(payload) is not None: |
There was a problem hiding this comment.
Treat promptCacheKey alias as explicit affinity signal
_resolve_file_account_for_responses only suppresses file-pin routing when "prompt_cache_key" is in model_fields_set, so a client-supplied camelCase promptCacheKey (which is accepted via model_extra and read by _prompt_cache_key_from_request_model) is not treated as a stronger signal. In that case the resolver can still return a pinned file account, and _select_account_with_budget_compatible will try that preferred account first, overriding the intended prompt-cache continuation routing for requests that include input_file.file_id.
Useful? React with 👍 / 👎.
Codex review (round 10) flagged that the resolver only checked the canonical `prompt_cache_key` field name in `model_fields_set`, so a client that posts directly to `/backend-api/codex/responses` with the camelCase `promptCacheKey` alias would be ignored as a continuation marker. The V1 normalization path (`/v1/responses`) does rewrite the alias before model_validate so the canonical key lands in `model_fields_set` correctly there, but the raw codex backend route bypasses that normalization and still receives the alias verbatim. Check both names. `_prompt_cache_key_from_request_model` already returns the populated value regardless of which name the client used, so when the alias *is* in `model_fields_set` we still need the value check to match. No test churn -- the existing precedence regression continues to cover canonical `prompt_cache_key` and the new branch is just a spelling tolerance for the alias.
|
Pushed Borderline-gap: the V1 normalization path ( explicit_cache_key = (
"prompt_cache_key" in explicit_fields
or "promptCacheKey" in explicit_fields
)
if explicit_cache_key and _prompt_cache_key_from_request_model(payload) is not None:
return None
No test churn -- the existing precedence regression covers the canonical key and the new branch is a spelling tolerance for the alias. @codex review |
|
Codex Review: Didn't find any major issues. Breezy! ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
) This reverts merge commit e42af5e. The slimming approach rewrites conversation history on the codex-lb side (a stateless forwarding proxy) and conflicts with several stateful surfaces that have to stay consistent with the upstream view: - Prompt-cache invalidation: every slimmed turn changes the input prefix and forces a cache miss against the upstream prompt cache, silently re-billing input tokens. This intersects with #515's pin / affinity work and is invisible to the user. - Assistant-role omission notice ('[codex-lb omitted N items]'): the model treats this as its own prior speech and starts apologising for missing context, hallucinating that earlier history is known, or contradicting the trimmed turns. - WebSocket turn_state mismatch: the Codex WS path is stateful through previous_response_id. After slimming, codex-lb's request view diverges from the upstream session view; replays of the slimmed payload can reference items the upstream copy expected but we already trimmed. These are not knobs we can tune: history compaction belongs in the Codex client (or upstream Responses API), not in a forwarding proxy. The 413 -> slim transition is strictly better for the immediate symptom, but it shifts the failure mode from a clear hard fail into silent degradation of cache cost, model trust, and WS continuity. Reverting before this lands in a release. Tracking the broader follow-up in #568. The original 413 reporter (#556) reopens for now while we route this through Codex CLI / file-upload paths instead.
… pin fields Audit follow-up to the rewrite removal. The image processor module, fetch_file_bytes helper, and the _FilePinEntry download_url/mime_type/ file_name fields were left in the previous commit on the assumption they would be useful as reusable utilities. They have zero callers in the production codebase on this branch -- the only consumers were the rewrite path itself (already deleted) and their own tests. Delete them and revert the pin entry to the original (account_id, expires_at) shape so the surface area matches the actual contract. Removed: - app/core/clients/image_processor.py and tests/unit/test_image_processor.py - app/core/clients/files.py::fetch_file_bytes (and its three tests) - _FilePinEntry.download_url / .mime_type / .file_name fields - _pin_expiry_from_download_url SAS-aware helper (no longer needed without the download_url field on the pin) - _pin_file_account's download_url= / mime_type= / file_name= keyword arguments (back to the original 2-arg signature) - finalize_file's extraction of download_url / mime_type / file_name from the upstream success payload (the file_id -> account pin was already being written without these fields before #571) - pyproject.toml direct pillow dependency (transitive coverage stays through python-multipart) Kept: - _classify_upstream_close + retry_precreated suppression - _resolve_stream_transport HTTP auto-fallback - _stream_responses bridge bypass for oversized payloads - _raise_for_unsupported_input_image_references and extract_input_image_file_references / _input_image_file_reference - create_file / finalize_file / _proxy_files_call (the actual /backend-api/files protocol implementation from #515) OpenSpec change add-backend-api-files-protocol updated to drop the 'image_processor / fetch_file_bytes remain reusable utilities' line.
…/ classifier hardening (#574) * refactor(proxy): reject input_image.file_id with 400, keep transport / classifier hardening * chore(proxy): drop dead image_processor / fetch_file_bytes / extended pin fields Audit follow-up to the rewrite removal. The image processor module, fetch_file_bytes helper, and the _FilePinEntry download_url/mime_type/ file_name fields were left in the previous commit on the assumption they would be useful as reusable utilities. They have zero callers in the production codebase on this branch -- the only consumers were the rewrite path itself (already deleted) and their own tests. Delete them and revert the pin entry to the original (account_id, expires_at) shape so the surface area matches the actual contract. Removed: - app/core/clients/image_processor.py and tests/unit/test_image_processor.py - app/core/clients/files.py::fetch_file_bytes (and its three tests) - _FilePinEntry.download_url / .mime_type / .file_name fields - _pin_expiry_from_download_url SAS-aware helper (no longer needed without the download_url field on the pin) - _pin_file_account's download_url= / mime_type= / file_name= keyword arguments (back to the original 2-arg signature) - finalize_file's extraction of download_url / mime_type / file_name from the upstream success payload (the file_id -> account pin was already being written without these fields before #571) - pyproject.toml direct pillow dependency (transitive coverage stays through python-multipart) Kept: - _classify_upstream_close + retry_precreated suppression - _resolve_stream_transport HTTP auto-fallback - _stream_responses bridge bypass for oversized payloads - _raise_for_unsupported_input_image_references and extract_input_image_file_references / _input_image_file_reference - create_file / finalize_file / _proxy_files_call (the actual /backend-api/files protocol implementation from #515) OpenSpec change add-backend-api-files-protocol updated to drop the 'image_processor / fetch_file_bytes remain reusable utilities' line.
* wip(files): scaffold core/clients/files.py with 3-step protocol stubs * wip(files): polish core/clients/files.py with retry-budget finalize loop * feat(proxy): add /backend-api/files upload protocol Implements the upstream Codex CLI three-step file upload protocol so clients can attach large files (e.g. images, PDFs) without hitting the 16 MiB websocket message ceiling on /responses (issue Soju06#510). Files are registered against an Azure Blob SAS URL and referenced from /responses prompts as { type: input_file, file_id: ... } content items. - POST /backend-api/files registers a file ({file_name, file_size, use_case}) and returns the upstream {file_id, upload_url}. The 512 MiB upstream cap is enforced at the edge by FileCreateRequest. - POST /backend-api/files/{file_id}/uploaded finalizes; the client module mirrors the upstream Codex CLI 30 s / 250 ms retry-poll loop while status == retry. - ProxyService.create_file / finalize_file reuse the existing account-selection / freshness / 401-retry / request-log plumbing. Logs use synthetic models 'files-create' / 'files-finalize' for dashboard request-log filtering. - Stop rejecting input_file content items with file_id in ResponsesRequest / ResponsesCompactRequest. Helpers _has_input_file_id / _is_input_file_with_id stay for diagnostics. * fix(files): close codex review P1 + P2 on PR Soju06#515 P1: stop finalize polling once the deadline is reached. `finalize_file` previously only checked the deadline before sleeping, so if the inter-poll sleep crossed the budget boundary the loop still issued one more `POST /files/{id}/uploaded` whose own request timeout could block well past the documented 30 s budget. Re-check the deadline immediately after the sleep so we never overshoot. P2: bound file upstream calls by the remaining request budget. `ProxyService._proxy_files_call` now pushes per-call timeout overrides (mirroring `push_transcribe_timeout_overrides`) so `create_file` and `finalize_file` inherit the per-request budget rather than the fixed 60 s default. The finalize budget is also clamped to the effective per-poll total so a smaller request budget cannot let the poll loop outlive the parent request. Test update: `test_finalize_file_returns_last_retry_after_budget_exhaustion` now asserts a single upstream call (the post-sleep deadline check stops the loop before issuing another `POST`). * fix(files): recompute finalize poll timeout from remaining deadline Codex review (933d139) flagged that the per-poll ClientTimeout was computed once before the loop and reused for every retry. A late retry could therefore begin with the full original timeout while only a few hundred ms remain until the 30 s finalize deadline, blowing past both budgets on slow networks. Recompute the per-poll timeout from `deadline - time.monotonic()` at the top of each iteration. When the remaining budget hits zero we surface the most recent payload (or a seeded status: retry placeholder if no poll has run yet) without issuing another POST. Tests still pass: 20 (9 unit + 11 integration). * fix(files): enforce API-key request limits on /backend-api/files Codex review (055d000) flagged that the new `/backend-api/files` and `/backend-api/files/{file_id}/uploaded` endpoints forwarded directly to `context.service` without calling `_enforce_request_limits`, unlike other billable proxy routes (transcribe, responses, compact). For deployments that lean on API-key quotas / self-limits this was a clean bypass: a key could register and finalize unlimited upstream files without local accounting, exhausting shared upstream resources and skipping rate-limit reservations. Reserve a request limit slot before forwarding (using synthetic models `files-create` / `files-finalize` to match the request-log entries written from `ProxyService._proxy_files_call`) and release it in a `finally` once the upstream call settles, mirroring the `_compact_responses` pattern. Tests: `pytest tests/integration/test_proxy_files.py` -- 11 passed. * fix(files): pin file_id to creating account so finalize lands on it Codex review (3ae2de6) flagged that `/backend-api/files` endpoints ran a fresh load-balancer selection per request without any `file_id` -> account binding, so create_file could go through one upstream account while the matching finalize_file ran on another. The upstream contract is account-scoped (chatgpt-account-id), so a finalize on a different account would fail with not-found / 401, and a follow-up `/responses` referencing that file_id would behave the same. Add an in-memory pin table on ProxyService: - `create_file`: on success, pin `file_id -> account_id` (5 min TTL). - `finalize_file`: look up the pin, pass it as `preferred_account_id` into the existing `_select_account_with_budget` plumbing (already supported by the load balancer for sticky-style preferences). - Pin TTL eviction runs opportunistically on each pin so the table stays bounded. `_proxy_files_call` now returns `(result, account_id)` instead of just `result` so create_file can record the pin without smuggling through the JSON body. Cross-instance handoff is best-effort: if finalize lands on a different replica with no pin, we fall back to a fresh load-balancer selection (this can fail upstream and the client will surface that, same as before). Tests: - New `test_backend_files_finalize_pins_to_create_account` (integration) imports two accounts, drives create_file -> finalize_file, and asserts the same upstream account_id was used for both calls. - 139 passed across the proxy / files / responses / transcriptions test families. * fix(files): route input_file.file_id /responses to the creating account Codex review (4715d2f) flagged that the file_id pin from create_file was only consulted by finalize_file, while /v1/responses, /backend-api/codex/responses, and /responses/compact still ran a fresh load-balancer selection per request. Because the upstream file API is account-scoped (chatgpt-account-id), a /responses request referencing an input_file.file_id from one account routed through a different upstream account would fail with not-found / 401, even though the file itself exists. Fix shape: - Add extract_input_file_ids helper in app/core/openai/requests.py walking both top-level items and nested role-message content parts. - Add ProxyService._resolve_file_account_for_responses that consults _file_account_pins and returns None when stronger affinity signals are present (prompt_cache_key, session header, turn_state header, previous_response_id). Multi-file_id ties pick the most-recently-pinned with lexicographic tie-break for determinism. - Wire the resolver into the three /responses entry points: - _stream_with_retry (HTTP /v1/responses + /backend-api/codex/responses) - _stream_via_http_bridge (HTTP bridge variant) - compact_responses (/responses/compact) - The websocket path is intentionally not wired here. Codex CLI's websocket flow already uses codex_session_affinity (turn_state header) which is a stronger signal, so file_id-only affinity has no observable benefit there and would require parsing the request payload that is currently consumed as raw text. Tests: - Unit: extract_input_file_ids covers string input, top-level + nested file_ids, dedup, blank/missing ids, unrelated content types. - Integration: imports two accounts, verifies that POST /v1/responses with input_file.file_id is routed to the same account as the preceding POST /backend-api/files. A second test verifies that an explicit prompt_cache_key overrides the file_id pin. OpenSpec: appends a new MODIFIED Requirement (`Responses requests with input_file.file_id route to the upload's account`) plus two scenarios under add-backend-api-files-protocol/specs/responses-api-compat. Verification: - uv run ruff check app tests -- clean - uv run ruff format --check -- clean - uv run ty check (touched modules) -- clean - uv run pytest tests/integration/test_proxy_files.py tests/integration/test_proxy_responses.py tests/integration/test_openai_compat_features.py tests/integration/test_proxy_compact.py tests/unit/test_files_client.py tests/unit/test_openai_requests.py -- 182 passed * fix(files): wire file_id pin into the websocket /responses path too Soju pointed out that Codex CLI/Desktop's typical flow is upload-an-image- then-converse, which is exactly the scenario where the file_id pin matters most for the websocket transport (the first turn after a `POST /backend-api/files` references the new file_id and has no other affinity signal yet -- no turn_state, no session, no prompt_cache_key). The previous round skipped the websocket path because the request payload there is consumed as raw text and re-parsing felt heavy, but `_prepare_websocket_response_create_request` already validates the inbound `response.create` into a ResponsesRequest model (`responses_payload`). Adding the pin lookup right after the affinity policy is computed is just three lines on the existing parse. Concretely: after the codex_session / prompt_cache affinity is wired into request_state.affinity_policy, look up the file_id pin and seed request_state.preferred_account_id when the helper resolves to an account. The helper itself enforces precedence: stronger affinity signals (prompt_cache_key, session header, turn_state header, previous_response_id) make it return `None`, so this never overrides existing routing. Test update: rewrote the `/v1/responses` integration regression to target the resolver helper directly (deterministic) and assert that the websocket prep path threads the same pin into `request_state.preferred_account_id`. Pin-via-route was previously flaky because the load balancer is capacity-weighted and pin state leaks across tests in the same pytest process; the helper-level test isolates the contract being verified. Tests: 218 passed across files/websocket/responses/compact/compat/units. * fix(files): only treat client-supplied prompt_cache_key as stronger affinity Codex review (round 7) flagged a real precedence bug in _resolve_file_account_for_responses: it short-circuited to None whenever payload.prompt_cache_key was non-empty, but _sticky_key_for_responses_request can *derive* and assign a cache key onto the payload when openai cache affinity is enabled. With the default config (cache affinity on with derivation), the condition was effectively always true even when the client did *not* send a cache key, so file-pin routing was silently skipped and /responses could land on a different account from the one that registered the file -- exactly the symptom we set out to fix. Use Pydantic's model_fields_set tracker to distinguish: explicit_fields = getattr(payload, "model_fields_set", set()) if ( "prompt_cache_key" in explicit_fields and _prompt_cache_key_from_request_model(payload) is not None ): return None # client-supplied cache key wins A derived prompt_cache_key (assigned by the affinity helper without recording it in model_fields_set) no longer blocks file-pin routing. The two existing precedence tests (explicit cache key overrides pin) continue to pass; a new regression (test_derived_prompt_cache_key_does_not_block_file_id_pin) pins the contract. Drive-by: replace payload.to_payload() | {"type": ...} with explicit dict construction in the websocket prep test so ty (currently blocking on dict union) stays green. Tests: 219 passed across files / websocket / responses / compact / compat / units. * fix(files): ignore synthesized turn-state when resolving file-pin Codex review (round 8) flagged that the websocket entry points always inject an x-codex-turn-state header before calling proxy_responses_websocket (via ensure_downstream_turn_state when the client did not supply one), and the HTTP path does the same with ensure_http_downstream_turn_state. The file-pin resolver was treating that synthesizer-generated placeholder as a client-supplied continuation marker, so the new file_id pin was silently never applied to first-turn upload-then-converse requests -- the very scenario the resolver was wired in for. Add _is_synthesized_turn_state(value) matching the (?:http_)?turn_<32 hex> shape of the synthesizer's output, and short-circuit the resolver only when the inbound turn-state value does NOT match that pattern (i.e. is genuinely client-supplied). Tests: - Existing websocket-prep regression keeps passing -- the synthesizer path now hits the pin instead of being shadowed by the empty headers={} argument the test happened to use. - New test_synthesized_turn_state_does_not_block_file_id_pin verifies both branches: synthesized turn_state (does not block) vs. client-supplied turn_state (still blocks). 220 tests passed across files / websocket / responses / compact / compat / unit suites. * fix(files): extend file-account pin TTL for 512 MiB uploads Codex review (round 9) flagged that the 5-minute pin TTL is too short for the 512 MiB upload ceiling we expose: a slow client uplink can keep PUTting blob bytes to the SAS URL for longer than 5 minutes, and the matching finalize / follow-up /responses then land on the wrong account because the pin has already expired. Bump to 30 minutes. That covers a 512 MiB upload at ~280 KiB/s, well below typical broadband uplink, and keeps the table size negligible (each pin is a short string tuple, opportunistic eviction runs on every write). No code-path change beyond the constant; all existing tests still pass. * fix(files): honor promptCacheKey alias as explicit affinity signal Codex review (round 10) flagged that the resolver only checked the canonical `prompt_cache_key` field name in `model_fields_set`, so a client that posts directly to `/backend-api/codex/responses` with the camelCase `promptCacheKey` alias would be ignored as a continuation marker. The V1 normalization path (`/v1/responses`) does rewrite the alias before model_validate so the canonical key lands in `model_fields_set` correctly there, but the raw codex backend route bypasses that normalization and still receives the alias verbatim. Check both names. `_prompt_cache_key_from_request_model` already returns the populated value regardless of which name the client used, so when the alias *is* in `model_fields_set` we still need the value check to match. No test churn -- the existing precedence regression continues to cover canonical `prompt_cache_key` and the new branch is just a spelling tolerance for the alias.
…" (Soju06#569) This reverts merge commit 28f4659. The slimming approach rewrites conversation history on the codex-lb side (a stateless forwarding proxy) and conflicts with several stateful surfaces that have to stay consistent with the upstream view: - Prompt-cache invalidation: every slimmed turn changes the input prefix and forces a cache miss against the upstream prompt cache, silently re-billing input tokens. This intersects with Soju06#515's pin / affinity work and is invisible to the user. - Assistant-role omission notice ('[codex-lb omitted N items]'): the model treats this as its own prior speech and starts apologising for missing context, hallucinating that earlier history is known, or contradicting the trimmed turns. - WebSocket turn_state mismatch: the Codex WS path is stateful through previous_response_id. After slimming, codex-lb's request view diverges from the upstream session view; replays of the slimmed payload can reference items the upstream copy expected but we already trimmed. These are not knobs we can tune: history compaction belongs in the Codex client (or upstream Responses API), not in a forwarding proxy. The 413 -> slim transition is strictly better for the immediate symptom, but it shifts the failure mode from a clear hard fail into silent degradation of cache cost, model trust, and WS continuity. Reverting before this lands in a release. Tracking the broader follow-up in Soju06#568. The original 413 reporter (Soju06#556) reopens for now while we route this through Codex CLI / file-upload paths instead.
…/ classifier hardening (Soju06#574) * refactor(proxy): reject input_image.file_id with 400, keep transport / classifier hardening * chore(proxy): drop dead image_processor / fetch_file_bytes / extended pin fields Audit follow-up to the rewrite removal. The image processor module, fetch_file_bytes helper, and the _FilePinEntry download_url/mime_type/ file_name fields were left in the previous commit on the assumption they would be useful as reusable utilities. They have zero callers in the production codebase on this branch -- the only consumers were the rewrite path itself (already deleted) and their own tests. Delete them and revert the pin entry to the original (account_id, expires_at) shape so the surface area matches the actual contract. Removed: - app/core/clients/image_processor.py and tests/unit/test_image_processor.py - app/core/clients/files.py::fetch_file_bytes (and its three tests) - _FilePinEntry.download_url / .mime_type / .file_name fields - _pin_expiry_from_download_url SAS-aware helper (no longer needed without the download_url field on the pin) - _pin_file_account's download_url= / mime_type= / file_name= keyword arguments (back to the original 2-arg signature) - finalize_file's extraction of download_url / mime_type / file_name from the upstream success payload (the file_id -> account pin was already being written without these fields before Soju06#571) - pyproject.toml direct pillow dependency (transitive coverage stays through python-multipart) Kept: - _classify_upstream_close + retry_precreated suppression - _resolve_stream_transport HTTP auto-fallback - _stream_responses bridge bypass for oversized payloads - _raise_for_unsupported_input_image_references and extract_input_image_file_references / _input_image_file_reference - create_file / finalize_file / _proxy_files_call (the actual /backend-api/files protocol implementation from Soju06#515) OpenSpec change add-backend-api-files-protocol updated to drop the 'image_processor / fetch_file_bytes remain reusable utilities' line.
P1: stop finalize polling once the deadline is reached.
`finalize_file` previously only checked the deadline before sleeping,
so if the inter-poll sleep crossed the budget boundary the loop still
issued one more `POST /files/{id}/uploaded` whose own request timeout
could block well past the documented 30 s budget. Re-check the
deadline immediately after the sleep so we never overshoot.
P2: bound file upstream calls by the remaining request budget.
`ProxyService._proxy_files_call` now pushes per-call timeout overrides
(mirroring `push_transcribe_timeout_overrides`) so `create_file` and
`finalize_file` inherit the per-request budget rather than the fixed
60 s default. The finalize budget is also clamped to the effective
per-poll total so a smaller request budget cannot let the poll loop
outlive the parent request.
Test update: `test_finalize_file_returns_last_retry_after_budget_exhaustion`
now asserts a single upstream call (the post-sleep deadline check
stops the loop before issuing another `POST`).
This reverts merge commit 22b84f7. The slimming approach rewrites conversation history on the codex-lb side (a stateless forwarding proxy) and conflicts with several stateful surfaces that have to stay consistent with the upstream view: - Prompt-cache invalidation: every slimmed turn changes the input prefix and forces a cache miss against the upstream prompt cache, silently re-billing input tokens. This intersects with Soju06#515's pin / affinity work and is invisible to the user. - Assistant-role omission notice ('[codex-lb omitted N items]'): the model treats this as its own prior speech and starts apologising for missing context, hallucinating that earlier history is known, or contradicting the trimmed turns. - WebSocket turn_state mismatch: the Codex WS path is stateful through previous_response_id. After slimming, codex-lb's request view diverges from the upstream session view; replays of the slimmed payload can reference items the upstream copy expected but we already trimmed. These are not knobs we can tune: history compaction belongs in the Codex client (or upstream Responses API), not in a forwarding proxy. The 413 -> slim transition is strictly better for the immediate symptom, but it shifts the failure mode from a clear hard fail into silent degradation of cache cost, model trust, and WS continuity. Reverting before this lands in a release. Tracking the broader follow-up in Soju06#568. The original 413 reporter (Soju06#556) reopens for now while we route this through Codex CLI / file-upload paths instead.
… pin fields Audit follow-up to the rewrite removal. The image processor module, fetch_file_bytes helper, and the _FilePinEntry download_url/mime_type/ file_name fields were left in the previous commit on the assumption they would be useful as reusable utilities. They have zero callers in the production codebase on this branch -- the only consumers were the rewrite path itself (already deleted) and their own tests. Delete them and revert the pin entry to the original (account_id, expires_at) shape so the surface area matches the actual contract. Removed: - app/core/clients/image_processor.py and tests/unit/test_image_processor.py - app/core/clients/files.py::fetch_file_bytes (and its three tests) - _FilePinEntry.download_url / .mime_type / .file_name fields - _pin_expiry_from_download_url SAS-aware helper (no longer needed without the download_url field on the pin) - _pin_file_account's download_url= / mime_type= / file_name= keyword arguments (back to the original 2-arg signature) - finalize_file's extraction of download_url / mime_type / file_name from the upstream success payload (the file_id -> account pin was already being written without these fields before Soju06#571) - pyproject.toml direct pillow dependency (transitive coverage stays through python-multipart) Kept: - _classify_upstream_close + retry_precreated suppression - _resolve_stream_transport HTTP auto-fallback - _stream_responses bridge bypass for oversized payloads - _raise_for_unsupported_input_image_references and extract_input_image_file_references / _input_image_file_reference - create_file / finalize_file / _proxy_files_call (the actual /backend-api/files protocol implementation from Soju06#515) OpenSpec change add-backend-api-files-protocol updated to drop the 'image_processor / fetch_file_bytes remain reusable utilities' line.
Summary
Implements the upstream Codex CLI three-step file upload protocol so clients can attach large files (e.g. images, PDFs) without hitting the 16 MiB websocket message ceiling on
/responses.Fixes #510.
What
POST /backend-api/files— registers a file with{file_name, file_size, use_case}and returns the upstream{file_id, upload_url}. Theupload_urlis an Azure Blob SAS link; clients PUT the bytes directly to it (the 512 MiB upstream cap is enforced at the codex-lb edge byFileCreateRequest).POST /backend-api/files/{file_id}/uploaded— finalizes; the upstream client polls whilestatus == "retry". The codex-lb client mirrors that loop server-side with a 30 s budget / 250 ms retry delay (matchingcodex-rs/codex-api/src/files.rs::upload_local_file)./responsesprompts as{"type": "input_file", "file_id": "..."}instead of being inlined as base64. This bypasses the per-message 16 MiB ceiling.input_file.file_id is not supportedvalidation inResponsesRequest._validate_input_typeandResponsesCompactRequest._validate_input_type(4 sites)._has_input_file_id/_is_input_file_with_idhelpers are kept for diagnostics.Why
Issue #510 reports
Payload too large: 413after a long conversation accumulates several screenshots inline. I verified empirically against my dev codex-lb (withCODEX_LB_UPSTREAM_RESPONSE_CREATE_MAX_BYTES=33554432) that:So the 16 MiB ceiling is upstream-side; raising codex-lb's local cap any further is wasted. The actual fix is to give clients a separate path for large attachments, which is the protocol upstream Codex CLI already implements.
Scope
transcribe).file_size > 0and<= 512 * 1024 * 1024).files-createandfiles-finalizefor dashboard filtering.openspec/changes/add-backend-api-files-protocol/.Out of scope
load_for_prompt_bytes).Verification
uv run ruff check app tests— cleanuv run ruff format --check app tests— 426 files already formatteduv run ty check app/...(all changed modules) —All checks passed!pytest tests/unit -q— 1472 passed, 3 skippedpytest tests/integration/test_proxy_*.py tests/integration/test_openai_compat_features.py -q— 148 passedNotes
FileCreateRequestusesextra="allow"so unknown upstream-side fields (if the contract grows) are forwarded verbatim.status: "retry"to the client when our 30 s budget is exhausted. Direct Codex CLI callers will keep polling on their end (they have their own loop), so we don't synthesize a 5xx — same shape ascodex-rs/codex-api/src/files.rs.