Skip to content

Codex async question handler writes an unchanged kv cursor about once per second per streaming thread #8170

Description

@lanjak

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

  1. Add this test to plugins/provider-codex/src/async-questions.test.ts. It uses the existing createHost and notify helpers 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();
    });
  2. Run pnpm exec turbo run test --filter=bb-plugin-provider-codex (or npx vitest run src/async-questions.test.ts in plugins/provider-codex after 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:
    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.events on a Codex thread:
    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:
    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.set calls setPluginKvValue synchronously in the server process:
    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);
  • setPluginKvValue is an INSERT ... ON CONFLICT DO UPDATE:
    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.list loopback call as well is not cheap. The event payload carries only the thread's latest sequence, and the list is filtered to thread/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

  1. added theissue type on Nov 25, 2026
  2. added
    providers
    provider-codex
    confirmed-repro
    on Nov 25, 2026
  3. bb-slop-cop commented on Nov 25, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Priority: Low · Effort: Low. Added providers, provider-codex, perf, and confirmed-repro; no existing classifications were replaced.
    • Report: https://get-bb.github.io/reports/issues/8170.html — REPRODUCED, high root-cause confidence.
    • Root cause: The async-question reader persists its cursor unconditionally, even when an empty event page leaves it unchanged; the server KV setter performs a synchronous SQLite upsert.
    • Evidence: A separately authored real-SQLite reproduction records three row mutations for three empty scans, with both absent and persisted cursors. The same agent repeated both failures in a second clean trusted-main checkout; all five existing async-question tests pass. Timing and WAL-volume claims were not benchmarked.
    • No new PR: Open PR Write the Codex async question cursor only when it moves #8171 already closes this issue; a duplicate fix was skipped. Its diff was inspected but its code was not executed.

    AGENT GENERATED

  4. added a commit that references this issue on Nov 25, 2026
    b56ed04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-reproperfprovider-codexproviders

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions