Skip to content

Finish deleting threads on removed machines and clean up orphaned thread storage - #4328

Merged
ymichael merged 6 commits into
mainfrom
bb/investigate-and-fix-issue-4160-thr_ehpewydf7k
Sep 26, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/investigate-and-fix-issue-4160-thr_ehpewydf7k

Conversation

@ymichael

@ymichael ymichael commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

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 Allow machine removal while preserving read-only thread history #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 Keep destroyed environment rows instead of pruning them #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. Keep destroyed environment rows instead of pruning them #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='...[dcc58375cc]': 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

AGENT GENERATED

ymichael and others added 6 commits September 24, 2026 21:54
Deleting a thread on a removed machine 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 destroyed-environment prune cleared these by accident.

A removed machine's storage is already gone or unreachable, so storage
deletion now settles immediately when the environment's host is destroyed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Threads deleted after their environment row was pruned (before #4259) were
hard-deleted without asking the host to remove thread-storage/<threadId>,
leaving folders on disk that no server path would ever clean up.

When a machine connects, the server now lists the top level of its
thread-storage directory with host.browse_directory and removes each
thread-id-shaped folder with no thread row (live, archived, or deleted)
using host.remove_path scoped to the storage root. Folders are listed
before the database is read, so a thread created mid-run is never treated
as an orphan. Thread ids are looked up in batches of 1,000 with a yield
between batches, so a large listing doesn't stall the server. The cleanup
stops if the server move freezes, the server shuts down, or the machine's
session changes. It reuses existing daemon commands, so the protocol
version is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Creating a host row also emits host-connected, before the daemon session
exists. On a machine's first enrollment the orphan cleanup ran at that
moment and logged "Thread storage orphan cleanup failed: Host is not
connected". It now returns quietly until a daemon is registered; the
registration's own host-connected event runs the cleanup.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A host.remove_path that exceeds the 30s RPC timeout keeps running on the
daemon; the server only stops waiting. Catching that error and moving on
started the next recursive delete while the previous one was still in
progress, so a slow backlog could pile up concurrent deletions.

The pass now stops on a timeout, an unavailable host, or an unexpected
error, and continues only past failures the daemon reported for a single
entry, such as a rejected symlink. The next connect retries the rest.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Move the cleanup off the host-connected listener and onto the periodic
sweep framework the database sweeps use. The thread-storage-orphan-cleanup
job runs every 60s and skips unless isDatabaseMaintenanceIdle reports no
active threads, provisioning, pending interactions, or project deletion.
Idle is rechecked before every removal.

Each connected host's thread-storage is listed once per daemon session into
a queue of orphaned ids. Passes consume the queue in the background with at
most 100 removals and a 10s elapsed budget, so the sweep tick never waits on
daemon RPCs. An entry the daemon rejects leaves the queue, so it cannot
starve later orphans, and an empty queue marks the session clean so it is not
listed again until the daemon reconnects. A timeout, unavailable host, or
unexpected error parks the session's queue, so later passes cannot stack
deletions behind one that may still be running on the daemon.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@ymichael
ymichael merged commit f3b2460 into main Sep 26, 2026
18 checks passed
@ymichael
ymichael deleted the bb/investigate-and-fix-issue-4160-thr_ehpewydf7k branch September 26, 2026 04:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Thread storage is never removed for a deleted thread whose environment row was already pruned

1 participant