Skip to content

fix(gateway): exit promptly after clean shutdown - #196067

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-process-exit-tail-after-clean-shutdown-20260919
Nov 9, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-process-exit-tail-after-clean-shutdown-20260919

Conversation

@steipete

@steipete steipete commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A clean Gateway shutdown could wait seconds for a referenced handle after its owners had settled. Runtime plugin compilation also left esbuild services resident, and terminating a source-compilation worker could leave a live service and zombie.

User Impact

Runtime plugin compilation now leaves no resident esbuild service or sync-API worker. Clean POSIX Gateway exits bound residual handles to 1,000 ms after finalizers, file logs and output pipes settle. Failed or retained cleanup keeps its existing handling. No configuration, dependency or schema changes.

Why This Change Was Made

Synchronous module hooks invoke the stock one-shot esbuild executable and reap it before returning. Browser catalogs use one lazy, short-lived compiler host per serialized batch. That host uses the async API, captures its native child handles, calls stop(), and awaits their close before exiting; Gateway awaits the host. Warm catalog hits spawn nothing. Registry shutdown joins admitted work and retains compiler cleanup failures separately from request serialization.

The snapshot owns import traversal, with one ordered set replacing duplicate queue/visited bookkeeping. Lazy parsing, cycles, re-exports, revision budgets and optional parse failures remain. Native source diagnostics retain source positions through CLI formatting. Net production growth is 77 lines for explicit ownership, failure receipts and final output draining. The existing POSIX SIGTERM fallback avoids forcing V8 teardown through process.exit().

Watchdog review follow-up

The final bound is one second, retaining margin for healthy natural exits. Before forcing SIGTERM, the existing synchronous one-line diagnostic now includes both active resource counts and _getActiveHandles() constructor-name counts; it contains no addresses or payload data. A real-process regression proves a 600 ms timer exits naturally after finalization (the old 100 ms bound killed it), while a five-second lingering timer remains bounded after its durable finalizer receipt.

The original 34-run Linux/btrfs results classify as 22 natural exits and 12 watchdog-forced exits. All 17 exact-parent runs were natural. At the prior 100 ms candidate bound, all five healthy controls were natural; all ten deliberate lingering-timer runs and both profiled lingering-timer runs were forced. Thus healthy forced exits were 0/5 at 100 ms, or 0/10 including the parent controls. Those original probes did not capture arming, so an exact historical armed-to-exit distribution is unavailable.

Follow-up head: 9241cdbe1235b5eb1eaad4b354b64b283f2d81b4. The 25-run follow-up records arming, JavaScript exit and OS process exit separately on the same synthetic Linux/btrfs shape. Healthy bounds alternate in repeated pairs. Local static checks/review were also active for part of this run; load is recorded. This is a lifecycle-margin measurement, not a new startup/CPU performance claim.

Healthy bound Natural / forced Arm → JS exit median / p95 Arm → OS exit median / p95
100 ms replay 10 / 0 0.230 / 0.444 ms 79.737 / 133.188 ms
Production 1,000 ms 10 / 0 0.224 / 0.328 ms 83.659 / 106.052 ms

At 100 ms, ranges are 0.214–0.444 ms to JavaScript exit and 65.205–133.188 ms to OS exit. At one second, ranges are 0.193–0.328 ms and 70.809–106.052 ms. The process can remain in native teardown past the timer deadline after JavaScript has exited; that is not a watchdog-forced shutdown. The one-second healthy clean-to-process-exit median is 123.764 ms (107.003–148.179 ms).

All five one-second deliberate lingering-handle runs were forced: arm-to-SIGTERM median 1,001.734 ms (1,001.416–1,006.089 ms), clean-to-process-exit median 1,084.242 ms (1,073.370–1,127.458 ms). Every follow-up run has zero startup compiler children and zero tracked survivors at exit. The forced log is one line, for example:

command settled but the process is still alive after 1000ms; active resources: Timeoutx1; active handles: unreported; terminating

Node omits timers from _getActiveHandles(), so the resource summary remains useful alongside handle types. The real Node process test separately verifies Socketx2. The 100 ms replay changes only the test observer's timer delay using --watchdog-ms 100; it is not runtime configuration or an exact historical-binary rerun. The original 34-run classification above comes from the actual retained runs.

Linux build inputs differ from the final follow-up only in test-allocation/assertion updates and equivalent comment/computed-property formatting; normalized emitted watchdog JavaScript matches. Exact-head verification for 9241cdbe1235b5eb1eaad4b354b64b283f2d81b4: CI 42668661311 passed, artifact build 42668660967 passed, and final security/gate reconciliation 42670294565 passed for this PR/head. The commit status API reports success for openclaw/ci-gate, openclaw/security-sensitive-review and openclaw/dependency-review. Both UI-e2e shards also passed. Skipped checks are not counted as proof. The one-second margin is conservative: the healthy samples did not require an increase, but the new 600 ms residual-work regression proves the extra margin preserves natural teardown.

Focused follow-up proof: 175 run-loop tests and 12 CLI process tests pass; Codex autoreview is scoped-clean at P0–P2. The full Linux artifact build passed. Scoped check:changed completed; new assertion-comment placement and underscore-API lint findings were corrected and their affected checks rerun green. The known exact-parent main regressions remain below. The seven added regression-test lines have a matching allocation increase.

Original compiler-owner evidence (100 ms candidate)

These measurements describe the earlier 100 ms candidate at 28f88a9; they do not claim the same forced-tail latency at the final one-second bound.

Controlled Linux arm64/Node 24.22.1 comparison on btrfs, four CPU quota, 16 GiB/no swap: a real Gateway with 24 synthetic plugins exercising both compiler paths, roughly 38 workers, about 3.7 GiB main RSS and 24 owned children. Ten fault runs per revision use alternating A/A–B/B pairs; five healthy controls and two separate allocation profiles per revision. The controlled fault is a referenced 4.8-second timer injected after the clean receipt.

Median metric Exact parent Candidate
Clean receipt → process exit, lingering handle 4,891 ms 181 ms
Tail p95 4,899 ms 188 ms
Healthy tail 132 ms 121 ms
Startup, fault runs 7,500 ms 7,443 ms
Cold catalog batch, fault runs 169 ms 201 ms
Whole-run cgroup CPU, fault runs 13.140 s 13.409 s
Main CPU after clean receipt 34.1 ms 30.8 ms
Main RSS at readiness 3,860 MiB 3,833 MiB
Resident esbuild processes after startup 2 0

The compiler host costs about 32 ms (+19%) per cold catalog batch in fault runs; healthy controls show 174 → 190 ms. Healthy startup is 7,298 → 7,096 ms and CPU 13.059 → 13.082 s. No tracked child survives exit in either arm; candidate has no startup zombie. Spawn-PID tracking catches orphans as well as descendants. A/A repeat tail differences have median 8.0 ms before and 1.0 ms after. This does not measure a precise cgroup-empty timestamp because the harness remains alive.

Separate post-clean allocation samples (n=2 per revision, 32 KiB sampling) have median 3,553,512 → 3,981,672 bytes (+0.41 MiB, +12%). These are sampled tail allocations, not whole-startup allocations or retained heap; profiled timings are excluded from the table.

Idle esbuild alone did not reproduce a multi-second tail; the exact production waiting handle is not claimed as proven. The exact-parent source-owner test independently reproduces the live-service/zombie defect. The controlled timer proves the final exit bound after cleanup.

  • 181 focused tests passed, six skipped. Real-process tests cover main/worker source compilation and browser service reaping. A host-kill regression proves shutdown rejects failed cleanup even after a later warm catalog read; removing the retained receipt makes it fail.
  • Shutdown receipts include 175 run-loop and 11 CLI process tests, finalizer persistence, real SQLite settlement and failed status preservation. Restoring the old settled-exit delay makes the lingering-timer regression fail.
  • Full Linux artifact builds passed for parent e792f74 and candidate a70391b. That earlier measured head, 28f88a9, changes only test allocation; its runtime, dependency and benchmark hashes match the earlier build.
  • Independent Codex review is clean at P0–P2, including a separate review of the final test-allocation correction.
  • Scoped check:changed ran. Local findings were fixed and affected type/lint/format/safety/test-allocation gates rerun successfully. The overall check is not green: exact-parent main regressions remain in changelog attribution (fix(release): align attribution gate with human credit policy #194364, 266a7aa) and unused dashboard authorDisplayName (Dashboards gallery: Display menu with list view, ordering and grouping #194455, cde34f1). Both reproduce on the exact parent and their introducing changes were identified.

Rerun after building the selected revision; use a new btrfs output directory:

node scripts/perf/gateway-process-exit-tail.mjs --output <new-directory> --plugins 24 --samples 10 --leak-ms 4800

Omit --leak-ms for healthy controls; use separate --profile runs for post-clean allocation sampling. Ready for review; no merge requested.

Five initial automation runs had startup_failure with no jobs (ClawSweeper Dispatch, Auto response, Security Review, PR context and evidence, Labeler). Their startup cause is unclassified, not claimed as inherited. The later head-specific Security Review reconciliation and all applicable required commit statuses succeeded as linked above. The PR remains unmerged.

Run runtime plugin compilation in owned one-shot esbuild processes so no compiler service or synchronous API worker remains resident. Join accepted browser catalog work before registry shutdown, then bound residual handles only after final cleanup and output draining.
@clawsweeper

clawsweeper Bot commented Nov 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 app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes scripts Repository scripts size: L labels Nov 9, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 9, 2026
@clawsweeper

clawsweeper Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces resident plugin compiler resources with one-shot processes and shortens the clean Gateway exit fallback after final cleanup.

Example: A clean POSIX Gateway shutdown leaves a referenced 4,800 ms timer.

  • Before: The timer can keep the process alive until it expires.
  • After: After finalizers and output draining finish, the process re-raises SIGTERM if referenced handles remain after 100 ms.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The source review found a coherent repair with meaningful regressions; supplied runtime evidence remains limited while the draft’s Linux comparison is unfinished.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; its body reports a built macOS Gateway scenario, while inspected regression code exercises the production cleanup owners and the declared Linux acceptance run remains pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A Gateway can report clean shutdown while its process continues running because compiler resources or another referenced handle remain.
Reason: The maintainer-authored direction addresses a concrete shutdown contract using existing owners, with no new configuration or persistent format.

Merge readiness

✅ Ready for maintainer review

Keep this useful maintainer-authored repair open; no concrete introduced correctness or security defect was found.

Priority: P2
Reviewed head: 863d511b73e0c6657078f3e8aa3f8e0e624908bc

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The declared Linux baseline/candidate comparison covering fault and healthy shutdowns, startup, catalog latency, CPU, allocation, and child cleanup is still pending.
Agent review details

How this fits together

Plugin source loading and browser import discovery invoke esbuild; registry retirement joins accepted catalog work, and CLI finalization drains logs and output before bounding residual process handles.

flowchart TD
  A[Plugin source and browser assets] --> B[Existing compilation owners]
  B --> C[One-shot esbuild processes]
  C --> D[Compiled modules and import metadata]
  D --> E[Registry shutdown joins accepted work]
  E --> F[CLI finalizers and output draining]
  F --> G[Natural exit or settled SIGTERM fallback]
Loading

Technical review

Best possible solution:

Retain the focused compiler-lifetime and cleanup-ordering repair, completing the author’s declared Linux acceptance comparison before making the draft ready.

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

Current-main source permits a referenced timer to retain a clean Gateway until the timer expires or the 10-second watchdog fires; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The change uses existing compilation, registry lifecycle, and CLI finalization owners while preserving lazy compilation, synchronous module hooks, preload traversal, and failed-cleanup handling.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Settled Gateway exit delay changes intended behavior with a stated reason (d6c8ad3: Bound leaked handles after all finalization while preserving supervisor exit semantics.)
  • Natural CLI shutdown and finalization keeps the original intent (98813c2: Finish owned work and exit naturally without forced V8 teardown.)
  • Plugin source compilation changes intended behavior with a stated reason (c8eab36: Use Jiti and esbuild while preserving synchronous and native plugin loading after the compiler migration.)
  • Lazy source diagnostics keeps the original intent (fa7f5f9: Avoid successful-path compiler work for Jiti and retain source-relative diagnostics on failure.)
  • Browser static import discovery changes intended behavior with a stated reason (0d03021: Preserve transitive preload hints using native import metadata instead of main-thread AST construction.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +54, Tests +148, Docs +5, Other +290. Total +497 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 5 132 78 +54
Tests 6 152 4 +148
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 2 290 0 +290
Total 14 579 82 +497

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Runtime production versus regression growth Runtime production +132/-78; tests and support +152/-4 The net 54 runtime lines replace resident compiler APIs and join existing cleanup owners; the regressions cover compiler reaping, admitted catalog settlement, and finalization before bounded exit.

Labels

Label changes:

  • add P2: This improves clean Gateway stop latency and compiler resource ownership without establishing an urgent core-runtime outage.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This improves clean Gateway stop latency and compiler resource ownership without establishing an urgent core-runtime outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Complete the declared Linux comparison and investigate any startup, catalog-latency, CPU, or allocation regression before marking the draft ready.

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 execution lanes are retired.

Reviewed November 9, 2026, 10:50 AM ET / 15:50 UTC.

@steipete
steipete marked this pull request as ready for review November 9, 2026 17:31
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T17:54:14.066931Z 9241cdb New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 28f88a9573

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +51 to +54
child = spawn(process.execPath, ["-e", browserCompilerHost, require.resolve("esbuild")], {
windowsHide: true,
stdio: ["ignore", "ignore", "inherit", "ipc"],
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Launch the compiler host in standalone script mode

When the Gateway runs from a compiled Bun standalone executable, process.execPath is the OpenClaw application, not a generic JavaScript runner. This spawn inherits the application environment without enabling BUN_BE_BUN, so it launches the OpenClaw entrypoint instead of evaluating browserCompilerHost. The existing resolveRuntimeScriptEnv() owner in cli-invocation.mjs explicitly documents that a compiled executable needs this mode to execute scripts. Consequently, a cold plugin browser catalog cannot complete its compiler exchange, and compiler disposal can reject the catalog request and retain a shutdown failure. Use the standalone-aware runtime environment when launching this host.

Useful? React with 👍 / 👎.

@steipete

steipete commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Landing note (maintainer review). On Team, the Gateway exited 3.4–4.8 s after "[shutdown] completed cleanly" on planned restarts. systemd went inactive 2.5–4.2 ms after the main exit, so the wait was Node itself. A live esbuild --service child and an unreaped esbuild zombie were present exactly in the long-tail stops. The Gateway now owns and reaps its plugin compiler processes, and compiler cleanup failures stay visible. After settled cleanup, logs and output are flushed and then a 1,000 ms exit watchdog is armed. A forced exit logs one line naming the remaining resource and handle types. No dependency patch.
Linux/btrfs: lingering-handle tail 4,891 → ~180 ms (1.08 s with a deliberately lingering timer under the 1 s bound). Healthy runs 10/10 natural at both 100 ms and 1,000 ms, with armed → OS exit p95 ~106–133 ms. Compiler children are zero after startup and at exit. Production +77 lines; exact-head CI green.

@steipete
steipete merged commit a25c1f3 into main Nov 9, 2026
121 of 122 checks passed
@steipete
steipete deleted the steipete/perf-micro-process-exit-tail-after-clean-shutdown-20260919 branch November 9, 2026 18:05
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 10, 2026
* fix(gateway): exit promptly after clean shutdown

Run runtime plugin compilation in owned one-shot esbuild processes so no compiler service or synchronous API worker remains resident. Join accepted browser catalog work before registry shutdown, then bound residual handles only after final cleanup and output draining.

* fix(gateway): reap batched browser compilers

* test(gateway): align compiler lifecycle test allocation

* fix(gateway): preserve natural exit margin and report lingering handles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L 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