Skip to content

Allow machine removal while preserving read-only thread history - #4090

Merged
ymichael merged 14 commits into
mainfrom
bb/unable-to-remove-machine-thr_u5bntygns4
Sep 24, 2026
Merged

ymichael merged 14 commits into
mainfrom
bb/unable-to-remove-machine-thr_u5bntygns4

Conversation

@ymichael

@ymichael ymichael commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Machine removal was blocked by unarchived threads, and persistent environment cleanup prevented removing compute while keeping thread history. Removal state lived on thread runtime even though the machine belongs to the environment, which made retained workspaces and their subscribers harder to represent consistently. The packages CI job also hit a timing race in the browser automation process test: it checked a child PID immediately after the supervisor exited.

What changed

  • Allow explicit removal of disposable and persistent machines, stop active work, and preserve threads as read-only history. Keep the host row for historical references. Automatic cleanup still respects live threads.
  • Propagate environment cleanup failures to machine removal and let Retry cleanup retry failed environments before removing compute.
  • Expose hostLifecycle (active, removing, cleanup-failed, or removed) on environment reads, lists, and included thread environments. Notify environment subscribers when the host lifecycle changes. The app uses this state for workspace labels, read-only banners, and unavailable execution controls; the sidebar remains unchanged.
  • Show the read-only thread banner collapsed by default: only the status ("Machine removed", "Machine removal in progress", "Machine cleanup failed", "Environment unavailable") is visible, and its explanation expands from the status toggle using the banner's existing section primitives.
  • List up to five of the machine's unarchived threads in the remove dialog, followed by "and N more". This adds an optional hostId filter to GET /threads, the SDK's threads.list, and bb thread list --machine <id-or-name> (alias --host); the total comes from the existing threads.count({ hostId }).
  • Keep the existing machine list labels ("Removing", "Cleanup failed"), machine detail Danger zone copy, and remove dialog copy.
  • Record intentional interruption as host-removed, with “Stopped because the machine was removed” in the timeline. Bump HOST_DAEMON_PROTOCOL_VERSION to 218 for the shared wire schema change, following version 217 on main.
  • Reject queued messages through the API while a machine is removing or removed. The existing remove command uses the same behavior as the UI.
  • Document --machine in the thread guide and update the verify-bb Remove host scenario. Machine guide, skill, and maintainer doc wording is unchanged.
  • Raise the SplitWorkspaceRoute brotli budget by 583 bytes for the added UI. CI measured 611.5 KB against the former 611.3 KB limit; the boot payload and forbidden-package checks remain unchanged.
  • Make the browser automation process test wait briefly for the OS to reap terminated children before checking their PIDs.

How you verified

  • Rebased on main (36fdd7f).
  • Passed the full Turbo repository typecheck (99 tasks), including SDK and environment provider fixtures.
  • Passed database (594), domain (213), core UI (30), CLI (854), browser automation (77), app (5,062), SDK (113), and worktree provider (96) tests. The browser automation suite includes the test that failed in CI.
  • The broad local server run passed 3,143 tests and timed out in two unrelated installer script tests with five-second limits. Rerunning that installer file alone passed 46 of 47 tests; the remaining test again hit its five-second limit while running three installer invocations. The changed server tests passed.
  • For the follow-up commit: typecheck (app, server, CLI, SDK), lint, and focused tests passed — app banner, machine settings, prompt area and machine tests (169), server thread data (83, including a new hostId list filter test), and CLI (854). The app build and bundle budget check passed (SplitWorkspaceRoute 611.6 KB of 611.9 KB brotli).
  • Drove the app on a fresh dev instance against base 36fdd7f17 and this branch with identical seeded machines (removed, removing, cleanup-failed, active with a live thread) and the same scripted browser steps. Before, removing the provider machine failed with "Archive or delete every thread on this machine before removing it"; after, the dialog listed the thread, removal succeeded, and the thread became read-only. A machine with eight unarchived threads showed five titles and "and 3 more". The banner rendered collapsed and expanded on click; machine list, detail, and dialog copy matched base.
  • git diff --check passed.
  • The documentation trim commit changes only Markdown; git diff --check passed.

AGENT GENERATED

@ymichael
ymichael force-pushed the bb/unable-to-remove-machine-thr_u5bntygns4 branch from 61c6409 to 696db52 Compare September 22, 2026 19:39
@ymichael
ymichael force-pushed the bb/unable-to-remove-machine-thr_u5bntygns4 branch from 696db52 to bbefa24 Compare September 23, 2026 22:24
@ymichael
ymichael merged commit dd95291 into main Sep 24, 2026
18 checks passed
@ymichael
ymichael deleted the bb/unable-to-remove-machine-thr_u5bntygns4 branch September 24, 2026 21:17
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]>
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.

1 participant