Skip to content

Make queued retries safe: drop or hold them once overtaken - #6727

Merged
ymichael merged 1 commit into
mainfrom
bb/pr-make-queued-retries-safe-thr_fswp9tifa8
Nov 2, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/pr-make-queued-retries-safe-thr_fswp9tifa8

Conversation

@ymichael

@ymichael ymichael commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Nothing re-checks a queued retry after it is created. retryFailedTurn queues a retry row whose content is either an agent-only "Please continue." (when the provider accepted the failed input) or a hidden re-send of the failed turn's input (turn-retry.ts#L108-L135, queued at turn-retry.ts#L210-L228). Appending a new turn request does not look at the queue (thread-events.ts#L548-L568). The only code that deletes a queued retry is the message-edit path (thread-edit-message.ts#L686-L691 → queued-thread-messages.ts#L1000). So when the user moves on and sends a new message, the old retry still fires later, either continuing a turn the user abandoned or re-sending input on top of the newer message. Separately, SDK threads.wait treats error as unreachable for idle and throws as soon as it sees it (threads.ts#L1725), so bb thread wait exits 4 even when a retry is queued to recover the thread by itself.

This is the first step of the queue plan: the queue holds only unsent work, the event log records everything after send, and the retry row is the one "owed work" row. Here the retry row learns that it is owed only until something newer overtakes it.

What changed

  • Overtaken retries (supersedeQueuedRetriesInTransaction in packages/db/src/data/queued-thread-messages.ts, called from appendPreparedClientTurnRequestedEventWithNotificationInTransaction in apps/server/src/services/threads/thread-events.ts): appending a turn request supersedes the queued retries of other turns in the same transaction.
    • If the provider accepted any input in the retry's chain (turn/input/accepted for the original request or any earlier retry of it), the retry row is deleted.
    • Otherwise the row waits on a new waitingOn kind, superseded (packages/domain/src/queued-message.ts). Automatic dispatch never claims it, and it doesn't block rows queued behind it. The user sends it with Send now or deletes it.
    • The append's notification includes queue-changed when a retry was superseded. parent-system-messages.ts now uses the append's own notification fields to deliver that.
  • With Keep one pending retry per thread for accepted turn failures #6842's retry join (getFirstUnclaimedQueuedRetry): a scheduled retry of a later accepted failure joins the thread's waiting retry. That join now skips Not sent rows. Otherwise the later failure would attach to a row that never sends by itself and get no automatic retry. Keep one pending retry per thread for accepted turn failures #6842's two tests now expect the combined behaviour: the earlier retry is dropped or Not sent when the next message overtakes it, and one retry still waits per thread.
  • wait on a recovering thread (packages/sdk/src/areas/threads.ts): when the thread is in a status that can't reach the target, threads.wait lists the thread's queue. If a retry will still send by itself (not superseded, not failed_exhausted), it keeps waiting. On timeout, the error names the retry and when it is scheduled.
  • Rendering of the new kind: app queue row (apps/app/src/lib/queued-message-wait.ts), CLI Waiting on column, and the server's send-now description.
  • Guides: bb-guide-thread-lifecycle (overtaken retries), bb-guide-thread-messaging (superseded kind), bb-guide-thread-inspection (thread wait exit codes).

No daemon wire change, so no HOST_DAEMON_PROTOCOL_VERSION bump. Plugin SDK surface unchanged.

Visible behaviour changes

  • A retry that a newer message overtook before the provider accepted its input now shows in the queue as "Not sent · a newer message was sent after it" (alert icon). The CLI shows not sent: a newer message was sent after it. It stays there until the user sends or deletes it. A retry that would only have continued an accepted turn disappears instead.
  • bb thread wait / threads.wait no longer exits 4 (unreachable) on a thread in error while a retry is pending that will send by itself. It keeps waiting. If it times out (exit 2), the message says It failed and a retry is scheduled for <time>; wait again to follow it.

How you verified

New tests. Each one that fails against main's source was confirmed by checking out main's non-test files and running them:

  • apps/server/test/threads/turn-failed-retry.test.ts › "a queued retry":
    • "is kept as Not sent when a newer message overtakes input the provider never accepted" (also sends it with Send now and checks the re-sent input): fails on main, passes here.
    • "is dropped when a newer message overtakes a turn the provider accepted": fails on main, passes here.
    • "does not hold back messages once it is Not sent": fails on main, passes here.
    • "gives an accepted failure its own retry when the thread's only retry is Not sent": fails without the join fix (the failure joins the Not sent row), passes here.
  • apps/cli/src/__tests__/command-output/thread-wait.test.ts:
    • "keeps waiting on a failed thread whose retry will send": fails on main, passes here.
    • "names the pending retry when it times out": fails on main, passes here.
    • "fails fast when the failed thread's retry is not sent" (superseded + failed_exhausted rows): passes on both. It guards the new check so these rows still exit 4.

Commands:

  • pnpm exec turbo run typecheck lint --filter='...[origin/main]': 153/153 tasks pass.
  • pnpm exec turbo run test for @bb/server (3824 passed), @bb/db (652), @bb/domain, @bb/sdk, @bb/cli (888), @bb/templates (47), after rebasing onto c2365296a4: all pass.
  • apps/app queued-message tests (6 files, 94 tests): pass.
  • node .github/workflows/check-plugin-sdk-version.mjs: "Plugin SDK surface unchanged."

🤖 Generated with Claude Code

AGENT GENERATED

ymichael added a commit that referenced this pull request Nov 2, 2026
## Human comments

## What was wrong

After a server restart, the GitHub PR Status plugin restores each
environment's PR from its database and serves it right away. It also
starts a background re-check right away, often before the host daemon
has reconnected. That re-check returned `unavailable` ("machine isn't
available"), and `store.load` replaced the environment's known PR link
with that result. The sidebar row badge disappeared and stayed gone
until something re-read that row, such as opening the thread or
refocusing the page. Observed on prod: the server restarted at 13:04:14
and the daemon reconnected at 13:04:20. Afterwards the sidebar showed
only #6849 (the thread that was opened). Six other inbox threads with
open PRs (#6760, #6755, #6736, #6728, #6727, #6734) showed no badge,
although their links and snapshots were still in the plugin database.

## What changed

- `plugins/github-pr-status/store.ts`: when a re-check of a known PR URL
comes back `unavailable`, the environment's link is no longer replaced,
so the last snapshot keeps being served. The snapshot's `fetchedAt` is
still bumped, so the regular poll retries it. Discovery reads (no known
URL) behave as before.
- Behaviour change: `bb pull-request show` for an environment whose
machine is offline now prints the last PR bb saw, or `unavailable` when
it has none. Actions (`ready`/`draft`/`merge`) still refuse with the
machine message. The skill doc and README are updated.

## How you verified

- New store test, "keeps serving a restored PR when its machine is
unreachable after a restart": it restores a persisted PR, makes the
first re-check return `unavailable`, and checks that the PR is still
served, nothing is published, and the next successful check publishes
the update. It fails without the fix (`expected { outcome: 'unavailable'
} to deeply equal { outcome: 'available' }`) and passes with it.
- `pnpm exec turbo run test typecheck lint
--filter=bb-plugin-bb--github-pr-status`: 183/183 tests pass, typecheck
and lint clean.

> AGENT GENERATED

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

Co-authored-by: Claude Opus 5.5 <[email protected]>
Nothing re-checked a queued retry after it was written. A newer message did
not affect it, so a scheduled "Please continue." or a hidden re-send of the
old input landed after the user had moved on. `bb thread wait` also failed at
once on a failed thread even when its retry was about to send.

- Appending a new turn request supersedes the retries of other turns, in the
  same transaction: a retry whose chain the provider accepted is deleted; one
  whose input was never accepted waits on the new `superseded` kind ("Not
  sent") and is only sent by the user.
- A later accepted failure no longer joins a Not sent retry (the
  `getFirstUnclaimedQueuedRetry` join from #6842 skips them), so it still gets
  a retry that sends by itself.
- SDK `threads.wait` (and `bb thread wait`) keeps waiting on a thread in error
  that has a retry which will send by itself, and names it on timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/pr-make-queued-retries-safe-thr_fswp9tifa8 branch from e0fcef1 to 2b1ac5f Compare November 2, 2026 23:00
@ymichael
ymichael merged commit 337b66d into main Nov 2, 2026
52 checks passed
@ymichael
ymichael deleted the bb/pr-make-queued-retries-safe-thr_fswp9tifa8 branch November 2, 2026 23:32
ymichael added a commit that referenced this pull request Nov 4, 2026
When a machine's daemon comes back as a new instance (bb quit, crashed,
updated, or the machine restarted), the server still interrupts the turns
it was running with host-daemon-restarted. With the new
continueThreadsAfterRestarts experiment (default off), it then queues a
retry of each cut turn through retryFailedTurn with reason "bb restarted",
scheduled 5 seconds out. The retry sends "Please continue." when the
provider accepted the cut turn's input and the original input otherwise.

Which threads resume: only active, unarchived threads cut by a new daemon
instance. Manual stops (stopping threads finalize as stopped), threads with
a pending question or approval, and archived or deleted threads stay as
before. A turn is not resumed again once its retry chain reaches attempt 4,
so a turn that keeps crashing bb resumes at most three times in a row.

A resuming thread's interruption reads "Thread interrupted because bb
restarted" with "bb will continue the thread in a few seconds.", and its
parent is not told about the interruption; it hears when the child
finishes. If queueing the resume fails, the parent gets the usual
interrupted notice.

Retries go first: a new retry row takes the front of the thread's queue,
and automatic claims skip rows behind a live retry (not Not sent, not
exhausted) until it sends or is dropped. A message sent before the resume
goes out still supersedes it, per #6727.

No daemon wire change and no plugin SDK change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 4, 2026
Review follow-up. Retries going first is needed for resume: a message
steered (the default send) while the daemon is down waits as host-offline,
and the reconnect's host-connected wake sends it before the resume, which
then drops the resume. Queued (thread-busy) rows already wait on an error
thread, so they were never the problem.

The earlier version refused automatic claims behind a live retry. That
stranded exactly those host-offline rows: the reconnect wake is their only
wake, so they stayed host-offline after the resume finished. Now the hold
is a core wait in the dispatch checkpoint: a drained, non-retry row on a
thread with a live retry is re-queued as thread-busy and sends when the
retry's turn ends. Inline sends and Send now are not held, so they still
overtake a pending retry.

Both halves are behind continueThreadsAfterRestarts: retry rows are moved
to the front of the queue only with it on, and the hold only applies with
it on. With it off, retry order and holding are exactly as on main, and
the two #6842 tests are back to main's version. The live-retry check is
SQL built on #6727's notSupersededQueuedThreadMessage instead of a JSON
parse.

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

## Human comments

## What was wrong

When bb restarts (an update, quit, crash, or machine restart) while
threads are running, the daemon comes back as a new instance and the
server interrupts every turn it was running with `host-daemon-restarted`
([session-owner-side-effects.ts#L113-L127](https://github.com/get-bb/bb/blob/010a3c0b898a10adeacf758b58baf794ddff51ad/apps/server/src/internal/session-owner-side-effects.ts#L113-L127)).
That reason maps to `run.failed`
([thread-lifecycle.ts#L400-L403](https://github.com/get-bb/bb/blob/010a3c0b898a10adeacf758b58baf794ddff51ad/apps/server/src/services/threads/thread-lifecycle.ts#L400-L403)),
so the thread ends in `error` with "Please retry the thread to
continue."
([thread-lifecycle.ts#L454-L456](https://github.com/get-bb/bb/blob/010a3c0b898a10adeacf758b58baf794ddff51ad/apps/server/src/services/threads/thread-lifecycle.ts#L454-L456)).
Nothing ever retries it, so every running thread needs a manual Retry
after each update. This is the first half of #6127 (resume after
restart). Update-when-idle is the other half.

## What changed

Everything is behind a new experiment, `resumeThreadsAfterRestart`
(Settings → Experiments → "Resume interrupted threads after a restart")
(default off, also off for early adopters).

- **Resume = the existing retry row**
(`apps/server/src/services/threads/restart-resume.ts`, wired into
`handleHostSessionOpened`). Nothing is recorded at shutdown: the
`host-daemon-restarted` interruption on reconnect is the signal. After
it, the server queues one retry per cut turn through `retryFailedTurn`
with reason "bb restarted", scheduled 5 s out. It is the same row as the
Retry button and provider-retry. It sends the agent-only "Please
continue." if the provider accepted the cut turn's input, otherwise the
original input.
- **Which threads resume:** only active, unarchived threads cut because
the daemon came back as a new instance. Not resumed:
  - manual stops (stopping threads finish as stopped);
- threads with a pending question or approval (they keep today's
message);
  - archived and deleted threads;
  - the same-instance "connection lost" and imported-snapshot cases.
- **Loop protection:** a turn is not resumed once its retry chain would
pass attempt 4 (`retry_attempt`), so a turn that keeps crashing bb
resumes at most three times in a row and then stays in error.
- **Wording:** a resuming thread's interruption reads "Thread
interrupted because bb restarted", with the detail "bb will resume the
thread shortly."
- **Child threads:** a resuming child doesn't send its parent an
"interrupted" notice; the parent hears when the child finishes. If
queueing the resume fails, the parent gets the usual interrupted notice.
- **Retries go first** (experiment only):
- a new retry row is placed at the front of the thread's queue
(`moveQueuedThreadMessageToFrontInTransaction`, `queue-waits.ts`);
- while a live retry is queued (not Not sent, not exhausted;
`hasLiveQueuedRetry`, SQL on #6727's
`notSupersededQueuedThreadMessage`), the dispatch checkpoint re-queues
any other row the queue drains as `thread-busy` (`dispatch-attempt.ts`),
so it goes out after the retry's turn ends;
- messages sent directly and Send now are not held, so a message you
send before the resume goes out still overtakes it (#6727's rule:
dropped, or Not sent).

This is needed for messages steered while the daemon is down: they wait
as `host-offline`, and without the hold the reconnect sends them before
the resume, which then drops the resume.
- Docs: `docs/configuration.md`, `bb guide thread-lifecycle`, `bb guide
customization`, Settings → Experiments.

No daemon wire change, so no `HOST_DAEMON_PROTOCOL_VERSION` bump. Plugin
SDK surface unchanged (`check-plugin-sdk-version.mjs`).

### What users see

- **Between the cut and the resume (about 12–14 s live):** the thread is
in `error`, with the red error icon in the sidebar and a red "Thread
interrupted because bb restarted · error" timeline row. The queue shows
"Retry failed turn from 1:00 PM · bb restarted · retrying at 1:00 PM ·
attempt 2". The retry is scheduled 5 s out, and the periodic queue sweep
that sends every scheduled retry picks it up on its next pass. After
that the agent carries on in the same thread; "Please continue." is
agent-only and not shown.
- **`bb thread wait`** follows the pending resume like any retry (live:
started while the resume was pending, exited 0 at idle).
- **Effect on Retry-button and provider-retry rows with the experiment
on:** they also go to the front of the queue. While one is pending, the
thread's other queued rows wait behind it: a `--send-at` message coming
due, a row a plugin releases, a `host-offline` row on reconnect, a
child-finished notice. For a provider-retry row scheduled hours out for
a subscription window, those rows now wait those hours instead of going
out and overtaking it. With the experiment off, ordering and holding are
unchanged from main.

## How you verified

The new tests are in `apps/server/test/threads/restart-resume.test.ts`.
They run on the real server harness and open the daemon session through
`/internal/session/open` as a new instance. Run against main's source
(with only the experiment key added), every one fails except the
experiment-off ordering check, which is there to show nothing changes:

| Test | On main |
|---|---|
| A restart cuts a turn and the thread resumes ("Please continue.",
attempt 2) | fails: no resume row |
| A message queued (`queue-if-active`) during the restart sends after
the resume, in order | fails: no retry in the queue |
| A message steered (`auto`) during the restart sends after the resume,
in order | fails: the follow-up is sent first |
| A message sent before the resume goes out overtakes it | fails: no
pending resume |
| Manual stop, pending question and archived threads don't resume, while
a running thread on the same restart does | fails: running thread not
resumed |
| Loop protection: three resumes, then the thread stays in error |
fails: no resumes |
| Experiment off: thread stays in error; turned on, the next cut resumes
| fails: no resume |
| A child resuming tells its parent nothing, then tells it when it
finishes | fails: child left in error |
| Experiment on: a Retry-button retry goes ahead of earlier queued
messages and holds them | fails: wrong order |
| Experiment off: retry order and holding unchanged | passes (no-change
check) |

I also checked that the steered test fails with an earlier version that
held rows at claim time: the reconnect wake is the only one for
`host-offline` rows, so they stayed stuck. That is why the hold lives in
the dispatch checkpoint.

Commands:
- `pnpm exec turbo run typecheck lint --filter='...[origin/main]'` (155
tasks) passes.
- `turbo run test` for `@bb/db` (651), `@bb/domain`, `@bb/templates`
(47) passes.
- `@bb/server` passes in full on the first commit. On the final code,
timing-sensitive suites (`install-machine-script` and similar) timed out
on a host at load average ~100. They pass on rerun, except
`install-machine-script`, which fails the same way on the base commit's
source.

Live, with `pnpm start:worktree` and real Claude Code threads running a
3-minute foreground shell loop, restarted with `kill` on literal PIDs:
- **QA 0 (control):** finished before any restart.
- **QA 2, daemon `kill -9`:** queued "bb restarted" attempt 2, resumed
("The loop was cut off before it printed LOOP-DONE, so I'm running it
again."), finished. `bb thread wait` followed it to idle.
- **QA 3, full server + daemon restart (SIGTERM to the launcher,
relaunch):** the thread was still `active` in the DB after shutdown
(nothing recorded), then it was cut on reconnect, resumed and finished.
- **QA 4, message queued while the daemon was down:** sent after the
resumed turn finished ("QUEUED-FOLLOW-UP").
- **QA 5, message sent while the resume was pending:** the resume was
dropped and only the message ran ("OVERTAKEN").
- **QA 6:** screenshots of the pending queue row and timeline wording,
then resumed.
- **QA 7, message steered while the daemon was down:** after reconnect
the queue showed the retry first and the message as `thread-busy`. It
ran in order: resume, FINISHED, then "STEERED-FOLLOW-UP".

Refs #6127

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

> AGENT GENERATED

---------

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