← reports

#8555 · Account Pooler discards saved quota readings after a usage check fails

Bug Medium Effort: Medium providers Issue #8555 · December 2, 2026 · base 4d7a9af6097bc785ccfa8283c46b98d5ff251fe8

Verdict: REPRODUCED · Root-cause confidence: high

What happens

Account Pooler checks the provider again when a request arrives after its short polling interval, even if the account is known to remain blocked until a future reset. A hub refresh can also check several accounts for the same provider at once. After an upstream 429, the usage source returns an error on a passive read even when the pool still has a valid observation. Provider Usage cannot show quota bars from that response on a cold cache.

Expected and observed

ScenarioExpectedObserved in both runs
Incoming Claude requests with a known future resetOnly the initial usage read; no early request-path rechecksUsage reads at 0, 31,000 and 62,000 ms; all three routed requests were rejected locally
First passive usage-source read gets a 429Return the saved unexpired 64% windowSource returns status: "error"; pool CLI still reports that window and no account error
Hub start with two eligible Claude accountsSame-provider checks do not overlapTwo checks in flight at once
Successive 429s with no retry headerRetries slow down after repeated failuresThree explicit checks hit the upstream one second apart, after the initial successful read
Passive read after a 10-second Retry-AfterThe read at 11 seconds can try againNo upstream call after the hold ended

The test injects provider responses; it does not establish Anthropic’s live throttling policy or reproduce the reporter’s live account count. The cold-cache effect follows from Provider Usage’s server code; this run did not drive the sidebar or use a live provider.

Environment and reproduction

Linux x86-64, Node v22.19.0, pnpm 9.15.0, Account Pooler 0.1.0, trusted get-bb/bb main at 4d7a9af6097bc785ccfa8283c46b98d5ff251fe8. The repository’s plugin test harness uses a temporary local SQLite store and in-process HTTP dispatch. The test clock and upstream responses are synthetic; no enrolled hosts, live credentials, or ports are used.

  1. Check out the base commit in a clean worktree and run pnpm install --frozen-lockfile --prefer-offline.
  2. Insert the test block below immediately before function deferred() in plugins/account-pool/src/server.test.ts. Leave production code unchanged.
  3. Run:
    export TMPDIR="$(mktemp -d)"
    pnpm exec turbo run test --env-mode=loose --filter=bb-plugin-account-pool -- src/server.test.ts -t 'issue-8555 local quota checks'
AssertionError: expected [ +0, 31000, 62000 ] to deeply equal [ +0 ]
AssertionError: expected { status: 'error', …(4) } to match object { status: 'ok', windows: [ …(1) ] }
AssertionError: expected 2 to be 1 // Object.is equality
AssertionError: expected 4 to be less than 4
AssertionError: expected [ +0, +0 ] to deeply equal [ +0, +0, 11000 ]
Tests  5 failed | 204 skipped (209)
Complete reproduction test block
describe("issue-8555 local quota checks", () => {
  const hour = 3_600_000;
  const initialTime = 1_800_000_000_000;
  const resetAt = initialTime + hour;

  async function quotaFixture(nextUsage: () => Response | Promise<Response>) {
    let now = initialTime;
    let logins = 0;
    const usageCalls: number[] = [];
    const fixture = await createFixture({
      upstreamUrl: "https://upstream.example",
      source: "oauth",
      options: {
        now: () => now,
        usageUrl: "https://upstream.example/quota",
        claudeLogin: async () => {
          logins += 1;
          return claudeCredentials({
            accessToken: `synthetic-access-${logins}`,
            expiresAt: initialTime + 2 * hour,
            accountUuid:
              logins === 1
                ? "11111111-1111-4111-8111-111111111111"
                : "22222222-2222-4222-8222-222222222222",
          });
        },
        fetch: async (input) => {
          if (new URL(String(input)).pathname !== "/quota") {
            return Response.json({});
          }
          usageCalls.push(now - initialTime);
          return nextUsage();
        },
      },
    });
    return {
      ...fixture,
      advance: (elapsed: number) => {
        now += elapsed;
      },
      usageCalls,
      readUsage: async (refresh: boolean) =>
        usageMeasurementSchema.parse(
          await fixture.host.harness.behavior.callRpc(usageFetchMethod, {
            resourceId: fixture.account.id,
            refresh,
          }),
        ).usage,
    };
  }

  function measurement(percent: number) {
    return Response.json({
      five_hour: { utilization: percent, resets_at: resetAt / 1_000 },
    });
  }

  function throttled() {
    return new Response(null, { status: 429 });
  }

  it("does not recheck a refused window before its known reset under traffic", async () => {
    const fixture = await quotaFixture(() => measurement(100));
    for (const elapsed of [0, 31_000, 31_000]) {
      fixture.advance(elapsed);
      const response = await fixture.host.harness.behavior.fetchHttp(
        "POST",
        "/v1/messages",
        {
          headers: authHeaders(fixture.key),
          body: JSON.stringify({ model: "claude-opus-4-1" }),
        },
      );
      expect(response.status).toBe(429);
      await response.text();
    }
    expect(fixture.usageCalls).toEqual([0]);
  });

  it("returns an unexpired saved window on the first passive usage read after a 429", async () => {
    let limited = false;
    const fixture = await quotaFixture(() =>
      limited ? throttled() : measurement(64),
    );
    limited = true;
    fixture.advance(301_000);
    const usage = await fixture.readUsage(false);
    const status = await fixture.host.harness.behavior.runCli([
      "status",
      "--json",
    ]);
    const account = statusReportSchema
      .parse(JSON.parse(status.stdout))
      .accounts.find(({ id }) => id === fixture.account.id);
    expect(account).toMatchObject({
      error: null,
      limitWindows: [expect.objectContaining({ resetAt, utilization: 0.64 })],
    });
    expect(fixture.usageCalls).toEqual([0, 301_000]);
    expect(usage).toMatchObject({
      status: "ok",
      windows: [expect.objectContaining({ usedPercent: 64 })],
    });
  });

  it("does not run same-provider usage checks concurrently at hub startup", async () => {
    let active = 0;
    let peak = 0;
    let startup = false;
    const fixture = await quotaFixture(async () => {
      if (startup) {
        active += 1;
        peak = Math.max(peak, active);
        await new Promise((resolve) => setTimeout(resolve, 30));
        active -= 1;
      }
      return measurement(64);
    });
    await addExistingAccount(fixture, "claude", { label: "second" });
    expect(fixture.usageCalls).toEqual([0, 0]);
    fixture.service.controller.abort();
    await fixture.service.done;
    fixture.advance(301_000);
    startup = true;
    const restarted = fixture.host.harness.behavior.runService("hub");
    cleanups.push(async () => {
      restarted.controller.abort();
      await restarted.done;
    });
    await vi.waitFor(() => {
      expect(fixture.usageCalls).toEqual([0, 0, 301_000, 301_000]);
      expect(active).toBe(0);
    });
    expect(peak).toBe(1);
  });

  it("does not retry at a fixed one-second interval after successive 429s", async () => {
    let limited = false;
    const fixture = await quotaFixture(() =>
      limited ? throttled() : measurement(64),
    );
    limited = true;
    expect(await fixture.readUsage(true)).toMatchObject({ status: "error" });
    fixture.advance(1_000);
    expect(await fixture.readUsage(true)).toMatchObject({ status: "error" });
    fixture.advance(1_000);
    expect(await fixture.readUsage(true)).toMatchObject({ status: "error" });
    expect(fixture.usageCalls.length).toBeLessThan(4);
  });

  it("permits a passive retry once the provider retry-after time has passed", async () => {
    let limited = false;
    const fixture = await quotaFixture(() =>
      limited
        ? new Response(null, { status: 429, headers: { "retry-after": "10" } })
        : measurement(64),
    );
    limited = true;
    expect(await fixture.readUsage(true)).toMatchObject({ status: "error" });
    fixture.advance(11_000);
    limited = false;
    await fixture.readUsage(false);
    expect(fixture.usageCalls).toEqual([0, 0, 11_000]);
  });
});

Root cause

  1. Routing requests a usage recheck if no account was picked or if the picked account exceeds threshold. The candidate filter asks only whether the account is over threshold; it does not distinguish unknown resets from known future resets. Window predicates already stop counting those windows when the reset arrives.
  2. The hub’s startup and periodic loop invokes a bulk refresh that launches each account in one Promise.all. The request-path refresh has the same fan-out.
  3. The usage adapter records a 429 retry deadline, and the shared parser defaults to one second without a retry header. The hub timestamps an attempt before it knows the outcome and checks the ordinary refresh interval before the retry deadline. A passive read is therefore still suppressed after the retry deadline.
  4. The usage source builds windows from the pool account but returns an error rather than those windows whenever the hub remembers a usage failure. Provider Usage stores only successful measurements and uses an error-only row if it has no previous measurement. The same error on a warm cache instead becomes a refresh warning alongside the previous measurement.

Verification

The same agent repeated the command in a second detached worktree at the same full commit, with a second frozen install, a separate temporary data directory, and only the new test block applied to tracked files. It got the same five assertion failures and 204 skips. The initial full monorepo builds stopped in the GitHub plugin’s bundling step because Plugin SDK runtime files were missing; the focused Turbo run completed its prerequisite tasks and reached all five assertions in both checkouts.

Suggested fix and linked PR

Keep known reset deadlines out of the request-path recovery poll when they already explain the block. Pace bulk checks by provider and track failed-attempt backoff separately from successful-refresh freshness. On passive reads, serve usable saved windows through transient check failures; keep errors visible on explicit refresh and when no observation is still usable.

PR #8556 is already linked. Static inspection of the diff shows changes in all three areas: per-provider bulk sequencing, reset-aware polling, and separate backoff plus a passive cache fallback. The sequencing is per bulk invocation, so overlapping callers are a useful additional test if the intended guarantee is a global per-provider concurrency limit. The PR branch was not checked out, run, or modified; this report does not verify the PR.

Related behavior: PR #8455 made usage-check failures observable. The change proposed here preserves explicit refresh errors while distinguishing them from passive display.