Repository navigation
perf(startup): short-circuit dist-internal ESM resolution with explicit module format - #128541
Conversation
…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.
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: found issues before merge. Reviewed August 24, 2026, 2:00 AM ET / 06:00 UTC. ClawSweeper reviewWhat this changesThe PR adds a Node ESM resolve hook that directly resolves eligible relative JavaScript imports within OpenClaw’s built distribution to reduce startup work. Merge readinessKeep 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 Review scores
Verification
Live VerificationCommand: Result: FAIL (partial) — step 2 Assertions:
How this fits togetherOpenClaw’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
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +112, Tests +121. Total +233 across 4 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against cc2993c72722. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
|
Merged via squash.
|
…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.
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.
What Problem This Solves
Warm
gateway runstartup burned 1.3–2.6s of CPU inside Node's ESM resolver. Profiles attributed it todist/plugin-module-loader-cache-*.js(resolve~1.9s), but that hook was only sitting in the stack: the real cost is Node'sgetPackageScopeConfig(), which runs for everyfile:URL it resolves to pick a module format and re-materializes package.json on each call — re-parsing openclaw's 318-key (~124KB)exportsmap 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.jsfiles found zero CJS-syntax files. So for a relative./chunk.jsimport insidedist/, Node's format detection can only ever conclude"module"— the scope walk is pure waste. The newsrc/entry.esm-resolve-fast-path.tsregisters aModule.registerHooksresolve hook from the main-module branches ofentry.tsandindex.tsthat short-circuits exactly those resolutions with the URL-joined target andformat: "module", which also skips format detection at load. Everything else defers tonextResolve:require()conditions, bare specifiers, non-.jstargets, parents outside dist, and../chains that escape the dist root. Source checkouts (tsx/vitest own.js→.tsrewrites) and runtimes withoutregisterHooks(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):[gateway] readypackage_json_reader.getprofile self timeAll CLI commands benefit too (both
openclaw.mjsand directdist/index.jsentry 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
getPackageScopeConfig= 92.9µs/call against this repo root (Node 26.5.0, warm), eagerly materializing all 318 export entries per call.package_json_reader.get1279ms self +getPackageScopeConfigchains underdefaultResolve; final profile after the change: frame absent, boot profile duration 7.2s → 4.2s.openclaw.mjs gateway runon the rebuilt dist reaches listening in 2.1s with the same 16 plugins and no errors;plugins list/--versionsmoke pass."type": "module"; 8,368 dist.jsfiles scanned, zero CJS-syntax.src/entry.esm-resolve-fast-path.test.ts(7 tests) exercises the registered hook via an injectedregisterHooksstub: 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-changedexit 0;pnpm buildgreen; fresh Codex autoreview clean (0 findings, "patch is correct 0.98").