Repository navigation
Description
Summary
Conversations through Account Pooler repeatedly failed with immediate HTTP 502 responses while direct (non-pooled) access to the same provider worked. This was first observed for Claude on both a local host and a remote sandbox, and subsequently reproduced identically for ChatGPT/Codex on the same machine. In both cases, inspecting the live server exposed TypeError: fetch failed with cause The session has been destroyed (error code ERR_HTTP2_INVALID_SESSION); clearing only the affected origin's cached connection pool restored a real pooled request without changing credentials or routing.
The failure is not provider-specific. It is a property of the shared, process-wide HTTP transport the hub uses for every upstream. Whichever origin's cached HTTP/2 session is destroyed (api.anthropic.com or chatgpt.com) then fails every request to that origin instantly, and the hub converts each into a generic 502 while the account remains marked ready.
Reproduction status: partial. The live incidents were observed on 0.42.0. On current main, the attached self-contained fault-injection script confirms that the real hub discards this transport cause and account fallback repeats the failure. I have not reproduced the original session-destruction trigger on a fresh process or current main.
Versions and environment
- Live incidents: bb-app 0.42.0 installed from npm through mise; built-in Account Pooler enabled.
- Server: Omarchy 4.0.0 (Arch-based Linux), x64; Node 26.7.0 with bundled Undici 8.9.0.
- Providers observed: Claude (via Claude Code) and ChatGPT/Codex, each through its own enabled OAuth account. Both accounts appeared
readythroughout. - The Claude incident affected one local thread and one Daytona-sandbox thread (the sandbox had no independent local Claude login). The ChatGPT/Codex incident affected multiple local Codex threads.
- Isolated reproduction tested against
mainat06aeaa994942ae7527dc49d2268c1f801e8542a0, using Node 26.7.0 / Undici 8.9.0. The fixture uses two synthetic API-key accounts to exercise current fallback behavior; the injected fault is at the transport boundary and is provider-independent. - The running installation was not upgraded or replaced with a custom build during this investigation.
Steps to reproduce
Deterministic partial reproduction on current main
This tests the real AccountPoolHub, account stores, migrations, and SQLite database, with a loopback HTTP upstream. Only the fetch failure is injected. It does not require provider credentials, make external API calls, read live BB state, enable a debugger, or modify installed BB files. Temporary fixture state is removed on exit. The injected fault is transport-level, so it models the failure for any upstream origin regardless of provider.
-
In a scratch directory, check out the tested commit and install dependencies:
git clone https://github.com/get-bb/bb.git bb-pool-repro cd bb-pool-repro git checkout 06aeaa994942ae7527dc49d2268c1f801e8542a0 pnpm install --frozen-lockfile -
Save the script below as
repro-account-pool.mjsin that checkout. -
Run
node --import tsx ./repro-account-pool.mjs.
This directly runs the isolated investigation script rather than the repository test suite. Exit 0 means the assertions reproduced the described current behavior; it does not mean the product bug is fixed.
Complete reproduction script
import assert from 'node:assert/strict';
import { mkdtemp, rm } from 'node:fs/promises';
import http from 'node:http';
import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { execFileSync } from 'node:child_process';
const root = process.cwd();
const source = path.join(root, 'plugins/account-pool');
const require = createRequire(path.join(source, 'package.json'));
const Database = require('better-sqlite3');
const { createHub } = await import(pathToFileURL(path.join(source, 'src/hub.ts')));
const { AccountStore, HubTokenStore, QuotaStore, PoolAffinityStore, QUOTA_MIGRATIONS } =
await import(pathToFileURL(path.join(source, 'src/store.ts')));
const directory = await mkdtemp(path.join(tmpdir(), 'bb-pool-repro-'));
const db = new Database(':memory:');
let hub;
let service;
const controller = new AbortController();
let upstreamRequests = 0;
let attempts = 0;
let broken = false;
const server = http.createServer(async (request, response) => {
for await (const chunk of request) {}
upstreamRequests++;
response.writeHead(200, { 'content-type': 'application/json' });
response.end(JSON.stringify({ type: 'message', content: [{ type: 'text', text: 'OK' }] }));
});
try {
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const origin = `http://127.0.0.1:${server.address().port}`;
db.exec('CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
for (const migration of QUOTA_MIGRATIONS) db.exec(migration);
const kv = {
async get(key) {
const row = db.prepare('SELECT value FROM kv WHERE key = ?').get(key);
return row === undefined ? undefined : JSON.parse(row.value);
},
async set(key, value) {
db.prepare('INSERT OR REPLACE INTO kv VALUES (?, ?)').run(key, JSON.stringify(value));
},
async delete(key) { db.prepare('DELETE FROM kv WHERE key = ?').run(key); },
};
const accounts = new AccountStore(kv, directory);
await accounts.initialize();
for (let i = 1; i <= 2; i++) {
await accounts.add({ provider: 'claude', kind: 'api-key', label: `fixture-${i}`,
email: null, accountUuid: null, subscriptionType: null, rateLimitTier: null,
enabled: true, priority: i }, { kind: 'api-key', apiKey: `fake-key-${i}` });
}
const hubTokens = new HubTokenStore(directory);
await hubTokens.initialize();
const token = await hubTokens.forHost('repro-host');
const injectedFetch = async (url, init) => {
assert.equal(new URL(url).origin, origin);
attempts++;
if (broken) throw new TypeError('fetch failed', {
cause: new Error('The session has been destroyed'),
});
return fetch(url, init);
};
hub = createHub({ accounts, hubTokens, quotas: new QuotaStore(db),
affinity: new PoolAffinityStore(db), fetch: injectedFetch,
getSettings: () => ({ anthropicUpstreamBaseUrl: origin,
codexUpstreamBaseUrl: origin, switchThreshold: 0.98 }) });
service = hub.start(controller.signal);
const request = () => new Request('http://repro.invalid/api/v1/plugins/account-pool/http/v1/messages', {
method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ model: 'claude-sonnet-4-6', max_tokens: 8,
messages: [{ role: 'user', content: 'Reply OK' }] }),
});
const probe = async (label, status) => {
const priorAttempts = attempts;
const priorUpstream = upstreamRequests;
const response = await hub.handle(request(), 'claude');
const body = await response.text();
assert.equal(response.status, status);
console.log(`${label}: HTTP ${response.status}; fetch attempts=${attempts-priorAttempts}; upstream requests=${upstreamRequests-priorUpstream}`);
console.log(body);
return body;
};
console.log(`Base: ${execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim()}`);
console.log(`Runtime: ${process.version}; Undici ${process.versions.undici}`);
console.log('Fault injection: real hub, SQLite, and loopback upstream; synthetic destroyed-session fetch failure.');
await probe('Healthy baseline', 200);
broken = true;
for (let i = 1; i <= 2; i++) {
const body = await probe(`Injected failure ${i}`, 502);
assert.equal(body.includes('The session has been destroyed'), false);
}
const status = await hub.status();
assert.equal(status.inFlight, 0);
assert.ok(status.accounts.every(a => a.status === 'ready' && a.error === null));
console.log(`After failures: ${status.accounts.length} accounts ready; account errors=null; inFlight=0`);
broken = false;
await probe('Fault removed', 200);
console.log('PASS: current hub masks the cause and fallback repeats the same transport failure.');
console.log('LIMIT: this does not reproduce the original Node/Undici session-destruction trigger.');
} finally {
controller.abort();
await service;
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
db.close();
await rm(directory, { recursive: true, force: true });
}Live incident reproduction and recovery
Once the running server was in the failed state, repeated authenticated POST requests to the pooled endpoint returned the same 502. One repeated probe completed in about 2 ms, measured with Date.now() around Node fetch and response-body consumption. Retrying the affected threads did not resolve it. This held for both the Claude endpoint (/v1/messages) and the ChatGPT/Codex endpoint (/v1/responses).
The precondition that put a live HTTP session into that state is unknown. These observations are not a deterministic recipe for making a healthy server enter it.
A temporary localhost Node debugger breakpoint at fetchUpstream's rethrow captured the exception below. For each incident we then removed and gracefully closed only the affected origin pool (https://api.anthropic.com, then later https://chatgpt.com) from the running Undici dispatcher's cached origin map. Requests began reaching that upstream again, and a real pooled request through the hub succeeded. The breakpoint and temporary inspector were removed afterward.
The private dispatcher-map operation was a one-time diagnostic recovery, not a proposed production implementation or a general workaround script.
Expected vs actual
Expected: when the hub cannot send requests because its transport session is unusable, retain a sanitized diagnostic cause and make the failure observable. If a stale transport can be identified safely, recover it with bounded connection replacement and retry before output starts, preserving cancellation and avoiding ambiguous request replay. Account failover alone should not be presented as recovery from an origin-wide transport failure.
Actual live API body (Claude endpoint):
{"type":"error","error":{"type":"api_error","message":"Account Pooler could not reach Anthropic."}}Actual live API body (ChatGPT/Codex endpoint):
{"error":{"message":"Account Pooler could not reach ChatGPT.","type":"api_error","code":null}}Actual exception captured inside the live process (both providers):
TypeError: fetch failed
cause: The session has been destroyed
code: ERR_HTTP2_INVALID_SESSION
Actual isolated script output on current main:
Base: 06aeaa994942ae7527dc49d2268c1f801e8542a0
Runtime: v26.7.0; Undici 8.9.0
Fault injection: real hub, SQLite, and loopback upstream; synthetic destroyed-session fetch failure.
Healthy baseline: HTTP 200; fetch attempts=1; upstream requests=1
{"type":"message","content":[{"type":"text","text":"OK"}]}
Injected failure 1: HTTP 502; fetch attempts=2; upstream requests=0
{"type":"error","error":{"type":"api_error","message":"Account Pooler could not reach Anthropic."}}
Injected failure 2: HTTP 502; fetch attempts=2; upstream requests=0
{"type":"error","error":{"type":"api_error","message":"Account Pooler could not reach Anthropic."}}
After failures: 2 accounts ready; account errors=null; inFlight=0
Fault removed: HTTP 200; fetch attempts=1; upstream requests=1
{"type":"message","content":[{"type":"text","text":"OK"}]}
PASS: current hub masks the cause and fallback repeats the same transport failure.
LIMIT: this does not reproduce the original Node/Undici session-destruction trigger.
The ready values above describe account eligibility. They are not necessarily wrong credential states; they simply provide no indication of the transport failure affecting every attempt.
Evidence
Investigation report
The live sequence, seen for each provider, was: pooled requests fail repeatedly → the same packaged fetch path reaches the provider in an isolated process → the live debugger reveals the destroyed-session cause on that origin's cached pool → clearing only that origin pool removes the immediate 502 → a real pooled invocation succeeds.
For the ChatGPT/Codex incident specifically, an in-process fetch to https://chatgpt.com through the poisoned dispatcher failed with The session has been destroyed / ERR_HTTP2_INVALID_SESSION, while https://api.anthropic.com was healthy at that moment (returned 401). After clearing only the ChatGPT pool, the in-process fetch returned 401 and a real pooled Codex request reached ChatGPT's backend. This confirms the failure is per-origin within one shared transport rather than a provider-specific defect.
BB investigation thread: thr_2zyhcwe4vj. These are reporter-local IDs, not publicly accessible reproduction dependencies. The report above and embedded script are self-contained.
Source evidence at the tested commit
- The fetch rejection is replaced with a generic UpstreamConnectionError, losing the original cause.
- The forwarding loop converts that error to the generic 502 and proceeds through account fallback.
Inference, not a proven upstream root cause: the recovery strongly implicates cached transport state in the live failures. We did not establish why the sessions were destroyed, capture their complete lifecycle, or prove a specific Undici/HTTP2 defect.
What you ruled out
- An invalid hub token: the authenticated requests passed hub authentication and reached
fetchUpstream. - Persistent inability to reach the providers from the machine: isolated packaged fetch paths received expected upstream 401s.
- A credential change being required for recovery: clearing the cached origin pool restored pooled access without reauthenticating or changing accounts.
- Provider-specific failure: the identical destroyed-session failure and recovery were observed for both Claude (
api.anthropic.com) and ChatGPT/Codex (chatgpt.com) on the same host. Whichever origin holds a destroyed cached session fails; the other can be healthy at the same time. - Remote-only failure: both local and remote threads hit the same hub failure.
- No exact duplicate was found when searching open/closed BB issues and PRs for account pool, pooler, Anthropic, ChatGPT, 502, Undici, HTTP/2, and the exact destroyed-session/could-not-reach messages on 2026-09-07.
- Related #3116 was included in merged #3117; it adds pre-stream failure recovery/fallback. The current-main script includes that work and shows both accounts still using the failing transport boundary.
- Related #2225 covers Claude SDK retry classification and blind retry storms; this report concerns the hub's transport state and discarded fetch cause.
- Not established: that a current-main live server naturally enters the same stale-session state; that a Node upgrade prevents it; or that merely adding another account of the same provider fixes it.
Suggested priority and effort
Medium — blocks all requests to an affected provider through the hub when triggered, including remote machines dependent on pooled credentials, but occurrence frequency and affected user scope are unknown. It is now confirmed to affect more than one provider, which raises impact relative to the original single-provider report. A targeted runtime recovery worked for each incident; no data loss was observed. Effort is uncertain until the native session-lifecycle trigger is reproduced.
Checks
- I reproduced this on the latest release or on
main, or I say above that I could not. Live stale-session behavior is unverified on current main; fault-injection behavior is verified there. - I searched open and closed issues for the same problem.
- This agent-written body includes the investigation report, tested commit, complete script, and actual output.
AGENT GENERATED
Activity
[-]Account Pooler: persistent immediate Claude 502s from a destroyed transport session; underlying cause is discarded[/-][+]Account Pooler: persistent immediate 502s from a destroyed transport session (Claude and ChatGPT/Codex); underlying cause is discarded[/+]bb-slop-cop commentedon Sep 8, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilotplugins,providerspartial-reprofix(account-pool): isolate upstream connections from shared HTTP/2 se…