Skip to content

fix(rate-limits): fall back to the local session log for Codex usage - #11766

Closed
YuSoeun wants to merge 3 commits into
stablyai:mainfrom
YuSoeun:fix/codex-session-log-usage-fallback
Closed

YuSoeun wants to merge 3 commits into
stablyai:mainfrom
YuSoeun:fix/codex-session-log-usage-fallback

Conversation

@YuSoeun

@YuSoeun YuSoeun commented Jul 31, 2026 •

Copy link
Copy Markdown

Summary

  • Unlike Claude, Codex has no live per-turn push into Orca — every usage refresh goes through chatgpt.com (backend fetch, RPC app-server, or a PTY /status probe), all of which require reaching OpenAI's network. When all three fail, the usage bar went completely dark with no local fallback (see the related Claude fix in fix(rate-limits): fall back to context_window for Claude usage on Vertex/proxy backends #11760 for the internal-network usage investigation this follows up on).
  • Codex's own session log already records a token_count event with total_token_usage and model_context_window on every turn. fetchCodexRateLimits now reads the most recently modified session log's last token_count event as a last-resort, network-free usage signal when every network path returns a genuine error.
  • Auth errors are explicitly excluded from the fallback — masking "you need to re-sign in" with a locally-derived ok would hide the one thing the user actually needs to act on.

Testing

  • pnpm typecheck (targeted: tsc --noEmit -p config/tsconfig.node.json)
  • pnpm lint (targeted oxlint + type-aware + native-plugins + max-lines-ratchet + reliability-gates on changed files)
  • pnpm test (targeted: all src/main/rate-limits/codex-*.test.ts — 89 tests passing, including 21 pre-existing codex-fetcher tests unchanged and 2 new integration tests for the fallback)
  • pnpm build — not run; native module rebuild requires Visual Studio Build Tools not available in this environment (unrelated to this change, which is TS-only)

New coverage:

  • codex-session-log-usage.test.ts — pure token_count parsing (last-event priority, last_token_usage fallback, malformed lines, missing model_context_window, clamping) and the file-selection wrapper via dependency injection
  • codex-fetcher.test.ts — the fallback engaging when every network path exhausts to status: 'error', and not engaging when the fetch was aborted

AI Review Report

Reviewed with Claude Code. Checked: cross-platform (pure JSON/string parsing, no OS-specific paths — reuses the existing codex-usage/scanner.ts directory discovery which already handles Windows/WSL/macOS/Linux session locations), SSH/remote compatibility (session log discovery is unchanged, local-only by design since this is a local fallback), auth-error handling (verified via test that auth errors are never masked by the fallback — this was caught as a real bug during review: an early version applied the fallback to auth-error results too, which surfaced during testing as a live session on the dev machine getting silently marked "ok"), and regression safety (all pre-existing codex-fetcher and codex-fetcher-auth-errors tests pass unchanged).

Security Audit

  • Reads only local files already covered by the existing Codex session-log scanner's directory allowlist; no new file paths or write operations introduced.
  • No new network calls, credentials, or IPC surface — purely a local-file read gated behind the same auth-presence check the rest of fetchCodexRateLimits already uses.
  • JSON parsing is wrapped in try/catch per line; malformed session logs degrade to null rather than throwing.

Notes

  • weekly stays null in the fallback result since the local session log has no 7-day window data — only the 5-hour session window is populated.
  • Twitter/X handle: not provided.

Unlike Claude, Codex has no live per-turn push into Orca — every usage
refresh goes through chatgpt.com (backend fetch, RPC app-server, or a PTY
/status probe), all of which require reaching OpenAI's network. When all
three fail, the usage bar went completely dark with no local fallback.

Codex's own session log already records a token_count event with
total_token_usage and model_context_window on every turn. Read the most
recently modified session log's last token_count event as a last-resort,
network-free usage signal — but only for genuine network/CLI failures, not
for auth errors, which need to stay visible so the user knows to re-sign in.
@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds a local session-log fallback to fetchCodexRateLimits so the usage bar stays populated when every network path (backend/RPC/PTY) fails for a non-auth reason. It follows a parallel fix for Claude (#11760) and gates the fallback carefully: auth errors and aborted fetches bypass it entirely.

  • codex-session-log-usage.ts — new module that scans session JSONL files sorted by mtime and extracts the usedPercent from the last token_count event, with full dependency injection for testability and graceful degradation on every fs error.
  • codex-fetcher.ts — fetchCodexRateLimitsViaNetwork is renamed (internal) and wrapped by the new exported fetchCodexRateLimits, which invokes the session-log reader only when the network result is a non-auth, non-aborted error.
  • Tests — 89 tests total; new codex-session-log-usage.test.ts covers parsing edge cases and file-selection logic; codex-fetcher.test.ts and the new abort-race test cover the integration path and the abort-during-read race.

Confidence Score: 5/5

Safe to merge — the change is strictly additive, activates only on a non-auth network-error path, and leaves all existing behavior unchanged.

The fallback is well-guarded: auth errors, aborted fetches, and non-error network results all bypass it. The session-log parser is purely functional with no side effects, errors are caught at every layer, and the abort-during-read race is explicitly tested. All 89 tests pass including the 21 pre-existing codex-fetcher tests.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/rate-limits/codex-fetcher.ts Wraps fetchCodexRateLimitsViaNetwork with a thin session-log fallback; auth-error and abort guard conditions are correct and tested.
src/main/rate-limits/codex-session-log-usage.ts New module that parses the last token_count event from a Codex session JSONL log; includes dependency-injected file discovery, stat, and read helpers for clean unit-testability.
src/main/rate-limits/codex-session-log-usage.test.ts New test file with thorough coverage of parsing edge cases (last-event priority, fallback field, malformed JSON, zero/missing context window, clamping) and file-selection logic.
src/main/rate-limits/codex-fetcher.test.ts Adds two integration tests: fallback engaging when all network paths fail, and fallback being skipped on abort; existing 21 tests patched to keep their null-mock default.
src/main/rate-limits/codex-fetcher-session-log-abort.test.ts New test validating the race where abort fires while readLatestCodexSessionUsedPercent is in-flight; confirms the result is discarded and an abort error is returned.
src/shared/rate-limit-types.ts One-line addition of 'session-log' to the UsageRateLimitSource union type.

Reviews (3): Last reviewed commit: "fix(rate-limits): recheck abort signal a..." | Re-trigger Greptile

Comment on lines +66 to +94
export async function readLatestCodexSessionUsedPercent(
listFiles: () => Promise<string[]> = listCodexSessionFiles,
statFile: (filePath: string) => Promise<{ mtimeMs: number }> = getProcessedFileInfo,
readFileFn: (filePath: string) => Promise<string> = (filePath) => readFile(filePath, 'utf8')
): Promise<number | null> {
try {
const files = await listFiles()
let latestPath: string | null = null
let latestMtimeMs = -Infinity
for (const filePath of files) {
try {
const info = await statFile(filePath)
if (info.mtimeMs > latestMtimeMs) {
latestMtimeMs = info.mtimeMs
latestPath = filePath
}
} catch {
// Missing/unreadable file — another session log may still qualify.
}
}
if (!latestPath) {
return null
}
const content = await readFileFn(latestPath)
return extractCodexSessionUsedPercentFromLog(content)
} catch {
return null
}
}

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 Full-file read for tail-of-file data

readFile(filePath, 'utf8') loads the entire session log into memory to then scan backward for the last token_count line. Session logs grow unboundedly with session length; a multi-hour session can produce logs well into the tens of megabytes, making this a non-trivial allocation on an already-stressed (network-down) path. Consider reading only the last N bytes (e.g. 64 KB) via a file handle and scanning that slice first, falling back to a full read only if no token_count is found — the last event is almost always near the end of the file.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +1249 to +1272
if (result.status !== 'error' || options?.signal?.aborted || isCodexAuthError(result.error)) {
return result
}
// Why: Codex has no live per-turn push like Claude's statusline — when every network
// path (backend/RPC/PTY) fails for a non-auth reason, the local session log's last
// token_count event is the only usage signal left, so usage doesn't go completely
// dark on an internal network.
const usedPercent = await readLatestCodexSessionUsedPercent().catch(() => null)
if (usedPercent === null) {
return result
}
return {
...result,
session: {
usedPercent,
windowMinutes: CODEX_SESSION_WINDOW_MINUTES,
resetsAt: null,
resetDescription: null
},
status: 'ok',
error: null,
usageMetadata: { ...result.usageMetadata, source: 'session-log' }
}
}

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 Stale-window usage shown as current

The fallback sets windowMinutes: CODEX_SESSION_WINDOW_MINUTES (5 h) but has no way to know whether the 5-hour window that produced the logged token_count event has already rolled over. A user who hit 80 % in the previous window, let the window reset, then lost network connectivity will see "80 % used" in the bar when they are actually at 0 % in the new window. Because resetsAt: null is returned, no misleading countdown is shown, but the usage bar itself can be materially wrong — with no visual cue that the figure is from a different window. This is an inherent limitation of the local-log approach, but it is worth documenting (e.g. with a staleWindowRisk flag in usageMetadata) so the UI layer can optionally render the bar differently (e.g. with reduced opacity or a "last known" label).

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Codex rate-limit fetching now reads usage from the latest usable local session log when eligible network fetches fail. The parser scans JSONL entries for the latest valid token_count event, validates the context window, and clamps the usage percentage. The reader orders session files by modification time and falls back to older files when needed. The rate-limit source type now includes session-log. Tests cover parsing, file selection, failure handling, fallback behavior, and cancellation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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 and concisely describes the main change: using the local Codex session log as a rate-limit fallback.
Description check ✅ Passed The description covers the change, testing, AI review, security audit, and notes; the missing Screenshots heading is non-critical for this non-UI change.

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: 2

🧹 Nitpick comments (2)
src/main/rate-limits/codex-session-log-usage.ts (2)

66-94: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Fall back to older session files when the newest yields no usable data.

readLatestCodexSessionUsedPercent only extracts usage from the single most recently modified file. If that file has no valid token_count event yet (for example, a session log just created but not yet used), the function returns null even though an older session log may hold a valid signal. Iterate files in descending mtimeMs order and try the next one when extraction returns null.

♻️ Proposed refactor to try older files
-    const files = await listFiles()
-    let latestPath: string | null = null
-    let latestMtimeMs = -Infinity
-    for (const filePath of files) {
-      try {
-        const info = await statFile(filePath)
-        if (info.mtimeMs > latestMtimeMs) {
-          latestMtimeMs = info.mtimeMs
-          latestPath = filePath
-        }
-      } catch {
-        // Missing/unreadable file — another session log may still qualify.
-      }
-    }
-    if (!latestPath) {
-      return null
-    }
-    const content = await readFileFn(latestPath)
-    return extractCodexSessionUsedPercentFromLog(content)
+    const files = await listFiles()
+    const candidates: { path: string; mtimeMs: number }[] = []
+    for (const filePath of files) {
+      try {
+        const info = await statFile(filePath)
+        candidates.push({ path: filePath, mtimeMs: info.mtimeMs })
+      } catch {
+        // Missing/unreadable file — another session log may still qualify.
+      }
+    }
+    candidates.sort((a, b) => b.mtimeMs - a.mtimeMs)
+    for (const { path } of candidates) {
+      try {
+        const content = await readFileFn(path)
+        const usedPercent = extractCodexSessionUsedPercentFromLog(content)
+        if (usedPercent !== null) {
+          return usedPercent
+        }
+      } catch {
+        // Unreadable file — try the next-newest candidate.
+      }
+    }
+    return null

66-94: 🚀 Performance & Scalability | 🔵 Trivial

Consider the cost of repeated session-log scans during sustained outages.

readLatestCodexSessionUsedPercent walks and stats every session file on each call. If Codex rate-limit polling retries periodically and the network stays down, this fallback runs on every poll cycle, repeating the directory walk and per-file stat calls each time. Consider caching the last-known-good result briefly or debouncing this fallback so persistent outages do not repeat the full filesystem scan on every poll.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ee83d21d-8cbc-4e69-99fc-809a3dd3f1d8

📥 Commits

Reviewing files that changed from the base of the PR and between 60d2493 and 39ae359.

📒 Files selected for processing (5)
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/rate-limits/codex-session-log-usage.test.ts
  • src/main/rate-limits/codex-session-log-usage.ts
  • src/shared/rate-limit-types.ts

Comment thread src/main/rate-limits/codex-fetcher.ts Resolved
…eads

readLatestCodexSessionUsedPercent only inspected the single most recently
modified session file. A freshly created session log with no token_count
event yet (or an unreadable file) made the fallback report nothing even
though an older log still had a usable signal.

Sort candidates by mtime and try each in order until one yields a value.

Addresses CodeRabbit feedback on stablyai#11766.
…ck read

readLatestCodexSessionUsedPercent() is awaited after the network paths
exhaust; if the fetch aborts while that read is in flight, the wrapper
returned a fabricated status: 'ok' from the local log instead of the
aborted result, breaking the abort-safety pattern used everywhere else
in this file. Caught by CodeRabbit review on stablyai#11766.
@Jinwoo-H

Copy link
Copy Markdown
Contributor

Thanks @YuSoeun for the Codex session-log fallback work. We consolidated this with #11760 and #11662 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.

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