Repository navigation
Description
Summary
The Codex provider plugin reads new async questions from the experimental_thread.events handler. The server fires that event about once per second per thread while the thread receives events. Each run ends with bb.storage.kv.set(cursorKey(threadId), cursor), also when the cursor did not move. The cursor moves only when a new thread/extensionState/updated row exists, so almost every run upserts the same value into the plugin_kv table of the main database. Plugins run in the server process, so the write is synchronous SQLite work on the server main thread.
Versions and environment
- bb from source at origin/main fb045a0.
- Linux (CachyOS, kernel 7.3), Node v26.13.1.
- Provider: Codex (any version; the defect is in the bb plugin, not in Codex).
Steps to reproduce
-
Add this test to
plugins/provider-codex/src/async-questions.test.ts. It uses the existingcreateHostandnotifyhelpers of that file:it("writes the cursor only when a new event row moved it", async () => { const rows: ReturnType<typeof questionRow>[] = []; const host = createHost(rows); const kvSet = vi.spyOn(host.bb.storage.kv, "set"); await notify(host); await notify(host); await vi.waitFor(() => expect(host.harness.sdk.callsTo("threads.events.list")).toHaveLength(2), ); expect(kvSet).not.toHaveBeenCalled(); });
-
Run
pnpm exec turbo run test --filter=bb-plugin-provider-codex(ornpx vitest run src/async-questions.test.tsinplugins/provider-codexafter the SDK is built).
Expected vs actual
Expected: no kv write when the events page is empty.
Actual:
AssertionError: expected "set" to not be called at all, but actually been called 2 times
1st set call: [ "async-question-cursor:thr_async", 0 ]
2nd set call: [ "async-question-cursor:thr_async", 0 ]
Evidence
- The handler reads the cursor, lists events after it, and writes it back unconditionally:
bb/plugins/provider-codex/src/async-questions.ts
Lines 44 to 71 in fb045a0
async function readNewQuestions( threadId: string, ): Promise<CodexAsyncQuestionState[]> { let cursor = (await bb.storage.kv.get<number>(cursorKey(threadId))) ?? 0; const questions: CodexAsyncQuestionState[] = []; for (;;) { const page = await bb.sdk.threads.events.list({ threadId, afterSeq: String(cursor), order: "asc", limit: String(EVENT_PAGE_SIZE), types: ["thread/extensionState/updated"], }); for (const row of page) { cursor = Math.max(cursor, row.seq); if ( row.type !== "thread/extensionState/updated" || row.data.kind !== CODEX_ASYNC_QUESTION_EXTENSION_KIND ) continue; const state = codexAsyncQuestionStateSchema.safeParse(row.data.payload); if (state.success) questions.push(state.data); } if (page.length < EVENT_PAGE_SIZE) break; } await bb.storage.kv.set(cursorKey(threadId), cursor); return questions; } - The handler runs for every
experimental_thread.eventson a Codex thread:bb/plugins/provider-codex/src/async-questions.ts
Lines 109 to 118 in fb045a0
bb.events.on("experimental_thread.events", ({ thread }) => { if (thread.providerId !== CODEX_PROVIDER_ID) return; enqueue(thread.id, async () => { for (const state of await readNewQuestions(thread.id)) { void ask(thread.id, state).catch((error: unknown) => { bb.log.warn( `async question handling failed for thread ${thread.id}: ${errorMessage(error)}`, ); }); } - The server throttles that event to one per second per thread:
bb/apps/server/src/services/plugins/plugin-thread-events.ts
Lines 89 to 97 in fb045a0
export function emitPluginThreadEvents(threadId: string): void { if (emitter === undefined || pendingThreadEvents.has(threadId)) return; const timer = setTimeout(() => { pendingThreadEvents.delete(threadId); emitter?.emitThreadEvents(threadId); }, 1_000); timer.unref?.(); pendingThreadEvents.set(threadId, timer); } kv.setcallssetPluginKvValuesynchronously in the server process:bb/apps/server/src/services/plugins/plugin-api.ts
Lines 739 to 752 in fb045a0
async set(key, value) { assertLive(); const json = JSON.stringify(value); if (json === undefined) { throw new Error(`kv value for "${key}" is not JSON-serializable`); } const bytes = Buffer.byteLength(json, "utf8"); if (bytes > KV_VALUE_MAX_BYTES) { throw new Error( `kv value for "${key}" is ${bytes} bytes; the limit is ${KV_VALUE_MAX_BYTES} (256KB). ` + `Store large data in storage.database() instead.`, ); } setPluginKvValue(db, pluginId, key, json); setPluginKvValueis anINSERT ... ON CONFLICT DO UPDATE:bb/packages/db/src/data/plugin-storage.ts
Lines 33 to 47 in fb045a0
export function setPluginKvValue( db: DbConnection, pluginId: string, key: string, value: string, ): void { const updatedAt = Date.now(); db.insert(pluginKv) .values({ pluginId, key, value, updatedAt }) .onConflictDoUpdate({ target: [pluginKv.pluginId, pluginKv.key], set: { value, updatedAt }, }) .run(); }
Measurement: a script ran the per-tick database work through getPluginKvValue and setPluginKvValue from @bb/db on a file database created with createConnection and migrate (WAL, synchronous = NORMAL, as in production), 50 cursor keys, 20,000 ticks, 3 rounds:
get + set (current): 44.59, 40.43, 42.10 us/tick, 20000 row writes per round
get only (no write): 15.85, 15.63, 15.90 us/tick, 0 row writes
So each idle tick costs about 26 microseconds of main-thread SQLite time and one committed write transaction (WAL append, later checkpoint) for no change. The cost is small per tick but it is paid for each streaming Codex thread, every second, for the whole turn.
What you ruled out
- The cursor never needs a rewrite to stay correct: it only grows (
Math.max), and the stored value is read at the start of every run. - Skipping the
threads.events.listloopback call as well is not cheap. The event payload carries only the thread's latest sequence, and the list is filtered tothread/extensionState/updated, so the plugin cannot know if a new matching row exists without the list or without storing the scanned sequence, which would again write on every tick.
AGENT GENERATED
Activity
bb-slop-cop commentedon Nov 25, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilotproviders,provider-codex,perf, andconfirmed-repro; no existing classifications were replaced.Write the Codex async question cursor only when it moves (get-bb#8171)