Skip to content

fix(gateway): stop post-ready sidecar timers on close - #117242

Merged
steipete merged 2 commits into
mainfrom
fix/gateway-postready-leaks
Aug 1, 2026
Merged

steipete merged 2 commits into
mainfrom
fix/gateway-postready-leaks

Conversation

@steipete

@steipete steipete commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway post-ready background work could outlive the gateway that scheduled it. In src/gateway/server-startup-post-attach.ts:

  • Two schedulePostReadySidecarTask call sites (sidecars.session-locks, sidecars.restart-sentinel) discarded their returned {stop} handles, making them unreachable from stopRegisteredPostReadySidecars — the tasks kept running after gateway close.
  • scheduleRestartSentinelWakeAfterReady fired a bare 750 ms setTimeout with no retained handle, no unref(), and no closing check — launched from one of the discarded sidecars, it is concrete "background work that begins after shutdown".
  • The gateway:startup internal hook fired via an unretained 250 ms setTimeout with no closing guard.

This matters because SIGUSR1 restarts a fresh gateway in the same process (src/cli/gateway-cli/run-loop.ts): old-generation timers must not fire into the replacement instance.

Additionally, the agentRuntimePluginPrewarm option was dead config: finishGatewayStartup (the sole production caller) never passed it, so the guard ?.enabled !== false was always true.

Why This Change Was Made

All post-ready work now belongs to the gateway generation that scheduled it: the two discarded handles are registered in postReadySidecars, and both raw timers go through a small shared scheduleGatewayGenerationTimer helper (retained handle, unref, stopped-check, cancel-on-close). The dead agentRuntimePluginPrewarm option is deleted rather than kept: prewarm behavior is unchanged (still enabled, same config fallback chain) — the option provably had no production caller on origin/main, and startGatewayPostAttachRuntime is gateway-internal, not shipped SDK.

Structured review raised preserving the option's opt-out; rejected after verification: zero production callers exist, the repo's policy is to remove stale internal args cleanly, and hypothetical callers do not warrant compat.

User Impact

No behavior change during normal operation. On shutdown and in-process restart (SIGUSR1), stale session-lock cleanup, restart-sentinel work, and the startup hook can no longer execute into a closing or replacement gateway — eliminating a class of post-shutdown races.

Evidence

  • node scripts/run-vitest.mjs src/gateway/server-startup-post-attach.test.ts — 63/63 pass (also run as autoreview parallel tests), including new close-before-fire coverage for all three handles.
  • Close/reload lifecycle tests: 155/155 pass.
  • Structured autoreview (Codex, gpt-5.6-sol, high): one P2 finding, rejected with the caller-verification above; no other findings.
  • Prod diff +125/−79; the shared timer helper replaces two duplicated raw setTimeout blocks.

🤖 Generated with Claude Code

Runtime proof (added post-review)

Close-race transcript on an integration build containing this PR: SIGTERM 40 ms after ready (inside both deferred-timer windows, with gateway-start-hooks=scheduled recorded), no callback output after "shutting down", and process exit in 111 ms — impossible pre-fix, when the 750 ms sentinel wake held the event loop with no handle or unref. Full transcript: #117242 (comment)

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Aug 1, 2026
@steipete
steipete marked this pull request as ready for review August 1, 2026 05:42
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Aug 1, 2026
@clawsweeper

clawsweeper Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 1, 2026, 1:57 AM ET / 05:57 UTC.

ClawSweeper review

What this changes

The PR registers delayed post-ready gateway sidecars and startup-hook timers with the gateway generation so close cancels them before they can run into an in-process replacement gateway.

Merge readiness

⛔ Blocked until real behavior proof is added - 3 items remain

Keep this maintainer-labeled PR open: the lifecycle fix follows the existing gateway close-owner boundary and has focused test coverage, but it still needs inspectable after-fix runtime proof before merge.

Priority: P2
Reviewed head: e3ad8c6c3f3b5aedf5c5246e88a1b64ef0a595be

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The code and focused regression coverage are coherent, but real behavior proof remains a merge gate.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The PR body reports focused tests, but it has no inspectable after-fix runtime artifact proving that a closed generation's callbacks remain suppressed during shutdown or in-process restart; add redacted terminal output, logs, or a recording. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The PR body reports focused tests, but it has no inspectable after-fix runtime artifact proving that a closed generation's callbacks remain suppressed during shutdown or in-process restart; add redacted terminal output, logs, or a recording. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 5 items Lifecycle owner: Current main transfers the post-ready sidecar list into runtime state, and the gateway lifecycle atomically clears that list before awaiting every handle's stop method; the proposed branch extends that same owner boundary to the delayed callbacks.
PR implementation: The proposed helper retains a timeout handle, calls unref, records stopped state, clears the timer on stop, and checks that state after lazy loading the restart-sentinel module; the startup hook is also registered in the post-ready sidecar list.
Focused regression coverage: The PR adds a fake-timer close-before-fire case that stops the registered post-ready list, releases delayed work, and asserts that the startup hook, session-lock cleanup, and restart-sentinel path do not run.
Findings None None.
Security None None.

How this fits together

Gateway startup schedules post-ready maintenance, cleanup, and internal-hook work after the server is ready. The gateway lifecycle stores those handles and stops them during close, while the SIGUSR1 run loop starts the next gateway in the same process.

flowchart LR
  A[Gateway ready] --> B[Post-ready sidecars]
  B --> C[Delayed hook and sentinel timers]
  C --> D[Gateway close or SIGUSR1 restart]
  D --> E[Registered stop handles]
  E --> F[Old generation work cancelled]
  F --> G[Replacement gateway]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The PR body reports focused tests, but it has no inspectable after-fix runtime artifact proving that a closed generation's callbacks remain suppressed during shutdown or in-process restart; add redacted terminal output, logs, or a recording. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - Before merge, add an inspectable redacted terminal trace, runtime log, or recording from close or SIGUSR1 restart showing that old-generation callbacks do not run after shutdown.
  • Resolve merge risk (P1) - The PR changes gateway close semantics; although the focused tests cover cancellation before the delayed callbacks fire, the operational restart path still needs real-behavior proof.
Agent review details

Security

None.

PR surface

Source +46, Tests +60. Total +106 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 125 79 +46
Tests 1 77 17 +60
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 202 96 +106

Review metrics

None.

Merge-risk options

Maintainer options:

  1. Add lifecycle proof before merge (recommended)
    Keep the current repair and provide redacted runtime output from close or SIGUSR1 restart that shows stale generation callbacks stay suppressed.
  2. Pause for owner review
    Pause if the gateway lifecycle owners want a different definition of which already-admitted post-ready work may finish after close.

Technical review

Best possible solution:

Keep the generation-owned timer and sidecar registration approach, then attach redacted shutdown or SIGUSR1 restart evidence demonstrating that the old generation cannot execute delayed startup work after close.

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

Yes, at source level: start post-ready work, begin close before its deferred callback fires, then advance the timer or initiate SIGUSR1 restart and verify no callback reaches the old generation. The PR's focused fake-timer regression test exercises that cancellation boundary, but this review did not execute it.

Is this the best way to solve the issue?

Yes. Registering each delayed callback with the existing post-ready lifecycle owner is narrower and more maintainable than adding downstream guards or allowing old-generation timers to survive close.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 0cd33bad88c7.

Labels

Label justifications:

  • P2: This is a bounded gateway shutdown and in-process restart race rather than a demonstrated service-wide outage.
  • merge-risk: 🚨 availability: The patch changes close-time timer cancellation in the gateway, so an error could either permit stale work after restart or suppress required post-ready work.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body reports focused tests, but it has no inspectable after-fix runtime artifact proving that a closed generation's callbacks remain suppressed during shutdown or in-process restart; add redacted terminal output, logs, or a recording. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Lifecycle owner: Current main transfers the post-ready sidecar list into runtime state, and the gateway lifecycle atomically clears that list before awaiting every handle's stop method; the proposed branch extends that same owner boundary to the delayed callbacks. (src/gateway/server-lifecycle.ts:366, 0cd33bad88c7)
  • PR implementation: The proposed helper retains a timeout handle, calls unref, records stopped state, clears the timer on stop, and checks that state after lazy loading the restart-sentinel module; the startup hook is also registered in the post-ready sidecar list. (src/gateway/server-startup-post-attach.ts:404, e3ad8c6c3f3b)
  • Focused regression coverage: The PR adds a fake-timer close-before-fire case that stops the registered post-ready list, releases delayed work, and asserts that the startup hook, session-lock cleanup, and restart-sentinel path do not run. (src/gateway/server-startup-post-attach.test.ts:2545, e3ad8c6c3f3b)
  • Feature provenance: The current post-ready background-work structure appears to date to the recent gateway change that yielded before post-ready work, making its author a relevant routing contact. It is on current main and is not contained in a local release tag check. (src/gateway/server-startup-post-attach.ts:365, 65f3e42f2433)
  • Protected handling: The supplied GitHub context includes the protected maintainer label, so this PR requires explicit maintainer handling rather than an automated cleanup outcome.

Likely related people:

  • Jason (Json): Authored the current-main change that introduced the post-ready background-work structure this PR repairs. (role: introduced adjacent lifecycle behavior; confidence: high; commits: 65f3e42f2433; files: src/gateway/server-startup-post-attach.ts)
  • steipete: Recent current-main history for this startup module includes Peter Steinberger's gateway/model startup work, and the proposed fix is in the same lifecycle surface. (role: recent area contributor; confidence: medium; commits: 09a64f7ab00f, 2d2ddc43d0dc; files: src/gateway/server-startup-post-attach.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Attach redacted terminal or runtime-log evidence from gateway close or SIGUSR1 restart showing no old-generation callback runs.
  • Update the PR body with that proof; if a fresh review does not trigger automatically, ask a maintainer to comment @clawsweeper re-review.

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 (1 earlier review cycle)
  • reviewed 2026-08-01T05:48:26.405Z sha efb0f06 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Aug 1, 2026
@steipete

steipete commented Aug 1, 2026

Copy link
Copy Markdown
Contributor Author

Runtime proof: close racing the deferred timers — scheduled callbacks stay suppressed (redacted transcript)

Real-behavior proof per review: ephemeral gateway (integration build containing this PR; isolated state dir, loopback) killed with SIGTERM 40 ms after ready — inside both deferred windows this PR governs (the 250 ms gateway:startup hook timer and the 750 ms restart-sentinel wake), with the log confirming the hook had been scheduled:

23:00:54.029 [gateway] http server listening (3 plugins: anthropic, memory-core, ollama; 1.3s)
23:00:54.036 [gateway] starting channels and sidecars...
23:00:54.064 [gateway] startup outcomes: ... gateway-start-hooks=scheduled; ...
23:00:54.065 [gateway] ready
23:00:54.085 [heartbeat] started
23:00:54.104 [admission] closed: restart drain
23:00:54.105 [gateway] received SIGTERM; shutting down
(no further output — log ends; process exited)
exit_after_ms=111

Two suppression facts in one artifact:

  1. gateway-start-hooks=scheduled at +0 ms, SIGTERM at +40 ms, and no hook execution line ever appears — the close path cancelled the scheduled 250 ms callback (previously unretained and uncancellable).
  2. Process exit in 111 ms. Before this PR the 750 ms restart-sentinel wake was a bare setTimeout with no handle and no unref() — it would have held the event loop and/or fired into a closing gateway. Post-fix the process is gone well before that timer's deadline.

Complementing the earlier steady-state proof on the same build (clean 44 ms shutdown with zero post-close task output after the timers had already fired), and the fake-timer regression tests asserting close-before-fire for all three handles.

🤖 Generated with Claude Code

@steipete
steipete merged commit 1b84119 into main Aug 1, 2026
130 checks passed
@steipete
steipete deleted the fix/gateway-postready-leaks branch August 1, 2026 06:03
@steipete

steipete commented Aug 1, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 1, 2026
* fix(gateway): stop post-ready sidecar timers on close

* fix(gateway): return promise from generation timer admission callback
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant