Skip to content

feat: run lean core workers in one shared host to cut small-machine memory - #202495

Merged
jalehman merged 7 commits into
mainfrom
feat/lean-shared-worker-host
Nov 22, 2026
Merged

jalehman merged 7 commits into
mainfrom
feat/lean-shared-worker-host

Conversation

@jalehman

@jalehman jalehman commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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 lean resource 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. standard keeps 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:

  • Code is shared, state is not. Each hosted module starts once per endpoint with its own port, admission relay and queue. The per-worker SQLite admission upstream is now scoped to the endpoint instead of being isolate-global. The host samples its own memory; endpoints never do.
  • One live endpoint per kind (per carrier class for the SQLite store). Extra slots of a kind keep their own dedicated workers: the state-read settlement floor of 2, bursts and the second agent carrier. Pool caps, floors, catalog custody (fix(agents): model catalog worker crashes leave no trace in logs or status #161740) and retirement timings are unchanged.
  • Single writer per database. Broker actor routing is unchanged. A hosted SQLite carrier stops logically only after every actor's native close is proven; any other stop replaces the host.
  • Real termination boundaries. An idle stop (idle timeout, rotation, close, shutdown) is a logical stop. The endpoint first releases what isolate exit would have released (state-read retained readers, transcript history databases), with a 10 s deadline. Cancellation, failure, self-retirement or an unknown reason terminates the host. CPU-heavy and synchronous kinds (prompt state, skills discovery) are not hosted and keep their own killable workers.
  • Host failure is explicit and recoverable. The host is created through the existing native-worker supervisor, so synchronous callers see its exit through service(). Host death fails every endpoint (error, exit and terminalFailure). 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.
  • Not hosted: Knowledge (Expose the resource profile to plugins; Knowledge lazy start for lean #202378), external databases, Postgres-engine installs, native-resource owners, non-canonical (update-generation or sealed) worker URLs, and runtimes whose explicit SQLite close is not qualified to release native resources (such as Bun on Windows), whose cleanup depends on worker exit.

The census reports the host as one worker. Its row adds hosts N endpoints, so budget admission (#202376) can charge one isolate. #202376 exports registerHostedSlotPredicate(url, key?). Whichever of the two PRs merges second adds and registers a stateless predicate: lean, a canonical hosted entrypoint, not Postgres, and an agent or shared-state SQLite key. It is not the live claimsSharedHostSlot check, 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)

  • [P1] Unqualified native close keeps dedicated workers. Confirmed in source: when explicitSqliteCloseReleasesNativeResources is false, closeReadResources and transcript discovery call pool.rotate() so worker exit releases native handles, sidecar locks and cleanup custody. A hosted endpoint treated rotation as a logical stop while a sibling kept the isolate alive. Of the two suggested fixes, I chose the smaller and safer one: claimsSharedHostSlot reuses 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.
  • [P2] Export guard. startHostedWorker is registered in workerProtocolModules for exactly the four hosted modules, using the guard's existing subset check. Collision checking is otherwise unchanged.
  • Benchmark applicability. On Node, bun-sqlite-library.ts decides explicitSqliteCloseReleasesNativeResources: 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.
  • Rebase. Rebased once onto main 5a4f6a82681f because src/infra/worker-task-host.ts conflicted with main commit 8bbb3539 ("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 on 4795dee4 and pass after the fix):

  • never hosts a core worker when native SQLite close is unqualified: all four kinds; it failed with expected 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 (census hostedEndpoints: 1; it failed with 2), and closeReadResources rotation removes its physical worker while the sibling stays up.

CI attribution for 4795dee4 (run 44849044890):

Check Cause Evidence Resolution
check-source-contracts PR lint:tmp:export-name-collisions: startHostedWorker repeated in 3 modules Fixed (P2)
checks-fast-baseline-ratchets PR assertion-safety: src/infra/shared-worker-host.worker.ts: 1 > 0 (SAFETY comment not adjacent to the cast) Fixed; ratchet OK locally
checks-node-changed-compact-large-8 PR Bun session-history-read.imports.test.ts: mock lacks closeHistoryDatabaseScopes Mock completed; passes on Bun
checks-node-changed-compact-large-9 Inherited Bun mcp-config-mutation.test.ts keep/replace custody: identity 8/4, expected 0 Same file fails identically under OPENCLAW_VITEST_RUNTIME=bun at exact base 28aa5c88 (identity 8 and 4); the PR does not touch it
checks-ui-e2e (2/5) Inherited route-asset-requests plugins: expected 57 to be less than or equal to 56 Reproduced on main 2d13f968 (57>56); the PR touches no ui/. #202795 on the new base restores this budget
PostgreSQL conformance (pg16-smoke) Not PR-caused (timing) server-database-engine-cron.postgres.test.ts "drains accepted cron finalization…" timed out at 90 s Local pg16 (same image) passed 4/4 on head and exact base; that test took 46.3 s and 45.4 s. Postgres installs never claim the shared host

Evidence

Current head: 40fc34f0df162c1d5bfdf0cb51b1bff7e46ac285, rebased onto main 5a4f6a82681f. The four feature commits match measured head c58ffafd503d918fd1fc58f5ffade1cb9dc2b599 except for the worker-task-host.ts admission-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; and git diff --check all pass.

Measured campaign (complete, on c58ffafd503d): Crabbox Linux local-container leases on one Mac Studio, Node v26.12.1, 8-CPU quota, no swap, each arm pinning gateway.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:

Workload 1.5 GiB lean 1.5 GiB standard 3 GiB lean 3 GiB standard
single 3/3 3/3 3/3 3/3
personal 3/3, no OOM 1/3: r1 and r2 agent.wait timeout with cgroup OOM kills (oom_kill 2 and 1); r3 completed 3/3 3/3

At 1.5 GiB both arms reach the cgroup limit. Lean records reclaim pressure (memory.events max 5,082–22,740 on personal) but no OOM. The one completed standard personal-1.5 GiB round recorded 302,867 max events.

Gateway process RSS (excludes child processes; not heap), busy-phase median, median (range) across rounds, MiB:

Workload Memory Lean Standard Paired lean − standard per round
single 1.5 GiB 1,124 (1,111–1,150) 1,209 (1,207–1,212) −88, −98, −57
single 3 GiB 1,292 (1,250–1,313) 1,337 (1,335–1,364) −85, −71, −24
personal 1.5 GiB 1,219 (1,197–1,241) 1,244 (r3 only) r3 only: −25 (busy peak +5)
personal 3 GiB 1,450 (1,448–1,493) 1,578 (1,529–1,680) −232, −85, −79

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 / .json in the evidence bundle.

Shared-host fault (f2-crash-3072-lean): a fatal throw at a dispatched hosted request (requestObserved=true) produced explicit endpoint errors:

session-transcript         Shared worker host failed: Synthetic lean benchmark worker fault
sqlite-store:agent         Shared worker host failed: Synthetic lean benchmark worker fault
plugin-model-catalog-read  Shared worker host failed: Synthetic lean benchmark worker fault

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 was ok.

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 ran version-bench c919a1e0, and the qualifications and the earlier f-crash cases ran eef0f878. 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:
    • lean-only claims;
    • two endpoints share one physical host, and census reports hostedEndpoints: 2;
    • a cancelled endpoint replaces the host and its sibling fails explicitly; a replacement starts on a new thread;
    • idle stops detach logically, and the last one joins the host;
    • a synchronous caller observes physical termination;
    • a hosted state reader's file descriptor closes on rotation while a sibling keeps the host alive (Linux);
    • a refused host constructor fails its endpoints and frees the slot;
    • a stop retried after rejection settles once the host joins.
  • Worker runtime, worker-task-pool, SQLite broker, state-read, catalog, transcript worker/lanes/readers, status/census and resource-profile suites pass. The PR-wrapper inventory closure passes.
  • Core typecheck, targeted oxlint/oxfmt and docs formatting pass.
  • build:strict-smoke on Linux emits dist/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:

  • Round 1: a logical stop left reader handles open; synchronous callers could not see host exit.
  • Round 2: the final retirement did not join the host; a refused constructor stranded endpoints; supervisor loss hung synchronous stops; a logical stop did not keep the process alive.
  • Round 3: a stop retried after the host joined could hang.
  • Round 4 (review repair): no verified P0–P2 findings. It checked the capability gate across all hosted kinds, capability monotonicity, the broker captured-policy gate, the test's fail-without-fix property, the admission-tracking merge, the guard registration and the Node benchmark claim.

Proof gaps closed on 40fc34f0 (Crabbox local-container, Mac Studio)

The legacy files were unreachable in the measured build. The c58ffafd image carried three untracked prototype files (src/infra/lean-worker-host.ts, lean-worker-host.worker.ts, lean-worker-scope.ts). Nothing emitted references them:

  • No tracked file at c58ffafd or 40fc34f0 mentions lean-worker.
  • Build entries come from the explicit runtime-process manifest. The only directory scan in tsdown.config.ts covers src/hooks/bundled.
  • In the measured image itself (dist/index.js and shared-worker-host.worker.js hashes match the campaign build), a scan of all 27,603 dist text 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.experimentalLeanHost and their error strings. No lean-worker* file was emitted.
head c58ffafd503d  legacy files untracked, sha256 = campaign inventory
dist files=27603 bytes=398238811 namedLegacy=[] legacyUniqueInDist=[]  -> no-legacy-token-in-dist

A clean build of 40fc34f0 from a fresh clone had no untracked files (git status --porcelain --untracked-files=all and git ls-files --others were both empty) and scans clean-no-legacy across dist and the packed tarball.

Upgrade from latest stable into lean. [email protected] (npm latest) was upgraded to a candidate tarball built from 40fc34f0 (build-info commit 40fc34f0df16). The run used a 3 GiB cgroup with no swap and gateway.resources.profile: "auto". Stable predates resource profiles, so this setting was added after the package install; the install itself left the config byte-identical.

CHECK profile-auto-lean-memory ok        configured=auto profile=lean reason=memory
CHECK memory-limit-cgroup-3GiB ok        cgroup-v2 3221225472
CHECK shared-host-hosted-endpoints ok    {"kind":"shared-worker-host.worker.js","count":1,"hostedEndpoints":4}
CHECK settings-preserved-vs-stable-written ok
CHECK settings-preserved-vs-original-input ok
CHECK openai-auto-enable-only ok         plugins.entries.openai = {enabled:true}
CHECK stable-messages-preserved ok       4 stable messages deep-equal after upgrade
CHECK turn-candidate-1 ok                same session, history 4 -> 6, prefix unchanged

openclaw status --all on the candidate: Resources │ lean (auto: memory) · 3072 MiB cgroup-v2 · 8 CPUs and Worker shared-worker-host.worker.js │ … hosts 4 endpoints. All 17 upgrade checks passed. The upgrade run recorded no memory.events max, oom or oom_kill. The settings comparison is the one from #202507: it strips only meta/wizard and 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-dts route) fails check-plugin-sdk-exports at 5,405,940 bytes against a 5,385,536-byte budget. The merge-base 5a4f6a82 fails identically at 5,405,627 bytes in the same lease and route. CI build-artifacts reports 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

@clawsweeper

clawsweeper Bot commented Nov 20, 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 scripts Repository scripts commands Command implementations agents Agent runtime and tooling size: XL labels Nov 20, 2026
@jalehman
jalehman marked this pull request as draft November 20, 2026 13:25
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 20, 2026
@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: Separate worker isolates recorded a median busy Gateway RSS of 1,578 MiB.
  • After: The shared-host campaign recorded 1,450 MiB, with separate endpoint ports and queues.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, coherent performance work with runtime and upgrade evidence; the measurements remain limited to one host and three rounds per workload cell.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The supplied Linux Node Gateway campaign exercises hosted workloads and injected host failure with explicit errors and recovery; current-head upgrade output demonstrates auto-selected lean, four hosted endpoints, preserved settings and history, and a successful subsequent turn. The memory campaign remains attributed to its earlier measured head, and the later clean-build scans address prototype contamination.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Small Gateway hosts spend substantial memory loading common dependencies into separate worker isolates.
Reason: The maintainer-authored direction provides measured savings and explicitly accepts the shared failure boundary without adding a configuration option.

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
Reviewed head: 40fc34f0df162c1d5bfdf0cb51b1bff7e46ac285

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway 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
Loading

Technical review

Best 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

  • SQLite carrier ownership and bounded transport keeps the original intent (979c0fc: Move blocking SQLite work into owned workers while retaining physical database custody, bounded queues, and uncertain-write settlement.)
  • Retained reader cleanup keeps the original intent (6c84ca1: Reuse native reader connections between requests and acknowledge cleanup before file retirement.)
  • Native-close qualification keeps the original intent (fcd59e6: Reuse workers only where explicit SQLite close proves native-resource release; otherwise worker exit remains the cleanup boundary.)
  • Resource-profile worker layout changes intended behavior with a stated reason (28aa5c8: Introduce resource profiles and diagnostics as the foundation for subsequent lean-only behavior.)
  • Worker task retirement ordering keeps the original intent (d90d52c: Join task execution and resource receipts before retiring the worker transport.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced change and current-main boundary: The pinned introduction adds shared hosting; fetched main still creates separate native workers through the task host and SQLite broker. (src/infra/worker-task-host.ts:104, 40fc34f0df16)
  • Prior native-close finding repaired: All hosted kinds now require qualified explicit SQLite close, and SQLite carriers additionally require the broker's captured close policy; unqualified runtimes retain physical worker retirement. (src/infra/shared-worker-host.ts:87, 40fc34f0df16)
  • Prior export finding repaired: The existing export guard now recognizes startHostedWorker as a fixed protocol export in precisely the four hosted entry modules. (scripts/check-export-name-collisions.mts:740, 40fc34f0df16)
  • Runtime proof and closed qualification gaps: The full PR body supplies paired Gateway memory measurements, explicit endpoint errors and recovery after a dispatched host fault, and current-head terminal output showing one host with four endpoints after upgrading v2026.11.6. Settings and stable session messages were preserved. It also records clean-build and packed-artifact scans excluding the legacy prototype. The captured body identity is b0e1cc5828cad87310b26a94bdcae5fbee2dbbd2442524b5e7f25116c837652e. (40fc34f0df16)
  • Accepted availability tradeoff: This maintainer-authored PR explicitly accepts replacing the whole host when an endpoint requires physical termination, failing sibling work visibly and recovering on subsequent requests. (src/infra/shared-worker-host.ts:245, 40fc34f0df16)
  • Related work has separate ownership: Lean: shared core worker host that shares code, not state #202377 owns shared core hosting, while feat: keep lean Gateway worker growth inside a memory budget #202507 owns memory-budget admission and documents the integration seam; neither supersedes this implementation.

Likely related people:

  • Peter Steinberger: Raw commit b3196df adds src/infra/worker-task-host.ts:29 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b3196dfda335; files: src/infra/worker-task-host.ts)
  • Josh Lehman: Raw commit 28aa5c8 adds docs/gateway/index.md:479 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 28aa5c88fd45; files: docs/gateway/index.md)
  • Vincent Koc: Raw commit 92d147d adds packages/worker-runtime/src/worker-task-server.ts:130 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 92d147da1552; files: packages/worker-runtime/src/worker-task-server.ts)

PR surface

Source +784, Tests +310, Docs +12, Other +21. Total +1127 across 30 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 21 1448 664 +784
Tests 3 310 0 +310
Docs 2 16 4 +12
Config 0 0 0 0
Generated 0 0 0 0
Other 4 21 0 +21
Total 30 1795 668 +1127

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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The feature addresses measured memory pressure on small Gateway hosts.
  • merge-risk: 🚨 availability: Hosted endpoints share a physical failure boundary, an explicitly accepted tradeoff supported by fault-recovery evidence.
  • 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 execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-11-20T13:45:22.599Z sha 0229d4b :: needs maintainer review before merge. :: none
  • reviewed 2026-11-21T01:23:08.147Z sha 4795dee :: needs changes before merge. :: [P1] Preserve physical retirement when native SQLite close is unqualified | [P2] Register the fixed hosted-start protocol with the export guard
  • reviewed 2026-11-21T04:19:37.845Z sha 40fc34f :: needs maintainer review before merge. :: none

Reviewed November 21, 2026, 1:06 AM ET / 06:06 UTC (Revision 4).

@jalehman
jalehman force-pushed the feat/gateway-resource-profile branch from 7c19a0c to e57f84a Compare November 20, 2026 15:21
@jalehman
jalehman force-pushed the feat/lean-shared-worker-host branch from 0229d4b to c58ffaf Compare November 20, 2026 15:56
@jalehman
jalehman force-pushed the feat/gateway-resource-profile branch 2 times, most recently from 9d7f71d to d22c81c Compare November 20, 2026 17:47
@jalehman
jalehman force-pushed the feat/lean-shared-worker-host branch from c58ffaf to d2a83aa Compare November 20, 2026 18:07
@jalehman
jalehman force-pushed the feat/gateway-resource-profile branch from d22c81c to 00102c7 Compare November 20, 2026 21:14
Base automatically changed from feat/gateway-resource-profile to main November 20, 2026 23:15
@jalehman
jalehman force-pushed the feat/lean-shared-worker-host branch from d2a83aa to 4795dee Compare November 20, 2026 23:19
@jalehman
jalehman marked this pull request as ready for review November 21, 2026 01:15
@jalehman

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Nov 21, 2026
@clawsweeper clawsweeper Bot added the status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. label Nov 21, 2026
@jalehman

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Nov 21, 2026
@jalehman
jalehman merged commit da13d2a into main Nov 22, 2026
179 checks passed
@jalehman
jalehman deleted the feat/lean-shared-worker-host branch November 22, 2026 07:21
@jalehman

Copy link
Copy Markdown
Contributor Author

Merged via squash.

scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 22, 2026
…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]>
@steipete

Copy link
Copy Markdown
Contributor

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 8d1e59c2fdd is 47,934 entries, using scripts/check-openclaw-installed-package-budget.mts, the same counting as the shipped 2026.9.3–9.8 updaters. The last Package Acceptance run on the 11-21 ref measured 47,280. A path diff shows +588 new dist/infra/shared-worker-host-*.mjs chunks from the shared host's codeSplitting: true build. The other +66 entries are ordinary churn.

The soft budget is 47,500, and Package Acceptance's npm_12_install_sh step fails above it, so the next release cut from main will be refused at that gate. release/2026.11.7 doesn't contain this commit. The hard limit is 50,000: shipped 9.3–9.8 updaters refuse a larger candidate, leaving 2,066 entries of headroom.

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.

Host build Files Start KB All four active KB
current (codeSplitting: true) 587 184 2,916
experimentalInlineCommonChunks (32 KiB) 480 441 3,514
catch-all group, entriesAware, merge threshold 16 KiB 267 693 4,633
catch-all group, entriesAware, merge threshold 64 KiB 117 6,111 6,164
codeSplitting: false 1 7,568 7,568

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.

scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 22, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…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
obviyus added a commit that referenced this pull request Nov 23, 2026
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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 24, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. scripts Repository scripts size: XL 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.

Lean: shared core worker host that shares code, not state

2 participants