Skip to content

One retry handoff for provider retry, Automations and Workflows - #7717

Merged
ymichael merged 3 commits into
mainfrom
bb/7708-failed-scheduled-automation-turn-is-retried-thr_nkv2eyk7cp
Nov 18, 2026
Merged

ymichael merged 3 commits into
mainfrom
bb/7708-failed-scheduled-automation-turn-is-retried-thr_nkv2eyk7cp

Conversation

@ymichael

@ymichael ymichael commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Three plugins could each re-run one failed turn: provider retry, Automations, and Workflows. Their handoff was the provider-retry.v1.consent RPC. The sending plugin had to answer "decline" within provider retry's 5 s timeout, and any miss counted as consent.

  • Automations misses when the run has no thread ID yet because the spawn response is still pending (the report forces this), or when its answer is slow, as on a Mac waking from DarkWake. 0.48.x has no handler at all (Stop provider failures from retiring recurring automations #6677 first shipped in 0.49.0, and the reporter is on 0.48). When it misses, provider retry resumes the thread while the automation's 30 s quick retry spawns a fresh thread.
  • Workflows has the same timeout miss. It then replaces the worker 1 s later in the same environment.

What changed

One rule now covers every retrier: provider retry owns a failed turn, and a plugin that re-runs failed work stands down while a retry is in hand. The sync point is provider retry's recorded decision, not timing.

  • provider-retry: no longer asks senders for consent. It records its decision for each turn.failed, after queueing any retry, and decision.get is now discoverable. Removed: the consent ask, declined-by-sender, the consent field in diagnostics and explain, and retryConsent* from the contract.
  • retry-handoff.ts, an identical copy in plugins/automations/src and plugins/workflows/src (plugins stay self-contained). readRetryHandoff reads the steps below in this order:
    1. The thread. Gone or archived → re-run.
    2. Provider retry's decision. Read before the queue, because provider retry queues the row and then records the decision. Reading the queue first loses that race: the live check below hit it, and the "lands mid-check" rows guard it.
    3. The queue. Any retry row → stand down. This covers provider retry and core's restart resume (bb restarted), and the reason names whichever it was.
    4. The latest turn request. The thread isn't in error and the request carries retryOfRequestId → stand down (overload retries fire 5–10 s out).
    5. Undecided failure → wait. Then re-run once the decision arrives, after 60 s, or right away when provider retry is not installed.
  • Automations (sweep.ts): before a quick retry of a failed scheduled run, a wait leaves the slot due (the next sweep is 10 s later). A stand-down records a skipped run, failed run <id> is not re-run: a retry (<reason>) is queued in thread <id>, and next_run_at moves to the next scheduled time. Automations' consent handler is deleted. If the handoff can't be read (for example decision.get times out), the sweep treats it as undecided: it waits while the failure is under 60 s old, then re-runs, as Workflows does. Before, the error escaped the sweep and the automation stayed due without ever running.
  • Workflows (service.ts, data.ts): when a worker's thread.failed fails a call, the call polls the handoff every second.
    • On stand-down, reopenFailedCallOnWorker sets the call back to running on the same worker. It then waits for that worker's result instead of spawning a replacement. A later failure of that worker goes through the handoff again.
    • While a handoff is pending, worker cleanup skips the worker. Without that, the call sitting briefly in failed makes cleanup archive the worker, which failed the run (found live).
    • Workflows' consent handler is deleted.
  • Docs: provider-retry SKILL.md, automations script-runtime.md, workflows runs.md, and the turn.failed entry in docs/api_to_audit.md.

No wire, SDK, or HOST_DAEMON_PROTOCOL_VERSION changes.

The remaining bound: a plugin re-runs on its own only if provider retry has not recorded a decision within 60 s of the failure. Provider retry's handler makes at most a few RPCs with 5 s timeouts, so this needs a stuck or crashed handler, or a process suspended across the window. Another gap: if threads.retry throws, provider retry records no decision, and the plugin re-runs after 60 s.

Left out:

  • If the Workflows plugin restarts during a handed-off wait, reconcileRunningCalls fails the call ("worker is in an error state"), and the restarted run's live suffix spawns a new worker while the old worker's queued retry still fires. Plugin restart already replays runs from scratch, and fixing that path means changing replay semantics.
  • If a turn fails before its spawn response returns, the run stays running until restart unless a provider retry finishes it. That's pre-existing and separate.

On the #7542 pointer: it doesn't affect this. #7542 changes the daemon turn.submit target to auto, but the persisted client/turn/requested target is still new-turn, as the live check below confirmed.

How you verified

Live on main first, with pnpm start:worktree, Claude Code pointed at a local 503 stub (CLAUDE_CODE_MAX_RETRIES=0), and real automations:

  • consent declined, and the automation's quick retry spawned a second thread. A double retry needs the consent miss, which the report's harness reproduces;
  • a target-thread send recorded target new-turn.

Live with this branch, same setup:

  • Automation: one thread. Provider retry Scheduled …: Provider unavailable. The run recorded skipped — failed run arun_… is not re-run: a retry (Provider unavailable) is queued in thread thr_…, and nextRunAt moved to the next hourly slot.
  • Automation, declined: a 400 stub gave not-retryable. The automation read the decision through decision.get and re-ran on its quick retry.
  • Workflows: one agent() call. The worker failed, provider retry queued a retry, and the call stayed running on the same worker ("keeps worker … a retry (Provider unavailable) is queued"). After two more provider-retry failures it was still one thread, still running, with attempt 3 queued and the worker not archived. The first two live runs here exposed the read-order race and the cleanup race above, and both fixes are in this branch.

Tests: the same handoff table runs in plugins/automations/src/server-harness.test.ts (real sweep service) and plugins/workflows/src/service-policy.test.ts (real workflow service):

  • six rows: provider retry queued, restart resume queued, retry already ran, retry lands mid-check, provider retry declined, provider retry not installed;
  • plus "waits for provider retry to decide" in both, which in Workflows also asserts the worker is not archived during the wait;
  • plus "re-runs after a minute without a decision" and "waits while provider retry's decision cannot be read, then re-runs after a minute" in Automations;
  • provider-retry: "publishes a failure's decision only once its retry is queued", plus discoverability.

Against main's sweep.ts / service.ts, the four stand-down cases fail in both plugins and the re-run controls pass. Against the old read order, the mid-check row fails in both. Without the cleanup guard, the Workflows wait test fails (expected [ 'child-1' ] to not include 'child-1'). Without the read-error catch in sweep.ts, the unreadable-decision test fails (expected [ [ { …(10) } ] ] to have a length of 2 but got 1): the automation never re-runs.

pnpm exec turbo run typecheck lint test --filter=bb-plugin-automations --filter=bb-plugin-provider-retry --filter=bb-plugin-workflows: 16/16 tasks, 165 + 27 + 273 tests. The lint warnings are pre-existing in each plugin's app.tsx.

Fixes #7708

🤖 Generated with Claude Code

AGENT GENERATED

@ymichael
ymichael force-pushed the bb/7708-failed-scheduled-automation-turn-is-retried-thr_nkv2eyk7cp branch from 2073673 to d8ea653 Compare November 18, 2026 00:27
@ymichael ymichael changed the title Let provider retry own failed automation turns; skip the automation's own retry One retry handoff for provider retry, Automations and Workflows Nov 18, 2026
ymichael and others added 2 commits November 17, 2026 21:01
… quick retry (#7708)

Automations no longer answers provider-retry.v1.consent. Before a quick
retry of a failed scheduled run, the sweep checks the run's thread: a
queued provider retry row, or a latest turn request that is itself a
retry, means provider retry took over, so the automation records the
slot as skipped instead of spawning or re-prompting again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Provider retry no longer asks senders for consent. It records each
failure's decision after queueing any retry and publishes it through a
discoverable decision.get RPC. Automations and Workflows share one rule
(identical retry-handoff.ts copies): read provider retry's decision
first, then the thread. A queued retry row (provider retry or core
restart resume) or a retry that already ran means stand down; an
undecided failure waits up to a minute; otherwise re-run.

Automations records the skipped quick retry with the actual reason.
Workflows reopens the failed call on the same worker instead of
spawning a replacement, and keeps that worker out of retirement
cleanup while the handoff is pending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/7708-failed-scheduled-automation-turn-is-retried-thr_nkv2eyk7cp branch from d8ea653 to e50bfd0 Compare November 18, 2026 05:33
…on (#7708)

An error while reading provider retry's decision escaped the sweep, so the
automation stayed due and never re-ran while the read kept failing. Treat a
failed read like an undecided failure: wait while the failure is under a
minute old, then re-run, matching Workflows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 1b70bb6 into main Nov 18, 2026
53 checks passed
@ymichael
ymichael deleted the bb/7708-failed-scheduled-automation-turn-is-retried-thr_nkv2eyk7cp branch November 18, 2026 17:56
ymichael added a commit that referenced this pull request Nov 18, 2026
…7749)

## Human comments

## What was wrong

Automations, Workflows and Tasks keep a record per piece of work: an
automation run, a workflow call, or a task's delegated-thread status.
Each closed that record only on `thread.idle` or `thread.failed`, for a
thread id it learned from its own SDK call. Every other way the work can
end left the record open:

- **Event before the link.** A plugin learns a spawned thread's id only
from the `threads.spawn` / `threads.fork` response, but core delivered
the thread's events as soon as they fired. A turn that ended first was
dropped, so the run stayed `running` until a restart.
- **Queued message deleted.** Core does emit `message.cancelled`
(`apps/server/src/routes/threads/actions.ts:439`), but no run-record
plugin listened for it. The Automations run stayed `running` on a
`pending` thread forever. Later runs deduped onto it, so the automation
was wedged, and the restart reconcile kept it open (`run.ts:456-457`).
- **Run thread archived or deleted.** Automations' `thread.deleted`
handler only disabled automations that target the thread and never
closed runs, and nothing handled archive. Only a restart closed these
runs.
- **Reconcile gave up.** One transient `threads.get` error left the run
open until the next restart (`run.ts:435-438`).
- **Workflow correction send deleted.** The call waited for the 24 h run
timeout (`service.ts:1131`).

Found by @thread:thr_nkv2eyk7cp while working on #7717. No filed issue
matches; #1914 is a different problem.

## What changed

**One outcome owner in core: `experimental_thread.settled`.**
- It delivers a `PluginThreadSettledEvent` union: `completed`
(`lastAssistantText`), `failed` (`error`), `cancelled` (the removed
queued `entry`, whose `originPluginId` names the sender), `archived`,
`deleted`.
- `apps/server/src/services/plugins/plugin-service.ts` emits it from the
same seams that already emit `thread.idle`, `thread.failed`,
`thread.archived`, `thread.deleted` and `message.cancelled`, so it can't
drift from them.
- The three plugins close their records from it with one exhaustive
`switch`:

| Record | completed | failed | cancelled (own message) | archived |
deleted |
|---|---|---|---|---|---|
| Automation run (`plugins/automations/src/run.ts`
`settleAutomationRunsForThread`) | succeeded | failed | skipped |
skipped | skipped, plus target automations disabled as before |
| Workflow call (`plugins/workflows/src/server.ts`) | result | failed |
failed | failed | failed |
| Tasks delegated thread (`plugins/tasks/lifecycle/index.ts`) | idle |
failed | idle if the thread is still `pending` with nothing left queued
| idle | completed |

**Automations reconcile.**
- A `pending` thread with nothing left queued is closed as skipped.
- A run whose thread can't be read is retried on the next sweep tick,
instead of waiting for the next restart.
- Only runs that were open at startup are retried, so an in-flight spawn
is never touched.

**Event ordering, kept from the first commit.** Core delivers a plugin's
events for a thread its own in-flight `threads.spawn` / `threads.fork`
may have created only after that call has returned.
`packages/plugin-sdk/src/internal/thread-event-gate.ts` holds this, and
core and the fake plugin host share it.
- I kept it instead of correlating by `pluginMetadata`, for three
reasons:
- Metadata is per thread, not per message, so Automations' target-thread
sends must match by thread anyway.
- Putting the receiving plugin's metadata in the payload would mean
building one payload per plugin.
- Tasks mirrors `thread.created` / `thread.active` for threads it
spawns. Those aren't terminal outcomes, and it relies on the ordering.
- With the hold, matching by thread id is safe for every thread event,
`settled` included. Its cost is that a spawning plugin hears about
threads created during its own call only once the call returns.

**Patches deleted:** the post-attach re-reads in
`plugins/workflows/src/service.ts`, which also invented the error
"Workflow worker failed before attachment completed", and in
`plugins/tasks/delegate/index.ts`, plus their test-only stubs.

**SDK surface:**
- `experimental_thread.settled` and `PluginThreadSettledEvent`. Entry in
`docs/api_to_audit.md`; callers are Automations, Workflows and Tasks.
- Docs: `backend-events.md`, `backend-sdk.md`, `testing.md`, the
`PluginEvents.on` JSDoc, and the Guide's `thread-events` card symbols.
- The fake plugin host follows `thread.idle` / `failed` / `archived` /
`deleted` with their settled event, as the server does. Tests emit
`cancelled` directly, because the fake has no thread record.
- Plugin SDK **0.6.160**. No server/daemon wire change.

### Left out, each with a different owner
- A concurrency-limit hold whose only recheck lands inside the 1 s
pacing window
(`apps/server/src/services/threads/queued-message-dispatch.ts:517`). The
record is core's queued row, released by plugin rechecks, not by a
thread outcome.
- A plugin schedule whose function never settles
(`packages/db/src/data/plugin-schedules.ts:98-126`). It waits on the
plugin's own promise.
- Browser Automation `cleanupPending` sessions waiting for a host
reconnect (`plugins/browser-automation/server.ts:166`).
- Tasks `taskThreadsAttach` (`delegate/index.ts:390-402`) reads the
status and then upserts it, for a thread that already exists.
- Of these, I reproduced none live.

## Decisions for review

- **Automations: archived or deleted run thread.** The run now closes
right away as skipped ("interrupted: thread … was archived/deleted").
Before, it stayed `running` until a restart closed it with the same
reason.
- **Automations: queued message deleted.** The run closes as skipped
("cancelled: its message was deleted before it ran"), and the next
manual run starts fresh.
- **Automations: pending thread with nothing queued.** The startup
reconcile now closes it as skipped instead of leaving it running.
- **Workflows:** deleting a worker's queued message fails its call.
- **Tasks:** an archived thread shows idle, and a pending delegated
thread shows idle once its last queued message is deleted, instead of
starting forever. Deleting one of several queued messages keeps it
starting.
- **Delayed delivery.** A spawning plugin gets events for threads
created during its own spawn/fork only once that call returns, normally
milliseconds and bounded by the SDK's 75 s timeout.

## How you verified

**Live, on `start:worktree`.** Claude Code was pointed at a stub API
that fails every request.

| Case | main | this branch |
|---|---|---|
| Spawn response held 4 s by a fetch preload (no product code changed) |
turn failed at +1.5 s; run `arun_otutef4oplm` stuck `running` until
restart | turn ended at +1.4 s; run closed `failed` at +4.04 s |
| `concurrency-limit global 0`, then the held message deleted with `bb
thread queue delete` | run `arun_3onytgpfaeu` stuck on a `pending`
thread through two restarts; later runs deduped onto it | run
`arun_kjn6kve3ouw` closed `skipped` at once; the next manual run got a
new id |
| Startup with that main-era run still open | — | reconcile closed
`arun_3onytgpfaeu` as skipped |
| Held run's thread archived with `bb thread archive` | — | run
`arun_zvbtq6iohhi` closed `skipped` |

**Guard tests:**
- **Each run-record plugin** has a table typed
`Record<PluginThreadSettledEvent["outcome"], …>`, so a new outcome kind
fails typecheck until each plugin handles it. Every row runs for real.
- Automations and Workflows run every outcome both before and after
spawn returns.
  - Tasks runs every outcome.
- Against main's handlers all 25 rows fail (Automations 10/10, Workflows
10/10, Tasks 5/5).
- `apps/server/test/services/plugins/plugin-thread-settled.test.ts` is a
core table, also typed by outcome. Each row drives core's real path:
lifecycle moves, `DELETE …/queued-messages/:id`, `archive-all`, `DELETE
/threads/:id`. It checks a fixture plugin receives exactly that outcome.
- `plugin-thread-creation-event-order.test.ts` uses a real server with
the response held for spawn and fork. Both rows fail on main.
- Gate unit tests, and the Automations reconcile table (pending with and
without queued rows; unreadable runs returned for retry).

**Commands:**
- `turbo run test` passes for these packages:

  | Package | Tests |
  |---|---|
  | SDK | 437 |
  | Tasks | 409 |
  | Workflows | 279 |
  | Automations | 178 |
  | Plugin API docs | 75 |
  | bb guide | 7 |

- `vitest run test/services/plugins test/skills` in `@bb/server`: 701
pass.
- `turbo run typecheck --filter='...[origin/main]'`: 108 tasks pass.
- Lint and type-aware lint pass for the touched packages.

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

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
scheinriese added a commit to scheinriese/bb-plugin-boat that referenced this pull request Nov 19, 2026
At a usage limit's reset, bb's provider retry retries every stopped chat
within the same minute. The message.dispatch hook, which bb runs before it
resumes a machine, now holds a reset retry that would wake a suspended Boat
sandbox until its own slot, 30 s after the one before and never before the
wake pacer's next free wake, with the time on the queued row. bb keeps
owning and sending the retry; user input is never held.

bb 0.49's provider retry asks the sending plugin first
(provider-retry.v1.consent; bb 0.50 removed that in get-bb/bb#7717). Boat
answers with a lookup: it declines usage-limit retries of the chats it runs
(task chats, reviews, orchestrators) and allows everything else. Once
provider retry has recorded that decline (decision.get: declined-by-sender),
or recorded nothing and bb's queue holds no retry, Boat queues the stopped
turn again itself with threads.retry for the planned time: one per stopped
turn, an ordinary retry row. Passing bb errors are tried again; only bb
refusing it for good settles it. A chat Boat resumed once is provider
retry's the next time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
scheinriese added a commit to scheinriese/bb-plugin-boat that referenced this pull request Nov 19, 2026
* Update bb on a resumed sandbox in a fresh prefix before bb's setup

bb's service on a sandbox updates itself in place when the bb server is
newer, and on a disk boat.dev is still restoring that npm install can hang
as a zombie or stop half way (MODULE_NOT_FOUND). Before bb's setup on a
resume, Boat now looks at bb's install over boat's exec API (one capped,
plain bash -c) and, when it's older than the server's version or broken
and the server's build is already downloaded there, copies that build to
/tmp, stops bb's unit, installs it into a fresh prefix with its own npm
cache, checks it (version, bin, native add-ons), swaps it in keeping the
old one, writes bb's artifact digest (bb's setup then doesn't install the
same build again) and starts the unit right away. Old and half-made
installs are deleted in the background afterwards. At most 5 minutes; any
failure keeps the old install, starts the unit again, is told in plain
words on the sandbox's tasks and backs off (30 minutes, doubling to 6
hours). A broken install with nothing to install from is moved aside so
bb's setup installs into an empty prefix.

A hung update of bb's own is not fought: nothing is stopped or installed,
and the wake fails already diagnosed (the guard reads wakeDiagnosis). A
zombie npm install, seen twice 5 s apart, is daemon-broken: the repair
under Needs you. bb's service stuck stopping, or an npm install whose read
of the disk made no progress for 2 minutes, is disk-restoring: Boat's own
retries. MODULE_NOT_FOUND counts only from this boot's journal.

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

* Read bb's files right after a wake, and wire the bb update in

Before bb starts on a woken sandbox, read through bb's data dir and the nvm
node bb runs on (nice, ionice, one file at a time), so boat.dev's lazy
restore streams them in before bb needs them. Old, half-made and
about-to-be-replaced installs, bb's download and anything outside the home
are skipped. It stops after 60 seconds or 1.5 GiB and never holds up the
wake past that, whatever the disk does.

The machine provider's resume now runs both steps (the look, the prefetch,
then the safe bb update) between turning off the login scripts and bb's
setup, with the server's version from bb.sdk.system.version (5 s at most,
cached 10 minutes; unknown: the download's own version counts).

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

* Pace usage-limit reset retries that would wake Boat sandboxes

At a usage limit's reset, bb's provider retry retries every stopped chat
within the same minute. The message.dispatch hook, which bb runs before it
resumes a machine, now holds a reset retry that would wake a suspended Boat
sandbox until its own slot, 30 s after the one before and never before the
wake pacer's next free wake, with the time on the queued row. bb keeps
owning and sending the retry; user input is never held.

bb 0.49's provider retry asks the sending plugin first
(provider-retry.v1.consent; bb 0.50 removed that in get-bb/bb#7717). Boat
answers with a lookup: it declines usage-limit retries of the chats it runs
(task chats, reviews, orchestrators) and allows everything else. Once
provider retry has recorded that decline (decision.get: declined-by-sender),
or recorded nothing and bb's queue holds no retry, Boat queues the stopped
turn again itself with threads.retry for the planned time: one per stopped
turn, an ordinary retry row. Passing bb errors are tried again; only bb
refusing it for good settles it. A chat Boat resumed once is provider
retry's the next time.

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

* Document the bb prefetch, the safe bb update and paced reset retries

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

* Never stop bb's own update half way, and tell what became of the old bb

From review t_24ceb6ed:
- The look now reports every live npm install of bb's own: in any state,
  found by its arguments (this data dir's npm or download) or by the unit it
  runs in. bb's in-place update running right now is never stopped: Boat
  waits for it (looking again every 10 s, up to 3 minutes), then decides
  again; still running, the wake goes to Boat's retries. The install script
  checks once more right before it stops bb's unit, and backs off if one
  started since the look.
- Every failure re-checks the old install (bin, daemon bundle, the version
  the look read): kept as it was, it starts again and the note says so; no
  longer complete after Boat's stop, it goes aside for bb's setup and the
  note says that; unreadable, the note says Boat couldn't check it. Nothing
  claims "kept" for an install that isn't.
- The install's time limit reserves bb's restart and the last checks (70 s)
  inside its 300 s, so the 360 s exec always sees the unit started again.
- Failure backoffs long past their retry time are dropped, and a removed
  machine's goes at once.
- A comment on why the resume has no running-turn check: bb resumes only a
  suspended machine.

--allow-scripts already names better-sqlite3, node-pty and @parcel/watcher,
as bb's installer does; a test pins it.

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

* Pace reset retries per machine, on the shared wake hold, without idle polls

From review t_24ceb6ed:
- The lane keys its slots by the machine (the hook context's host id):
  every reset retry for one sandbox goes in its slot, so the others neither
  wait after it woke nor push other sandboxes back. A slot stays 15 minutes.
- The slot also waits out the wake hold the paid resume and the watchdog
  share (src/wake-budget.ts), on top of the pacer's next slot.
- A limit failure reads provider retry's decision only when Boat itself
  declined that request: it waits up to 10 s for bb 0.49's consent question
  and stops there when there's none (always, on bb 0.50).

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

* Document waiting for bb's own update and per-machine reset slots

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

* Check for bb's own update right before stopping its unit

The install script looked for a live npm install of bb's own before
copying and checking the download, which leaves a few seconds in which
bb's update could start unseen and then be stopped half way. The check now
runs immediately before systemctl --user stop, after the copy, gzip -t, the
version check and the leftover rename. A test starts bb's npm during the
gzip check: it's caught, and nothing is stopped or installed.

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

---------

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.

Failed scheduled automation turn is retried twice (provider-retry resumes the thread and the automation starts a fresh one)

1 participant