Skip to content

Deleting a thread blocks the server for seconds (single cascade DELETE); chunked purge patch with measurements #7281

Closed

Description

@lucascastellanibr

Problem

Deleting a thread blocks the bb server for the whole cascade delete. DELETE /api/v1/threads/:id already does the fast part (markThreadDeleted sets deleted_at and the thread leaves the UI). Later, when the host has removed the thread's folder, finalizeStoppedThreadInTransaction (called from settleThreadStorageDeleteCommandResult) calls deleteThread (packages/db/src/data/threads.ts), which runs a single DELETE FROM threads WHERE id = ?. SQLite then cascades through every row of events, thread_search_segments (whose trigger deletes from the FTS5 table) and the other child tables, in one transaction, on the event loop.

On bb 0.48.1 (Linux host, 2026-11-09) one of these took 35.2 s (13.8 s CPU) with the event loop stalled 15 s, for a thread with 201,118 events. Two more in the same minute took 14.1 s and 2.4 s. They fired when five deleted threads whose folders had been failing with EACCES finally got their storage removed, so several big cascades ran back to back.

Measured (copy of a real bb.db)

Copy of a 6.8 GB bb.db (2,164,948 events, 95,694 search segments), bb 0.48.1's own SQLite 3.53.4 / better-sqlite3 13.0.3 and the same connection PRAGMAs, cold cache before each run.

Case Today: one DELETE per thread With the patch below
50 real archived threads (median 688 events, max 9,631) worst transaction 948 ms, median 79 ms, 15 above 100 ms worst 75 ms, p99 50 ms, none above 100 ms; event loop max 83 ms; 0 orphan rows
same 50, warm worst 1,524 ms (fixed-size chunks: worst 55 ms)
3 big threads (130,544 / 62,539 / 44,332 events) 8,333 / 3,198 / 2,381 ms worst 273 ms (one events chunk), p99 43 ms; 20 s total over 40 sweeps

About 85% of the time is events (14 indexes). A thread_search_segments row costs ~5x an event because of the FTS5 table with prefix '2 3'.

Proposed fix (patch against the 0.48.1 bundle)

  1. finalizeStoppedThreadInTransaction no longer calls deleteThread; it queues the thread in thread_pruning_work with a new policy deleted-thread-purge (the row cascades away with the thread, so no migration).
  2. A new PERIODIC_SWEEP_JOBS entry, deleted-thread-purge, deletes the child rows of up to 8 queued threads table by table, one IMMEDIATE transaction per chunk: DELETE FROM <table> WHERE rowid IN (SELECT rowid FROM <table> WHERE thread_id = ? LIMIT ?), with setImmediate between chunks and each chunk wrapped in runEventLoopWorkSync so it shows up in the stall report.
  3. Chunk size adapts toward ~25 ms per chunk (halve above, +25% below 8 ms). thread_search_segments starts at 16 rows (max 64); other tables start at 128 (max 500). One sweep works at most 500 ms and continues on the next.
  4. When the child tables are empty, it calls the same deleteThread in an IMMEDIATE transaction with a NotificationBuffer.

Nothing user-visible changes: the thread already has deleted_at, and bb already lives with deleted threads still in the db while their folder is pending. A restart mid-purge resumes, since the request is in the db and each chunk is a whole transaction.

Open: the single 273 ms chunk is unexplained; the likely cause is the WAL auto-checkpoint on that chunk's COMMIT.

Optional second step: FTS

  • fts5(text, tokenize='unicode61', prefix='2 3', content='', contentless_delete=1) with the same content: deleting the 50 threads' search rows worst 30 ms vs 262 ms today. listThreadSearchMatchRows only reads rowid and MATCH from the FTS table and gets text from thread_search_segments, so search keeps working. Rebuilding with 95,694 rows took 6.0 s, so that migration must be chunked too.
  • optimize took 2.7 s in one transaction (warm).
Patch (bb 0.48.1, node_modules/bb-app/server/dist/start-server.js; patch -p1 in the app folder; node --check passes)
--- a/node_modules/bb-app/server/dist/start-server.js	2026-11-09 14:26:39.973620438 -0300
+++ b/node_modules/bb-app/server/dist/start-server.js	2026-11-09 14:26:40.078619763 -0300
@@ -41293,6 +41293,11 @@
   }
 }
 var THREAD_PRUNING_PENDING_POLICY;
+var DELETED_THREAD_PURGE_POLICY = "deleted-thread-purge";
+function queueDeletedThreadPurge(db, threadId) {
+  db.run(sql`INSERT OR IGNORE INTO thread_pruning_work (policy, thread_id)
+    VALUES (${DELETED_THREAD_PURGE_POLICY}, ${threadId})`);
+}
 var init_thread_pruning_work = __esm({
   "../../packages/db/src/data/thread-pruning-work.ts"() {
     "use strict";
@@ -104821,7 +104826,7 @@
     if (finalizedThread.environmentId !== null && finalizedThread.storageDeletedAt === null)
       return;
     if (providerEnvironmentHasPendingWork(deps.db, finalizedThread.id)) return;
-    deleteThread(deps.db, deps.hub, finalizedThread.id);
+    queueDeletedThreadPurge(deps.db, finalizedThread.id);
     if (finalizedThread.environmentId !== null)
       refreshProviderRetirement(deps, finalizedThread.environmentId);
   }
@@ -231413,6 +231418,65 @@
     }
   }
 }
+var DELETED_THREAD_PURGE_TABLES = [
+  "prompt_history_entries",
+  "thread_dynamic_context_file_states",
+  "terminal_sessions",
+  "pending_interactions",
+  "thread_tabs",
+  "thread_conversation_outlines",
+  "thread_plugin_metadata",
+  "project_attachment_threads",
+  "thread_pruning_cursors",
+  "queued_thread_messages",
+  "thread_search_segments",
+  "events"
+];
+var DELETED_THREAD_PURGE_TARGET_MS = 25;
+var DELETED_THREAD_PURGE_SWEEP_BUDGET_MS = 500;
+var DELETED_THREAD_PURGE_FIRST_BATCH = { thread_search_segments: 16 };
+var DELETED_THREAD_PURGE_MAX_BATCH = { thread_search_segments: 64 };
+var deletedThreadPurgeBatches = /* @__PURE__ */ new Map();
+function purgeBatchFor(table) {
+  return deletedThreadPurgeBatches.get(table) ?? DELETED_THREAD_PURGE_FIRST_BATCH[table] ?? 128;
+}
+function adaptPurgeBatch(table, batch, ms) {
+  const max = DELETED_THREAD_PURGE_MAX_BATCH[table] ?? 500;
+  const next = ms > DELETED_THREAD_PURGE_TARGET_MS ? Math.max(8, Math.floor(batch / 2)) : ms < DELETED_THREAD_PURGE_TARGET_MS / 3 ? Math.min(max, Math.ceil(batch * 1.25)) : batch;
+  deletedThreadPurgeBatches.set(table, next);
+}
+async function runDeletedThreadPurgeSweep(deps) {
+  const started = performance2.now();
+  const queued = deps.db.$client.prepare(
+    "SELECT w.thread_id AS threadId FROM thread_pruning_work w JOIN threads t ON t.id = w.thread_id WHERE w.policy = ? AND t.deleted_at IS NOT NULL ORDER BY w.thread_id LIMIT 8"
+  ).all(DELETED_THREAD_PURGE_POLICY);
+  for (const { threadId } of queued) {
+    for (const table of DELETED_THREAD_PURGE_TABLES) {
+      const statement = deps.db.$client.prepare(
+        `DELETE FROM "${table}" WHERE rowid IN (SELECT rowid FROM "${table}" WHERE thread_id = ? LIMIT ?)`
+      );
+      for (; ; ) {
+        if (performance2.now() - started > DELETED_THREAD_PURGE_SWEEP_BUDGET_MS) return;
+        const batch = purgeBatchFor(table);
+        const batchStarted = performance2.now();
+        const deleted = runEventLoopWorkSync(
+          `sweep:deleted-thread-purge:${table}`,
+          () => deps.db.$client.transaction(() => statement.run(threadId, batch).changes).immediate()
+        );
+        adaptPurgeBatch(table, batch, performance2.now() - batchStarted);
+        await new Promise((resolve28) => setImmediate(resolve28));
+        if (deleted === 0) break;
+      }
+    }
+    const notificationBuffer = new NotificationBuffer();
+    runEventLoopWorkSync(
+      "sweep:deleted-thread-purge:thread",
+      () => deps.db.transaction((tx) => deleteThread(tx, notificationBuffer, threadId), { behavior: "immediate" })
+    );
+    notificationBuffer.flushInto(deps.hub);
+    await new Promise((resolve28) => setImmediate(resolve28));
+  }
+}
 async function runRetainedEventOutputExpirySweep(deps, now2) {
   const changedThreadIds = /* @__PURE__ */ new Set();
   try {
@@ -231545,6 +231609,12 @@
   },
   createThreadEventPruningJob(THREAD_PRUNING_SWEEP_LIMITS),
   {
+    cadenceMs: 0,
+    category: "retention",
+    name: "deleted-thread-purge",
+    run: runDeletedThreadPurgeSweep
+  },
+  {
     cadenceMs: DATABASE_MAINTENANCE_CHECK_INTERVAL_MS,
     category: "maintenance",
     name: "database-maintenance",

Benchmark scripts: https://github.com/leanrails-inc/bb-plugins/tree/main/plugins/thread-cleanup/bb-core (repo may be private; happy to share).

Activity

  1. added theissue type on Nov 9, 2026
  2. added
    threads
    no-repro
    on Nov 9, 2026
  3. bb-slop-cop commented on Nov 9, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · High priority · Medium effort. Labels: threads, perf, no-repro.
    • Reproduction report: ALREADY FIXED on main. Root-cause confidence: high.
    • Root cause: finalization previously triggered a synchronous cascade through thread history. Merged PR Delete threads from bb.db in paced batches through the item sweep runner #7184 replaced it with a persistent, bounded, yielding purge on November 6, 2026.
    • Verification: two clean checkouts of 17c2018ab988e2ed49140821e5a8c854a8f3d3b8; all three server tests passed in each. With 16,384 synthetic events, timers observed partial deletion in both runs; the database suite also passed. The reported disk database and exact installed build were not tested.
    • No new PR: the reported path is already repaired on trusted main; another fix would duplicate the existing change. Reproduction label: no-repro.

    AGENT GENERATED

  4. ymichael commented on Nov 9, 2026

    @ymichael
    Collaborator

    Fixed in #7184

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

    no-reproperfthreads

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions