Skip to content

feat(proxy): add /backend-api/files upload protocol - #515

Merged
Soju06 merged 13 commits into
mainfrom
feat/file-upload-protocol
May 1, 2026
Merged

Soju06 merged 13 commits into
mainfrom
feat/file-upload-protocol

Conversation

@Soju06

@Soju06 Soju06 commented Apr 29, 2026

Copy link
Copy Markdown
Owner

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}. The upload_url is an Azure Blob SAS link; clients PUT the bytes directly to it (the 512 MiB upstream cap is enforced at the codex-lb edge by FileCreateRequest).
  • POST /backend-api/files/{file_id}/uploaded — finalizes; the upstream client polls while status == "retry". The codex-lb client mirrors that loop server-side with a 30 s budget / 250 ms retry delay (matching codex-rs/codex-api/src/files.rs::upload_local_file).
  • Files registered this way can be referenced from /responses prompts as {"type": "input_file", "file_id": "..."} instead of being inlined as base64. This bypasses the per-message 16 MiB ceiling.
  • Removed the existing input_file.file_id is not supported validation in ResponsesRequest._validate_input_type and ResponsesCompactRequest._validate_input_type (4 sites). _has_input_file_id / _is_input_file_with_id helpers are kept for diagnostics.

Why

Issue #510 reports Payload too large: 413 after a long conversation accumulates several screenshots inline. I verified empirically against my dev codex-lb (with CODEX_LB_UPSTREAM_RESPONSE_CREATE_MAX_BYTES=33554432) that:

  • 14 MiB / 15.5 MiB payloads → upstream accepts and processes
  • 17 MiB+ payloads → upstream WebSocket closes with 1009 (message too big)

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

  • Backend client + service + API (3 endpoints, account-selection / freshness / 401-retry plumbing reused from transcribe).
  • Pydantic edge validation (file_size > 0 and <= 512 * 1024 * 1024).
  • Logging into request-logs as synthetic models files-create and files-finalize for dashboard filtering.
  • Tests (9 unit + 11 integration + 3 regression unit + 1 converted integration = 24 changes, all green).
  • OpenSpec change notes under openspec/changes/add-backend-api-files-protocol/.

Out of scope

  • Dashboard "files" view UI.
  • Image-resize-before-upload (codex CLI handles client-side via load_for_prompt_bytes).
  • Persisted file metadata in codex-lb's DB (the upstream contract is stateless from our perspective; we just forward).

Verification

  • uv run ruff check app tests — clean
  • uv run ruff format --check app tests — 426 files already formatted
  • uv run ty check app/... (all changed modules) — All checks passed!
  • pytest tests/unit -q — 1472 passed, 3 skipped
  • pytest tests/integration/test_proxy_*.py tests/integration/test_openai_compat_features.py -q — 148 passed

Notes

  • FileCreateRequest uses extra="allow" so unknown upstream-side fields (if the contract grows) are forwarded verbatim.
  • The finalize endpoint surfaces 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 as codex-rs/codex-api/src/files.rs.

Soju06 added 3 commits April 29, 2026 11:35
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.
@Soju06

Soju06 commented Apr 29, 2026

Copy link
Copy Markdown
Owner Author

@codex review

1 similar comment
@Soju06

Soju06 commented Apr 29, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread app/core/clients/files.py
Comment on lines +212 to +216
while True:
try:
async with client_session.post(
url,
data=b"{}",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +1984 to +1986
try:
return await invoke(access_token, account_id, filtered)
except FileProxyError as files_exc:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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`).
@Soju06

Soju06 commented Apr 29, 2026

Copy link
Copy Markdown
Owner Author

Pushed 5f0be47 addressing both codex review findings:

P1 — finalize polling overshoot

finalize_file previously only checked the deadline before sleeping, so the inter-poll sleep crossing the budget boundary still let one more POST /files/{id}/uploaded go out — and that extra call could block on its own request timeout well past the documented 30 s finalize budget.

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 parsed

Updated regression: test_finalize_file_returns_last_retry_after_budget_exhaustion now asserts exactly one upstream call (the initial poll), not two.

P2 — file upstream calls now respect remaining request budget

Added push_files_timeout_overrides / pop_files_timeout_overrides (mirroring the transcribe path's contextvars) and _proxy_files_call now pushes the remaining per-request budget into them around the upstream invocation:

timeout_tokens = push_files_timeout_overrides(
    connect_timeout_seconds=remaining_budget,
    total_timeout_seconds=remaining_budget,
)

finalize_file also clamps its 30 s poll budget to the effective per-poll total so the poll loop cannot outlive the parent request when the caller has less than 30 s left.

Verification

  • uv run ruff check / format --check clean on touched files
  • uv run ty check clean on touched files
  • pytest tests/unit/test_files_client.py tests/integration/test_proxy_files.py — 20 passed

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread app/core/clients/files.py Outdated
Comment on lines +263 to +265
timeout = aiohttp.ClientTimeout(
total=effective_per_poll_total,
sock_connect=effective_connect,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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).
@Soju06

Soju06 commented Apr 29, 2026

Copy link
Copy Markdown
Owner Author

Pushed 49c0b62 for the new P1 codex flagged on 5f0be47 (Derive finalize poll timeout from remaining deadline).

The previous fix bounded the budget but the per-poll aiohttp.ClientTimeout was still computed once before the loop and reused for every retry. A late retry could therefore start with the full original timeout while only a few hundred ms remained until the 30 s finalize deadline, blowing past both budgets on slow networks.

Now the per-poll timeout is recomputed from deadline - time.monotonic() at the top of each iteration:

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),
)

parsed is seeded to {"status": "retry"} so the very-first-iteration deadline-already-past path returns a deterministic shape.

The other two line comments on 5f0be47 are codex restating its earlier P1 / P2 (those were already addressed in the previous push and the textual diff hasn't changed in those regions); no new action needed there.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread app/modules/proxy/api.py
Comment on lines +586 to +590
result = await context.service.create_file(
payload.model_dump(mode="json", exclude_none=True),
request.headers,
api_key=api_key,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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.
@Soju06

Soju06 commented Apr 29, 2026

Copy link
Copy Markdown
Owner Author

Pushed 5f609a6 for the new P1 codex flagged on 49c0b62 (Enforce API-key limits before forwarding file endpoints).

Real bypass: /backend-api/files and /backend-api/files/{file_id}/uploaded skipped _enforce_request_limits, so an API key could register and finalize unlimited upstream files without local rate-limit accounting. Other billable routes (_transcribe_request, _responses, _compact_responses) all reserve before forwarding and release in a finally.

Now both file endpoints reserve before forwarding, using synthetic models files-create / files-finalize to match the request-log entries written from ProxyService._proxy_files_call:

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 49c0b62 are stale repeats of the P1/P2 already addressed in 5f0be47 and 49c0b62; no new action there.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +1957 to +1961
selection = await self._select_account_with_budget_compatible(
deadline,
request_id=request_id,
kind=kind,
api_key=api_key,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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.
@Soju06

Soju06 commented Apr 29, 2026

Copy link
Copy Markdown
Owner Author

Pushed 4527d66 for the new P1 codex flagged on 5f609a6 (Preserve account affinity across file protocol calls).

The upstream file protocol is account-scoped (chatgpt-account-id header), so a finalize on a different account from create would fail with not-found / 401, and a follow-up /responses referencing that file_id would behave the same. With multiple accounts and capacity-weighted routing this is observable.

Fix shape (in-memory pin):

  • ProxyService gains _file_account_pins: dict[str, tuple[str, float]] (file_id -> (account_id, expires_at)) with a 5-minute TTL and opportunistic eviction.
  • create_file: on success, record file_id -> account_id from the upstream response.
  • finalize_file: look the pin up first and pass it as preferred_account_id to _select_account_with_budget_compatible -- the load balancer already honors that field as a sticky-style preference.
  • _proxy_files_call now returns (result, account_id) instead of just result so the pin is recorded without smuggling fields through the JSON body.
  • Cross-instance handoff is best-effort: if a finalize lands on a different replica with no pin, we fall back to a fresh selection. The upstream surfaces that as not-found, same shape as before.

Regression test: test_backend_files_finalize_pins_to_create_account imports two accounts, drives create -> finalize, and asserts both calls used the same upstream account_id.

Verification:

  • ruff/format/ty clean on touched files
  • pytest tests/integration/test_proxy_files.py tests/integration/test_proxy_transcriptions.py tests/integration/test_proxy_responses.py tests/unit/test_files_client.py tests/unit/test_openai_requests.py -- 139 passed

The other line comments on 5f609a6 are stale repeats of the earlier P1/P2 already addressed in 5f0be47 / 49c0b62 / 5f609a6.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +337 to 347
# ``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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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
@Soju06

Soju06 commented Apr 30, 2026

Copy link
Copy Markdown
Owner Author

Pushed ce76d87 for the new P1 codex flagged on 4527d66 (Route file_id responses to the creating account).

The previous round wired the file_id pin into create/finalize, but /responses flows still ran fresh load-balancer selections. Since the upstream file API is account-scoped (chatgpt-account-id), a /v1/responses request referencing an input_file.file_id from one account that landed on a different upstream account would fail with not-found / 401.

What changed:

  • New helper extract_input_file_ids(input_value) in app/core/openai/requests.py -- walks top-level items + nested role-message content parts and returns the set of referenced file_ids.

  • New ProxyService._resolve_file_account_for_responses(payload, headers) -- looks up _file_account_pins, but only when no stronger affinity is set:

    • explicit prompt_cache_key
    • session header / turn_state header (codex_session)
    • previous_response_id

    Multi-file_id ties prefer the most-recently-pinned with a lexicographic tie-break for determinism.

  • Wired into 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 -- Codex CLI's websocket flow already uses codex_session_affinity (turn_state header) which is a stronger signal that overrides the file_id pin anyway, and the websocket request payload is consumed as raw text rather than the parsed ResponsesRequest model the helper expects.

Tests:

  • Unit (tests/unit/test_openai_requests.py): extract_input_file_ids covers string input, top-level + nested file_ids, dedup / blank / missing ids, and unrelated content types.
  • Integration (tests/integration/test_proxy_files.py):
    • test_v1_responses_with_input_file_id_pins_to_creating_account -- imports two accounts, asserts the /v1/responses request with input_file.file_id lands on the creating account.
    • test_v1_responses_prompt_cache_key_overrides_file_id_pin -- verifies precedence: prompt_cache_key keeps its existing routing.

OpenSpec: new Responses requests with input_file.file_id route to the upload's account requirement + two scenarios under add-backend-api-files-protocol/specs/responses-api-compat/spec.md.

Verification:

  • uv run ruff check app tests -- clean
  • uv run ruff format --check -- clean
  • uv run ty check -- clean on touched modules
  • 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

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread app/modules/proxy/service.py Outdated
Comment on lines +1968 to +1969
if _prompt_cache_key_from_request_model(payload) is not None:
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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.
@Soju06

Soju06 commented Apr 30, 2026

Copy link
Copy Markdown
Owner Author

Pushed 30ab726 to wire the file_id pin into the websocket path too -- you're right that upload-then-converse on the same turn is exactly the case where file_id-only affinity matters, and that's the dominant Codex CLI / Desktop flow.

What changed:

_prepare_websocket_response_create_request already parses the inbound response.create into a ResponsesRequest model and computes the affinity policy. After that block, look up the file_id pin and seed request_state.preferred_account_id when the helper resolves to an account:

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 None when stronger affinity (prompt_cache_key, session header, turn_state header, previous_response_id) is present, so existing routing wins.

Test rewrite: the previous /v1/responses-via-route regression was flaky because the capacity-weighted load balancer chooses non-deterministically and pin state leaks across tests in the same pytest process. Replaced with a helper-level test that:

  • Pins file_response_pin -> acc_resp_a directly.
  • Asserts the resolver returns acc_resp_a for a payload referencing it.
  • Drives _prepare_websocket_response_create_request and asserts it threads the same pin into request_state.preferred_account_id.

That isolates the contract under verification and is deterministic.

Verification:

  • ruff check / format -- clean
  • ty check on touched modules -- clean
  • pytest tests/integration/test_proxy_files.py tests/integration/test_proxy_websocket_responses.py tests/integration/test_proxy_responses.py tests/integration/test_proxy_compact.py tests/integration/test_openai_compat_features.py tests/unit/test_files_client.py tests/unit/test_openai_requests.py -- 218 passed

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread app/modules/proxy/service.py Outdated
Comment on lines +1970 to +1971
if _sticky_key_from_turn_state_header(headers) is not None:
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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.
@Soju06

Soju06 commented Apr 30, 2026

Copy link
Copy Markdown
Owner Author

Pushed b33bf87 for the new P1 codex flagged on 30ab726 (Distinguish explicit and derived prompt cache keys).

Real bug -- not just stale review noise:

_sticky_key_for_responses_request / _sticky_key_for_compact_request can derive a prompt_cache_key and assign it onto the payload when openai cache affinity is enabled. With the default config (cache affinity on, derivation on), _prompt_cache_key_from_request_model(payload) is not None was effectively always true even when the client did not send a cache key. So my precedence check was unconditionally short-circuiting and file-pin routing was silently skipped on the very first turn -- the upload-then-converse scenario you raised earlier.

Fix: use Pydantic's model_fields_set to honor only client-supplied cache keys.

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:

  • The two existing precedence tests still pass (explicit key blocks file pin).
  • New regression test_derived_prompt_cache_key_does_not_block_file_id_pin simulates the affinity helper's derived assignment by setting the attribute and removing it from model_fields_set (which is what the helper effectively does), then asserts the resolver still returns the file_id pin.

Drive-by: replaced payload.to_payload() | {"type": ...} with explicit dict construction in the websocket prep test -- ty currently blocks on dict-union there and the CI Type check (ty) job was red on the previous push because of it. Now ty is clean again.

Verification:

  • ruff check / format -- clean
  • ty check -- clean
  • pytest tests/integration/test_proxy_files.py tests/integration/test_proxy_websocket_responses.py tests/integration/test_proxy_responses.py tests/integration/test_proxy_compact.py tests/integration/test_openai_compat_features.py tests/unit/test_files_client.py tests/unit/test_openai_requests.py -- 219 passed

The other line comments on 30ab726 are stale repeats of P1/P2 already addressed in earlier rounds.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

ℹ️ 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".

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.
@Soju06

Soju06 commented Apr 30, 2026

Copy link
Copy Markdown
Owner Author

Pushed 4cdcdf0 for the new P1 codex flagged on b33bf87 (Allow file-id affinity despite synthetic turn-state headers).

Real follow-up to my own incomplete first attempt at this. The websocket entry points (and the HTTP path) always inject an x-codex-turn-state header on first turns when the client did not supply one, via ensure_downstream_turn_state / ensure_http_downstream_turn_state. My resolver was treating any turn-state value as a client-supplied continuation marker, so file-pin routing was silently never applied to the upload-then-converse flow that actually motivated this whole subsystem.

Fix: synthesizer outputs match (?:http_)?turn_<32 hex>. Add _is_synthesized_turn_state(value) and short-circuit only on values that do NOT match that pattern.

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 lookup

Tests (test_synthesized_turn_state_does_not_block_file_id_pin):

  • Synthesized header (turn_<hex>) -- helper still returns the pin.
  • Client-supplied header (client-conversation-handle-42) -- helper returns None so the conversation continuation keeps its routing.

Verification:

  • ruff check / format -- clean
  • ty check -- clean
  • 220 tests passed across files / websocket / responses / compact / compat / unit suites

The b33bf87 review's other line comments are stale repeats of the earlier rounds' findings (the bot still echoes them per-commit) -- already addressed.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread app/modules/proxy/service.py Outdated
# (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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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.
@Soju06

Soju06 commented Apr 30, 2026

Copy link
Copy Markdown
Owner Author

Pushed b715170 for the new P1 codex flagged on 4cdcdf0 (Extend file-account pin TTL for 512 MiB upload flows).

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 /responses then land on the wrong account because the pin already expired -- defeating the affinity guarantee on exactly the heavy-upload flows that need it most.

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 4cdcdf0 are stale repeats of P1/P2 already addressed in earlier rounds.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread app/modules/proxy/service.py Outdated
# 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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.
@Soju06

Soju06 commented Apr 30, 2026

Copy link
Copy Markdown
Owner Author

Pushed 7356778 for the new P2 codex flagged on b715170 (Treat promptCacheKey alias as explicit affinity signal).

Borderline-gap: the V1 normalization path (/v1/responses -> V1ResponsesRequest.to_responses_request) rewrites promptCacheKey -> prompt_cache_key before ResponsesRequest.model_validate so the canonical name lands in model_fields_set correctly. But the raw codex backend route (/backend-api/codex/responses) binds ResponsesRequest directly via FastAPI body, so a client posting the camelCase alias would have it preserved verbatim and "prompt_cache_key" in model_fields_set would be false -- silently making the file pin override an explicit continuation marker.

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

_prompt_cache_key_from_request_model already accepts either name when it reads the populated value, so the value-check still fires correctly.

No test churn -- the existing precedence regression covers the canonical key and the new branch is a spelling tolerance for the alias.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

ℹ️ 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".

@Soju06
Soju06 merged commit 7ecb77a into main May 1, 2026
18 checks passed
Soju06 added a commit that referenced this pull request May 9, 2026
)

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.
Soju06 added a commit that referenced this pull request May 10, 2026
… 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.
Soju06 added a commit that referenced this pull request May 10, 2026
…/ 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.
vitalNohj pushed a commit to vitalNohj/codex-lb that referenced this pull request Jul 17, 2026
* 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.
vitalNohj pushed a commit to vitalNohj/codex-lb that referenced this pull request Jul 17, 2026
…" (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.
vitalNohj pushed a commit to vitalNohj/codex-lb that referenced this pull request Jul 17, 2026
…/ 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.
glopyglerky pushed a commit to glopyglerky/codex-lb that referenced this pull request Dec 2, 2026
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`).
glopyglerky pushed a commit to glopyglerky/codex-lb that referenced this pull request Dec 2, 2026
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.
glopyglerky pushed a commit to glopyglerky/codex-lb that referenced this pull request Dec 2, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Payload too large: 413 error

1 participant