Repository navigation
fix(gateway): preserve live owners through restart - #147242
Conversation
Record Gateway process identity and listener mode in the existing shared state lease table while retaining the native coordinator as authority. Revalidate ownership before stale cleanup and escalation, route foreground restarts to the selected owner, and protect new startup generations from stale observations left by an earlier crash. Keep the published no-row discovery contract and the Windows snapshot-miss fallback. Cover the reported lock-before-listener and foreground-task mismatch flows with ordered regressions and shared SQLite lifetime proof. Reported by @deYangar (#140162). Fixes #140162 Related: #146387, #147019
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. Reviewed September 13, 2026, 4:52 PM ET / 20:52 UTC (Revision 7). ClawSweeper reviewWhat this changesThe PR records Gateway process ownership so restart preserves live or slow-starting processes, targets foreground Gateways correctly, and limits Scheduled Task cleanup to verified owners. Merge readiness⛔ Blocked before merge - 5 items remain The fix remains necessary, and no actionable code findings remain from this review. The recorded maintainer decision accepts the outstanding proof gaps; the supported proof override is not yet recorded in the PR labels. Priority: P1 Review scores
Verification
How this fits togetherGateway lifecycle commands coordinate running processes, native service managers, and shared SQLite state. Ownership checks determine which process may restart or stop, while health checks determine whether the replacement is ready. flowchart TD
A[Restart command] --> B[Read Gateway ownership]
C[Gateway startup] --> D[Shared lease and physical coordinator]
D --> B
B --> E{Verified owner type}
E --> F[Targeted foreground restart]
E --> G[Native service restart]
F --> H[Replacement health check]
G --> H
Before merge
Agent review detailsSecurityNone. PR surfaceSource +695, Tests +1568, Docs +1, Other -2. Total +2262 across 46 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep ownership publication with the existing lease/coordinator lifecycle, preserve legacy installed-argument attribution, and retain the documented upgrade-risk acceptance. Do we have a high-confidence way to reproduce the issue? Yes, source inspection supports the reported mechanism: current main can classify a listener as stale from native-runtime mismatch without consulting the proposed owner record. This review did not execute a current-main reproduction. Is this the best way to solve the issue? Yes, the patch uses the existing coordinator, lease heartbeat, and targeted restart contracts, and the earlier defects are repaired. Native Windows and published-updater coverage remain limited as explicitly acknowledged. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 6dbdbc515515. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (6 earlier review cycles)
|
Use the installed service environment for ownership reads during native restart and stop. Extend the stored-environment regression and update cleanup assertions to cover the selected state directory. Refs #140162
Acquire non-reentrant physical Gateway exclusion before legacy Windows termination, and retain it through graceful cleanup, escalation, and exit verification. Missing lease rows cannot authorize killing an unpublished coordinator holder. Preserve ambiguous coordinator-backed owners and keep file-lock-only legacy cleanup while physical ownership is free. Cover the publication ordering and prevent replacement admission until termination has settled. Refs #140162
|
Merged via squash.
|
Record Gateway owner identity alongside the physical lifecycle coordinator so restart cleanup preserves live and slow-starting Gateways before they begin listening. Route foreground restarts through the recorded owner even when an installed Scheduled Task uses a different launch mode. Limit Scheduled Task termination to the installed task's recorded owners or exact installed-argv-attributed legacy processes. Revalidate ownership before termination, repair initially unavailable native process identity through the guarded heartbeat, and preserve captured Unix process-group identities through escalation. Validated by exact-head CI run 34780366323, including the affected Windows batch's 88 passing tests, and a scoped-clean P1 review. Native Windows final-effect proof and a published-updater end-to-end matrix remain accepted proof gaps; the Windows guest was unavailable in startup recovery. Supervisor metadata uses the new owner row's JSON payload without a schema version, table, or retention change. Reported by @deYangar (openclaw#140162). Fixes openclaw#140162
rebase 時のコンフリクト解決 (onto 92635da, 元コミット 119f95fdaa6): - 上流 openclaw#143905/openclaw#147242 で safe RPC restart 分岐に assertGatewayServiceFallbackAllowed("safe RPC restart") が追加された。 本コミットは safe 分岐を external-supervisor 判定より前へ移し暗黙 safe 判定を 足しているため、移動先の分岐に上流のガードを取り込み、旧位置の重複分岐は削除
rebase 時のコンフリクト解決 (onto 92635da, 元コミット 119f95fdaa6): - 上流 openclaw#143905/openclaw#147242 で safe RPC restart 分岐に assertGatewayServiceFallbackAllowed("safe RPC restart") が追加された。 本コミットは safe 分岐を external-supervisor 判定より前へ移し暗黙 safe 判定を 足しているため、移動先の分岐に上流のガードを取り込み、旧位置の重複分岐は削除 rebase 時のコンフリクト解決 (onto 57fd13e, 元コミット 21f40bf994c): - 上流 8b680f3 (openclaw#178163) が createSafeGatewayRestartPreflight の inspectors 引数と SafeRestartInspectors 型を削除。引数なしの形に合わせ、 session admission / mutation を 0 に固定するスタブだけを外して実数で数える - 上流 c268b9d (openclaw#181608) が SafeRestartTarget 型を引数へインライン化。 インライン型のまま transport 引数を追加 - 上流がテストを describe なしのトップレベル it と、実モジュールの spy による カウンタ差し替えに書き直したため、両テストファイルは上流版を基に 本コミットのケースを追加。restart-coordinator.test.ts は session-controller.lifecycle.js を spy して admitted turn を 1 件にする rebase 時の調整 (onto 258d034, 元コミット 76c4af4b6cc): - restart-suspension.test.ts: 上流 36e277d (openclaw#175837) が session-lifecycle-admission.js を session controller へ統合して削除し、 上流 f27df1d (openclaw#165330) が scheduleGatewayRestart の skipCooldown を 削除していた。どちらも前回のベース (57fd13e) より前の変更で、 このファイルは読み込みに失敗し上流分を含む全テストが動いていなかった。 後継の beginSessionEffect / getSessionControllerWorkCount (session-controller.lifecycle.js) へ置き換え、skipCooldown を外した。 クールダウンは直前に再起動を発信した場合だけ掛かるため、外しても挙動は同じ rebase 時のコンフリクト解決 (onto 638a185, 元コミット a06162363f5): - 上流が lifecycle-safe-restart.ts に restartFlagConflictError / assertNativeRestartFlags を追加し、runDaemonRestart の冒頭で呼ぶ形にした (--preserve-definition と --safe、 --skip-deferral の組み合わせ検査)。上流の2関数と呼び出しを残したまま shouldUseImplicitSafeRestart と requestSafeGatewayRestartIfNeeded の呼び出しを その直後に並べた (フラグ検査 → 暗黙 safe 判定 → external-supervisor の順)。 旧位置の `if (opts.safe)` 分岐は本コミットが既に削除済みで、重複は残っていない。
Fixes #140162
Related: #146387, #147019
What Problem This Solves
Fixes restarts killing a ready or slow-starting Gateway as stale, or failing when a foreground Gateway owns the port while an installed Scheduled Task uses a different launch mode.
User Impact
Verified live owners survive stale cleanup, including before their listener opens. Restart targets a recorded foreground owner even when a native service is installed. Scheduled Task cleanup preserves external supervisors and other tasks, and tells the operator which supervisor to use. Older installed-command-attributed Gateways remain terminable during an update.
Why This Change Was Made
The physical Gateway coordinator holds a separate SQLite database. A
gateway-owner/globalrow in the existing sharedstate_leasestable publishes PID, host, native start identity, listener mode, supervisor kind/name, and port. It reuses the existing heartbeat and dead/recycled-owner reclaim machinery. Supervisor identity is a JSON payload field on this new, unreleased row: no schema change, compatibility reader, configuration option, dependency, or retention change.All round-three findings are addressed:
schtaskskind and matching installed task name. External and other-task owners are preserved. Launchd/systemd do not select recorded owners by supervised mode; their shared stale cleanup already preserves recorded owners.Health checks no longer infer staleness from unknown listeners or the old startup timer. Foreground routing uses the caller's selected state. Ownership is rechecked before signals; failed heartbeat cleanup retains physical custody. The #146387 snapshot-miss handling and #147019 shared process-start budget remain intact.
Reported by @deYangar (#140162).
Evidence
5eb21fa9f2bbb06b756f30251065d1b43823847a: pause after publication before listening, restart while paused, resume, verify new generation and/readyz200 with no stale kill, then verify row/port cleanup.pnpm check:changed: passed, including core/test typechecks, changed-file lint, schema v17 guard, and zero runtime import cycles. The final staged candidate received a P1 scoped-clean autoreview. Test-only type/lint findings were fixed without weakening assertions or baselines.d4fdc0e13fe578a9a7b06db9dc89956c9210997c.77c87d9f6769928ee8841d418052efa981689b28has parents maind2f67deda7908066cc111c794e1c6a0f5d0f82b7and the exact final head. The main parent includes fix(ci): tooling shard fails on QA Profile Evidence routing after #143968 #147293; no empty refresh commit was needed.Native Windows final-effect proof was attempted through the local Parallels Windows 11 guest. It booted into unrepaired Windows startup recovery; bounded current-user exec returned 255. The guest was returned to its initial stopped state. Task-owned termination and external-owner refusal have boundary evidence, not native Windows execution. A published-updater end-to-end matrix remains unrun; no operator Gateway was used.
ClawSweeper review
Maintainer decision: land the reviewed head
d4fdc0e13fe578a9a7b06db9dc89956c9210997c, accepting the bounded proof gaps below. The completed ClawSweeper review of this head reports no actionable code findings.src/cli/gateway-cli/run-loop.tspublishes supervisor kind;src/daemon/schtasks-process.tsselects only the installed task's recorded owners and preserves exact installed-argv cleanup for older holders without rows;src/infra/gateway-owner-lease.tsretries identity lookup and repairs unknown identity through the guarded heartbeat;src/infra/restart-stale-pids.tsretains captured group identities through escalation.