#6669 · Usage throttling has no shared cooldown
Verdict: REPRODUCED · Root-cause confidence: high · label: confirmed-repro
1. TL;DR
Claude usage checks can repeatedly fail even while other provider functionality remains usable. In deterministic tests against main, two immediate reads both contact a synthetic endpoint despite its 300-second Retry-After header. The server also makes two host probes for two sequential error reads, and the provider-owned resource makes a third collection immediately after caching a failure. A prior successful 42% usage window disappears from that resource response while its last-success timestamp survives. These observations establish the missing cooldown and lost resource data; they do not establish how Anthropic dynamically extends throttling in production.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Server failures do not share a cache lifetime. | Verified | Two public API reads yield two host usage probes; assertion expects one. |
| Claude ignores upstream retry timing. | Verified | Two direct provider calls immediately perform two fetches after a synthetic 429 with Retry-After: 300. |
| The provider resource drops previously good windows and retries errors. | Verified | Good read, forced failed read, ordinary read: three collections; error response keeps observedAt but contains neither windows nor a last-good measurement. |
| Usage snapshots are cached for only ten seconds at the server and sixty seconds at the resource. | Verified by source | TTL expressions below; only the resource's successful-result gate is needed for the reproduction. |
| The bundled display can retain a stale snapshot. | Verified by source, not UI exercised | The aggregate plugin retains successful values separately; this is not an SDK-wide guarantee. |
| Reported macOS incidence, polling frequencies, CLI version behavior, and prolonged upstream throttling. | Unverified | No real credentials, production instance, macOS host, or third-party CLI were used. Rate-limit prolongation is a plausible consequence, not demonstrated. |
3. Environment
- Trusted target: public get-bb/bb, origin/main at
9662c45478f4a74f33f11b70187657d97f1e14a7, fetched on 2026-10-30. - Linux x86_64 (gVisor 4.19.0), Node v22.19.0, pnpm 9.15.0, Vitest 4.1.1.
- Bundled provider package: bb-plugin-provider-claude-code 0.1.0; plugin SDK 0.6.105. No external Claude binary is executed.
- Two separate detached worktrees, named base and verify, at the same trusted commit. Only the two authored reproduction files were added; production code remained unchanged.
- All credentials and network responses are synthetic. Plugin tests stub credential reads, child processes, and fetch. Server tests use the real migrated SQLite harness, a new mkdtemp data directory per run, and in-process app requests; no HTTP listeners, dev server, or user runtime data are involved.
- Frozen installs succeeded in both checkouts. Initial broad build failed because an unrelated plugin build raced the SDK runtime output. A targeted Turbo SDK build succeeded, and all reproduction commands reached their intended assertions. Existing focused suites passed.
4. Minimal reproduction
- Start from the exact trusted commit and install/build through Turbo.
- Copy the two linked reproduction artifacts into their respective package test directories.
- Run both focused commands. They intentionally exit 1 on the unchanged code.
git clone https://github.com/get-bb/bb.git bb-6669 cd bb-6669 git checkout --detach 9662c45478f4a74f33f11b70187657d97f1e14a7 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk curl --fail -o plugins/provider-claude-code/src/issue-6669-repro.test.ts https://get-bb.github.io/reports/issues/6669/repro/plugin-repro.test.ts curl --fail -o apps/server/test/public/issue-6669-repro.test.ts https://get-bb.github.io/reports/issues/6669/repro/server-repro.test.ts pnpm exec turbo run test --filter=bb-plugin-provider-claude-code -- src/issue-6669-repro.test.ts pnpm exec turbo run test --filter=@bb/server -- test/public/issue-6669-repro.test.ts
Expected: a sequential read during a cooldown reuses the failure instead of probing upstream again. A last-successful usage snapshot should remain available to readers with explicit stale/error semantics rather than masquerading as current success.
Actual, both checkouts:
provider fetches: expected 1, received 2 resource collections after good / forced-error / ordinary read: expected 2, received 3 server host probes for two sequential ordinary error reads: expected 1, received 2 good resource: usage.status = ok, windows[0].usedPercent = 42 failed resource: usage.status = error, observedAt unchanged, no windows or last-good snapshot
Verbatim assertion output:
AssertionError: expected "vi.fn()" to be called 1 times, but got 2 times AssertionError: expected "vi.fn()" to be called 2 times, but got 3 times AssertionError: expected 2 to be 1 // Object.is equality
Provider and resource reproduction
import { afterEach, expect, it, vi } from "vitest";
import {
createFakePluginHost,
makeHostResponse,
} from "@get-bb/plugin-sdk/testing";
vi.mock("node:child_process", () => ({
execFile: (
_file: string,
_args: readonly string[],
_options: object,
callback: (
error: Error | null,
result: { stdout: string; stderr: string },
) => void,
) => callback(null, { stdout: "", stderr: "" }),
}));
vi.mock("node:fs/promises", () => ({
default: {
readFile: (file: string) =>
Promise.resolve(
JSON.stringify(
file.endsWith(".credentials.json")
? {
claudeAiOauth: {
accessToken: "test-access-token",
expiresAt: null,
subscriptionType: "pro",
},
}
: { oauthAccount: { emailAddress: null } },
),
),
},
}));
vi.mock("@get-bb/plugin-sdk/provider-bridge", async (importOriginal) => ({
...(await importOriginal<
typeof import("@get-bb/plugin-sdk/provider-bridge")
>()),
experimental_resolveExecutablePath: () => Promise.resolve("/test/claude"),
}));
import { getClaudeProviderUsage } from "./bridge/provider-maintenance.js";
import { registerUsageSource } from "./usage-source.js";
import { usageFetchMethod, usageMeasurementSchema } from "./usage-contract.js";
afterEach(() => vi.unstubAllGlobals());
it("honors a throttled response before attempting another upstream request", async () => {
const fetchUsage = vi.fn(
async () =>
new Response("", { status: 429, headers: { "Retry-After": "300" } }),
);
vi.stubGlobal("fetch", fetchUsage);
const first = await getClaudeProviderUsage();
const second = await getClaudeProviderUsage();
console.log(
"throttled probes",
JSON.stringify({
first,
second,
upstreamRequests: fetchUsage.mock.calls.length,
}),
);
expect(first).toMatchObject({ supported: true, usage: { status: "error" } });
expect(fetchUsage).toHaveBeenCalledTimes(1);
});
it("records what the usage resource exposes after a successful read followed by an error", async () => {
const collect = vi
.fn()
.mockResolvedValueOnce({
"claude-code": {
status: "ok",
accountEmail: null,
planLabel: "Pro",
windows: [{ label: "Weekly", usedPercent: 42, resetsAt: null }],
},
})
.mockResolvedValue({
"claude-code": {
status: "error",
accountEmail: null,
planLabel: "Pro",
message: "synthetic throttling",
},
});
const { bb, harness } = createFakePluginHost({
sdk: {
hosts: {
get: async ({ hostId }) =>
makeHostResponse({ id: hostId, status: "connected" }),
},
providers: {
list: async () => [
{
id: "claude-code",
pluginId: "provider-claude-code",
displayName: "Claude",
},
],
},
system: { usageLimits: collect },
},
});
try {
registerUsageSource(bb);
const read = async (refresh: boolean) =>
usageMeasurementSchema.parse(
await harness.behavior.callRpc(usageFetchMethod, {
resourceId: JSON.stringify(["test-host", "claude-code"]),
refresh,
}),
);
const good = await read(false);
const failed = await read(true);
const repeated = await read(false);
console.log(
"resource reads",
JSON.stringify({
good,
failed,
repeated,
collections: collect.mock.calls.length,
}),
);
expect(good.usage).toMatchObject({
status: "ok",
windows: [{ usedPercent: 42 }],
});
expect(failed.observedAt).toBe(good.observedAt);
expect(failed.usage).toMatchObject({ status: "error" });
expect(failed.usage).not.toHaveProperty("windows");
expect(collect).toHaveBeenCalledTimes(2);
} finally {
await harness.lifecycle.dispose();
}
});
Server API reproduction
import { expect, it } from "vitest";
import { registerHostRpcResponder } from "../helpers/host-rpc.js";
import { seedHostSession } from "../helpers/seed.js";
import { withTestHarness } from "../helpers/test-app.js";
it("shares a usage failure across sequential non-refresh readers", async () => {
await withTestHarness(async (harness) => {
const { host, session } = seedHostSession(harness.deps, {
id: "throttled-usage",
});
let probes = 0;
const responder = registerHostRpcResponder(harness, {
hostId: host.id,
sessionId: session.id,
handle(request) {
if (request.command.type === "provider.usage") {
probes += 1;
return {
ok: true,
result: {
supported: true,
usage: {
status: "error",
message: "synthetic throttling",
accountEmail: null,
planLabel: null,
},
},
};
}
if (request.command.type === "provider.health") {
return {
ok: true,
result: {
supported: true,
health: {
status: "not_installed",
statusMessage: null,
accountEmail: null,
planLabel: null,
installedVersion: null,
minimumSupportedVersion: null,
canInstall: false,
canUpdate: false,
loginCommand: null,
},
},
};
}
throw new Error(`Unexpected command ${request.command.type}`);
},
});
try {
const url = `/api/v1/system/usage-limits?hostId=${host.id}&providerId=claude-code`;
const first = await harness.app.request(url);
const second = await harness.app.request(url);
expect(first.status).toBe(200);
expect(second.status).toBe(200);
console.log(
"server readers",
JSON.stringify({
first: await first.json(),
second: await second.json(),
probes,
}),
);
expect(probes).toBe(1);
} finally {
responder.unregister();
}
});
});
5. Root cause
No retry deadline at the provider boundary
The provider always fetches after resolving credentials. A 429 becomes a generic error message: the response headers are not inspected and no retry state is stored. This alone permits back-to-back requests.
plugins/provider-claude-code/src/bridge/provider-maintenance.ts:527
return { supported: true, usage: { status: "expired" } };
}
const known = { planLabel: planLabel(credentials), accountEmail: email };
try {
const response = await fetch(CLAUDE_USAGE_URL, {
headers: {
Authorization: `Bearer ${credentials.accessToken}`,
Accept: "application/json",
"Content-Type": "application/json",
"anthropic-beta": "oauth-2025-04-20",
"User-Agent": "claude-code/2.1.0",
},
signal: AbortSignal.timeout(USAGE_FETCH_TIMEOUT_MS),
});
if (response.status === 401) {
return { supported: true, usage: { status: "expired" } };
}
if (!response.ok) {
return {
supported: true,
usage: {
status: "error",
message:
response.status === 429
? "Anthropic temporarily throttled this usage check. This does not mean your Claude limit is exhausted. Try again later."
: `Claude usage request failed (HTTP ${response.status}).`,
...known,
},
};
}
return {
supported: true,
usage: {
...normalizeUsage(await response.json(), credentials, email),
The server deliberately gives errors zero TTL
The server coalesces concurrent calls, but an error gets zero lifetime. Therefore sequential readers start a new host RPC. Importantly, an existing server test explicitly enshrines immediate retry for generic errors: blindly increasing every error TTL would change that behavior rather than selectively handling throttling.
apps/server/src/services/system/usage-limits.ts:18
type UsageResult = HostDaemonOnlineRpcResult<"provider.usage">;
const usageCaches = new WeakMap<object, AsyncTtlMemo<string, UsageResult>>();
function providerUsageCache(deps: AppDeps) {
let cache = usageCaches.get(deps.db);
if (!cache) {
cache = createAsyncTtlMemo<string, UsageResult>({
maxEntries: 1_024,
ttlMs: (result) =>
result.supported && result.usage.status === "error" ? 0 : 10_000,
});
Existing generic-error recovery test
Successful-only caching overwrites the last good resource measurement
The provider resource reuses a cached value only when status is ok. It sets observedAt to the previous success time on failure, then replaces the same cache entry with the error. Its error schema has no windows or explicit stale-measurement field. A timestamp without the matching value cannot reconstruct the last successful limits.
plugins/provider-claude-code/src/usage-source.ts:66
if (
!refresh &&
previous?.usage.status === "ok" &&
previous.observedAt !== null &&
Date.now() - previous.observedAt < 60_000
)
return previous;
const promise = (async () => {
try {
const result = await bb.sdk.system.usageLimits({
hostId,
providerId,
refresh,
});
const usage = result[providerId];
if (!usage) throw new Error("Provider returned no usage information.");
const metadata = metadataSchema.parse(usage);
const value = usageMeasurementSchema.parse({
accountKey: metadata.accountKey,
observedAt:
usage.status === "ok" ? Date.now() : (previous?.observedAt ?? null),
usage: {
accountEmail: null,
planLabel: null,
...usage,
plan: metadata.plan,
...(usage.status === "ok"
? {
windows: usage.windows.map((window, index) => ({
...window,
...windowMetadataSchema.parse(window),
id: `${index}:${window.label}`,
cost: window.cost ?? null,
})),
}
: {}),
},
});
cache.set(resourceId, value);
plugins/provider-claude-code/src/usage-contract.ts:42
const usageSchema = z.discriminatedUnion("status", [
z.object({
status: z.literal("ok"),
...accountFields,
windows: z.array(usageWindowSchema),
}),
z.object({ status: z.literal("not_installed"), ...accountFields }),
z.object({ status: z.literal("unauthenticated"), ...accountFields }),
z.object({ status: z.literal("expired"), ...accountFields }),
z.object({
status: z.literal("error"),
...accountFields,
message: z.string(),
}),
]);
export const usageAccountKeySchema = z
.string()
.min(1)
.nullable()
The aggregate Provider usage plugin has a separate stale-value policy; that does not preserve results for direct system or resource consumers. Aggregate resource collection.
6. Proposed fix and simple-fix gate
A complete repair should distinguish retryable throttling from ordinary failures, bound and share a retry deadline by the correct host/provider/account identity, and preserve last-successful windows with an explicit stale age. Specify whether forced refresh can bypass cooldown, how account changes invalidate cached data, how Retry-After seconds and dates are parsed, and how malformed or missing headers fall back. Keep genuine fresh errors distinguishable from stale successful values.
No automatic PR: the verified full defect spans the provider bridge, server cache, and public resource contract. The typed provider error exposes no retry deadline; the resource error schema exposes no last-good value. Implementing explicit stale results and shared selective cooldown requires contract/semantics and product-policy decisions, which are outside the rule's simple-fix allowance. A generic error TTL alone would leave retry timing and lost data unfixed and would contradict the existing recovery test.
Provider usage wire contract. No production fix, dependency, schema change, branch, commit, or PR was made in get-bb/bb.
7. Verification
The same agent repeated the two exact commands in a second clean detached checkout at 9662c45478f4a74f33f11b70187657d97f1e14a7, after a separate frozen install and SDK build. A fresh SQLite harness/data directory was used; the reproduction needs no listening ports. Both provider assertions again failed on counts 2 versus 1 and 3 versus 2, and the server assertion again failed on 2 versus 1. Both resource outputs retained observedAt while dropping windows. This is a clean repeat, not independent verification. No behavioral report correction was needed.
Control checks on unchanged production code: the existing provider credential/resource suites passed (6 tests), and the existing public system usage suite passed. See exact totals in the logs.
8. Related issues and pull requests
No linked open pull request appeared in the issue's cross-reference timeline or the open-PR search for issue 6669 at investigation time. Related feature scope: #6153; it is not evidence of a fix for this defect. No pull-request code was checked out or run.
9. Appendix
- base-plugin-repro.log
- base-server-repro.log
- verify-plugin-repro.log
- verify-server-repro.log
- existing-plugin-tests.log
- existing-server-tests.log
Control commands:
pnpm exec turbo run test --filter=bb-plugin-provider-claude-code -- src/bridge/provider-maintenance.credentials.test.ts src/usage-source.test.ts pnpm exec turbo run test --filter=@bb/server -- test/public/public-system-usage-limits.test.ts git diff --check
All issue content was treated as untrusted claims. No issue-supplied script, patch, branch, binary or external link was executed or fetched. Reproduction artifacts were authored from trusted repository code. No live Anthropic request was sent. No visual screenshot is needed for these nonvisual boundary tests.
> AGENT GENERATED