Skip to content

refactor(gateway): share one shutdown drain wait - #165574

Merged
steipete merged 2 commits into
mainfrom
steipete/restart-drain-20261005
Oct 5, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/restart-drain-20261005

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Related: #164403, #165524

What Problem This Solves

CLI shutdown and direct Gateway close maintained separate drain loops and log formatters, making their timing and ownership behavior harder to keep consistent. This is the maintainer-requested S6 restart-reliability audit slice.

User Impact

Existing drain budgets and recovery behavior are preserved. CLI shutdown waits for process-wide work; direct restart close waits for its Gateway's active chat runs and accepted queued turns, plus the process-wide pending-reply count (the existing getTotalPendingReplies counter is process-global; this PR does not change that scope). Remaining work uses the same named-count log format. No configuration, schema, durability, or migration changes are required. The change takes effect in the next Gateway process; it cannot modify shutdown already running older code.

Why This Change Was Made

One inspector-driven wait owns deadline handling and polling. Callers retain their scope, polling intervals (250 ms process-wide, 100 ms per Gateway), and timer-reference behavior. Close preparation normalizes restart mode once while retaining the public restartExpectedMs adapter. Terminal persistence, recovery marking, cancellation, resource retirement, and the native process-exit path retain their ordering.

The duplicate reply poller and formatter are removed. Production delta: 81 additions, 119 deletions; net −38 lines, excluding tests and docs. This is an ownership-preserving refactor, with no shutdown-speed claim.

Evidence

A historical read-only audit found 9 of 11 restarts exhausted their bounded drain while agent turns were executing. Eight logged recovery marking before a later cleanup deadline; the ninth last logged a pending marker, although a zero-result completion could be silent. Deadline messages repeated the last drain snapshot and did not identify the later blocked cleanup owner. No attributable registration-release bug was established, so this change does not widen budgets or remove joins.

All heavy validation ran on Blacksmith Testbox (blacksmith-testbox, profile openclaw-check), with the base and candidate source hashes verified. The restart proof used lease tbx_01m45zb6tm0gzs02dtthy1w2v1, based on 5cd4a04fe65d plus the reviewed patch. Production and test files remain byte-identical after the final mechanical rebase. The final docs-only commit corrects the description of the process-wide pending-reply counter.

node scripts/run-vitest.mjs \
  src/infra/gateway-active-work.test.ts \
  src/gateway/server-close.test.ts \
  src/gateway/server-shutdown.test.ts \
  src/cli/gateway-cli/run-loop.test.ts \
  src/gateway/server.agent-execution-shutdown.test.ts \
  src/cli/gateway-cli/run-loop.direct-stop-active-work.process.test.ts \
  src/cli/gateway-cli/run-loop-shutdown-budget.test.ts \
  src/gateway/server-close.agent-databases.test.ts --maxWorkers=1

291 passed; 231.25 s wall, including real OS SIGTERM, direct close and CLI paths, two-Gateway isolation, queued input, terminal persistence, database-close receipts, and native deadlines. Changed-test execution cost: active-work suite 40 ms; shutdown suite 10.48 s (existing native process-tree cases). New coverage uses fake timers and replaces the narrower reply-grace case; no new process or Gateway boots were added.

Before the refactor, the original four focused suites passed 257 tests in 89.22 s on tbx_01m45wdkv2vcp2cpgkce72j489. The final run includes additional native-exit coverage and a newer base, so these are test-cost measurements, not a before/after performance benchmark.

Earlier validation found inherited stale-baseline and unused-export failures. Their upstream fixes were incorporated by rebase, with no unrelated fixes copied into this diff. The rebase preserves #165524's native exit path and received fresh independent review: scoped-clean through P2. node scripts/check-changed.mjs --staged passed formatting, all ratchets, core production types, and all 27 core-test type graphs. It stopped at two inherited unused exports: src/agents/runtime/index.ts: BranchSummaryResult and src/gateway/chat-sanitize.ts: stripEnvelopeFromMessage. Removing this lane's patch and running node --import tsx scripts/check-deadcode-exports.mts on untouched base 5cd4a04fe65d reproduced the same failures. The nine remaining planned lint/schema/storage/import-cycle/auth checks were then run individually and all passed; changed-file lint reported zero warnings/errors and import-cycle checking found zero cycles. The full gate is reported as an inherited failure, not green.

The first CI run was cancelled by fail-fast after five unrelated PR-tooling tests failed: two in eager-import-closure.test.ts, three in pr-worktree-provision.test.ts. The CI merge base omitted deferred-plugin-migrations.contract.ts from the wrapper inventory. Upstream fix 044859704eba is now incorporated by rebase. The patch ID and all nine reviewed files are unchanged; the earlier review and behavior proof remain valid.

Exact-head CI run 37314223759 passed on b31be072c3f4ccfefaf64db37dd4ad960de6a032: all 62 jobs settled, no failures. The 10 executed Node-test jobs consumed 2,260 runner-seconds, including setup; the longest was 416 s. That result is historical evidence for the unchanged production and test patch; the final docs-only head has the inherited CI failure documented below.

Inherited CI failure — authorized admin landing

The reviewed head is fff8393d0ed53d6e79767c2569b562a34ca6158e. ClawSweeper's durable review names this head, reports no actionable findings, and confirms the documentation scope correction.

Exact-head CI run 37318297550, attempt 1 has one non-aggregate failed job: check-test-types-core-5. It reports test/gateway-rpc-exporters.test.ts(110,9): TS2322, assigning GatewayMethodDescriptorInput[] to GatewayMethodDescriptor[] without required profileAccess. The failure was introduced on main by 3e7f2d88803e294a0a0b03cc136014648c0e5ddd (test(gateway): register descriptors in RPC exporter fixture) and is tracked by #165597. This PR does not modify that fixture or the descriptor/registry type contracts.

The inspected CI checkout is 91a7e8b8b51abbc1b5130a558495046afdef526d, merging this head into baseline 740ddaa458e3a6d931a03a323b6f853767227c0f. The failure inputs are unchanged between that baseline and tested merge. openclaw/ci-gate aggregates the same failure. The successful pr-fail-fast monitor cancelled checks-node-changed-1 and check-test-types-core-2, check-test-types-core-3, and check-test-types-core-4; those cancelled jobs remain incomplete coverage, not passing evidence. security-fast passed.

The maintainer authorized the native inherited-failure admin exception for this exact head. No CI rerun or source push is requested to obtain green. Existing reviewed Testbox proof and historical green CI remain scoped evidence for the unchanged production/test patch; current-head CI is explicitly not green.

@clawsweeper

clawsweeper Bot commented Oct 5, 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 size: M labels Oct 5, 2026
@steipete
steipete marked this pull request as ready for review October 5, 2026 12:50
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 5, 2026, 9:52 AM ET / 13:52 UTC (Revision 3).

ClawSweeper review

What this changes

The PR shares shutdown waiting and remaining-work formatting between CLI shutdown and direct Gateway close while preserving their existing work scopes and cleanup ordering.

Merge readiness

✅ Ready for maintainer review

The prior reply-scope documentation finding is resolved, and no introduced correctness defect was found. This remains useful work absent from current main; the earlier green CI result does not establish passing checks for the pinned head.

Priority: P3
Reviewed head: fff8393d0ed53d6e79767c2569b562a34ca6158e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, maintainable refactor with the prior documentation correction completed and no blocking patch finding.
Proof confidence 🌊 off-meta tidepool Not applicable: Repository State identifies a MEMBER author, exempting ordinary contributor proof. The supplied Testbox validation exercises shutdown owners and native process paths, but was not rerun here; the final commit is docs-only. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State identifies a MEMBER author, exempting ordinary contributor proof. The supplied Testbox validation exercises shutdown owners and native process paths, but was not rerun here; the final commit is docs-only. No stored-data contract changes.
Evidence reviewed 8 items Introduced patch: Reviewed the pinned merge-base-to-head delta across all nine introduced paths. The UI files in endpoint drift are base-branch changes and were not attributed to this PR.
Shared wait preserves caller contracts: The waiter normalizes finite deadlines, returns the final inspected snapshot, and supports unreferenced timers. Process-wide waiting retains its 250 ms interval; restart reply waiting retains 100 ms and ref:false. Recovery marking, queued cancellation, controller cancellation, and resource retirement remain in their existing order.
Prior finding resolved: The final commit changes only the documentation to identify process-wide pending replies. The captured PR body now makes the same distinction. Production server-lifecycle.ts passes getTotalPendingReplies, whose registry sums every registered dispatcher; the injected two-counter test does not prove production reply isolation.
Findings None None.
Security None None.

How this fits together

Gateway shutdown waits for admitted work before cancellation and resource retirement. CLI shutdown inspects process-wide activity; direct Gateway restart inspects its own chat runs and queued turns alongside the existing process-wide pending-reply count.

flowchart TD
  A[CLI shutdown] --> C[Process-wide activity]
  B[Direct Gateway restart] --> D[Gateway chat and queue activity]
  E[Process-wide pending replies] --> D
  C --> F[Shared deadline wait]
  D --> F
  F --> G[Drain result and named counts]
  G --> H[Existing recovery and cleanup]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -38, Tests +31, Docs +5. Total -2 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 6 81 119 -38
Tests 2 62 31 +31
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 148 150 -2

Review metrics

None.

Technical review

Best possible solution:

Keep one shared deadline waiter while callers retain their existing activity scopes, timer behavior, and persistence-before-retirement ordering.

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

Not applicable: this PR consolidates existing shutdown behavior rather than claiming a newly reproduced defect; source inspection confirms the duplicate waiting paths.

Is this the best way to solve the issue?

Yes: a shared inspector-driven waiter removes duplicate deadline handling without moving cancellation or persistence ownership.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is a bounded internal consolidation that preserves existing shutdown behavior and makes no shutdown-speed claim.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Repository State identifies a MEMBER author, exempting ordinary contributor proof. The supplied Testbox validation exercises shutdown owners and native process paths, but was not rerun here; the final commit is docs-only. No stored-data contract changes.

Evidence

What I checked:

  • Introduced patch: Reviewed the pinned merge-base-to-head delta across all nine introduced paths. The UI files in endpoint drift are base-branch changes and were not attributed to this PR. (fff8393d0ed5)
  • Shared wait preserves caller contracts: The waiter normalizes finite deadlines, returns the final inspected snapshot, and supports unreferenced timers. Process-wide waiting retains its 250 ms interval; restart reply waiting retains 100 ms and ref:false. Recovery marking, queued cancellation, controller cancellation, and resource retirement remain in their existing order. (src/infra/gateway-drain.ts:2, fff8393d0ed5)
  • Prior finding resolved: The final commit changes only the documentation to identify process-wide pending replies. The captured PR body now makes the same distinction. Production server-lifecycle.ts passes getTotalPendingReplies, whose registry sums every registered dispatcher; the injected two-counter test does not prove production reply isolation. Public docs: docs/gateway/restart-recovery.md. (docs/gateway/restart-recovery.md:142, fff8393d0ed5)
  • Current main still has separate waiting: Fetched main retains its own process-wide waiting loop and the separate restart reply poller and formatter. The merged related cleanup and native-exit PRs address adjacent shutdown behavior rather than implementing this consolidation. (src/infra/gateway-active-work.ts:214, 9251c970d840)
  • Latest-release check: The shared gateway-drain module is absent from the supplied latest release revision, consistent with this being pending refactor work rather than an already-shipped consolidation. (src/infra/gateway-drain.ts, fc23bc864e45)
  • Validation and proof scope: The captured body reports 291 passing Testbox cases covering CLI and direct-close paths, OS signals, queued input, persistence, and native deadlines. New active-work cases use fake timers and the existing close fixture. This is contributor-reported validation, not reviewer execution; the author is identified as MEMBER in Repository State, so ordinary external-contributor proof is exempt. (src/infra/gateway-active-work.test.ts:32, fff8393d0ed5)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vito Cappello: 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 (2 earlier review cycles)
  • reviewed 2026-10-05T12:56:16.365Z sha 9c540fbb88c9129e45e0964a732d719e536b3775 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T13:27:08.034Z sha b31be07 :: needs changes before merge. :: [P3] Describe the production reply counter's global scope

Keep process-wide CLI and instance-owned Gateway inspectors separate while sharing deadline waiting and count formatting. Preserve restart metadata normalization, terminal persistence joins, recovery marking, and cancellation ordering. No schema, durability, or drain-budget changes.
@steipete
steipete force-pushed the steipete/restart-drain-20261005 branch from 9c540fb to b31be07 Compare October 5, 2026 13:05
@steipete
steipete merged commit bfe9281 into main Oct 5, 2026
122 of 130 checks passed
@steipete
steipete deleted the steipete/restart-drain-20261005 branch October 5, 2026 14:03
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
* refactor(gateway): share one shutdown drain wait

Keep process-wide CLI and instance-owned Gateway inspectors separate while sharing deadline waiting and count formatting. Preserve restart metadata normalization, terminal persistence joins, recovery marking, and cancellation ordering. No schema, durability, or drain-budget changes.

* docs(gateway): describe the process-wide pending-reply count in Gateway close drain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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

Development

Successfully merging this pull request may close these issues.

1 participant