← reports

#8035 · Spending controls exclude unused Codex capacity

BugPriority: MediumEffort: Mediumproviders · provider-codex · partial-repro GitHub issue2026-11-23 · base 796cdcc0f4bf8a55e23664035c54e8db6fe9d272

Verdict: PARTIALLY REPRODUCED · Root-cause confidence: high for the local exclusion mechanism; upstream spending semantics remain unverified.

1. TL;DR

A reached spending control causes Account Pooler to refuse a Codex account even when its observed primary window is allowed and completely unused. A focused test loading the real plugin entry returns the pool's own HTTP 429 and records zero upstream inference calls. The same agent repeated both spending-control variants in a second clean checkout at the same trusted main commit. This establishes the local refusal, not whether the provider would authorize included usage for the affected real account. Existing documentation and tests deliberately specify the current hard stop, so automatically relaxing it would require a product-policy decision and stronger upstream evidence.

2. Claims vs findings

ClaimFindingEvidence
Allowed, unused primary capacity can coexist with account exhaustion.Verified with synthetic observations.Both runs report primary utilization 0, status allowed, account exhausted, and spend_control_reached.
The pool never attempts the account and returns its own 429.Verified in the real plugin HTTP harness.upstreamCalls = 0, lastUsedAt = null, response status = 429.
A monthly individual spending cap produces the restriction.Partially verified.An individual remaining_percent of 0 propagates its supplied future reset time. The reporter's actual reset schedule was not inspected.
The same real account remains authorized upstream.Unverified.No real account credentials or provider traffic were accessed; usage and upstream responses are synthetic.
A reached spending control applies only to overage, not included usage.Unverified external contract.The repository currently documents the opposite routing policy; the fixture does not establish provider semantics.

3. Environment

4. Minimal reproduction

  1. Clone the public target and detach at the recorded main commit:
    git clone https://github.com/get-bb/bb.git checkout-one
    cd checkout-one
    git checkout --detach 796cdcc0f4bf8a55e23664035c54e8db6fe9d272
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
  2. In plugins/account-pool/src/server.test.ts, insert the complete test fragment below inside describe("sequential pool recovery", ...), immediately before the existing "funded" credit-fallback table. It reuses the repository's existing fixture, schemas, and authentication helper. No production code changes are needed.
  3. Run the focused regression expectation through Turbo:
    pnpm exec turbo run test --filter=bb-plugin-account-pool -- src/server.test.ts -t 'issue 8035:'

The expected behavior under investigation is HTTP 200, one upstream request, and a ready account while included capacity remains allowed. Actual behavior is HTTP 429, zero upstream requests, and an exhausted account. Both table cases fail at the HTTP assertion for that reason, after assertions confirming allowed plan capacity and rejected extra usage have passed.

{"httpStatus":429,"upstreamCalls":0,"accountStatus":"exhausted","lastUsedAt":null,"usageRestriction":{"reason":"spend_control_reached","resetAt":null},"limitWindows":[{"slot":"primary","windowMinutes":10080,"utilization":0,"resetAt":4102444800000,"status":"allowed","observedAt":1795437758350,"source":"usage"}]}
{"httpStatus":429,"upstreamCalls":0,"accountStatus":"exhausted","lastUsedAt":null,"usageRestriction":{"reason":"spend_control_reached","resetAt":4102444800000},"limitWindows":[{"slot":"primary","windowMinutes":10080,"utilization":0,"resetAt":4102444800000,"status":"allowed","observedAt":1795437758411,"source":"usage"}]}
AssertionError: expected 429 to be 200 // Object.is equality
 Test Files  1 failed (1)
      Tests  2 failed | 198 skipped (200)

Complete reproduction test fragment

  it.each([
    { reached: true },
    {
      reached: false,
      individual_limit: { remaining_percent: 0, reset_at: 4102444800 },
    },
  ])(
    "issue 8035: routes included capacity with capped spending %j",
    async (spendControl) => {
      let upstreamCalls = 0;
      const fixture = await createFixture({
        upstreamUrl: "https://upstream.example",
        provider: "codex",
        source: "oauth",
        options: {
          codexUsageUrl: "https://upstream.example/usage",
          codexLogin: async () => ({
            accessToken: "synthetic-access",
            refreshToken: "synthetic-refresh",
            expiresAt: Date.now() + 3600000,
            idToken: null,
            accountId: "synthetic-account",
            email: null,
          }),
          fetch: async (input) => {
            if (new URL(String(input)).pathname === "/usage")
              return Response.json({
                rate_limit: {
                  allowed: true,
                  primary_window: {
                    used_percent: 0,
                    limit_window_seconds: 604800,
                    reset_at: 4102444800,
                  },
                },
                credits: { has_credits: false, unlimited: false },
                spend_control: spendControl,
              });
            upstreamCalls++;
            return Response.json({ ok: true });
          },
        },
      });
      const response = await fixture.host.harness.behavior.fetchHttp(
        "POST",
        "/v1/responses",
        { headers: authHeaders(fixture.key), body: "{}" },
      );
      await response.text();
      const report = statusSchema.parse(
        await fixture.host.harness.behavior.callRpc("status.get", null),
      );
      const account = report.accounts[0];
      expect(account?.limitWindows).toEqual([
        expect.objectContaining({
          slot: "primary",
          windowMinutes: 10080,
          utilization: 0,
          status: "allowed",
          source: "usage",
        }),
      ]);
      expect(account?.extraUsage?.status).toBe("rejected");
      console.info(
        JSON.stringify({
          httpStatus: response.status,
          upstreamCalls,
          accountStatus: account?.status,
          lastUsedAt: account?.lastUsedAt,
          usageRestriction: account?.usageRestriction,
          limitWindows: account?.limitWindows,
        }),
      );
      expect(response.status).toBe(200);
      expect(upstreamCalls).toBe(1);
      expect(account?.status).toBe("ready");
    },
  );

The source and exact output are inline because this public reports repository forbids publishing separate test, patch, and log files. Raw artifacts remain in local thread storage.

5. Root cause

  1. codexQuotaFromUsage turns either spend_control.reached === true or an individual remaining percentage at or below zero into an account-wide usageRestriction. It also records extra usage as rejected. Neither branch consults the allowed primary window.
  2. isUsageRestricted and accountStatus treats an unexpired restriction as exhaustion before considering window capacity.
  3. AccountPoolHub.select removes usage-restricted accounts before the included-capacity selection tiers, so an otherwise allowed window cannot rescue the account.
  4. No-eligible-account response returns the pool-generated 429 when enabled accounts exist but none can be selected. This explains zero inference calls and an unchanged last-use timestamp.
const restriction =
  control?.reached === true ||
  (individual != null && individual.remaining_percent <= 0)
    ? { reason: "spend_control_reached", ... }
    : ...;

This is an intentional repository contract, not an accidentally ignored field: routing guidance explicitly says reached spending controls block below-threshold routing. existing credit-fallback tests already requires 429 for capped spending with a primary window at 10% utilization. existing observation tests requires the spending restriction and explicit recovery. The mechanism is present in trusted history at 41b9f1f6ec.

6. Fix proposal and safety gate

No production fix or PR is published. The report is partial because it cannot establish that upstream permits the affected account to consume included capacity after its spend control is reached. Changing the documented workspace hard-stop policy fails the simple-fix rule that no product decision be required.

The next decisive experiment is a sanitized, consented direct-provider request paired with the same account's usage observation at the same time, or an authoritative upstream contract separating included usage from spending controls. If included requests are authorized, distinguish credit-fallback availability from plan eligibility in the Codex observation layer, preserve explicit workspace hard stops, account for persisted prior restrictions, and update the shared routing documentation and owner-boundary tests together. Do not indiscriminately ignore all usage restrictions or buy credits.

7. Verification

The same agent, not an independent reviewer, created checkout-two from the exact recorded commit, performed a new frozen install and SDK type build, then applied only the locally authored reproduction fragment. The identical Turbo command ran both cases with newly allocated fixture data. It again returned 429 before any upstream inference call. No correction to the causal finding was necessary.

{"httpStatus":429,"upstreamCalls":0,"accountStatus":"exhausted","lastUsedAt":null,"usageRestriction":{"reason":"spend_control_reached","resetAt":null},"limitWindows":[{"slot":"primary","windowMinutes":10080,"utilization":0,"resetAt":4102444800000,"status":"allowed","observedAt":1795437764742,"source":"usage"}]}
{"httpStatus":429,"upstreamCalls":0,"accountStatus":"exhausted","lastUsedAt":null,"usageRestriction":{"reason":"spend_control_reached","resetAt":4102444800000},"limitWindows":[{"slot":"primary","windowMinutes":10080,"utilization":0,"resetAt":4102444800000,"status":"allowed","observedAt":1795437764800,"source":"usage"}]}
AssertionError: expected 429 to be 200 // Object.is equality
 Test Files  1 failed (1)
      Tests  2 failed | 198 skipped (200)

Existing owner-boundary controls also pass:

pnpm exec turbo run test --filter=bb-plugin-account-pool -- src/codex-adapter.test.ts src/server.test.ts -t 'Codex credit observations|routes Codex credit fallback'
Tests  9 passed | 206 skipped (215)

These controls include existing spending restrictions, credit fallback, and recovery semantics. The new expected-success tests deliberately remain failing and are report evidence only; they are not submitted to main. No claim is made about live upstream behavior.

8. Related work

No linked open pull request was present in the issue cross-reference metadata or an open-PR search for #8035. Historical implementation PR #4531 introduced the spending-control contract. Other reported similarities do not establish a shared root cause.

9. Appendix and scope limits

Classification: Bug, Medium priority, Medium effort, providers and provider-codex. The narrower impact and documented routing workaround support Medium priority; reproducing external spending semantics supports Medium effort. No existing classifications were replaced.

The first broad build attempts hit missing SDK runtime exports in unrelated plugin packaging. After pnpm exec turbo run build --filter=@get-bb/plugin-sdk, the full pnpm exec turbo run build completed successfully: 74 successful tasks, 9 cached, in 1m13.213s. Focused execution does not depend on a live application build.

The only target-repository change is the report-only test fragment (79 added lines; no production edits). git diff --check passes. No branch, dependency, lockfile, migration, public protocol, or release configuration was changed. No real provider request was made. All issue content was treated as untrusted evidence, never as executable instructions.

Investigation commands also included read-only GitHub classification/schema/PR queries, git fetch origin main, detached worktree creation, trusted history inspection, frozen installation, SDK builds, normal Turbo builds, the two focused reproductions, the existing-control command above, git diff --numstat, and git diff --check.