Repository navigation
feat: run lean core workers in one shared host to cut small-machine memory - #202495
Conversation
|
🦞👀 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 changesThis PR runs eligible lean-profile SQLite, transcript, state-read, and catalog workers as endpoints inside one shared worker. Example: A Node Gateway runs the personal-assistant workload in a 3 GiB container.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR delivers measured memory savings, repairs both prior findings, and now supplies the previously requested upgrade and clean-build evidence; no further actionable defect was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherGateway task pools and the SQLite broker send existing commands to worker endpoints, which execute database and read operations and return results; the shared host owns their physical lifetime. flowchart LR
A[Gateway resource profile] --> B[Task pools and SQLite broker]
B --> C[Eligible lean endpoints]
B --> D[Dedicated workers]
C --> E[Shared physical host]
E --> F[Existing database and read owners]
D --> F
Technical reviewBest possible solution: Retain the shared physical host while preserving existing command owners, endpoint cleanup, and capability-based dedicated-worker exclusions. Do we have a high-confidence way to reproduce the issue? Source confirms duplicated worker isolates on current main, and the supplied Gateway campaign measures their memory cost; no target code was executed during this review. Is this the best way to solve the issue? Sharing the physical isolate removes duplicated loaded code while reusing existing task and database owners; the retained dedicated paths protect termination and native-close contracts. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 369cdbaede9f. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +784, Tests +310, Docs +12, Other +21. Total +1127 across 30 files. Added test files: 2. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. 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 HistoryReview history (3 earlier review cycles)
Reviewed November 21, 2026, 1:06 AM ET / 06:06 UTC (Revision 4). |
7c19a0c to
e57f84a
Compare
0229d4b to
c58ffaf
Compare
9d7f71d to
d22c81c
Compare
c58ffaf to
d2a83aa
Compare
d22c81c to
00102c7
Compare
d2a83aa to
4795dee
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…9388 stage 5) Absorbs openclaw/openclaw main b949a1c (62 commits past the absorbed 5a3e6b1, which is the merge-base) into a329243, so openclaw#129388's presentation can fast-forward. rerere was off for the merge; nothing arrived pre-staged. 7 content conflicts: - Generated, regenerated rather than hand-merged: config-baseline counts and sha256 (config:docs:gen; core 2668 + fork 17 = 2685) and gateway predicates.js (gateway:validators:gen). Node 24.21.0 and Bun 1.4.4 write byte-identical output. - src/infra/worker-cpu.ts: upstream openclaw#202507 moved WorkerCpuHandle and WorkerMemoryMessage into worker-cpu-types.ts, which makes the fork's Pick<> line-cap edit (57703db) moot; upstream's type move is taken unchanged. The Worker launch composes both edits: upstream's process-generation file resolution (openclaw#202495/openclaw#202507, skipped for eval sources) and the fork's reviewed compiler policy published at launch (2a10009). They touch disjoint inputs (filename vs execArgv and environment data). Upstream's shared worker host starts its one physical Worker through createCpuTrackedWorker, so it publishes the same policy. - update-cli.fresh-doctor.test: openclaw#203194 (prepared releases and a resident launcher) deleted the two Git current-process tests; the fork's cliArgs config-validate matcher lived in one of them and goes with it. The fork's isGatewayCommand install matcher stays (merged cleanly) and the now-unused cliArgs import is dropped. - update-cli.target-schema.test: openclaw#203194 deleted the four trailing Git in-place tests; every fork compiler-flag matcher (5780288 and earlier) lived in them. The file now equals upstream's. - update-command-definition-recovery.test-support: both imports kept (the fork's isCliCommand/isGatewayCommand, upstream openclaw#201894's releaseLaunchedState); upstream's 199 added lines carry no positional argv matchers. Refs openclaw#129388 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Follow-up from the update-reliability sweep: this change pushed the installed npm package over the release installed-tree budget. Measured: the npm 12 install of main The soft budget is 47,500, and Package Acceptance's What I tried (rolldown 1.2.15). Each row is the host graph alone: file count, then the KB of chunks evaluated at host start and with all four hosted modules active.
Building the host together with the dedicated state-read worker saves only 115 files with chunk optimization off. With optimization on it saves 356, but the host then loads 715 KB at start and the catalog worker roughly 2 MB more. Merging transcript and the catalog worker into the same build also bundles fs-safe into them. None of these cut the file count without making the lean host load more code, and lowering that load is the point of this PR. So I haven't landed a change. The choice is between merging chunks (the 16 KiB merge threshold is the mildest option that frees about 320 entries) and finding entries elsewhere: the gzip sidecars or a dependency trim, both of which need sign-off. That's for the owners to decide. The budget only runs in dispatch-only Package Acceptance, which is why this PR's CI didn't catch the growth. |
…compiler policy The stage-5 merge composed createCpuTrackedWorker's launch from two independent edits: upstream openclaw#202495/openclaw#202507 resolve the worker file through the process's runtime generation (resolveProcessRuntimeWorkerFile, skipped for eval sources), and the fork's 2a10009 publishes the reviewed compiler policy and filters execArgv at launch (prepareWorkerCompilerPolicy). No test covered both at once: runtime-worker-url's real-parent case launched without a generation, and runtime-worker-generation's retained-runtime case never checked flags. The real Node parent now also sets a process generation that maps an absent installed thread to the retained copy, launches it through createCpuTrackedWorker, and checks that the retained thread's child carries the parent's flags. With upstream's launch line alone the thread refuses --no-opt in its execArgv (ERR_WORKER_INVALID_EXEC_ARGV); with the fork's alone the installed thread is not found (ERR_MODULE_NOT_FOUND). Refs openclaw#129388 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…emory (openclaw#202495) * feat: share one core worker host in the lean resource profile * fix: release hosted resources on logical stop and supervise the shared host * fix: join the shared host on final retirement and settle every native stop outcome * fix: settle a stop retried after the shared host joined * fix: keep dedicated core workers when native SQLite close is unqualified Runtimes whose explicit SQLite close does not prove native release (such as Bun on Windows) retire workers by rotation so worker exit frees handles, sidecar locks and cleanup custody. A hosted endpoint stops logically, so these runtimes never claim a shared-host slot, and a SQLite broker that captured the conservative policy keeps its carriers dedicated. * fix: register the hosted worker start protocol with the export guard * fix: annotate the host engine-selection assertion and mock the history scope close
The installed package tree shrinks by about 758 files. That brings it back under the 47,500-entry installed package budget. The shared worker host, the state reader and the transcript worker now build as one graph, so their common modules ship once. Part of #204008. ## Problem #202495 ("run lean core workers in one shared host") added `infra/shared-worker-host.worker` as a standalone runtime process with its own private chunk graph. The host imports the state reader and the session transcript worker, and those two workers also keep their own private graphs. So the package ships the same modules up to three times: | Chunk directory | Files on `main` | |---|---| | `infra/shared-worker-host-*` | 589 | | `state/openclaw-state-read-*` | 338 | | `config/sessions/transcript-*` | 404 | Scheduled `main` CI measured 48,070 installed entries against the 47,500 budget (`scripts/check-openclaw-installed-package-budget.mts`). ## Solution - `standaloneRuntimeProcessBuildGroups` (`scripts/lib/runtime-process-core-build-entries.mts`) returns one build per standalone entry, but puts the three hosted entries in one build. `getStandaloneRuntimeProcessOutputOptions` gives the three entries the host's chunk directory. - `tsdown.config.ts` and `scripts/lib/vitest-worker-compiler.mts` both build from those groups, so the package and the test worker generations use the same layout. - Each worker keeps its own entry file and loads only the chunks that its own graph reaches. Rolldown puts a module in a chunk only with modules that the same entries reach. - The session transcript worker now bundles `@openclaw/fs-safe`, as the state reader and the host already do. Inside the lean host it already ran with the bundled copy. ## Evidence - A build of only the grouped config emits 573 files in `infra/shared-worker-host-*` and none in the state-read or transcript directories (main: 1,331 across the three). - `test/scripts/runtime-process-build-graph.test.ts` passes, including the private-chunk limit and the "out of the Gateway server graph" checks for all three workers. - `src/infra/shared-worker-host.test.ts` and `shared-worker-host.unqualified-close.test.ts` pass on a freshly compiled worker generation (the host loads the state reader and transcript modules from the shared directory). - Gap: the full installed-tree count is not re-measured locally. 48,070 − 758 ≈ 47,312 is an estimate; the package acceptance budget check measures it. Co-authored-by: Ayaan Zaidi <[email protected]>
…es (#203241) * fix(gateway): shutdown never first-imports chunks an in-place update replaced * test(gateway): guard built shutdown against late first-imports * fix(gateway): keep broker close functions visible to dead-export scan * fix(process): supervisor shutdown warnings never first-import their logger; guard tracks pre-signal modules * test(ci): watch supervisor shutdown owners for the late-import guard * test(gateway): readable late-import entry parsing * test(gateway): stop the guard Gateway after startup maintenance settles * test(gateway): guard only hashed dist chunks that a swap removes * test(gateway): skip the SIGTERM guard where taskkill stops the Gateway * fix(gateway): prime supervisor shutdown logger from the shutdown runtime; add restart worker to PR wrapper inventory * fix(memory-core): own the manager runtime loader in a leaf module so closing never loads the provider * fix(state): agent lease cleanup handler loads with the state worker; guard stop budget and watch paths * fix(cron): claimed runs load their finalization before shutdown can need it; watch memory loader owners * fix(cron): scheduled runs also load finalization with their scheduler (cherry picked from commit 78a6ca1) Release adaptation: Preserve the stable cron dispatch preamble and command set, without main-only cron.importLegacyMemberSources; scheduler and queue still prepare finalization together. The shutdown-runtime overlap is supplied by the preceding #203185 backport. Companions: #203185 selected and applied first. #203839 replaces test process ownership separately and is not required for this guard: the stable fixture supports the same child, entrypoint and stop APIs. #203790, #202507, #202495 startup/resource changes, #201024 cgroup sizing, #197395 cron backoff, and #204210/#203458/#203271 wrapper-only overlaps are not dependencies. Co-authored-by: RomneyDa <[email protected]>
The installed package tree shrinks by about 758 files. That brings it back under the 47,500-entry installed package budget. The shared worker host, the state reader and the transcript worker now build as one graph, so their common modules ship once. Part of openclaw#204008. ## Problem openclaw#202495 ("run lean core workers in one shared host") added `infra/shared-worker-host.worker` as a standalone runtime process with its own private chunk graph. The host imports the state reader and the session transcript worker, and those two workers also keep their own private graphs. So the package ships the same modules up to three times: | Chunk directory | Files on `main` | |---|---| | `infra/shared-worker-host-*` | 589 | | `state/openclaw-state-read-*` | 338 | | `config/sessions/transcript-*` | 404 | Scheduled `main` CI measured 48,070 installed entries against the 47,500 budget (`scripts/check-openclaw-installed-package-budget.mts`). ## Solution - `standaloneRuntimeProcessBuildGroups` (`scripts/lib/runtime-process-core-build-entries.mts`) returns one build per standalone entry, but puts the three hosted entries in one build. `getStandaloneRuntimeProcessOutputOptions` gives the three entries the host's chunk directory. - `tsdown.config.ts` and `scripts/lib/vitest-worker-compiler.mts` both build from those groups, so the package and the test worker generations use the same layout. - Each worker keeps its own entry file and loads only the chunks that its own graph reaches. Rolldown puts a module in a chunk only with modules that the same entries reach. - The session transcript worker now bundles `@openclaw/fs-safe`, as the state reader and the host already do. Inside the lean host it already ran with the bundled copy. ## Evidence - A build of only the grouped config emits 573 files in `infra/shared-worker-host-*` and none in the state-read or transcript directories (main: 1,331 across the three). - `test/scripts/runtime-process-build-graph.test.ts` passes, including the private-chunk limit and the "out of the Gateway server graph" checks for all three workers. - `src/infra/shared-worker-host.test.ts` and `shared-worker-host.unqualified-close.test.ts` pass on a freshly compiled worker generation (the host loads the state reader and transcript modules from the shared directory). - Gap: the full installed-tree count is not re-measured locally. 48,070 − 758 ≈ 47,312 is an estimate; the package acceptance budget check measures it. Co-authored-by: Ayaan Zaidi <[email protected]>
Fixes #202377
Related: #202373
Builds on #202422 (merged as 28aa5c8)
What Problem This Solves
On small machines the Gateway runs many background workers. Each worker loads its own copy of largely the same code, so worker memory grows past what a 1–2 GiB host can hold. The core SQLite, transcript, state-read and catalog workers are the biggest duplicates.
User Impact
User impact: with the
leanresource profile (auto-selected below 8 GiB of effective memory, or set explicitly), these four core workers run as endpoints inside one shared host worker. They load their common code once, which uses less memory.standardkeeps today's worker layout; every new path is unreachable there.Lean accepts one new failure mode: if a hosted task fails, is cancelled or times out, the whole shared host is replaced. Every hosted endpoint's in-flight work then fails with an explicit
Shared worker host failed: …error, and the next request starts a fresh host. Callers never hang.Why This Change Was Made
The prototype in #202373 showed the memory saving but broke several guarantees. This version keeps them:
service(). Host death fails every endpoint (error, exit andterminalFailure). A replacement starts only after the old host has exited: one host isolate at a time. The last endpoint's retirement joins the physical host.The census reports the host as one worker. Its row adds
hosts N endpoints, so budget admission (#202376) can charge one isolate. #202376 exportsregisterHostedSlotPredicate(url, key?). Whichever of the two PRs merges second adds and registers a stateless predicate: lean, a canonical hosted entrypoint, not Postgres, and anagentorshared-stateSQLite key. It is not the liveclaimsSharedHostSlotcheck, so a running hosted floor slot is still not charged as an isolate.Accepted edge case: some agent-database reader caches are shared across the whole isolate. They are released by explicit close requests or when the host exits, not when a single endpoint stops.
Review Repair (ClawSweeper 2/6 on
4795dee4)explicitSqliteCloseReleasesNativeResourcesis false,closeReadResourcesand transcript discovery callpool.rotate()so worker exit releases native handles, sidecar locks and cleanup custody. A hosted endpoint treatedrotationas a logical stop while a sibling kept the isolate alive. Of the two suggested fixes, I chose the smaller and safer one:claimsSharedHostSlotreuses the existing capability owner (getSqliteRuntimeCapabilities) and refuses every hosted kind when close is unqualified. The SQLite broker also requires its own captured close policy, so an early conservative broker never hosts a carrier. Forcing physical host termination would instead fail every sibling on each routine rotation. The capability is decided once and only moves from pending (false) to decided, so a slot hosted under qualified close is never retired under an unqualified policy.startHostedWorkeris registered inworkerProtocolModulesfor exactly the four hosted modules, using the guard's existing subset check. Collision checking is otherwise unchanged.bun-sqlite-library.tsdecidesexplicitSqliteCloseReleasesNativeResources: true("Node runtime") before any other branch, including early broker captures. The measured Linux Node v26.12.1 campaign path hosts the same endpoints as before, so the evidence below still applies. Only Bun runtimes with unqualified close (for example Bun Windows) change; they now use the standard dedicated layout.main5a4f6a82681fbecausesrc/infra/worker-task-host.tsconflicted with main commit8bbb3539("keep Code Mode usable after read-only workers retire"). Resolution: hosted endpoints still return early, because the physical host registers its one thread for admission. Dedicated workers, including read-only ones, now track admission unconditionally, as on main. A hosted endpoint's logical stop closes its retained connections, which decrements their admission references. Range-diff: only that hunk differs. The three earlier fix commits are identical.New tests (
src/infra/shared-worker-host.unqualified-close.test.ts; both fail on4795dee4and pass after the fix):never hosts a core worker when native SQLite close is unqualified: all four kinds; it failed withexpected true to be false.rotates an unqualified reader by physical worker exit while a shared host stays up: a real state-read pool with a live hosted sibling. The reader is a dedicated worker (censushostedEndpoints: 1; it failed with 2), andcloseReadResourcesrotation removes its physical worker while the sibling stays up.CI attribution for
4795dee4(run 44849044890):lint:tmp:export-name-collisions:startHostedWorkerrepeated in 3 modulesassertion-safety:src/infra/shared-worker-host.worker.ts: 1 > 0(SAFETY comment not adjacent to the cast)session-history-read.imports.test.ts: mock lackscloseHistoryDatabaseScopesmcp-config-mutation.test.tskeep/replace custody:identity8/4, expected 0OPENCLAW_VITEST_RUNTIME=bunat exact base28aa5c88(identity 8 and 4); the PR does not touch itroute-asset-requestsplugins:expected 57 to be less than or equal to 562d13f968(57>56); the PR touches noui/. #202795 on the new base restores this budgetserver-database-engine-cron.postgres.test.ts"drains accepted cron finalization…" timed out at 90 sEvidence
Current head:
40fc34f0df162c1d5bfdf0cb51b1bff7e46ac285, rebased ontomain5a4f6a82681f. The four feature commits match measured headc58ffafd503d918fd1fc58f5ffade1cb9dc2b599except for theworker-task-host.tsadmission-tracking merge described above. Three review-repair commits follow. Fresh validation on this head: 42 focused files (shared-host, unqualified-close, worker-task host/pool/server, SQLite broker/relay, state-read, transcript worker/lanes/readers, catalog-read, history imports, resource-profile, status-resources, export guard), 476 tests in 6 Vitest shards;pnpm tsgo:core; type-aware oxlint and oxfmt on touched files; the export-collision guard; the assertion-safety ratchet;pnpm config:docs:check; andgit diff --checkall pass.Measured campaign (complete, on
c58ffafd503d): Crabbox Linuxlocal-containerleases on one Mac Studio, Node v26.12.1, 8-CPU quota, no swap, each arm pinninggateway.resources.profile, inspector detached. 24 matrix cases (single-bot and personal-assistant workloads × 1.5/3 GiB × lean/standard × 3 interleaved rounds), plus 3 qualifications and 4 fault cases. 29 of 31 exited 0. Every lease was stopped and every receipt matches its Crabbox terminal receipt. The measured commit is patch-equivalent to this head's four feature commits apart from the admission-tracking merge hunk; the review repair changes no hosting on Node (see above). The benchmark did not run on this head.Completion:
agent.wait timeoutwith cgroup OOM kills (oom_kill2 and 1); r3 completedAt 1.5 GiB both arms reach the cgroup limit. Lean records reclaim pressure (
memory.events max5,082–22,740 on personal) but no OOM. The one completed standard personal-1.5 GiB round recorded 302,867maxevents.Gateway process RSS (excludes child processes; not heap), busy-phase median, median (range) across rounds, MiB:
Lean busy-phase Gateway RSS is lower in all 10 paired rounds, busy peak in 9 of 10, and post-work median in all 10. Max registered physical workers is lower or equal in every pair (lean 18–26, standard 18–29), with 4–5 hosted endpoints on lean. Child-process RSS is reported separately and shows no consistent difference (−90 to +91 MiB). The informational event-loop stall p95 is comparable (lean 47–68 ms, standard 58–61 ms medians), except for the pressured standard personal-1.5 GiB round (210 ms p95, ~1 s worst). Full per-phase figures (fresh, busy, peak, post-work), cgroup, worker and stall data:
campaign-summary.md/.jsonin the evidence bundle.Shared-host fault (
f2-crash-3072-lean): a fatal throw at a dispatched hosted request (requestObserved=true) produced explicit endpoint errors:Up to 4 endpoints were hosted during this case; errors were recorded for the 3 with in-flight or subsequent work, and the harness asserts that every recorded error carries this prefix, not that there is one error per endpoint. The Gateway survived and a replacement host started. The interrupted turn completed, the next turn was
ok, history was preserved, 7/7 SQLite integrity checks passed and 33 turns were verified. The standard control (f2-crash-3072-standard, SQLite-store fault, no shared host) recorded no endpoint errors. Its interrupted turn failed ('error' !== 'ok'), and the Gateway survived and the next turn wasok.Caveats: the built image carried three untracked legacy files that are not in the measured tree (
src/infra/lean-worker-host.ts,lean-worker-host.worker.ts,lean-worker-scope.ts). They are not shown to have no runtime effect. Receipt manifest hashes are read at completion, so they do not identify the harness that ran. Per-result harness hashes are recorded: the matrix and f2 ranversion-benchc919a1e0, and the qualifications and the earlier f-crash cases raneef0f878. All results are process RSS and cgroup measurements on one host with n=3 per cell, so ranges are given and no significance is claimed.Focused tests (all passing):
src/infra/shared-worker-host.test.ts(7). The first two fail without the fix:hostedEndpoints: 2;build:strict-smokeon Linux emitsdist/infra/shared-worker-host.worker.js(on the earlier head).src/infra/shared-worker-host.unqualified-close.test.ts(2), described above.Independent Astra review ran four rounds. All verified findings are fixed, each with a regression test or a repro rerun:
Proof gaps closed on
40fc34f0(Crabboxlocal-container, Mac Studio)The legacy files were unreachable in the measured build. The
c58ffafdimage carried three untracked prototype files (src/infra/lean-worker-host.ts,lean-worker-host.worker.ts,lean-worker-scope.ts). Nothing emitted references them:c58ffafdor40fc34f0mentionslean-worker.tsdown.config.tscoverssrc/hooks/bundled.dist/index.jsandshared-worker-host.worker.jshashes match the campaign build), a scan of all 27,603disttext files, source maps included, found none of the 16 tokens that occur only in those files. The tokens included./lean-worker-scope.js,createLeanWorker,openclaw.experimentalLeanHostand their error strings. Nolean-worker*file was emitted.A clean build of
40fc34f0from a fresh clone had no untracked files (git status --porcelain --untracked-files=allandgit ls-files --otherswere both empty) and scansclean-no-legacyacrossdistand the packed tarball.Upgrade from latest stable into lean.
[email protected](npmlatest) was upgraded to a candidate tarball built from40fc34f0(build-info commit40fc34f0df16). The run used a 3 GiB cgroup with no swap andgateway.resources.profile: "auto". Stable predates resource profiles, so this setting was added after the package install; the install itself left the config byte-identical.openclaw status --allon the candidate:Resources │ lean (auto: memory) · 3072 MiB cgroup-v2 · 8 CPUsandWorker shared-worker-host.worker.js │ … hosts 4 endpoints. All 17 upgrade checks passed. The upgrade run recorded nomemory.eventsmax,oomoroom_kill. The settings comparison is the one from #202507: it strips onlymeta/wizardand validates the openai auto-enable.Every lease exited as recorded and was stopped and confirmed gone: inspect, upgrade and the clean build exited 0; build attempt 1 exited 1 on the inherited budget below.
Inherited, not from this PR: the full package build (
write-unified-entry-dtsroute) failscheck-plugin-sdk-exportsat 5,405,940 bytes against a 5,385,536-byte budget. The merge-base5a4f6a82fails identically at 5,405,627 bytes in the same lease and route. CIbuild-artifactsreports 5,286,752 through its own declaration step. The candidate was packaged with the repository's update-candidate route (OPENCLAW_UPDATE_IN_PROGRESS=1, which makes size limits advisory).🦞 Made with OpenClaw