Repository navigation
perf(gateway): settle queued wakes before shutdown drain - #167666
Conversation
Release heartbeat waiters when irreversible shutdown closes admission so queued cron work cannot wait for a runner stop behind its own drain. Pause dispatch while retaining notifications for in-process restart, and preserve admitted handlers and their terminal persistence. Include command-lane and request owners in the final drain observation reported when the shutdown deadline expires.
|
🦞👀 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 maintainer review before merge. What this changesThe Gateway settles queued heartbeat callers when shutdown begins, preserves running work and notifications for an in-process restart, and names pending owners in deadline diagnostics. Example: Stop a Gateway with only queued heartbeat work outstanding.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR remains useful because current main retains the shutdown dependency cycle. No actionable introduced defect was found; the documented CI failure is inherited. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe Gateway wake queue schedules heartbeat and background-event turns. Shutdown waits for tracked work before closing shared resources, so queued callers must settle without prematurely retiring admitted handlers or writes. flowchart TD
A[Heartbeat and background events] --> B[Shared wake queue]
C[Stop or restart signal] --> D[Close work admission]
D --> B
B --> E[Settle queued callers and pause dispatch]
B --> F[Admitted handlers and writes]
E --> G[Drain tracked work]
F --> G
G --> H[Close shared resources]
Technical reviewBest possible solution: Keep shutdown settlement in the shared wake owner while preserving admitted writes, notification custody, and existing drain budgets. Do we have a high-confidence way to reproduce the issue? Yes: current-main admission rejection, wake retries, cron watchdog suspension, and CLI drain ordering establish the cycle, supported by reported before/after SIGTERM observations. This review did not execute a reproduction. Is this the best way to solve the issue? Yes: settling queued callers at the existing irreversible drain signal removes the cycle at its producer without shortening write grace or adding another shutdown owner. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 94c0f0d589ab. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +40, Tests +99, Docs +5. Total +144 across 8 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReviewed October 9, 2026, 3:42 AM ET / 07:42 UTC (Revision 3). |
|
Merged with the operator-authorized inherited-failure exception in 8a4ed22. The only failed CI root was All other executed PR CI jobs passed. Native admission verified review, security, policy, exact head, and baseline evidence before the pinned REST squash; CI was not rerun. The shutdown proof remains 75.517 → 1.619 seconds with all eight committed replies retained, and admitted terminal writes still hold shutdown open. Full commands, costs, and limitations are in the PR body. |
…7666) Release heartbeat waiters when irreversible shutdown closes admission so queued cron work cannot wait for a runner stop behind its own drain. Pause dispatch while retaining notifications for in-process restart, and preserve admitted handlers and their terminal persistence. Include command-lane and request owners in the final drain observation reported when the shutdown deadline expires. Synthetic real-Gateway SIGTERM proof: queued-only stop improved from 75.517s to 1.619s, with all eight committed replies and terminal done state retained. Pending terminal persistence still held shutdown open. Land under the inherited-CI-failure exception: the unchanged-main notification product proof reproduces the same 180-second timeout and watcher teardown failure; all other executed PR CI jobs passed.
…, batch 2) Restores the remaining small Gate 2.7 drops from the lane-base review; continuation behavior is unchanged. Taken from upstream verbatim (the fork hunks had no continuation content): host-tool-factory.ts (public test-contract helper; its re-entry guard can no longer fire), codex side-question.test-support.ts, doctor-health.migration-refusal.test.ts, board-notices.ts (no Raw alias), channel-ingress-gateway-restart fixture (parent test owns the timeout). Ported into fork forms: - session-event-wake.types.ts: HeartbeatWakeRequest/HeartbeatRunResult instead of the aliases upstream deleted in openclaw#167666; upstream's base-tick comment back above the slot-group loop. - session-delivery-queue-codec.ts: SessionDeliveryContext = Pick<DeliveryContext, ...> (openclaw#165916); recovery imports split as upstream. - subagent-announce.format nested-matrix helper: upstream's consolidated block (openclaw#166052) verbatim; the fork copy still ran 4 tests upstream retired in openclaw#165177. - runAgentAttempt is synchronous again (its only caller awaits it), with upstream's sync-throw assertion. - prepared-compaction-runtime: upstream's bootstrap-disclosure comment; dropped tool options duplicated from the conversationContext spread (senderIsOwner and disableContinuationTools stay). - agent-runner-result-accounting.test: one provenance it.each at module scope, stale visibleToolErrorObserved (openclaw#126542) dropped. - small: subagent-registry arrow form, STALE_UNENDED_SUBAGENT_RUN_MS not exported, dead loadConfig mock keys, upstream comments/imports in agent.ts schema, media-only/session/timeout/followup-status/storage tests. Refs #1475 Co-Authored-By: Claude Opus 5.5 <[email protected]>
What Problem This Solves
Fixes Gateway shutdown consuming its entire drain budget when a cron heartbeat is waiting in the wake queue.
User Impact
Queued heartbeat wakes settle when shutdown closes admission, so idle work no longer delays stop or restart. Running wakes, pending reply delivery, and terminal persistence retain the existing drain grace. Deadline logs identify pending command lanes, request owners, and close steps. No configuration or storage migration is required.
Why This Change Was Made
Cron retains its run while a heartbeat wake coalesces or backs off. Once shutdown closes admission, the queue retries rejected admission indefinitely; those retries disable the cron execution watchdog without starting another attempt. The CLI waits for cron before server close can stop the heartbeat runner, creating a shutdown dependency cycle.
The wake owner now settles waiting callers from the existing irreversible drain signal and pauses dispatch. It retains queued notifications for the next in-process runtime and leaves admitted handlers running. This removes the retry cycle at its producer. Existing drain budgets continue to protect active writes.
Production LOC: +40 net lines (excluding tests, test support, and docs). This preserves the distinction between queued and admitted work, retains notifications across handler replacement, and reports named owners.
Evidence
On a Linux rig (Node 26.8.1), using a real Gateway, OS SIGTERM, CronService, wake admission, SQLite transcript writes, and the terminal persistence owner:
donestate retainedThe idle case improves 46.6× / 97.9% with the same native 90-second stop policy. Pending-write timings include actual persistence settlement and vary with rig load. Patched shutdown completed cleanly. The base run also logged a cron receipt-authority error during forced cleanup; this proof does not claim successful cron receipt finalization on the base.
The extended queued-heartbeat regression fails on the base because the wake has not settled before server close. The focused run passed 156 tests across 4 files in 122.98 s with
pnpm test <focused files> --maxWorkers=1. The corrected notification-retention candidate passed 82 focused tests in 239.47 s; 235 sibling tests passed in 1197.55 s across Gateway-close, terminal persistence, wake lifecycle, and CLI stop-budget coverage. The planned type, lint, schema, boundary, and safety checks passed. The global dead-export scan is the sole staged-check failure and reproduces unchanged on main; details follow.Synthetic measurements and sibling tests ran on the authorized Linux rig fallback after initial allocation delays. The final staged checks ran on Blacksmith Testbox
tbx_01m4fjv9qxx4bpn6tsjdt9psak(providerblacksmith-testbox, profileopenclaw-check, Node 24.19.0). The initial queued Testbox was stopped. No tests or builds ran on the Mac. Independent review is clean at P0–P2 after preserving notification wakes for in-process restart. The measured commandpnpm test src/infra/session-event-wake-concurrency.test.ts --maxWorkers=1passed all 14 tests in 2.05 s wall time (warm) on that CI-class runner. PR CI run37895297806completed in 530 s wall time / 7,417 summed job-seconds. Its only failed root was the pre-existing Gateway notification product proof described below; all other executed jobs passed. The synthetic proof does not exercise a live model, external channel, or production Gateway.Pre-existing dead-export failure
node --import tsx scripts/check-deadcode-exports.mtsfails identically on this candidate and a clean, independently installed main checkout at73fdd3d2c6b249c7f4494990856f88713a634617on the same Testbox. These paths are outside this PR:src/agents/cli-runner/tool-authority.ts:bindCliQuestionAnswerAuthoritysrc/auto-reply/reply/session-event-handoff.ts:prepareSessionEventTargetForHostsrc/config/sessions/session-accessor.sqlite-entry-cache-publication.ts:readSessionEntryCreationTransitionsrc/infra/heartbeat-events-filter.ts:RESTART_CONTINUATION_CONTEXT_PREFIXThe last two also fail the full-tree scan. The guard remained enabled. All commands after that guard in the unchanged
check-changed --staged --dry-runplan were run separately and passed, including changed-file Oxlint, native schema version, legacy-store, media, sidecar, import-cycle, webhook, and pairing-boundary guards.Staged gate timing summary
Focused and sibling test commands
The proof uses synthetic state. Historical production incident attribution remains open because its log lacked owner identities.
Inherited PR CI failure
CI run 37895297806 has one failed root:
checks-node-changed-compact-small-19, plus its downstream aggregate.src/gateway/server.heartbeat-store-lifecycle.product-proof.test.tstimes out inhandles a queued child notice after same-store replacementat 180,000 ms, then reports 11 unclosed skills watchers. All other executed jobs passed, including security, types, lint, guards, and UI E2E.Independently reproduced on unchanged main
eda09031d5963c8147db8f5eeee0afc61e493196, CI's exact main parent, with an in-tree frozen-lockfile install on AWS Crabboxcbx_a01c2fa13d4c:Result: 1 passed / 1 failed, 245.11 s, with the same 180,000 ms timeout and 11-watchers teardown failure. Both the test and session-state notice owner are byte-identical between that baseline and CI's tested merge
fbfbdfdef6fa21df7156361f64f6123a6c1f7992. Earlier main change #167113 moved notices to ordinary session-event execution; the test still waits for a heartbeat-only prompt. This direct Gateway replacement flow does not enter the CLI restart-drain path. The watcher error follows the unresolved fixture body.Landing uses the authorized inherited-failure exception, preserving the red CI result. No CI rerun, update-branch, or workflow dispatch was used to chase green.