Skip to content

fix(status): add auto heal for rate-limit/ quota exceed status after reset in the ui - #529

Closed
huzky-v wants to merge 3 commits into
Soju06:mainfrom
huzky-v:fix/ui-status-auto-heal
Closed

huzky-v wants to merge 3 commits into
Soju06:mainfrom
huzky-v:fix/ui-status-auto-heal

Conversation

@huzky-v

@huzky-v huzky-v commented Apr 30, 2026 •

Copy link
Copy Markdown
Collaborator

Address #479

Probably fix the issue that the UI still show the stale status after the time resets
As currently the status update is more like lazy update, if there is no request to codex-lb or the account does not tide to any API, the status shown in UI will never be updated.
Not sure why the request does not get routed, but this would best effort reset the status, as a fallback, with the help of scheduler

This fix is to introduce the account status for those account status = rate-limit/ quota exceed in the scheduler

@huzky-v huzky-v changed the title fix(ui+status): add auto heal for rate-limit/ quota exceed status after reset fix(ui+status): add auto heal for rate-limit/ quota exceed status after reset in the ui Apr 30, 2026
@huzky-v huzky-v changed the title fix(ui+status): add auto heal for rate-limit/ quota exceed status after reset in the ui fix(status): add auto heal for rate-limit/ quota exceed status after reset in the ui Apr 30, 2026
@Soju06

Soju06 commented May 11, 2026

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3aa828fda5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread app/core/usage/refresh_scheduler.py Resolved
@Soju06

Soju06 commented May 11, 2026

Copy link
Copy Markdown
Owner

Thanks @huzky-v -- the design itself is clean: reusing _state_from_account from a synthetic runtime, gating writes through update_status_if_current, and complementing the in-process recovery in #559 (which only covers QUOTA_EXCEEDED from the usage path, while this PR covers both RATE_LIMITED and QUOTA_EXCEEDED and survives cross-process / cold-start stuck rows). The OpenSpec design.md is genuinely good.

I checked merge-tree against current main (post-#559) and there is no text or semantic conflict -- the two paths are complementary (sync vs periodic / single-process vs cross-process). So functionally we're good to land this once one P1 is addressed.

P1 -- AsyncSession concurrent use

Codex review caught this and it's correct:

# app/core/usage/refresh_scheduler.py:130
latest_primary, latest_secondary = await asyncio.gather(
    usage_repo.latest_by_account(window="primary"),
    usage_repo.latest_by_account(window="secondary"),
)

usage_repo here is bound to a single AsyncSession (created in the surrounding async with get_background_session() block earlier in _refresh_once). SQLAlchemy explicitly documents that AsyncSession is not safe for concurrent use across tasks -- it carries per-session state (current transaction, identity map, dialect-level cursors) that breaks when two coroutines fence it at the same time.

When this hits, the failure mode is one of two SQLAlchemy errors:

  • InvalidRequestError: This session is already in use (the friendly one)
  • StatementError with a MissingGreenlet or a closed-cursor message (the less friendly one)

Either way the surrounding try ... except Exception: in _refresh_once swallows it and the whole reconcile pass plus the usage refresh in the same cycle become a no-op. Worst case the scheduler loops at the configured interval with both responsibilities silently failing.

Suggested fix

Sequential calls are the simplest and match the SQLAlchemy contract:

latest_primary = await usage_repo.latest_by_account(window="primary")
latest_secondary = await usage_repo.latest_by_account(window="secondary")

The two queries don't share a critical section that benefits from parallelism (no cross-DB joins, no upstream calls in between), and latest_by_account is a small indexed read. Sequential is the right shape here.

If we ever do want parallelism on a future variant -- for example to also pull additional-quota windows in the same cycle -- the right pattern is per-task sessions:

async with get_background_session() as session_primary, get_background_session() as session_secondary:
    primary_repo = UsageRepository(session_primary)
    secondary_repo = UsageRepository(session_secondary)
    latest_primary, latest_secondary = await asyncio.gather(
        primary_repo.latest_by_account(window="primary"),
        secondary_repo.latest_by_account(window="secondary"),
    )

But that is overkill for two small reads -- the sequential pattern above is fine.

Tests to update

The existing test_usage_refresh_scheduler_recovery.py uses a stub StubUsageRepository so it doesn't exercise the real session. Two options:

  • add a focused unit test that constructs a real UsageRepository against an in-memory SQLite session and runs reconcile_recoverable_account_statuses against it. The point is to ensure the sequential pattern survives the SQLAlchemy contract, not to exercise the logic itself.
  • or add a small note to design.md explaining the sequential read choice so future contributors don't re-introduce the gather.

Whichever is easier on your side.

Not blocking otherwise

The rest of the PR is in good shape and the merge-tree against main is clean. Once you push the sequential read I'll re-run @codex review and we can land it. Thanks again for the fix -- the periodic-reconciliation safety net complements #559 well.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3aa828fda5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread app/core/usage/refresh_scheduler.py Resolved
@huzky-v

huzky-v commented May 11, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@huzky-v
huzky-v requested a review from Soju06 May 11, 2026 08:19
@Soju06

Soju06 commented May 12, 2026

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b958b79f6f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread app/modules/proxy/load_balancer.py Resolved
@Soju06

Soju06 commented May 12, 2026

Copy link
Copy Markdown
Owner

Thanks @huzky-v -- the AsyncSession P1 (asyncio.gather -> sequential awaits) is fixed and the re-review picked up a different P1 that needs to be addressed before merging. This one is more impactful because it can re-introduce the 429 it's trying to recover from.

P1 -- rate-limit cooldown is bypassed in recovery state

In app/modules/proxy/load_balancer.py:1169, background_recovery_state_from_account seeds runtime.cooldown_until with blocked_at:

runtime.cooldown_until = blocked_at  # in the past as soon as we evaluate it

This causes the RATE_LIMITED branch of _state_from_account to treat the cooldown as expired the moment we evaluate the account, because blocked_at is always in the past. The flow that breaks:

  1. Upstream rate-limits account; we set status = RATE_LIMITED, blocked_at = T, with a real retry delay (e.g., 30 minutes).
  2. Some unrelated usage refresh writes a primary row at T + 5min while the account is still genuinely cooling down.
  3. Recovery path runs background_recovery_state_from_account, seeds cooldown_until = blocked_at = T (in the past).
  4. _state_from_account sees cooldown_until is expired, clears runtime_reset, flips the account back to ACTIVE.
  5. We immediately route to the account and re-trigger 429 (and now the cooldown shows the new blocked_at, looping the same logic 30 minutes early every cycle).

The intent of the recovery scheduler is the opposite -- only flip an account back to ACTIVE after the real reset has elapsed. Seeding with blocked_at reads more like a typo for the actual reset time.

Suggested fix

Seed cooldown_until with the real cooldown deadline, not the moment the block started:

# app/modules/proxy/load_balancer.py:~1169
runtime.cooldown_until = (
    account.rate_limit_reset_at      # if a hard reset timestamp is known
    or (account.blocked_at + retry_delay)  # else derive from blocked_at + delay
)

(Exact field names depend on what Account/recovery state actually exposes -- the point is to use the reset deadline, not the block start.)

If the recovery state has no notion of "how long the cooldown is" because that info lives elsewhere, then the recovery path should not clear runtime_reset in this branch at all -- let the original RATE_LIMITED state's cooldown gate make the active/blocked decision.

Tests to add

def test_recovery_state_preserves_rate_limit_cooldown_when_block_recent():
    account = _make_account(
        status=AccountStatus.RATE_LIMITED,
        blocked_at=now - timedelta(minutes=5),
        rate_limit_reset_at=now + timedelta(minutes=25),
    )
    state = background_recovery_state_from_account(account)
    runtime = _state_from_account(account, state)
    assert runtime.status == AccountStatus.RATE_LIMITED  # not ACTIVE
    assert runtime.cooldown_until > now

def test_recovery_state_recovers_account_after_cooldown_elapsed():
    account = _make_account(
        status=AccountStatus.RATE_LIMITED,
        blocked_at=now - timedelta(hours=2),
        rate_limit_reset_at=now - timedelta(minutes=5),  # already past reset
    )
    state = background_recovery_state_from_account(account)
    runtime = _state_from_account(account, state)
    assert runtime.status == AccountStatus.ACTIVE

Not blocking otherwise

  • The asyncio.gather -> sequential await change for latest_by_account is correct (one shared AsyncSession per scheduler tick).
  • The UI side of the auto-heal is fine; the issue is in the gating before we display "recovered".

Once this is fixed I'll re-run @codex review and queue for merge.

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create an environment for this repo.

@huzky-v

huzky-v commented May 12, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@huzky-v
huzky-v marked this pull request as draft May 12, 2026 06:53
@huzky-v
huzky-v force-pushed the fix/ui-status-auto-heal branch from 6efd07d to 19fff75 Compare May 12, 2026 07:27
@huzky-v
huzky-v marked this pull request as ready for review May 12, 2026 07:43
@huzky-v

huzky-v commented May 12, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@huzky-v
huzky-v force-pushed the fix/ui-status-auto-heal branch 2 times, most recently from c40cac3 to 7608bf8 Compare May 14, 2026 07:00
@huzky-v

huzky-v commented May 15, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@huzky-v
huzky-v requested review from Soju06 and removed request for Soju06 May 15, 2026 11:20
@Komzpa Komzpa added the 🤖 codex: ok [@codex review] says no issues found. label May 16, 2026
@Soju06

Soju06 commented May 19, 2026

Copy link
Copy Markdown
Owner

Current-main smoke failure before merge

Live PR gates are green (codex: ok, 18/18 CI, CLEAN/MERGEABLE), but the PR no longer passes a focused no-commit merge smoke against the current origin/main.

Repro I ran:

git fetch origin main pull/529/head:refs/remotes/origin/pr-529 --prune
git worktree add --detach .worktree/review-pr-529 refs/remotes/origin/pr-529
cd .worktree/review-pr-529
git merge --no-commit --no-ff origin/main

uv run --locked openspec validate reconcile-background-account-status --strict
uv run --locked ruff check \
  app/core/usage/refresh_scheduler.py \
  app/modules/proxy/load_balancer.py \
  tests/integration/test_accounts_api_extended.py \
  tests/unit/test_load_balancer.py \
  tests/unit/test_request_locality.py \
  tests/unit/test_usage_refresh_scheduler_recovery.py
uv run --locked ty check \
  app/core/usage/refresh_scheduler.py \
  app/modules/proxy/load_balancer.py \
  tests/integration/test_accounts_api_extended.py \
  tests/unit/test_load_balancer.py \
  tests/unit/test_request_locality.py \
  tests/unit/test_usage_refresh_scheduler_recovery.py
uv run --locked pytest -q -ra \
  tests/integration/test_accounts_api_extended.py \
  tests/unit/test_load_balancer.py \
  tests/unit/test_request_locality.py \
  tests/unit/test_usage_refresh_scheduler_recovery.py \
  --durations=20

OpenSpec / ruff / ty pass, but pytest fails:

FAILED tests/integration/test_accounts_api_extended.py::test_accounts_list_stale_rate_limited_status_recovers_after_background_reconcile

assert stale_account["status"] == "rate_limited"
E AssertionError: assert 'active' == 'rate_limited'
E   - rate_limited
E   + active

This looks like drift against current main: /api/accounts now returns the effective status as active for this expired/stale rate_limited account, while the PR test still expects the stale persisted rate_limited state before background reconciliation.

Could you rebase/merge current main and update the PR to align the behavior/test with the current /api/accounts effective-status semantics? After that, the focused pytest command above should pass on the merged tree.

@huzky-v
huzky-v force-pushed the fix/ui-status-auto-heal branch from 7608bf8 to f09b655 Compare May 19, 2026 05:13
@Komzpa Komzpa removed the 🤖 codex: ok [@codex review] says no issues found. label May 19, 2026
@Komzpa

Komzpa commented May 19, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b7fd132fcd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1197 to +1198
account.status == AccountStatus.RATE_LIMITED
and blocked_at is not None

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 Badge Require freshness when recovering markerless rate limits

When a persisted rate_limited row has no blocked_at marker, this guard is skipped entirely, so _state_from_account() can return ACTIVE solely because reset_at is in the past and the latest primary row is below 100%, even if that row predates the rate-limit event or the background refresh just failed. This makes the new scheduler reconciliation clear legacy/markerless rate-limit rows without the fresh post-block usage proof required by the recovery path, potentially re-enabling an account before a successful usage refresh confirms recovery.

Useful? React with 👍 / 👎.

@Komzpa Komzpa added the 🤖 codex: needs work [@codex review] raised an issue label May 19, 2026
@huzky-v

huzky-v commented May 20, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@huzky-v
huzky-v force-pushed the fix/ui-status-auto-heal branch from f46b0d6 to 7535ad1 Compare May 20, 2026 09:20
@Komzpa Komzpa removed the 🤖 codex: needs work [@codex review] raised an issue label May 20, 2026
@Komzpa

Komzpa commented May 20, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7535ad11e1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1197 to +1202
account.status == AccountStatus.RATE_LIMITED
and blocked_at is not None
and reset_at is not None
and reset_at <= time.time()
and not _usage_entry_recorded_after_block(primary_entry, blocked_at)
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Require post-block secondary evidence before quota recovery

The background recovery path only enforces a post-block freshness check for RATE_LIMITED accounts; QUOTA_EXCEEDED accounts can still be returned as ACTIVE by _state_from_account when reset_at has elapsed even if the latest secondary usage row predates blocked_at. Because this commit now persists that recovery in reconcile_recoverable_account_statuses, a stale pre-block secondary snapshot can incorrectly reactivate an account and send traffic to an actually exhausted quota window.

Useful? React with 👍 / 👎.

Comment on lines +147 to +148
if account.status in (AccountStatus.RATE_LIMITED, AccountStatus.QUOTA_EXCEEDED) and status == AccountStatus.ACTIVE:
return account.status

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 Badge Avoid hard-coupling UI status recovery to refresh scheduler

This override prevents the API mapper from ever showing ACTIVE for persisted rate_limited/quota_exceeded rows, even when apply_usage_quota computes recovery from usage data. If background refresh is disabled or not running (it is gated by usage_refresh_enabled and leader acquisition), statuses remain permanently stale in /api/accounts, which is a functional regression from the previous on-read recovery behavior.

Useful? React with 👍 / 👎.

@Soju06 Soju06 added the 🤖 codex: needs work [@codex review] raised an issue label May 21, 2026
@Soju06

Soju06 commented May 21, 2026

Copy link
Copy Markdown
Owner

Maintainer cleanup: closing this as stale / no longer merge-ready against the current main.

This PR has been open across substantial main-branch churn and is currently carrying at least one stale signal (conflicts/blocked or failing checks, outstanding codex: needs work, draft/old branch state, or overlap with newer/current implementation). Keeping it open is making the PR queue harder to reason about.

If the change is still needed, please open a fresh, focused PR rebased on current main with green CI and a clean Codex review.

@Soju06 Soju06 closed this May 21, 2026
@huzky-v
huzky-v deleted the fix/ui-status-auto-heal branch May 21, 2026 07:19
@Komzpa Komzpa added the stale No response from reporter; scheduled for close label May 21, 2026
@Komzpa

Komzpa commented May 21, 2026

Copy link
Copy Markdown
Collaborator

Revived on a maintainer-owned branch as #754 because this PR head has maintainerCanModify=false and cannot be updated here. Keeping credit to the original implementation in the replacement PR.

@Komzpa Komzpa added superseded Replaced by another PR, issue track, or merged implementation and removed 🤖 codex: needs work [@codex review] raised an issue labels May 21, 2026
@Soju06 Soju06 added the 🤖 codex: needs work [@codex review] raised an issue label May 21, 2026
@Komzpa Komzpa removed the 🤖 codex: needs work [@codex review] raised an issue label May 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale No response from reporter; scheduled for close superseded Replaced by another PR, issue track, or merged implementation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants