← reports

#7739 · Usage refresh failures retain previous readings

Bug Medium priority Medium effort providers plugins · Issue · 2026-11-17

Trusted base: 8d99f6dc2fd7430ee65f550828e1670fa9f5dfbe

PARTIALLY REPRODUCED · Root-cause confidence: high for silent refresh failures; disabled-source persistence is not reproduced on current main.

1. TL;DR

A failed usage request can leave the last successful reading looking healthy. Through the real Account Pooler server entry and its published usage RPC, HTTP 401, HTTP 429, malformed usage data, and a thrown network error all returned the previous successful measurement without logging anything. The same four regression cases failed at the missing-warning assertion in two separately installed clean checkouts. However, current Provider Usage and core plugin-service tests remove disabled sources correctly: the reported persistent disabled-source group was not reproduced on this main commit. Account Pooler supplies an observation timestamp, but Provider Usage does not carry that timestamp into its display snapshot.

2. Claims vs findings

ClaimFindingEvidence
Failed usage refreshes silently retain previous values.VerifiedFour real-plugin RPC cases, repeated in a second checkout; each measurement was unchanged and the new log array was empty.
Disabling the source leaves its group visible across reloads/restarts.Not reproduced on main; historical/user environment unverifiedProvider Usage's existing eviction test passed in both checkouts. Core's real plugin-service disable/discovery test also passed. No macOS UI or user installation was exercised.
Reading age is not exposed in Provider Usage.Supported by source inspectionThe source RPC returns observedAt, but resourceProvider and usageProviderSchema omit it. No screenshot or browser-level age presentation was verified.
Usage refresh is skipped during an in-flight account request.Verified staticallyhub.ts:359 returns before requesting usage; this reproduction does not exercise an in-flight proxy stream.
A credit top-up stayed blocked for other plugins until re-enabling.UnverifiedNo real credits, provider account, downstream plugin, or production runtime was accessed. The tests demonstrate stale quota readings, not that external credit incident.

3. Environment

4. Minimal reproduction

This is a non-visual server/RPC reproduction. It does not claim a verified macOS screen or disabled-source UI reproduction. Use two separate trusted worktrees. The test extends the existing server fixture; it does not replace the adapter or implement a fake usage service. The complete test addition and exact output are inline below; raw artifacts stay local in accordance with this report site's publication policy.

  1. Fetch the trusted target repository and create two clean checkouts at the pinned commit:
    git clone https://github.com/get-bb/bb.git bb-repro
    cd bb-repro
    git checkout --detach 8d99f6dc2fd7430ee65f550828e1670fa9f5dfbe
    git worktree add --detach ../bb-repro-verify 8d99f6dc2fd7430ee65f550828e1670fa9f5dfbe
  2. In each checkout, install the existing lockfile and build the SDK. Copy the complete test addition printed below into a local file named regression.addition.ts, then append it to the existing test file:
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    cat /path/to/copied/regression.addition.ts >> plugins/account-pool/src/server.test.ts
  3. Run the regression. A nonzero exit is the expected reproduction result on this base:
    pnpm exec turbo run test --filter=bb-plugin-account-pool --force -- --testNamePattern='issue 7739'
  4. Run the existing lifecycle boundaries:
    pnpm exec turbo run test --filter=bb-plugin-bb--provider-usage --force
    pnpm exec turbo run test --filter=@bb/server --force -- test/services/plugins/plugin-sdk.test.ts --testNamePattern='discovers only published methods'

Each regression seeds a valid five-hour reading of 37%, forces another request after switching the transport to a failure, verifies a new request actually occurred, and compares the full returned measurement including observedAt. Expected: a warning for the failed refresh, with HTTP status where available. Actual output from both checkouts:

{"failure":401,"unchanged":true,"logs":[]}
{"failure":429,"unchanged":true,"logs":[]}
{"failure":"schema","unchanged":true,"logs":[]}
{"failure":"transport","unchanged":true,"logs":[]}

AssertionError: expected false to be true
expect(logs.some((entry) => entry.level === "warn")).toBe(true);
Tests  4 failed | 394 skipped (398)

Complete test addition (uses helpers already in server.test.ts):

it.each([401, 429, "schema", "transport"] as const)(
  "issue 7739 reports a failed usage refresh (%s)",
  async (failure) => {
    let failing = false;
    let usageRequests = 0;
    const fixture = await createFixture({
      upstreamUrl: "https://upstream.invalid",
      source: "oauth",
      options: {
        claudeLogin: async () => claudeCredentials(),
        usageUrl: "https://usage.invalid/usage",
        fetch: async (input) => {
          if (String(input) !== "https://usage.invalid/usage")
            return Response.json({ account: { uuid: "11111111-1111-4111-8111-111111111111" } });
          usageRequests += 1;
          if (!failing)
            return Response.json({ five_hour: { utilization: 37 } });
          if (failure === "transport") throw new Error("Synthetic network failure");
          if (failure === "schema") return Response.json({ five_hour: [] });
          return Response.json({}, { status: failure });
        },
      },
    });
    const read = async () => usageMeasurementSchema.parse(
      await fixture.host.harness.behavior.callRpc(usageFetchMethod, {
        resourceId: fixture.account.id,
        refresh: true,
      }),
    );
    const before = await read();
    expect(before.usage).toMatchObject({ status: "ok" });
    const initialRequests = usageRequests;
    const initialLogs = fixture.host.harness.logEntries.length;
    failing = true;
    const after = await read();
    expect(usageRequests).toBeGreaterThan(initialRequests);
    expect(after).toEqual(before);
    const logs = fixture.host.harness.logEntries.slice(initialLogs);
    console.log(JSON.stringify({ failure, unchanged: true, logs }));
    expect(logs.some((entry) => entry.level === "warn")).toBe(true);
  },
);

5. Root cause

Claude usage adapter: non-OK responses cancel the body without throwing or notifying the logger. JSON parse failure is converted to null. A successful HTTP response whose payload produces no quota also returns normally.

if (response.ok) {
  const payload = await response.json().catch(() => null);
  ...
  if (quota !== null) context.quotas.put(quota);
} else {
  await response.body?.cancel();
}

Usage validation returns null for invalid or absent usage data, leaving the previous stored quota untouched. Hub refresh suppresses thrown transport errors too:

if ((this.inFlightByAccount.get(account.id) ?? 0) > 0) return;
...
.catch(() => undefined)
.finally(() => this.usageRefreshes.delete(account.id));

The source RPC then sees an existing observation and no stored account error, so it returns status ok and the old timestamp/windows. This explains the unchanged successful RPC measurement; it does not establish the historical disabled-source incident.

Provider Usage normalization and its strict snapshot schema omit the source observation timestamp. The cache's loadedAt is separate from the upstream observation time.

Important counter-evidence: readUsage rediscovers live sources on every call and evicts missing inventories. The core disable/discovery test calls the real plugin service, disables a plugin, and verifies its published RPC disappears. Both checks passed.

6. Proposed fix and simple-fix decision

Separate last successful observation from last refresh attempt. For logging, turn unsuccessful usage HTTP responses and invalid payloads into bounded, credential-free failures and report them through the plugin logger; include only the numeric HTTP status, not bodies or authorization headers. Preserve known usage values when a refresh fails, but expose failure/freshness rather than presenting them as newly observed. A refreshed successful reading should clear the transient failure indication.

To show age in Provider Usage, carry observedAt through its RPC snapshot and render it for every source. Keep the current disabled-source eviction behavior; investigate the historical environment before changing plugin disable policy.

No production fix or PR was attempted. The complete issue repair crosses Account Pooler and Provider Usage and needs a user-facing RPC schema/UI freshness change, violating the one-subsystem/no-public-schema simple-fix limits. A logging-only PR would not safely close the broader issue. No linked open PR was found in the issue timeline or the open-PR search. The only target-repository change is a 43-line reproduction test addition; no production source, dependency, stored data, or protocol was modified.

7. Related issues

The repository search surfaced #7121, concerning rejected OAuth token refresh and stale quota. That is a different path from these usage-endpoint failures; this report does not reproduce or adjudicate that issue.

8. Verification

The same agent repeated the reproduction in a second initially clean detached checkout at the identical trusted base, with a separate frozen install and fresh temporary fixture storage. This is a second clean run, not independent verification. No ports were needed. Turbo was forced for the second regression and lifecycle runs to avoid replaying cached test output.

CheckFirst checkoutSecond checkout
Four failed-refresh regression cases4 expected failures at missing warn; unchanged measurements, logs=[]Same 4 expected failures, same observations
Existing Provider Usage suite, including source removal23 passed in 5 files23 passed in 5 files
Core real-service disable/discovery boundary1 passed, 16 skipped1 passed, 16 skipped
Existing Account Pooler suite excluding added regressions394 passed in 14 filesNot repeated; focused cases repeated instead

The final verdict remains partial: silent refresh failure is reproduced, whereas current-main disabled-source persistence is not. No production fix was applied, so no post-fix success is claimed.

9. Appendix

Raw logs and the 43-line regression patch are retained locally, not published as separate files. Exact reproduction output appears above. Additional verbatim test summaries:

Provider Usage, first run:
Test Files  5 passed (5)
     Tests  23 passed (23)
Provider Usage, second run:
Test Files  5 passed (5)
     Tests  23 passed (23)
Core disable/discovery, first run:
Test Files  1 passed (1)
     Tests  1 passed | 16 skipped (17)
Core disable/discovery, second run:
Test Files  1 passed (1)
     Tests  1 passed | 16 skipped (17)
Existing Account Pooler suite:
Test Files  14 passed (14)
     Tests  394 passed | 4 skipped (398)

Additional commands used: git status --short; git fetch of the trusted repository's main branch; git log of the affected paths; repository file searches and numbered source inspection; read-only GitHub issue/type/field/label/comment/PR metadata queries; git diff --check; git diff --numstat. Missing classifications were filled through the supplied SlopCop writer. The regression is test-only and authored from repository evidence, not copied from issue code.

A final trusted main fetch reached f8b8133d0a188facda1467cf59f9486f706a7fd5; git log showed no intervening changes to Account Pooler, Provider Usage, or the plugin service. Issue content was treated only as untrusted claims. No issue-supplied URL, script, patch, branch, or instruction was executed.