← reports

#6169 · Account-pool threshold excludes upstream-allowed capacity

BugPriority: MediumEffort: Mediumprovidersprovider-claude-codeGitHub issue2026-10-23

Trusted base: 1e80ca7b44bccd06c6da75ed9ca6ba497bd380f5. Verdict: REPRODUCED · Root-cause confidence: high · reproduction label: confirmed-repro.

1. TL;DR

The actual Account Pooler plugin can return its own 429 without contacting an account whose upstream quota status remains allowed at 99% utilization. At the default 98% threshold, both routing and retry availability classify that account as exhausted. In a two-account synthetic reproduction, the pool instead advertises a two-hour reset belonging to the other, genuinely rejected account. Changing only the threshold to 1 immediately makes the first account routable and retry availability ready. This reproduces the routing mechanism, not the reporter's private incident timeline; importantly, current configuration documentation explicitly describes a hard cutoff, so changing that policy is not a decision-free automated fix.

2. Claims vs findings

ClaimFindingEvidence
Threshold exhaustion can exclude an allowed account.VerifiedReal plugin HTTP boundary returns 429 with allowed utilization 0.99; CLI reports exhausted.
A rejected account's reset can be quoted despite allowed capacity.VerifiedRejected account reset is now + 7,200 seconds; allowed account reset is now + 86,400. Pool emits retry-after 7200 and blocked retryAt 1900007200000.
Threshold 1 restores traffic without changing quota observations.VerifiedConfiguration RPC alone changes availability to ready; the next request succeeds on the same allowed upstream.
Extra-usage routing is a distinct bypass.VerifiedProduction selection explicitly bypasses exhaustion for extra usage. Reproduction uses extraUsage null; existing extra-usage cases pass.
The reported live accounts completed multiple turns and Provider Retry parked actual threads.Not independently verifiedNo private account, thread, or runtime data accessed. Retry availability and response headers are reproduced, but no live provider or Provider Retry scheduler was run.
At utilization 1 with allowed status, utilization can still dominate.Source-supported onlyactiveWindow compares utilization regardless of allowed status. This specific state was not exercised by the new test.

3. Environment

4. Minimal reproduction

Use a fresh checkout of the public repository at the exact base commit. Save the complete patch below as /tmp/issue-6169.patch. It adds a single observable-boundary regression to the existing plugin suite and reuses existing fixtures; it does not modify production code.

git clone https://github.com/get-bb/bb.git bb-6169
cd bb-6169
git checkout 1e80ca7b44bccd06c6da75ed9ca6ba497bd380f5
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
git apply /tmp/issue-6169.patch
pnpm exec turbo run test --filter=bb-plugin-account-pool -- src/server.test.ts -t 'issue 6169'
  1. First request succeeds and learns allowed utilization 0.99 for the first account.
  2. Next request reaches the second account, learns a real quota rejection, and has no remaining eligible candidate.
  3. A further request returns a pool-generated 429 with zero upstream attempts; CLI and retry availability are captured.
  4. Change only switchThreshold to 1 through the actual configuration RPC. Retry availability becomes ready and the first account serves another 200.
  5. The final assertion deliberately requires the requested soft-threshold behavior at the default setting. It fails against unchanged main, after all diagnostic and workaround assertions have passed.

Expected: when only preference-threshold exhaustion remains, use the allowed account and return 200. Actual: 429, retry-after 7200, and no upstream attempt. This expected behavior is the proposed product correction, not the current documented hard-cutoff contract.

Complete reproduction patch

diff --git a/plugins/account-pool/src/server.test.ts b/plugins/account-pool/src/server.test.ts
index 3b87d8d62..51cadc1be 100644
--- a/plugins/account-pool/src/server.test.ts
+++ b/plugins/account-pool/src/server.test.ts
@@ -322,6 +322,120 @@ function authHeaders(key: string): Record<string, string> {
   };
 }
 
+it("issue 6169 keeps upstream-allowed traffic routable after the soft switch point", async () => {
+  const now = 1_900_000_000_000;
+  const attempts: string[] = [];
+  const fixture = await createFixture({
+    upstreamUrl: "https://upstream.example",
+    apiKey: "synthetic-allowed",
+    options: {
+      now: () => now,
+      fetch: async (_input, init) => {
+        const key = new Headers(init?.headers).get("x-api-key") ?? "";
+        attempts.push(key);
+        const allowed = key === "synthetic-allowed";
+        return Response.json(
+          { served: allowed },
+          {
+            status: allowed ? 200 : 429,
+            headers: {
+              "anthropic-ratelimit-unified-5h-status": allowed
+                ? "allowed"
+                : "rejected",
+              "anthropic-ratelimit-unified-5h-utilization": allowed
+                ? "0.99"
+                : "1",
+              "anthropic-ratelimit-unified-5h-reset": String(
+                now / 1000 + (allowed ? 86_400 : 7_200),
+              ),
+            },
+          },
+        );
+      },
+    },
+  });
+  await addApiAccount(fixture, "synthetic-rejected");
+  const send = () =>
+    fixture.host.harness.behavior.fetchHttp("POST", "/v1/messages", {
+      headers: authHeaders(fixture.key),
+      body: JSON.stringify({ model: "claude-opus-4-1", messages: [] }),
+    });
+  const warm = await send();
+  expect(warm.status).toBe(200);
+  await warm.text();
+  const learningRejection = await send();
+  await learningRejection.text();
+  const attemptsBeforeBlocked = attempts.length;
+  const blocked = await send();
+  const blockedBody = await blocked.json();
+  const availability = await fixture.host.harness.behavior.fetchHttp(
+    "GET",
+    "/retry-availability?provider=claude&family=opus",
+    {
+      headers: authHeaders(fixture.key),
+    },
+  );
+  const blockedAvailability = await availability.json();
+  const beforeStatus = await fixture.host.harness.behavior.runCli([
+    "status",
+    "--json",
+  ]);
+  const beforeAccounts = statusReportSchema.parse(
+    JSON.parse(beforeStatus.stdout),
+  ).accounts;
+  const blockedAttempts = attempts.length - attemptsBeforeBlocked;
+  await fixture.host.harness.behavior.callRpc("config.set", {
+    switchThreshold: 1,
+  });
+  const recoveredAvailabilityResponse =
+    await fixture.host.harness.behavior.fetchHttp(
+      "GET",
+      "/retry-availability?provider=claude&family=opus",
+      {
+        headers: authHeaders(fixture.key),
+      },
+    );
+  const recoveredAvailability = await recoveredAvailabilityResponse.json();
+  const recovered = await send();
+  const recoveredBody = await recovered.json();
+  console.log(
+    "ISSUE_6169_EVIDENCE",
+    JSON.stringify({
+      threshold: 0.98,
+      blockedStatus: blocked.status,
+      retryAfter: blocked.headers.get("retry-after"),
+      blockedBody,
+      blockedAvailability,
+      blockedAttempts,
+      accountStatuses: beforeAccounts.map((account) => ({
+        status: account.status,
+        utilization: account.fiveHourUtilization,
+        upstreamStatus: account.fiveHourStatus,
+        extraUsage: account.extraUsage,
+      })),
+      workaroundThreshold: 1,
+      recoveredStatus: recovered.status,
+      recoveredBody,
+      recoveredAvailability,
+      attempts,
+    }),
+  );
+  expect(blockedAttempts).toBe(0);
+  expect(blockedAvailability).toEqual({
+    kind: "blocked",
+    retryAt: now + 7_200_000,
+  });
+  expect(recoveredAvailability).toEqual({ kind: "ready" });
+  expect(recovered.status).toBe(200);
+  expect(recoveredBody).toEqual({ served: true });
+  expect(attempts).toEqual([
+    "synthetic-allowed",
+    "synthetic-rejected",
+    "synthetic-allowed",
+  ]);
+  expect(blocked.status).toBe(200);
+});
+
 async function addApiAccount(
   fixture: Fixture,
   apiKey: string,

Observed output (identical in both checkouts)

{
  "threshold": 0.98,
  "blockedStatus": 429,
  "retryAfter": "7200",
  "blockedBody": {
    "type": "error",
    "error": {
      "type": "rate_limit_error",
      "message": "No Account Pooler account is currently eligible. Next account is expected to be available at 2030-03-17T19:46:40.000Z (in 7200 seconds)."
    }
  },
  "blockedAvailability": {
    "kind": "blocked",
    "retryAt": 1900007200000
  },
  "blockedAttempts": 0,
  "accountStatuses": [
    {
      "status": "exhausted",
      "utilization": 0.99,
      "upstreamStatus": "allowed",
      "extraUsage": null
    },
    {
      "status": "exhausted",
      "utilization": 1,
      "upstreamStatus": "rejected",
      "extraUsage": null
    }
  ],
  "workaroundThreshold": 1,
  "recoveredStatus": 200,
  "recoveredBody": {
    "served": true
  },
  "recoveredAvailability": {
    "kind": "ready"
  },
  "attempts": [
    "synthetic-allowed",
    "synthetic-rejected",
    "synthetic-allowed"
  ]
}

AssertionError: expected 429 to be 200
Test Files  1 failed (1)
Tests       1 failed | 188 skipped (189)

The failing assertion is intentional evidence. Earlier assertions verify zero upstream calls during exclusion, the rejected account's exact retry time, ready availability after the configuration change, a successful upstream response, and the complete upstream-attempt sequence. These controls distinguish the threshold defect from an upstream outage.

5. Root cause

activeWindow uses rejection or utilization at/above the configured threshold:

status?.toLowerCase() === "rejected" ||
(utilization !== null && utilization >= threshold)

An allowed status does not override that utilization comparison. Selection filters shared and model-family exhaustion before constructing candidates; extra usage is its only exhaustion bypass. Therefore no merely above-threshold account reaches the later candidate preference and affinity logic. Account status reports the same state as exhausted.

accountAvailability evaluates the same configured-threshold predicate. For each exhausted account it computes a blocking reset, then returns the earliest account availability. In this synthetic pool, the earliest is the genuinely rejected account's two-hour reset, despite the other account continuing to serve when the threshold is raised. noEligibleResponse propagates that result to the 429 text and retry-after.

The OAuth usage-refresh-before-refusal path at refreshExhaustedUsage and the request loop does not change this eligibility rule. This reproduction uses API-key test accounts with observed headers, so it isolates routing from OAuth polling and cannot by itself verify a live usage API incident.

Policy caveat: configuration documentation explicitly says this is the fraction at which an account stops receiving matching traffic. Routing guidance describes advancement to the next eligible account; it does not explicitly promise that above-threshold accounts remain eligible. The behavior is confirmed, but a soft switch point would be a deliberate policy change rather than a mechanical correction to an already specified fallback.

6. Proposed fix and automation decision

First decide whether the pool-wide threshold is a hard reserve or a soft routing preference, and how that interacts with paid extra usage. If soft semantics are chosen, keep below-threshold accounts preferred, then permit otherwise allowed, non-held, non-errored accounts before refusing. Share the resulting eligibility contract with retry availability and account status; maintain hard provider rejections, usage restrictions, model-family limits, and reset expiration. Do not simply remove the threshold comparison everywhere, because that would erase early switching.

No pull request opened. Although a local implementation might fit the line/file limits, changing documented hard-cutoff/reserve semantics and fallback ordering requires a product decision. The automation's simple-fix conditions therefore fail before production edits. No branch was pushed and no dependency, protocol, persisted data, or production source changed.

The regression was designed from trusted repository routing code rather than copied from issue code. Its primary owner is the plugin HTTP boundary, where it observes actual routing, quota persistence, and availability. Existing tests do not exercise the state where every enabled account is past the preference threshold without extra usage. It requires no new production seam.

7. Related issues and pull requests

No linked open pull request was present in the issue's connected/cross-referenced metadata or an open-PR search for issue 6169 at investigation time. The repository's existing extra-usage implementation and its tests cover a different entitlement-based bypass. A reserve-setting feature and retry rescheduling are separate policy/lifecycle concerns; neither was implemented here.

8. Verification

The same agent repeated the test in a second newly created detached checkout of 1e80ca7b44bccd06c6da75ed9ca6ba497bd380f5, with a fresh frozen install and separately allocated fixture storage. The original source tree was clean before applying the same agent-authored patch. No first-checkout build or node_modules tree was copied into the second checkout; ordinary pnpm/Turbo caches were available.

pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
git apply /tmp/issue-6169.patch
pnpm exec turbo run test --filter=bb-plugin-account-pool -- src/server.test.ts -t 'issue 6169'

Result: expected regression failure, 429 instead of 200.
Evidence JSON: byte-for-byte equal to the first run.
Workaround controls: all passed.
Report correction after second run: none.

This is a repeat reproduction by the same agent, not independent verification. No live provider incident claim is elevated beyond what the synthetic test establishes.

9. Appendix: additional checks

pnpm exec turbo run test --filter=bb-plugin-account-pool -- src/server.test.ts -t 'applies config threshold|routes exhausted Claude|prefers subscription quota|refreshes exhausted usage|reports retry availability'
Result: 14 passed, 175 skipped.

pnpm exec turbo run build
Result after SDK build preparation: 71 tasks successful.

git diff --check
Result: clean.

The initial full build encountered a pre-existing clean-build ordering race: the GitHub plugin started before the SDK host runtime output existed. Building the existing SDK through Turbo and retrying the full build succeeded; no build source was modified. Node build and bundle-size warnings were non-fatal. The expected-failing reproduction is kept as inline evidence rather than landed as a failing repository test. No visual screenshots are relevant to this nonvisual routing behavior.

Issue text, links, and code were treated as untrusted claims. No issue-provided script, branch, patch, or external link was executed or fetched. Only trusted main and the reproduction authored from its code were run. Raw logs and local artifacts remain outside this public report repository; the complete reproducible patch and necessary output are embedded here.

> AGENT GENERATED