Skip to content

fix(gateway): recover in-flight replies across restart - #138071

Merged
steipete merged 4 commits into
mainfrom
codex/fix-gateway-restart-reply-cancellation
Sep 4, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/fix-gateway-restart-reply-cancellation

Conversation

@steipete

@steipete steipete commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where users restarting a Gateway during an in-flight tool wait could receive a late failure reply instead of reliable recovery. Restart marking could also touch work belonging to another Gateway instance in the same process. The release verification scenario stalled at its 120-second deadline.

Why This Change Was Made

Bind reply operations and session admissions to the existing host-owned Gateway resolver at admission. Plugin dispatch keeps its lifetime-guarded resolver wrapper and records the canonical host identity separately in the existing private WeakMap; shutdown never invokes a retired resolver to infer ownership. Capture the closing instance's exact owners before awaited restart marking, revalidate ownership and lifecycle immediately before cancellation and the durable write, and cancel parent replies before channel/tool teardown. An explicit unbound owner remains unbound during native-command adoption.

Queued follow-ups retain their constructor's Gateway binding through delivery retries, while each new turn acquires its own current execution authority. Existing finalizing owners stay non-abortable. If restart marking fails, shutdown keeps its explicit warning and cancels the parent consistently with the existing chat path; it does not claim that recovery was persisted.

User Impact

Interrupted tool work can reach restart recovery without a late response from the retiring reply. One Gateway's shutdown cannot mark or cancel another instance's work, and queued delivery retries do not inherit a later caller's request context.

Evidence

The original full release run exposed the failure in gateway-restart-inflight-run. A fresh Linux reproduction on the frozen release source failed at its unchanged 120-second deadline. Its synthetic transcript showed the old parent finalizer after child cancellation and before recovery.

Focused regressions cover cancellation ordering, marker failure, replacements during awaited marking, reentrant abort callbacks, finalizing owners, real SQLite instance isolation, post-plan release/lifecycle rotation, unbound adoption, and retry callback handoff. Every newly identified failure was reproduced before repair.

The unchanged Linux scenario now passes in 19.000 seconds: three restarts, three retained recovery policies, one final delivery, zero resend notices, and no unsafe visible finalizer. All 34 changed source inputs matched the recorded hashes before and after rebuilding. This exercises the real Gateway, channel, tool wait, and restart machinery with a mock provider; it is not a published-package or external-provider test.

The final release-context owner suite passes 227 tests across seven files. Main passes the 11 final focused cases and canonical core typecheck; the earlier main sibling run passed 111 tests before the wrapper addition. Touched-file lint passes. Independent source review and all three managed Codex review passes found no actionable P0–P2 issue. The complete changed gate passed, including core and test types, all three dead-export scans, lint, schema and legacy-store guards, import cycles, and webhook/pairing boundaries. The initial hosted CI run exposed one incomplete agent-handler fixture; the follow-up below repairs it. On the previous head 963adabb490dfa6c11bb5ab7284571e207c64038, the repaired agent-handler shard passed in 7m13s. CI 33857070273 attempt 1 completed with 106 successful jobs and one failed memory-test leaf plus its aggregate gate. That main-only test and owner are unchanged by this PR, and the same shard passed on the preceding PR commit. The single failed-only retry repeated the same 120-second memory-test timeout (job 100982128690, 2,123 other tests passed). That blocked the previous head. The independently landed canonical fixture fix described below is now included; the exact-head CI result is recorded below. No timeout or assertion was weakened.

No configuration, schema, stored representation, protocol, or dependency changes. Production is +228/-33 (net +195); tests and support are +431/-2 (net +429). The repair removes global restart-marker selection, shares the existing abort loop, and binds at the sole admission producer instead of expanding the operation factory. Remaining growth establishes the missing instance/lifecycle ownership boundary, detached callback scoping, and commit-time checks; reordering shutdown alone failed the real reproduction and cannot protect other Gateway instances or post-await replacement.

Release-note context: Gateway restart recovery now cancels retiring parent replies before channel/tool teardown and preserves instance ownership through plugin dispatch and queued delivery retries.

Hosted CI follow-up

The agent-handler suite deliberately controls lifecycle generation in both its event and run-registry mocks. The new admission path reached the registry getter that its full mock omitted, so 206 cases failed before reaching their behavior assertions. The fixture now reads the same existing mutable generation through that getter; it does not import a competing real generation or change production behavior. A focused pre-edit case reproduced the failure, and all 302 consumer cases pass afterward in their original order, including reset, rotation and chat-abort integration. Scoped lint and the canonical Gateway test typecheck also pass. Independent incremental Codex review found no actionable P0–P2 issue in this fixture follow-up.

Review response

Decision for the latest review's production-growth item: retain the canonical Gateway-resolver binding from admission through shutdown and retry handoff. The +195 production lines establish facts that the prior global flow did not retain: the admitting instance, its lifecycle generation, the exact captured operation, and synchronous revalidation after asynchronous preparation. Removing those checks would reintroduce cross-instance marking/cancellation or stale-owner writes; reordering shutdown alone already failed the unchanged real restart reproduction.

The repair absorbs this into the existing private resolver WeakMap, admission producer, abort loop, and durable commit guard. It removes global marker selection and avoids expanding the operation factory. No parallel recovery path, configuration option, schema change, or public compatibility layer was added. The review identifies no smaller coherent absorption or actionable correctness/security defect; the focused cross-instance, replacement, rotation, unbound-adoption, reentrant-abort, and retry tests cover the required boundary. No source change is needed for this review item. Required exact-head CI remains the landing gate; the canonical memory-fixture repair below is included and its CI result is recorded below.

Canonical memory fixture refresh

Head 9e9f0c0bd625d16f054b0a1fe2f55ef1f81a4be8 adopts the already-landed test-only fix from #138123, commit 02099218c1ac706400211d193c7c2a7bd3d23bf8. The first recall-tracking case bypassed the existing isolated memory-tool helper and synchronously loaded real plugins during construction. The shared helper already used by its siblings disables that unrelated discovery while preserving all assertions, order, deadlines, and explicit dreaming configuration. No release or production code changes were added.

All four recall cases pass locally in their original order (first case 19 ms). The complete changed-file gate passes, including extension test types, lint and all three dead-export scans. Independent P0–P2 review is clean. This refresh is +18/−26 test lines, zero production lines; the existing restart repair remains +195 production lines. The canonical source PR also has successful exact-head CI; the refreshed PR still requires its own CI before landing.

Previous CI result

CI 33866131175 finished with failure on head 9e9f0c0bd625d16f054b0a1fe2f55ef1f81a4be8. The repaired memory shard passed in 4m23s. Two separate blockers remain: the dependency advisory service timed out, leaving the audit incomplete; and the current-main merge candidate deletes docs/clawhub/publishing.md while qa/scenarios/plugins/clawhub-release-policy-contracts.yaml still references it. The scenario-catalog assertion correctly rejects that missing file. The latter came from the main-side removal in #138157; the reviewed PR head still contains the document. Neither is a restart-recovery regression.

The native review artifacts were refreshed for this exact head and validate successfully. Required green CI remains unsatisfied; no merge bypass or repeated unchanged retry was used. One cached compact-shard record still reported running after the overall run became terminal; it is not counted as a verified pass.

Canonical documentation fixture refresh

Head 888a1905675a9032e42c7a6a99962d57960f3254 adopts the one-line scenario reference correction already landed in #138044, commit 085641a41a5db77af4420249a6896fbc7eea9f23. The scenario now points to the existing plugin-building guide. This imports only the canonical fixture line; scenario execution and production code are unchanged. All 58 catalog tests pass in their original order, the complete canonical changed-file gate passes, and independent P0–P2 review has zero findings. New exact-head CI is required before landing. The refresh is +1/−1 fixture lines, zero production lines.

Green hosted validation

CI33872175170 succeeded on 888a1905675a9032e42c7a6a99962d57960f3254, including the required aggregate gate. All134 attached passing checks and41 scoped skips are terminal; none remain failed or pending. Workflow Sanity33872175065 also passed. This satisfies the latest ClawSweeper review’s complete-CI request and rank-up move. Native preparation supplies the refreshed integration receipt before merge.

Bind reply and session admission ownership to the Gateway host, including
lifetime-wrapped plugin dispatch and queued delivery retries. Mark exact
active owners durably, revalidate at commit and cancellation, then abort
retiring parents before tool and channel teardown.

The unchanged Linux scenario now completes three restarts with three
retained recovery policies and one final delivery in 19 seconds.
@steipete steipete self-assigned this Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Sep 4, 2026
Expose the registry generation from the same mutable fixture state used by
agent events and lifecycle rotation. Gateway agent-handler admission now
reaches the intended behavior assertions after the restart ownership fix.
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 8:47 AM ET / 12:47 UTC.

ClawSweeper review

What this changes

The PR binds in-flight replies and session admissions to the Gateway that admitted them so restart recovery and shutdown do not affect another in-process Gateway’s work.

Regression provenance

Possible regression — probable (reproduction; failure trace; reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this maintainer-owned PR open. Current main still lacks the Gateway-scoped recovery ownership in this branch; source and focused boundary tests support the repair, with no introduced correctness finding found. Complete exact-head CI is still required before merge.

Priority: P1
Reviewed head: 888a1905675a9032e42c7a6a99962d57960f3254

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused behavior evidence and boundary coverage support a coherent repair; complete exact-head CI remains the final merge gate.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (linked_artifact): The supplied PR evidence records an after-fix Linux run through the real Gateway, channel, tool-wait, and restart machinery: the unchanged three-restart scenario completed in 19 seconds with one final delivery and no unsafe visible finalizer. Its mock provider is appropriate for this internal transport and lifecycle recovery path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): The supplied PR evidence records an after-fix Linux run through the real Gateway, channel, tool-wait, and restart machinery: the unchanged three-restart scenario completed in 19 seconds with one final delivery and no unsafe visible finalizer. Its mock provider is appropriate for this internal transport and lifecycle recovery path.
Evidence reviewed 6 items Gateway-scoped shutdown repair: Shutdown snapshots reply operations before awaited recovery marking, then cancels only operations that are still the same registry entry, in the same lifecycle generation, and bound to the closing Gateway.
Admission owner boundary: Session admissions capture the Gateway resolver at admission and restart marking selects only the captured owner set, rechecking ownership immediately before the durable commit.
Current-main comparison: The fetched current-main version still collects all active session admissions and lacks the Gateway-bound reply-abort snapshot, so the central repair is not already implemented on main.
Findings None None.
Security None None.

How this fits together

Gateway shutdown coordinates active reply cancellation and durable restart-recovery records. Channel and plugin work enters through reply admission, retains its originating Gateway ownership, and is either cancelled before teardown or recovered by the next session.

flowchart LR
  A[Channel or plugin request] --> B[Reply admission]
  B --> C[Gateway-owned reply and session work]
  C --> D[Restart shutdown]
  D --> E[Recovery marker]
  D --> F[Reply cancellation]
  E --> G[Next-session recovery]
  F --> G
Loading

Before merge

  • Resolve merge risk (P1) - The supplied exact-head CI rollup is incomplete and its supplied test-merge artifact is stale, so merge integration remains unproven despite the focused source and behavior evidence.
  • Complete next step (P2) - Obtain a complete green required-CI result for head 888a190 before merge.
Agent review details

Security

None.

PR surface

Source +195, Tests +421, Other 0. Total +616 across 23 files.

View PR surface stats
Area Files Added Removed Net
Source 14 228 33 +195
Tests 8 449 28 +421
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 23 678 62 +616

Review metrics

Metric Value Why it matters
Production and test delta production +228/-33 (net +195); tests/test-support/QA +450/-29 (net +421) The production growth is concentrated in the Gateway ownership, reply admission, and commit-time revalidation boundary; the added tests exercise the corresponding cross-instance and lifecycle cases.

Merge-risk options

Maintainer options:

  1. Validate the integrated head (recommended)
    Obtain complete green required CI for the current head before merging this durable session-recovery change.

Technical review

Best possible solution:

Retain the admission-time Gateway binding and synchronous ownership revalidation as the canonical repair, then merge only after complete required CI is green for the current head.

Do we have a high-confidence way to reproduce the issue?

Yes—at high confidence from the reviewed current-main global selection path and the supplied frozen-release restart trace; this read-only review did not rerun the scenario.

Is this the best way to solve the issue?

Yes—the admission-time binding, captured shutdown snapshot, and pre-effect revalidation repair the ownership boundary more safely than inferring the active Gateway during shutdown.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8ef56e23c9d2.

Labels

Label justifications:

  • P1: A Gateway restart during active reply work can otherwise produce late failure delivery or incorrect restart recovery.
  • merge-risk: 🚨 session-state: The patch changes durable restart-recovery marking and lifecycle ownership checks for active session work.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The supplied PR evidence records an after-fix Linux run through the real Gateway, channel, tool-wait, and restart machinery: the unchanged three-restart scenario completed in 19 seconds with one final delivery and no unsafe visible finalizer. Its mock provider is appropriate for this internal transport and lifecycle recovery path.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied PR evidence records an after-fix Linux run through the real Gateway, channel, tool-wait, and restart machinery: the unchanged three-restart scenario completed in 19 seconds with one final delivery and no unsafe visible finalizer. Its mock provider is appropriate for this internal transport and lifecycle recovery path.

Evidence

What I checked:

  • Gateway-scoped shutdown repair: Shutdown snapshots reply operations before awaited recovery marking, then cancels only operations that are still the same registry entry, in the same lifecycle generation, and bound to the closing Gateway. (src/gateway/server-close.ts:348, 888a1905675a)
  • Admission owner boundary: Session admissions capture the Gateway resolver at admission and restart marking selects only the captured owner set, rechecking ownership immediately before the durable commit. (src/sessions/session-lifecycle-admission.ts:480, 888a1905675a)
  • Current-main comparison: The fetched current-main version still collects all active session admissions and lacks the Gateway-bound reply-abort snapshot, so the central repair is not already implemented on main. (src/gateway/server-close.ts:334, 8ef56e23c9d2)
  • Boundary regression coverage: Focused tests cover foreign Gateway isolation, replacement and rebinding during the awaited marker, finalizing owners, marker failure, lifecycle rotation, and unbound adoption. (src/gateway/server-close.test.ts:1077, 888a1905675a)
  • Area history: Recent merged history shows steipete authored prior restart-recovery and Gateway-lifecycle work in the same central files, supporting routing to this area owner. (src/agents/main-session-recovery/main-session-restart-recovery-marking.ts:111, 870ed9a5ab5d)
  • Release and integration status: The PR head is not contained by a local release tag and remains unmerged. The supplied test-merge record is stale and the supplied check rollup is incomplete, so neither establishes exact-head landing safety. (888a1905675a)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Obtain a complete green required-CI result on head 888a190.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-09-04T09:26:44.628Z sha 963adab :: blocked before merge. :: none
  • reviewed 2026-09-04T10:00:53.526Z sha 963adab :: blocked before merge. :: none
  • reviewed 2026-09-04T10:12:18.824Z sha 963adab :: blocked before merge. :: none
  • reviewed 2026-09-04T11:14:37.362Z sha 9e9f0c0 :: blocked before merge. :: none
  • reviewed 2026-09-04T11:52:50.286Z sha 9e9f0c0 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Sep 4, 2026
Adopt the already-landed canonical fixture repair from #138123 so the
Gateway restart forward-port can run its memory CI shard without loading
real plugins in the first recall-tracking case. Preserve all assertions,
test order, and deadlines. No production changes.

Source: 0209921
Validation: all four recall cases in original order; complete changed-file
gate including extension test types, lint, and dead-export scans; independent
P0-P2 review clean.
Adopt the canonical fixture correction from #138044 (085641a)
after main removed the former publishing page. Scenario behavior stays
unchanged. Verified all 58 catalog tests, complete changed-file checks,
and independent review.

@sylvesterkaczmarek sylvesterkaczmarek left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct fix shape. Bind the admitting Gateway identity once, then revalidate instance and lifecycle after awaited restart preparation. That closes the cross-instance and stale-owner races; cancelling the parent before channel/tool teardown also matches recovery ordering.

@steipete
steipete merged commit 9319ba0 into main Sep 4, 2026
189 checks passed
@steipete
steipete deleted the codex/fix-gateway-restart-reply-cancellation branch September 4, 2026 13:00
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
* fix(gateway): recover in-flight replies across restart

Bind reply and session admission ownership to the Gateway host, including
lifetime-wrapped plugin dispatch and queued delivery retries. Mark exact
active owners durably, revalidate at commit and cancellation, then abort
retiring parents before tool and channel teardown.

The unchanged Linux scenario now completes three restarts with three
retained recovery policies and one final delivery in 19 seconds.

* fix(test): keep Gateway admission on the fixture lifecycle generation

Expose the registry generation from the same mutable fixture state used by
agent events and lifecycle rotation. Gateway agent-handler admission now
reaches the intended behavior assertions after the restart ownership fix.

* test: reuse isolated memory tools in recall tracking

Adopt the already-landed canonical fixture repair from openclaw#138123 so the
Gateway restart forward-port can run its memory CI shard without loading
real plugins in the first recall-tracking case. Preserve all assertions,
test order, and deadlines. No production changes.

Source: 2fddacd
Validation: all four recall cases in original order; complete changed-file
gate including extension test types, lint, and dead-export scans; independent
P0-P2 review clean.

* test(qa): refresh ClawHub release policy docs reference

Adopt the canonical fixture correction from openclaw#138044 (62e4d4d)
after main removed the former publishing page. Scenario behavior stays
unchanged. Verified all 58 catalog tests, complete changed-file checks,
and independent review.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: memory-core Extension: memory-core extensions: qa-lab gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants