Skip to content

Run every periodic sweep job through one item sweep runner - #7190

Merged
ymichael merged 6 commits into
mainfrom
bb/item-sweeps
Nov 6, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/item-sweeps

Conversation

@ymichael

@ymichael ymichael commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Background sweeps could get stuck on one bad item or one hung call. Each periodic job had its own error boundary, but the runner only saw whole jobs. Inside a job, each loop decided for itself what one failing item meant, and most got it wrong:

  • One failure ended the pass, and the same item came up first again 10 s later, so it blocked every item behind it:
    • Deleted threads and archived teardown. Neither loop in the lifecycle sweep had a per-thread try. One archived thread whose saved startup context fails its strict parse stopped every later teardown and every deleted-thread finalization.
    • Event pruning caught the error and rethrew it. The failed policy's cursor rolled back and was picked first again, so one thread could freeze all four pruning policies.
    • Turn-start deadline: one throwing thread stopped the threads after it.
    • Completed output migration: one failing target blocked the targets after it.
    • Startup recovery: one failing step skipped the steps after it.
  • One hung call stopped a job for good. A job still running is skipped on every later pass, and nothing bounded these waits:
    • plugin schedules waited on each schedule with no timeout;
    • environment provisioning can wait on daemon commands with a 24 h timeout;
    • the environment lifecycle waited for every teardown at once.
  • Plugin schedule rows for unloaded plugins stayed due and could fill the 100-row batch.

What changed

One runner for every periodic job. PeriodicSweepJob is now just a name, a cadence, background, and sweep(deps, now), which returns an item sweep. There is no other kind of job.

  • The runner (apps/server/src/services/system/item-sweep.ts) takes list({ excludedKeys }), a stable key, process, and concurrency. It runs each item behind its own boundary:
    • A failure is written to the new sweep_item_failures table (sweep, item key, attempts, first failure, retry time, last error), and the remaining items still run.
    • The item is left out until its retry time: 1 minute, doubling to 1 hour, counted from the pass, or from when it failed if it ran past the 60 s detach. list receives the excluded keys so LIMIT queries can leave them out in SQL.
    • Each failure logs a warning; from the fifth attempt on, an error.
    • A success clears the record. A record whose item hasn't been listed for an hour past its retry time is dropped. Startup drops records of sweeps that no longer exist.
    • It stops waiting for any item after 60 s, skips it while still running (also in an overlapping pass of the same sweep, such as the event-driven and periodic queue wakes), and records its outcome when it settles.
    • It runs up to concurrency items at once and yields every 8 ms.
    • A background job doesn't hold up the rest of the pass and is skipped on later passes until it finishes.
  • Three constructors for three shapes:
    • defineItemSweep: a list read once per pass;
    • defineScanSweep: a cursor scan that lists again after each batch until nothing new comes back. It never processes a key twice in a pass and leaves out keys that failed earlier in the pass;
    • defineSingleItemSweep: one bulk statement or maintenance pass.
  • Every job's items:
    • environment provisioning, thread provisioning, archived-thread teardown and deleted-thread finalization (the last two split out of thread-provisioning-orphan-cleanup);
    • turn-start deadline; project deletion;
    • plugin schedules, which now list only loaded plugins' rows;
    • environment teardowns, with unbounded concurrency;
    • machines, as two sweeps: a removal request per machine, and the machine sweep itself, which runs in the background as before;
    • the four queued-message wakes, on both the periodic and the event-driven path. Each message's own retry and exhausted state stays inside process;
    • thread-storage orphan cleanup, one item per host, in the background as before;
    • attachment backfill and orphan prune, one project per pass. The runner's records replace the backfill's own error column and 60 s skip. The column stays in the schema, unused, because migration tests rewind and rerun every later migration and a plain DROP COLUMN can't run twice;
    • completed output migration, one item per target, each with an equal share of the 64-advance budget;
    • event pruning, a scan sweep whose items are each policy's next thread (<policy>:<thread>). pickThreadPruningThread commits the choice in its own transaction before any pruning, so a failure lands on that thread through the runner, and the next pick moves past it until its retry time;
    • single-item sweeps for the bulk prunes, the two claim and owner releases, and database and plugin-database maintenance.
  • Deleted on the way: the hand-written failure handling in the pruning sweep, ThreadPruningAdvanceError, skipThreadPruningThread, advanceThreadPruningPolicy, the backfill's own retry skip, and the storage orphans' runningHostIds.
  • Startup recovery runs each step behind its own boundary.
  • Migration 0153_sweep_item_failures, idempotent. No HOST_DAEMON_PROTOCOL_VERSION change.
  • Docs: docs/system-overview.md (Background sweeps) and docs/events-table-pruning.md.
  • Order: this lands before Delete threads from bb.db in paced batches through the item sweep runner #7184. That PR rebases next and records purge failures through this runner instead of its own columns. Move archived threads to cold storage from Storage & retention, with a thread.delete_finalize hook, export and import #7107 follows.

Known limits, unchanged from main:

  • A row that always fails inside one output-migration target keeps that target backing off, with error logs, rather than being skipped.
  • If stopping a run fails after the turn-start deadline appended its error event, the retry appends another. Backoff now spaces those out.
  • A one-off failure in a bulk job (such as the machine-auth prune) now waits a minute before the retry, instead of 10 s.

How you verified

  • apps/server/test/system/item-sweep.test.ts:
    • a failing item doesn't stop the items after it;
    • it is recorded, excluded until exactly 60 s later, retried, and cleared on success;
    • delays double (60 s, 120 s, 240 s, 480 s, 960 s), with one error log on the fifth failure;
    • an unlisted record is kept until an hour past its retry time, then dropped;
    • with two hung items and one quick one, the pass returns at 60 s rather than earlier or later; the hung items are skipped while in flight, and a rejection 10 minutes later is recorded with its retry time counted from that rejection;
    • when two passes of one sweep overlap, an item the other pass is running isn't started again.
  • apps/server/test/system/periodic-sweep-jobs.test.ts:
    • every job name is unique and matches the name of the item sweep it runs, so failure records line up;
    • a deleted thread whose finalization throws no longer stops another deleted thread from being removed. On main, the whole sweep rejects.
  • apps/server/test/system/thread-pruning-sweep.test.ts:
    • with a trigger making deletes fail for one thread, the other thread is pruned in the same pass. The broken thread records turn-diffs:<id> with 1 attempt, isn't retried before its retry time, is pruned afterwards, and the record clears;
    • the existing pruning tests (busy threads, mid-visit busy, rotation and budget, overrun, notifications after a failed batch) pass on the scan sweep.
  • Local runs:
    • @bb/server and @bb/db typecheck pass.
    • @bb/server tests in test/system, test/services, test/threads, test/public, test/server-move, test/internal, test/hosts, test/projects, test/environments and test/machines pass: 3,205 of 3,206. The exception, public-host-management "revoke the removed host's cloud machine", fails locally because the connect plugin's frontend build can't resolve @bb/domain. It passes in CI, and this PR doesn't touch plugins.
    • The full @bb/db suite passes (660), including the migration-rewind tests.
  • Overhead, measured on a scrubbed copy of a real bb.db: one pass costs 29 µs with no items, 32 µs with 10 and 75 µs with 100. That's about 0.3 ms per 10 s across the 9 items jobs.

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 4 commits November 6, 2026 09:55
Periodic sweep jobs are now either items jobs or tasks. Items jobs list
their items with a stable key and process them through defineItemSweep,
which catches each item's failure, records it in sweep_item_failures,
leaves the item out until its retry time (1 minute doubling to 1 hour),
logs an error from the fifth attempt, clears the record on success, and
can stop waiting for an item that runs too long.

Moved onto it: environment provisioning, thread provisioning, archived
thread teardown, deleted thread finalization, turn-start deadline,
project deletion and plugin schedules. Event pruning now skips a thread
it cannot prune and retries it later instead of rethrowing, and output
migration backs off a failing target instead of blocking the ones after
it. Startup recovery runs each step behind its own error boundary.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…to it

The runner now stops waiting for any item after 60 seconds (it is skipped
while still running and its outcome is recorded when it settles), runs up
to a declared number of items at once, and yields every 8 ms. Environment
teardown sweeps run on it with unbounded concurrency, so one hung teardown
no longer holds the job; releasing finished preparation owners is its own
task job. Unlisted failure records are kept until an hour past their retry
time so LIMIT-bounded lists keep their attempt counts, and startup drops
records of sweeps that no longer exist.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…m sweeps

The four periodic queued-message wakes (idle recovery, due scheduled,
failed retry, orphaned plugin waits) now run through item sweeps on both
the periodic and the event-driven path, with releasing stale claims as its
own bulk task. Thread storage orphan cleanup runs per host on the runner as
a background job, so it still never holds up the rest of the pass.
Attachment backfill uses the runner's failure records and exclusion
instead of its own error column and 60 second skip; the column stays in
the schema until it can be dropped with a rerunnable migration.

Items jobs now declare whether they run in the background.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
There is no task kind any more: every periodic job is an item sweep.
Single statements and maintenance passes use defineSingleItemSweep.
Event pruning is a scan sweep (defineScanSweep) whose items are each
policy's next thread: picking the thread commits in its own transaction,
so a failure lands on that thread through the runner and the next pick
moves past it, which replaces ThreadPruningAdvanceError, the skip helper
and the hand-written failure bookkeeping. Output migration's items are
its targets, each with an equal share of the budget. The machine
lifecycle splits into a removal-request sweep and a background lifecycle
sweep, and attachment orphan prune lists one project per pass.

The runner relists scan sweeps until nothing new comes back, never
processes a key twice in a pass, and leaves out keys that failed earlier
in the pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael ymichael changed the title Run sweep items through one runner that isolates and backs off failures Run every periodic sweep job through one item sweep runner Nov 6, 2026
ymichael and others added 2 commits November 6, 2026 12:45
…ass is running

A detached item that failed later recorded its retry time from the start
of the pass that launched it, so a ten-minute hang came back already due.
The failure is now timed from when the item settles. Overlapping passes
of the same sweep could also start an item the other pass was still
running, because exclusions were read only when the pass listed; each
item is now checked against the in-flight set right before it starts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…past the detach

Adding real elapsed time to every failure made retry times depend on how
long a quick failing item took, which broke exact backoff timings on slower
Windows runners. Items that fail within the pass keep the pass's time; only
items that ran past the 60-second detach count from when they failed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit b99706a into main Nov 6, 2026
52 checks passed
@ymichael
ymichael deleted the bb/item-sweeps branch November 6, 2026 22:24
ymichael added a commit that referenced this pull request Nov 6, 2026
…ner (#7184)

## Human comments

## What was wrong

Deleting a thread ends with one `DELETE FROM threads` that cascades to
every event, search segment and prompt history row, in one transaction
on the server's main thread. On a scrubbed copy of a heavy install (3.9
GB `bb.db`), deleting its 40 largest deletable threads (406k events) one
by one blocked the server for 250 ms per thread at the median and 1,554
ms at worst. Storage retention's delete-after policy and project
deletion take the same path, so deleting many old threads stalls bb
again and again. It is also the delete step the cold tier (#7107) needs.

## What changed

Deleting a thread now finishes through a paced background sweep on the
shared item sweep runner from #7190. Nothing changes for users: a thread
disappears from lists, search and the sidebar the moment it is marked
deleted, as before.

- **Queue.** Where `finalizeStoppedThreadInTransaction` used to call
`deleteThread`, it now inserts the thread into a new `thread_purges`
table (`thread_id`, `requested_at`). The row cascades away with the
thread, so the queue needs no cleanup. The deleted-thread finalization
sweep skips threads already queued.
- **Sweep.** `thread-purge` is a `background` job in
`PERIODIC_SWEEP_JOBS`, built with `defineScanSweep`. It lists the oldest
queued thread that no longer owns lifecycle dependents, so owners still
go after their dependents. It then deletes that thread in steps, each
one immediate transaction:
  1. the next events, 64 rows or 512 KB, always at least one row;
2. then search segments, prompt history and attachment links, 128 rows
at a time;
  3. then the thread row, through the existing `deleteThread`.

Steps run in 10 ms slices. After each slice the sweep rests 9× as long
while a client is connected or a thread is running, and 1× otherwise. A
run stops after 30 seconds, or when a server move freezes the DB, and
the next pass continues. That keeps each item well under the runner's
60-second detach. A new delete starts at the next pass, at most 10 s
later.
- **Failures** go through the runner. A thread whose step throws has its
transaction rolled back. It gets a `sweep_item_failures` row and is left
out until its retry time (1 minute, doubling to at most 1 hour), while
other threads keep going. It stays queued and hidden and is never
dropped.
- **Migration `0154_thread_purges`** adds the table and its
`requested_at` index, idempotently. No `HOST_DAEMON_PROTOCOL_VERSION`
change; no app, CLI or contract change.
- `docs/system-overview.md` describes the queue.

## How you verified

- `packages/db/test/data/thread-purges.test.ts`:
- events are deleted in row- and byte-capped batches, an oversized event
alone, then prompt history in `maxRows` batches;
  - the thread row is never touched, and other threads' events stay;
- the queue takes the oldest request first, skips excluded threads, and
holds an owner until the threads it owns are gone.
- `apps/server/test/threads/thread-purge.test.ts`:
- after `DELETE /threads/:id`, the thread keeps its events and returns
404 until the sweep deletes them;
- with a trigger making one thread's deletes fail, the next thread is
still deleted. The failing thread records attempt 1 with a retry 60 s
later, is skipped at +59.999 s, and is deleted at +60 s with its failure
record cleared.
- Existing tests in 8 files (13 call sites) that expected the row gone
right after a sweep or route now drain the queue with the
`runThreadPurges` helper, which runs the production sweep.
- Locally:
  - `@bb/db` passes, 662 tests;
- `@bb/server` passes 3,935 of 3,936, the one failure being
`public-host-management`, which fails only locally on the connect plugin
build;
  - typecheck and lint pass.
- **Real server** (`pnpm start:worktree`, fresh data dir, driven with
the source `bb` CLI):
- deleting a thread hides it at once, and its rows are gone within one
pass;
  - deleting an owner removes its lifecycle dependent and sidebar child;
- a 30k-event, 57 MB thread was purged in about 3 s, during which `GET
/api/v1/threads` stayed at p50 3.1 ms, max 16.4 ms;
- a failing purge backs off while the next thread is deleted, and
retries 60 s later;
  - a restart mid-purge resumes;
  - project deletion completes;
  - the only server warning was the intended failure.
- **Bench:** the 40 largest deletable threads on a fresh scrubbed
heavy.db copy each run (405,939 events):

  | Path | Event loop | Wall time |
  |---|---|---|
| `main`: one cascade per thread | blocks of 250 ms median, 1,554 ms max
| 13.2 s, all blocking |
  | Paced, idle (rest 1×) | p99 25.9 ms, max 46 ms | 41.6 s |
  | Paced, busy (rest 9×) | p99 5.9 ms, max 116 ms | 232 s |

Timed one at a time, steps take 1.3 ms at p50, 26.8 ms at p99 and 72 ms
at most, and 24 s in all. The busy maximum is one outlier that includes
a WAL auto-checkpoint inside a commit, which any write on the main
thread can hit today. The bench script and DB copies stayed in thread
storage and were deleted.

> 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 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.

1 participant