Repository navigation
perf: reduce packaged runtime module-loading overhead - #139754
Conversation
Avoid repeated Node package-format metadata parsing for internal chunks while preserving named JavaScript entrypoints, public SDK paths, stable runtime aliases, and historical upgrade aliases. Validation: 242 focused tests, normal build, built status-runtime loading, actual package inventory/import-closure checks, and independent Codex P0 review passed. All typechecks passed. Local aggregate lint was blocked by an ancestor-checkout punycode manifest lookup; neutral Linux validation and original retention stress acceptance remain pending. Related: #136639.
Match the existing inventory-owned private QA namespace when packing reused build outputs. Add real npm-pack regression coverage and remove ignored promise-executor return values from startup metadata tests without changing their timing or cleanup behavior. The new package regression failed before the exclusion repair and passed afterward. Package E2E: 63 passed, 3 Windows-only skipped. Startup metadata: 22 passed. Focused lint and independent Codex P0 review passed. Related: #136639.
|
🦞👀 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. Reviewed September 6, 2026, 4:13 AM ET / 08:13 UTC. ClawSweeper reviewWhat this changesEmit internal runtime chunks as explicit ESM files while preserving public JavaScript entrypoints, update chunk discovery and packaging coverage, and complete installation in the Docker test image. Merge readiness✅ Ready for maintainer review This PR remains useful and has no identified blocking defect. The earlier chunk-discovery finding is fixed, and source inspection resolves the previous migration checkbox: the Docker change completes an existing package lifecycle without changing operator data or storage semantics. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw’s build packages its runtime into public entrypoints and shared internal modules. Postbuild tooling preserves compatibility aliases, and installed-package checks verify that the CLI, Gateway, and test fixtures can load those modules. flowchart TD
A[Runtime source] --> B[Unified build]
B --> C[Public JavaScript entrypoints]
B --> D[Internal ESM chunks]
D --> E[Compatibility aliases]
C --> F[Packaged runtime]
E --> F
D --> F
F --> G[CLI and Gateway checks]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceTests +115, Config 0, Other +2. Total +117 across 25 files. View PR surface stats
Review metricsNone. Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Use explicit ESM for internal chunks while retaining public entrypoints, historical aliases, user loader hooks, and the existing package lifecycle. Do we have a high-confidence way to reproduce the issue? Not applicable as a discrete bug reproduction: this is a runtime packaging optimization. Supplied installed-package evidence exercises the changed loading paths; this read-only review did not execute them or establish an exact-head performance gain. Is this the best way to solve the issue? Yes. The existing build option and extension-aware consumers provide a narrow solution while preserving compatibility contracts; the Docker correction uses the canonical postinstall entrypoint. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 43a9c9758d7e. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
|
Merged via squash.
|
* build: emit internal runtime chunks as explicit ESM Avoid repeated Node package-format metadata parsing for internal chunks while preserving named JavaScript entrypoints, public SDK paths, stable runtime aliases, and historical upgrade aliases. Validation: 242 focused tests, normal build, built status-runtime loading, actual package inventory/import-closure checks, and independent Codex P0 review passed. All typechecks passed. Local aggregate lint was blocked by an ancestor-checkout punycode manifest lookup; neutral Linux validation and original retention stress acceptance remain pending. Related: openclaw#136639. * build: preserve private QA exclusions across chunk formats Match the existing inventory-owned private QA namespace when packing reused build outputs. Add real npm-pack regression coverage and remove ignored promise-executor return values from startup metadata tests without changing their timing or cleanup behavior. The new package regression failed before the exclusion repair and passed afterward. Package E2E: 63 passed, 3 Windows-only skipped. Startup metadata: 22 passed. Focused lint and independent Codex P0 review passed. Related: openclaw#136639. * test: preserve user loader proof for ESM chunks * test: recognize ESM chunks in remaining runtime fixtures * test(docker): complete package lifecycle before read-only proof * test(docker): consolidate the packaged-image lifecycle contract
The dist-relative resolve hook (#128541) short-circuited relative ".js" imports so Node skipped package-scope format detection. #139754 then emitted core chunks as ".mjs", which already carry their format, so the hook now matches about 0.1% of resolutions (30 of 28,038 on Node for the gateway/reply import graph). The pinned Bun fork has since gained Module.registerHooks. With any resolve hook registered, Bun routes every resolution through its JS customization-hooks chain instead of its native parallel loader: 303,185 hook calls for the same graph, 140 short-circuits. In fresh Bun processes importing that graph, median wall time drops from 12.65 s to 2.54 s without the hook (9 interleaved pairs, loaded host). Remove the hook and its call sites instead of special-casing Bun; Node keeps the explicit-format chunks that replaced it.
…9543) The dist-relative resolve hook (openclaw#128541) short-circuited relative ".js" imports so Node skipped package-scope format detection. openclaw#139754 then emitted core chunks as ".mjs", which already carry their format, so the hook now matches about 0.1% of resolutions (30 of 28,038 on Node for the gateway/reply import graph). The pinned Bun fork has since gained Module.registerHooks. With any resolve hook registered, Bun routes every resolution through its JS customization-hooks chain instead of its native parallel loader: 303,185 hook calls for the same graph, 140 short-circuits. In fresh Bun processes importing that graph, median wall time drops from 12.65 s to 2.54 s without the hook (9 interleaved pairs, loaded host). Remove the hook and its call sites instead of special-casing Bun; Node keeps the explicit-format chunks that replaced it.
Related: #136639 — preserve conversations under session-maintenance pressure.
What Problem This Solves
Resolves avoidable module-loading overhead in the packaged runtime, particularly when operators use Node preload/loader hooks. Internal code-split files currently use
.js, so Node repeatedly resolves their package format against OpenClaw's large package metadata. This surfaced while exercising Gateway startup and restart in the retention stress scenarios.Why This Change Was Made
Emit the unified runtime graph's internal hashed chunks as explicit ESM (
.mjs) using tsdown's existing chunk filename option. Keep named/public.jsentrypoints, declarations, workers, stable runtime aliases, historical hashed.jsaliases, export allowlists, shutdown retention, and the user-loader guard unchanged. Update existing chunk consumers and their tests to recognize both extensions; preserve the existing private-QA package exclusion across either extension.This is separate from the retention-policy change and from the small QA visibility-metadata cleanup. It adds no loader cache, Node patch, dependency, configuration option, schema, or protocol change. Production/tooling growth is six net lines; most changed lines are existing test tables and artifact-boundary coverage.
User Impact
Internal runtime modules carry an explicit format without changing the paths users, plugins, or workers load. Preloaded user resolver hooks continue to observe module resolution. Private QA chunks remain excluded even when the canonical packer reuses a prebuilt tree.
Evidence
Focused tooling, worker, and canonical-packer suites: 316 passed, with three Windows-only cases skipped on macOS. The normal build on
16417367fea55e1169036e47058f824138319a2fpassed in 13m 47.7s, followed by the 23 loader tests andnode scripts/check-package-dist-imports.mjs .. Subsequent follow-through is limited to the Docker E2E image and test consumers; the runtime build logic is unchanged.node scripts/run-vitest.mjs src/entry.esm-resolve-fast-path.test.ts: 23 passed, none skipped, including actual built entry/index processes with synchronous preload, asynchronous loader, and split-quotedNODE_OPTIONS. The observer previously recognized only.js; all three real-process cases failed at the missing observation before it was corrected to recognize.mjstoo. Production loader guards are unchanged.A real canonical npm-pack regression demonstrated that the old root exclusion omitted private
.jsfiles but admitted a private.mjsfile, while the package inventory already rejected both. The same regression passes with the existing private prefix excluded independently of extension.Fresh independent Codex autoreview: scoped-clean at P0 for the complete candidate, including the subsequently separated metadata change. This is the requested review threshold, not a claim that lower-priority findings were audited.
The earlier frozen combined prototype completed all functional Linux smoke phases—archival, archive lookup/restoration, continuation, graceful restart, immediate in-flight crash recovery, and disk-pressure cleanup—with database integrity intact. Its largest measured full-lifetime gap fell from approximately 1.5 seconds to 523.265 ms, but the smoke still failed the unchanged 500 ms requirement. Those timings used a preload, which deliberately disables the existing resolver optimization; they are not uninstrumented default-path measurements. Detailed qualification: fix(sessions): preserve conversations under maintenance pressure #136639 (comment).
Clean installed-package proof passed on Linux/Node 24.19.0: the configured Blacksmith Testbox built the exact
16417367fea55e1169036e47058f824138319a2fsource, packed and verified the actual npm tarball, and ranbash scripts/e2e/openai-web-search-minimal-docker.sh. This exercises the changed private chunk locator through both the synthetic provider's success and rejection paths. Providerblacksmith-testbox, leasetbx_01m1th8sdw56g6st89jmtyfrgj, run 34012793337, command exit 0 in 318.8s. The harness deletes successful scenario logs by design; its synchronous exit result and tarball-integrity output were retained. The lease was stopped and its completed state verified.Built status-runtime loading and both heartbeat-fixture chunk imports passed against completed output with isolated OpenClaw state. The latter is import/shape proof only: no app-server mode, provider request, heartbeat execution, or Codex protocol claim.
CI passed for head
164173and head2aa8cfe. The2686ff2run found two stale Docker recipe assertions; both are corrected and consolidated inf642dcd429a082876952259a752a426ccc9e8663. That test-only follow-through leaves runtime and Dockerfile source unchanged from the Docker-tested commit. Exact-head CI forf642dcdpassed with no pending required checks.Review follow-through
The sealed-service fixture's
.js-only selector was a real omission. Against the completed build it found zero ownership chunks while four matching.mjschunks existed. Its existing selector now accepts both extensions; all unprivileged, read-only mount, and release-root ownership assertions remain unchanged.The same audit corrected two other test consumers without adding production code: the prepared-Gateway module lookup and the raw-CDP fixture's paired removal/check globs. The prepared-Gateway regression failed before the correction with
Could not resolve built prepared-model-runtime- module; afterward both existing model-picker scenarios passed using the isolated Gateway and synthetic Telegram API. Command:node scripts/run-vitest.mjs test/e2e/qa-lab/runtime/telegram-model-picker-prepared-gateway.e2e.test.ts. The browser finding was verified against immutable CI artifactdist-runtime-build(run 34012569438, artifact 9982950836), not a changing local build: it containsdist/pw-ai-Biu1LSh7.mjs, and its build commit is the CI merged85d0e669727ebacae6f9ff9a9bf6a92eefbb9c1with this PR's164173head as a parent. The artifact listing contains neitherqa-runtime-*chunks nordist/plugin-sdk/qa-lab.js, and its producer job does not enable private QA.The consumer follow-through changes four lines across three test files. Syntax, formatting, targeted lint, the Docker boundary guard, and fresh independent Codex autoreview at P0 passed.
The complete sealed-service run also exposed a pre-existing image-initialization defect: the functional image imported only postinstall's cleanup function, leaving
.openclaw-lifecycle-pendingpresent. Four writable-container denial scenarios passed, but a fresh read-only container failed trying to create the lifecycle lock before reaching the service assertion. The test image now invokes the existing complete postinstall script during its writable build step; its obsolete partial-hook comment was removed. No runtime recovery code or assertion changed.Complete Docker proof passed after that image correction, using the configured Blacksmith Testbox, lease
tbx_01m1tmym033x8q3v76q586vz28, run 34015453273. The unchanged sealed-service script passed all four ownership-denial scenarios, same-UID read-only file mounts in modes0400and0644, and both paired mounts (matching release accepted, different release rejected). A fresh read-only image probe reportedpending: false, and the raw-CDP Docker scenario passed afterward. The combined command exited 0 in 291.5s. This tested frozen source treedb3b0299ce9873c8d57c4bbc8726df3b3e31acdc, including the then-uncommitted image correction. Image-fix commit 2686ff2 retains that exact tree. The lease was stopped and its completed state verified. The image correction also passed the Docker boundary guard and fresh independent review at P0.The final CI follow-through consolidates two overlapping Docker recipe checks into the owning tooling suite. The old checks required the partial cleanup call, and one explicitly forbade the complete postinstall entrypoint. All package-extraction, dependency-cache, and postinstall-before-self-link assertions remain; the obsolete private-registry policy assertion and duplicate case are removed. The consolidated guard was demonstrated to fail against the original partial-hook recipe, then both affected suites passed with the repaired recipe: 281 passed, two platform-specific skips. Command:
node scripts/run-vitest.mjs src/docker-build-cache.test.ts test/scripts/docker-build-helper.test.ts. Targeted lint, the max-lines guard, and fresh independent review at P0 also passed. This test-only consolidation removes ten lines and changes neither runtime nor Dockerfile source.The automated data-model compatibility checkbox is not applicable to this build PR.
scripts/e2e/Dockerfilenow invokes the same pruning operation and the existing package-lifecycle marker completion inscripts/postinstall-bundled-plugins.mjs:357-411; it does not migrate operator state or persist a plugin registry. No SQLite schema, index, projection, retention policy, operator configuration, or user-data representation changes here. The installed-package/read-only proof above verifies that existing lifecycle contract; mixed-extension alias tests retain the stable and historical.jsupgrade paths. ClawSweeper's source review likewise reports no migration or blocking patch defect—the remaining generic checkbox is a classification false positive, not an unimplemented data migration.Scope and remaining validation
This PR is not a retention stress-pass report. SCALE and MASSIVE have no accepted final-candidate result; their workloads, 4/30/60-minute budgets, 500 ms limit, and crash ordering are unchanged. Prototype measurements are not a default-loader performance comparison for this head.
The branch's aggregate local check encountered an inherited services-shard count of 721 against the 720 limit. Base and candidate have identical expanded roots. This was already repaired on
mainby #139645 (moves logging roots to infra, without raising the limit or dropping coverage), and the PR CI run passed. No shard-policy change is included here.