Skip to content

fix(gateway): wait for lifecycle ownership during restart - #146189

Merged
steipete merged 3 commits into
mainfrom
steipete/upd-restart-lifecycle-handoff
Sep 12, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/upd-restart-lifecycle-handoff

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #146142

Additional instructions

Maintainer edits: This branch is in openclaw/openclaw; maintainers with repository write access can update it directly.

What Problem This Solves

Fixes an issue where users restarting a supervised Gateway could get an immediate startup failure while another OpenClaw process still held lifecycle ownership. Repeated failed starts could exhaust systemd's start limit and leave the Gateway down.

Reported by @waynegault (#146142).

Why This Change Was Made

Gateway acquisition now waits for lifecycle-coordinator contention under a five-minute monotonic deadline, with backoff from 250 ms to 2 seconds. It logs the initial wait and successful acquisition, and includes the elapsed wait in a terminal ownership error. The deadline loop is shared with the startup-migration lease fix from #120959; migration owner classification and polling cadence stay intact.

Supervised startup recognizes lifecycle contention and passes the same absolute deadline into acquisition, including time spent loading startup code. A healthy port cannot turn coordinator contention into successful startup. Generated systemd units allow ten starts per 300 seconds while retaining the five-second restart delay; both documented unit examples match. Launchd already has throttling without a finite start-limit latch.

The coordinator remains an anonymous SQLite lock. Holder identity is a follow-up pending Peter's persistence design decision. A foreign live owner receives the same bounded wait and still fails if it never releases; the code never steals ownership. Normal restart already releases ownership before handing off in both v2026.9.3 and this branch, so the reporter's exact overlapping process remains unidentified.

User Impact

A restarted Gateway waits, with a generous bounded budget, for its predecessor to release lifecycle ownership instead of failing immediately and tripping systemd's start limit.

The candidate Gateway owns this behavior, so an older installed updater or existing unit can benefit without learning a new handoff marker. The revised systemd limits apply when the service definition is rewritten. No configuration options, dependencies, schemas, or retained-state semantics change.

Evidence

  • Before the fix, the new real cross-process coordinator tests failed immediately on a predecessor scheduled to release after two seconds, and the permanent-owner test received the old error without a wait. The supervised-classification test independently failed on lifecycle contention.
  • The existing systemd unit test failed before the template change: expected burst 10, received 5.
  • Focused proof: 314 tests passed, covering lifecycle and role locks, migration leases, supervised startup, run-loop shutdown, restart sentinels, systemd units, and launchd plists.
  • node scripts/check-changed.mjs passed, including production/test typechecks, lint, schema guards, and zero runtime import cycles. git diff --check passed.
  • Independent autoreview: scoped-clean through P2.
  • Linux Testbox: remote pnpm build and real systemd restart passed, with candidate source hashes verified. Node 24.19.0 / systemd 255.4. An independent synthetic holder retained the actual coordinator until two seconds after the replacement logged waiting. Readiness succeeded; PID changed; NRestarts=0, Result=success, ExecMainStatus=0, and no failed-start message. The owned service and Testbox were cleaned up.
waiting for gateway-lifecycle ownership held by another OpenClaw process, up to 300 s
gateway-lifecycle ownership acquired after 3.8 s
ActiveState=active  SubState=running  NRestarts=0  Result=success

Testbox run, lease tbx_01m2b60qf71cpz0zhr9p7z153q, wrapper exit 0. Provider cleanup can mark the hosting Actions run cancelled; the proof command itself passed.

node scripts/run-vitest.mjs \
  src/infra/gateway-lock.test.ts \
  src/infra/gateway-lock.roles.test.ts \
  src/infra/state-database-coordinator.test.ts \
  src/infra/startup-migration-checkpoint.test.ts \
  src/cli/gateway-cli/run.supervised-lock.test.ts \
  src/cli/gateway-cli/run-loop.test.ts \
  src/gateway/server-restart-sentinel.test.ts \
  src/daemon/systemd-unit.test.ts \
  src/daemon/launchd-plist.test.ts

Production grows by 93 lines for bounded asynchronous acquisition, diagnostics, and deadline propagation; the migration polling loop is shared rather than duplicated. There is no persistent ownership representation change.

CI also exposed an obsolete whole-module lock mock in CLI option coverage. Removing that mock restored the real timeout, contention classifier, and error class; all 94 CLI option/lifecycle tests passed (node scripts/run-vitest.mjs src/cli/gateway-cli/run.option-collisions.test.ts). No assertions were weakened.

The first CI run exposed the infra test-root cap (701 roots versus the existing 700 limit). Both new ownership regressions were consolidated into the existing Gateway lock-role test file, preserving the cap and all assertions. The consolidated Gateway lock-role suite and repository partition/cap suite then passed 29 tests:

node scripts/run-vitest.mjs src/infra/gateway-lock.roles.test.ts test/scripts/tsgo-core-test-shards.test.ts

Published restart driver × candidate: Exact npm [email protected] ran gateway restart --preserve-definition --json against the candidate under the same injected contention. It exited 0 with result=restarted, preserved the unit bytes, and produced a ready successor after a 3.8-second ownership wait with NRestarts=0. Runtime source hashes remained unchanged through the test-only consolidation. Published-driver Testbox run, lease tbx_01m2b6pjepvdw2wj60sgv8hnf9, wrapper exit 0; service, profile, and lease cleaned up. Setup initially hit the released CLI's canonical-path and enabled-unit guards; the final fixture used its supported named-profile layout and normal service enablement.

These Linux cells inject contention; they do not establish the original production holder or WSL2-specific behavior. The compatibility cell covers the published restart driver, not a full npm update.

Two unrelated failures were identified in the merged CI revision for head cafce22616e (main d8312aab8aca):

  • checks-node-compact-small-29: gateway-other has 701 roots on that main revision versus 700 on this branch. Main PR fix(gateway): expose missing worker RPC latency diagnostics #145602 / 31c8b990cb5c added the worker-metrics test; this branch changes no Gateway test roots or shard configuration. This is separate from the corrected infra-root increase above.
  • checks-windows-node-test-2: update-managed-service-handoff-database-publication.test.ts expects “changed during initialization” but receives “file is not a database” on Node 24.21.0. The test and its 265-file static dependency closure, package/lock files, and relevant runner inputs are unchanged by this branch; none of the changed lifecycle acquisition modules is in that closure. The exact Windows cause remains for its owner to investigate.

Both existing guards/assertions are retained. Final-head CI passed for 5c6dcc64d0005c6bac5df1d08f4b398b0baf44b4: completed successful run. The earlier failures above are historical; the current check rollup is green.

ClawSweeper review

The latest completed review of 5c6dcc64d0005c6bac5df1d08f4b398b0baf44b4 found no code or security defects. No code fixups were needed. Skipped: identify the original WSL2 holder and prove a full npm update before merge. The maintainer explicitly approved landing the bounded lifecycle-contention repair with these documented limitations: real Linux cross-process contention and the published 2026.9.3 restart driver prove the changed boundary. Identifying the original holder and adding coordinator holder identity remain follow-ups, with the latter pending a persistence decision.

A restarted Gateway waits, with a generous bounded budget, for its predecessor to release lifecycle ownership instead of failing immediately and tripping systemd start limits. Share the migration acquisition deadline loop and carry one monotonic deadline through supervised startup.

Fixes #146142. Reported by @waynegault (#146142). Coordinator holder identity remains a follow-up pending a persistence design decision.
@clawsweeper

clawsweeper Bot commented Sep 12, 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 cli CLI command changes app: linux plugin: linux-node size: M maintainer Maintainer-authored PR labels Sep 12, 2026
@steipete
steipete marked this pull request as ready for review September 12, 2026 16:21
@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. 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. labels Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 12, 2026, 1:37 PM ET / 17:37 UTC (Revision 4).

ClawSweeper review

What this changes

Gateway startup waits for lifecycle ownership under a shared five-minute retry budget, reuses migration polling, and updates systemd restart limits and documentation.

Merge readiness

⛔ Blocked before merge - 1 item remains

This remains a useful, proven fix: reviewed main and v2026.9.4 still fail immediately on lifecycle contention. No blocking correctness or security finding remains.

Priority: P1
Reviewed head: 5c6dcc64d0005c6bac5df1d08f4b398b0baf44b4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with strong restart and compatibility evidence, meaningful regression coverage, and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Recorded Linux/systemd runs exercise the production Gateway acquisition path under real cross-process SQLite contention and show readiness after a 3.8-second wait; the published 2026.9.3 restart driver also succeeds with unchanged service-definition bytes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): Recorded Linux/systemd runs exercise the production Gateway acquisition path under real cross-process SQLite contention and show readiness after a 3.8-second wait; the published 2026.9.3 restart driver also succeeds with unchanged service-definition bytes.
Evidence reviewed 9 items Current main still needs contention recovery: The reviewed main revision directly acquires the lifecycle coordinator and immediately wraps contention as a GatewayLockError; it has no asynchronous lifecycle wait.
Latest release retains immediate failure: The v2026.9.4 source also performs a single lifecycle-coordinator acquisition and immediately throws on contention.
Ownership remains exclusive: Acquisition retries only gateway-lifecycle contention, obtains the existing SQLite coordinator before proceeding, and releases it if subsequent lock acquisition fails. No live-holder reclamation, schema change, or new authorization capability is introduced.
Findings None None.
Security None None.

How this fits together

The Gateway startup loop acquires exclusive state ownership before starting the server. Service supervisors launch replacements during restart, so temporary ownership contention can otherwise prevent the replacement from becoming ready.

flowchart TD
  A[Startup or supervised restart] --> B[Shared retry deadline]
  B --> C[Acquire lifecycle ownership]
  C -->|Held elsewhere| D[Bounded wait]
  D --> C
  D -->|Deadline reached| E[Ownership error]
  C -->|Acquired| F[State and config locks]
  F --> G[Gateway server startup]
Loading

Before merge

  • Resolve merge risk (P1) - The original WSL2 coordinator holder remains unidentified; the successful Linux contention cells do not establish the exact production race or full npm-update behavior.
Agent review details

Security

None.

PR surface

Source +93, Tests +125, Docs +2. Total +220 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 6 139 46 +93
Tests 5 134 9 +125
Docs 3 6 4 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 279 59 +220

Review metrics

Metric Value Why it matters
Production versus regression coverage production net +93 lines; tests and test support net +125 lines Production growth implements bounded waiting and deadline propagation while sharing the existing migration polling mechanism.
Restart compatibility 1 published-driver × candidate cell The 2026.9.3 restart command successfully launched the candidate while preserving the existing service definition.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep contention recovery in the existing acquisition owner, preserve exclusive access, and retain published-driver compatibility without adding persistent holder metadata to this fix.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep contention recovery in the existing acquisition owner, preserve exclusive access, and retain published-driver compatibility without adding persistent holder metadata to this fix.

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

Yes for the contention failure mechanism: another process holding the lifecycle coordinator makes reviewed main fail immediately. The exact original WSL2 overlap remains unestablished; this read-only review ran no tests.

Is this the best way to solve the issue?

Yes. Bounded asynchronous acquisition repairs the missing tolerance at its existing owner, and the shared helper preserves migration retry semantics without changing persisted state.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: The linked production report describes supervised restart failures that can exhaust systemd retries and leave the Gateway unavailable.
  • 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 (logs): Recorded Linux/systemd runs exercise the production Gateway acquisition path under real cross-process SQLite contention and show readiness after a 3.8-second wait; the published 2026.9.3 restart driver also succeeds with unchanged service-definition bytes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded Linux/systemd runs exercise the production Gateway acquisition path under real cross-process SQLite contention and show readiness after a 3.8-second wait; the published 2026.9.3 restart driver also succeeds with unchanged service-definition bytes.

Evidence

What I checked:

Likely related people:

  • steipete: 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-12T16:29:04.962Z sha d795a3b :: blocked before merge. :: none
  • reviewed 2026-09-12T17:00:44.484Z sha cafce22 :: blocked before merge. :: none
  • reviewed 2026-09-12T17:20:15.805Z sha 5c6dcc6 :: needs maintainer review before merge. :: none

Consolidate the two cross-process lifecycle regressions into the existing lock-role suite. Preserve the 700-root typecheck guard and the existing file-size limits.
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 12, 2026
Remove the obsolete whole-module mock so supervised startup uses the real lifecycle timeout, contention classifier, and error class. The run-loop remains mocked and no locks are acquired by these option tests.
@steipete
steipete merged commit 7249a93 into main Sep 12, 2026
205 checks passed
@steipete
steipete deleted the steipete/upd-restart-lifecycle-handoff branch September 12, 2026 17:48
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
…46189)

A restarted Gateway waits, with a generous bounded budget, for its predecessor to release lifecycle ownership instead of failing immediately and tripping systemd's start limit. Share the bounded acquisition loop with startup migrations and carry one monotonic deadline through supervised startup, preserving exclusive ownership and terminal contention errors.

Generated systemd units allow ten starts per 300 seconds and retain the five-second restart delay. Existing installed updaters and service units benefit from the candidate-side acquisition fix. No configuration, schema, dependency, or persistent-store recovery change is introduced.

Fixes openclaw#146142
Reported by @waynegault (openclaw#146142).

Proof: cross-process regression coverage, focused lifecycle and service tests, exact-head CI, Linux systemd restart under injected coordinator contention, and the published [email protected] restart driver against the candidate all passed. The real restart acquired ownership after 3.8 seconds and reached readiness with zero systemd restarts.

Coordinator holder identity remains a follow-up pending a persistence decision. The proof does not identify the original WSL2 holder or cover a full npm update.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: linux cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. plugin: linux-node proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

1 participant