Repository navigation
fix(gateway): finish restart cleanup and unblock database recovery - #164403
Conversation
Keep admitted subagent cleanup with its original Gateway after ingress closes, and retain deletion code before an in-place update can replace runtime files. Preserve session-generation and live-owner checks. Activate deferred agent-database preparation when sidecars are ready, without waiting for unrelated subagent restoration. Keep existing integrity checks and clean-close receipt requirements unchanged.
|
🦞👀 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: blocked before merge. Reviewed October 3, 2026, 2:07 PM ET / 18:07 UTC (Revision 3). ClawSweeper reviewWhat this changesThe PR keeps admitted subagent cleanup running through Gateway shutdown, retains its deletion dependencies during installed-file replacement, and starts deferred database preparation before subagent restoration finishes. Merge readiness⛔ Blocked before merge - 2 items remain The fix remains useful on current main, and the latest commit resolves the prior observer-failure finding. No remaining introduced correctness defect was found. Priority: P1 Review scores
Verification
How this fits togetherThe Gateway owns agent execution, session deletion, and database readiness. Restart cleanup must settle admitted work before retiring those dependencies, while new requests remain refused. flowchart TD
A[Admitted agent work] --> B[Gateway shutdown drain]
B --> C[Tracked cleanup continuation]
C --> D[Live owner and session checks]
D --> E[Session deletion]
E --> F[Dependency retirement]
G[Sidecars ready] --> H[Deferred database preparation]
Before merge
Agent review detailsSecurityNone. PR surfaceSource -26, Tests +131, Docs +14. Total +119 across 22 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the shared cleanup and admission owners, with published-driver upgrade evidence confirming child deletion, clean shutdown, and successor availability. Do we have a high-confidence way to reproduce the issue? Yes: current-main source retains the closed-transport cleanup path, and supplied before/after Gateway traces reproduce a retained child. This read-only review did not execute target code. Is this the best way to solve the issue? Yes: continuing admitted cleanup through the existing execution and deletion owners is a focused repair that preserves new-request refusal and session-generation guards. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against f7d9a968f278. LabelsLabel changes:
Label 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
History |
Model hosted session deletion at its canonical domain boundary while keeping transport rollback and restored cleanup on the same controlled completion. Track work in the restored Gateway fixture and observe detached continuation failures so FIFO, publication, and live-owner assertions retain their meaning. Replace the unreachable hosted RPC barrier with a deletion-owner barrier and fail promptly if cleanup settles before it arrives.
Expect the detached cleanup observer to report injected receipt, retirement, and transcript cleanup failures. Keep durable-state and retry assertions, and verify unreadable receipt retry cannot execute another native write.
…penclaw#164403) * fix(gateway): finish restart cleanup and unblock database recovery Keep admitted subagent cleanup with its original Gateway after ingress closes, and retain deletion code before an in-place update can replace runtime files. Preserve session-generation and live-owner checks. Activate deferred agent-database preparation when sidecars are ready, without waiting for unrelated subagent restoration. Keep existing integrity checks and clean-close receipt requirements unchanged. * test(gateway): align hosted cleanup fixtures with lifecycle ownership Model hosted session deletion at its canonical domain boundary while keeping transport rollback and restored cleanup on the same controlled completion. Track work in the restored Gateway fixture and observe detached continuation failures so FIFO, publication, and live-owner assertions retain their meaning. Replace the unreachable hosted RPC barrier with a deletion-owner barrier and fail promptly if cleanup settles before it arrives. * test(subagents): assert deliberately failed cleanup settlement Expect the detached cleanup observer to report injected receipt, retirement, and transcript cleanup failures. Keep durable-state and retry assertions, and verify unreadable receipt retry cannot execute another native write.
Upstream openclaw#164403 (995b5ac) requires a run finalizer's subagent-session cleanup to settle before the Gateway retires, during stop and restart. The feature's continuation guards in deleteSubagentSessionForCleanup (live custody, active descendants, staged post-compaction delegates) read durable state before the delete and inherited the closing request's work scope, so close aborted them and the call threw instead of returning an outcome: server.agent-execution-shutdown.test.ts failed 2/3 at the candidate (passes 3/3 at upstream dd61952). The guards now run outside the async work scope, like other detached cleanup. A guard that still fails is reported like a failed delete: onError, deferred retry, "failed". Patch-coupled: with this file reverted the upstream test fails 2/3; with it, 3/3. The 16 subagent-session-cleanup test files pass; tsgo core clean. Found by F' Mode-B 37551941552 (agentic-control-plane-agent-chat). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
What Problem This Solves
Restarts can leave subagent child sessions behind and keep sessions unavailable while unrelated subagent restoration is pending.
User Impact
Already-admitted cleanup can finish before its Gateway dependencies retire, and deferred stores can become usable while subagent restoration is still pending. New RPCs remain refused during shutdown. No configuration, schema, data-retention, integrity, or updater/deployer policy changes.
Why This Change Was Made
Cleanup was treated as new work, and child deletion reentered the closed RPC dispatcher. Terminal cleanup and resource retirement now use the existing tracked continuation owner, and the restart-only retry loops against a closed admission fence are removed. Explicitly transferred lifecycle cleanup joins the original Gateway's tracked work and calls the shared session-deletion owner, with live Gateway lifetime, cleanup-generation, and exact session-identity checks through commit. Authenticated spawn rollback and standalone callers retain their existing transport contract. Internal cleanup joins the complete deletion operation; the Gateway shutdown deadline remains authoritative. Shutdown preparation also warms the cleanup caller's own import promise before an in-place update can remove old dist chunks. Deletion/reset cleanup uses static imports inside that existing lazy boundary, removing nested loaders and the kill runtime's load-and-reenter branch.
Activate deferred database preparation at sidecar readiness, before awaiting restored subagent work. Inspection already starts in foreground and continues after the five-second wait; its scheduling is unchanged. Preparation still awaits that store's inspection and any earlier serialized preparation. Parked delivery retries remain durable successor obligations: retaining their up-to-five-minute backoff as active shutdown work would lengthen restarts. A retry whose original root is still live can continue under that root.
The incident's time before stale-lease detection is not a lease TTL. Read-only startup inspection can perform full-file
PRAGMA integrity_checkandforeign_key_checkbefore writable admission logs stale leases. Writable current-schema admission separately checkstranscript_eventswithquick_check, other discovered tables/shadow tables andsqlite_schemawith per-tableintegrity_check, and foreign keys. A valid same-version clean-close receipt already skips both blocking scans. Those guarantees are retained: a WAL checkpoint cannot establish table/index/foreign-key integrity; substitutingquick_checkfor the full-file inspection would lose index/uniqueness validation.clean-close receipt: active-leasesconfirms the logging owner released its own lease while another remained. Current worker teardown already joins native cleanup. This change neither clears live leases nor manufactures a receipt. A dirty/missing receipt or a version change still requires the original validation scans; this PR does not shorten or add a new bound to those scans. An exhausted hard deadline cannot truthfully certify a clean close.Evidence
Synthetic Linux rig: 8 cores / 30 GiB RAM, Node 26.8.1, pnpm 12.5.1; isolated loopback ports and task-owned state only. Both heads use the same generated 500,500 events / 500 sessions / 4,589,445,120 bytes, with no production data. Measured and Testbox-validated base:
d6c1b1f9e14aa06443c685d81414911628e18914plus this patch. Before publication, the branch was rebased onto8e4f1533a300361272fc20f0517b6c005430a8f3; the stable patch ID is unchanged. The initial published head wasa88e6342c79046f64227f5476a3dfeccfbc8289c; the fixture-only CI follow-up isb0503f274d3e7140945aa901b39dacafefc3fa1b.The harness runs the built Gateway with parent and child embedded requests actively streaming, sends SIGTERM with a one-second requested drain, observes drain exhaustion and abort, enforces a 90-second supervisor deadline, and reads the lease table, clean-close receipt, and remaining child sessions after self-exit. Synthetic service markers select the native missing-unit 90-second fallback (approximately 85 seconds internally); no service unit was created or changed. Successor availability is measured using a successful
sessions.listagainst the generated inventory.These single paired runs establish cleanup correctness and the under-30-second clean-restart target, not a statistically meaningful latency/RSS improvement.
The additional in-place-update proof retires the built deletion/reset/bash/kill chunks after the parent and child are streaming, then sends SIGTERM and restores the files only after exit. The version without retention fails with
Cannot find module .../sessions-delete-*.mjsand leaves one child. The final candidate has zero missing-module errors, deletes the child, exits in 19,809 ms against an 84,858 ms budget, and serves successor sessions 312 ms after ready. Both that predecessor and the successor's final stop leave zero leases and a clean receipt. This exercises removed runtime artifacts; it is not a published-updater-driver test.Before/after timeline excerpts (UTC, synthetic state)
Neither successor entered degraded recovery or ran blocking validation: the clean receipt selected the existing fast path. The first process in each run admitted the cold copied fixture before the timed shutdown; that untimed preparation is not counted as a clean restart.
The supported dist build command
node --import ./scripts/tsx.mjs scripts/build-all.mts sourcePerformancepassed on both heads (baseline 135.9s; final candidate 97.7s). All rig workloads ran withnice -n 10 ionice -c3and disk-backedTMPDIRunder the isolated worktree.Blacksmith Testbox provider
blacksmith-testbox, profileopenclaw-check. Initial proof used leasetbx_01m413v1ccf2pfkxjrd71c6jrt(run); final proof usestbx_01m4181m2jjbc9g1j1va08fa3z(run).node scripts/run-vitest.mjs src/gateway/server-agent-database-startup.test.ts src/gateway/server-startup-update-canary.test.ts --maxWorkers=1: 12 passed, 103.91s command wall; startup case times total 75.251s, canary 0.039s. The existing Gateway/worker fixture is needed to prove post-attach ordering, preparation, secrets fencing, corruption refusal, deletion/cancellation, and update-canary behavior; no new Gateway boot was added.node scripts/run-vitest.mjs src/gateway/server.agent-execution-shutdown.test.ts --maxWorkers=1: 3 passed, 46.84s command wall; stop/restart/graceful test times 4.364s / 1.952s / 2.313s. Extends the existing suite fixtures to verify live-authority revocation, changed session identity, real child deletion before dependency teardown, and refusal after close. Replacing only the cleanup helper with baseline code makes the restart case fail through the closed transport (40.39s command wall).node scripts/run-vitest.mjs src/agents/subagents/registry/subagent-registry-lifecycle.test.ts src/agents/subagents/spawn/subagent-spawn-cleanup.test.ts --maxWorkers=1: 210 + 7 passed, 40.94s command wall. The lifecycle regression also failed against the original admission code before the repair.node scripts/run-vitest.mjs src/agents/tools/sessions-spawn-tool.test.ts src/agents/subagents/announce/subagent-announce.test.ts --maxWorkers=1 -t 'cleans up the created visible|reports the retained child|keeps a failed visible child|deleting the child|delete cleanup|deleting a completed session-mode': 7 + 4 passed, 22.93s command wall (11.83s / 8.88s shards). These preserve authenticated caller rollback and standalone cleanup.node scripts/run-vitest.mjs src/gateway/server.sessions.delete-lifecycle.test.ts src/agents/subagents/registry/subagent-control.test.ts src/gateway/server-agent-database-startup.test.ts src/gateway/server-startup-update-canary.test.ts --maxWorkers=1: 88 passed (17 deletion, 59 control, 11 startup, 1 canary), 202.20s command wall. These include the corrected deletion fixture and recheck startup after preload changes.node scripts/check-changed.mjs --stagedgate: passed, 1345.46s command wall. All 15 hashes matched; production types, all 27 test type graphs, formatting, lint (zero warnings/errors), unused exports (zero), import cycles (zero), docs, SQLite/schema, and remaining repository guards passed.Fresh independent Codex autoreview of all 15 files: scoped-clean through P2, both passes with no findings (static review). Production diff: +125 / −151 = −26 LOC, excluding tests, test support, and docs.
Limits: the current baseline already releases its leases and writes the receipt in this rig, so this PR does not claim to reproduce or eliminate the full reported outage. The reproduced shutdown defect is failed child cleanup. A cold-copy calibration took 139.632 seconds from ready to sessions, including 36.802 seconds of writable validation; that is not a clean-restart speedup comparison. Both measured same-version successors reused their valid receipts and needed no degraded recovery. Preparation activation is additionally proved with restoration held pending at the real post-attach boundary.
The original full build was OOM-killed while the rig also ran typechecks. Subsequent dist proofs use the supported
sourcePerformanceruntime build profile, not declaration output. No local suites, typechecks, or builds ran. No production host, service unit, or deployer was changed.The logged drain capacity is an upper bound: restart intent can request a shorter wait within the supervisor budget. Approximately 74 seconds of capacity versus 45 seconds elapsed therefore does not by itself establish a policy mismatch. Operator stop and drain settings are unchanged.
CI fixture repair
Initial published-head CI 37137338759 failed two test shards. The remaining jobs completed without cancellation. Three restored-registry cases still modeled deletion only through an RPC fake and supplied a partial hosted context without execution tracking. One publication case omitted detached-continuation results from its work observer, hiding the real stale-claim rejection. One hosted-authority case waited for an RPC precommit barrier that transferred cleanup no longer reaches.
The follow-up is fixture-only: model the canonical deletion boundary for hosted cleanup, provide the real execution tracker, and observe detached-continuation results. Existing FIFO, retry/publication, expired-tool-authority, and live-owner mutation assertions remain. No timeout inflation, production fallback, or skipped cases.
On replacement Blacksmith Testbox lease
tbx_01m41azhm4b66vmpk4qgjc9271(run;blacksmith-testbox,openclaw-check, Node 24.19.0), both controls used the original CI plans and file ordering. Both invokednode --import tsx scripts/ci-run-node-test-shard.mtswith the decoded originalOPENCLAW_NODE_TEST_GROUPS_JSONplans, CI runtime policy, two requested workers and continue-on-failure enabled. Native host admission clamped plan concurrency from two to one on its 4-core/16-GiB runner. The first queued lease disappeared before running any command.The final three-file
node scripts/check-changed.mjs --stagedgate passed in 501.68s. It selected eight affected test type graphs and passed fixture/line-cap ratchets, formatting, API/boundary/dead-export checks and lint (zero warnings/errors). A runner portal sync warning occurred after the successful command; source sync and exact staged hashes were verified before execution. Fresh independent review of the final fixture diff is scoped-clean through P2, with no findings.The validated fixture-only follow-up is published as
b0503f274d3e7140945aa901b39dacafefc3fa1b. Its CI run exposed four additional expected-error fixture mismatches: unreadable committed receipts during announcement delivery and cleanup start, a refused store-retirement write, and failed replacement transcript cleanup. The improved observer now reports those deliberately injected detached failures. The tests assert each specific aggregate while preserving durable fences, retry behavior, and no-replay checks. Explicit retry of an unreadable cleanup-start receipt additionally proves no further native-worker call occurs. The validation lease was stopped successfully; all original production rig and build evidence remains applicable.Final expected-error repair on Blacksmith Testbox
tbx_01m41dhfb8any574jwt9m65qjj(run;blacksmith-testbox/openclaw-check): original CI invocations, 26 files, 350 cases, same ordering and admitted host worker limits.All four expected failures reproduced; the corrected replay passed 350/350. Process wall time was 280.194s baseline / 271.874s corrected, including preparation. Commands used the same CI shard entrypoint and decoded original plans as above. Native sync left edits unstaged and Git used different hash abbreviations; preflight caught both before any tests, and the harness then verified the exact staged file set plus full-index patch hash. Fresh review of all four assertion changes is scoped-clean through P2.
The final four-file
node scripts/check-changed.mjs --stagedgate passed in 228.90s, including the selectedagents-sessionstype graph (35.3s), all fixture/line-cap/boundary guards, three unused-export scans, and lint with zero warnings/errors. Exact source and staged full-index patch hashes were verified. The lease was stopped successfully. Final expected-error repair:e0deef8d801d81b27f056724b24906220f9b4e29; exact-head hosted CI run 37142681402 passed, with no failed or unfinished jobs.