Repository navigation
Keep destroyed environment rows instead of pruning them - #4259
Merged
Merged
Conversation
Pruning a destroyed environment rewrote every event row that referenced it to clear events.environment_id, and it cleared threads.environment_id, so a later thread delete could no longer reach the host that holds its storage. Remove the destroyed-environment prune sweep. Index the two per-tick environment queries so retained rows are skipped: a partial provider lifecycle index, and a partial owner-thread index for the preparation-owner release. Fixes #4161 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
ymichael
force-pushed
the
bb/investigate-issue-4161-in-bb-thr_vihaah7ffx
branch
from
September 24, 2026 17:24
b0d096c to
9320ce7
Compare
albrand
pushed a commit
to alb-hold/bb
that referenced
this pull request
Sep 24, 2026
Conflicts resolved with fork behavior kept and upstream API shape taken: - packages/db environments: fork's nullable-provider listProviderLifecycleEnvironments with upstream get-bb#4259's raw status predicate (matches the new partial index). - session-owner-side-effects: fork exceptThreadIds plus upstream includeStopping; fork-adoption passes includeStopping: false. Upstream's settleRemovedHostWork again interrupts provisioning on machine removal (lost in c7f8d85). - provider-orchestration test: fork checkout-retirement tests kept; the prune test goes with upstream's removal of pruneDestroyedEnvironments. - server-moved test: fork's deterministic flush harness kept. - Fork-only toEnvironmentResponse callers pass db (upstream signature). - pnpm-lock: stale picomatch 4.0.4 snapshots normalized to upstream's 4.0.5. Co-Authored-By: Claude Opus 5.5 <[email protected]>
SawyerHood
added a commit
that referenced
this pull request
Sep 25, 2026
## Human comments ## What was wrong Many server, db, domain and contract tests duplicated a stronger test at the owning boundary. Examples: - three "Unsupported tool" variants that hit the same fallback branch; - twin public-thread and thread-parent tests; - ten "ships X enabled/disabled" builtin tests. Others pinned incidental literals, such as exact gzip byte counts in `payload-size.test.ts` and copied icon and logo lists. Some couldn't fail at all: a check for a connect route that doesn't exist, and a "migrates without throwing" test that every db test already repeats. A few kept dead production code alive: - `hasCompletedEventLoopWorkForTests` (no callers since #4259) - `pruneThreadEventsBeforeSequence` (no callers since #3766) - `claimQueuedThreadMessage` - `createHostDaemonClient` in the host-daemon-contract source ## What changed Found by a read-only test audit using the repo `test-audit` skill (#4361). - **Dead production code removed, with its tests:** - `hasCompletedEventLoopWorkForTests` - `pruneThreadEventsBeforeSequence` and its transaction variant. The other prune wrappers are unchanged. - `claimQueuedThreadMessage`. Test call sites use `claimQueuedThreadMessageGroup` with `{ kind: "explicit-send" }`. - `isAgentDelegatedChildThread`, inlined. - **Tests rewritten or moved:** - The randomized `timeline-context-order-cache` test now prunes through the live `advanceThreadPruning` path, and asserts that rows are actually pruned. - `createHostDaemonClient` moves into its only user, `internal-session-protocol-version.test.ts`. The wire schema is unchanged, so no `HOST_DAEMON_PROTOCOL_VERSION` bump. - **Duplicates folded into their keepers or tables:** the builtin plugin defaults, `requestMatchesEntityTag` cases and pending-interaction `reason`. - **Not in this PR:** the `thread_dynamic_context_file_states` table (no writer since #2140) and its schema test. Dropping it needs a migration decision. Production +1/−117, tests +137/−1555. ## How you verified - `pnpm exec turbo run test lint typecheck` passes for `@bb/server`, `@bb/db`, `@bb/domain`, `@bb/server-contract` and `@bb/host-daemon-contract`. - The only failures were `@bb/server` timeouts at load average 40. The base commit shows them too, and they pass when rerun alone. - oxlint's `no-comments` errors match base. - An independent verifier used before and after worktrees on 175d5ac. For each removed test it wrote the bug that test catches as a production change, then checked that the old test fails and a remaining test also fails. - Result: 44 OK, 5 with no unique failure mode, 0 lost. - Builtin plugin icon names stay covered by `PluginIcon.test.tsx` ("resolves every named branding.icon the shipped plugins declare"). - Both `isParentNotifiableChildThread` clauses stay caught. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Sep 26, 2026
…ead storage (#4328) ## Human comments ## What was wrong #4259 stopped the destroyed-environment prune, so newly deleted threads now keep their environment and reach the host's `thread.storage.delete`. Two gaps remained around #4160: - **Removed machines.** Deleting a thread whose machine was removed (the host row is kept with `destroyedAt` set since #4090) sent `thread.storage.delete` to a host that no longer exists. The command never succeeded, so the thread stayed a soft-deleted tombstone and the lifecycle sweep retried it forever. Before #4259 the 7-day prune cleared these by accident. - **Existing orphans.** Threads deleted after their environment was pruned were hard-deleted without contacting the host, so their `thread-storage/<threadId>` folders stayed on disk. No thread row is left to recover the owning host, and no code path would ever remove them. The reporter had about 1,400 such folders. ## What changed - **`requestThreadStorageDeletion`** (`apps/server/src/services/threads/thread-lifecycle.ts`): when the thread's environment is on a destroyed host, storage is marked deleted and the thread finalized straight away. A removed machine's storage is gone or unreachable. - **Orphaned folder cleanup as an idle periodic sweep** (new `apps/server/src/services/threads/thread-storage-orphans.ts`, registered in `PERIODIC_SWEEP_JOBS` as `thread-storage-orphan-cleanup`, category `orphan-cleanup`, cadence 60s): - **Idle gate.** A tick does nothing unless `isDatabaseMaintenanceIdle(getDatabaseMaintenanceActivity(db))` reports no active or starting threads, environment provisioning, pending interactions, or project deletions. This is the same gate the thread pruning and database maintenance sweeps use. Idle is checked again before every removal. - **Background passes.** For each connected host, the tick starts at most one background pass and returns immediately. Daemon RPCs can take up to the 30s timeout, so the sweep tick never waits on them. - **One listing per daemon session.** The first pass lists the top level of `<dataDir>/thread-storage` with `host.browse_directory` and keeps only folder names that pass `isRawThreadId`. It looks them up in `threads` 1,000 at a time, yielding between batches, via the new `listExistingThreadIds`. The folders with no thread row become that session's queue. - **Bounded, resumable passes.** Each pass takes at most 100 removals or 10s of elapsed time from the queue, deleting one folder at a time with `host.remove_path` and the storage root as `rootPath`. - An entry the daemon rejects (for example `invalid_path` for a symlink) is logged and leaves the queue, so it cannot starve later orphans. - An empty queue marks the session clean, so it isn't listed again until the daemon reconnects. - **Parking.** A removal that times out (`command_timeout`), an unavailable host (`host_unavailable`), or an unexpected error parks the session's queue until a new daemon session. A timed-out `host.remove_path` keeps running on the daemon, so starting more deletions would pile them up. - **Safety guards:** - folders are listed before the database is read, and a folder is only created after its thread row, so a thread created mid-run can't look orphaned - any thread row counts as "keep": live, archived, or deleted but still waiting for storage deletion - files and names that aren't thread IDs are ignored - passes stop when a server move freezes the server or the machine's daemon session changes - `callHostOnlineRpc` requires an active, connected machine and never wakes a suspended one - **Wire:** no change. The cleanup reuses the existing `host.browse_directory` and `host.remove_path` daemon commands, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged and already-installed machines work. - **Known risk (accepted):** the cleanup trusts the server database. If the database is rolled back or replaced while a machine keeps its data dir (`bb server unlock` after a move, `bb server import` into an existing install, restoring a `bb.db` backup), folders of threads created after that snapshot are deleted once the app is idle. - **Deviation from the issue:** the issue proposed storing the host on each thread and adding the directory size to `bb thread show --json`. #4259 made the first unnecessary. The second is not included. ## How you verified - **`apps/server/test/threads/delete-on-removed-machine.test.ts` (new):** removes a machine through `DELETE /hosts/:id`, deletes its thread, runs the lifecycle sweep, and expects the row gone with no `thread.storage.delete` queued. Failed on main (the row remained); passes with the change. - **`apps/server/test/threads/thread-storage-orphans.test.ts` (new, 7 tests):** - the sweep skips while a thread is active, with no daemon calls - a backlog of 150 orphans is removed across two passes with exactly one listing, and a third sweep on the cleaned session makes no calls - a zero elapsed budget lists but removes nothing - an orphan rejected with `invalid_path` is followed by the next orphan on the next pass without re-listing - a removal that never answers parks the queue: on a fake clock past the 30s timeout the pass settles, and a second pass starts no further removal. The test fails with parking removed. - selection: of 1,000 leading orphans, a live thread, a soft-deleted thread, a `workflows` folder and a thread-named file, only the orphans are removed, and the live thread sits after the first 1,000-ID batch - a rejected removal doesn't stop later removals in the same pass - **Live dev server** (`pnpm start:worktree`, 3,000 seeded threads, 300 orphan folders): the idle sweep removed the orphans in 100-attempt passes about 60s apart (99, 100, 100 and 1 removed; the first pass's 100th attempt was the refused symlink). It kept all live folders, `workflows`, the thread-named file, and the symlink along with its outside target. A base server at `dcc58375cc` with the same fixture removed nothing. The removed-machine path was also checked on both through the API and `bb:dev thread delete`. - **Real daemon handlers:** I ran `browseHostDirectory` and `removeHostPath` against a temporary `thread-storage` folder. They listed both thread folders and removed only the targeted one. - **Cost at scale:** measured with fake thread IDs. 3,000 folders: 302 KB listing, ~2 ms parse, ~7 ms lookup. 50,000 folders: 5 MB listing, ~13 ms parse, ~76 ms total lookup (split into yielded batches). - **Commands at `e0426507c0`:** - `pnpm exec turbo run typecheck lint --filter='...[dcc5837]'`: 10/10 - `pnpm exec turbo run test --filter=@bb/server`: 3218 passed, 1 skipped, 1 failed. The failure was a 5s timeout in `install-machine-script.test.ts`, the shell-script flake; that file passes alone (47/47). - CI run 36215870353: success Fixes #4160 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
A sweep deleted destroyed environment rows 7 days after destruction.
events.environment_idandthreads.environment_idboth referenceenvironmentswithON DELETE SET NULL, so before each delete the sweep had to clear the environment reference on every event row. SQLite rewrites the whole record to change one column, so every destroyed environment's full event history was rewritten (#4161). The same delete also clearedthreads.environment_id. A laterDELETE /threads/:idthen couldn't tell which host held the thread'sthread-storage/<threadId>directory, marked storage as deleted, and orphaned the directory (#4160). The sweep existed only to free a ~450-byte environment row.Investigating #4161: on a 5.9 GB real database (2.29M events, 132k events on 126 destroyed environments), the detach UPDATE took 0.4 ms p50 / 23 ms max and the candidate SELECT 1.1 ms p50 / 24 ms max. The reported 1–8 s statements did not reproduce. The rewrite volume is real either way (~986k rows on the reporter's host), and #4160 is a correctness bug with the same cause.
What changed
pruneDestroyedEnvironments, its sweep job, and its TTL and batch constants (packages/db/src/data/sweeps.ts,apps/server/src/services/system/periodic-sweeps.ts). Destroyed environment rows are now kept. Threads keep their environment, so thread deletion reaches the host, and event rows are never rewritten.packages/db/src/data/environments.ts,packages/db/src/schema.ts, migration0131_environment_retention_indexes):listProviderLifecycleEnvironmentsuses a new partial indexenvironments_provider_lifecycle_idxthat leaves outdestroyed/removedrows. It previously walked every row for the provider.releaseFinishedEnvironmentPreparationOwnersonly touches rows that have an owner.environments_owner_thread_idxis now partial (WHERE owner_thread_id IS NOT NULL) with the same uniqueness semantics. Previously it rewrote every removed environment on every tick.IF EXISTS/IF NOT EXISTS, following 0106, 0107 and 0125.events_environment_idxstays, because project and host deletion still cascade throughON DELETE SET NULL.environment-deletedchange kind is now never emitted (the prune was its only source). It's part of the plugin SDK surface, so I left it rather than bump the SDK here.destroyed-environment-pruneblocks the event loop for 1–8 s per statement #4161's proposed fixes: none of the time-budget, side-table or worker-thread changes. The rewrite is removed instead of bounded.How you verified
apps/server/test/services/periodic-sweeps.test.ts:runPeriodicSweeps.environment_idsurvive, andDELETE /threads/:idqueuesthread.storage.deletefor the archived thread.packages/db/test/query-plans.test.ts:listProviderLifecycleEnvironmentssearchesenvironments_provider_lifecycle_idx, and the release UPDATE searchesenvironments_owner_thread_idx. Neither query scans the table.bb.db. It took 28 ms, andEXPLAIN QUERY PLANshows both queries on the new indexes.pnpm exec turbo run typecheck lint --filter='...[origin/main]': passpnpm exec turbo run test --filter=@bb/db --filter=@bb/server: db 588/588, server 3158 passed / 1 skippedFixes #4161
Refs #4160
🤖 Generated with Claude Code