Skip to content

perf(startup): short-circuit dist-internal ESM resolution with explicit module format - #128541

Merged
steipete merged 1 commit into
mainfrom
steipete/confident-dijkstra-8e2eb0
Aug 24, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/confident-dijkstra-8e2eb0

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Warm gateway run startup burned 1.3–2.6s of CPU inside Node's ESM resolver. Profiles attributed it to dist/plugin-module-loader-cache-*.js (resolve ~1.9s), but that hook was only sitting in the stack: the real cost is Node's getPackageScopeConfig(), which runs for every file: URL it resolves to pick a module format and re-materializes package.json on each call — re-parsing openclaw's 318-key (~124KB) exports map every time (~93µs/call, measured on Node 26.5.0). A gateway boot resolves ~17k module edges across 8,368 dist files, so this scales with both graph size and exports size.

Why This Change Was Made

Every built dist file is ESM: all 145 package.json files under dist/ declare "type": "module", and a scan of all 8,368 dist .js files found zero CJS-syntax files. So for a relative ./chunk.js import inside dist/, Node's format detection can only ever conclude "module" — the scope walk is pure waste. The new src/entry.esm-resolve-fast-path.ts registers a Module.registerHooks resolve hook from the main-module branches of entry.ts and index.ts that short-circuits exactly those resolutions with the URL-joined target and format: "module", which also skips format detection at load. Everything else defers to nextResolve: require() conditions, bare specifiers, non-.js targets, parents outside dist, and ../ chains that escape the dist root. Source checkouts (tsx/vitest own .js→.ts rewrites) and runtimes without registerHooks (Bun) are gated out, and the hook is idempotent per dist root.

User Impact

Roughly halves warm gateway boot. Interleaved same-dist A/B (hook env-gated on/off, isolated OPENCLAW_STATE_DIR, macOS, Node 26.5.0, 16 bundled plugins):

Metric Hook off Hook on
Self-reported "listening" time 3.3–6.6s stable 2.1s
User CPU to [gateway] ready ~5.2s ~2.9s
package_json_reader.get profile self time 1.28s absent

All CLI commands benefit too (both openclaw.mjs and direct dist/index.js entry install the hook). Resolution results are byte-identical to Node's defaults — this deletes cost, not behavior.

Production LOC is positive (+~110 incl. doc comments): a new capability at the entry-bootstrap owner boundary (sibling to entry.compile-cache.ts); there is no existing structure that can absorb it.

Evidence

  • Micro-benchmark: getPackageScopeConfig = 92.9µs/call against this repo root (Node 26.5.0, warm), eagerly materializing all 318 export entries per call.
  • Baseline profile: package_json_reader.get 1279ms self + getPackageScopeConfig chains under defaultResolve; final profile after the change: frame absent, boot profile duration 7.2s → 4.2s.
  • Boot proof: openclaw.mjs gateway run on the rebuilt dist reaches listening in 2.1s with the same 16 plugins and no errors; plugins list/--version smoke pass.
  • Safety proof: all 145 dist package.jsons are "type": "module"; 8,368 dist .js files scanned, zero CJS-syntax.
  • Tests: src/entry.esm-resolve-fast-path.test.ts (7 tests) exercises the registered hook via an injected registerHooks stub: short-circuit shape, require-condition/bare/absolute/non-.js/out-of-root/escaping deferrals, idempotence, and non-dist/Bun gating. Entry test surface (entry.*.test.ts) green; check-changed exit 0; pnpm build green; fresh Codex autoreview clean (0 findings, "patch is correct 0.98").

…it module format

Node's ESM resolver runs getPackageScopeConfig() for every file: URL to pick
a module format, and each call re-materializes package.json — re-parsing
openclaw's 318-key exports map (~93µs/call, verified on Node 26.5.0). Across
the ~17k module edges of a gateway boot that costs 1.3-2.6s CPU, showing up
in profiles as package_json_reader.get (self time) or attributed inclusively
under any registered resolve hook.

Install a Module.registerHooks resolve fast path from the main-module entry
points that resolves relative "./*.js" imports inside dist/ by URL join with
format "module", skipping scope detection entirely. Behavior-identical: all
145 dist package.json files declare type module and dist contains no
CJS-syntax .js files, so Node would conclude the same format. require()
resolutions, bare specifiers, non-.js targets, out-of-dist parents, and
dist-escaping ../ chains defer to default resolution; source checkouts and
runtimes without registerHooks (Bun) are untouched.

Measured (interleaved same-dist A/B, isolated OPENCLAW_STATE_DIR, macOS,
Node 26.5.0): gateway boot user CPU 5.2s -> 2.9s, self-reported listening
time 3.3-6.6s -> stable 2.1s.
@clawsweeper

clawsweeper Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Aug 24, 2026
@steipete
steipete marked this pull request as ready for review August 24, 2026 05:51
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 24, 2026
@clawsweeper

clawsweeper Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 24, 2026, 2:00 AM ET / 06:00 UTC.

ClawSweeper review

What this changes

The PR adds a Node ESM resolve hook that directly resolves eligible relative JavaScript imports within OpenClaw’s built distribution to reduce startup work.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open: the new process-wide resolver hook can bypass resolver hooks preloaded by users, changing established Node loader behavior for qualifying built modules.

Priority: P2
Reviewed head: d341c8b028d2485b500da32010c466ebbf4eb5cb

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The performance target is supported by useful reported terminal evidence, but the patch has a concrete P1 compatibility defect in its process-wide hook behavior.
Proof confidence 🌊 off-meta tidepool Not applicable: Not applicable: this is maintainer-authored; the PR body reports a rebuilt-dist gateway run, but it does not cover the outstanding loader-chain compatibility case.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Not applicable: this is maintainer-authored; the PR body reports a rebuilt-dist gateway run, but it does not cover the outstanding loader-chain compatibility case.
Evidence reviewed 5 items Changed short-circuit: The new hook returns a URL, module format, and shortCircuit for eligible imports, so later resolution hooks are not invoked.
Node hook contract: On the installed Node 24.19.0 runtime, a later registered resolve hook ran first; returning shortCircuit prevented the earlier hook from running. The PR directly depends on this node:module contract.
Existing preload-hook coverage: Current main deliberately starts a process with --import resolver guards, including one that must observe the run-main import; the comment records that later hooks own the requested specifier.
Findings 1 actionable finding [P1] Preserve preloaded resolver hooks
Security None None.

Live Verification

Command: pnpm test:startup:bench:smoke

Result: FAIL (partial) — step 2 expect_output Primary entry: expected terminal output was not visible within 30 seconds: "Primary entry"

pnpm test:startup:bench:smoke
runner@runnervm76f27:/tmp/clawsweeper-live-proof-128541-Qeoq2F/target$ pnpm test:startup:bench:smoke
$ node --import tsx scripts/ensure-cli-startup-build.mts && node --import tsx scripts/bench-cli-startup.ts --preset real --case gatewayStatusJson --runs 1 --war
mup 0 --output .artifacts/cli-startup-bench-smoke.json
[cli-startup-build] dist startup entry or metadata missing; running cliStartup build profile
pnpm test:startup:bench:smoke
[build-all] tsdown
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

[tsdown-build] invocation 2/2 finished in 14.1s
[build-all] tsdown done in 15.4s
[build-all] external-plugins:local-dist
[external-plugin-local-dist] built 61 plugins in 2630ms
[build-all] external-plugins:local-dist done in 3s
[build-all] check-cli-bootstrap-imports


Assertions:

  • FAIL expect_output: Primary entry
  • FAIL expect_output: gateway status --json

How this fits together

OpenClaw’s CLI and gateway boot from built entry points that dynamically load internal modules. The new hook sits in Node’s module-resolution chain and either returns an internal module URL or delegates to the normal resolver.

flowchart LR
A[CLI or gateway entry] --> B[Bootstrap hook installation]
C[Process preload hooks] --> D[Node resolver chain]
B --> D
D --> E{Eligible internal JS import}
E -->|yes| F[Direct module URL]
E -->|no| G[Normal Node resolution]
F --> H[Loaded runtime module]
G --> H
Loading

Before merge

  • Preserve preloaded resolver hooks (P1) - This hook is registered after --import hooks, so Node calls it first; its shortCircuit return prevents those earlier hooks from seeing every eligible dist-relative import. Current main deliberately uses preloaded resolve guards in src/cli/help-exit.process.test.ts, so packaged users with loader transforms or instrumentation can silently lose them. Defer when a custom preload is present, or otherwise retain the earlier hook chain, and add a built-dist process regression test.
  • Resolve merge risk (P1) - Merging would silently bypass preloaded Node resolver hooks for matching built imports, breaking user loader transformations, instrumentation, or policy hooks that currently observe those specifiers.

Findings

  • [P1] Preserve preloaded resolver hooks — src/entry.esm-resolve-fast-path.ts:99
Agent review details

Security

None.

PR surface

Source +112, Tests +121. Total +233 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 3 112 0 +112
Tests 1 121 0 +121
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 233 0 +233

Review metrics

Metric Value Why it matters
Production versus test LOC production +112, tests +121 The process-wide loader policy adds substantial bootstrap code, so an integration proof of loader compatibility matters before merge.

Merge-risk options

Maintainer options:

  1. Preserve preloaded resolver hooks (recommended)
    Make the optimization defer when a process started with custom loader hooks, or otherwise preserve their visibility, then prove the built distribution still invokes the preload hook.

Technical review

Best possible solution:

Keep the fast path only where no earlier custom resolver can be bypassed, and add a built-distribution process test with a preloaded resolver hook that must observe an eligible import.

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

Yes: a Node 24.19.0 hook-chain probe showed that a later short-circuit prevents an earlier resolver hook from running, and current main has a --import resolver-hook process path. A rebuilt-dist invocation should be added as the final regression proof.

Is this the best way to solve the issue?

No: a process-wide fast path must not preempt preloaded loader hooks; conservatively disabling it for such launches, with built-dist coverage, is safer than assuming the default resolver is the only participant.

Full review comments:

  • [P1] Preserve preloaded resolver hooks — src/entry.esm-resolve-fast-path.ts:99
    This hook is registered after --import hooks, so Node calls it first; its shortCircuit return prevents those earlier hooks from seeing every eligible dist-relative import. Current main deliberately uses preloaded resolve guards in src/cli/help-exit.process.test.ts, so packaged users with loader transforms or instrumentation can silently lose them. Defer when a custom preload is present, or otherwise retain the earlier hook chain, and add a built-dist process regression test.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against cc2993c72722.

Labels

Label changes:

  • add P2: This is a normal-priority CLI startup optimization with a concrete compatibility regression but no evidence of an active widespread outage.
  • add merge-risk: 🚨 compatibility: The new short-circuit changes how existing --import resolver hooks participate in packaged CLI resolution.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Not applicable: this is maintainer-authored; the PR body reports a rebuilt-dist gateway run, but it does not cover the outstanding loader-chain compatibility case.

Label justifications:

  • P2: This is a normal-priority CLI startup optimization with a concrete compatibility regression but no evidence of an active widespread outage.
  • merge-risk: 🚨 compatibility: The new short-circuit changes how existing --import resolver hooks participate in packaged CLI resolution.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Not applicable: this is maintainer-authored; the PR body reports a rebuilt-dist gateway run, but it does not cover the outstanding loader-chain compatibility case.

Evidence

What I checked:

  • Changed short-circuit: The new hook returns a URL, module format, and shortCircuit for eligible imports, so later resolution hooks are not invoked. (src/entry.esm-resolve-fast-path.ts:99, d341c8b028d2)
  • Node hook contract: On the installed Node 24.19.0 runtime, a later registered resolve hook ran first; returning shortCircuit prevented the earlier hook from running. The PR directly depends on this node:module contract. (src/entry.esm-resolve-fast-path.ts:14, d341c8b028d2)
  • Existing preload-hook coverage: Current main deliberately starts a process with --import resolver guards, including one that must observe the run-main import; the comment records that later hooks own the requested specifier. (src/cli/help-exit.process.test.ts:82, cc2993c72722)
  • Current main is unaffected: Current main does not install this fast path at the entry bootstrap, and the PR head is not an ancestor of current main. (src/entry.ts:122, cc2993c72722)
  • Entry-point history: History shows prior startup and entry-path work by the likely owners, including compile-cache and legacy-entry changes. (src/entry.ts:120, 715e32448e2d)

Likely related people:

  • steipete: Prior startup work in src/entry.ts includes the Node 24 compile-cache cleanup, and this PR changes the same bootstrap boundary. (role: recent entry-point contributor; confidence: high; commits: 715e32448e2d, 1e6e68534786; files: src/entry.ts, src/entry.compile-cache.ts)
  • vincentkoc: Introduced the entry-point compile-cache behavior that shares the process-startup boundary with this resolver installation. (role: adjacent startup-path contributor; confidence: medium; commits: 8c4071f36a76; files: src/entry.compile-cache.ts, src/entry.ts)

Rank-up moves

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

  • Preserve visibility for a resolver hook preloaded with --import before short-circuiting internal imports.
  • Add a built-dist process test that proves the preload hook observes an eligible internal import.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete merged commit 74af716 into main Aug 24, 2026
239 checks passed
@steipete
steipete deleted the steipete/confident-dijkstra-8e2eb0 branch August 24, 2026 06:20
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 25, 2026
…it module format (openclaw#128541)

Node's ESM resolver runs getPackageScopeConfig() for every file: URL to pick
a module format, and each call re-materializes package.json — re-parsing
openclaw's 318-key exports map (~93µs/call, verified on Node 26.5.0). Across
the ~17k module edges of a gateway boot that costs 1.3-2.6s CPU, showing up
in profiles as package_json_reader.get (self time) or attributed inclusively
under any registered resolve hook.

Install a Module.registerHooks resolve fast path from the main-module entry
points that resolves relative "./*.js" imports inside dist/ by URL join with
format "module", skipping scope detection entirely. Behavior-identical: all
145 dist package.json files declare type module and dist contains no
CJS-syntax .js files, so Node would conclude the same format. require()
resolutions, bare specifiers, non-.js targets, out-of-dist parents, and
dist-escaping ../ chains defer to default resolution; source checkouts and
runtimes without registerHooks (Bun) are untouched.

Measured (interleaved same-dist A/B, isolated OPENCLAW_STATE_DIR, macOS,
Node 26.5.0): gateway boot user CPU 5.2s -> 2.9s, self-reported listening
time 3.3-6.6s -> stable 2.1s.
steipete added a commit that referenced this pull request Oct 12, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant