Skip to content

fix(gateway): avoid stuck shutdowns after lifecycle errors - #145241

Merged
vincentkoc merged 4 commits into
openclaw:mainfrom
metahacker:fix/gateway-shutdown-deadline-completion-20260911
Sep 21, 2026
Merged

vincentkoc merged 4 commits into
openclaw:mainfrom
metahacker:fix/gateway-shutdown-deadline-completion-20260911

Conversation

@metahacker

@metahacker metahacker commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Related: #132616
Companion library repair: openclaw/fs-safe#254 (merged)

What Problem This Solves

A Gateway can close its listener but remain alive after retirement, log flushing, or an exit listener throws. Cancelling the shutdown deadline in finally leaves the supervisor unable to replace the non-listening process.

User Impact

Keep the existing main-thread deadline and hard-exit watchdog armed until lifecycle completion succeeds. Retire a settled restart's upgrade callback without cancelling its original deadline, so a later managed-update signal cannot accidentally remove the remaining exit fallback.

Successful restart, hosted-stop, ordinary-stop, managed-update, restoration, drain, and authority contracts retain their existing owners and budgets. There are no new flags, timeout values, dependency changes, configuration defaults, or persistence/migration surfaces.

Current Integration and Review

Preserves the original contributor commits and integrates main bb9564112c40. The published, SSH-signed head is d03fdc2525e0, tree e1ff425fc60a. It is source-tree-identical to reviewed and packaged candidate 84f1e7d5eed1; only signatures and corresponding first-parent commit IDs changed. Production delta is 31 added / 33 removed lines. The extracted test helper keeps the existing test file within its line budget.

Independent CLI review of the repaired completion paths is scoped-clean with no P0–P2 findings. Its late-managed-update finding was reproduced and repaired before the final review. Existing ordinary-stop fixes and the already-landed companion library repair are retained, not credited as new changes here.

Evidence

  • Original SIGUSR2 exit-handler/log-flush controls and the late-managed-update regression fail before their respective repairs and pass after them.

  • 212 tests across the run-loop, forced-cron process, and independent hard-exit process suites passed with --maxWorkers=1: 113.85 seconds wall. The new focused regression measured 82 ms. Final tree differs from that tested tree only by removing an unused test import; executable production and test behavior are unchanged.

  • Final scoped lint, formatting, line-cap and changed-diff checks passed. The local broad static run passed production typechecking but was interrupted during test-type shards by the Gateway restart; its exit is unavailable and is not claimed passing. Hosted exact-head CI subsequently passed, including required static lanes; this does not retroactively establish the interrupted local exit. Both required CI/security contexts are successful.

  • Exact candidate package built successfully in secretless Docker. Package SHA-256: 341ad1522c7552ecc479b29f6df43fe11bd9460c9701d7524ab2cd73cdecec76. Candidate and plugin registry both identify 84f1e7d5eed1.

  • Final normal upgrade/restart passed at 2026-09-21T07:25:25Z: published 2026.9.4 updater to unchanged candidate, then candidate-to-future auto-auth managed restart, 438 seconds lane / 441.25 seconds launcher, exit 0. The fresh data-only worktree and Docker-inspected artifact mount had no previous lane artifacts. Exact candidate package above, plus independently reviewed companion fixture #154560, patch SHA-256 33031d902bbc0fad7699a3fba34e75d2e877b52415a858f820566ce565a0bc1a. Automatic supervisor replacement (5406 to 10728), serving agent turn, migration, plugin resolution/cleanup, Doctor, health/readiness/status all passed. No product PID/boot guard or assertion was weakened.

  • The earlier uncorrected normal lane failed after 384 seconds: its inherited synthetic manager exposed supervisor PID 5374 as MainPID instead of actual Gateway child 5388. Production correctly rejected the mismatch before this PR's modified completion path; recovery was healthy. Both original fixture files and the drain helper match base bb9564112c40. That failed receipt remains retained. Companion fix: report the actual gateway PID in upgrade survival tests #154560 corrects the fixture producer/projections and was applied only to the isolated trusted harness for the final passing run; it is not a source change in this PR.

  • Final legacy-operator-state upgrade passed on the unchanged package at 2026-09-21T06:32:54Z: 243 seconds lane / 246.59 seconds launcher, exit 0. Automatic supervisor replacement, migrations, Gateway probes, a real candidate agent turn, cron owners, plugins, update idempotence, clean Doctor and backup rollback passed. Earlier c97062fb normal/legacy passes and the intermediate corrected-fixture pass are historical, not the final reviewed-fixture receipt.

  • Hosted CI attempt 1 at exact published head failed one unchanged cron process-group timeout fixture after 120 seconds (job); the rest of that cron shard passed 939 tests. The identical selected test passed on the exact head in 78 ms with its original timeout and no source change. Existing issue Investigate cron shell process-group timeout test stall in CI #139983 and recent perf(gateway): reduce session projection allocation churn #154415 evidence record this timing-sensitive fixture; the isolated pass does not prove a fix or identify the stalled await. The original-job-order reproduction passed on attempt 2 without a code change: job 106240960764 completed successfully at 2026-09-21T07:22:34Z, and the exact-head CI workflow is successful. This is passing validation, not proof of an underlying fixture fix. No timeout, assertion, production, or baseline was weakened.

Update Behavior

This changes candidate Gateway completion, not the installed updater. Proof uses the published [email protected] updater, the exact candidate package, normal and legacy operator-state scenarios, and the maintained synthetic systemd fixture. No operator state or credentials are copied into the containers. This is not native-systemd certification, a production deployment, or Night Watch acceptance.

@clawsweeper

clawsweeper Bot commented Sep 11, 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 cli CLI command changes size: S labels Sep 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 11, 2026
@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 21, 2026, 3:07 AM ET / 07:07 UTC (Revision 4).

ClawSweeper review

What this changes

Keeps Gateway shutdown deadlines armed through lifecycle completion failures, clears settled restart callbacks, and adds signal-driven regression coverage.

Merge readiness

✅ Ready for maintainer review

This remains a useful, focused fix: current main still cancels restart deadlines when lifecycle completion throws. No actionable introduced defect was found, and the recorded package and upgrade evidence supports the change.

Priority: P2
Reviewed head: d03fdc2525e0d28752b1064250fcc57ffcf2ee3a

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level repair with meaningful regressions and recorded package recovery evidence, with validation limits clearly disclosed.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Recorded final-package execution exercises Gateway lifecycle completion through published-updater installation and legacy-state supervisor replacement, followed by healthy probes and a real agent turn. Error-path regressions supplement that evidence; the separate normal-cell fixture failure remains a disclosed limitation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded final-package execution exercises Gateway lifecycle completion through published-updater installation and legacy-state supervisor replacement, followed by healthy probes and a real agent turn. Error-path regressions supplement that evidence; the separate normal-cell fixture failure remains a disclosed limitation.
Evidence reviewed 7 items Introduced production change: The pinned delta moves deadline cancellation after successful completion while independently clearing the settled restart callback. Existing budgets, handoff checks, and persistence contracts are unchanged.
Still necessary on current main: Current main retains unconditional deadline cancellation in the restart completion finally block. Its run-loop file is unchanged from the pinned PR base. The adjacent merged native-drain repair addresses timeout budgets and exit status, not this completion-error path.
Meaningful regression coverage: The extracted helper retains existing shutdown cases and adds four signal/error combinations plus a late managed-update case. Assertions cover eventual exit, retained watchdogs, cancellation of the late handoff, and absence of runtime reuse. These use the existing run-loop signal fixture and fake timers.
Findings None None.
Security None None.

How this fits together

The Gateway run loop handles stop and restart requests, drains work, and hands control back to the process supervisor. Its shutdown timers provide a final exit path when cleanup fails.

flowchart TD
  A[Stop or restart request] --> B[Gateway run loop]
  B --> C[Drain work and close listener]
  C --> D[Complete lifecycle cleanup]
  D --> E{Completion succeeds?}
  E -->|Yes| F[Cancel shutdown deadlines]
  E -->|No| G[Retain timed exit fallback]
  G --> H[Supervisor can recover]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -2, Tests +146. Total +144 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 31 33 -2
Tests 2 320 174 +146
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 351 207 +144

Review metrics

None.

Technical review

Best possible solution:

Keep one shutdown deadline owner active until lifecycle completion succeeds, preserving existing supervisor recovery and managed-update ownership checks.

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

Yes, from source: a rejected restart completion reaches current main's unconditional deadline cancellation after listener closure. The supplied regressions exercise that path; this read-only review did not execute tests.

Is this the best way to solve the issue?

Yes. Moving cancellation to successful completion and independently retiring the restart callback fixes the existing owner without new settings, budgets, or competing lifecycle machinery.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This repairs a bounded lifecycle-error path that can leave a non-listening Gateway process alive.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded final-package execution exercises Gateway lifecycle completion through published-updater installation and legacy-state supervisor replacement, followed by healthy probes and a real agent turn. Error-path regressions supplement that evidence; the separate normal-cell fixture failure remains a disclosed limitation.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded final-package execution exercises Gateway lifecycle completion through published-updater installation and legacy-state supervisor replacement, followed by healthy probes and a real agent turn. Error-path regressions supplement that evidence; the separate normal-cell fixture failure remains a disclosed limitation.

Evidence

What I checked:

  • Introduced production change: The pinned delta moves deadline cancellation after successful completion while independently clearing the settled restart callback. Existing budgets, handoff checks, and persistence contracts are unchanged. (src/cli/gateway-cli/run-loop.ts:943, d03fdc2525e0)
  • Still necessary on current main: Current main retains unconditional deadline cancellation in the restart completion finally block. Its run-loop file is unchanged from the pinned PR base. The adjacent merged native-drain repair addresses timeout budgets and exit status, not this completion-error path. (src/cli/gateway-cli/run-loop.ts:920, 585312d8ba73)
  • Meaningful regression coverage: The extracted helper retains existing shutdown cases and adds four signal/error combinations plus a late managed-update case. Assertions cover eventual exit, retained watchdogs, cancellation of the late handoff, and absence of runtime reuse. These use the existing run-loop signal fixture and fake timers. (src/cli/gateway-cli/run-loop-shutdown-completion.test-support.ts:219, d03fdc2525e0)
  • Recorded real package and upgrade evidence: The supplied body at sourceRevision 055d9410426298ee0b6f4d0d309e9e0fd1cea66e67da95ba6e97bd569f5fac23 records a published 2026.9.4 updater installing the candidate and a final legacy-state cell completing automatic supervisor replacement, Gateway probes, a real agent turn, and rollback at 2026-09-21T06:32:54Z. The candidate package is reported tree-identical to this head; local inspection confirmed the head tree e1ff425fc60acd4b052486f089b095ea6501a754. The 212 focused tests are supplemental evidence, not a live fault-injection claim. (d03fdc2525e0)
  • Disclosed fixture failure remains separate: The normal upgrade cell's later maintenance-drain failure is explicitly reported as failed. Both synthetic systemd fixture files have zero introduced diff; their MainPID projections match the described fixture boundary. The successful legacy cell does not turn that normal cell into a pass. The unchanged cron timeout also remains documented without claiming an isolated replay fixed it. (scripts/e2e/lib/upgrade-survivor/systemd-fixture.mjs:332, d03fdc2525e0)
  • Lifecycle history and routing: Current-main history identifies recent shutdown-budget, foreground-update, and restart-cleanup work, including 54abbae. This supports area routing, not attribution of the original defect. Older blame and release-blob inspection encountered unavailable objects, so no introducing author or shipped fix is asserted. (src/cli/gateway-cli/run-loop.ts, 54abbae585bc)

Likely related people:

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

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 (3 earlier review cycles)
  • reviewed 2026-09-11T20:27:53.662Z sha 352cf903eab8080fc0d2dbd208fa6d452ad1d646 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-14T18:50:21.600Z sha ee97b88 :: blocked before merge. :: none
  • reviewed 2026-09-21T06:38:04.518Z sha d03fdc2 :: needs maintainer review before merge. :: none

@metahacker
metahacker force-pushed the fix/gateway-shutdown-deadline-completion-20260911 branch from 352cf90 to ee97b88 Compare September 14, 2026 18:42
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 14, 2026
@fuller-stack-dev fuller-stack-dev self-assigned this Sep 14, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review September 21, 2026 06:24
@openclaw-barnacle openclaw-barnacle Bot added size: L triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Sep 21, 2026
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

Published signed head d03fdc2525e0d28752b1064250fcc57ffcf2ee3a preserves contributor ancestry and the reviewed/tested tree. The body now records the 212 focused tests, clean CLI review, final package build, passing published9.4-to-candidate installation, and the inherited synthetic-systemd MainPID mismatch found in the subsequent managed-handoff fixture. Both fixture projections and the maintenance-drain helper are unchanged from base; independent QA owns the fixture repair. Legacy-state automatic-restart proof is running separately. No production identity fence is weakened and the failed fixture is not reported passing.

@clawsweeper

clawsweeper Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 21, 2026
@vincentkoc
vincentkoc merged commit 6f60b59 into openclaw:main Sep 21, 2026
399 of 405 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

@clawsweeper

clawsweeper Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix(gateway): avoid stuck shutdowns after lifecycle errors This is item 1/1 in the current shard. Shard 0/1.

This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

steipete added a commit that referenced this pull request Sep 21, 2026
Integrate the landed shutdown-completion owner fix from #145241 so its
extracted regression suite composes with the forced-restart drain policy.
Keep the cleanup-only fixtures explicitly exhausted and preserve their
original timeout assertions.

Co-authored-by: Alex Markson <[email protected]>
Co-authored-by: Vincent Koc <[email protected]>
vincentkoc added a commit to vyctorbrzezowski/openclaw that referenced this pull request Sep 21, 2026
…question-layout-restart-recovery-20260921

* 'main' of https://github.com/openclaw/openclaw: (110 commits)
  perf(infra): collect and retire idle worker heaps (openclaw#154408)
  perf(sessions): hand shared history to the final reader (openclaw#154552)
  fix: clarify Codex onboarding migration scope (openclaw#151383)
  fix: recover conflicted PRs after accepted auto-merge
  perf(update): defer Gateway maintenance during candidate validation (openclaw#154548)
  perf(test): advance llama.cpp reload deadlines virtually (openclaw#154536)
  refactor(skills): prepare pinned library resources off-thread (openclaw#148560)
  fix(tooling): preserve Node compiler policy in script subprocesses (openclaw#154509)
  ci: select supported Node and cover packaged Node 26 (openclaw#154298)
  fix(release): preserve Telegram rerun evidence (openclaw#154561)
  docs: follow pending PR merges through completion
  fix(gateway): avoid stuck shutdowns after lifecycle errors (openclaw#145241)
  fix(ui): let focused dashboard widgets fill the task area (openclaw#154440)
  feat(release): add non-Latest extended-stable releases (openclaw#154515)
  fix(release): project 7.35 package Telegram config (openclaw#154546)
  refactor(config): derive host contracts from schemas (openclaw#153936)
  fix(ui): remove finished subagents from inline activity (openclaw#154469)
  refactor(config): derive core channel contracts from schemas (openclaw#153935)
  refactor(config): derive boundary contracts from schemas (openclaw#153937)
  fix(ui): keep thread activity current across cached updates (openclaw#154540)
  ...
steipete added a commit that referenced this pull request Sep 21, 2026
* fix: let forced Gateway restarts drain admitted work

Keep force separate from exhausted drain budgets and settle startup orphan rows with their failure receipts in one transaction. Reuse prepared process fixtures for restart coverage.

* test: include drain budget in external restart health check

Preserve the exact running-Gateway and no-candidate-state assertions while allowing the existing five-minute drain budget before the one-minute readiness window.

* test(gateway): control elapsed drain clocks

* refactor(gateway): separate restart budget and warning formatting

* fix(gateway): retain shutdown deadlines through completion

Integrate the landed shutdown-completion owner fix from #145241 so its
extracted regression suite composes with the forced-restart drain policy.
Keep the cleanup-only fixtures explicitly exhausted and preserve their
original timeout assertions.

Co-authored-by: Alex Markson <[email protected]>
Co-authored-by: Vincent Koc <[email protected]>

* test(gateway): clean up forced restart fixtures

---------

Co-authored-by: Alex Markson <[email protected]>
Co-authored-by: Vincent Koc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 22, 2026
…145241)

* fix(gateway): retain deadlines through restart completion

* test(gateway): extract shutdown completion coverage

---------

Co-authored-by: Vincent Koc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 22, 2026
…54300)

* fix: let forced Gateway restarts drain admitted work

Keep force separate from exhausted drain budgets and settle startup orphan rows with their failure receipts in one transaction. Reuse prepared process fixtures for restart coverage.

* test: include drain budget in external restart health check

Preserve the exact running-Gateway and no-candidate-state assertions while allowing the existing five-minute drain budget before the one-minute readiness window.

* test(gateway): control elapsed drain clocks

* refactor(gateway): separate restart budget and warning formatting

* fix(gateway): retain shutdown deadlines through completion

Integrate the landed shutdown-completion owner fix from openclaw#145241 so its
extracted regression suite composes with the forced-restart drain policy.
Keep the cleanup-only fixtures explicitly exhausted and preserve their
original timeout assertions.

Co-authored-by: Alex Markson <[email protected]>
Co-authored-by: Vincent Koc <[email protected]>

* test(gateway): clean up forced restart fixtures

---------

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

Labels

cli CLI command changes P2 Normal backlog priority with limited blast radius. 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.

3 participants