Skip to content

Handle provider subscription rate-limit retries - #1027

Merged
ymichael merged 32 commits into
mainfrom
bb/handle-provider-rate-limit-retries-thr_nhfaj9pyvu
Aug 7, 2026
Merged

ymichael merged 32 commits into
mainfrom
bb/handle-provider-rate-limit-retries-thr_nhfaj9pyvu

Conversation

@ymichael

@ymichael ymichael commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • normalize Codex and Claude subscription rate-limit telemetry into a shared provider state
  • add guarded, at-most-once continuation on the same provider conversation using agent-only Please continue.
  • add the opt-in builtin provider-retry plugin with in-memory scheduling, account coordination, UI, SDK, and CLI controls
  • enable it explicitly through Extensions → Plugins or bb plugin enable provider-retry
  • allow plugins to be enabled or disabled directly from their settings detail page
  • intentionally exclude retry persistence across server or daemon restarts

Safety

  • continuation is allowed only for the latest terminal failed turn with no emitted output or possible side effect
  • provider-owned retries remain authoritative while active
  • reset changes, host disconnects, cancellation races, and realtime reconnection are handled explicitly
  • credits and spend controls remain manual-retry cases

Validation

  • 13 affected Turbo typecheck tasks pass
  • app: 2,354 tests pass
  • server: 1,330 tests pass
  • agent runtime: 802 tests pass
  • provider-retry plugin: 10 tests pass
  • host-daemon contract: 49 tests pass
  • CLI, SDK, plugin SDK, server contract, templates, and domain suites pass
  • standalone provider-retry plugin build passes

@ymichael
ymichael force-pushed the bb/handle-provider-rate-limit-retries-thr_nhfaj9pyvu branch 2 times, most recently from 8842902 to 0436b99 Compare August 5, 2026 22:46
ymichael added a commit that referenced this pull request Aug 5, 2026
## Summary

- give the structured workflow harness test a test-local 30-second
timeout
- keep the 15-second default timeout for the rest of the workflows suite

## Why

The packages check on #1027 timed this test out after 15.815 seconds.
The same test took 8.065 seconds and 10.852 seconds in the two preceding
successful runs, while it takes about 0.9 seconds locally. The test runs
several complete workflow lifecycles and validates multi-megabyte
payloads, so its runtime is unusually sensitive to shared-runner
contention.

## Testing

- pnpm exec turbo run test --filter=bb-plugin-workflows --force (5
consecutive runs)
- pnpm exec turbo run typecheck --filter=bb-plugin-workflows
@ymichael
ymichael marked this pull request as ready for review August 5, 2026 23:34
@ymichael
ymichael force-pushed the bb/handle-provider-rate-limit-retries-thr_nhfaj9pyvu branch 3 times, most recently from 6c1b96e to 7f29243 Compare August 7, 2026 17:59
@ymichael
ymichael force-pushed the bb/handle-provider-rate-limit-retries-thr_nhfaj9pyvu branch from 866542d to eb2a10d Compare August 7, 2026 19:32
@ymichael
ymichael merged commit 5a96873 into main Aug 7, 2026
10 checks passed
@ymichael
ymichael deleted the bb/handle-provider-rate-limit-retries-thr_nhfaj9pyvu branch August 7, 2026 20:44
ymichael added a commit that referenced this pull request Aug 12, 2026
## Motivation

The four provider adapters (claude-code, codex, pi, acp) and three
bridges carry near-verbatim copies of the same machinery: stdio harness,
session registry, adapter identity/command/translation boilerplate, turn
lifecycle, item-id scoping, and tool item translation. That duplication
has a measurable history of making cross-provider work slow and lossy:

- **Manual compaction (#1152)** landed through 19 commits, more than 11
of them iterating the same feature provider-by-provider ("Make OpenCode
ACP compaction reliable", "Avoid false Pi compaction success", "Show ACP
compaction lifecycle", "Fix compaction lifecycle races", ...). One
feature, re-fought per adapter.
- **Rate-limit normalization (#1027)** only ever shipped to 2 of 4
providers. On main today, `ProviderRateLimitState` is referenced by
claude-code and codex translation only — Pi and ACP have zero
references. Duplication didn't just slow the change down; it silently
dropped half the matrix.
- **`classifyExecutionSettingsChange` (#1236)** had to touch all four
adapters to change one provider's behavior, because the member wiring is
copied everywhere.

After this PR, the shared machinery lives in
`packages/agent-runtime/src/shared/` and a cross-provider change of this
kind is a one-place change.

## Honest accounting

Repo-wide this is roughly **−300 lines net** (2,204 insertions, 2,512
deletions, all inside `packages/agent-runtime`). The ~1,640-line figure
from the de-slop audit counts *duplicated* lines, not deletable ones —
extracting a shared implementation still costs its one copy plus
parameterization. The value of this PR is **one-place-change for
cross-provider behavior**, not raw deletion.

## Commit-by-commit review guide

The 8 commits are logically staged; each is independently revertable and
behavior-preserving:

1. **`fff1c494c` share bridge stdio harness** — the three bridges'
identical stdin/stdout JSON-RPC loop (readline wiring, dispatch, error
replies) moves to `shared/bridge-harness.ts`.
2. **`e1e7615ba` share bridge session registry** — the per-bridge
`Map`-of-sessions bookkeeping (create/get/stop/dispose) moves to
`shared/bridge-session-registry.ts`.
3. **`66fee1a30` share bridge environment helpers** — env-override
construction/parsing dedup in `shared/adapter-utils.ts` (round-trip
covered by a new test), plus `shared/mime-types.ts`.
4. **`6e6e9fbc1` share standard adapter members** — the biggest one.
Each adapter's copied identity/launch members, `initialize` plan,
unsupported-command fallbacks, accepted-command translation, model-list
parsing, and tool-call decoding collapse into
`createStandardAdapterMembers()` (`shared/standard-adapter-members.ts`);
adapters keep only their provider-specific `buildProviderCommandPlan`.
Review focus: confirm each adapter's per-command plans are unchanged
(they are moved, not edited).
5. **`4c6a3c65b` centralize provider turn hooks** — per-adapter
`ensureXTurnStarted` wrappers and the copied error-envelope-to-events
helper become `onTurnStart`/`onTurnFinish` hooks and `buildErrorEvents`
on the shared turn-state registry; `shared/provider-error-events.ts` is
deleted.
6. **`276516e32` share scoped item id factories** — the copied
open/completed scoped-item-id resolution moves to
`shared/scoped-item-ids.ts`.
7. **`fbd671c2a` share tool item translation** — the copied
toolUse/toolResult item builders move to
`shared/tool-item-translation.ts`.
8. **`86a313d7b` remove dead exports and helpers** — deletes exports and
helpers made unreferenced by the extractions (verified by repo-wide
typecheck).

## Wire compatibility (server ↔ host daemon)

**No `HOST_DAEMON_PROTOCOL_VERSION` bump needed, and none is included.**
The diff is confined to `packages/agent-runtime`;
`packages/host-daemon-contract` (session payloads, WS messages, host RPC
commands/results) is untouched and the protocol version stays at 106 on
both sides. The refactor changes where adapter/bridge code lives, not
what crosses the wire: the 900+ adapter tests that assert exact
translated `ThreadEvent` output (ids, scopes, payloads) pass without any
expectation changes, so the event stream the daemon posts to the server
is byte-identical.

## Rebase provenance

This branch originated in archived thread `thr_jyia7bkdqn` and was
rebased onto current main (original authorship preserved in the
commits). The rebase crossed #1280 (sent-message editing) and #1321
(provider-unhandled-event fix), both of which touched the same adapters;
conflicts were resolved by preserving main's shipped behavior and
re-grafting it into the extracted structure:

- `thread/discard` command plans re-added per provider (acp: noop,
claude-code: `thread/stop`, pi: `thread/discard`) inside each
`buildProviderCommandPlan`.
- Claude Code's `latestProviderCheckpointId` reset moved into the shared
`onTurnStart` hook (fires only for newly opened turns, same guard as the
removed wrapper).
- `sourceProviderCheckpointId` forwarding re-added to the claude-code
and pi `thread/fork` plans.

The rebase delta vs the original branch inside `packages/agent-runtime`
is exactly the sum of #1280 + #1321 (+1,124/−36), i.e. nothing from main
was lost and nothing beyond the refactor was introduced.

## Verification

- `pnpm exec turbo run typecheck` — whole repo, 58/58 tasks pass.
- `pnpm exec turbo run test --filter=@bb/agent-runtime` — 907 passed, 1
failed: `runtime.process-lifecycle.test.ts > bounds provider stderr
while data arrives without a newline`, which fails identically on
unmodified origin/main (reproduced during this work; also documented as
pre-existing in #1321). The lifecycle suites
(`runtime.lifecycle.test.ts` 28/28, `runtime.process-lifecycle.test.ts`
21/21 excluding the pre-existing failure) covering the Codex recovery
paths pass.
- `pnpm exec turbo run test --filter=@bb/host-daemon` (the only
dependent of `@bb/agent-runtime`) — 541/541 pass.

> AGENT GENERATED: by Claude Fable 5

🤖 Generated with [Claude Code](https://claude.com/claude-code)
amadad pushed a commit to amadad/bb that referenced this pull request Aug 14, 2026
## Summary

- give the structured workflow harness test a test-local 30-second
timeout
- keep the 15-second default timeout for the rest of the workflows suite

## Why

The packages check on get-bb#1027 timed this test out after 15.815 seconds.
The same test took 8.065 seconds and 10.852 seconds in the two preceding
successful runs, while it takes about 0.9 seconds locally. The test runs
several complete workflow lifecycles and validates multi-megabyte
payloads, so its runtime is unusually sensitive to shared-runner
contention.

## Testing

- pnpm exec turbo run test --filter=bb-plugin-workflows --force (5
consecutive runs)
- pnpm exec turbo run typecheck --filter=bb-plugin-workflows
amadad pushed a commit to amadad/bb that referenced this pull request Aug 14, 2026
## Summary

- normalize Codex and Claude subscription rate-limit telemetry into a
shared provider state
- add guarded, at-most-once continuation on the same provider
conversation using agent-only `Please continue.`
- add the opt-in builtin provider-retry plugin with in-memory
scheduling, account coordination, UI, SDK, and CLI controls
- enable it explicitly through Extensions → Plugins or `bb plugin enable
provider-retry`
- allow plugins to be enabled or disabled directly from their settings
detail page
- intentionally exclude retry persistence across server or daemon
restarts

## Safety

- continuation is allowed only for the latest terminal failed turn with
no emitted output or possible side effect
- provider-owned retries remain authoritative while active
- reset changes, host disconnects, cancellation races, and realtime
reconnection are handled explicitly
- credits and spend controls remain manual-retry cases

## Validation

- 13 affected Turbo typecheck tasks pass
- app: 2,354 tests pass
- server: 1,330 tests pass
- agent runtime: 802 tests pass
- provider-retry plugin: 10 tests pass
- host-daemon contract: 49 tests pass
- CLI, SDK, plugin SDK, server contract, templates, and domain suites
pass
- standalone provider-retry plugin build passes
ymichael added a commit that referenced this pull request Oct 20, 2026
## Human comments

## What was wrong

Provider retry only scheduled retries for two kinds of failure:
structured overloads (529) and rate limits. Every other failure was
declined as `not-retryable`. When the Account Pooler, or the provider
itself, briefly cannot be reached, Claude Code records the failure as
`{category: "internal", httpStatusCode: 502}` and Codex records
`{category: "stream-disconnected", httpStatusCode: 502}`. Neither
matched, so the thread stayed in `error` until someone sent a new
message. The 429 half of #4839 was already fixed by #5283; this PR
covers the 502/503 half. Nothing in the history shows 5xx failures being
excluded on purpose: #1027 scoped the plugin to subscription limits, and
#2801 added only `overloaded`.

## What changed

- `plugins/provider-retry/src/retry-policy.ts`: a failure counts as
"provider unavailable" when its HTTP status is 500, 502, 503 or 504, or
its category is `internal`, `connection-failed` or
`stream-disconnected`. Such failures are retried for every thread,
pooled or not, with exponential backoff that starts at 1 minute: 1–2,
2–4, 4–8 and 8–16 minutes with jitter. They share the existing 5-attempt
cap, and the queue card shows "Provider unavailable". Overload timing is
unchanged; the backoff helper now takes a base delay. Rate-limit
failures keep their existing handling. `unauthorized` (401) and other
permanent failures are still declined.
- The longer base delay is deliberate. Providers already retry 5xx
errors internally for a few minutes, so the 5-second overload backoff
would use up the attempt cap during an outage like the 30-minute one
reported in #4839.
- Docs: the provider-retry overview, skill and package description, plus
the `bb guide plugins` and `bb guide providers` templates.
- No server/daemon wire change, CLI change or protocol bump.

## How you verified

- **Production evidence (from a local bb.db):**
- Pooler 502s on 2026-09-23 were recorded with exactly the `errorInfo`
shapes above.
  - Each affected thread sat idle about 20 minutes, until a manual send.
- The 429 wave on 2026-10-20 was retried automatically, confirming #5283
works.
- **Regression tests (`plugins/provider-retry/server.test.ts`):**
- Policy cases built from the recorded shapes: Claude Code pooler 502,
Codex stream-disconnected 502, Codex too-many-failed-attempts 503, and a
connection failure.
  - One plugin-level case that queues a "Provider unavailable" retry.
- All 5 new tests fail against the previous policy and pass with this
change.
- The existing decline test used a 500 as its example of a permanent
failure; it now uses a 401.
- **Commands:**
- `pnpm exec turbo run test typecheck lint
--filter=bb-plugin-provider-retry --filter=@bb/templates`: 26 and 46
tests pass.
- `pnpm exec turbo run test --filter=@bb/server --
test/threads/turn-failed-retry.test.ts
test/services/plugins/plugin-authoring-docs.test.ts
test/services/plugins/builtin-plugins.test.ts`: 60 tests pass.
- `pnpm exec turbo run test typecheck --filter=@bb/plugin-registry
--filter=@bb/bundled-plugins`: pass.
  - `oxfmt --check` is clean.
- **Live test (`pnpm start:worktree`):**
- Claude Code was routed through a local proxy that returns the pooler's
exact "502 Account Pooler could not reach Anthropic." response.
- The follow-up turn failed and a "Provider unavailable · attempt 2"
retry was queued about 90 s later.
- Attempt 2 failed while the outage was still on, and attempt 3 was
queued about 4 minutes later.
- After the outage ended, attempt 3 ran on its own and the agent
replied.
  - A 401 from the same proxy was recorded as `Skipped: not-retryable`.

Fixes #4839

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

1 participant