Skip to content

Fix stale Codex usage after reset - #21748

Merged
OrcaWin merged 2 commits into
mainfrom
OrcaWin/np-reset
Sep 20, 2026
Merged

OrcaWin merged 2 commits into
mainfrom
OrcaWin/np-reset

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​44 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​44
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​68 $\color{#cf222e}{\Huge{\mathbf{−}}}$​20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​48

ELI5

After a Codex reset succeeds, the status bar now keeps checking briefly until the refreshed quota is visible, instead of leaving the old 100% value on screen.

What Changed

  • Added bounded post-reset Codex usage retries when the first quota response still contains the pre-reset session usage or is temporarily unavailable.
  • Kept target and generation checks unchanged so a reset cannot overwrite a newer runtime/account selection.
  • Added a regression test covering 100% followed by 0%.

Why

The reset mutation and quota read are separate backend operations, so the first read can briefly lag behind a successful reset. A short, bounded retry makes the status bar converge to the new data without adding a permanent polling cost.

Linked Issue

No issue was provided for this request.

Visual Proof

N/A — this is a data-refresh timing fix; the status bar layout and controls are unchanged.

Testing

  • Automated tests added/updated.
  • pnpm test src/main/rate-limits/service-account-target-selection.test.ts
  • pnpm tc:node
  • Changed-file oxlint and formatting hooks

AI Disclosure

Codex (GPT-6)

Review

Agent skill upstream boundary

  • Not applicable.

Notes

The retry is limited to successful reset outcomes and at most three additional reads with 250 ms spacing. No platform-specific, SSH, mobile, or wire-format behavior changed.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • Before/after screenshots or videos attached, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • Full lint/typecheck/test/build (CI will cover)

@coderabbitai

coderabbitai Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The reset outcome now reaches fetchCodexResetResultState. After a reset, the service retries Codex rate-limit reads up to three times, with a 250 ms delay between attempts, until refreshed session or weekly usage becomes visible. Other outcomes retain single-fetch behavior. Tests cover stale session and weekly quota responses.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 27904

A reset can still display stale weekly usage for accounts whose session window appears before the weekly value refreshes. Correct the visibility predicate before merging.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change, rationale, testing, visual impact, AI disclosure, and compatibility considerations. However, it does not provide the required linked issue and explicitly states that… Add a valid linked issue under the Linked Issue section, using the required Fixes #<issue-number> format, before merging.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: fixing stale Codex usage after a reset.
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.
Full details: Description check

Explanation

The description covers the change, rationale, testing, visual impact, AI disclosure, and compatibility considerations. However, it does not provide the required linked issue and explicitly states that no issue was provided.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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

Run ID: 79c3acda-8d1e-4618-afa1-2a805b25235f

📥 Commits

Reviewing files that changed from the base of the PR and between b5b727b and fd81ade.

📒 Files selected for processing (3)
  • src/main/rate-limits/service-account-target-selection.test.ts
  • src/main/rate-limits/service/service-account-refresh.ts
  • src/main/rate-limits/service/service-fetch-targets.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

} finally {
this.finishFetchCycle(controller)
}
const resetVisible = fresh.status === 'ok' && (fresh.session?.usedPercent ?? 0) <= 0

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not treat a missing session window as a visible reset.

fresh.session?.usedPercent ?? 0 converts a null session to zero. An ok response with no session window therefore stops the retry loop immediately.

Require a session window before declaring the reset visible. Otherwise, a temporarily missing session can return blank or stale usage instead of using the remaining retries.

Proposed fix
-      const resetVisible = fresh.status === 'ok' && (fresh.session?.usedPercent ?? 0) <= 0
+      const resetVisible =
+        fresh.status === 'ok' && fresh.session !== null && fresh.session.usedPercent <= 0
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const resetVisible = fresh.status === 'ok' && (fresh.session?.usedPercent ?? 0) <= 0
const resetVisible =
fresh.status === 'ok' && fresh.session !== null && fresh.session.usedPercent <= 0

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

Important

The post-reset retry only inspects the 5-hour session window, so it never retries when weekly is the window the reset changed — and for weekly-only accounts it exits on the very first read. Details inline.

Reviewed changes

fetchCodexResetResultState now converges the Codex usage snapshot after a successful reset instead of trusting the first (possibly lagging) read.

  • Bounded post-reset retry — after outcome === 'reset', re-read Codex usage up to 3 extra times, 250 ms apart, stopping once the session window reports 0%.
  • Outcome-aware gating — non-reset outcomes still perform a single read; the target/provenance/generation guards around publishing are unchanged.
  • Regression test — asserts 100% → 0% converges and that fetchCodexRateLimits is called twice.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

} finally {
this.finishFetchCycle(controller)
}
const resetVisible = fresh.status === 'ok' && (fresh.session?.usedPercent ?? 0) <= 0

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.

The retry stops as soon as session.usedPercent <= 0, so it never covers the weekly window. For a weekly-only account (session: null) the predicate is true on the first read and the loop breaks immediately, even when weekly is the window the reset changed — the same stale-usage symptom this PR fixes.

Technical details
# Post-reset retry predicate only observes the session window

## Affected sites
- `src/main/rate-limits/service/service-fetch-targets.ts:126` — `resetVisible` reads `fresh.session?.usedPercent ?? 0`, so a null or zero session satisfies it regardless of `weekly`.
- `src/main/rate-limits/service-account-target-selection.test.ts:149` — the new test only exercises the session path (100 → 0).

## Required outcome
- Decide which windows the reset is expected to change and wait for all of them (or the specific exhausted one) before stopping.

## Evidence
- Weekly-only is a supported shape: `codex-rate-limit-window-classification.ts:43` classifies a 10080-minute primary as `weekly` with `session: null`; `service-account-target-selection.test.ts:456` exercises it.
- Reset eligibility is credit-only, not window-specific: `src/shared/codex-reset-credit-scope.ts:59`, `codex-reset-credit-scope-validation.ts:47`.
- User-facing copy: `CodexSwitcherMenu.tsx:113` ("resets any eligible usage windows"); `docs/site/content/docs/mobile.mdx:76` ("refreshes eligible rate-limit windows").
- External: openai/codex issues #37396 and #45570 report a redeemed credit clearing the weekly window.

## Open questions for the human
- Does a reset always clear every exhausted window together, or only the one that triggered it? If `weekly` can lag independently the predicate needs to include it; if the windows always move together, `session` may be enough but a null session still short-circuits the loop.

if (attempt > 0) {
await waitForCodexResetRefresh()
}
const controller = this.beginFetchCycle()

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.

stop() aborts in-flight fetches, but an aborted fetch resolves to status: 'error', which this loop treats as retryable. Since stop() already cleared activeFetchAbortControllers, the fresh controller each attempt creates is never aborted, so up to three real Codex fetches run after the service is torn down.

Technical details
# Retry loop outlives service teardown

## Affected sites
- `src/main/rate-limits/service/service-fetch-targets.ts:107` — a new `beginFetchCycle()` per attempt with no abort check.
- `src/main/rate-limits/service/service-configuration.ts:108` — `stop()` calls `abortActiveFetchCycle()`, which aborts and then clears the controller set.
- `src/main/rate-limits/codex-rate-limit-fetch-result.ts:3` — an aborted fetch returns `status: 'error'`, so `resetVisible` stays false and the loop retries.

## Required outcome
- A `stop()` during the retry sequence should end the sequence rather than spawn three more reads.

## Suggested approach
- Hold one controller for the whole sequence (register it via `beginFetchCycle`, finish it once), pass its `signal` to each `fetchCodexRateLimits` call, and wait with the existing `delayUnlessAborted` (`src/main/rate-limits/service/service-types.ts:140`) so an abort breaks the loop.

@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: Advanced

Run ID: 0558c325-1b80-4de0-bd42-a336ac3cd9aa

📥 Commits

Reviewing files that changed from the base of the PR and between fd81ade and 2790456.

📒 Files selected for processing (2)
  • src/main/rate-limits/service-account-target-selection.test.ts
  • src/main/rate-limits/service/service-fetch-targets.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

}
const sessionImproved =
fresh.session !== null &&
(previous.session === null || fresh.session.usedPercent < previous.session.usedPercent)

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not treat a newly present window as reset visibility.

If previous.weekly is 100% and previous.session is null, a response with session.usedPercent still at 100% and weekly.usedPercent still at 100% sets sessionImproved to true. The loop then stops before the weekly window refreshes.

Only count a window with a previous value when its usedPercent decreases. Add a test for this mixed-window response.

Proposed fix
 const sessionImproved =
-  fresh.session !== null &&
-  (previous.session === null || fresh.session.usedPercent < previous.session.usedPercent)
+  fresh.session !== null &&
+  previous.session !== null &&
+  fresh.session.usedPercent < previous.session.usedPercent
 const weeklyImproved =
-  fresh.weekly !== null &&
-  (previous.weekly === null || fresh.weekly.usedPercent < previous.weekly.usedPercent)
+  fresh.weekly !== null &&
+  previous.weekly !== null &&
+  fresh.weekly.usedPercent < previous.weekly.usedPercent

Also applies to: 39-39

@OrcaWin
OrcaWin merged commit e225b4b into main Sep 20, 2026
29 of 30 checks passed
@OrcaWin
OrcaWin deleted the OrcaWin/np-reset branch September 20, 2026 05:22
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.

1 participant