Skip to content

fix(codex): retain the K12 short-window quota end to end - #2141

Open
lidge-jun wants to merge 1 commit into
devfrom
codex/absorb-k12-short-window
Open

fix(codex): retain the K12 short-window quota end to end#2141
lidge-jun wants to merge 1 commit into
devfrom
codex/absorb-k12-short-window

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Aug 19, 2026

Copy link
Copy Markdown
Owner

Summary

parseUsageQuota filled shortPercent and setAccountQuotaFromParsed dropped it, so the K12 5-hour burst window never reached the cache, the accounts DTO, the dashboard, or routing (#2047). A saturated short window was invisible to account selection.

Credit: @Ingwannu's #2056 is the implementation carried here — shortPercent joins hasKnownQuotaValue, a new snapshotHasShort stops a short-only snapshot reading as empty, partial weekly/monthly snapshots no longer clobber a known short window, and updateAccountQuota carries the tuple. @yzxcj797's #2062 targeted the same issue with a narrower cache write.

The blocker both PRs shared, now fixed

Review flagged this on #2056 and #2062: computeCodexUsageScore took Math.max over every finite window, so a snapshot carrying only shortPercent: 0 scored a flat 0. An account whose weekly/monthly usage was never observed then looked like the emptiest in the pool, and pickLowestUsageAmong would route everything to it — the opposite of what the quota data is for.

The burst window now refines a known long-window position rather than standing in for one: with no governing window observed, the score stays CODEX_UNKNOWN_USAGE_SCORE.

Worth flagging explicitly: the ported test asserted the old behavior directly (computeCodexUsageScore({ shortPercent: 0 })0). I did not delete it quietly — it is replaced by a case that pins the corrected contract in both directions, including that a hot burst still wins once a long window is known.

Verification

  • RED-first: reverting only src/codex/quota.ts and src/codex/routing.ts fails 6 tests, including the new short-only guard.
  • bun test --isolate tests — 13,538 pass, 0 fail, 10 skip (855 files).
  • bun test --isolate tests/codex-routing.test.ts tests/codex-auth-api.test.ts — 319 pass, 0 fail.
  • bun run typecheck — clean.
  • bun run privacy:scan — passed.

Supersedes

Closes #2056 (@Ingwannu) and #2062 (@yzxcj797) once merged, both with attribution. #2063 (@yzxcj797) was already superseded by the merged #2055 and is closed.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed. (Restores quota data that was already specified to flow end to end.)
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults. (Touches quota values and account-selection scoring, not credentials. No quota value or account id is logged. Privacy scan green.)

Closes #2047

Summary by CodeRabbit

  • Bug Fixes
    • Improved quota tracking for short-term burst windows alongside weekly and monthly limits.
    • Preserved burst usage percentages, reset times, and window durations when quota information is updated partially.
    • Corrected usage scoring so short-window-only data remains unknown until sufficient longer-term usage data is available.
    • Ensured zero-usage short-term quotas are recognized and retained across account refreshes.

parseUsageQuota filled shortPercent and setAccountQuotaFromParsed dropped it, so
the 5-hour burst window never reached the cache, the accounts DTO, the dashboard,
or routing. A saturated short window was invisible to account selection.

Carries @Ingwannu's #2056: shortPercent joins hasKnownQuotaValue, a new
snapshotHasShort keeps a short-only snapshot from reading as empty, partial
weekly/monthly snapshots no longer clobber a known short window, and
updateAccountQuota carries the tuple.

Also fixes the blocker raised in review on both #2056 and #2062: the scorer took
Math.max over every finite window, so a snapshot carrying only shortPercent: 0
scored a flat 0 and made an account whose long windows were never observed look
like the emptiest in the pool - pickLowestUsageAmong would then send every
request to it. The burst window now refines a known long-window position instead
of standing in for one, and returns CODEX_UNKNOWN_USAGE_SCORE until a governing
window is actually observed.

The ported test asserted the old behavior directly
(computeCodexUsageScore({ shortPercent: 0 }) === 0); it is replaced by a case
that pins the corrected contract in both directions.

Closes #2047
@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner August 19, 2026 18:39
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@github-actions

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@coderabbitai

coderabbitai Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 9e3ab279-6fd2-4eec-95b0-93cd51b4bf33

📥 Commits

Reviewing files that changed from the base of the PR and between cd8f9b8 and 9b0c5a0.

📒 Files selected for processing (4)
  • src/codex/quota.ts
  • src/codex/routing.ts
  • tests/codex-auth-api.test.ts
  • tests/codex-routing.test.ts

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


📝 Walkthrough

Walkthrough

Quota handling now retains sub-day burst-window fields during detection, cache merges, credits-only updates, and incremental updates. Routing incorporates short-window usage only when weekly or monthly usage is known. Tests cover persistence, DTO projection, parsing, and plan-specific scoring.

Changes

Short-window quota handling

Layer / File(s) Summary
Quota detection and preservation
src/codex/quota.ts
Quota detection recognizes short-window usage. Partial, credits-only, non-monthly, and incremental updates preserve shortPercent, shortResetAt, and shortWindowSeconds, including existing monthly data.
Short-window routing score
src/codex/routing.ts
computeCodexUsageScore requires finite weekly or monthly usage. It uses shortPercent to refine known scores and keeps short-only snapshots unknown.
Persistence and scoring regressions
tests/codex-auth-api.test.ts, tests/codex-routing.test.ts
Tests cover quota-field preservation, K12 WHAM-to-cache-to-DTO projection, short-only snapshots, zero-valued short usage, and Go-plan scoring.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Merge Risk: ⚪ Minimal · up to 9b0c5

The quota propagation and routing behavior is supported by passing tests and type checks, and no actionable merge-blocking risk remains.

Sequence Diagram(s)

sequenceDiagram
  participant WHAM
  participant parseUsageQuota
  participant QuotaCache
  participant AccountDTO
  participant computeCodexUsageScore
  WHAM->>parseUsageQuota: quota windows
  parseUsageQuota->>QuotaCache: weekly, monthly, and short-window fields
  QuotaCache->>AccountDTO: retained quota fields
  QuotaCache->>computeCodexUsageScore: known long-window and short-window usage
  computeCodexUsageScore-->>QuotaCache: usage score
Loading

Possibly related PRs

Suggested reviewers: ingwannu, luvs01

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the Codex fix and the retained K12 short-window quota, which matches the primary change.
Linked Issues check ✅ Passed The changes preserve short-window quota data through quota handling and serialization, update routing behavior, and add regression tests for issues [#2056] and [#2047].
Out of Scope Changes check ✅ Passed The changes are limited to quota preservation, routing behavior, and related regression tests described by the linked issues.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/absorb-k12-short-window

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.

@lidge-jun

Copy link
Copy Markdown
Owner Author

리뷰 · 우선순위 62 / 80

#2047 맞음. parseUsageQuotashortPercent를 채우는데(quota.ts:517) setAccountQuotaFromParsed가 안 복사함. snapshotHasUsage가 weekly/monthly만 봄. 5시간 버스트가 캐시/DTO/대시보드/라우팅에 안 감. computeCodexUsageScore도 short를 안 받음.

#2056을 가져오면서 리뷰가 막았던 함정을 고침. Math.max에 short만 넣으면 shortPercent: 0이 점수 0이 됨. 주/월을 한 번도 못 본 계정이 풀에서 제일 비어 보여서 전부 그리로 감. 지금은 긴 창이 없을 때 CODEX_UNKNOWN_USAGE_SCORE로 남김. 버스트는 긴 창 위치를 다듬을 뿐임. 예전 테스트가 shortPercent: 0 → 0을 단언하던 걸 새 계약으로 바꿈. 조용히 안 지움.

#2056이랑 #2062를 이걸로 닫으면 됨. #2063은 이미 #2055에 먹힘. #2046 detail.code 오분류는 다른 줄임. 이 PR이 그걸 안 닫음. types.ts/config.ts 안 건드림. 분할에 깔림 없음.

점수는 62임. 풀 픽이 가짜 0으로 쏠리면 실사용임. 2.27 필수까지는 아님. #2137보다 뒤.

해결방안: 머지. Closes #2047 유지. #2056 #2062 attribution 달고 닫기. #2046은 열어 둘 것.

이 댓글은 grok-bot이 작성했습니다

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant