Skip to content

fix(codex): fall back on invalid rate-limit RPC responses - #11662

Closed
kazu-42 wants to merge 3 commits into
stablyai:mainfrom
kazu-42:agent/fix-codex-rpc-rate-limit-fallback
Closed

kazu-42 wants to merge 3 commits into
stablyai:mainfrom
kazu-42:agent/fix-codex-rpc-rate-limit-fallback

Conversation

@kazu-42

@kazu-42 kazu-42 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Validate the successful account/rateLimits/read envelope before treating an app-server response as usable.
  • Return an RPC error for missing or malformed required rateLimits data, including malformed nested primary / secondary windows, so the existing /status PTY fallback can recover usage instead of showing an incorrect empty state.
  • Preserve Orca's existing tolerance for an explicit rateLimits: null, and preserve allowPtyFallback: false for background managed-account previews.

Protocol evidence

The current Codex app-server documentation shows account/rateLimits/read returning a result wrapper with rateLimits, optional rateLimitsByLimitId, and optional rateLimitResetCredits.

The locally installed codex-cli 0.146.0 generated schema (codex app-server generate-json-schema) declares rateLimits as the required backward-compatible single-bucket view and rateLimitsByLimitId as optional. A rateLimitsByLimitId-only success is therefore treated as invalid rather than silently mapped to empty usage.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — ran 8 focused files / 72 tests covering RPC, backend supplementation, PTY settlement, test-harness disposal, auth errors, window classification, and target selection
  • pnpm build — no packaging, renderer, dependency, or asset changes
  • Added regression tests

Focused verification on the exact rebased head:

Test Files  8 passed (8)
Tests       72 passed (72)

The primary regression test failed on the old implementation because { rateLimitsByLimitId: null } was accepted as status: "ok" with null windows and PTY never started. It now reaches PTY and returns the parsed 5-hour and weekly usage. Separate tests lock explicit-null compatibility, malformed top-level rejection, and both fallback-enabled and fallback-disabled behavior for malformed nested windows.

AI Review Report

Five independent final review axes covered correctness, reliability, security/data integrity, cross-version/platform compatibility, and maintainability/test quality.

The review checked:

  • required-own-property validation versus missing, primitive, array, optional-field-only envelopes, and malformed nested windows;
  • explicit-null behavior and forward-compatible fallback rather than speculative parsing of undocumented unwrapped shapes;
  • listener, timer, abort, and child-process cleanup through the shared settle(..., { kill: true }) path, including effective test-double subscription disposal;
  • allowPtyFallback: false behavior for managed-account background previews;
  • macOS, Linux, Windows host, WSL, and SSH implications;
  • fixed diagnostic text without response payload, stderr, tokens, or account material;
  • max-lines policy, fake-timer cleanup, and shared RPC/PTY test harness design.

All five final axes reported no remaining P0-P3 findings.

Security Audit

  • No response payload or credential material is added to logs or returned errors.
  • The guard uses an own-property check and rejects null top-level values, primitives, arrays, and missing required data.
  • The existing account-scoped CODEX_HOME / WSL execution target is unchanged.
  • Normal interactive polling may start only the existing PTY fallback after an invalid RPC result; background managed-account previews still disable PTY fallback.
  • No new IPC, shell command, dependency, path input, or persistence format is added.

Notes

  • This is intentionally separate from fix(codex): make account removal crash-safe #11655: account-removal durability and rate-limit protocol parsing have independent failure modes, tests, and rollback paths.

  • Unknown or future response shapes fail over to the existing PTY reader instead of being accepted as empty usage.

  • Rollback is a one-commit revert with no migration.

  • Contributor X: @DevKazu42

@kazu-42
kazu-42 marked this pull request as ready for review July 31, 2026 02:42
@kazu-42

kazu-42 commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The RPC rate-limit response now requires a rateLimits property. Runtime validation rejects missing, null-result, array, and invalid object shapes. Invalid responses produce an Invalid RPC rate-limit response error and terminate the child process. Tests use shared RPC and PTY helpers and cover PTY fallback, explicit null handling, malformed responses, and timer cleanup.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the main change: using PTY fallback when rate-limit RPC responses are invalid.
Description check ✅ Passed The description covers the change, testing, review, security, platform checks, risks, and the absence of visual changes.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 18c1e24b-f4d8-4e16-a73d-f1d77c502654

📥 Commits

Reviewing files that changed from the base of the PR and between b5abab8 and 4d3a95f.

📒 Files selected for processing (2)
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts

Comment thread src/main/rate-limits/codex-fetcher.ts Resolved
@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds validation of the account/rateLimits/read RPC envelope in the Codex rate-limit fetcher, so that missing or malformed rateLimits data returns an RPC error instead of silently producing an empty state — allowing the existing PTY fallback to recover usage figures.

  • Introduces isRpcRateLimitsResponse, a type guard that rejects null top-level values, missing rateLimits own-property, array shapes, and malformed nested primary/secondary windows, while preserving compatibility for an explicit rateLimits: null.
  • Extracts makeRpcChild, makePtyTerm, makeDisposable, and respondToRpcResult into a shared codex-fetcher-rpc-test-harness.ts so both existing and new regression tests use a consistent, disposal-aware mock implementation.
  • Adds vi.useRealTimers() to the afterEach hook to prevent fake-timer state from leaking across tests.

Confidence Score: 5/5

Safe to merge — the change is a well-scoped guard that adds an explicit validation step before consuming the RPC response, with no changes to the happy-path data flow or persistence format.

The type guard correctly rejects all malformed shapes (missing key, null top-level, array, invalid nested windows) while preserving the documented explicit-null case. The fallback wiring through the existing allowPtyFallback / isCodexAuthError checks is untouched. Tests cover all new branches including the disabled-fallback path, and the fake-timer leak is fixed in afterEach. No data is lost or misinterpreted on either the valid or invalid response paths.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/rate-limits/codex-fetcher.ts Adds isRpcRateLimitsResponse type guard and wires it into the RPC response handling path; logic is correct and the error path correctly falls through to PTY fallback or returns an error when fallback is disabled.
src/main/rate-limits/codex-fetcher-rpc-test-harness.ts New shared harness; upgrades makePtyTerm to use Sets so multiple subscriptions coexist correctly, and gives makeDisposable a real cleanup callback so disposal actually removes handlers.
src/main/rate-limits/codex-fetcher.test.ts Migrates helpers to the shared harness, adds five regression tests covering invalid RPC shapes, explicit-null compatibility, and allowPtyFallback: false paths; fixes timer leak by adding vi.useRealTimers() to afterEach.
src/main/rate-limits/codex-fetcher-rpc-test-harness.test.ts Adds a focused unit test verifying that disposing a PTY event subscription stops event delivery; correctly exercises the new Set-based handler management.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[fetchCodexRateLimits] --> B[fetchViaRpc]
    B --> C[RPC: account/rateLimits/read]
    C --> D{msg.error?}
    D -- yes --> E[settle error + kill]
    D -- no --> F{isRpcRateLimitsResponse?}
    F -- no --> G[settle Invalid RPC rate-limit response + kill]
    F -- yes --> H{rateLimits === null?}
    H -- yes --> I[settle ok: session=null, weekly=null]
    H -- no --> J[classifyCodexRateLimitWindows]
    J --> K[settle ok with session/weekly]
    G --> L{rpcResult.status === ok/unavailable?}
    E --> L
    K --> L
    I --> L
    L -- yes --> M[withBackendSessionWindow / withBackendRateLimitResetCredits]
    M --> N[Return result]
    L -- no --> O{isCodexAuthError?}
    O -- yes --> P[Return auth error]
    O -- no --> Q{allowPtyFallback === false?}
    Q -- yes --> R[Return RPC error]
    Q -- no --> S[fetchViaPty PTY fallback]
    S --> T[Parse PTY output]
    T --> N
Loading

Reviews (3): Last reviewed commit: "test(codex): dispose RPC PTY harness lis..." | Re-trigger Greptile

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e5c389e7-a662-48b5-81d8-d387290338ac

📥 Commits

Reviewing files that changed from the base of the PR and between 4d3a95f and 6b200d0.

📒 Files selected for processing (3)
  • src/main/rate-limits/codex-fetcher-rpc-test-harness.ts
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts

@Jinwoo-H

Copy link
Copy Markdown
Contributor

Thanks @kazu-42 for the malformed Codex rate-limit fallback fix. We consolidated this with #11766 and #11760 in canonical issue #17518, covering provider RPC, PTY, and local-log fallback behavior. We will reimplement the matrix on current main; no contributor follow-up is requested. Closing this superseded branch while preserving your credit.

@Jinwoo-H Jinwoo-H closed this Aug 31, 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.

5 participants