← reports

#7418 · Busy accounts cannot refresh obsolete quota windows

BugPriority: LowEffort: Lowproviders Issue #74182026-11-11 · base 365d7c5237ae270be0555b5b44ea61020252713e

Verdict: REPRODUCED · Root-cause confidence: high · reproduction label: confirmed-repro

1. TL;DR

A pooled account can retain an obsolete short-term usage window while serving a long-running response. Partial response headers preserve the last short-term observation, but the hub refuses to ask the usage endpoint for authoritative data whenever that account has a request in flight. This refusal also affects an explicit CLI refresh, which reports success without updating the usage snapshot. A deterministic regression reproduced the stale window in two separate checkouts of trusted main, and a one-line removal of the busy-account guard makes the same test pass without ending the active stream.

2. Claims vs findings

ClaimFindingEvidence
Missing short-term headers retain the old window.VerifiedThe test seeds 12% via one response, advances the clock by one minute, and receives weekly-only headers. The primary window retains its original timestamp while the account timestamp advances.
Explicit refresh does not clear stale data during a request.VerifiedThe real plugin CLI refresh succeeds with one response body still open, but the baseline retains both header windows instead of replacing them with the usage response.
Periodic refresh uses the same busy-account exclusion.Verified by sourceThe service loop and forced refresh both converge on refreshAccountUsage. The periodic five-minute timer was not separately advanced in this test.
An authoritative response can remove the obsolete window.VerifiedThe synthetic endpoint returns five_hour: null and a seven-day bucket; after the fix only the weekly usage window remains, before the streaming request ends.
The display can present an older window with a newer account timestamp.Verified by source and stateThe regression checks distinct timestamps. The publisher includes stored windows and the account-level timestamp, not window-level ages. No browser rendering was claimed or captured.
The reporter’s provider actually removed an account limit.Unverified externallyNo live credentials, production database, runtime logs, or provider traffic were accessed. The exact provider-side transition is represented by controlled transport responses.

3. Environment

4. Minimal reproduction

  1. Create and build a clean trusted checkout:
    WORK=$(mktemp -d)
    git clone --depth 1 --branch main https://github.com/get-bb/bb.git "$WORK/bb"
    cd "$WORK/bb"
    git fetch origin main
    git checkout 365d7c5237ae270be0555b5b44ea61020252713e
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build
    
  2. Save the complete patch below as /tmp/issue-7418-regression.patch, then apply it to add only the focused regression:
    git apply /tmp/issue-7418-regression.patch
    pnpm exec turbo run test --filter=bb-plugin-account-pool -- src/server.test.ts -t 'refreshes usage and drops obsolete windows while an account is streaming'
  3. The regression seeds a short-term header observation, leaves the next weekly-only response body open, and invokes the real plugin CLI command account refresh. The fake usage endpoint is prepared to remove the primary window.
  4. Expected: the refresh leaves the response in flight, makes one usage read, removes the primary window, and updates weekly utilization to 45%. Actual on base: the command succeeds, but primary 12% and weekly 44% remain header-sourced.

Observed failure, first checkout

bb-plugin-account-pool:test:  FAIL  |bb-plugin-account-pool| src/server.test.ts > sequential pool recovery > refreshes usage and drops obsolete windows while an account is streaming
bb-plugin-account-pool:test: AssertionError: expected [ { slot: 'primary', …(6) }, …(1) ] to deeply equal [ ObjectContaining{…} ]
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test: - Expected
bb-plugin-account-pool:test: + Received
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test:   [
bb-plugin-account-pool:test:     {
bb-plugin-account-pool:test: +     "observedAt": 1794381562494,
bb-plugin-account-pool:test: +     "resetAt": 4102444800000,
bb-plugin-account-pool:test: +     "slot": "primary",
bb-plugin-account-pool:test: +     "source": "header",
bb-plugin-account-pool:test: +     "status": null,
bb-plugin-account-pool:test: +     "utilization": 0.12,
bb-plugin-account-pool:test: +     "windowMinutes": 300,
bb-plugin-account-pool:test: +   },
bb-plugin-account-pool:test: +   {
bb-plugin-account-pool:test: +     "observedAt": 1794381622494,
bb-plugin-account-pool:test: +     "resetAt": 4102444800000,
bb-plugin-account-pool:test:       "slot": "secondary",
bb-plugin-account-pool:test: -     "source": "usage",
bb-plugin-account-pool:test: -     "utilization": 0.45,
bb-plugin-account-pool:test: +     "source": "header",
bb-plugin-account-pool:test: +     "status": "allowed",
bb-plugin-account-pool:test: +     "utilization": 0.44,
bb-plugin-account-pool:test: +     "windowMinutes": 10080,
bb-plugin-account-pool:test:     },
bb-plugin-account-pool:test:   ]
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test:  ❯ src/server.test.ts:6999:47
bb-plugin-account-pool:test:     6997|       const after = await status();
bb-plugin-account-pool:test:     6998|       expect(after.inFlight).toBe(1);
bb-plugin-account-pool:test:     6999|       expect(after.accounts[0]?.limitWindows).toEqual([
bb-plugin-account-pool:test:        |                                               ^
bb-plugin-account-pool:test:     7000|         expect.objectContaining({
bb-plugin-account-pool:test:     7001|           slot: "secondary",
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test:  Test Files  1 failed (1)
bb-plugin-account-pool:test:       Tests  1 failed | 197 skipped (198)
Complete reproduction patch (apply to the recorded base)
diff --git a/plugins/account-pool/src/server.test.ts b/plugins/account-pool/src/server.test.ts
index fc52b05..049893f 100644
--- a/plugins/account-pool/src/server.test.ts
+++ b/plugins/account-pool/src/server.test.ts
@@ -6918,6 +6918,99 @@ describe("sequential pool recovery", () => {
     },
   );
 
+  it("refreshes usage and drops obsolete windows while an account is streaming", async () => {
+    let now = Date.now();
+    let messageCount = 0;
+    let usageReads = 0;
+    const stream = new TransformStream<Uint8Array, Uint8Array>();
+    const writer = stream.writable.getWriter();
+    const fixture = await createFixture({
+      upstreamUrl: "https://upstream.example",
+      source: "oauth",
+      options: {
+        now: () => now,
+        usageUrl: "https://upstream.example/usage",
+        fetch: async (input) => {
+          if (new URL(String(input)).pathname === "/usage") {
+            usageReads++;
+            return Response.json({
+              five_hour: null,
+              seven_day: { utilization: 45, resets_at: "4102444800" },
+            });
+          }
+          messageCount++;
+          const headers = {
+            "anthropic-ratelimit-unified-7d-utilization": "0.44",
+            "anthropic-ratelimit-unified-7d-reset": "4102444800",
+            ...(messageCount === 1
+              ? {
+                  "anthropic-ratelimit-unified-5h-utilization": "0.12",
+                  "anthropic-ratelimit-unified-5h-reset": "4102444800",
+                }
+              : { "content-type": "text/event-stream" }),
+          };
+          return messageCount === 1
+            ? Response.json({ ok: true }, { headers })
+            : new Response(stream.readable, { headers });
+        },
+      },
+    });
+    const send = () =>
+      fixture.host.harness.behavior.fetchHttp("POST", "/v1/messages", {
+        headers: authHeaders(fixture.key),
+        body,
+      });
+    const first = await send();
+    expect(first.status).toBe(200);
+    await first.text();
+    const firstObservedAt = now;
+    now += 60_000;
+    const response = await send();
+    const responseBody = response.text();
+    const status = async () =>
+      statusSchema.parse(
+        await fixture.host.harness.behavior.callRpc("status.get", null),
+      );
+    try {
+      expect(response.status).toBe(200);
+      const before = await status();
+      expect(before.inFlight).toBe(1);
+      expect(before.accounts[0]?.observedAt).toBe(now);
+      expect(before.accounts[0]?.limitWindows).toEqual(
+        expect.arrayContaining([
+          expect.objectContaining({
+            slot: "primary",
+            utilization: 0.12,
+            observedAt: firstObservedAt,
+            source: "header",
+          }),
+        ]),
+      );
+      const readsBeforeRefresh = usageReads;
+      const refresh = await fixture.host.harness.behavior.runCli([
+        "account",
+        "refresh",
+        fixture.account.id,
+        "--json",
+      ]);
+      expect(refresh.exitCode).toBe(0);
+      const after = await status();
+      expect(after.inFlight).toBe(1);
+      expect(after.accounts[0]?.limitWindows).toEqual([
+        expect.objectContaining({
+          slot: "secondary",
+          utilization: 0.45,
+          source: "usage",
+        }),
+      ]);
+      expect(usageReads).toBe(readsBeforeRefresh + 1);
+    } finally {
+      await writer.close();
+      await responseBody;
+    }
+    expect((await status()).inFlight).toBe(0);
+  });
+
   it("returns Codex paid pins to recovered subscriptions and persists spending restrictions", async () => {
     let now = Date.now();
     let signIns = 0;
Added regression test
  it("refreshes usage and drops obsolete windows while an account is streaming", async () => {
    let now = Date.now();
    let messageCount = 0;
    let usageReads = 0;
    const stream = new TransformStream<Uint8Array, Uint8Array>();
    const writer = stream.writable.getWriter();
    const fixture = await createFixture({
      upstreamUrl: "https://upstream.example",
      source: "oauth",
      options: {
        now: () => now,
        usageUrl: "https://upstream.example/usage",
        fetch: async (input) => {
          if (new URL(String(input)).pathname === "/usage") {
            usageReads++;
            return Response.json({
              five_hour: null,
              seven_day: { utilization: 45, resets_at: "4102444800" },
            });
          }
          messageCount++;
          const headers = {
            "anthropic-ratelimit-unified-7d-utilization": "0.44",
            "anthropic-ratelimit-unified-7d-reset": "4102444800",
            ...(messageCount === 1
              ? {
                  "anthropic-ratelimit-unified-5h-utilization": "0.12",
                  "anthropic-ratelimit-unified-5h-reset": "4102444800",
                }
              : { "content-type": "text/event-stream" }),
          };
          return messageCount === 1
            ? Response.json({ ok: true }, { headers })
            : new Response(stream.readable, { headers });
        },
      },
    });
    const send = () =>
      fixture.host.harness.behavior.fetchHttp("POST", "/v1/messages", {
        headers: authHeaders(fixture.key),
        body,
      });
    const first = await send();
    expect(first.status).toBe(200);
    await first.text();
    const firstObservedAt = now;
    now += 60_000;
    const response = await send();
    const responseBody = response.text();
    const status = async () =>
      statusSchema.parse(
        await fixture.host.harness.behavior.callRpc("status.get", null),
      );
    try {
      expect(response.status).toBe(200);
      const before = await status();
      expect(before.inFlight).toBe(1);
      expect(before.accounts[0]?.observedAt).toBe(now);
      expect(before.accounts[0]?.limitWindows).toEqual(
        expect.arrayContaining([
          expect.objectContaining({
            slot: "primary",
            utilization: 0.12,
            observedAt: firstObservedAt,
            source: "header",
          }),
        ]),
      );
      const readsBeforeRefresh = usageReads;
      const refresh = await fixture.host.harness.behavior.runCli([
        "account",
        "refresh",
        fixture.account.id,
        "--json",
      ]);
      expect(refresh.exitCode).toBe(0);
      const after = await status();
      expect(after.inFlight).toBe(1);
      expect(after.accounts[0]?.limitWindows).toEqual([
        expect.objectContaining({
          slot: "secondary",
          utilization: 0.45,
          source: "usage",
        }),
      ]);
      expect(usageReads).toBe(readsBeforeRefresh + 1);
    } finally {
      await writer.close();
      await responseBody;
    }
    expect((await status()).inFlight).toBe(0);
  });

The existing test file’s helpers exercise the real plugin boundary. No new production seam or dependency is required. Reproduction source and output are embedded here rather than published as separate artifacts, following the reports repository’s privacy and file-hygiene rules.

5. Root cause

Responses may legitimately omit a window. The header merger therefore keeps the previous value instead of treating absence as evidence that a limit was removed.

plugins/account-pool/src/quota.ts:82

  headers: Headers,
  slot: LimitWindowSlot,
  previous: AccountQuota,
  now: number,
): LimitWindow | null {
  const { minutes, header } = CLAUDE_WINDOWS[slot];
  const utilization = parseNumber(
    headers.get(`${PREFIX}${header}-utilization`),
  );
  const resetAt = parseReset(headers.get(`${PREFIX}${header}-reset`));
  const status = headers.get(`${PREFIX}${header}-status`);
  const prior =
    previous.limitWindows.find((window) => window.slot === slot) ?? null;
  if (utilization === null && resetAt === null && status === null)
    return prior;
  return {
    slot,
    windowMinutes: minutes,
    utilization: utilization ?? prior?.utilization ?? null,
    resetAt: resetAt ?? prior?.resetAt ?? null,
    status: status ?? prior?.status ?? null,
    observedAt: now,
    source: "header",
  };
}

Each upstream response is merged immediately. A weekly update advances the account observation even while an older primary observation survives.

plugins/account-pool/src/hub.ts:620

          const { response } = upstream;
          const observed = adapter.quotaFromHeaders(
            selected.account.id,
            response.headers,
            this.options.quotas.get(selected.account.id),
            family,
            this.options.now(),
          );
          this.options.quotas.put(observed);

plugins/account-pool/src/quota.ts:147

  const observed =
    limitWindows.some((window) => !previous.limitWindows.includes(window)) ||
    representativeClaim !== null ||
    extraUsage !== previous.extraUsage ||
    scoped !== null;
  return {
    accountId,
    usageRestriction: previous.usageRestriction,
    extraUsage,
    representativeClaim: representativeClaim ?? previous.representativeClaim,
    familyWeekly,
    limitWindows,
    observedAt: observed ? now : previous.observedAt,
    heldUntil: previous.heldUntil,

The actual defect is refresh starvation: the busy-account guard returns before refresh deduplication, throttling, and the adapter request. Forced refresh bypasses the interval but not this guard. A continuously active account can therefore never obtain the usage snapshot needed to clear the obsolete value.

plugins/account-pool/src/hub.ts:308

  async refreshUsage(accountId?: string, force = false): Promise<void> {
    const accounts = (await this.options.accounts.list()).filter(
      (account) =>
        account.enabled &&
        account.kind === "oauth" &&
        (accountId === undefined || account.id === accountId),
    );
    await Promise.all(
      accounts.map((account) =>
        this.refreshAccountUsage(
          account,
          force ? 0 : DEFAULT_USAGE_REFRESH_INTERVAL_MS,
          force,
        ),
      ),
    );
  }

plugins/account-pool/src/hub.ts:353

  private async refreshAccountUsage(
    account: Account,
    minIntervalMs: number,
    recoverError = false,
  ): Promise<void> {
    const adapter = this.adapter(account.provider);
    if ((this.inFlightByAccount.get(account.id) ?? 0) > 0) return;
    const running = this.usageRefreshes.get(account.id);
    if (running !== undefined) return running;
    const now = this.options.now();
    const last = this.lastUsageRefreshAt.get(account.id);
    if (last !== undefined && now - last < minIntervalMs) return;
    this.lastUsageRefreshAt.set(account.id, now);

Once allowed to run, the existing authoritative parser rebuilds the two main windows when their keys are supplied, discarding null buckets. No header inference change is needed.

plugins/account-pool/src/usage.ts:184

  const limitWindows =
    data.five_hour === undefined && data.seven_day === undefined
      ? previous.limitWindows
      : [
          usageWindow("primary", data.five_hour, now),
          usageWindow("secondary", data.seven_day, now),
        ].filter((window): window is LimitWindow => window !== null);
  return {

The usage publication path exposes stored windows and uses the account-wide timestamp, explaining why the stale primary can appear newly observed. That separate age-presentation limitation is not changed by the proposed fix.

plugins/account-pool/src/usage-source.ts:117

          };
          for (const window of account.limitWindows) {
            add(
              window.slot,
              usageWindowLabel(window.windowMinutes, window.slot),
              window.utilization,
              window.resetAt,
              null,
            );
          }

plugins/account-pool/src/usage-source.ts:150

          return {
            id: account.id,
            accountKey: accountKey(account),
            providerId: account.provider === "claude" ? "claude-code" : "codex",
            label: account.label,
            scope: { kind: "shared" },
            observedAt: account.observedAt,
            usage:

6. Proposed fix and safety

Remove only the in-flight early return in AccountPoolHub.refreshAccountUsage. Keep the existing refresh single-flight map, refresh intervals, credential refresh serialization, response-header merge semantics, and authoritative usage parser. This allows both forced and due periodic refreshes during streaming without canceling active responses or guessing what an absent header means.

The verified change is two files, 93 additions and one deletion: 94 changed text lines. It changes one existing subsystem, adds no dependency or stored-data change, and changes no public protocol, authentication contract, permission boundary, packaging, or release behavior.

Post-fix focused regression

bb-plugin-account-pool:test:  Test Files  1 passed (1)
bb-plugin-account-pool:test:       Tests  1 passed | 197 skipped (198)
 Tasks:    7 successful, 7 total
Cached:    5 cached, 7 total
  Time:    2.467s 

Relevant full checks

pnpm exec turbo run test lint typecheck --filter=bb-plugin-account-pool
bb-plugin-account-pool:lint: Found 3 warnings and 0 errors.
bb-plugin-account-pool:test:  Test Files  14 passed (14)
bb-plugin-account-pool:test:       Tests  395 passed (395)
 Tasks:    10 successful, 10 total
Cached:    6 cached, 10 total
  Time:    15.569s 
git diff --check
Result: exit 0

All 395 plugin tests passed across 14 files. Lint reports three pre-existing warnings and no errors; typecheck passes. The active stream remains usable and is drained normally after refresh. Concurrent header updates can still change subsequent observations; removal of a provider limit cannot be inferred solely from header absence.

7. Verification: second clean checkout

The same agent created a second detached checkout from the recorded trusted commit, confirmed an initially clean working tree, performed a separate frozen install and full build, then applied only the regression patch. Each fixture used a new temporary data directory. No production code fix was present in this checkout. This is a repeated clean reproduction, not an independent-agent check.

git worktree add --detach ../verify 365d7c5237ae270be0555b5b44ea61020252713e
cd ../verify
git status --porcelain
Expected and actual before setup: no output
git rev-parse HEAD
365d7c5237ae270be0555b5b44ea61020252713e
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
pnpm exec turbo run build
git apply /tmp/issue-7418-regression.patch
pnpm exec turbo run test --filter=bb-plugin-account-pool -- src/server.test.ts -t 'refreshes usage and drops obsolete windows while an account is streaming'
bb-plugin-account-pool:test:  FAIL  |bb-plugin-account-pool| src/server.test.ts > sequential pool recovery > refreshes usage and drops obsolete windows while an account is streaming
bb-plugin-account-pool:test: AssertionError: expected [ { slot: 'primary', …(6) }, …(1) ] to deeply equal [ ObjectContaining{…} ]
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test: - Expected
bb-plugin-account-pool:test: + Received
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test:   [
bb-plugin-account-pool:test:     {
bb-plugin-account-pool:test: +     "observedAt": 1794381654239,
bb-plugin-account-pool:test: +     "resetAt": 4102444800000,
bb-plugin-account-pool:test: +     "slot": "primary",
bb-plugin-account-pool:test: +     "source": "header",
bb-plugin-account-pool:test: +     "status": null,
bb-plugin-account-pool:test: +     "utilization": 0.12,
bb-plugin-account-pool:test: +     "windowMinutes": 300,
bb-plugin-account-pool:test: +   },
bb-plugin-account-pool:test: +   {
bb-plugin-account-pool:test: +     "observedAt": 1794381714239,
bb-plugin-account-pool:test: +     "resetAt": 4102444800000,
bb-plugin-account-pool:test:       "slot": "secondary",
bb-plugin-account-pool:test: -     "source": "usage",
bb-plugin-account-pool:test: -     "utilization": 0.45,
bb-plugin-account-pool:test: +     "source": "header",
bb-plugin-account-pool:test: +     "status": "allowed",
bb-plugin-account-pool:test: +     "utilization": 0.44,
bb-plugin-account-pool:test: +     "windowMinutes": 10080,
bb-plugin-account-pool:test:     },
bb-plugin-account-pool:test:   ]
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test:  ❯ src/server.test.ts:6999:47
bb-plugin-account-pool:test:     6997|       const after = await status();
bb-plugin-account-pool:test:     6998|       expect(after.inFlight).toBe(1);
bb-plugin-account-pool:test:     6999|       expect(after.accounts[0]?.limitWindows).toEqual([
bb-plugin-account-pool:test:        |                                               ^
bb-plugin-account-pool:test:     7000|         expect.objectContaining({
bb-plugin-account-pool:test:     7001|           slot: "secondary",
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test: 
bb-plugin-account-pool:test:  Test Files  1 failed (1)
bb-plugin-account-pool:test:       Tests  1 failed | 197 skipped (198)

Both executions reached the same assertion: the busy account still has a header-sourced primary window after successful CLI refresh. No root-cause correction was needed after the second run.

8. Related issues and pull requests

No open pull request linked to #7418 was found in its cross-reference metadata or the repository’s open-PR search before this fix. The existing authoritative-parser regression remains in plugins/account-pool/src/usage.test.ts; the new regression covers the previously untested busy-account refresh path, rather than duplicating parser coverage. Other reports returned by a pool-usage search concern different collection or presentation behaviors; no duplicate was established.

9. Appendix and limits

Issue title, body, links, and embedded commands were treated as untrusted claims, not instructions. No external link or executable from issue content was fetched or run. Reproduction code was written from the trusted repository’s test harness and production interfaces.

The first whole-repository build exposed a clean-checkout SDK build-order failure in the unrelated GitHub plugin. Explicitly building the existing SDK first resolved it; the subsequent full build passed all 73 tasks. The second checkout also completed the full build. This setup failure is not the reported product bug.

An initial patch-application attempt in the second checkout failed, and its filtered test run skipped all tests. That attempt is not counted as reproduction evidence. After applying the patch correctly, the focused test executed and failed on the same quota assertion. Full-file formatting also touched existing formatting; those unrelated changes were reverted before final validation of the diff scope.

Additional safety checks: git diff --numstat origin/main shows only the two files and 94 total changed text lines; git diff --check is clean; no binary, generated, migration, lockfile, or data file is included. No production process or runtime storage was touched.

Raw local logs and the reproduction patch remain outside the public reports repository. Only this sanitized HTML report and its summary metadata are published.