codex icon indicating copy to clipboard operation
codex copied to clipboard

Usage-limit 429: codex-family rate-limit headers discarded when x-codex-active-limit names another limit

Open imluckii opened this issue 1 month ago • 3 comments

Area

Core (codex-api / error mapping)

Steps to reproduce

  1. Use a ChatGPT-plan account that hits a usage limit on the codex backend (chatgpt.com/backend-api/codex/responses).
  2. Send a request that receives 429 with these (real, captured) headers and body:
X-Codex-Active-Limit: premium
X-Codex-Plan-Type: plus
X-Codex-Primary-Used-Percent: 100
X-Codex-Primary-Reset-At: 1793390439
X-Codex-Primary-Window-Minutes: 300
X-Codex-Secondary-Used-Percent: 53
X-Codex-Secondary-Reset-At: 1793870576
X-Codex-Secondary-Window-Minutes: 10080
X-Codex-Credits-Balance: 0

{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_at":1793390439,"eligible_promo":null,"limit_window_minutes":300,"resets_in_seconds":4454}}
  1. Observe what map_api_error produces for the rate-limit snapshot, and what downstream consumers (app-server account/rateLimits/updated notifications, TUI rate-limit banner) receive.

Expected behavior

The 429 carries a complete x-codex-* window family (primary 100% + reset timestamp, secondary 53% + reset). map_api_error should surface that snapshot on UsageLimitReachedError.rate_limits so core's update_rate_limits records the real windows and the app-server emits an account/rateLimits/updated notification with usable reset data.

Actual behavior

api_bridge.rs parses the snapshot from the ACTIVE limit family only: parse_rate_limit_for_limit(headers, limit_id) where limit_id comes from x-codex-active-limit: premium. That keys the header prefix to x-premium-*, which matches nothing, so the snapshot is RateLimitSnapshot { limit_id: "premium", primary: None, secondary: None, ... }. The complete codex-family window data on the same response is discarded.

Downstream effect: core calls update_rate_limits with the empty snapshot and clients receive an all-null premium update instead of real window state. Any client that tracks usage-window resets (e.g. to schedule resume-after-limit) only has data if earlier successful responses already primed its state; a client whose first request in a session 429s never learns the reset time, even though the error message itself says "try again at

Impact tier

Medium: no data loss or crash, but automated resume-after-limit and usage-window display silently break exactly when the limit is hit, which is when they matter.

Version or commit

rust-v0.165.0 (also present on current main; verified against codex-api/src/api_bridge.rs)

Environment

Linux x86_64 + aarch64, codex CLI driven through an OpenAI-compatible proxy; headers captured live from the codex backend's 429 on 2026-10-30.

Workaround

None client-side; a client can fall back to parsing resets_at out of the 429 body, but the structured snapshot path stays blind until a successful response re-primes it.

imluckii avatar Oct 30 '26 19:10 imluckii

Reference implementation that fixes this locally (passes the full codex-api lib suite, 193/193, including the two tests pinning metadata-only active families):

--- a/codex-rs/codex-api/src/api_bridge.rs
+++ b/codex-rs/codex-api/src/api_bridge.rs
@@
                             let limit_id = extract_header(headers.as_ref(), ACTIVE_LIMIT_HEADER);
                             let promo_message = headers.as_ref().and_then(parse_promo_message);
                             let rate_limit_reached_type =
                                 headers.as_ref().and_then(parse_rate_limit_reached_type);
+                            // The active-limit family can arrive without any window
+                            // headers (e.g. an upgrade-gated "premium" limit), while the
+                            // default codex family on the same response still carries the
+                            // real usage windows. Keep the active family's snapshot when
+                            // it has windows or the default family has nothing to add;
+                            // otherwise fall back to the codex windows (preserving the
+                            // active family's limit name and credits) so clients receive
+                            // usable reset times instead of an empty snapshot.
+                            let has_windows = |snapshot: &RateLimitSnapshot| {
+                                snapshot.primary.is_some() || snapshot.secondary.is_some()
+                            };
                             let rate_limits = headers
                                 .as_ref()
                                 .and_then(|map| {
-                                    parse_rate_limit_for_limit(map, limit_id.as_deref())
+                                    parse_rate_limit_for_limit(map, limit_id.as_deref()).map(
+                                        |snapshot| {
+                                            if has_windows(&snapshot) {
+                                                return snapshot;
+                                            }
+                                            match parse_default_rate_limit(map) {
+                                                Some(defaults) if has_windows(&defaults) => {
+                                                    RateLimitSnapshot {
+                                                        limit_name: snapshot
+                                                            .limit_name
+                                                            .or(defaults.limit_name),
+                                                        credits: snapshot
+                                                            .credits
+                                                            .or(defaults.credits),
+                                                        ..defaults
+                                                    }
+                                                }
+                                                _ => snapshot,
+                                            }
+                                        },
+                                    )
                                 })
                                 .map(|mut snapshot| {
                                     snapshot.rate_limit_reached_type = rate_limit_reached_type;
                                     snapshot
                                 });

with use crate::rate_limits::parse_default_rate_limit; and use codex_protocol::protocol::RateLimitSnapshot; added to the imports.

Regression test (fails on main with limit_id == "premium" / no windows, passes with the patch):

#[test]
fn map_api_error_keeps_codex_windows_when_active_limit_family_is_empty() {
    let mut headers = HeaderMap::new();
    headers.insert(ACTIVE_LIMIT_HEADER, http::HeaderValue::from_static("premium"));
    headers.insert("x-codex-primary-used-percent", http::HeaderValue::from_static("100"));
    headers.insert("x-codex-primary-window-minutes", http::HeaderValue::from_static("300"));
    headers.insert("x-codex-primary-reset-at", http::HeaderValue::from_static("1793390439"));
    headers.insert("x-codex-secondary-used-percent", http::HeaderValue::from_static("53"));
    let body = serde_json::json!({
        "error": {
            "type": "usage_limit_reached",
            "plan_type": "plus",
            "resets_at": 1793390439,
            "limit_window_minutes": 300,
        }
    })
    .to_string();
    let err = map_api_error(ApiError::Transport(TransportError::Http {
        retry_after: None,
        status: http::StatusCode::TOO_MANY_REQUESTS,
        url: Some("http://example.com/v1/responses".to_string()),
        headers: Some(headers),
        body: Some(body),
    }));

    let CodexErrorDetails::UsageLimitReached(usage_limit) = err.details() else {
        panic!("expected CodexErrorDetails::UsageLimitReached, got {err:?}");
    };
    let snapshot = usage_limit
        .rate_limits
        .as_ref()
        .expect("codex window headers should produce a rate-limit snapshot");
    assert_eq!(snapshot.limit_id.as_deref(), Some("codex"));
    let primary = snapshot.primary.as_ref().expect("primary window");
    assert_eq!(primary.used_percent, 100.0);
    assert_eq!(primary.resets_at, Some(1793390439));
}

Design note: metadata-only active families (e.g. codex_other with a limit name but no windows, and no default-family windows either) keep today's behavior exactly - the fallback only fires when the default family actually has windows to contribute.

Authored with GLM (glm-5.3) through the Hermes agent.

imluckii avatar Oct 30 '26 19:10 imluckii

Thanks - the matrix matches what the reference patch above already does, mapping each case:

  1. active=premium with only x-codex-primary/secondary-* present: the fallback returns the default-family snapshot keyed codex with its own reset epochs, and never fabricates premium windows (the active family's limit name/credits ride along as display metadata).
  2. Genuinely present x-premium-* windows: has_windows(active) is true, so the active snapshot is returned untouched in its own bucket.
  3. No window-family headers at all: api_bridge still returns the metadata-only snapshot (existing tests pin the limit-name/reached-type path), so the "don't publish an all-null update as measured state" half of this belongs on the consumer side - in core/src/session/turn.rs the usage-limit branch could gate update_rate_limits on the same has-windows predicate rather than treating Some as quota data.
  4. Body error.resets_at is untouched by the patch; it stays error-level evidence feeding UsageLimitReachedError.resets_at and the retry message.

Verified against the full codex-api lib suite (193 passed) with a regression test for case 1; cases 2-4 are covered by the existing map_api_error_* tests, which stay green.

imluckii avatar Oct 30 '26 21:10 imluckii

Closing from the reporter's side. We only needed this fixed in our two consumers, and both are done: t3 re-reads rate limits after a first-request 429 (pingdotgg/t3code#27791) and recovers the reset time from the error text on proxied routes (pingdotgg/t3code#32188), and our proxy no longer carries a header workaround now that the parser quirk is understood. The active-limit parsing behavior remains as described for anyone tracking it upstream.

imluckii avatar Nov 22 '26 20:11 imluckii