Skip to content

perf(gateway): settle queued wakes before shutdown drain - #167666

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-shutdown-drain-full-budget-20260919
Oct 9, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-shutdown-drain-full-budget-20260919

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

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:

Synthetic workload Base Patched Persisted result
Only queued heartbeat work at SIGTERM 75.517 s 1.619 s All 8 committed replies and terminal done state retained
Accepted terminal write still pending at SIGTERM 75.448 s 65.575 s All 8 replies retained; exit waited for the real terminal write under rig load

The 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 (provider blacksmith-testbox, profile openclaw-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 command pnpm test src/infra/session-event-wake-concurrency.test.ts --maxWorkers=1 passed all 14 tests in 2.05 s wall time (warm) on that CI-class runner. PR CI run 37895297806 completed 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.mts fails identically on this candidate and a clean, independently installed main checkout at 73fdd3d2c6b249c7f4494990856f88713a634617 on the same Testbox. These paths are outside this PR:

  • src/agents/cli-runner/tool-authority.ts: bindCliQuestionAnswerAuthority
  • src/auto-reply/reply/session-event-handoff.ts: prepareSessionEventTargetForHost
  • src/config/sessions/session-accessor.sqlite-entry-cache-publication.ts: readSessionEntryCreationTransition
  • src/infra/heartbeat-events-filter.ts: RESTART_CONTINUATION_CONTEXT_PREFIX

The last two also fail the full-tree scan. The guard remained enabled. All commands after that guard in the unchanged check-changed --staged --dry-run plan 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
   274ms  ok         conflict markers
   292ms  ok         line-cap growth ratchet
   6.02s  ok         max-lines suppression ratchet
  12.16s  ok         assertion SAFETY comment ratchet
   2.46s  ok         SQLite worker ratchet
   1.06s  ok         test timeout race ratchet
  10.99s  ok         first-party mock export ratchet
   188ms  ok         changelog attributions
   145ms  ok         doctor deprecation registry
   187ms  ok         guarded extension wildcard re-exports
   163ms  ok         plugin-sdk wildcard re-exports
   271ms  ok         duplicate scan target coverage
   252ms  ok         dependency pin guard
   219ms  ok         format changed files
   3.85s  ok         config docs baseline
   1.87s  ok         plugin boundaries
   7.69s  ok         wrapper shadowing
   460ms  ok         package patch guard
   266ms  ok         test temp creation report (warning-only)
  71.72s  ok         core tsgo graph boundary
  53.31s  ok         typecheck core
1210.64s  ok         typecheck core tests
   5.88s  ok         coercion helper declaration guard
   7.16s  ok         deprecated API usage
  73.57s  failed:1   dead export scan (skip with OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1)
Focused and sibling test commands
pnpm test src/gateway/server-close.queued-heartbeat.test.ts src/infra/session-event-wake-concurrency.test.ts src/infra/gateway-active-work.test.ts src/cli/gateway-cli/run-loop.test.ts --maxWorkers=1
pnpm test src/infra/session-event-wake*.test.ts src/infra/heartbeat-wake*.test.ts src/gateway/server-close.queued-heartbeat.test.ts --maxWorkers=1
node scripts/run-vitest.mjs src/infra/session-event-wake*.test.ts src/infra/heartbeat-wake*.test.ts src/gateway/server-close*.test.ts src/gateway/session-lifecycle-persistence-owner.test.ts src/cli/gateway-cli/run-loop-shutdown-budget.test.ts

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.ts times out in handles a queued child notice after same-store replacement at 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 Crabbox cbx_a01c2fa13d4c:

node scripts/run-vitest.mjs src/gateway/server.heartbeat-store-lifecycle.product-proof.test.ts

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.

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.
@clawsweeper

clawsweeper Bot commented Oct 9, 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: S labels Oct 9, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Oct 9, 2026
@steipete
steipete marked this pull request as ready for review October 9, 2026 06:46
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The 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.

  • Before: The reported Linux SIGTERM run takes 75.517 seconds to exit.
  • After: The reported patched run exits in 1.619 seconds with all eight committed replies and terminal done state retained.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful owner-level repair with sufficient shutdown observations, meaningful regressions, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied Linux real-Gateway SIGTERM observations exercise the changed wake owner through CronService and shutdown: queued-only work exits promptly, while an accepted terminal write still delays exit until persistence settles and all eight replies remain present. Synthetic state does not establish historical incident attribution. No stored-data format, migration, or persisted setting changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Stopping or restarting an otherwise idle Gateway can wait the full drain budget because a queued heartbeat cannot finish.
Reason: This repairs a concrete shutdown cycle while preserving the designed protection for running work. Prior merged area history supports the recorded direction without a new product decision.

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
Reviewed head: 4ed8e546e28405c5457e245efa60bcea6df8f086

Before merge

None.

Findings

None.

Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduced behavior: The pinned introduction diff adds shutdown settlement to the existing wake owner and enriches existing diagnostics without adding another scheduler, configuration option, or persistent format. (src/infra/session-event-wake.ts:553, 4ed8e546e284)
  • Current-main necessity: The changed production owners and restart documentation are unchanged between the merge base and fetched main. The unpatched wake dispatcher retries admission failures, while cron disables its watchdog during queue waits and CLI shutdown joins process activity before server close. (src/infra/session-event-wake.ts:446, 94c0f0d589ab)
  • Execution and restart boundaries: The drain listener settles pending entries without aborting active handlers. Enqueues during drain settle their callers, scheduling remains fenced, and queued notifications survive for handler replacement. Existing admission and store-current checks remain intact. (src/infra/session-event-wake.ts:556, 4ed8e546e284)
  • Real shutdown observations: The complete supplied PR body, captured with sourceRevision d2ec78ea25effe3bb0678fdd3d0d0aaa1d1f66bc99ed1c138fd0882e81444a8c, reports Linux real-Gateway OS SIGTERM runs through CronService, wake admission, SQLite transcript writes, and terminal persistence. Queued-only shutdown improves from 75.517 to 1.619 seconds; a pending accepted terminal write still holds patched exit until settlement, with all eight replies retained. Synthetic state limits historical incident attribution, not coverage of this shutdown path. (4ed8e546e284)
  • Meaningful regression coverage: The extended close regression requires heartbeat settlement before server close while an admitted cron sibling continues holding resource retirement. The wake-owner regression covers queued, retrying, late, and admitted wakes plus notification delivery after replacement. The body reports the extended regression failing on base and candidate suites passing; this read-only review did not execute tests. (src/gateway/server-close.queued-heartbeat.test.ts:105, 4ed8e546e284)
  • Notification-retention provenance: fix(cron): prevent heartbeat catch-up from blocking startup #151319 established skipped waiter settlement when a handler is unavailable while preserving queued notifications and busy retries. Its introducing patch was inspected against its recorded parent, and this PR preserves that distinction. (src/infra/session-event-wake.ts:578, 460b6769d1ff)

Likely related people:

  • Peter Steinberger: Raw commit 460b676 adds src/infra/session-event-wake.ts:471 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 460b6769d1ff; files: src/infra/session-event-wake.ts)

PR surface

Source +40, Tests +99, Docs +5. Total +144 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 61 21 +40
Tests 4 102 3 +99
Docs 1 6 1 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 169 25 +144

Review metrics

Metric Value Why it matters
Production and test growth Production +40 net lines; tests and test support +99 net lines The production growth preserves queued versus admitted lifecycle ownership and reuses existing diagnostics; regressions protect shutdown ordering and restart retention.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This bounded lifecycle repair prevents queued heartbeat work from unnecessarily consuming the shutdown drain budget.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-09T06:45:16.580Z sha 4ed8e54 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-09T06:51:47.874Z sha 4ed8e54 :: needs maintainer review before merge. :: none

Reviewed October 9, 2026, 3:42 AM ET / 07:42 UTC (Revision 3).

@steipete
steipete enabled auto-merge (squash) October 9, 2026 06:48
@steipete
steipete merged commit 8a4ed22 into main Oct 9, 2026
209 of 214 checks passed
@steipete
steipete deleted the steipete/perf-micro-shutdown-drain-full-budget-20260919 branch October 9, 2026 07:42
@steipete

steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Merged with the operator-authorized inherited-failure exception in 8a4ed22.

The only failed CI root was checks-node-changed-compact-small-19: server.heartbeat-store-lifecycle.product-proof.test.ts timed out after 180 seconds in the same-store replacement case, followed by 11 unclosed skills watchers. The identical failure reproduced on unchanged main eda09031d5963c8147db8f5eeee0afc61e493196 on AWS Crabbox cbx_a01c2fa13d4c (1 passed / 1 failed, 245.11 seconds). The test still waits for a heartbeat prompt after #167113 moved these notices to ordinary session events. Both relevant source files match CI's baseline and tested merge.

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.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…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.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 20, 2026
…, 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]>
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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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