Skip to content

fix(gateway): settle interrupted turns and cancel queued shutdown recovery - #177223

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-aborted-runs-never-settle-sigkill-20260919
Oct 19, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-aborted-runs-never-settle-sigkill-20260919

Conversation

@steipete

@steipete steipete commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway shutdown could retire its in-process instance binding before admitted turns finished pending-input settlement. Keep that binding until received execution and finalizers join; the existing entry fence continues rejecting new requests.

Worker reconciliation had a separate shutdown hang: provisioning recovery lost the service cancellation signal before waiting for session admission. A recovery queued behind another session mutation could therefore keep shutdown.worker-environments.reconcile-guard pending indefinitely. Carry the existing signal through the coordinator queue and session admission. Preserve FIFO ordering and the joins for provider operations and writes that already started.

Both changes use the existing lifecycle owners. No new state, timeout, configuration, schema, or public API is introduced. Production LOC is +10, solely for the explicit coordinator cancellation contract and passing that signal through existing admission.

Evidence

  • Binding lifetime: the existing real Gateway integration enters through the production in-process dispatcher, holds finalization through stop/restart, and checks error-free pending-input settlement. Stop/restart failed before the ordering repair; stop, restart, and graceful drain pass (3 tests). Recovery marking precedes cancellation, new entry is refused, cleanup finishes before teardown, and the binding is unavailable afterward.
  • Reconciliation hang: a new case in the existing provisioning-cancellation file holds a real session mutation, enters reconciliation through its installed guard, then stops the service. Before the fix, shutdown stays pending until the held mutation releases (the assertion fails after 3 seconds). Afterward shutdown completes while the mutation remains held; durable provisioning and its allocation remain intact, and no provider allocation or destruction starts.
  • Focused worker proof: provisioning-cancellation 31/31, coordinator admission/reclaim 28/28. Provider-settlement custody and FIFO cases remain green. The provisioning file took 53.45s; the three-file first candidate run took 105.72s and exposed only a missing spy in the new fixture, corrected before the final green run.
  • Extended the existing real-process SIGTERM E2E with detached a2a delivery and a yielded-parent lifecycle wake, retaining its pending model transports, background Git child, and recovered provisioning. It requires exit 0 within 10 seconds, no shutdown deadline or missing-binding error, and child termination. Both baseline and candidate pass: 12.187s/9.623s test-only, 20.54s/43.66s wall including module-cache preparation. This is signal-boundary coverage, not the causal red/green proof above or a paired performance measurement.
  • Changed-file format/lint and diff checks pass. The core typecheck passed for the initial binding repair; PR CI covers the final cancellation signature and broad checks. No local suite or build ran.
  • Full-candidate independent Codex autoreview is clean through P1; no actionable findings. Simplification retained the existing owners, cancellation signal and cleanup joins.
  • Final-head CI run 39235568093 passed, including production/test types, changed test lanes, lint, and all three PostgreSQL conformance shards. Both enforced CI-gate publishers passed before the pinned squash merge. One earlier PR-body check rejected non-template section headings; the corrected headings passed without a code change or CI rerun.

Real-model comparison and limitations

Two concurrent real-model A/B pairs ran on isolated synthetic Linux Gateways under an exclusive measurement lock. Each side used 16 CPUs, separate state and ports, the same driver and start barrier; the second pair swapped CPU halves. At SIGTERM each had three admitted runs, session:a2a-send, subagents:lifecycle-wake, three background sleep descendants, and an independent OpenAI stream interrupted immediately after its first assistant chunk.

Pair Baseline SIGTERM to exit Candidate SIGTERM to exit Candidate minus baseline Baseline/candidate abort to run registry empty Baseline/candidate abort to lifecycle-wake release
1 1,030ms 1,083ms +53ms 25/29ms 125/129ms
2, CPUs swapped 1,826ms 3,064ms +1,238ms 29/28ms 1,129/2,430ms

Every measured restart and subsequent recovery shutdown exited 0, without a deadline, binding failure, or surviving background child. The run registry cleared within 29ms after abort. The one-second target for every owner was not met: pair 2 retained a lifecycle-wake tail in both versions, longer on the candidate. Existing traces place that wait in session admission/received-work cleanup after the agent lanes aborted; they do not establish the cause of the variable tail. These results demonstrate shutdown within a few seconds, not a speedup or unconditional timing neutrality. CPU busy averages across the two halves were 8.46%/7.04% in pair 1 and 7.85%/7.86% in pair 2, retained as context only.

All four next boots reported started=2 settled=1 failed=0 skipped=0. The interrupted peer and streaming turns completed successfully. The lifecycle-wake owner settled as operator_authority_unavailable under the synthetic fixture's existing authority policy; a separate persisted synthetic-device pilot did not restore that authority. Parent-wake resumption remains a proof gap. Recovery records and policy are unchanged by this patch.

The compiled baseline was f2f019d60638d9813d2324e5126d7b1d2666fce5; the candidate was that source plus the exact three production-file changes in 32f3b5e3ff6b48a5f354f178b9b2d43212fe9e2c, verified by file hashes. The final rebase was patch-identical and brought only unrelated UI/memory/test changes. Final-head PR CI covers the rebased tree. Both sandbox builds passed; no Testbox lease or local build/suite ran.

The original 85-second incident was not reproduced or conclusively attributed. Its printed work inventory was captured before abort, while the pending reconciliation close step was current; the missing-binding warning alone does not prove run admission leaked. The deterministic integration regressions above prove the two repaired defects.

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XS labels Oct 19, 2026
@steipete
steipete marked this pull request as ready for review October 19, 2026 10:00
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T10:14:52.540440Z 32f3b5e New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…ement

Keep new request entry fenced while aborted in-process turns finish their pending-input and finalizer cleanup. Retire the instance after received execution has drained, preserving restart recovery ordering.
Carry the environment shutdown signal through provisioning recovery admission while retaining FIFO ordering and provider settlement. Prove shutdown releases a recovery queued behind session mutation, and cover SIGTERM with active a2a and lifecycle-wake turns.
@steipete
steipete force-pushed the steipete/perf-micro-aborted-runs-never-settle-sigkill-20260919 branch from e4931d8 to 32f3b5e Compare October 19, 2026 10:10
@steipete steipete changed the title fix(gateway): let interrupted agent turns settle before retiring their instance fix(gateway): settle interrupted turns and cancel queued shutdown recovery Oct 19, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. 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. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR retains Gateway bindings through interrupted-turn settlement and cancels provisioning recovery waiting for session admission.

Example: Gateway shutdown begins while recovery for environment-shutdown-queued-recovery waits behind a session mutation.

  • Before: Worker-environment shutdown waits until the unrelated mutation releases admission.
  • After: Queued recovery exits while the mutation remains held, preserving the provisioning record and allocation.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful, focused repairs with meaningful runtime evidence, blocked by a concrete destructive cancellation regression.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied real-model Linux Gateway runs exercise SIGTERM with active peer delivery, lifecycle-wake work, streaming, and child processes, reporting clean shutdown and peer/stream recovery; owner integrations provide causal binding-settlement and queued-admission evidence, while parent-wake resumption remains explicitly unproven.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Stopping or restarting a Gateway can interrupt pending-input settlement or hang behind provisioning recovery waiting for session admission.
Reason: The maintainer-authored direction repairs concrete lifecycle failures using existing owners without adding configuration or public APIs.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep this PR open: both shutdown repairs address current defects, but forwarding service shutdown cancellation into provider request cancellation introduces a blocking worker-destruction regression.

Priority: P1
Reviewed head: 32f3b5e3ff6b48a5f354f178b9b2d43212fe9e2c

Before merge

  • Keep shutdown cancellation out of provider destruction intent (P1) - When guarded provisioning recovery has already entered provider allocation or bootstrap, this argument carries the environment service's shutdown signal into session admission. Admission combines it into the signal passed through runRecovery to reconcileEnvironmentCore; provider-lifecycle then installs createWorkerProvisionCancellation on it. A normal beginClose therefore invokes that listener's store.requestDestroy, setting destroyRequestedAtMs on the recoverable environment. Recovery subsequently destroys the allocation instead of adopting it, contradicting the shutdown-preservation contract established by fix: Gateway shutdown hangs during recovered worker provisioning #176777. Separate admission-wait cancellation from explicit request cancellation and add a regression that shuts down after provider entry, reopens state, and preserves the same allocation.
  • Explain or restore the original intent of Shutdown interruption versus destruction intent - d01eb83: Service shutdown cancels attempts without requesting machine destruction; the newly forwarded service signal now reaches the explicit-cancellation destruction listener.

Findings

  • [P1] Keep shutdown cancellation out of provider destruction intent — src/gateway/worker-environments/placement-dispatch-coordinator.ts:554-555

Provenance

  • Shutdown interruption versus destruction intent changes intended behavior without addressing why it exists (d01eb83: Service shutdown cancels attempts without requesting machine destruction; the newly forwarded service signal now reaches the explicit-cancellation destruction listener.)

Tests

  • Missing end-to-end proof: The process E2E passes on both versions; supplied causal red/green evidence comes from the owner integration regressions.
Agent review details

How this fits together

Gateway shutdown fences request entry, cancels admitted execution, and joins cleanup; worker reconciliation enters the placement coordinator and session-admission owner before invoking provider recovery.

flowchart TD
  A[Gateway shutdown] --> B[Request entry fence]
  A --> C[Received execution drain]
  C --> D[Gateway binding retirement]
  A --> E[Worker reconciliation guard]
  E --> F[Placement coordinator]
  F --> G[Session admission]
  G --> H[Provider recovery]
Loading

Technical review

Best possible solution:

Keep the binding-lifetime repair and cancel queued admission without treating service shutdown as an explicit provider destruction request.

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

Source inspection establishes both original shutdown paths and the introduced cancellation-to-destruction chain; no target code was executed during this review.

Is this the best way to solve the issue?

The existing owners are appropriate and the binding repair is focused, but admission-wait cancellation must remain separate from provider request cancellation.

Full review comments:

  • [P1] Keep shutdown cancellation out of provider destruction intent — src/gateway/worker-environments/placement-dispatch-coordinator.ts:554-555
    When guarded provisioning recovery has already entered provider allocation or bootstrap, this argument carries the environment service's shutdown signal into session admission. Admission combines it into the signal passed through runRecovery to reconcileEnvironmentCore; provider-lifecycle then installs createWorkerProvisionCancellation on it. A normal beginClose therefore invokes that listener's store.requestDestroy, setting destroyRequestedAtMs on the recoverable environment. Recovery subsequently destroys the allocation instead of adopting it, contradicting the shutdown-preservation contract established by fix: Gateway shutdown hangs during recovered worker provisioning #176777. Separate admission-wait cancellation from explicit request cancellation and add a regression that shuts down after provider entry, reopens state, and preserves the same allocation.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 16f1ef80f9d5.

Provenance checked

  • Gateway binding retirement changes intended behavior with a stated reason (c5c090c: Recovery custody must be recorded before cancellation and retirement of retained principals; the PR preserves that ordering while extending binding availability through settlement.)
  • Per-session recovery ordering and provider custody keeps the original intent (fix(gateway): keep slow worker operations from blocking unrelated sessions #160299: Unrelated sessions must progress independently while same-session operations retain FIFO ordering and ownership through provider settlement.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/gateway/server-worker-placement-provision-cancellation.test.ts --maxWorkers=1
  • pnpm test src/gateway/worker-environments/provider-provisioning.shutdown-replay.test.ts src/gateway/worker-environments/placement-dispatch-coordinator-admission.test.ts src/gateway/worker-environments/placement-dispatch-coordinator-reclaim.test.ts --maxWorkers=1
  • pnpm test src/gateway/server.agent-execution-shutdown.test.ts --maxWorkers=1
  • Verify admitted provider recovery survives shutdown and next boot with the same allocation and no destruction intent.
  • git diff --check

What I checked:

  • Introduced production changes: The pinned introduction diff moves binding retirement after the received-work join and forwards the reconciliation service signal through coordinator and session admission; current main retains the original behavior. (src/gateway/server-lifecycle.ts:539, 32f3b5e3ff6b)
  • Shutdown becomes destructive request cancellation: The new admission argument joins the service shutdown signal into the signal passed to runRecovery and reconcileEnvironmentCore. Provider recovery installs createWorkerProvisionCancellation on that signal, whose abort listener persists requestDestroy. (src/gateway/worker-environments/placement-dispatch-coordinator.ts:555, 32f3b5e3ff6b)
  • Existing non-destructive shutdown contract: fix: Gateway shutdown hangs during recovered worker provisioning #176777 deliberately distinguishes owner shutdown from explicit request cancellation: shutdown interrupts provisioning while preserving durable allocations for replay. (src/gateway/worker-environments/provider-lifecycle.ts:446, d01eb83804ae)
  • Regression coverage stops before destructive branch: The added cancellation case verifies shutdown before provider entry. The process E2E seeds an environment without a provisioning placement, so it does not exercise the newly forwarded signal through admitted placement recovery. (src/gateway/server-worker-placement-provision-cancellation.test.ts:625, 32f3b5e3ff6b)
  • Supplied runtime observations: The full PR body reports isolated real-model Linux Gateway SIGTERM comparisons, clean exits, terminated descendants, and successful interrupted peer/stream recovery; it explicitly disclaims a speedup and successful parent-wake resumption. (32f3b5e3ff6b)
  • CI failure is PR-body validation: The failed PR context and evidence check reports missing authored sections, although the current body contains both sections; this is not a production-diff defect. PostgreSQL conformance remains in progress and the aggregate gate remains pending. (32f3b5e3ff6b)

Likely related people:

  • Peter Steinberger: Raw commit 755dad7 adds src/gateway/server-worker-placement-reconcile-guard.ts:23 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 755dad74d1fc; files: src/gateway/server-worker-placement-reconcile-guard.ts)

PR surface

Source +10, Tests +149, Docs +6. Total +165 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 37 27 +10
Tests 3 167 18 +149
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 210 45 +165

Labels

Label changes:

  • add P1: Shutdown reliability affects active Gateway workflows, and the introduced signal propagation can replace recoverable provisioning with durable destruction intent.
  • add merge-risk: 🚨 session-state: A normal shutdown can mark an in-progress worker allocation for destruction instead of preserving its provisioning state for restart.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P1: Shutdown reliability affects active Gateway workflows, and the introduced signal propagation can replace recoverable provisioning with durable destruction intent.
  • merge-risk: 🚨 session-state: A normal shutdown can mark an in-progress worker allocation for destruction instead of preserving its provisioning state for restart.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 19, 2026, 6:32 AM ET / 10:32 UTC.

@steipete
steipete merged commit 3825c6a into main Oct 19, 2026
178 of 181 checks passed
@steipete
steipete deleted the steipete/perf-micro-aborted-runs-never-settle-sigkill-20260919 branch October 19, 2026 10:37
steipete added a commit that referenced this pull request Oct 19, 2026
Align the shutdown fixture with #177223 (3825c6a), which keeps the
in-process Gateway binding until accepted execution and finalizers join.
Its contract states: "Keep that binding until received execution and
finalizers join; the existing entry fence continues rejecting new requests."

During Gateway stop or restart, the admitted Board read can return its
snapshot before worker retirement. Require the expected session, revision,
and status widget instead of an error from the formerly premature binding
retirement. Let unexpected request errors reject directly. Preserve the new
request refusal, held-read join, open database, and final database-close
assertions.

The original fixture reproduces the hourly failure on main 55bc065.
The complete repaired file passes under pinned Bun with maxWorkers=1.
Gateway-server test types, type-aware core lint, formatting, whitespace,
and independent P2 autoreview pass. No production behavior or timeout changes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
…overy (openclaw#177223)

* fix(gateway): preserve instance binding through interrupted run settlement

Keep new request entry fenced while aborted in-process turns finish their pending-input and finalizer cleanup. Retire the instance after received execution has drained, preserving restart recovery ordering.

* fix(gateway): cancel queued worker recovery during shutdown

Carry the environment shutdown signal through provisioning recovery admission while retaining FIFO ordering and provider settlement. Prove shutdown releases a recovery queued behind session mutation, and cover SIGTERM with active a2a and lifecycle-wake turns.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
Align the shutdown fixture with openclaw#177223 (deb7430), which keeps the
in-process Gateway binding until accepted execution and finalizers join.
Its contract states: "Keep that binding until received execution and
finalizers join; the existing entry fence continues rejecting new requests."

During Gateway stop or restart, the admitted Board read can return its
snapshot before worker retirement. Require the expected session, revision,
and status widget instead of an error from the formerly premature binding
retirement. Let unexpected request errors reject directly. Preserve the new
request refusal, held-read join, open database, and final database-close
assertions.

The original fixture reproduces the hourly failure on main b53d602.
The complete repaired file passes under pinned Bun with maxWorkers=1.
Gateway-server test types, type-aware core lint, formatting, whitespace,
and independent P2 autoreview pass. No production behavior or timeout changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant