Skip to content

bug(SUB-003): auto-switch ping-pongs between rate-limited subscriptions due to clear_rate_limit_events destroying detection signal #444

Closed

Description

@vybe

Summary

When multiple Claude Max subscriptions are simultaneously exhausted (e.g. during a weekly usage-limit window), the SUB-003 auto-switch service repeatedly re-assigns agents between two already-exhausted subscriptions every ~15–60 minutes instead of detecting that no viable alternative exists. Each cycle causes: 2× failed scheduled executions with 429, a DB write, and a full container restart. Over ~90 minutes this was observed to cause 8+ switches across 4 agents, all looping between subscriptions that each report the same weekly reset time. The bug is a logic defect where the detection signal is wiped on every switch, so the "is this subscription rate-limited?" check always returns False on the next cycle.

Component

Backend / Subscription Auto-Switch (SUB-003) — services/subscription_auto_switch.py + db/subscriptions.py

Priority

P1 — major feature broken (auto-switch actively worsens behavior when all subs are exhausted). Workaround exists: disable the auto_switch_subscriptions system setting.

Observed behavior

Sample timeline for one agent over ~75 minutes (all three subscriptions report resets <date>, 3pm (America/New_York) — i.e. truly out of quota):

Time Action Sub before → after
T+0 auto-switch sub-A → sub-B
T+29m auto-switch sub-B → sub-A
T+50m auto-switch sub-A → sub-B
T+74m auto-switch sub-B → sub-A

After 10+ 429 errors and 8+ switches, subscription_rate_limit_events contains zero rows in the last 2-hour window — events are deleted faster than the window can hold them.

Error

Underlying 429 body (from Anthropic, faithfully surfaced by agent):

Subscription usage limit: You've hit your limit · resets <date>, 3pm (America/New_York).
To resolve: (1) wait for the usage reset, (2) set an ANTHROPIC_API_KEY on this agent
for pay-per-use billing, or (3) assign a different subscription token in
Settings → Subscriptions.

Backend INFO log pattern (repeats):

[SUB-003] Rate-limit event #1 for agent '<name>' on subscription <id> — waiting for 2+ before auto-switch
[SUB-003] Auto-switching agent '<name>' from '<sub-A>' to '<sub-B>' after 2 consecutive rate-limit errors
[SUB-003] Auto-switch complete: {'switched': True, 'agent_name': '<name>', 'old_subscription': '<sub-A>', 'new_subscription': '<sub-B>', 'consecutive_errors': 2, 'restart_result': 'success'}

Location

Bug 1 — event signal destroyed on switch:

  • File: src/backend/services/subscription_auto_switch.py
  • Function: _perform_auto_switch()
  • Offending line:
    # Clear rate-limit events for the old subscription on this agent
    db.clear_rate_limit_events(agent_name, old_subscription_id)

Bug 2 — viability check relies on (now-empty) table:

  • File: src/backend/db/subscriptions.py
  • Function: select_best_alternative_subscription() uses is_subscription_rate_limited() which only asks "any events for this sub in last 2h?" — returns False after Bug 1 deleted them.

Root Cause

Interaction between two functions:

  1. _perform_auto_switch calls db.clear_rate_limit_events(agent_name, old_subscription_id) after every successful switch, deleting the records that prove the old subscription is rate-limited.
  2. select_best_alternative_subscription iterates candidates and skips any where is_subscription_rate_limited(sub_id) returns True — but that function counts rows in subscription_rate_limit_events over a 2h window. Because Bug 1 just emptied those rows, the newly-drained subscription looks viable again on the next cycle.

Net effect: the service is stuck switching between N exhausted subscriptions in round-robin, because no subscription ever accumulates enough evidence to be marked unavailable.

Secondary design concern

Even if Bug 1 is fixed, the 2-hour sticky window in is_subscription_rate_limited is far too short for Claude Max usage limits, which reset weekly (the 429 body reports a reset time often 1–2 days out). After 2h, events age out via cleanup_old_rate_limit_events and the ping-pong can resume.

Reproduction Steps

  1. Enable the auto_switch_subscriptions system setting.
  2. Have at least 2 Claude Max subscriptions assigned to agents on the platform, both at or near their usage-limit ceiling.
  3. Drive scheduled executions through both until both return 429 with a multi-day reset time.
  4. Observe backend logs for ~30–90 minutes — agents ping-pong between the two subscriptions, each switch preceded by exactly 2 fresh 429s.
  5. Query subscription_rate_limit_events at any time: the table will be empty or near-empty despite continuous 429s.

Suggested Fix

Minimum viable patch (stops the ping-pong)

Remove the clear_rate_limit_events call from _perform_auto_switch. Let events age out naturally via the existing 2h detection window and 24h cleanup job. Do not destroy the signal.

# src/backend/services/subscription_auto_switch.py :: _perform_auto_switch
# REMOVE:
db.clear_rate_limit_events(agent_name, old_subscription_id)

This alone stops the immediate thrashing — after a switch, the old subscription retains its 2+ events and is_subscription_rate_limited correctly returns True for the next 2 hours.

Proper fix

  1. Parse the reset time from the 429 body (Anthropic returns it in the message; optionally honor retry-after header if present) and store rate_limited_until on the subscription record.
  2. is_subscription_rate_limited(sub_id) → return now() < sub.rate_limited_until.
  3. Keep subscription_rate_limit_events solely for per-agent consecutive-error counting (the "2+ before switch" trigger), not for deciding WHICH subscription is viable.
  4. On a successful (non-429) execution, clear the per-agent consecutive counter and reset rate_limited_until to NULL.
  5. When select_best_alternative_subscription returns None (all exhausted), mark the current subscription's rate_limited_until and emit a single "all subscriptions exhausted — manual intervention required" notification, instead of silently continuing to attempt a switch on every cron tick.

Test coverage to add

  • Unit test: after an auto-switch, the old subscription is still reported as rate-limited by is_subscription_rate_limited for the remainder of the window.
  • Integration test: given two exhausted subscriptions, the service performs at most ONE switch attempt, then emits the "no viable alternative" warning on subsequent 429s — not another switch.

Environment

  • Trinity version: 588c8fd (main @ 2026-04-21)
  • Affected since: SUB-003 introduction (subscription auto-switch feature)

Related

  • src/backend/services/subscription_auto_switch.py
  • src/backend/db/subscriptions.py (record_rate_limit_event, is_subscription_rate_limited, clear_rate_limit_events, select_best_alternative_subscription)
  • subscription_rate_limit_events table schema
  • system_settings.auto_switch_subscriptions toggle

Metadata

Metadata

Assignees

No one assigned

    Labels

    complexity-lowpriority-p1type-bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions