Skip to content

fix(rate-limits): ignore stale Claude statusline snapshots from idle sessions - #23421

Closed
gabba6 wants to merge 2 commits into
stablyai:mainfrom
gabba6:fix/stale-live-claude-usage
Closed

gabba6 wants to merge 2 commits into
stablyai:mainfrom
gabba6:fix/stale-live-claude-usage

Conversation

@gabba6

@gabba6 gabba6 commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Every Claude Code session tells Orca how much of the usage limit is used. A session that has been idle for a while still reports its old number. Orca took that old number as the newest one, so the usage bar jumped backwards (e.g. 99% → 91% → 100%) and stayed wrong. Usage inside one limit window can only go up, so Orca now ignores a report that is lower than what it already has for the same window.

What Changed

  • Before: ingestLiveClaudeRateLimits accepted every statusline post from any session of the selected account and stamped it updatedAt: now. An idle session re-posting an older snapshot overwrote a newer value from an active session. Because the stale post counted as a fresh live feed, it also skipped the OAuth poll that would have corrected it.
  • After: a live window is dropped when it belongs to the same window as the current one (reset within 5 minutes) but reports lower usage, or when it belongs to an earlier window. If both windows of a post are dropped, the state (and updatedAt) stays untouched, so the OAuth poll is not gated by stale data.
  • A new window (later reset) is always accepted, so the bar still drops to the new value after a reset, including early resets. If either side has no reset time, or the current window has already ended, behaviour is unchanged.

Why

The alternatives were to only take posts from the most recently active session (Orca does not know which session is "active" at post time) or to always prefer the OAuth value (the live feed exists to save the endpoint's tight budget). Using the monotonic property of a usage window needs no extra state and keeps both paths working.

Linked Issue

Fixes part 1 of #23414 (the "working" state is a separate problem and not touched here).

Visual Proof

N/A – no UI change; only which usage value reaches the existing bar. The scenario is covered by the new service test.

Testing

  • Added claude-usage-window.test.ts (same window lower/higher, earlier window, new window, unknown reset, ended window) and a service test in service-live-claude-usage.test.ts that reproduces the idle-session re-post and the following reset.

  • vitest run src/main/rate-limits/claude-usage-window.test.ts src/main/rate-limits/service-live-claude-usage.test.ts: 18 passed. pnpm tc:node passes. On macOS.

  • In src/main/rate-limits/, 4 tests in codex-fetcher-pty-settle.test.ts fail on my machine with and without this change (timer/PTY related, unrelated).

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Investigated, implemented and tested with Claude Code (Claude Opus 5.5).

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Security: no new data or requests. Cross-platform/SSH/mobile: logic only in the main-process rate-limit service, platform independent. Backwards compatible: posts without resets_at behave as before.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

🤖 Generated with Claude Code

…sessions

Every Claude session of the account forwards its own last rate_limits
snapshot. An idle session re-posting an older value for the same window
rolled the usage bar back (e.g. 99% -> 91%) and, being marked fresh,
also gated the OAuth poll. Usage inside one window only grows, so a
lower value for the same reset (or an earlier reset) is now dropped.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

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

✅ No new issues found.

Reviewed changes

  • Stale-window filter — adds isStaleClaudeUsageWindow, which drops a live window reporting lower usage for the same reset (within a 5-minute tolerance) or an earlier reset than the current one.
  • Ingest integration — ingestLiveClaudeRateLimits filters each window through the helper before applying; when both windows are dropped it returns before touching state or updatedAt, so a fully stale post no longer gates the OAuth poll.
  • Tests — new unit coverage for the helper plus a service test reproducing the idle-session re-post and the following reset.

ℹ️ A stale session can still refresh updatedAt when only one of its windows is stale

The early return fires only when both windows are dropped. A statusline payload usually carries both, and a stale session's weekly window can be equal to (not lower than) the current one — equality is not stale — so the post is applied with updatedAt: now and the OAuth poll is still deferred by MIN_REFETCH_MS. The displayed values stay correct because the stale session window is dropped, so this is a note rather than a request; just be aware the "stale data does not gate the poll" guarantee is conditional on both windows being lower.

Technical details
# Partial-drop still bumps updatedAt

## Affected sites
- `src/main/rate-limits/service/service-fetch-policy.ts:108-123` — `keepIfNewer` returns `null` only for the stale window; the other (non-stale) window keeps `freshSession`/`freshWeekly` truthy, so the `if (!freshSession && !freshWeekly) return` guard does not fire.
- `src/main/rate-limits/service/service-fetch-policy.ts:127-135` — the dedupe only suppresses the update while within `LIVE_CLAUDE_INGEST_DEDUPE_MS` (30s); past that the update runs and `updatedAt` becomes `now`.

## Required outcome
None — the applied values are still correct (`session`/`weekly` fall back to `previous` for the dropped side). Recorded for context on the gating guarantee.

## Open questions for the human
- Is deferring the OAuth poll on a stale-but-partially-non-stale post acceptable, or should a post whose *effective* windows are identical to the current state skip the `updatedAt` bump entirely?

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: a2fc38b6-253c-4bfa-95d7-5c5cffb65ec8

📥 Commits

Reviewing files that changed from the base of the PR and between 4fcdd26 and 2c8d073.

📒 Files selected for processing (3)
  • src/main/rate-limits/claude-usage-window.ts
  • src/main/rate-limits/service-live-claude-usage.test.ts
  • src/main/rate-limits/service/service-fetch-policy.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/rate-limits/service-live-claude-usage.test.ts
  • src/main/rate-limits/service/service-fetch-policy.ts

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


📝 Walkthrough

Walkthrough

Adds isStaleClaudeUsageWindow to compare incoming and stored Claude usage windows. Live ingestion filters session and weekly windows through this helper and skips updates when neither window survives. Tests cover reset-time and usage comparisons, and confirm that a lower usage value is accepted when the reset time advances.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 2c8d0

The stale-window filtering matches the intended behavior for comparable active windows, and no identified change blocks merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 2c8d0

The change appears to limit stale usage updates without expanding who can submit them. No material security issue was established, but some ingestion and concurrency behavior remains unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The observed effect is confined to the selected account’s Claude usage snapshot and the fetch cadence derived from its freshness; the supplied impact map identifies no changed dependency edge.

Trust Boundaries and Controls

  • observed — Configuration-directory matching is the visible account-attribution control before live data reaches the snapshot. The changed helper neither authenticates the event nor grants it another state sink.

Resilience and Maintainability Implications

  • observed — Rejecting a stale-only post preserves the prior timestamp, allowing the normal freshness gate to expire rather than treating that post as a fresh live update.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: ignoring stale Claude statusline snapshots from idle sessions.
Description check ✅ Passed The description is complete and aligned with the template. It explains the user impact, implementation, rationale, linked issue, testing, AI use, compatibility considerations, and the lack of visual c…
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.
  • Fix all pre-merge checks with AI

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: b32658c2-b8fb-471d-b37d-800698f3c5a7

📥 Commits

Reviewing files that changed from the base of the PR and between 27b823f and 4fcdd26.

📒 Files selected for processing (4)
  • src/main/rate-limits/claude-usage-window.test.ts
  • src/main/rate-limits/claude-usage-window.ts
  • src/main/rate-limits/service-live-claude-usage.test.ts
  • src/main/rate-limits/service/service-fetch-policy.ts

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

A stale post whose other window only repeats the current value is no
progress and no longer bumps updatedAt, so it cannot defer the OAuth
poll. Same-window tolerance narrowed to 60s.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@gabba6

gabba6 commented Sep 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews. Addressed in the latest commit:

  • Partial stale post refreshing updatedAt: when a window of a post is dropped as stale and the other one only repeats the current value, the post is now ignored completely, so it no longer bumps updatedAt or defers the OAuth poll. New service test covers exactly this case. I kept the existing 30s dedupe for normal, non-stale posts on purpose, so an active session with unchanged usage still keeps the live feed fresh as before (the suggested diff would have changed that behaviour too).
  • Near-tolerance reset: narrowed the same-window tolerance from 5 minutes to 60 seconds. Statusline (whole seconds) and OAuth (sub-second) reset times for the same window differ by less than a second, while distinct windows are hours apart.

Targeted tests (claude-usage-window, service-live-claude-usage, service-refresh-orchestration) and pnpm tc:node pass.

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

ℹ️ No critical issues — one behavior note inline.

Reviewed changes

  • Narrowed same-window tolerance — SAME_WINDOW_TOLERANCE_MS dropped from 5 minutes to 1 minute, tightening both the earlier-window and same-window usedPercent comparisons. The predicate only becomes more conservative, so no fresh post is newly dropped.
  • Partial-stale no-op — added a droppedStale early return in ingestLiveClaudeRateLimits so a post that drops one stale window while the other merely repeats the current state leaves updatedAt untouched (and no longer gates the OAuth poll).
  • Test — new service test covering a stale 5h value posted alongside a repeated weekly value.

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

Comment on lines +123 to +131
// Why: a stale post whose other window merely repeats the current value is no progress and must not refresh the live-feed age.
const droppedStale = (incomingSession && !freshSession) || (incomingWeekly && !freshWeekly)
if (
droppedStale &&
isSameUsageWindow(previous?.session ?? null, session) &&
isSameUsageWindow(previous?.weekly ?? null, weekly)
) {
return
}

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.

Returning here also skips the status: 'ok' / error: null flip and the activeFailureStreakByProvider.claude = 0 reset below, which is broader than the comment's stated "must not refresh the live-feed age". When previous is an applyStalePolicy-retained error state that still carries the same windows (service-result-policy.ts:55-65), a partially-stale post now leaves the provider flagged error until the next successful OAuth poll instead of clearing it — the guard has no previous.status === 'ok' / source === 'live-session' precondition. This may well be the intent, but it is untested; please confirm.

Technical details
# Early return suppresses error recovery, not just the age refresh

## Affected sites
- `src/main/rate-limits/service/service-fetch-policy.ts:123-131` — the new `droppedStale` guard returns before `activeFailureStreakByProvider.claude = 0` (line 141) and the `updateState({ ... claude: { status: 'ok', error: null } })` write (lines 142-162).
- `src/main/rate-limits/service/service-result-policy.ts:55-65` — `applyStalePolicy` can return `{ ...previous, error: fresh.error, status: 'error' }` while retaining `session`/`weekly`, so the guarded `previous` shape is reachable.

## Reachable shape
`previous = { status: 'error', session: { usedPercent: 99, resetsAt: R }, weekly: { usedPercent: 40, resetsAt: W }, updatedAt: >5min old }`; incoming `fiveHour: { 91, R }` (same window, lower → dropped) + `sevenDay: { 40, W }` (exact repeat). `droppedStale` true, both `isSameUsageWindow` checks true → return. Before this commit the post cleared the error and reset the failure streak.

## Required outcome
Confirm whether a stale, no-progress post should still clear an `error` state and reset the failure streak. If not, a one-line comment noting the intent is enough; if the goal is only to avoid bumping `updatedAt`, write the state with `updatedAt: previous.updatedAt` instead of returning.

adifsgaid added a commit to adifsgaid/orca that referenced this pull request Oct 12, 2026
An idle Claude session keeps reporting the usage of a window that has since
rolled over (the stale statusline snapshots stablyai#23421 describes), and an inactive
account's cached reading can outlive its window. The auto-switch policy counted
both as current, so a stale 96% could trigger a switch and an account whose
window had reset could be skipped as exhausted. A window past its reset time
no longer counts.
brennanb2025 added a commit that referenced this pull request Oct 23, 2026
…alue (#32249)

* fix(usage): ignore an idle Claude session's older usage for the same window

Claude Code re-sends each session's last-seen rate limits to the statusline,
dropping only windows whose reset has passed. An idle session days old keeps
posting the current weekly window at the value it saw back then, so the
weekly figure flipped between that stale value and the current one while the
5-hour figure held. Usage inside one window only grows, so a lower value for
the same reset (or an earlier reset) is dropped, and a post with nothing newer
leaves the snapshot and the OAuth poll timing untouched.

Fixes STA-10493 (#28418). Ports the rule from #23421.

Co-authored-by: Gabriel Petrovic <[email protected]>

* fix(usage): separate Claude display receipts from corrective checks

* fix(usage): honor Claude retry eligibility when selecting refreshes

* test: verify fresh usage checks after service recreation

---------

Co-authored-by: Gabriel Petrovic <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor

Thanks @gabba6 for the work here. Closing as superseded: your stale-snapshot rule was ported into #32249, so idle sessions no longer drag weekly usage back to an old value; thanks for the design and tests, credited as co-author. Appreciate the contribution, and feel free to open a fresh PR against current main if you see anything still missing.

@nwparker nwparker closed this Oct 24, 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.

2 participants