All reports · Issue #7281

#7281 · Thread deletion yields between database purge batches

2026-11-09 · Bug · High priority · Medium effort · threads, perf · base 17c2018ab988e2ed49140821e5a8c854a8f3d3b8

Verdict: ALREADY FIXED on trusted main. Root-cause confidence: high for the historical synchronous cascade and its removal from finalization. This is not a claim about which published installer includes the fix.

1. TL;DR

A large synchronous SQLite cascade can monopolize the server's JavaScript thread. The reported direct cascade at thread finalization is no longer present on the tested main commit: finalization queues a persistent purge instead. PR #7184 merged on November 6, 2026 at 22:58:19 UTC, before this issue was created on November 9. Two fresh-checkout runs with 16,384 synthetic events each showed timers executing while only part of the event history had been deleted. No new production patch or duplicate PR is warranted.

2. Claims vs findings

Claim examinedFindingEvidence
Finalization immediately deletes the thread and cascades all history.Already fixed on main.Finalization calls requestThreadPurge; the request leaves all 16,384 events intact and the deleted thread returns HTTP 404.
Large history cleanup runs without yielding.Not observed on main.Timers observed partially deleted histories 121 times in checkout A and 102 times in checkout B.
The installed version stalls for tens of seconds on a multi-gigabyte database.Unverified.No reporter database, installed bundle, cold-cache disk benchmark, or EACCES recovery was used. Current main has different code and SQLite versions.
FTS redesign and checkpoint tuning would improve disk-bound tail latency.Unverified; separate performance work.This investigation does not test those proposals or reproduce the reported checkpoint outlier.

3. Environment

4. Minimal reproduction

  1. Make a clean trusted checkout at the recorded commit, then install and build:
    git clone https://github.com/get-bb/bb.git bb-7281-A
    cd bb-7281-A
    git checkout --detach 17c2018ab988e2ed49140821e5a8c854a8f3d3b8
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@bb/server
  2. Save the authored reproduction test included below as apps/server/test/threads/issue-7281-repro.test.ts. Run:
    pnpm exec turbo run test --force --filter=@bb/server -- test/threads/issue-7281-repro.test.ts test/threads/thread-purge.test.ts --silent=false
    pnpm exec turbo run test --filter=@bb/db -- test/data/thread-purges.test.ts
  3. The test seeds a 16,384-event idle thread in one transaction, issues the real DELETE route, then runs the real purge sweep. A timer queries the remaining event count while deletion proceeds. Expected on fixed main: HTTP 200, all history retained immediately after marking deleted, GET returns 404, at least one timer sees a partially deleted history, and the sweep finally removes both history and thread. A regression to a single synchronous cascade fails the retained-history or partial-deletion assertion.
RunDELETE requestPurgeTimer ticks during partial deletionLargest observed timer gap
A18 ms290 ms12113 ms
B, second clean checkout17 ms258 ms10216 ms

Both server runs: 3 tests passed across 2 files. Additional database suite in A: 2 tests passed, covering row/byte limits, oversized-event progress, queue ordering, and lifecycle dependencies. All five distinct tests passed. No test was intentionally made to fail because this is an already-fixed report, not a proposed fix.

Authored test

import { performance } from "node:perf_hooks";
import { expect, it } from "vitest";
import { sql } from "drizzle-orm";
import { getThread } from "@bb/db";
import { threadScope } from "@bb/domain";
import { threadPurgeSweep } from "../../src/services/threads/thread-purge.js";
import {
  seedHostSession,
  seedProjectWithSource,
  seedStoredEvent,
  seedThread,
} from "../helpers/seed.js";
import { withTestHarness } from "../helpers/test-app.js";

it("services timers between partial deletions of a large deleted thread", async () => {
  await withTestHarness(async (harness) => {
    const { host } = seedHostSession(harness.deps);
    const { project } = seedProjectWithSource(harness.deps, { hostId: host.id });
    const thread = seedThread(harness.deps, { projectId: project.id });
    const totalEvents = 16_384;
    harness.db.transaction(() => {
      for (let sequence = 1; sequence <= totalEvents; sequence++) {
        seedStoredEvent(harness.deps, {
          data: { text: "synthetic retention measurement ".repeat(16) },
          scope: threadScope(),
          sequence,
          threadId: thread.id,
          type: "thread/identity",
        });
      }
    });
    const countEvents = () =>
      harness.db.get<{ count: number }>(
        sql`SELECT count(*) AS count FROM events WHERE thread_id = ${thread.id}`,
      )?.count ?? 0;
    const requestStartedAt = performance.now();
    const response = await harness.app.request(`/api/v1/threads/${thread.id}`, {
      method: "DELETE",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ childThreadsConfirmed: false }),
    });
    const requestMs = performance.now() - requestStartedAt;
    expect(response.status).toBe(200);
    expect(getThread(harness.db, thread.id)?.deletedAt).toEqual(expect.any(Number));
    expect(countEvents()).toBe(totalEvents);
    expect((await harness.app.request(`/api/v1/threads/${thread.id}`)).status).toBe(404);
    let timerTicks = 0;
    let partialDeletionTicks = 0;
    let maximumGapMs = 0;
    let previousTickAt = performance.now();
    const timer = setInterval(() => {
      const now = performance.now();
      maximumGapMs = Math.max(maximumGapMs, now - previousTickAt);
      previousTickAt = now;
      timerTicks++;
      const remaining = countEvents();
      if (remaining > 0 && remaining < totalEvents) partialDeletionTicks++;
    }, 1);
    const purgeStartedAt = performance.now();
    try {
      await threadPurgeSweep(harness.deps).run(harness.deps, Date.now());
    } finally {
      clearInterval(timer);
    }
    expect(partialDeletionTicks).toBeGreaterThan(0);
    expect(countEvents()).toBe(0);
    expect(getThread(harness.db, thread.id)).toBeNull();
    console.log(JSON.stringify({
      totalEvents,
      requestMs: Math.round(requestMs),
      purgeMs: Math.round(performance.now() - purgeStartedAt),
      timerTicks,
      partialDeletionTicks,
      maximumGapMs: Math.round(maximumGapMs),
    }));
  });
}, 30_000);

5. Root cause and existing repair

The trusted merge diff for 72323b5ebc27c0aa63657c5fa4b25a085a69f42d replaces the historical direct deleteThread call with requestThreadPurge. The low-level deleteThread primitive still performs a synchronous parent DELETE; invoking it before removing a large child history is the historical root cause. This investigation did not execute the older implementation or validate the issue's exact timings.

  1. Finalization waits for storage deletion and provider work, then persists a purge request rather than deleting the history.
  2. thread_purges stores requests durably. deleteThreadPurgeBatch caps events by row count and payload bytes, then removes bounded search/history/attachment rows.
  3. Purge transactions use at most 64 event rows / 512 KiB of event data, or 128 rows from the other batched tables, before final parent deletion.
  4. The sweep loop targets 10 ms slices and awaits a timer between slices. It rests longer while clients or running threads exist. Periodic scheduling runs this as a background sweep.

These are bounded-work heuristics, not a strict maximum transaction duration. Oversized individual events, other cascade tables, filesystem stalls, or WAL checkpoint work can still cost more than the slice target. The synthetic run does not prove that all disk-heavy deletion workloads are stall-free.

6. Fix proposal and PR decision

Keep the existing paced-purge implementation. No new PR: the reported single-cascade finalization path was already replaced by merged PR #7184, and the defect is not reproduced on trusted main. If stalls persist on a build containing that commit, the next experiment is a scrubbed disk-backed database with search rows and per-transaction/checkpoint timings. FTS layout changes would need separate migration and product review, not an automatic simple fix.

7. PR metadata

GitHub issue timeline and the open-PR search for #7281 showed no linked open PRs at investigation time. Existing merged #7184 is cited as trusted-main history, not a newly checked-out PR branch; no PR code was executed outside the recorded main checkout.

8. Related issues

#5730 concerns long-term database growth; #5192 concerns server stalls. Neither was modified in this run.

9. Verification

The same agent repeated the reproduction in a second clean detached checkout at exactly 17c2018ab988e2ed49140821e5a8c854a8f3d3b8. Before adding only the authored test, its worktree was clean. It had its own frozen install and build; the test command used --force so Turbo executed the tests rather than replaying cached test results. Its real migrated database and temporary harness data directory were new; no network server ports were needed. Result: 3/3 server tests passed, 102 timer observations of partial deletion, zero remaining target events, and no remaining target thread. No correction to the first-run conclusion was required. This is a repeat run by the same agent, not independent verification.

10. Evidence and limits

Issue text, embedded patch, and external links were treated as untrusted claims. No supplied patch, benchmark, external repository, installed bundle, or real-user database was fetched or run. Code links above were checked against the recorded trusted main files. Screenshots are not applicable. Root-cause confidence is high for the changed call path; confidence does not extend to untested disk-tail latency or the reported installed build.

The test and both server-run outputs are included inline. Raw local artifacts are retained outside the published site. The database suite also reported Test Files 1 passed (1); Tests 2 passed (2). Frozen installs and scoped server builds succeeded. Builds emitted an existing SDK declaration warning about child_process; Vitest emitted configuration and experimental-SQLite warnings. They did not cause failures.

First run output

 RUN  v4.1.12 checkout-A/apps/server
@bb/server:test: 
@bb/server:test: (node:2732) ExperimentalWarning: SQLite is an experimental feature and might change at any time
@bb/server:test: (Use `node --trace-warnings ...` to show where the warning was created)
@bb/server:test: (node:2734) ExperimentalWarning: SQLite is an experimental feature and might change at any time
@bb/server:test: (Use `node --trace-warnings ...` to show where the warning was created)
@bb/server:test:  ✓ |@bb/server| test/threads/thread-purge.test.ts (2 tests) 821ms
@bb/server:test: stdout | test/threads/issue-7281-repro.test.ts > services timers between partial deletions of a large deleted thread
@bb/server:test: {"totalEvents":16384,"requestMs":18,"purgeMs":290,"timerTicks":121,"partialDeletionTicks":121,"maximumGapMs":13}
@bb/server:test: 
@bb/server:test:  ✓ |@bb/server| test/threads/issue-7281-repro.test.ts (1 test) 2668ms
@bb/server:test:    ✓ services timers between partial deletions of a large deleted thread  2047ms
@bb/server:test: 
@bb/server:test:  Test Files  2 passed (2)
@bb/server:test:       Tests  3 passed (3)
@bb/server:test:    Start at  17:51:21
@bb/server:test:    Duration  12.12s (transform 11.00s, setup 3.71s, import 11.48s, tests 3.49s, environment 0ms)
@bb/server:test: 

 Tasks:    10 successful, 10 total
Cached:    0 cached, 10 total
  Time:    41.672s 

Second clean run output

 RUN  v4.1.12 checkout-B/apps/server
@bb/server:test: 
@bb/server:test: (node:3631) ExperimentalWarning: SQLite is an experimental feature and might change at any time
@bb/server:test: (Use `node --trace-warnings ...` to show where the warning was created)
@bb/server:test: (node:3632) ExperimentalWarning: SQLite is an experimental feature and might change at any time
@bb/server:test: (Use `node --trace-warnings ...` to show where the warning was created)
@bb/server:test:  ✓ |@bb/server| test/threads/thread-purge.test.ts (2 tests) 825ms
@bb/server:test: stdout | test/threads/issue-7281-repro.test.ts > services timers between partial deletions of a large deleted thread
@bb/server:test: {"totalEvents":16384,"requestMs":17,"purgeMs":258,"timerTicks":102,"partialDeletionTicks":102,"maximumGapMs":16}
@bb/server:test: 
@bb/server:test:  ✓ |@bb/server| test/threads/issue-7281-repro.test.ts (1 test) 2548ms
@bb/server:test:    ✓ services timers between partial deletions of a large deleted thread  1938ms
@bb/server:test: 
@bb/server:test:  Test Files  2 passed (2)
@bb/server:test:       Tests  3 passed (3)
@bb/server:test:    Start at  17:52:25
@bb/server:test:    Duration  10.21s (transform 8.84s, setup 2.47s, import 9.79s, tests 3.37s, environment 0ms)
@bb/server:test: 

 Tasks:    10 successful, 10 total
Cached:    0 cached, 10 total
  Time:    37.085s 

> AGENT GENERATED