#7337 · Reconnect retries storage deletion after cleanup has completed
Verdict: REPRODUCED · Root-cause confidence: high for redundant reconnect commands. The reported macOS process counts and outage duration were not measured here.
1. TL;DR
Deleting a thread removes its host storage before a budgeted database purge removes the thread row. Reconnecting a host incorrectly treats those retained rows as unfinished storage cleanup, even when the database already records successful removal. A regression test using the real server reconciliation path and migrated SQLite database emits two deletion requests when only one thread still needs cleanup. The same result occurs for all five eligible lifecycle states in two clean trusted checkouts. The daemon-side process-scanning path explains the amplification risk, but this Linux investigation does not establish the reported macOS outage duration.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Reconnect repeats cleanup for storage already marked deleted. | Verified by execution | All five regression cases fail on trusted main: completed and pending rows both generate deletion RPCs. |
| Queued purges do not suppress the duplicate command. | Verified by execution | Idle and error cases explicitly retain a purge request; the duplicate still appears. |
| Distinct thread deletions can fan out without a shared cap. | Verified by inspection | The guard is keyed by thread ID, while each deletion helper is started without awaiting it. |
| Each macOS cleanup necessarily scans two to ten times. | Qualified | Each lookup starts a fresh lsof on non-Linux Unix. The kill loop makes up to ten lookups, but exits after the first lookup if there are no matching processes. An already absent directory can therefore incur only one scan. |
| Hundreds of lsof processes cause 15–20 second stalls and 30 second timeouts. | Not measured | No macOS host or live bulk-deletion incident was used. These timings and process counts remain reporter observations. |
3. Environment
- Trusted public repository: get-bb/bb. Base:
7c1353d80729983b86ea1555d18b42407f320406, fetched from main on 2026-11-10. - Linux x86_64, kernel 4.19.0-gvisor; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.12.
- Two separate temporary checkouts, called
BASEandVERIFYbelow; both initially detached at the recorded commit. - Real migrated SQLite copies via the existing server test harness. Every case receives a fresh temporary data directory. No listener, real provider, production data, runtime credential, or browser is used; no network port is required.
4. Minimal reproduction
- Create a clean checkout of the trusted commit and install/build the server with existing dependencies:
git clone https://github.com/get-bb/bb.git bb-repro cd bb-repro git checkout --detach 7c1353d80729983b86ea1555d18b42407f320406 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@bb/server
- Save the complete test below as
apps/server/test/public/public-thread-reconnect-storage.test.ts. - Run
pnpm exec turbo run test --filter=@bb/server -- test/public/public-thread-reconnect-storage.test.ts. - Expected: only the still-pending thread generates a storage-delete command. Actual: both the completed thread and pending thread generate commands, failing every case.
The positive control is important: the test waits for the genuinely pending deletion and acknowledges it, so a silent/disconnected transport cannot make the negative assertion pass. Idle/error cases model purge-queued rows; active/starting/stopping cases also test recovery before a purge request exists. The host transport is captured by the existing test harness; a real daemon is not launched.
Complete regression test
import {
getThread,
markThreadDeleted,
markThreadStorageDeleted,
requestThreadPurge,
} from "@bb/db";
import { expect, it } from "vitest";
import { reconcileDaemonReportedThreads } from "../../src/services/threads/thread-lifecycle.js";
import {
listQueuedCommands,
reportQueuedCommandSuccess,
waitForQueuedCommand,
} from "../helpers/commands.js";
import {
seedEnvironment,
seedHostSession,
seedProjectWithSource,
seedThread,
} from "../helpers/seed.js";
import { withTestHarness } from "../helpers/test-app.js";
it.each(["idle", "error", "active", "starting", "stopping"] as const)(
"does not repeat completed storage deletion on reconnect for %s threads",
async (status) => {
await withTestHarness(async (harness) => {
const { host } = seedHostSession(harness.deps);
const { project } = seedProjectWithSource(harness.deps, {
hostId: host.id,
});
const environment = seedEnvironment(harness.deps, {
hostId: host.id,
projectId: project.id,
});
const completed = seedThread(harness.deps, {
projectId: project.id,
environmentId: environment.id,
status,
});
const pending = seedThread(harness.deps, {
projectId: project.id,
environmentId: environment.id,
status: "idle",
});
for (const thread of [completed, pending]) {
markThreadDeleted(harness.db, harness.deps.hub, {
threadId: thread.id,
});
}
markThreadStorageDeleted(harness.db, { threadId: completed.id });
if (status === "idle" || status === "error") {
requestThreadPurge(harness.db, {
now: Date.now(),
threadId: completed.id,
});
}
await reconcileDaemonReportedThreads(harness.deps, {
hostId: host.id,
activeThreadIds: [],
undeliveredEventThreadIds: [],
sameDaemonInstance: false,
});
const retry = await waitForQueuedCommand(
harness,
({ command }) =>
command.type === "thread.storage.delete" &&
command.threadId === pending.id,
);
const commands = listQueuedCommands(harness, "thread.storage.delete");
await reportQueuedCommandSuccess(harness, retry, {
providerCheckpointId: null,
});
expect(commands).toEqual([
expect.objectContaining({ threadId: pending.id }),
]);
expect(getThread(harness.db, completed.id)?.storageDeletedAt).not.toBeNull();
});
},
);
First run — verbatim assertion and summary lines
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
@bb/server:test: Test Files 1 failed (1)
@bb/server:test: Tests 5 failed (5)
@bb/server:test: Duration 7.88s (transform 4.14s, setup 1.20s, import 4.23s, tests 931ms, environment 0ms)
Exit status: 1. The failing array assertion contains one extra thread.storage.delete for the completed-storage thread in every case.
5. Root cause
Host session attachment invokes reconciliation with the reported active thread IDs. Reconciliation selects retained deleted rows across active, idle, error, starting and stopping states, but neither selects nor checks their storage-deletion timestamp. It then requests host cleanup for every deleted row.
for (const thread of pendingThreads) {
if (thread.deletedAt !== null) {
requestThreadStorageDeletion(deps, thread, {
hostId: args.hostId,
id: thread.environmentId,
});
continue;
}
}
The in-flight guard deduplicates only the same thread; it does not cap concurrent cleanup across distinct threads. The periodic finalization sweep already checks storageDeletedAt and finalizes completed cleanup instead of asking the host to repeat it. Purge-queued rows are excluded from that sweep but remain eligible for reconnect reconciliation.
The daemon deletion handler scans process working directories before removing storage. The Unix lsof scanner spawns a machine-wide lookup, and Every list call chooses a fresh platform lookup before filtering directories. The kill loop can repeat the lookup up to five rounds. This makes redundant reconnect commands unnecessary host work, even if storage is already absent. No shared scan promise exists in this code.
6. Proposed fix
Select storageDeletedAt in reconnect reconciliation. For a deleted thread with completed cleanup, call the existing stopped-thread finalizer and continue; otherwise preserve the existing storage-delete retry. This removes the verified root cause while recovering finalization without a new protocol, stored-data format, or daemon policy. Keep the regression as a server lifecycle test.
Cross-thread RPC throttling and shared platform scans would be separate hardening work. They are not required for the small reconnect fix, and this report does not claim to verify or ship them.
7. Verification
The same agent repeated the reproduction, not an independent reviewer. A second new checkout VERIFY was detached at the full base commit, received only the same new test, and used a separate dependency installation, build outputs, temporary migrated database files, and per-case temporary data directories. No port reuse occurs because these tests do not bind listeners.
cd VERIFY pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@bb/server pnpm exec turbo run test --filter=@bb/server -- test/public/public-thread-reconnect-storage.test.ts
Second run — verbatim assertion and summary lines
@bb/server:test: Test Files 1 failed (1)
@bb/server:test: Tests 5 failed (5)
@bb/server:test: Duration 15.33s (transform 11.67s, setup 5.20s, import 7.83s, tests 830ms, environment 0ms)
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
@bb/server:test: AssertionError: expected [ { …(3) }, { …(3) } ] to deeply equal [ ObjectContaining{…} ]
Exit status: 1; the same five redundant-command failures recur. No correction to the server-side finding was necessary. The report qualifies the minimum lsof count: an empty match set takes one scan, not necessarily two.
Minimal fix verification
A local branch from the same freshly fetched trusted main adds five production lines: select the existing storage-deletion timestamp and finalize already-cleaned deleted rows before the RPC branch. Five new regression cases and 25 existing lifecycle/sweep tests pass (30 total across five files). The server typecheck passes. Formatting and whitespace checks pass. The patch contains 82 added text lines across two existing-server-subsystem files, with no deletions, binary files, dependency changes, generated files, migrations, protocol changes, or public API changes.
pnpm exec turbo run test --filter=@bb/server -- test/public/public-thread-reconnect-storage.test.ts test/public/public-thread-lifecycle-ownership.test.ts test/public/public-thread-lifecycle-admission.test.ts test/services/periodic-sweeps.test.ts test/system/periodic-sweep-jobs.test.ts Test Files 5 passed (5) Tests 30 passed (30) pnpm exec turbo run typecheck --filter=@bb/server Tasks: 6 successful, 6 total pnpm exec oxfmt --check apps/server/src/services/threads/thread-lifecycle.ts apps/server/test/public/public-thread-reconnect-storage.test.ts All matched files use the correct format. git diff --check origin/main git diff --numstat origin/main 5 0 apps/server/src/services/threads/thread-lifecycle.ts 77 0 apps/server/test/public/public-thread-reconnect-storage.test.ts
The final checked-in regression omits the reproduction's redundant unchanged-timestamp assertion; its command-count assertion and all five lifecycle cases are unchanged. The fix intentionally does not add a cross-thread concurrency limit or change platform process enumeration.
8. Related issues and pull requests
Issue #6499 concerns daemon drops during server event-loop stalls; it is background context, not evidence of this defect. The target issue had no linked open pull request at investigation time; a separate open-PR search for the numeric issue also returned none. No pull-request code was executed.
9. Appendix
Both frozen installs and server builds succeeded before reproduction. Existing Vite native-config and SQLite experimental warnings were non-fatal. Full raw logs and the test source are retained locally outside this public reports repository; relevant verbatim lines and the complete repeatable test are inline above, as required by this site's artifact policy. No screenshots are needed for this nonvisual lifecycle bug.
Issue text was treated solely as untrusted claims. Its proposed implementation was not executed; the test and minimal fix were derived from the trusted repository path. No real bulk deletion or production session was used.
Read-only GitHub metadata established Type, Priority, Effort, labels and cross-references. Trusted source commands additionally included git fetch origin main, git rev-parse origin/main, git log, and source searches. All GitHub metadata writes use the designated SlopCop entrypoint.