← reports

#6835 · Synchronous event persistence blocks timers during SQLite waits

BugHighEffort: Highhost · threads · perfGitHub issue2026-11-02 · base 93411e8e6afad9a8cf50244a2cd9f468543f859e

Verdict: PARTIALLY REPRODUCED · Root-cause confidence: high for synchronous event-loop blocking; unverified for the reported cold-read I/O attribution.

1. TL;DR

Database work on the server's JavaScript thread can prevent unrelated timers and request handlers from running while SQLite waits. Two clean-source runs at the same trusted main commit demonstrate this mechanism: a worker holds a real SQLite write lock for 700 ms while the server's event-append transaction runs, and a 20 ms timer fires after 739.2 ms and 739.1 ms. This is a controlled contention experiment, not a reproduction of multi-gigabyte cold reads or the reported 15–18 second outages. Main already contains the relevant covering index and incremental pruning, including a zero busy timeout during pruning. Those mitigations do not make the remaining synchronous database operations asynchronous.

2. Claims vs findings

Claim or hypothesisStatusEvidence
Slow SQLite work can stall unrelated server event-loop work.Verified mechanismThe real daemon-event persistence boundary delays a 20 ms timer to approximately 739 ms under a controlled writer lock in both runs.
A missing thread/turn index explains the observed query time.Not supported on current mainThe migrated schema already has events_thread_turn_type_item_sequence_idx. SQLite chooses it as a covering index for the thread/turn type lookup; the assertion passes twice. The user's installed database was not inspected.
Pruning still needs incremental, bounded batches.Already implemented on current mainLive and background batch sizes are 32 and 500, respectively. Existing tests exercise resumable cursors and bounded probes. Row limits do not guarantee a wall-clock I/O deadline.
Pruning waits on a competing writer for seconds.Not reproduced on current mainPruning temporarily sets the busy timeout to zero. Both fresh tests observe a lock error in less than 150 ms and restoration of the normal 5000 ms timeout.
Multi-gigabyte database reads caused the specific reported outages and daemon failures.UnverifiedNo original database, original logs, macOS workload, cold-page experiment, or daemon network reproduction was used. The synthetic fixture is small and the demonstrated wait is a write-lock wait, not a disk read.

3. Environment and trust

4. Minimal reproduction

  1. Obtain the trusted repository and pin the tested main commit:
    git clone https://github.com/get-bb/bb.git bb-6835-first
    cd bb-6835-first
    git checkout --detach 93411e8e6afad9a8cf50244a2cd9f468543f859e
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build
    The first broad build hit a missing SDK-dist build-order race. Building SDK types after the SDK runtime build completed, then retrying the normal build succeeded: 72 tasks successful. No source change or dependency was needed.
  2. Save the complete inline reproduction as packages/db/test/issue-6835-repro.test.ts and run:
    pnpm exec turbo run test --filter=@bb/db -- --reporter=verbose test/issue-6835-repro.test.ts
    The test opens a real migrated file-backed WAL database, starts a worker that holds BEGIN IMMEDIATE for 700 ms, schedules a 20 ms timer, and runs the same immediate transaction plus daemon-event append function used by the server route.
  3. Expected responsiveness contract: the heartbeat should run within 150 ms despite another connection holding the write lock. Actual first-run output:
    event-insert-heartbeat-ms 739.2
    AssertionError: expected 739.225034 to be less than 150
    Test Files  1 failed (1)
    Tests  1 failed | 2 passed (3)
    The expected failure is exclusively the heartbeat assertion, after one event has been successfully persisted. Both the covering-index assertion and non-waiting-pruning assertions pass.
Complete reproduction test
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { performance } from "node:perf_hooks";
import { Worker } from "node:worker_threads";
import { describe, expect, it } from "vitest";
import { threadScope } from "@bb/domain";
import { createConnection } from "../src/connection.js";
import { createMigratedConnection } from "../src/testing.js";
import { noopNotifier } from "../src/notifier.js";
import { upsertHost } from "../src/data/hosts.js";
import { createProject } from "../src/data/projects.js";
import { createThread } from "../src/data/threads.js";
import { appendDaemonEventsInTransaction } from "../src/data/events.js";
import { advanceThreadPruning } from "../src/data/thread-pruning.js";

function fixture() {
  const directory = mkdtempSync(join(tmpdir(), "bb-6835-"));
  const filename = join(directory, "fixture.sqlite");
  const template = createMigratedConnection();
  try {
    writeFileSync(filename, template.$client.serialize());
  } finally {
    template.$client.close();
  }
  const db = createConnection(filename);
  const host = upsertHost(db, noopNotifier, { name: "reproduction" });
  const { project } = createProject(db, noopNotifier, {
    name: "reproduction",
    source: { type: "local_path", hostId: host.id, path: directory },
  });
  const thread = createThread(db, noopNotifier, {
    projectId: project.id,
    providerId: "codex",
  });
  return {
    db,
    filename,
    thread,
    close() {
      db.$client.close();
      rmSync(directory, { recursive: true, force: true });
    },
  };
}

async function withWriterLock(filename: string, work: () => Promise<void>) {
  const worker = new Worker(
    `const { parentPort, workerData } = require("node:worker_threads");
const Database = require(workerData.modulePath);
const db = new Database(workerData.filename);
db.exec("BEGIN IMMEDIATE");
parentPort.postMessage("locked");
setTimeout(() => {
  db.exec("COMMIT");
  db.close();
}, 700);`,
    {
      eval: true,
      workerData: {
        filename,
        modulePath: createRequire(import.meta.url).resolve("better-sqlite3"),
      },
    },
  );
  try {
    await new Promise<void>((resolve, reject) => {
      worker.once("message", () => resolve());
      worker.once("error", reject);
    });
    await work();
  } finally {
    await worker.terminate();
  }
}

describe("issue 6835 isolated SQLite reproduction", () => {
  it("already has a covering index for a thread and turn type lookup", () => {
    const instance = fixture();
    try {
      const plan = instance.db.$client
        .prepare("EXPLAIN QUERY PLAN SELECT type FROM events WHERE thread_id = ? AND turn_id = ?")
        .all(instance.thread.id, "turn");
      console.log("query-plan", JSON.stringify(plan));
      expect(JSON.stringify(plan)).toContain(
        "COVERING INDEX events_thread_turn_type_item_sequence_idx",
      );
    } finally {
      instance.close();
    }
  });

  it("already skips a contended live pruning transaction", async () => {
    const instance = fixture();
    try {
      await withWriterLock(instance.filename, async () => {
        const startedAt = performance.now();
        expect(() => advanceThreadPruning(instance.db, {
          threadId: instance.thread.id,
        })).toThrow(/locked/);
        const elapsed = performance.now() - startedAt;
        console.log("pruning-lock-wait-ms", elapsed.toFixed(1));
        expect(elapsed).toBeLessThan(150);
        expect(instance.db.$client.pragma("busy_timeout", { simple: true })).toBe(5000);
      });
    } finally {
      instance.close();
    }
  });

  it("keeps a 20 ms heartbeat responsive during a contended event insert", async () => {
    const instance = fixture();
    try {
      await withWriterLock(instance.filename, async () => {
        const startedAt = performance.now();
        const heartbeat = new Promise<number>((resolve) => {
          setTimeout(() => resolve(performance.now() - startedAt), 20);
        });
        const inserted = instance.db.transaction(
          (transaction) => appendDaemonEventsInTransaction(transaction, [{
            threadId: instance.thread.id,
            environmentId: null,
            providerThreadId: null,
            itemId: null,
            itemKind: null,
            parentToolCallId: null,
            scope: threadScope(),
            type: "thread/identity",
            data: JSON.stringify({ providerThreadId: "synthetic-provider-thread" }),
          }]),
          { behavior: "immediate" },
        );
        expect(inserted.acceptedEvents).toHaveLength(1);
        const delay = await heartbeat;
        console.log("event-insert-heartbeat-ms", delay.toFixed(1));
        expect(delay).toBeLessThan(150);
      });
    } finally {
      instance.close();
    }
  });
});

5. Root cause

The daemon-events route synchronously enters an immediate SQLite transaction before returning to the event loop. Its actual call boundary is internal/events.ts:1213–1218:

appendResult = deps.db.transaction(
  (tx) => appendDaemonEventsInTransaction(tx, eventInputs),
  { behavior: "immediate" },
);

createConnection constructs a synchronous better-sqlite3 database and sets busy_timeout = 5000. The transaction wrapper invokes the caller directly (connection.ts:340–346). A contended BEGIN IMMEDIATE therefore waits in the same thread that must run the timer. The reproduction releases that lock from a worker so progress does not depend on the blocked thread. Merely putting an await around a synchronous call would not move the database work off-thread.

This proves a mechanism capable of contributing to stalls, not the cause of the specific long SELECT timings. A single lock wait is bounded by the configured timeout; this experiment does not establish why the reported stalls exceeded it. WAL readers normally coexist with a writer. Slow reads, storage latency, page faults, and longer sequences of synchronous calls require their own evidence.

The thread/turn/type covering index is already defined at schema.ts:844–850 and installed by real migrations. The query-plan test asserts that SQLite selects it for the type lookup. Adding a redundant index is not justified by this reproduction.

Pruning already uses persistent progress, 32/500 batch limits, and a temporary zero busy timeout with restoration. The server calls it synchronously at event-pruning.ts:65–76. Bounded rows and no lock waiting reduce contention but cannot guarantee that an individual disk operation returns quickly.

6. Proposed fix and simple-fix decision

Preserve the existing index and bounded pruning. To guarantee that slow storage cannot stop server timers, design asynchronous database ownership: for example, a dedicated database worker with explicit request scheduling and transaction boundaries. Preserve ordering, commit notifications, synchronous internal assumptions, and shutdown behavior; then test both locked writes and cold reads while an unrelated request or heartbeat remains responsive.

No automatic fix or pull request: moving this synchronous database boundary off-thread requires an architecture decision and coordinated contracts. That fails the simple-fix criteria. Adding another index requires a migration and is unsupported by the observed access path; simply making a function async would not address the cause. The exact large-database read stall was also not reproduced. No fix branch was created or pushed.

No open pull request linked to #6835 was present in the issue's cross-reference metadata or the open-PR search at investigation time. No linked pull-request code was checked out.

7. Verification: second clean run by the same agent

A separate detached worktree, <temporary-root>/verify, was created from the full base SHA above. Its clean status and HEAD were checked before copying only the authored test. A separate frozen install and the identical Turbo reproduction command were run there. The fixture was newly generated and the worker/SQLite connections were new; no data file or running instance was shared.

event-insert-heartbeat-ms 739.1
AssertionError: expected 739.0952010000001 to be less than 150
Test Files  1 failed (1)
Tests  1 failed | 2 passed (3)

This is a repeated check by the same agent, not independent verification. An initial draft fixture omitted required event fields and failed with an unrelated SQL syntax error; it was corrected to the production daemon-event append contract before either final recorded run. No production source was changed. The final verdict remains partial because neither run reproduces cold reads, macOS conditions, or multi-second daemon disconnects.

8. Related issues

The repository search surfaced #5270, which concerns a different external SQLite-reader failure, and #4943, which concerns documentation of SQLite access from plugins. Neither was used as causal evidence here. This experiment holds the competing connection in another worker, not another SQLite library in the server thread. No duplicate or equivalent fix was established.

9. Appendix: checks and artifacts

Existing connection, event persistence, query-plan, and pruning tests pass unmodified:

pnpm exec turbo run test --filter=@bb/db -- --reporter=verbose test/query-plans.test.ts test/data/thread-pruning.test.ts test/connection.test.ts test/data/events.test.ts

Test Files  4 passed (4)
Tests  187 passed (187)

Existing pruning tests include lock contention, timeout restoration, resumable cursors, and bounded probes; these do not establish a wall-clock storage-latency bound. Full sanitized logs remain in the local investigation evidence directory, outside this public repository. The complete test and essential exact output are inline so no unpublished file is needed to repeat the experiment.

Repository metadata and installed dependency versions were read locally and with GitHub read APIs. Writes to issue classifications and report publication use the supplied SlopCop GitHub command. No screenshots apply to this nonvisual concurrency defect.