Repository navigation
Description
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()usesis_subscription_rate_limited()which only asks "any events for this sub in last 2h?" — returnsFalseafter Bug 1 deleted them.
Root Cause
Interaction between two functions:
_perform_auto_switchcallsdb.clear_rate_limit_events(agent_name, old_subscription_id)after every successful switch, deleting the records that prove the old subscription is rate-limited.select_best_alternative_subscriptioniterates candidates and skips any whereis_subscription_rate_limited(sub_id)returnsTrue— but that function counts rows insubscription_rate_limit_eventsover 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
- Enable the
auto_switch_subscriptionssystem setting. - Have at least 2 Claude Max subscriptions assigned to agents on the platform, both at or near their usage-limit ceiling.
- Drive scheduled executions through both until both return 429 with a multi-day reset time.
- Observe backend logs for ~30–90 minutes — agents ping-pong between the two subscriptions, each switch preceded by exactly 2 fresh 429s.
- Query
subscription_rate_limit_eventsat 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
- Parse the reset time from the 429 body (Anthropic returns it in the message; optionally honor
retry-afterheader if present) and storerate_limited_untilon the subscription record. is_subscription_rate_limited(sub_id)→return now() < sub.rate_limited_until.- Keep
subscription_rate_limit_eventssolely for per-agent consecutive-error counting (the "2+ before switch" trigger), not for deciding WHICH subscription is viable. - On a successful (non-429) execution, clear the per-agent consecutive counter and reset
rate_limited_untiltoNULL. - When
select_best_alternative_subscriptionreturnsNone(all exhausted), mark the current subscription'srate_limited_untiland 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_limitedfor 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.pysrc/backend/db/subscriptions.py(record_rate_limit_event,is_subscription_rate_limited,clear_rate_limit_events,select_best_alternative_subscription)subscription_rate_limit_eventstable schemasystem_settings.auto_switch_subscriptionstoggle
Activity
fix(SUB-003): stop ping-pong between exhausted subscriptions (#444) (#…
feat(subscription): auto-switch on first failure + auth-class triggers (
Release: v0.5.0 (#608)
fix(subscriptions): a rejected token is not a rate limit (#2354)
chore(enterprise): bump submodule pin to 2a5def35 — rooms removed fro…
feat(subscriptions): a recovered subscription stops claiming it is ra…
fix(subscriptions): auto-switch ranks alternatives by cached headroom…
fix(subscriptions): readmission orders the reading against the failur…
fix(subscriptions): a rate-limited turn completes on another subscrip…
Release: v0.9.5 (#2872)