Skip to content

fix(responses): count input tokens locally for Codex OAuth - #2

Merged
anhtran-ai merged 2 commits into
release/v3.8.51from
fix/local-responses-input-token-count
Sep 10, 2026
Merged

anhtran-ai merged 2 commits into
release/v3.8.51from
fix/local-responses-input-token-count

Conversation

@anhtran-ai

Copy link
Copy Markdown

Problem

POST /v1/responses/input_tokens was handled by the generic Responses passthrough and forwarded to chatgpt.com/backend-api/codex/responses/input_tokens. For the Codex OAuth account in production, that upstream subpath is not served (404 through the Chrome transport) and native transport is intercepted by a Cloudflare managed challenge. The forwarding path can never return a useful count, adds latency/fallback, and previously terminalized the healthy connection.

Fix

Add a static /v1/responses/input_tokens route that shadows [...path] and counts locally with the existing js-tiktoken counter (o200k_base for cx/Codex). It returns the exact OpenAI contract:

{"object":"response.input_tokens","input_tokens":123}

No upstream request is issued. The route preserves API-key/model policy and process-wide body admission, counts instructions, structured input, tool definitions and Responses config, and applies a conservative overhead model measured against live Codex usage.

The companion classifier safety net is already merged in fork PR #1 and proposed upstream in diegosouzapw#13161.

Validation

Local:

  • Route unit tests: 9/9 pass.
  • npm run typecheck:core: clean.
  • ESLint: clean.

Production (llm-gateway/omniroute:3.8.51-113ddf9a-azox1):

  • Static route schema: 8/8 exact.
  • Live A/B against Codex usage.input_tokens: 8/8 valid, 0 under-counts, median absolute error 0%; five cases exact, structured input +12.2%, one tool +1.5%, two tools +30.7% (safe direction: early compaction).
  • Count soak: 50/50 and isolated 100/100 HTTP 200.
  • Isolated 100-count soak: proxy log delta 0, Cloudflare challenge 0, permanent bans 0.
  • Normal Codex inference: 6/6 HTTP 200 after the first deploy; all 8 A/B inference requests also HTTP 200.
  • Persisted Codex state: is_active=1, test_status=active, no error fields.
  • Container: healthy, restart count 0; LiteLLM, 9Router and portal peers were not recreated.

Production rollback artifacts:

  • Previous image remains: llm-gateway/omniroute:3.8.50-5458026c.
  • Intermediate candidate remains: llm-gateway/omniroute:3.8.51-55155b92-azox1.
  • Predeploy data backup: omniroute-data-pre-55155b92-20260910-105915.tgz (mode 0600).
  • Candidate booted healthy against a cloned production volume; SQLite integrity ok, 2 provider connections.

…t rejection, not a ban

A Cloudflare managed/JS challenge served in front of an upstream provider is the
same class of block as a Cloudflare 1010 — the edge refused the CLIENT's
signature — but it is a different product surface and carries none of the 1010
markers isCloudflareFingerprintRejection() looks for.

It therefore fell through the entire 403 ladder in classifyProviderError() to the
terminal default FORBIDDEN, which chatCore persists via writeTerminalStatus() as
testStatus=banned / isActive=false. That state never auto-recovers, so a single
challenge takes the whole provider offline until an operator reconnects in the
dashboard.

Observed on POST chatgpt.com/backend-api/codex/responses/input_tokens for a
healthy Codex OAuth account: the response carried cf-mitigated: challenge,
server: cloudflare and a ~12KB text/html interstitial with
window._cf_chl_opt = {... cType: 'managed', cZone: 'chatgpt.com' ...}. The same
connection refreshed its OAuth token successfully in the same second and served
normal /responses traffic seconds before and after, so the account was never
banned upstream.

Classify the interstitial as FINGERPRINT_REJECTION, reusing the existing
non-terminal precedent from diegosouzapw#9929: authTerminalStatus already treats that type as
non-terminal, so the request falls through to the next combo target and the
account state stays untouched.

The markers are matched as full, distinctive Cloudflare-internal strings
(_cf_chl_opt, cdn-cgi/challenge-platform, the challenge-error-text span id
including its escaped-quote nested form) and never as the loose word
"challenge", so provider bodies discussing a challenge in prose are unaffected.

Tests cover the full interstitial, the gateway-nested error.message form, each
marker individually, prose false-positive guards, and regression guards proving
a genuine permission 403 and the ChatGPT Web Sentinel/Turnstile 403 (diegosouzapw#8813) both
still classify as FORBIDDEN.
The ChatGPT subscription backend does not serve
/backend-api/codex/responses/input_tokens for the affected account. Native
requests to that path are intercepted by an OpenAI Cloudflare managed challenge,
while the same path over the bundled Chrome transport returns 404 Not Found.
Forwarding the client preflight can therefore never return a useful count and,
before the companion classifier fix, permanently disabled the healthy Codex
connection on the first challenge.

Add a static /v1/responses/input_tokens route that shadows the generic
Responses passthrough, uses the existing offline o200k_base token counter, and
returns the standard response.input_tokens contract without issuing any upstream
request. Count instructions, structured input, tool definitions and config;
apply a conservative five-percent margin so the failure mode is earlier client
compaction rather than a context-window overflow.

Preserve the API-key and model-policy boundary from the catch-all Responses path.
Tests pin the public schema, prove fetch is never called, cover text,
instructions, structured input, tools, non-text parts, server-held context ids,
invalid JSON, OPTIONS, and the conservative lower bound.
@anhtran-ai
anhtran-ai merged commit 90a3afa into release/v3.8.51 Sep 10, 2026
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.

2 participants