Skip to content

fix(plugins): release preparation workers after plugin startup - #177141

Open
vincentkoc wants to merge 10 commits into
mainfrom
fix/plugin-source-state-handoff-20261019
Open

vincentkoc wants to merge 10 commits into
mainfrom
fix/plugin-source-state-handoff-20261019

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Landing hold: the completed 20-run cold-cache comparison fails the recorded acceptance rule. Do not merge until performance acceptance is resolved. One-plugin median RSS rises 8.0%; five-plugin median RSS falls 3.2% but startup rises 34.0%. Worker retirement alone is not an accepted process-memory win.

What Problem This Solves

External plugins keep their source-preparation workers alive for as long as their loaded artifacts survive, retaining an isolate per plugin after startup work has finished.

User Impact

The fix transfers prepared source facts to the loaded artifact owner, then waits for physical worker exit before publishing loaded plugins. Lazy imports, captured source bytes, native-library custody, and reload recovery remain functional. The paired workload below does not establish an acceptable process-memory improvement; this implementation remains under investigation.

Why This Change Was Made

Preparation workers should own initial capture work. The loaded plugin instance should own the resulting source artifact and its lazy execution state. Moving prepared facts to that existing owner removes the need for a permanent preparation isolate.

Evidence

  • Source-reviewed regression loads a real external plugin, requires preparation workers to have exited while its registered tool remains live, then edits the original helper before its first lazy import and checks the captured value.

  • The existing Gateway concurrency workload now samples the physical worker census through diagnostics.lanes before and after the timed load window.

  • Targeted formatting, staged diff checks, and the line-cap ratchet passed. The initial Testbox allocation queued and was stopped without running tests; local proof uses the native PR checkout with its own qualified dependencies. The baseline regression fails on the retained preparation worker; candidate retirement, lazy imports, native custody, recovery, and independent capture disposal tests pass. Node sibling coverage passed: 146 tests, with 7 platform skips. Core and script type checks and targeted lint passed. Independent reviews found no remaining product finding.

  • The first real baseline smoke completed its four requested agent turns but failed teardown because the generic child stopper forced SIGKILL after two seconds. It is excluded from performance evidence. Both measured variants used the same committed benchmark harness from 7d63c2fd41aaf978ecaff8a02cb347518cd2fb4b, which uses acknowledged Gateway shutdown and rejects every forced child cleanup. Slow-shutdown CPU-profile flushing and forced-descendant failure are covered by CLI tests. Runtime build identities remain separate: baseline 097f40bde788c85c4696eaaad78a9a13424cbbd5, candidate 7d63c2fd41aaf978ecaff8a02cb347518cd2fb4b. Both receive only the same benchmark-script and shared benchmark-environment overlays from 7d63c2fd41aaf978ecaff8a02cb347518cd2fb4b; the final source also removes a type-only import cycle found by hosted CI. The nine affected modules emit byte-identical JavaScript before and after that type repair, and the final candidate was rebuilt from its exact source head.

  • Final candidate build, core/script type checks, and the full import-cycle guard passed (zero cycles). The architecture failure on the previous CI head was introduced by this branch and is repaired here. The subsequent CI failure in the Doctor readiness test is detailed below.

Ownership and scope

The plugin instance owns the prepared source artifact. Preparation borrows host capture/native custody, transfers plain facts, settles admission publication, and physically exits before registration. The existing artifact builder resumes lazy capture and recovery locally. The worker RPC codec and retained artifact proxy are removed. Native admission borrowers survive cache retirement until their owning artifacts are disposed. Failed physical stops remain reachable for terminal cleanup retries.

  • Production/tooling: +1,181 / -1,482 lines, net -301; tests/fixtures: +532 / -511, net +21. Documentation and wrapper inventory: +2 / -1.
  • Covered sibling contracts: lazy imports after source mutation, recorded misses/deferred targets, aliases, native-root custody, publication settlement, worker-stop retries, recovery, and independent artifact disposal. Node and Bun focused proof passed.
  • No config/default surface, SQLite schema, Gateway protocol, or public plugin SDK API changes.
  • The original partial-report contract is preserved: the first worker census is recorded before load and unavailable after data is explicit null. The CLI regression fails before this fix and passes after it.
  • Release-note context: external plugins release their preparation isolate after startup while retaining lazy import and recovery behavior.
  • Follow-up outside this change: attribute the independently retained transcript/background worker pools under load and after quiescence; worker counts alone do not establish their individual RSS cost.

The first completed pair is diagnostic-only: baseline had already populated its build-qualified worker bytecode cache during the earlier smoke, while the candidate had not. Both formerly used a shared system temp directory. RSS was 2,303 vs 2,070 MiB, startup 6,425 vs 12,955 ms, and load CPU 2,535 vs 4,248 ms; these are not accepted improvement/regression estimates. Provider request counts and bytes matched. The common harness now confines TMPDIR/TMP/TEMP to each fixture, so every process starts with a fresh worker cache without changing main-thread cache policy. All 47 focused benchmark tests passed. The completed paired series used that explicit cold-cache condition; the same acceptance thresholds below remain binding.

Performance acceptance rule, recorded before the first run:

  • Build baseline and candidate separately. Use the same Node runtime and host; run serially with host load and available memory recorded.
  • Real isolated Gateway, real transport and agent turns, mock provider; test both 1 and 5 external plugins, concurrency 1, one agent warmup turn, three measured turns, one run per invocation, no discarded warmup runs.
  • Interleave baseline/candidate, at least five samples each per plugin count. Report cold startup separately from warm turn load, with median, p95, and range for RSS, peak RSS, setup, turn latency, process/main CPU, and workload counts.
  • Required count result: zero live source-preparation workers after loading and after turns on the candidate, with all configured plugins loaded and every launched turn verified. Lazy imports and recovery must remain functional.
  • Acceptance: lower median post-load total RSS, with a repeatable reduction across samples; no material regression in startup, CPU, peak RSS, or turn latency. Any metric worsening by 20% or more stops landing pending explicit owner acceptance. Failed or incomplete workload runs do not count as performance evidence.

Command shape (repeat with --plugin-count 5):

pnpm test:gateway:concurrency --entry dist/entry.js --gateway-runtime node --provider mock --plugin-count 1 --concurrency 1 --agent-warmup-turns 1 --turns-per-session 3 --runs 1 --warmup 0 --json

Completed paired results

Five interleaved baseline/candidate pairs per plugin count; all 20 runs included. Baseline 097f40b; candidate and common harness 7d63c2f. Separate compiled generations, Node 26.7.0, macOS arm64, 18 logical CPUs, 48 GiB physical memory, fixture-owned cold worker caches. With five runs, nearest-rank p95 is the maximum, not a stable population tail.

1 external plugin

Metric Baseline median / p95 [range] Candidate median / p95 [range] Median change
RSS after MiB 2,042.8 / 2,418.8 [1,793.7–2,418.8] 2,205.6 / 2,324.4 [1,966.3–2,324.4] +8.0%
Peak RSS MiB 2,142.2 / 2,491.7 [1,852.2–2,491.7] 2,236.2 / 2,392.2 [2,134.4–2,392.2] +4.4%
Startup ms 6,676.2 / 8,206.7 [5,778.0–8,206.7] 6,516.0 / 7,595.8 [5,574.7–7,595.8] -2.4%
Setup ms 5,026.4 / 5,460.1 [4,324.4–5,460.1] 4,619.2 / 5,952.7 [4,071.3–5,952.7] -8.1%
Turn load ms 4,112.6 / 4,329.1 [3,816.9–4,329.1] 3,919.7 / 4,690.3 [3,810.2–4,690.3] -4.7%
Process CPU ms 3,471.2 / 4,196.4 [2,700.2–4,196.4] 3,116.7 / 3,143.6 [2,514.6–3,143.6] -10.2%
Main CPU ms 942.0 / 957.0 [680.6–957.0] 791.6 / 876.9 [656.9–876.9] -16.0%

5 external plugins

Metric Baseline median / p95 [range] Candidate median / p95 [range] Median change
RSS after MiB 2,047.9 / 2,528.0 [2,013.0–2,528.0] 1,982.4 / 2,263.3 [1,864.0–2,263.3] -3.2%
Peak RSS MiB 2,134.7 / 2,595.0 [2,088.2–2,595.0] 2,104.4 / 2,368.9 [1,982.4–2,368.9] -1.4%
Startup ms 7,437.3 / 9,320.1 [6,655.7–9,320.1] 9,962.4 / 11,785.2 [7,582.4–11,785.2] +34.0%
Setup ms 5,391.0 / 7,336.0 [4,143.9–7,336.0] 4,487.5 / 6,506.3 [4,416.0–6,506.3] -16.8%
Turn load ms 4,212.7 / 6,176.6 [3,814.7–6,176.6] 4,009.5 / 4,116.3 [3,718.0–4,116.3] -4.8%
Process CPU ms 3,795.4 / 4,800.5 [2,345.6–4,800.5] 3,242.1 / 3,687.7 [2,507.8–3,687.7] -14.6%
Main CPU ms 1,073.8 / 1,137.3 [660.1–1,137.3] 854.2 / 977.3 [659.0–977.3] -20.4%

All 20 runs completed one verified warmup plus three verified measured turns, registered every synthetic plugin, and exited cleanly. Preparation census was 1 or 5 on baseline and zero on every candidate before and after load. Both cohorts performed the same benchmark-turn and activity-recap inference work; background embedding timing crossed the warmup/load boundary and adaptive probe counts varied. These remain comparability limits. No high or low sample was discarded.

One-plugin paired RSS changes were +260.00, -213.20, -76.53, +530.73, and -380.05 MiB. Three of five pairs improved, but the cohort median rose. The fourth pair exceeded the 20% RSS/peak regression threshold. Worst per-run p95 probe tails also worsened (readyz +73.6%, sessions.list +74.5%, Control UI +41.3%), although pooled p95 improved. The five-plugin startup median and p95 worsened by 34.0% and 26.4%. These failures prevent landing under the recorded rule.

Host load and free memory varied; one-plugin one-minute host load ranged 11.26–25.63, and one candidate started with 469 MiB free. This is not a causal attribution or a waiver. Much of the first two five-plugin startup gaps precedes preparation; separate startup and load CPU profiles are being collected to locate the cost.

CI test-lifetime repair

The Doctor readiness test granted each of three sequential child phases 30 seconds but granted their parent only 45 seconds. In the failed CI run, Doctor completed after 24.4 seconds and Gateway readiness after 41.3 seconds; the parent aborted the status child at 45.1 seconds, before its own deadline. The existing getCliProcessTestTimeout helper now derives the parent budget from all three unchanged 30-second phase budgets. Assertions, startup coverage, cancellation and cleanup remain intact. The focused process test and targeted test lint passed; independent review found no scoped issue. Test-only head c9f4644 does not alter the measured runtime at 7d63c2f or resolve the performance hold.

Instrumented attribution follow-up

A separate five-plugin profile pair completed the workload and clean shutdown. These instrumented runs are diagnostic only and do not replace the 20 unprofiled samples above. Six transcript threads identified by loaded execution frames retained 378.9 MiB baseline and 372.1 MiB candidate of aggregate used V8 heap at the final sampled instant. This is worker heap, not attributed RSS; two census transcript workers lacked identity mapping, and idle preparation isolates lacked heap samples. Each run also had one worker retire before profiler stop. The next investigation targets read-only transcript paths importing writable database/schema modules, with unchanged read/admission/lifecycle behavior as a required contract. No memory gain from that follow-up is established.

Validation follow-up

A subsequent full-tree and production unused-export scan on this head identified two exports left behind by the preparation-worker handoff: recordPluginNativeLoad and subscribePluginNativeLoads in src/plugins/plugin-source-capture-native-loads.ts. The recorder is still used internally, but its export has no consumer; the subscription and observer dispatch have no remaining consumer. This is an unresolved cleanup in this held PR. The independent transcript-reader change does not modify these files and does not resolve the performance hold.

@vincentkoc vincentkoc self-assigned this Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 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 scripts Repository scripts size: S labels Oct 19, 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head 097f40bde788c85c4696eaaad78a9a13424cbbd5, but the PR head is now c9f464482229bc5677fc8c0f8f8176ff6fc913cf. Its old verdict and PR readiness labels are no longer current.

Next step
Run or wait for a fresh ClawSweeper review on the current PR head.

Review history (1 earlier review cycle)
  • reviewed 2026-10-19T08:45:26.509Z sha 097f40b :: needs changes before merge. :: [P2] Include the runtime handoff before asserting worker retirement | [P2] Save the first worker census before starting load

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: XL and removed size: S labels Oct 19, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review October 19, 2026 09:07
@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Oct 19, 2026
@ExoHumann

Copy link
Copy Markdown
Contributor

@vincentkoc There’s overlap with #176192 at the plugin capture/loading boundary. Our approach retains preparation-worker ownership while removing synchronous worker round trips from module loading; yours transfers source state to the plugin owner and retires the workers.

Our isolated Windows/Node 24.21.0 workload with 1,000 dependencies and 10,000 imported modules completed startup in 74.9 s and changed-plugin reload in 67.8 s, with zero 15-second HTTP/WS deadline misses. Three HTTP connection resets remained, so this was not a zero-failure responsiveness result.

The harness and revision-specific evidence are in #176192. A Windows CI package also passed build and fresh-install verification; those checks are separate from the local workload measurements above.

Would comparing the same dependency-heavy fixture against your handoff help us coordinate the changes and preserve the ownership, native-custody, and recovery contracts?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants