Skip to content

fix(gateway): interrupt worker teardown during shutdown - #183579

Merged
steipete merged 2 commits into
mainfrom
perf/l1749-shutdown-reconcile
Oct 25, 2026
Merged

steipete merged 2 commits into
mainfrom
perf/l1749-shutdown-reconcile

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes Gateway shutdown waiting minutes for a worker-environment teardown during reconciliation, until the service supervisor kills the process.

User Impact

Shutdown can interrupt Crabbox capture, stop, and checkpoint cleanup, retain their durable recovery state, and retry the same cleanup after restart. Pending replies, terminal persistence, and actual child-process settlement keep their existing drain obligations. There is no schema, configuration, or retention change.

Why This Change Was Made

The observed pending operation was provider destroy, not inspection. Production traces showed it still pending after 219 seconds; another timeout had no active turns or pending owners. Both the earlier inspection cancellation fix (#180841) and cleanup-acceptance change (#182138) were already in the affected build. Crabbox's bounded stop budget is 16 minutes 45 seconds, but reconciliation dropped cancellation before reaching it.

The teardown owner now supplies Gateway lifecycle cancellation for normal, failed-bootstrap, and expired-preparation cleanup, and Crabbox forwards it through its command chain. Explicit turn cancellation still runs compensating cleanup; it does not cancel teardown. The existing provider deadline also aborts destroy. The owner still joins the underlying mutation; a timeout or cancellation does not falsely declare physical teardown complete. The additive optional destroy.signal provider contract documents that requirement.

Evidence

  • Core shutdown and provider-timeout regressions fail on unchanged main because destroy receives no cancellation signal. Candidate tests verify interruption, retained identity, reopening the store, and cleanup retry after restart; failed-bootstrap cleanup preserves the original failure.
  • Crabbox real-child regressions cover capture, stop, and post-stop checkpoint deletion. Interrupted deletion retains retirement debt, and normal provider maintenance clears it later. All 46 tests in the three focused plugin files pass.
  • Existing preserve-only drain and real Gateway-close persistence tests pass. Focused reconciliation/allocation proof: 32/32; provisioning, node provisioning, explicit-cancellation, and lifecycle siblings also exercised. Targeted core typecheck, changed-file lint/format, export collision guard, and 22 closure tests pass. PR CI supplies broad validation.
  • Independent subagent review (autoreview route unavailable): addressed cancellation gaps in bootstrap-failure cleanup and post-stop checkpoint retirement; final review clean.

Acceptance declared before the process/load measurements: the real isolated dist Gateway must interrupt a hanging fixture destroy and exit cleanly within a 20-second budget, retain the exact lease, and complete cleanup after restart. Base must reproduce the blocked shutdown. Required Team-shaped load comparison uses the canonical harness, 10-minute arms, two counterbalanced timing and allocation pairs. Report server-side latency and host load, and obtain A/A controls before treating an adverse load metric as a regression.

Runtime code delta: +32 net lines for lifecycle cancellation, the existing deadline abort, and the additive provider contract. No second lifecycle owner or state store was introduced. The separate 340-line script is reproducible process proof.

Real dist-Gateway reproduction passed on base 9db139fcf842 versus candidate 5c33ee10cc36: baseline remained blocked at the 20,002.5 ms harness deadline and required SIGKILL; candidate aborted provider teardown and exited cleanly in 801.7 ms. Candidate retained the exact lease and operation ID with a visible interruption, and the next boot completed cleanup. Clean shutdown after replay was 640.7 ms on base and 591.0 ms on candidate. This is isolated synthetic process evidence, not a live deployment timing claim.

Both full builds passed; all 281 shared compiled package files are byte-identical between builds. The initial stress attempt failed during setup because the instrumentation loader disabled source aliases but could not resolve two worker-telemetry workspace dependencies. The loader now resolves those dependencies through the measured build’s compiled exports while leaving built-runtime imports untouched. Its real-child regression fails on the original loader; all six focused harness tests and a native-subagent smoke pass, with independent review clean. No performance verdict is drawn from failed setup or smoke runs. The full canonical stress campaign below completed successfully on the same final head.

Completed load acceptance

Canonical harness from this tooling head: two AB/BA pairs for untraced timing and two separate AB/BA allocation pairs, eight fresh 10-minute measurement windows plus warmup. Each arm used 10,800 synthetic sessions, 40 enabled bundled plugins, 65 WebSocket clients, four concurrent mock-provider turns per round, real tool calls/native subagents, and list/search/history/sidebar churn. All eight arms passed workload coverage and error checks; each completed 40 reported parent turns and matching tool results. Only isolated loopback development Gateways were exercised.

Mean across the two matched pairs (percentage column is the mean of the two paired percentage deltas):

Metric Base Candidate Absolute delta Paired relative delta
Main-thread CPU % 7.449 7.826 +0.377 +5.13%
Allocation MiB/s 27.719 28.100 +0.381 +1.38%
GC s/min 0.143 0.157 +0.014 +9.68%
Loop p99 ms 30.859 31.597 +0.737 +2.46%
Client list p99 ms 41.937 45.394 +3.456 +8.21%
Handler mean ms 11.138 11.988 +0.850 +7.69%
Handler p99 estimate ms 35.394 38.691 +3.297 +9.31%
RSS MiB 2649.176 2637.296 -11.880 -0.45%
Main heap MiB 653.174 700.080 +46.907 +7.19%

These steady-state differences do not cross the predeclared adverse gates. Total untraced GC rose by 14 ms/min, below the 50 ms/min materiality floor; no maximum GC pause exceeded 50 ms or twice its paired baseline. This is a shutdown/recovery improvement, not a steady-state throughput claim. No A/A rejection investigation was triggered; the small differences are not attributed causally to this patch.

Per-arm measurements, sample counts, and host load
Arm CPU % Alloc MiB/s GC s/min Loop p99 ms (n) Client list p99 ms (n) Handler mean / p99 est ms (n) RSS / heap MiB Host load 1m mean [min,max] (n)
timing-1-base 7.63 n/a 0.1464 31.52 (27988) 42.14 (1204) 11.26 / 35.45 (1173) 2646.89 / 649.73 11.90 [9.45,15.40] (20)
timing-1-candidate 7.83 n/a 0.1658 31.21 (28032) 48.01 (1202) 11.59 / 39.54 (1173) 2695.77 / 707.69 12.81 [9.14,17.99] (20)
timing-2-candidate 7.82 n/a 0.1477 31.98 (27907) 42.78 (1202) 12.39 / 37.84 (1173) 2578.82 / 692.47 15.76 [9.29,20.91] (20)
timing-2-base 7.27 n/a 0.1393 30.20 (27874) 41.73 (1202) 11.01 / 35.34 (1173) 2651.47 / 656.61 10.08 [4.30,20.36] (20)
allocation-1-base 8.92 27.63 0.2819 33.62 (27713) 60.20 (1202) 12.53 / 44.09 (1173) 2706.90 / 653.45 16.01 [4.93,56.33] (20)
allocation-1-candidate 8.33 28.24 0.2612 33.06 (27573) 56.32 (1202) 12.60 / 47.27 (1173) 2714.02 / 651.41 13.29 [6.17,31.61] (20)
allocation-2-candidate 8.30 27.96 0.2612 32.11 (27701) 43.97 (1202) 12.09 / 37.95 (1173) 2731.41 / 652.12 9.52 [6.56,14.55] (20)
allocation-2-base 8.17 27.81 0.2500 31.77 (27800) 39.51 (1202) 11.52 / 32.97 (1173) 2656.98 / 653.76 10.69 [6.94,15.46] (21)

CPU is main OS-thread CPU (100% = one core); allocation is sampled JS allocation, excluding native/external memory. RSS is process-wide and heap is the end-of-window main isolate, not a retained-heap claim. Allocation-pass timing/GC are diagnostic only. Each host-load window has 20–21 samples on a 32-logical-CPU Mac; no window was excluded after observing results. Achieved list/RPC rates and full workload completion were checked, rather than assuming offered load equals completed work.

Handler values use first-to-last scrape counter deltas, excluding warmup and omitting up to the final 15 seconds. Handler p99 is a histogram bucket estimate, not exact client latency. Each timing handler p99 falls in the 30–40 ms bucket and has 1,173 observations; client list tails have 1,202–1,204 samples and loop tails approximately 28,000. Major-GC per-collection percentiles are context only because each timing arm has fewer than 50 collections.

Untraced GC detail (total duration, not normalized by collection count):

Arm Kind Collections Total ms p95 ms p99 ms Max ms
timing-1-base minor 598 937.60 2.15 3.72 9.20
timing-1-base incremental 21 16.93 0.97 0.98 0.98
timing-1-base major 21 510.05 38.21 38.24 38.24
timing-1-candidate minor 694 1008.06 2.23 3.10 4.63
timing-1-candidate incremental 25 20.35 1.05 1.17 1.17
timing-1-candidate major 25 632.74 45.41 46.02 46.01
timing-2-candidate minor 595 966.04 2.28 4.04 6.32
timing-2-candidate incremental 20 16.48 1.03 1.04 1.04
timing-2-candidate major 20 497.44 37.38 42.98 42.96
timing-2-base minor 597 915.54 2.40 3.52 4.77
timing-2-base incremental 20 15.60 1.00 1.03 1.03
timing-2-base major 20 462.01 34.91 42.56 42.54

GC percentiles are histogram estimates; maxima are recorded raw durations. GC p99s below 1,000 collections, p95s below 200, and major-GC tails below 50 collections are context rather than gates. All original windows are included.

Final validation

Exact head 5c33ee10cc3674437aaa4762930b811f897ce15c: CI passed, build passed, no reruns. Independent local review, GitHub Codex review, and ClawSweeper identified no remaining actionable findings. ClawSweeper's previously unfinished load-evidence item is completed above.

Remaining limits: the historical trace identifies provider destroy, not which individual Crabbox child command was pending. Tests cover all three command boundaries. Third-party providers must honor the optional signal; the owner intentionally keeps waiting for actual mutation settlement rather than falsely releasing a live write. No production restart or live deployment timing is claimed.

@clawsweeper

clawsweeper Bot commented Oct 25, 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 scripts Repository scripts extensions: crabbox size: L labels Oct 25, 2026
@steipete
steipete marked this pull request as ready for review October 25, 2026 12:06
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T12:33:05.716665Z 5c33ee1 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.

@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 25, 2026
@steipete
steipete force-pushed the perf/l1749-shutdown-reconcile branch from 68a76c6 to 5c33ee1 Compare October 25, 2026 12:30
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Passes shutdown, suspension, and deadline cancellation through worker teardown and Crabbox commands while preserving cleanup recovery.

Example: Gateway receives SIGTERM while provider destroy is hanging.

  • Before: The reported baseline exceeded the 20-second shutdown budget and required SIGKILL.
  • After: The reported candidate exited cleanly, retained the lease and operation identity, and completed cleanup after restart.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, focused repair with no actionable findings; proof confidence is limited by reported rather than linked process output and unfinished load acceptance.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its body reports a built-Gateway SIGTERM and restart comparison supported by the committed fixture, while raw output is unlinked and load acceptance remains pending.
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 shutdown waits minutes for worker cleanup and can end in supervisor termination.
Reason: The maintainer-authored repair addresses an evidenced lifecycle failure while preserving durable cleanup and child-settlement obligations.

Merge readiness

✅ Ready for maintainer review

Keep open: current main still has the teardown cancellation gap, and this PR repairs it through the existing lifecycle owner. No actionable introduced defect was found.

Priority: P1
Reviewed head: 5c33ee10cc3674437aaa4762930b811f897ce15c

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The declared Team-shaped load comparison remains unfinished in the supplied evidence.
Agent review details

How this fits together

The worker-environment service serializes provider operations and persists cleanup intent; Crabbox translates teardown into capture, stop, and checkpoint cleanup commands.

flowchart TD
 A[Gateway shutdown or suspension] --> B[Environment lifecycle owner]
 B --> C[Serialized provider destroy]
 C --> D[Crabbox command chain]
 D --> E[Child process settlement]
 E --> F[Durable cleanup outcome]
 F --> G[Startup reconciliation]
Loading

Technical review

Best possible solution:

Keep teardown cancellation in the existing lifecycle owner, retain unconfirmed cleanup for restart, and honor the author’s landing hold.

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

Current-main source exposes the missing signal, and the committed process fixture targets that exact path; the PR reports a failing baseline and successful candidate, but no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch repairs the shared teardown owner and its Crabbox consumer, preserves compensating cleanup and mutation settlement, and introduces no competing lifecycle or storage owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Provider teardown budgets and serialized ownership keeps the original intent (c753bbd: Provide bounded teardown budgets while retaining queue ownership checks, explicit overrides, and process settlement.)
  • Maintenance interruption keeps the original intent (5cedb0d: Cancel reconciliation observations without converting maintenance interruption into user-requested destruction.)
  • Cleanup acceptance and confirmation keeps the original intent (a23ba6f: Allow reclaim after accepted cleanup while retaining ownership until physical release is confirmed.)
  • Stress instrumentation loader keeps the original intent (ed32fdc: Measure isolated built Gateways without redirecting their runtime imports through controller source aliases.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +32, Tests +253, Docs +8, Other +364. Total +657 across 17 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 44 12 +32
Tests 8 261 8 +253
Docs 2 9 1 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 2 364 0 +364
Total 17 678 21 +657

Review metrics

Metric Value Why it matters
Production versus test changes Runtime +44/-12; tests +261/-8 Runtime growth carries cancellation through existing owners; tests protect distinct interruption, settlement, and restart boundaries.

Labels

Label changes:

  • add P1: The reported production shutdown stalls until supervisor termination, and current-main source retains the uncancellable destroy path.
  • add merge-risk: 🚨 compatibility: Adds an optional provider API parameter and interruption behavior; the maintainer-authored contract explicitly preserves settlement for providers that ignore cancellation.
  • 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 reported production shutdown stalls until supervisor termination, and current-main source retains the uncancellable destroy path.
  • merge-risk: 🚨 compatibility: Adds an optional provider API parameter and interruption behavior; the maintainer-authored contract explicitly preserves settlement for providers that ignore cancellation.
  • 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.

Rank-up moves

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

  • Complete the declared load comparison and resolve the author’s explicit landing hold.

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 25, 2026, 8:54 AM ET / 12:54 UTC.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
)

* fix(gateway): interrupt worker teardown during shutdown

* fix(perf): resolve worker telemetry from measured build
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 extensions: crabbox gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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