Skip to content

Bound environment teardown retries and add guarded recovery - #5961

Merged
brsbl merged 15 commits into
mainfrom
bb/fix-endless-environment-teardown-retries-thr_7y7sh3cxeb
Oct 22, 2026
Merged

brsbl merged 15 commits into
mainfrom
bb/fix-endless-environment-teardown-retries-thr_7y7sh3cxeb

Conversation

@brsbl

@brsbl brsbl commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Interrupted setup cancellation escaped teardown failure bookkeeping, causing endless retries. Detached hooks can survive daemon exit, so reboot alone cannot prove termination. See the interrupted-setup report.

What changed

  • Failed teardown backs off for 1, 2, 4 and 8 minutes, then stops at “Needs recovery.”
  • bb environment cleanup <id> --recover acknowledges interrupted hooks after inspection and retries removal.
  • RuntimeManager setup records its operation before dispatch; confirmed script failures finish the marker and permit retry.
  • Recovery refuses active hooks, workspace cwd/mapped paths, and unreadable same-UID processes. It kills nothing.
  • Processes owned by other users need separate inspection. Workspace inspection requires Linux.
  • The additive inspection RPC uses protocol 249; older compatible daemons receive an upgrade-required error without an unsupported command.
  • CLI help, the environment guide, SDK recovery input, and Plugin Guide describe the new behavior.

How you verified

  • Regression tests on main failed for both persisted-hook and missing-hook cases.
  • Remote CI on 45ca9be6d772e45d3d65cbfeda3ea7d8a6207d92: passed.
  • Independent review found no blocking issues; the cancellation follow-up below remains deferred.
  • Repeatable isolated e2e on the same head: passed. Script and instructions.
  • Compatibility tests require zero inspection requests to accepted older daemons and preserve unfinished hooks until supported recovery.
Repeatable e2e results

The committed script launches one fresh runtime, interrupts real setup, and advances cleanup explicitly while checking persisted backoff deadlines. Both terminal counts are observed for 75 seconds. Recovery is exercised before and after the surviving process exits.

HEAD 45ca9be6d772e45d3d65cbfeda3ea7d8a6207d92
PASS real setup survives isolated daemon restart; operation remains unresolved
PASS backoff deadlines 1/2/4/8 minutes; explicit cleanup advances five failures to Needs recovery
PASS no retries for 75 seconds: interrupted setup 5 -> 5; legacy 7873 -> 7873
PASS recovery refuses surviving same-UID workspace process without deleting workspace
PASS recovery after process exit finishes hook, runs teardown, and removes workspace
PASS legacy fixture recovers after stopping at 7873 attempts
PASS owned runtime released; automated e2e complete
Non-blocking follow-up

A confirmed setup cancellation can leave its setup marker unresolved. The settlement condition at environment-engine.ts:1493 omits provision_cancelled, although environment-lifecycle-script.ts:301 verifies termination before that outcome. Retrying can therefore require explicit recovery. Follow-up: settle proven cancellations while keeping ambiguous and unverified outcomes blocked. This remains deferred alongside durable process ownership and automatic restart recovery.

Research baseline and reuse

Baseline: 405592c0b71b1655a6ab2e1cc7498b5beeb78caa. Read the lifecycle/hook implementations, schema, handshake and their Git histories.

Fixes #5960

BB-Thread-ID: thr_7y7sh3cxeb

AGENT GENERATED

@brsbl brsbl changed the title Bound interrupted environment cleanup and add guarded recovery Bound environment teardown retries and add guarded recovery Oct 21, 2026
@brsbl
brsbl marked this pull request as ready for review October 21, 2026 04:11
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-21T04:11:41.474796Z
We couldn’t complete this review. Comment @codex review to try again.
1d72888 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@brsbl
brsbl merged commit 8160529 into main Oct 22, 2026
48 checks passed
@brsbl
brsbl deleted the bb/fix-endless-environment-teardown-retries-thr_7y7sh3cxeb branch October 22, 2026 03:30
ymichael added a commit that referenced this pull request Nov 14, 2026
Unarchiving a thread after its environment's delete was requested but
before the removal started left the request pending forever: the sweep
skipped environments with live threads and never cleared it, and the
next archive removed the worktree at once, skipping both graces. The
sweep now withdraws a removal that has not started once a live thread
uses the environment again.

When the same daemon instance reconnected during worktree setup, the
server refused to re-send the attach because #5961's setup marker was
unfinished, and failed the thread. A different daemon instance already
interrupts provisioning when it opens its session, so a provisioning
environment resumed on socket open belongs to the connected daemon,
which joins the setup still running. Only that resume path re-sends;
every other path keeps the refusal.

The ordering test now has no known failures and checks that a
restarted daemon is never asked to re-run an unfinished setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 14, 2026
Unarchiving a thread after its environment's delete was requested but
before the removal started left the request pending forever: the sweep
skipped environments with live threads and never cleared it, and the
next archive removed the worktree at once, skipping both graces. The
sweep now withdraws a removal that has not started once a live thread
uses the environment again.

When the same daemon instance reconnected during worktree setup, the
server refused to re-send the attach because #5961's setup marker was
unfinished, and failed the thread. A different daemon instance already
interrupts provisioning when it opens its session, so a provisioning
environment resumed on socket open belongs to the connected daemon,
which joins the setup still running. Only that resume path re-sends;
every other path keeps the refusal.

The ordering test now has no known failures and checks that a
restarted daemon is never asked to re-run an unfinished setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 16, 2026
…und (#7553)

## Human comments

## What was wrong

Past environment bugs (#3650, #4325, #6828, #6892, #7194, #7242, #7311
and others) were each caught after release, one ordering at a time. No
test drove the real environment engine, the real Worktree and Project
checkout plugins, and real git together through orderings of user and
machine events. The ordering test added here found two bugs on main, and
this PR fixes both.

1. **A deleted environment stuck after an unarchive, then removed with
no grace.** `DELETE /environments/:id` only sets `teardownStatus:
"running"`; the removal happens on the next sweep. If a thread was
unarchived before that sweep, `sweepProviderEnvironmentInSlot` returned
early for an environment with live threads and never cleared the
request. The environment stayed in `teardown` indefinitely: restore
refused it ("not destroyed") and cleanup refused it ("still has live
threads"). The next archive skipped both the 30 s archive undo grace and
the 5-minute retire grace, and removed the worktree, uncommitted files
included, within a second.
2. **A thread failed when the same daemon reconnected during worktree
setup.** #5961 records a setup marker before sending
`environment.attach`. When the daemon reconnected as the same instance
(#3650's case), the server re-sent the attach, but
`runEnvironmentProvisionCommand` refused because the marker was
unfinished. The thread failed with "An earlier setup has an unknown
outcome…", even though the setup was still running and finished seconds
later. The #3650 test seeds a path the provider doesn't own, so it never
writes the marker. Proof runs show the failure starts at #5961.

## What changed

- `apps/server/src/services/environments/environment-engine.ts`
- **Bug 1:** when the sweep finds live threads on an environment whose
removal was requested but has not started (`teardownStatus: "running"`
while still `ready`; starting a removal sets `error`), it withdraws the
request (`teardownStatus` and `retireAt` back to null), and normal
retirement applies. The withdrawal is silent: nothing is added to the
thread's timeline. A removal that has already started is untouched
(#6892's path).
- **Bug 2:** a new `resumeEnvironmentProvisioningForReconnectedDaemon`,
called only from the daemon socket-open path, may re-send an attach
whose setup marker is unfinished. This is safe because the session-open
route, which is awaited before the daemon opens its socket, already
interrupts every provisioning environment when a *different* daemon
instance replaces the session. An environment still provisioning at
socket open therefore had its setup sent to this same daemon, and
`RuntimeManager.ensureEnvironment` joins the in-flight setup (or returns
the finished entry). `resumeEnvironmentProvisioningForHost` keeps main's
signature and behaviour. Every other path keeps #5961's refusal: the
periodic sweep, retries, and the server-move release.
- `apps/server/src/ws/daemon-protocol.ts`: socket open calls the new
resume.
- `packages/templates/src/templates/bb-guide-environments.md`: `bb
environment delete` notes that unarchiving a thread before removal
starts cancels the request.
- New tests:
-
`apps/server/test/services/environments/provider-orchestration.test.ts`:
archive, `DELETE /environments/:id`, unarchive; then the sweep keeps the
environment ready, and never calls `remove`.
-
`apps/server/test/environments/environment-lifecycle-orderings.test.ts`:
the ordering suite.
- **Real code, real data.** A migrated SQLite database
(`createMigratedConnection`), the real server environment engine and
routes, and the real Worktree and Project checkout plugins. Their host
halves run in host-entry harnesses against real git repositories (with a
bare `origin`) in a fresh `mkdtemp` directory, reached through
`plugin.host.call` on a fake daemon.
- **Fake daemon.** It runs turns, answers `environment.attach` by
inspecting the real workspace, can hold or fail any host operation, and
can disconnect, reconnect, or restart as a new instance.
- **Ten orderings** built from create, attach a second thread, archive,
unarchive, remove or retire, restore, failed setup, and daemon
disconnect, reconnect and restart, on one or two machines.
- **Rules checked after every ordering**, compared by rule and subject
only, never messages, counts or timings:
      - `removed-in-use`
      - `work-lost`
      - `orphaned-worktree` / `-branch` / `-claim` / `-row`
- `unsettled-environment` / `unsettled-thread` / `thread-failed` /
`create-raced`
- `setup-rerun`: a restarted daemon is never asked to re-run a setup
whose outcome is unknown. This guards #5961, and it fails if the restart
interrupt at session open is removed.

      There are no known failures.

No protocol, wire, schema, CLI, SDK or plugin API changes. No new
`@bb/db` query functions. No existing test is changed: the server-move
code and its tests, `internal-events-tool-calls.test.ts`, and #5961's
tests are identical to main.

**What a user would see differently, beyond the bugs going away
(decisions for Michael):**
- Deleting an environment and then unarchiving one of its threads before
the removal starts (up to one 10 s sweep) keeps the workspace. Within
one sweep, `bb environment show` returns to `Lifecycle: active`. Before,
the environment was stuck in `teardown` and the next archive removed it
within a second, skipping both graces.
- If the server restarts during worktree setup and the same daemon
process reconnects, setup now resumes instead of failing with "An
earlier setup has an unknown outcome". A restarted daemon still fails
the thread as before.

**Run time:** about 25 s of test time for the ordering file (10
orderings), in its own isolated worker.

## How you verified

**Live, before and after**, using `pnpm start:worktree` from this
checkout on fresh dev data dirs (never a copy of `~/.bb`), the real host
daemon, real Claude Code turns, and temp git repos with an `origin`:
- **Bug 1.** Spawn a worktree thread, `bb thread archive`, `bb
environment delete`, `bb thread unarchive`.
- *Before:* the environment stayed `teardown / running`.
`restore-environment` → 409 "Thread must be settled…"; `environment
cleanup` → 409 "still has live threads". When the thread was archived
again, the worktree and an uncommitted `notes.txt` were gone within 1 s.
- *After:* within one sweep the environment was back to `Lifecycle:
active`. The thread's timeline gets no new entry. On the next archive
the worktree and `notes.txt` survived 60 s, with `retireAt` 5 minutes
out.
- **Bug 2, daemon reconnect.** A 60 s `.bb-env-setup.sh`; the server was
paused with SIGSTOP for 40 s so the daemon's lease expired.
`host_daemon_sessions` shows the same `instance_id` reconnecting.
- *Before:* "Workspace setup interrupted" → "An earlier setup has an
unknown outcome…", while the setup then finished.
- *After:* the setup completed, the marker finished, the thread went
idle and Claude replied "ok". `.bb-env-setup.sh` ran once.
- **Bug 2, server restart.** The server process was killed with SIGKILL
during the same 60 s setup, and the launcher restarted it (new PID
within 3 s). The daemon kept its PID and `instance_id`, so its session
was replaced by the same instance. The thread went idle with Claude's
"ok", the setup marker finished, and the script's own run log has
exactly one line.
- **#5961's protection, live on the fixed build.** The daemon was killed
with SIGKILL during setup and respawned as a new instance. The thread
failed with "Host daemon restarted while preparing the workspace", and
setup was not re-run.
- **Server-move release path, shown by existing tests.** This PR doesn't
change `apps/server/src/services/server-move/environment.ts` (zero diff
against main). Its call, `resumeEnvironmentProvisioningForHost`, keeps
main's signature and behaviour (`setupRunsOnConnectedDaemon: false`).
The existing, unmodified `test/server-move/freeze-work.test.ts` asserts
that a move release calls it with `{ hostId }`. The existing, unmodified
#5961 test in `test/environments/environment-provisioning.test.ts`
("does not replace an unresolved RuntimeManager setup with a new
successful attempt") asserts that this path still refuses an unfinished
setup. Both pass.

**Proof runs of the test** (kept out of this PR). The test was run on
each listed fix's merge commit and its parent, and the violations were
diffed:

| Fix | Caught? | Ordering → violation on the parent |
|---|---|---|
| #3650 | yes | reconnect during setup → `thread-failed: A` |
| #4325 | yes | second thread's setup fails on a shared checkout →
`orphaned-claim: env(B)` |
| #6828 | yes | retire with a `refs/worktree/*` ref → `work-lost:
worktree-ref in A` |
| #6892 | yes | unarchive while removal runs → `orphaned-row: env(A)` |
| #7194 | yes | slow removal on machine a while b's grace passes →
`unsettled-environment: env(B)` |
| #7242 | yes | archive and retire → `orphaned-branch: env(B)` |
| #7311 | yes | three creates on one checkout path → `create-raced:
create C`, `thread-failed: A` |
| #3756 (extra) | yes | archive during setup → `unsettled-thread: A` |
| #4187 | no | The cancel only fired on a second placement pass while
the new thread still owned the merged checkout row. Public actions join
in one pass. |
| #5961 | no | Before #5961, attach-based setup wrote no persisted hook
record, so the retry loop it fixed never arises here. |
| #6016 | no | Directory moves are not among the orderings. |
| #6889 | no | Only an error message changed, and the test asserts
rules, not messages. |

The restart ordering and the `setup-rerun` rule were added after the
proof runs. They guard the reconnect fix and were checked by the
mutation above rather than against history.

**Local:** targeted suites pass: `test/environments`,
`test/services/environments`, thread provisioning recovery, internal
events tool calls, periodic sweeps, public environment routes,
environment providers, live commands and `test/server-move` (375 tests),
plus `@bb/thread-view` and `@bb/templates` tests. `turbo run typecheck
lint:type-aware` for `@bb/server` and `@bb/thread-view` pass, and `oxfmt
--check` is clean. CI runs the full suites.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 18, 2026
…eeds-recovery state (#7725)

## Human comments

## What was wrong

Each server-persisted retry schedule wrote its own backoff, and only
some of them had an end. Environment teardown got a cap and a "Needs
recovery" state in #5961. Machine teardown did not. `removeMachine`
increments `hosts.teardown_attempt` but never compares it to anything,
and every failure re-arms `remove_retry_at` at +60 s. A machine whose
provider removal keeps failing therefore retries every minute forever.
This had no issue; I reproduced it live on `origin/main` 1fa400d
(below). The item sweep runner (#7190) persisted a 1 min → 1 h backoff
in `sweep_item_failures` but had no needs-recovery state: after 5
failures it only logged. `hosts.suspend_retry_at` was named like a
schedule, but nothing ever retried on it. It only blocked manual
suspends for 10 s. Separately, `bb-app start` restarted a server that
would not start every 1 s with no limit (#3340).

## What changed

**One owner.** `nextPersistedRetryAt(delays, attempts, now)` in `@bb/db`
(`packages/db/src/persisted-retry.ts`) books every persisted retry. It
returns `null` once `attempts` runs past the delay list; that is the
needs-recovery state. Environments and queued messages stop there.
Machine teardown and item sweeps declare a slow hourly retry instead
(`nextSlowPersistedRetryAt`), so they stay in needs recovery but a later
success is still observed. The delay lists, the `Needs recovery:`
message and its parser live in
`apps/server/src/services/lib/persisted-retry.ts`. The four schedules
use it:

| Schedule | Attempt column | Delays | Needs recovery shows as |
Recovery |
|---|---|---|---|---|
| `environments.retire_at` (teardown) | `teardown_attempt` | 1, 2, 4, 8
min (unchanged) | `Needs recovery: …` teardown message | `bb environment
cleanup <id> --recover` (unchanged) |
| `hosts.remove_retry_at` (teardown) | `teardown_attempt` | 1, 2, 4, 8
min, then once an hour (was 60 s forever) | `Needs recovery: <error>.`
lifecycle message and `lifecycle.teardown.needsRecovery: true`; `bb
machine list` adds the retry-cleanup hint | "Retry cleanup" / `bb
machine retry-cleanup`, which now resets the 5-attempt budget |
| `sweep_item_failures.retry_at` | `attempts` | 1, 2, 4, 8, 16, 32, 60
min, then once an hour (was 1 min doubling to 1 h, with no
needs-recovery state) | `needsRecovery: true` in `bb server sweeps` and
an error log line | the first success clears it; `bb server sweeps
retry` (new) resets the budget now |
| `queued_thread_messages.next_attempt_at` | `failure_count` | 15 s, 1
min, 5 min (unchanged) | `failed_exhausted` | unchanged |

**Guard** (`apps/server/test/system/persisted-retry-schedules.test.ts`):
- A scan of the migrated database requires every `*retry_at` /
`*retire_at` / `*next_attempt_at` column to be registered together with
its attempt column.
- For each registered schedule, a scenario fails the operation
permanently and drives the real owner at each booked time.
- Each scenario must reach a needs-recovery state that the public API
shows, with each attempt run exactly once.
- Each entry then declares what happens after that:
- `stops`: the schedule becomes NULL and nothing runs again 30 days
later (environments, queue);
- `slow-retry` every hour (machine teardown, item sweeps): exactly one
attempt per interval, never earlier, and still in needs recovery.
- A schedule with no attempt column fails the scan, and one that never
reaches needs recovery fails the scenario.

**Copies deleted:**
- `environment-engine.ts`: `MAX_REMOVE_ATTEMPTS` / `REMOVE_RETRY_MS` and
its `2 ** (attempt - 1)` formula (#5961).
- `item-sweep.ts`: `sweepRetryDelayMs` / `REPEATED_FAILURE_ATTEMPTS`
(#7190).
- The queue transition's private `retryDelaysMs[failureCount - 1]`.
- The three `Date.now() + 60_000` re-arms in
`provider-orchestration.ts`.
- `hosts.suspend_retry_at` and its five writes plus the 10 s gate in
`lifecycle.ts` (migration `0158_drop_suspend_retry_at` drops the
column).
- `launcher.ts`: the fixed `MANAGED_PROCESS_RESTART_RETRY_DELAY_MS`
(three sites) and `superviseHostDaemonProcess`'s private backoff. Both
now use one restart budget, whose delay comes from the shared
`calculateExponentialBackoffDelay` in `@bb/domain`, the helper plugin
services, daemon self-update and the host watchers already use.

**Machine sweep.** Errors that escape `sweepProviderMachine` while the
machine is removing now count one teardown attempt through the owner. In
any other phase they go to the item sweep runner. Previously they bumped
`teardown_attempt` and marked teardown `failed` on active or suspended
machines too. A machine waiting on an environment that needs recovery
now re-checks hourly instead of every 60 s.

**Launcher (#3340).** Server and daemon restarts back off 1 s → 30 s,
and 60 s of uptime resets the count. This is the policy `bb-host-daemon`
already used. After 8 consecutive server failures, `bb-app start` stops
bb and exits 75, so systemd `RestartPreventExitStatus=75` can stop
restarting it. Host daemon restarts never give up. This deliberately
does not include #3339's diagnostic-file retention part of #3340.

**New surface.**
- Routes: `GET /server/sweep-failures` and `POST
/server/sweep-failures/retry`.
- SDK: `experimental_server.sweepFailures()` and
`experimental_server.retrySweepFailures()` (entry in
`docs/api_to_audit.md`).
- CLI: `bb server sweeps [--json]` and `bb server sweeps retry
[--json]`.
- Docs: the machines guide chapter covers teardown recovery, the
launcher exit code and sweeps, and the bb-cli command index lists the
new commands.
- `Host.lifecycle.teardown.needsRecovery` (boolean). `bb machine list`
uses it to print `<name> (<id>): Needs recovery: <error>. Inspect the
machine, then run bb machine retry-cleanup <id>.`
- `@get-bb/plugin-sdk` 0.6.157.
- No boot budget change. The new `Host` field adds 0.3 KB brotli to the
boot payload (418.4 → 418.7 KB on the same build), which fits under
main's 419.1 KB limit after #7730.
- No daemon wire change.

## Review decisions (resolved)

1. **Machines keep retrying after needs recovery.** An orphaned cloud VM
can keep billing, so after the 5-attempt budget a machine's teardown
retries once an hour. It keeps the `Needs recovery:` message, and "Retry
cleanup" grants a fresh 5-attempt budget. Environments, sweeps and
queued messages still stop at needs recovery.
2. **No CLI hint in the machine's message.** The app shows the "Retry
cleanup" button beside the message, so the stored message is just `Needs
recovery: <error>.` The CLI hint appears only in `bb machine list`
output, driven by the new `needsRecovery` field.
3. Accepted as proposed:
- Sweep items that need recovery appear only in `bb server sweeps`, the
SDK and an error log line, after 8 attempts (about 2 h). They now keep
retrying hourly; see the next section.
- Errors outside removal in the machine lifecycle sweep back off through
the sweep runner.
   - `hosts.suspend_retry_at` and its 10 s refusal are dropped.
- `bb-app start` exits 75 after 8 consecutive server failures, while
daemon restarts back off and never stop.
- Plugin-owned schedules are out of scope. `storage-retention`'s
`archive_cleanup.next_attempt_at` retries hourly forever, and
`workflows`' `notification_next_attempt_at` retries until delivered or
abandoned. The guard only scans `bb.db`.
- Two existing quirks are unchanged: the machine detail page shows the
message twice, and the button is offered during automatic retries.

## Second review (follow-ups)

**1. Regression: parked sweep items never came back. Reproduced and
fixed.** On the previous head, an item sweep's eighth failure set
`retry_at` NULL. Every later pass excluded that item, nothing ever
forgot the row, and a success on another path never cleared it, because
the runner clears a record only when the runner itself runs the item. So
a machine whose resume failed for about 2 h had its
`machine-provider-lifecycle` item parked for good, and a later removal
never got its retries. The same applied to every item sweep, for example
`queued-message-auto-send` (`thread:<id>`) and `turn-start-deadline`.
The new test `tears a machine down after its lifecycle sweep needed
recovery outside removal` failed on that head (`removals` was 0).

The class-level fix is in the runner. A permanently parked item can
never be seen to succeed, so a needs-recovery item now keeps retrying
hourly, the same way machines do. It still shows `needsRecovery: true`,
and the first success deletes the record. This keeps main's old 1 h
ceiling and adds the visible state. `retry_at` is NOT NULL again, so
migration 0158 only drops `hosts.suspend_retry_at`. **This revises
decision 1 for sweeps.** Sweeps no longer stop at needs recovery,
because stopping makes recovery unobservable for any item whose cause
clears up. I preferred this to clearing parked rows from removal or
retry-cleanup, which would fix machines only.

**2. Other long-lived retries, and why each stays where it is:**
- **`bb-app` launcher.** My restart budget's own `2 **` formula is gone.
It now uses `calculateExponentialBackoffDelay`, so there is one backoff
formula across the launcher, plugin services, daemon self-update and the
host watchers.
- **Daemon self-update**
(`apps/host-daemon/src/protocol-self-update.ts:303-341`). Left uncapped
on purpose. A daemon whose protocol the server rejects has no other way
back, so this belongs with the reconnects you asked me not to cap. It
already uses the shared backoff helper, capped at 5 min. The server
already shows the state (`lastRejectedProtocolVersion`, update status in
Settings → Updates and `bb updates`), and `bb machine retry-update` is
the manual retry. The daemon can't import the server-side owner.
- **Restart resume**
(`apps/server/src/services/threads/restart-resume.ts:34, 186`). Not a
schedule. It runs once per server restart, and its count is the turn's
retry chain (`MAX_RESTART_RESUME_ATTEMPT = 4`). When it gives up, the
interrupted turn stays failed in the timeline, so the user already sees
the end state and can send again. Its 5 s delay is boot settling, not
backoff.
- **Plugin service crash restart**
(`apps/server/src/services/plugins/plugin-runtime.ts:722`). Left
uncapped on purpose. It supervises in memory like the daemon restarts: 1
s → 60 s, with a reset after 5 min healthy. Many plugin services are
themselves connections (tunnels, schedulers), and the plugin already
reports a crash during activation as an error. It already uses the
shared backoff helper.
- **Guard reach.** The guard covers server-persisted schedules
(`bb.db`), where a missing cap had leaked: #5960, #7190 and machine
teardown. Daemon-side and in-memory loops aren't persisted. They are
processes or connections meant to retry for good, and the repo now
shares one backoff formula for them. A source-pattern guard (for example
on `2 **`) would check code shapes rather than behavior, so I didn't add
one. A new persisted retry column still fails the scan.

## Issues this root cause produced

| | Issue / PR | What happened | Would this have prevented it? |
|---|---|---|---|
| unfiled | machine teardown | retried every 60 s forever (live repro
below) | yes: fixed here, and the guard fails on main |
| closed | #5960, #4158 | environment teardown retried forever after an
interrupted hook (fixed by #5961) | yes: the guard registers
`environments.retire_at`, and #5961's copy is now the shared owner |
| closed | #7190 (PR) | the sweep runner shipped a persisted backoff
without a terminal state | yes: the guard fails on main for
`sweep_item_failures.retry_at` |
| open | #3340 | `bb-app` startup failures retried every 1 s forever |
yes: fixed here (restart part) |
| closed | #2993 → #2994 | the `bb-app` supervisor retried forever after
another server took its port | partly: #2994 detects the healthy server;
the new cap bounds any other cause in that same loop |
| closed | #1674 → #1675; #5682 | automations hot-looped dispatch
errors; storage-retention and Modal cleanup retried rapidly | no: these
are plugin-owned schedules (out of scope) |
| open | #2328 | automatic recovery storms a dead Codex thread | no: a
different mechanism (no persisted schedule) |

## How you verified

- **Live repro on main** (`origin/main` 1fa400d, isolated dev
instance, plugin machine provider whose `remove` always fails):
`teardown_attempt` went 1 → 9 over 8 min. Each time `remove_retry_at`
was re-armed about 60 s ahead, with no "Needs recovery" and no server
log line. Notes: `$BB_THREAD_STORAGE/live-repro-machine-teardown.md`.
- **The guard fails on main** (commit 1 only): the schema scan finds the
unregistered `hosts.suspend_retry_at`. `hosts.remove_retry_at` is still
re-armed after 40 rounds (`expected 3460000 to be null`).
`sweep_item_failures.retry_at` is still re-armed (`expected 130780000 to
be null`). Environments and queued messages pass.
- **The guard passes on this branch**, including the declared hourly
slow retry for machines and sweeps, and the regression test above, along
with new tests for the recovery verbs (`retry-cleanup` resets the
budget; `bb server sweeps` lists and retries a parked item), the sweep
escalation, and the launcher giving up with exit 75.
- `pnpm exec turbo run test --filter=@bb/server --
test/services/machines
test/services/environments/provider-orchestration.test.ts
test/environments/environment-lifecycle-orderings.test.ts
test/threads/queue-drain-failure.test.ts test/system
test/threads/environment-providers.test.ts
test/public/public-environments.test.ts`: 587 passed.
- `pnpm exec turbo run test --filter=@bb/db`: 724 passed.
`check:query-costs` passes.
- `bb-app` launcher suites: 92 passed. `@bb/cli`, `@bb/sdk`,
`@bb/server-contract`, `@bb/domain`, `@get-bb/plugin-sdk` and
`@bb/templates` tests pass.
- `turbo run lint typecheck` passes for the affected packages.
- **Live QA on this branch, before the review changes** (isolated `pnpm
start:worktree`, same failing provider). Since then the guard and the
retry-cleanup test cover the hourly retry and the hint-free message.
  - `remove` was called at +0, +63 s, +120 s, +240 s and +480 s.
- Attempt 5 logged `Machine teardown needs recovery` with
`removeRetryAt: null`.
- `bb machine show --json` then showed `"message": "Needs recovery:
repro: provider remove fails Inspect the machine, then run bb machine
retry-cleanup host_….", "teardown": {"status":"failed","attempt":5}`.
The missing full stop QA spotted is fixed in the last commit.
  - No further `remove` call came over the next 4.5 min.
- `bb machine retry-cleanup` ran one attempt at once (attempt 1, next
retry +60 s), and the cycle resumed.
- `bb server sweeps`, `bb server sweeps --json` and `bb server sweeps
retry` returned `No sweep items are failing.`, `{"failures": []}` and
`No sweep items need recovery.`

Side finding, not fixed here: `bb machine remove` prints "Machine …
removed" even when the removal failed
(`apps/cli/src/commands/machine.ts:486`).

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[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.

Environment teardown retries forever after an interrupted hook, with no recovery path

1 participant