Skip to content

fix: resume replay-safe work after gateway restarts - #104997

Merged
steipete merged 3 commits into
mainfrom
codex/resume-interrupted-turns
Jul 12, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/resume-interrupted-turns

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Closes #104993

What Problem This Solves

Fixes an issue where users with replay-safe in-flight agent work would receive a restart-interruption notice and have to resend their request when the Gateway restarted.

Why This Change Was Made

Gateway recovery now recognizes persisted replay-safe Code Mode checkpoints and reconstructs the interrupted turn automatically. Recovered runs are durably constrained to audited read-only tools or plugin tools explicitly marked replay-safe; ambiguous and side-effecting work still fails closed.

User Impact

Replay-safe work continues after a Gateway restart and delivers one final response without another user message. Restart recovery does not automatically repeat unsafe external actions.

Evidence

  • Real Gateway child-process replacement: Crabbox run run_9ca55c40677c, passed=1 failed=0.
    • Persisted tail: assistant/toolUse/wait
    • Recovered tail: assistant/stop/text
    • Completion markers: 1
    • Resend notices: 0
    • Result: RESTART-CODE-MODE-WAIT-OK
  • Focused remote tests: Crabbox run run_13b5379ca3ac, 269 tests passed across restart recovery, Code Mode, session persistence, replay safety, and QA runtime.
  • Full changed-file gate: Crabbox run run_75cb5ad1900f, including formatting, typecheck, lint, policy checks, and import-cycle validation.
  • Docs validation: MDX and internal-link checks passed in run_72241a3256c3 and run_8343e0972025.
  • Fresh Codex autoreview: no accepted/actionable findings.

AI-assisted. I reviewed the implementation and understand the restart classifier, durable session guard, and fail-closed tool policy.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling extensions: qa-lab size: XL maintainer Maintainer-authored PR labels Jul 12, 2026
@clawsweeper

clawsweeper Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head b68ff9165fc14fae3c355173915163d702011524, but the PR head is now f8d9881f7db233deec0295d89fd82fa9195897cd. Its old verdict and PR readiness labels are no longer current.

Next step
Run or wait for a fresh ClawSweeper review on the current PR head.

@steipete

Copy link
Copy Markdown
Contributor Author

Land-ready proof for f8d9881f7db233deec0295d89fd82fa9195897cd:

  • Before: a Gateway restart abandoned the in-flight turn and emitted the resend notice from [Bug]: Gateway restart abandons replay-safe in-flight work #104993.
  • After: pnpm openclaw qa suite --provider-mode mock-openai --scenario gateway-restart-inflight-run completed through a real child-process Gateway replacement with one RESTART-CODE-MODE-WAIT-OK delivery and zero resend notices. Crabbox run_9ca55c40677c.
  • Focused regression suite: pnpm test src/agents/code-mode.test.ts src/agents/main-session-restart-recovery.test.ts src/agents/tool-replay-safety.test.ts src/agents/command/session-store.test.ts extensions/qa-lab/src/scenario-catalog.test.ts extensions/qa-lab/src/scenario-runtime-api.test.ts extensions/qa-lab/src/suite-runtime-agent-process.test.ts extensions/qa-lab/src/suite-runtime-flow.test.ts extensions/qa-lab/src/suite-runtime-gateway.test.ts — 269 passed, Crabbox run_13b5379ca3ac.
  • Full changed gate: CI=1 OPENCLAW_CHECK_CHANGED_REMOTE_CHILD=1 OPENCLAW_CHANGED_LANES_RAW_SYNC=1 pnpm check:changed — passed, Crabbox run_75cb5ad1900f.
  • Dependency contract follow-up: pnpm test src/plugins/contracts/extension-runtime-dependencies.contract.test.ts — 422 passed, Crabbox run_cafbe2deb1e6.
  • Docs: pnpm docs:check-mdx and pnpm docs:check-links — passed, Crabbox run_72241a3256c3 and run_8343e0972025.
  • Exact-head hosted CI: Actions run 29181107635; bundled protocol, both plugin contracts, QA smoke, build, lint, types, security, and selected runtime quality lanes passed.
  • Fresh Codex autoreview: no accepted or actionable findings.

Known proof gap: no production Discord restart was forced. The deterministic QA scenario uses the real Gateway child and the shared session/recovery/delivery path with qa-channel transport. The separate iOS Periphery workflow reports pre-existing dead code at apps/ios/WatchApp/Sources/WatchInboxStore.swift:242; this PR has no apps/ios/** diff, and the repo-native prepare gate classifies hosted gates as passed.

@steipete
steipete merged commit d14bb8e into main Jul 12, 2026
102 of 103 checks passed
@steipete
steipete deleted the codex/resume-interrupted-turns branch July 12, 2026 05:37
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 12, 2026
* fix: resume replay-safe work after gateway restart

* chore: leave restart note to release process

* fix: sync restart recovery protocol artifacts
obviyus added a commit that referenced this pull request Oct 17, 2026
…etes (#174696)

Related: #169118

## What Problem This Solves

Fixes: after `image_generate` (or video/music generation) finishes, the agent cannot check or fix the result. A failed generation is only reported and never retried. A wrong image is captioned "not fully fixed yet" and left as is.

The cause: every generated-media completion, failed ones included, ran as a durable "recovery" agent turn. That turn forced `forceRestartSafeTools`, `disableMessageTool` and an exact host media allowlist. The model saw only restart-safe tools: `image_generate` and `message` were gone. If evidence was missing, a re-arm loop replayed the whole turn. The tool list also changed between normal turns and completion turns, which broke the prompt cache.

## User Impact

- Generated media reaches the chat exactly once, sent by the host.
- The agent then gets one ordinary completion turn with its normal toolset. It can compare the result with the request and generate again, or retry a failed generation.
- The completion turn's tool schema matches an ordinary completion turn, not a restart-safe subset (37 of 38 tools in the live run below, against 11 before).

## Why This Change Was Made

The host owns the bytes and the agent owns the conversation. No model turn sits in the media delivery path.

1. **Host delivery.** The durable session-delivery row (same `agentTurn` entry kind and fields, no schema change) now sends its `expectedMediaUrls` with a deterministic outbound send. The send uses a stable delivery intent per row, so the outbound queue's receipt dedupes replays. It also carries the original requester session (session id and lifecycle revision), so outbound custody refuses the send, including a later recovery replay, if that session was reset or replaced. For internal routes, the media goes into the owning transcript as one idempotent host message. The send is fenced: a replay of a started send settles only from its outbound receipt and never sends again, even after the receipt has expired. An ambiguous send (a possible send, or a terminally failed or missing outbound receipt) dead-letters instead of sending again.
2. **One ordinary completion turn.** After the send settles, the row advances (media list cleared, a host notice that the files were already sent is put before the event). The next drain then runs one `agent` turn with the requester's normal tools and reply policy: no `forceRestartSafeTools`, no `disableMessageTool`, no media allowlist. The turn keeps its start fence, so an interrupted turn is never replayed. If only the follow-up turn is lost after the media was delivered, the row settles as delivered. Otherwise the media task would report the media as undelivered and retain it a second time (visible on webchat).
3. **Failures.** A failed generation has no media, so its row skips the send and runs only the ordinary completion turn. It keeps the durable row, not the direct announce path, because the direct path rejects generated-media events in cron-run sessions.
4. **New instruction.** The completion instruction tells the model that the host already sent the files. It asks the model to check the result against the request and continue (for example, generate again with adjusted parameters) when the result falls short or the failure looks recoverable. Otherwise the model gives a short reply. The model judges quality; no code judge was added.
5. **Removed:** the media evaluator and re-arm loop, `internalDeliveryMediaUrls` / `internalDeliverySuppressText` plumbing, the media branch of the recovery-options invariant (`resolveCommandRecoveryOptions`), `constrainRestartRecoveryDeliveryPayloads`, `buildGeneratedMediaDeliveryContext`, the retry prompt, and evidence helpers only that path used. `forceRestartSafeTools` stays for real restart recovery (#104997).

Upgrade: pending media rows from older versions drain through the new path. The host transcript step uses its own stable key, so it cannot collide with a transcript entry an older release already wrote. A row that a previous version re-armed is host-sent and then gets the completion turn (covered by a test). A row with a started attempt dead-letters, as before.

This replaces the queued agent turn that #108024 introduced for exactly-once delivery (#87989, #87995). It also removes the CLI message-tool mismatch in #169118, because the completion turn no longer restricts the message tool.

## Evidence

**Live Telegram (Test Server, real user account, mock model provider that logs the tools offered on each request). "This PR" rows ran on the exact head build:**

| Run | Build | What happened in the chat | Completion turn tools |
| --- | --- | --- | --- |
| A: generate | main | "Working on it." → 1 photo, captioned "The date ring is wrong but I cannot regenerate from this turn." | 11 restart-safe tools, no `image_generate`, no `message` |
| A: generate | this PR | "Working on it." → photo 1 → "Working on it." → photo 2 → final reply | 37 tools incl. `image_generate` and `message`. It called `image_generate` again. |
| C: provider fails | main | "Working on it." → "Image generation failed and I cannot retry here." | 11 tools |
| C: provider fails | this PR | "Working on it." → retry → 1 photo → final reply | 37 tools. It retried. |
| D: restart mid-send | this PR | Telegram accepted `sendPhoto`, the response was held, the Gateway restarted, then the response was released. Exactly 1 photo. | Outbound recovery refused a blind replay. The row dead-lettered. No duplicate. |

On every run, each photo appeared as exactly one native Telegram message. The user turn offered 38 tools. The one tool missing from the completion turn is `transcripts`, which needs a human sender or operator identity. Ordinary subagent completion turns also lack it.

**Live Telegram with a real model** (`gpt-6-sol`, real `gpt-image-1`, Code Mode on as in production, Tool Search off). A logging proxy in front of the OpenAI API recorded the tools offered on each request and injected one fault per run:

| Run | Injected fault | What happened |
| --- | --- | --- |
| Wrong result | First image returned as a blank grey square | The completion turn opened it with `view_image`, saw it was blank, built a corrected calendar with `exec`, checked it, and sent it ("The first image didn't render…"). 2 photos, each once. |
| Failed generation | First image request returned HTTP 500 | The completion turn said "hit a temporary image-service error, retried", called `image_generate` again, real `gpt-image-1` returned 200. 1 photo, then the reply. |

In Code Mode, the user turn and the completion turn offered the identical tool list (`exec`, `message`, `sessions_yield`, `view_image`, `wait`), so the prompt cache holds across them. With Code Mode off, a separate run showed 38 vs 37 tools (`transcripts`, see above).

**Focused tests:** the three `server-restart-sentinel*` suites pass. They cover the host send before the completion turn, no resend after a crash between send and turn, dead-letter on a possible send or a terminal outbound failure, deferral while outbound recovery owns the send, safe retry when the send provably did not reach the chat, failed generation, cron continuation, the internal-route transcript, an old re-armed row, requester binding through the real queue, and a refused follow-up turn after delivered media. Queue, recovery, announce, media-background and managed-attachment suites also pass (258 tests). CI is green on the head apart from one ratchet failure that comes from `main` and also fails on unrelated PRs (see the maintainer override comment).

Requester revocation: the binding test asserts the original requester (session id, lifecycle revision) reaches outbound custody. The existing outbound integration test `deliver.session-generation.integration.test.ts` ("replays every same-generation result and terminalizes only revoked unsent results") proves that custody refuses a revoked generation before platform I/O, including on recovery.

Not covered: in run D the completion turn does not run, because the row dead-letters on the ambiguous send. That is the intended exactly-once trade-off.

## Merge danger

Two-way door. A revert restores the old queued agent turn. The rows this PR writes use the existing entry kind and fields, so the old code reads them. Blast radius: every generated-media completion on every channel, including internal webchat delivery and cron-run sessions.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…etes (openclaw#174696)

Related: openclaw#169118

## What Problem This Solves

Fixes: after `image_generate` (or video/music generation) finishes, the agent cannot check or fix the result. A failed generation is only reported and never retried. A wrong image is captioned "not fully fixed yet" and left as is.

The cause: every generated-media completion, failed ones included, ran as a durable "recovery" agent turn. That turn forced `forceRestartSafeTools`, `disableMessageTool` and an exact host media allowlist. The model saw only restart-safe tools: `image_generate` and `message` were gone. If evidence was missing, a re-arm loop replayed the whole turn. The tool list also changed between normal turns and completion turns, which broke the prompt cache.

## User Impact

- Generated media reaches the chat exactly once, sent by the host.
- The agent then gets one ordinary completion turn with its normal toolset. It can compare the result with the request and generate again, or retry a failed generation.
- The completion turn's tool schema matches an ordinary completion turn, not a restart-safe subset (37 of 38 tools in the live run below, against 11 before).

## Why This Change Was Made

The host owns the bytes and the agent owns the conversation. No model turn sits in the media delivery path.

1. **Host delivery.** The durable session-delivery row (same `agentTurn` entry kind and fields, no schema change) now sends its `expectedMediaUrls` with a deterministic outbound send. The send uses a stable delivery intent per row, so the outbound queue's receipt dedupes replays. It also carries the original requester session (session id and lifecycle revision), so outbound custody refuses the send, including a later recovery replay, if that session was reset or replaced. For internal routes, the media goes into the owning transcript as one idempotent host message. The send is fenced: a replay of a started send settles only from its outbound receipt and never sends again, even after the receipt has expired. An ambiguous send (a possible send, or a terminally failed or missing outbound receipt) dead-letters instead of sending again.
2. **One ordinary completion turn.** After the send settles, the row advances (media list cleared, a host notice that the files were already sent is put before the event). The next drain then runs one `agent` turn with the requester's normal tools and reply policy: no `forceRestartSafeTools`, no `disableMessageTool`, no media allowlist. The turn keeps its start fence, so an interrupted turn is never replayed. If only the follow-up turn is lost after the media was delivered, the row settles as delivered. Otherwise the media task would report the media as undelivered and retain it a second time (visible on webchat).
3. **Failures.** A failed generation has no media, so its row skips the send and runs only the ordinary completion turn. It keeps the durable row, not the direct announce path, because the direct path rejects generated-media events in cron-run sessions.
4. **New instruction.** The completion instruction tells the model that the host already sent the files. It asks the model to check the result against the request and continue (for example, generate again with adjusted parameters) when the result falls short or the failure looks recoverable. Otherwise the model gives a short reply. The model judges quality; no code judge was added.
5. **Removed:** the media evaluator and re-arm loop, `internalDeliveryMediaUrls` / `internalDeliverySuppressText` plumbing, the media branch of the recovery-options invariant (`resolveCommandRecoveryOptions`), `constrainRestartRecoveryDeliveryPayloads`, `buildGeneratedMediaDeliveryContext`, the retry prompt, and evidence helpers only that path used. `forceRestartSafeTools` stays for real restart recovery (openclaw#104997).

Upgrade: pending media rows from older versions drain through the new path. The host transcript step uses its own stable key, so it cannot collide with a transcript entry an older release already wrote. A row that a previous version re-armed is host-sent and then gets the completion turn (covered by a test). A row with a started attempt dead-letters, as before.

This replaces the queued agent turn that openclaw#108024 introduced for exactly-once delivery (openclaw#87989, openclaw#87995). It also removes the CLI message-tool mismatch in openclaw#169118, because the completion turn no longer restricts the message tool.

## Evidence

**Live Telegram (Test Server, real user account, mock model provider that logs the tools offered on each request). "This PR" rows ran on the exact head build:**

| Run | Build | What happened in the chat | Completion turn tools |
| --- | --- | --- | --- |
| A: generate | main | "Working on it." → 1 photo, captioned "The date ring is wrong but I cannot regenerate from this turn." | 11 restart-safe tools, no `image_generate`, no `message` |
| A: generate | this PR | "Working on it." → photo 1 → "Working on it." → photo 2 → final reply | 37 tools incl. `image_generate` and `message`. It called `image_generate` again. |
| C: provider fails | main | "Working on it." → "Image generation failed and I cannot retry here." | 11 tools |
| C: provider fails | this PR | "Working on it." → retry → 1 photo → final reply | 37 tools. It retried. |
| D: restart mid-send | this PR | Telegram accepted `sendPhoto`, the response was held, the Gateway restarted, then the response was released. Exactly 1 photo. | Outbound recovery refused a blind replay. The row dead-lettered. No duplicate. |

On every run, each photo appeared as exactly one native Telegram message. The user turn offered 38 tools. The one tool missing from the completion turn is `transcripts`, which needs a human sender or operator identity. Ordinary subagent completion turns also lack it.

**Live Telegram with a real model** (`gpt-6-sol`, real `gpt-image-1`, Code Mode on as in production, Tool Search off). A logging proxy in front of the OpenAI API recorded the tools offered on each request and injected one fault per run:

| Run | Injected fault | What happened |
| --- | --- | --- |
| Wrong result | First image returned as a blank grey square | The completion turn opened it with `view_image`, saw it was blank, built a corrected calendar with `exec`, checked it, and sent it ("The first image didn't render…"). 2 photos, each once. |
| Failed generation | First image request returned HTTP 500 | The completion turn said "hit a temporary image-service error, retried", called `image_generate` again, real `gpt-image-1` returned 200. 1 photo, then the reply. |

In Code Mode, the user turn and the completion turn offered the identical tool list (`exec`, `message`, `sessions_yield`, `view_image`, `wait`), so the prompt cache holds across them. With Code Mode off, a separate run showed 38 vs 37 tools (`transcripts`, see above).

**Focused tests:** the three `server-restart-sentinel*` suites pass. They cover the host send before the completion turn, no resend after a crash between send and turn, dead-letter on a possible send or a terminal outbound failure, deferral while outbound recovery owns the send, safe retry when the send provably did not reach the chat, failed generation, cron continuation, the internal-route transcript, an old re-armed row, requester binding through the real queue, and a refused follow-up turn after delivered media. Queue, recovery, announce, media-background and managed-attachment suites also pass (258 tests). CI is green on the head apart from one ratchet failure that comes from `main` and also fails on unrelated PRs (see the maintainer override comment).

Requester revocation: the binding test asserts the original requester (session id, lifecycle revision) reaches outbound custody. The existing outbound integration test `deliver.session-generation.integration.test.ts` ("replays every same-generation result and terminalizes only revoked unsent results") proves that custody refuses a revoked generation before platform I/O, including on recovery.

Not covered: in run D the completion turn does not run, because the row dead-letters on the ambiguous send. That is the intended exactly-once trade-off.

## Merge danger

Two-way door. A revert restores the old queued agent turn. The rows this PR writes use the existing entry kind and fields, so the old code reads them. Blast radius: every generated-media completion on every channel, including internal webchat delivery and cron-run sessions.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docs Improvements or additions to documentation extensions: qa-lab gateway Gateway runtime maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Gateway restart abandons replay-safe in-flight work

1 participant