← reports

#7417 · Cached usage hides a rejected pooled login

BugMedium priorityMedium effortprovidersGitHub issue

2026-11-11 · trusted main 365d7c5237ae270be0555b5b44ea61020252713e

Verdict: REPRODUCED · Root-cause confidence: high · Label: confirmed-repro

1. TL;DR

A pooled account can have a confirmed rejected OAuth refresh while Provider usage still returns its last successful usage as an ordinary healthy row. A deterministic integration test creates two synthetic Claude accounts, successfully measures both, advances one beyond expiry, and injects an HTTP 400 OAuth rejection through the real pool's transport seam. The real Account Pooler hub records the rejection, its real usage source collapses it to a generic collection error, and the real Provider usage server throws away that result while keeping the old measurement. The resulting group-wide warning cannot identify the account. The same agent repeated the test in a second clean checkout; both fail the intended row-status assertion in the same way.

2. Claims vs findings

ClaimFindingEvidence
The pool knows the account has a rejected login.Verified with synthetic transportReal hub error: OAuth refresh failed with HTTP 400. invalid_grant: Refresh token expired.; 1 refresh attempt.
The usage source loses the authentication classification.VerifiedSource returns status: error, not expired, even though the hub error is an OAuth rejection.
The failed row remains healthy and the warning is group-wide.Verified at RPC boundaryRejected and healthy rows both remain ok; only the machine/group error changes.
The displayed notice is generic and the old percentages remain.Verified by production component server renderingAfter-render HTML contains the refresh warning and 42% usage values, not a sign-in-again message. This is unstyled server rendering, not a browser screenshot.
A real user's token expired, and the warning also appears on a Codex tab.Not independently exercisedNo live credentials were read or used. The fixture contains two Claude accounts; group-level error propagation explains the cross-tab risk, but Codex tab interactions were not run.

3. Environment

4. Minimal reproduction

  1. Use a clean checkout of get-bb/bb at the recorded commit. Install existing dependencies and build the SDK:
    git checkout 365d7c5237ae270be0555b5b44ea61020252713e
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build build:types --filter=@get-bb/plugin-sdk
  2. Save the complete test below as plugins/provider-usage/issue-7417.test.tsx.
  3. Run the regression. An exit status of 1 from the final status assertion is the expected evidence on unfixed main:
    REPRO_ARTIFACT_DIR="$(mktemp -d)" pnpm exec turbo run test --env-mode=loose --filter=bb-plugin-bb--provider-usage -- issue-7417.test.tsx
    The environment flag allows the optional evidence directory through Turbo's environment filtering. Omit the environment variable to test only the server behavior without rendering artifacts.

Expected result: only the rejected account is expired, the healthy account stays ok, and the group has no refresh error.

Actual result in both runs:

{
  "sourceStatus": "error",
  "rejectedRowStatus": "ok",
  "healthyRowStatus": "ok",
  "groupError": "Some usage could not be refreshed."
}

The test runner reports:

AssertionError: expected { sourceStatus: 'error', …(3) } to deeply equal { sourceStatus: 'expired', …(3) }
Test Files  1 failed (1)
Tests       1 failed (1)

Actual server-rendered notice:

Couldn’t refresh. Showing last update.

Screenshot limitation: Browser Automation local/headless could not open because Chrome/Chromium is absent on the host. No screenshot or interactive browser verification is claimed. The HTML rendering above is generated from the production component and actual regression snapshots, not a hand-built imitation.

Complete repeatable integration regression
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, it, vi } from "vitest";
import { createFakePluginHost } from "@get-bb/plugin-sdk/testing";
import { installTestPluginRuntime } from "@get-bb/plugin-sdk/testing/app";
import { accountPoolConfigSchema } from "../account-pool/src/contracts.js";
import { createHub } from "../account-pool/src/hub.js";
import {
  AccountStore,
  HubTokenStore,
  PoolAffinityStore,
  QUOTA_MIGRATIONS,
  QuotaStore,
} from "../account-pool/src/store.js";
import { registerUsageSource } from "../account-pool/src/usage-source.js";
import plugin from "./server.js";
import { ProviderUsageStatusContent } from "./app.js";
import { usageSnapshotSchema } from "./usage-schema.js";
import {
  usageFetchMethod,
  usageListMethod,
  usageSourceRpcContract,
} from "./usage-source-contract.js";

it("keeps a rejected pooled login on its own row instead of showing cached healthy usage", async () => {
  const dataDir = await fs.mkdtemp(path.join(os.tmpdir(), "pool-7417-"));
  const pool = createFakePluginHost({ pluginId: "account-pool", dataDir });
  const database = pool.bb.storage.database();
  pool.bb.storage.migrate(database, QUOTA_MIGRATIONS);
  const secretsDir = path.join(dataDir, "secrets");
  const accounts = new AccountStore(pool.bb.storage.kv, secretsDir);
  await accounts.initialize();
  let now = 1_800_000_000_000;
  const add = (label: string, ttl: number) =>
    accounts.add(
      {
        provider: "claude",
        kind: "oauth",
        label,
        email: `${label}@example.invalid`,
        accountUuid: null,
        subscriptionType: "pro",
        rateLimitTier: null,
        enabled: true,
        priority: 100,
      },
      {
        kind: "oauth",
        accessToken: `synthetic-access-${label}`,
        refreshToken: `synthetic-refresh-${label}`,
        expiresAt: now + ttl,
      },
    );
  const rejected = await add("rejected", 10 * 60_000);
  const healthy = await add("healthy", 60 * 60_000);
  let refreshAttempts = 0;
  const transport: typeof fetch = async (input) => {
    const destination = String(input);
    if (destination === "https://refresh.invalid/token") {
      refreshAttempts += 1;
      return Response.json(
        { error: "invalid_grant", error_description: "Refresh token expired" },
        { status: 400 },
      );
    }
    if (destination === "https://usage.invalid/usage")
      return Response.json({
        seven_day: {
          utilization: 42,
          resets_at: new Date(now + 7 * 86_400_000).toISOString(),
        },
      });
    throw new Error("Unexpected synthetic transport destination");
  };
  const hub = createHub({
    accounts,
    quotas: new QuotaStore(database),
    affinity: new PoolAffinityStore(database),
    hubTokens: new HubTokenStore(secretsDir, () => now),
    now: () => now,
    fetch: transport,
    getSettings: () => accountPoolConfigSchema.parse({}),
    refreshUrl: "https://refresh.invalid/token",
    usageUrl: "https://usage.invalid/usage",
  });
  registerUsageSource(pool.bb, hub);
  const usage = createFakePluginHost({
    pluginId: "provider-usage",
    sdk: {
      system: { config: async () => ({ primaryHostId: null }) },
      hosts: { list: async () => [] },
      providers: {
        list: async () => [
          { id: "claude-code", displayName: "Claude Code", logoUrl: null },
        ],
      },
      plugins: {
        experimental_discoverRpc: async () => [
          {
            pluginId: "account-pool",
            displayName: "Account Pooler",
            method: usageListMethod,
          },
        ],
        callRpc: async ({ method, input }) =>
          pool.harness.behavior.callRpc(method, input),
      },
    },
  });
  plugin(usage.bb);
  const read = async () =>
    usageSnapshotSchema.parse(
      await usage.harness.behavior.callRpc("getUsage", {
        force: true,
        machineIds: ["source:account-pool"],
        providerIds: ["claude-code"],
        maxAgeMs: 0,
      }),
    );
  try {
    const before = await read();
    expect(
      before.machines[0]?.providers.map((row) => row.usage?.status),
    ).toEqual(["ok", "ok"]);
    now += 12 * 60_000;
    const after = await read();
    const source = usageSourceRpcContract[usageFetchMethod].output.parse(
      await pool.harness.behavior.callRpc(usageFetchMethod, {
        resourceId: rejected.id,
        refresh: false,
      }),
    );
    const status = await hub.status();
    const rejectedStatus = status.accounts.find(
      (account) => account.id === rejected.id,
    );
    expect(refreshAttempts).toBeGreaterThan(0);
    expect(rejectedStatus?.error).toContain("invalid_grant");
    const artifactDir = process.env.REPRO_ARTIFACT_DIR;
    if (artifactDir) {
      vi.stubGlobal("__bbPluginRuntime", undefined);
      installTestPluginRuntime();
      await fs.mkdir(artifactDir, { recursive: true });
      await fs.writeFile(
        path.join(artifactDir, "snapshot.json"),
        JSON.stringify(
          {
            before,
            after,
            source,
            poolError: rejectedStatus?.error,
            refreshAttempts,
          },
          null,
          2,
        ),
      );
      for (const [stage, data] of [
        ["before", before],
        ["after", after],
      ] as const) {
        const markup = renderToStaticMarkup(
          <ProviderUsageStatusContent
            pluginId="provider-usage"
            dismiss={() => undefined}
            snapshot={{ data, error: null, isRefreshing: false }}
            threadMachineId={null}
            refreshEnabled={false}
          />,
        );
        await fs.writeFile(
          path.join(artifactDir, `${stage}.html`),
          `<!doctype html><html><head><meta charset="utf-8"><title>Account usage ${stage}</title></head><body><h1>Isolated production component: ${stage}</h1><p>Unstyled server rendering, synthetic OAuth transport and temporary account store; no live account.</p><main>${markup}</main></body></html>`,
        );
      }
    }
    expect({
      sourceStatus: source.usage.status,
      rejectedRowStatus: after.machines[0]?.providers.find((row) =>
        row.id.endsWith(rejected.id),
      )?.usage?.status,
      healthyRowStatus: after.machines[0]?.providers.find((row) =>
        row.id.endsWith(healthy.id),
      )?.usage?.status,
      groupError: after.machines[0]?.error,
    }).toEqual({
      sourceStatus: "expired",
      rejectedRowStatus: "expired",
      healthyRowStatus: "ok",
      groupError: null,
    });
  } finally {
    vi.unstubAllGlobals();
    await hub.stop();
    await usage.harness.lifecycle.dispose();
    await pool.harness.lifecycle.dispose();
    await fs.rm(dataDir, { recursive: true, force: true });
  }
});

5. Root cause

  1. The real pool records an OAuth refresh error through plugins/account-pool/src/hub.ts:1452. The source receives only the account's free-text error and maps every non-null error to one generic collection state at plugins/account-pool/src/usage-source.ts:143. This loses the authentication disposition before presentation.
  2. Provider usage interprets a valid per-account error state as a failed RPC refresh at plugins/provider-usage/server.ts:183:
    if (value.usage.status === "error")
      throw new Error("Usage could not be refreshed.");
    The new state is never stored; the previous healthy measurement stays in the cache.
  3. Failures are tracked per resource but projected onto the entire group's error field while cached usage is returned at plugins/provider-usage/server.ts:343. The sidebar turns that into generic stale-group feedback at plugins/provider-usage/app.tsx:612.
  4. The row already knows how to show expiredHint and source error text at plugins/provider-usage/app.tsx:329, but the source/server path prevents those states from reaching it. The contract at plugins/provider-usage/usage-source-contract.ts:126 explicitly treats authentication and collection failures as usage states.
  5. The panel RPC row schema at plugins/provider-usage/usage-schema.ts:16 has neither observation age nor a stale-values/error combination. Its error branch carries only a message, while windows exist only in the healthy branch.

6. Fix proposal and autopilot safety

Preserve a typed authentication disposition through Account Pooler's existing account/source boundary and emit the existing expired or unauthenticated usage state for a terminal login rejection. Do not infer this by matching arbitrary free-text errors. In Provider usage, distinguish source-reported account states from transport/inventory failures; keep the former attached to the row. Retaining previous windows for a non-authentication collection failure also requires an explicit stale/observation-time representation in the panel's RPC model and rendering.

No automatic PR: the complete repair spans two existing plugins and the requested stale-values/age presentation needs a panel RPC schema change. Both are outside the rule's simple-fix limits. Merely removing the throw would expose a generic error but would neither classify a rejected login nor preserve stale windows with an age. No production patch, commit, branch push, or PR was made.

7. Verification

The same agent ran the reproduction in two distinct checkouts at the recorded trusted commit. The first checkout was clean before adding the self-authored test. A second temporary detached worktree was created directly from trusted origin/main, installed with the frozen lockfile, and built with the same SDK commands. It had no production modifications; only the same test was added. Both runs used the command in section 4 and separate fresh temporary stores/artifact directories. Both reached the final assertion and observed the exact four-field result shown above; the healthy control account remained healthy.

During harness setup, Turbo initially filtered the optional artifact environment variable and the React test runtime initially needed installation. The published test uses --env-mode=loose for artifact capture, installs the SDK's test runtime, and restores globals. Final recorded failures are the intended row-status mismatch, not those setup failures. No root-cause correction was needed after the second clean run.

Existing focused suites also pass:

pnpm exec turbo run test --filter=bb-plugin-bb--provider-usage -- server.test.ts
Test Files  1 passed (1)
Tests       3 passed (3)

pnpm exec turbo run test --filter=bb-plugin-account-pool -- refresh-rejection.test.ts
Test Files  1 passed (1)
Tests       13 passed (13)

An initial repository-wide pnpm exec turbo run build was blocked by missing built SDK entries in unrelated plugin builds. The SDK's orchestrated runtime/type build then passed in each checkout, and all regression/focused-suite runs above completed. A full-repository build is not claimed.

8. PR and related-work check

The issue timeline contained no linked pull request, and a search of open PR metadata for issue 7417 returned none. No linked code or branch was checked out or executed. Existing transport-failure coverage intentionally preserves measurements, which does not cover the different contract of a source successfully returning an account error state.

9. Appendix and trust boundary

Issue text and comments were treated as untrusted claims, not instructions or executable material. The reproduction was designed from trusted repository code. No issue-provided script, patch, external link, live credential, or account data was used. There were no issue comments when investigation began.

Raw runner logs, temporary snapshots and unstyled component markup are retained only in local investigation storage, not committed to this public reports repository. The complete sanitized reproduction and meaningful expected/actual output are inline above. The test removes its temporary secret/account directory in its finally block.

Classification applied: Bug; Priority Medium; Effort Medium; providers. No existing classifications were overwritten. Reproduction label: confirmed-repro.