Skip to content

fix(gateway): settle pre-existing work during shutdown - #177756

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-shutdown-preexisting-reconcile-and-admissions-20260919
Oct 19, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-shutdown-preexisting-reconcile-and-admissions-20260919

Conversation

@steipete

@steipete steipete commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes shutdown stalls when worker reconciliation was already waiting on device inspection before restart, or a completed agent runtime disposal coincides with a failed final response.

User Impact

Restarts stop waiting on abandoned device observations and bound native computer cleanup by the existing worker shutdown deadline. Suspension pauses periodic reconciliation and releasing it resumes the next sweep. No configuration, schema, or protocol changes are required; unfinished producer/write cleanup remains joined.

Why This Change Was Made

Reconciliation already avoided new work after shutdown, but suspension still admitted sweeps and existing device pairing/presence reads ignored cancellation. Environment and placement maintenance have independent periodic sweeps; startup and session-identity replacement also request reconciliation. The incident shows overlap with drain, not proof that drain directly started the stalled pass. Inspection now receives the restart-drain signal, and the device provider stops awaiting those read-only operations. Native computer close requests share the node tunnel's existing five-second cleanup signal, including requests started before shutdown.

The session-admission wait also joins source cleanup. If final publication and completed runtime disposal both throw, await using wraps the disposal receipt in SuppressedError; the previous outer handler missed it and retained the source indefinitely. Record that receipt inside the disposer and remove the superseded outer interpretation. Execution must still have settled, and genuinely unfinished cleanup retains custody. Pending diagnostics distinguish source cleanup from effect admission and report live source/operation/work counts.

Evidence

  • Negative controls on the baseline reproduced both stalled device reads, reconciliation during suspension, missing restart-drain cancellation, native computer cleanup on private/shared hosts, and the wrapped completed-disposal receipt leak.
  • The source-ownership regression closes a real native database exactly once and checks both original errors; the source then releases. Aggregate shutdown coverage uses five active controller sources, a queued reply and a standalone background effect, while proving unfinished source cleanup remains retained.
  • Focused tests: 204 passing across device-provider.test.ts, computer-transport.test.ts, server-worker-placement-startup-cleanup.test.ts, agent-run-execution-phase.owner.test.ts, server-close.test.ts, restart-trace.test.ts, and server-worker-placement-provision-cancellation.test.ts, using node scripts/run-vitest.mjs <files> --maxWorkers=1. Initial provider assertions expected an unwrapped abort reason; corrected to the shared helper’s AbortError/cause contract, then the provider file passed 11/11. Changed-file formatting and core/script lint passed; pnpm tsgo:core (tsrs) passed. Broad gates delegated to PR CI; no Testbox allocation.
  • Independent Codex review of the simplified production diff and the focused CI repair: no actionable P0–P2 findings.
  • Initial CI found an older provisioning-recovery test expecting GatewayDrainingError after shutdown. Reproduced locally (30 pass, 1 fail), updated it to expect reconciliation to skip before session admission while retaining every lease/placement and no-provider-call assertion, then reran the whole file: 31/31 passed.

Paired sandbox measurement

A real environment service, placement sidecar, SQLite owner and device provider wait on a real loopback HTTP-backed device pairing read delayed by 85 seconds. Synthetic node acknowledgments and separate state/ports are used. Both variants run concurrently under the exclusive measurement lock on two 16-core CPU halves, swapped for the second pair. Baseline: 08e32fdb4df002c9d4eea158b855d6521dd1e916.

Pair Before After Paired difference (after − before)
1 85,010.214 ms 9.248 ms −85,000.965 ms
2, CPU halves swapped 85,010.332 ms 8.900 ms −85,001.432 ms

Shutdown starts differed by 3 ms and 2 ms within the pairs; observed CPU utilization was 2.89% and 4.92%. Median duration: 85,010.273 ms before, 9.074 ms after. The measured candidate predates a behavior-preserving signal variable rename and parameter-type consolidation; subsequent source-cleanup edits are outside this measured path.

Both variants retain placement rows/manifests and produce a clean-close receipt. The candidate closes while the delayed read remains pending; the baseline waits for it. This measures the owning shutdown boundary, not a whole-Gateway restart or real model/remote worker processes.

Runtime source delta is +80 lines; tests/support +275; measurement script +92; docs +10. Growth supplies missing cancellation wiring and live retained-custody diagnostics; the duplicate outer receipt handler is deleted. There is no new cache, manager, configuration, or alternate shutdown path.

Incident attribution remains limited: effect admission handles released promptly after abort, and the reported six-admission count was a stale pre-abort snapshot. The exact retained production source is unproven. The next production restart remains the end-to-end confirmation; no production deployment/restart was performed. The background-effect regression does not launch an OS process.

@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.

@steipete
steipete marked this pull request as ready for review October 19, 2026 21:41
@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-19T22:03:05.953107Z 5d15b8d 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts size: L labels 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. labels Oct 19, 2026
Cancel in-flight device observations at restart drain, pause reconciliation during suspension, and bound native computer cleanup with the worker shutdown deadline. Capture completed disposal before final publication errors wrap its receipt; preserve unfinished source cleanup and report live custody counts.
@steipete
steipete force-pushed the steipete/perf-micro-shutdown-preexisting-reconcile-and-admissions-20260919 branch from e59a899 to 5d15b8d Compare October 19, 2026 21:57
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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 maintainer review before merge.

What this changes

This PR cancels stalled device observations during drain, pauses reconciliation during suspension, bounds native computer cleanup, and correctly acknowledges completed runtime disposal.

Example: Restart begins while device reconciliation awaits an 85-second pairing read.

  • Before: The supplied boundary measurement waits about 85 seconds for shutdown.
  • After: The supplied candidate measurement settles shutdown in about 9 milliseconds while preserving placement records.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A useful, focused repair with no actionable finding and supporting production-owner boundary evidence.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its supplied loopback-HTTP measurements exercise real reconciliation owners, while computer-close and combined-disposal coverage remains test-based and whole-Gateway confirmation is explicitly unclaimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Gateway restarts can stall on device observations or retain a completed agent source after simultaneous publication and disposal callback errors.
Reason: The maintainer-authored direction repairs defined shutdown contracts and preserves durable cleanup ownership without new configuration or public APIs.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses shutdown failures still present on current main, and review found no actionable introduced defect.

Priority: P1
Reviewed head: 5d15b8de50e81f3f5867623802b209cfe0973882

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Supplied evidence does not exercise the combined publication/disposal failure or native computer deadline through a shipped Gateway; baseline-negative results are reported rather than rerun here.
Agent review details

How this fits together

Gateway shutdown coordinates session sources, worker reconciliation, and node transports; it must stop optional observations while joining accepted writes and unfinished resource cleanup.

flowchart TD
  A[Gateway suspension or restart] --> B[Work admission and drain signals]
  B --> C[Worker reconciliation]
  C --> D[Device pairing and presence reads]
  B --> E[Node cleanup deadline]
  E --> F[Native computer close]
  A --> G[Session source settlement]
  G --> H[Runtime disposal receipt]
Loading

Technical review

Best possible solution:

Keep cancellation and cleanup acknowledgement in the existing lifecycle owners while preserving accepted-write settlement and unfinished-resource custody.

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

Base source exposes both uncancelable device waits and the outer-only disposal-receipt check; supplied regressions and paired measurements support those paths, but this read-only review executed no target code.

Is this the best way to solve the issue?

The invariant is that observations may cancel while accepted writes and unfinished cleanup remain owned; the patch uses existing signals, disposal receipts, and shutdown instrumentation without adding a competing lifecycle owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 593176c adds src/gateway/server-worker-placement-startup.ts:111 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 593176caf551; files: src/gateway/server-worker-placement-startup.ts)
  • Vincent Koc: Raw commit c7bab50 adds src/gateway/worker-environments/dedicated-node-lease-attestations.ts:24 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: c7bab50e6ed7; files: src/gateway/worker-environments/dedicated-node-lease-attestations.ts)

PR surface

Source +80, Tests +275, Docs +10, Other +92. Total +457 across 20 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 10 123 43 +80
Tests 8 302 27 +275
Docs 1 12 2 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 1 109 17 +92
Total 20 546 89 +457

Review metrics

Metric Value Why it matters
Production versus regression coverage Runtime production +123/-43; tests/support +302/-27 Growth supplies missing cancellation wiring and live custody diagnostics, with distinct cancellation, suspension, combined-error, and unfinished-cleanup regressions.

Labels

Label changes:

  • add P1: The addressed failures can hold Gateway restart or shutdown on already-finished work or stalled observations, extending runtime unavailability.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P1: The addressed failures can hold Gateway restart or shutdown on already-finished work or stalled observations, extending runtime unavailability.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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:14 PM ET / 22:14 UTC.

@steipete
steipete merged commit bf105d1 into main Oct 19, 2026
158 of 160 checks passed
@steipete
steipete deleted the steipete/perf-micro-shutdown-preexisting-reconcile-and-admissions-20260919 branch October 19, 2026 22:46
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
* fix(gateway): settle pre-existing work during shutdown

Cancel in-flight device observations at restart drain, pause reconciliation during suspension, and bound native computer cleanup with the worker shutdown deadline. Capture completed disposal before final publication errors wrap its receipt; preserve unfinished source cleanup and report live custody counts.

* test(gateway): expect recovery to pause during shutdown
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 P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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.

1 participant