Repository navigation
Conversation
Proves that a single-module compile can answer a question about an
import by READING it rather than assuming. `plainCalleeIsMemoizable`
currently says an imported binding's "body is across a module boundary
we cannot read" — this reads it.
Design notes, both deliberate:
- Demand-driven, not a pre-pass. Bundlers transform an importer BEFORE
its dependencies, so "pass 1 collects, pass 2 consumes" is always one
build too late. The importer pre-scans its own source and pulls only
the imports that could change an answer.
- Source text, not bundler metadata. The void-component proof next door
rides Rollup module-graph `meta`, which is exactly why the rspack
plugin has no equivalent. Resolve + readFile is the one primitive both
bundlers supply, so a single implementation serves each.
Every fact is a property of one module's own source, which is what makes
it cacheable per file and sound without a closed-world assumption. Facts
that need every CALL SITE — "this prop is always passed a stable value"
— are a different class, only sound under a closed world, and are called
out as not modelled rather than half-supported.
Absence of a fact means "assume nothing", so the failure mode of the
whole mechanism is the behaviour that predates it, never a missed
dependency.
GATED OFF in both plugins. Two integration problems remain:
1. the candidate pre-scan is a second parse of every module, +27% on
top of compile. Measured: of a 298ms pre-scan over 300 modules,
290ms is the duplicate parse and 9ms the actual walk, so sharing
the compiler's existing AST takes this under +1%.
2. `addWatchFile` on a resolved dependency perturbs Vite's module
graph — it breaks the user-app eval sandbox's resolveId policy —
so watch invalidation needs a `hotUpdate` design instead.
With the gate off the transform path is byte-identical to before.
Co-Authored-By: Claude Opus 5 <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 3 potential issues.
Autofix Details
Bugbot Autofix prepared fixes for all 3 issues found in the latest run.
- ✅ Fixed: Rspack resolve ignores nested importer
- Changed the rspack resolve adapter to accept and use the
importerargument for derivingissuerand for the self-reference guard, matching the Vite adapter's behavior for recursive forward resolution.
- Changed the rspack resolve adapter to accept and use the
- ✅ Fixed: Hint skips unstable_use imports
- Updated
HOOK_IMPORT_HINTregex from\buse[A-Z]to\b(?:unstable_)?use[A-Z]so the optionalunstable_prefix is matched, consistent withisHookName.
- Updated
- ✅ Fixed: Empty-deps stability trusts spelling
- Replaced the raw
callee.namecheck inmarkEmptyDepsStablewith ananalysis.trustedHookNameslookup so only verified Octane hook imports are treated as stable, closing the soundness hole for shadowed names and restoring alias support.
- Replaced the raw
Or push these changes by commenting:
@cursor push 5462a7fb0d
Preview (5462a7fb0d)
diff --git a/packages/octane/src/compiler/module-facts.js b/packages/octane/src/compiler/module-facts.js
--- a/packages/octane/src/compiler/module-facts.js
+++ b/packages/octane/src/compiler/module-facts.js
@@ -59,7 +59,7 @@
const MAX_DEPTH = 4;
-const HOOK_IMPORT_HINT = /\bimport\b[^;]*\buse[A-Z]/;
+const HOOK_IMPORT_HINT = /\bimport\b[^;]*\b(?:unstable_)?use[A-Z]/;
function unwrap(node) {
while (
@@ -192,8 +192,8 @@
if (kind !== 'const' || decl.id.type !== 'Identifier') continue;
const init = unwrap(decl.init);
if (init?.type !== 'CallExpression') continue;
- const callee = unwrap(init.callee);
- if (callee?.type !== 'Identifier' || !EMPTY_DEPS_STABLE_HOOKS.has(callee.name)) continue;
+ const trustedName = analysis.trustedHookNames.get(init) ?? null;
+ if (trustedName === null || !EMPTY_DEPS_STABLE_HOOKS.has(trustedName)) continue;
const deps = unwrap(init.arguments?.[1]);
if (deps?.type !== 'ArrayExpression' || (deps.elements?.length ?? 0) !== 0) continue;
const binding = bindings[0]?.binding;
diff --git a/packages/rspack-plugin-octane/src/loader.js b/packages/rspack-plugin-octane/src/loader.js
--- a/packages/rspack-plugin-octane/src/loader.js
+++ b/packages/rspack-plugin-octane/src/loader.js
@@ -92,16 +92,16 @@
*/
function hookStabilityFor(context, candidates, id) {
const resolver = context.getResolve({ dependencyType: 'esm' });
- const issuer = dirname(cleanModuleId(id));
return resolveHookStability(candidates, id, {
- resolve: async (request) => {
+ resolve: async (request, importer) => {
+ const issuer = dirname(cleanModuleId(importer));
let resolved;
try {
resolved = await resolver(issuer, request);
} catch {
return null;
}
- return typeof resolved === 'string' && resolved !== cleanModuleId(id) ? resolved : null;
+ return typeof resolved === 'string' && resolved !== cleanModuleId(importer) ? resolved : null;
},
readFile: async (path) => {
try {You can send follow-ups to the cloud agent here.
… bugs Both problems that gated this off are solved. The pre-scan no longer parses. It runs on every module the bundler transforms, so parsing there was a second full parse of the whole program — measured at +27% on top of compile, ~97% of which was the parse itself. A candidate list only has to be a SUPERSET, because precision comes later from reading the dependency, and both error directions are safe: over-matching costs one cached analysis that yields no fact, under-matching loses an optimisation but can never produce a wrong answer. That makes a lexical scan the right tool. Now +0.1% (361ms -> 1ms over 300 modules). Watch invalidation no longer uses `addWatchFile`. Registering a resolved dependency as a watch file pushes Vite into re-resolving that absolute path against the importer, which trips any `resolveId` plugin policing what a module may import — the user-app eval sandbox is exactly such a plugin, and it broke. Every file read is already a real import, so the graph edge exists; what was missing is only re-transforming the IMPORTER when the dependency's contents change, which `hotUpdate` does directly. The full suite passes with the gate forced on. Review fixes: - The rspack adapter ignored its `importer` argument and resolved every hop from the original module's directory. Following a transparent re-export would then resolve a relative specifier from the wrong place and prove stability from a different file than Vite read. - `HOOK_IMPORT_HINT` required a word boundary before `use`, so the `unstable_` prefix `isHookName` accepts never reached the scan. - Empty-deps stability trusted the SPELLING `useMemo`/`useCallback`. A local helper with that name was proven stable — a wrong fact, so a missed dependency — while an aliased Octane import was never proven. It now resolves the call to the hook it actually is. Still gated: `hotUpdate` is not yet covered by a dev-server test, and enabling changes emitted output for every app, so the flip wants its own changeset and benchmark run. Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Autofix Details
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Shadowed callees get import facts
- Added calleeIsModuleImport() scope-chain walk to verify the callee identifier resolves to the module scope (where imports live) before trusting octaneLocals/importedHookOrigins lookups, preventing local variables or parameters that shadow an imported hook name from inheriting the import's facts.
- ✅ Fixed: Rspack gate option unreachable
- Added unstable_crossModuleHookFacts to LOADER_OPTION_KEYS, added boolean validation in normalizeOptions, included it in the normalized output object, and forwarded it from the plugin's loaderOptions to the loader.
Or push these changes by commenting:
@cursor push a83297ec24
Preview (a83297ec24)
diff --git a/packages/octane/src/compiler/module-facts.js b/packages/octane/src/compiler/module-facts.js
--- a/packages/octane/src/compiler/module-facts.js
+++ b/packages/octane/src/compiler/module-facts.js
@@ -243,6 +243,17 @@ export function extractModuleFacts(source, id) {
markEmptyDepsStable(ast, analysis);
const scopeOfNode = (node) => analysis.nodeScopes.get(node) ?? null;
+ function calleeIsModuleImport(node) {
+ const scope = scopeOfNode(node);
+ if (!scope) return false;
+ for (let current = scope; current !== null; current = current.parent) {
+ if (current.bindings.get(node.name) !== undefined) {
+ return current === analysis.moduleScope;
+ }
+ }
+ return false;
+ }
+
// Which octane hooks are in lexical scope, and under what local name.
const octaneLocals = new Map();
const importedHookOrigins = new Map();
@@ -243,6 +243,17 @@ export function extractModuleFacts(source, id) {
markEmptyDepsStable(ast, analysis);
const scopeOfNode = (node) => analysis.nodeScopes.get(node) ?? null;
+ function calleeIsModuleImport(node) {
+ const scope = scopeOfNode(node);
+ if (!scope) return false;
+ for (let current = scope; current !== null; current = current.parent) {
+ if (current.bindings.get(node.name) !== undefined) {
+ return current === analysis.moduleScope;
+ }
+ }
+ return false;
+ }
+
// Which octane hooks are in lexical scope, and under what local name.
const octaneLocals = new Map();
const importedHookOrigins = new Map();
@@ -290,7 +301,10 @@ export function extractModuleFacts(source, id) {
const only = unwrap(returns[0]);
if (only?.type === 'CallExpression') {
const callee = unwrap(only.callee);
- const origin = callee?.type === 'Identifier' ? importedHookOrigins.get(callee.name) : null;
+ const origin =
+ callee?.type === 'Identifier' && calleeIsModuleImport(callee)
+ ? importedHookOrigins.get(callee.name)
+ : null;
if (origin) {
facts.set(name, {
kind: 'hook',
@@ -290,7 +301,10 @@ export function extractModuleFacts(source, id) {
const only = unwrap(returns[0]);
if (only?.type === 'CallExpression') {
const callee = unwrap(only.callee);
- const origin = callee?.type === 'Identifier' ? importedHookOrigins.get(callee.name) : null;
+ const origin =
+ callee?.type === 'Identifier' && calleeIsModuleImport(callee)
+ ? importedHookOrigins.get(callee.name)
+ : null;
if (origin) {
facts.set(name, {
kind: 'hook',
@@ -301,7 +315,10 @@ export function extractModuleFacts(source, id) {
continue;
}
// A direct octane hook result: `return useRef(null)`.
- const octaneName = callee?.type === 'Identifier' ? octaneLocals.get(callee.name) : null;
+ const octaneName =
+ callee?.type === 'Identifier' && calleeIsModuleImport(callee)
+ ? octaneLocals.get(callee.name)
+ : null;
if (octaneName && LIFETIME_STABLE_HOOKS.has(octaneName)) {
facts.set(name, {
kind: 'hook',
@@ -301,7 +315,10 @@ export function extractModuleFacts(source, id) {
continue;
}
// A direct octane hook result: `return useRef(null)`.
- const octaneName = callee?.type === 'Identifier' ? octaneLocals.get(callee.name) : null;
+ const octaneName =
+ callee?.type === 'Identifier' && calleeIsModuleImport(callee)
+ ? octaneLocals.get(callee.name)
+ : null;
if (octaneName && LIFETIME_STABLE_HOOKS.has(octaneName)) {
facts.set(name, {
kind: 'hook',
diff --git a/packages/rspack-plugin-octane/src/plugin.js b/packages/rspack-plugin-octane/src/plugin.js
--- a/packages/rspack-plugin-octane/src/plugin.js
+++ b/packages/rspack-plugin-octane/src/plugin.js
@@ -329,6 +329,9 @@ export class OctaneRspackPlugin {
...(this.options.requireDirective === undefined
? null
: { requireDirective: this.options.requireDirective }),
+ ...(this.options.unstable_crossModuleHookFacts === undefined
+ ? null
+ : { unstable_crossModuleHookFacts: this.options.unstable_crossModuleHookFacts }),
};
compiler.options.module.rules.push({
test: OCTANE_RULE,
@@ -329,6 +329,9 @@ export class OctaneRspackPlugin {
...(this.options.requireDirective === undefined
? null
: { requireDirective: this.options.requireDirective }),
+ ...(this.options.unstable_crossModuleHookFacts === undefined
+ ? null
+ : { unstable_crossModuleHookFacts: this.options.unstable_crossModuleHookFacts }),
};
compiler.options.module.rules.push({
test: OCTANE_RULE,
diff --git a/packages/rspack-plugin-octane/src/shared.js b/packages/rspack-plugin-octane/src/shared.js
--- a/packages/rspack-plugin-octane/src/shared.js
+++ b/packages/rspack-plugin-octane/src/shared.js
@@ -45,6 +45,7 @@ const LOADER_OPTION_KEYS = new Set([
'requireDirective',
'universalRuntime',
'layerSpecializations',
+ 'unstable_crossModuleHookFacts',
]);
const PLUGIN_OPTION_KEYS = new Set([...LOADER_OPTION_KEYS, 'runtime', 'transpile']);
const LAYER_SPECIALIZATION_KEYS = new Set(['runtime', 'renderers', 'universalRuntime']);
@@ -45,6 +45,7 @@ const LOADER_OPTION_KEYS = new Set([
'requireDirective',
'universalRuntime',
'layerSpecializations',
+ 'unstable_crossModuleHookFacts',
]);
const PLUGIN_OPTION_KEYS = new Set([...LOADER_OPTION_KEYS, 'runtime', 'transpile']);
const LAYER_SPECIALIZATION_KEYS = new Set(['runtime', 'renderers', 'universalRuntime']);
@@ -178,6 +179,7 @@ function normalizeOptions(value, plugin) {
assertBooleanOption(options, 'dev');
assertBooleanOption(options, 'profile');
assertBooleanOption(options, 'requireDirective');
+ assertBooleanOption(options, 'unstable_crossModuleHookFacts');
if (
options.exclude !== undefined &&
(!Array.isArray(options.exclude) || options.exclude.some((entry) => typeof entry !== 'string'))
@@ -178,6 +179,7 @@ function normalizeOptions(value, plugin) {
assertBooleanOption(options, 'dev');
assertBooleanOption(options, 'profile');
assertBooleanOption(options, 'requireDirective');
+ assertBooleanOption(options, 'unstable_crossModuleHookFacts');
if (
options.exclude !== undefined &&
(!Array.isArray(options.exclude) || options.exclude.some((entry) => typeof entry !== 'string'))
@@ -203,6 +205,9 @@ function normalizeOptions(value, plugin) {
...(options.requireDirective === undefined
? null
: { requireDirective: options.requireDirective }),
+ ...(options.unstable_crossModuleHookFacts === undefined
+ ? null
+ : { unstable_crossModuleHookFacts: options.unstable_crossModuleHookFacts }),
...(plugin && options.transpile !== undefined ? { transpile: options.transpile } : null),
...(plugin && options.runtime !== undefined ? { runtime: options.runtime } : null),
};
@@ -203,6 +205,9 @@ function normalizeOptions(value, plugin) {
...(options.requireDirective === undefined
? null
: { requireDirective: options.requireDirective }),
+ ...(options.unstable_crossModuleHookFacts === undefined
+ ? null
+ : { unstable_crossModuleHookFacts: options.unstable_crossModuleHookFacts }),
...(plugin && options.transpile !== undefined ? { transpile: options.transpile } : null),
...(plugin && options.runtime !== undefined ? { runtime: options.runtime } : null),
};You can send follow-ups to the cloud agent here.
Adds the dev-server test the previous revision was missing, fixes two more review findings, and settles the default on measurement. HMR invalidation is now proven, not asserted. A Vite dev server boots in middleware mode, transforms a component, rewrites the imported hook so its result stops being provably stable, fires the watcher, and re-transforms. Removing the `hotUpdate` invalidation fails the second assertion; disabling facts fails the first. That hook is what keeps dev and production AGREEING. Without it a long-lived dev server keeps its first answer while a fresh production build re-derives a new one — the divergence is the absence of invalidation, not its presence. Everything else is mode-independent: same analysis, same cache, same code path in dev and build, and the setting is per project rather than per mode. Review fixes: - Direct-return extraction keyed callees by SPELLING. A parameter or local shadowing an imported hook inherited that import's stability, so a freshly allocated value could be proven stable — a wrong fact, and a missed dependency in every caller. Callees now resolve through the scope walk. - The rspack gate option was unreachable: absent from the loader allowlist and never forwarded. The same gap existed in @octanejs/vite-plugin, which filters its options too. Left OFF by default, on evidence. Measured on the website build: feature off 17.5s async transform + pre-scan, no work 18.8s (+7%) full fact resolution 20.0s (+14%) and that buys 2 proven facts out of 315 candidate imports. Roughly half the cost is the transform having to go async at all, so a synchronous fast path over the build-scoped cache is the route to a default-on version; until then this would tax every build for a benefit almost no app collects. A build-scoped cache is already in (facts were being re-parsed once per importer, which alone was +29%). Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Autofix Details
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Rspack fact cache never invalidates
- Added
invalidateFactCache(rspackFactCache, cleanModuleId(...))at the top of the Rspack loader so the process-scoped cache drops stale facts for the current module before any importer re-reads them.
- Added
- ✅ Fixed: Vite watch builds keep stale facts
- Added
invalidateFactCache(factCache, id)in the Vite plugin'swatchChangehook (guarded bycrossModuleHookFacts) sovite build --watchrebuilds clear stale facts the same wayhotUpdatedoes for dev serve.
- Added
Or push these changes by commenting:
@cursor push 444e069589
Preview (444e069589)
diff --git a/packages/octane/src/compiler/vite.js b/packages/octane/src/compiler/vite.js
--- a/packages/octane/src/compiler/vite.js
+++ b/packages/octane/src/compiler/vite.js
@@ -340,6 +340,7 @@
},
watchChange(id) {
compiler.invalidate(id);
+ if (crossModuleHookFacts) invalidateFactCache(factCache, id);
},
generateBundle(_outputOptions, bundle) {
if (!emitClientReferenceManifest) return;
diff --git a/packages/rspack-plugin-octane/src/loader.js b/packages/rspack-plugin-octane/src/loader.js
--- a/packages/rspack-plugin-octane/src/loader.js
+++ b/packages/rspack-plugin-octane/src/loader.js
@@ -7,6 +7,7 @@
createOctaneCompiler,
createFactCache,
findFactCandidates,
+ invalidateFactCache,
resolveHookStability,
} from 'octane/compiler/bundler';
import {
@@ -135,6 +136,7 @@
export default function octaneLoader(source, inputSourceMap) {
this.cacheable?.(true);
clearBuildInfo(this._module);
+ invalidateFactCache(rspackFactCache, cleanModuleId(this.resource ?? this.resourcePath));
try {
const options = normalizeLoaderOptions(this.getOptions?.() ?? {});
diff --git a/packages/rspack-plugin-octane/tests/loader.test.ts b/packages/rspack-plugin-octane/tests/loader.test.ts
--- a/packages/rspack-plugin-octane/tests/loader.test.ts
+++ b/packages/rspack-plugin-octane/tests/loader.test.ts
@@ -15,6 +15,7 @@
// exist because the module is imported at load time.
createFactCache: () => ({ files: new Map(), resolved: new Map() }),
findFactCandidates: () => [],
+ invalidateFactCache: () => {},
resolveHookStability: async () => null,
}));You can send follow-ups to the cloud agent here.
Two review findings, one root cause: the fact cache was pruned in one mode per bundler and stale in the others. A stale entry is the dangerous direction — a hook that stops being stable keeps proving stable, so its callers keep dropping a live capture from their inferred arrays. Vite pruned only in `hotUpdate`, which is the dev server. `vite build --watch` goes through `watchChange`, which already invalidated the compiler but not the facts, so importers re-transformed against the previous extraction. Both entry points now drop the file. Rspack held one cache for the whole PROCESS. `addDependency` correctly rebuilds importers when a fact file changes, but those rebuilds were handed the old parse. The cache is now scoped per compilation through a WeakMap, so a watch rebuild starts clean and a finished compilation can be collected. The shared contract is covered directly: prove a hook stable, change the file, confirm the cache still answers with the old parse, then invalidate and confirm it re-reads. Neutering `invalidateFactCache` fails it. Co-Authored-By: Claude Opus 5 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Stale facts after cache race
- Added a generation counter to the fact cache that is incremented on invalidation; factsForFile now captures the generation before the await and only writes back to cache if it has not changed, preventing a pre-invalidation parse from repopulating the cache with stale data.
- ✅ Fixed: Rspack always goes async
- Deferred the this.async() call until after checking whether fact candidates or server import requests are non-empty, so modules with no async work stay on the synchronous callback path matching the Vite plugin's existing design.
Or push these changes by commenting:
@cursor push 3601e5aeb8
Preview (3601e5aeb8)
diff --git a/packages/octane/src/compiler/module-facts.js b/packages/octane/src/compiler/module-facts.js
--- a/packages/octane/src/compiler/module-facts.js
+++ b/packages/octane/src/compiler/module-facts.js
@@ -385,9 +385,12 @@
async function factsForFile(path) {
let cached = cache.files.get(path);
if (cached !== undefined) return cached;
+ const gen = cache.generation;
const source = await io.readFile(path);
cached = source === null ? new Map() : extractModuleFacts(source, path);
- cache.files.set(path, cached);
+ if (cache.generation === gen) {
+ cache.files.set(path, cached);
+ }
return cached;
}
@@ -458,7 +461,7 @@
* @returns {Promise<((request: string, imported: string) => any) | null>}
*/
export function createFactCache() {
- return { files: new Map(), resolved: new Map() };
+ return { files: new Map(), resolved: new Map(), generation: 0 };
}
/**
@@ -472,6 +475,7 @@
export function invalidateFactCache(cache, path) {
cache.files.delete(path);
cache.resolved.clear();
+ cache.generation++;
}
export async function resolveHookStability(candidates, id, io) {
diff --git a/packages/rspack-plugin-octane/src/loader.js b/packages/rspack-plugin-octane/src/loader.js
--- a/packages/rspack-plugin-octane/src/loader.js
+++ b/packages/rspack-plugin-octane/src/loader.js
@@ -232,9 +232,6 @@
environment === 'server' && typeof compiler.clientReferenceForFile === 'function'
? compiler.clientReferenceForFile(id)
: null;
- const asyncCallback = this.async?.() ?? callback;
- const fail = (error) =>
- asyncCallback(error instanceof Error ? error : new Error(String(error)));
// Hook facts apply to both environments, so they resolve first and are
// threaded through whichever path this module takes.
// Opt-in — see the measurement note in octane/compiler/vite.js.
@@ -242,20 +239,21 @@
options.crossModuleHookFacts === true && typeof this.getResolve === 'function'
? findFactCandidates(String(source), id)
: [];
+ const serverRequests =
+ environment === 'server' && currentReference === null && typeof this.getResolve === 'function'
+ ? compiler.findServerImportRequests(String(source), id)
+ : [];
+ const needsAsync = factCandidates.length > 0 || serverRequests.length > 0;
+ const asyncCallback = needsAsync ? (this.async?.() ?? callback) : callback;
+ const fail = (error) =>
+ asyncCallback(error instanceof Error ? error : new Error(String(error)));
const withHookStability = (hookStability) => {
- if (
- environment === 'server' &&
- currentReference === null &&
- typeof this.getResolve === 'function'
- ) {
- const requests = compiler.findServerImportRequests(String(source), id);
- if (requests.length > 0) {
- resolveClientOnlyImports(this, compiler, source, id).then(
- (imports) => finish(imports, asyncCallback, hookStability),
- fail,
- );
- return;
- }
+ if (serverRequests.length > 0) {
+ resolveClientOnlyImports(this, compiler, source, id).then(
+ (imports) => finish(imports, asyncCallback, hookStability),
+ fail,
+ );
+ return;
}
finish([], asyncCallback, hookStability);
};You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit ff72377. Configure here.
|
This adds a lot of complexity at this stage, let's defer to later. |
…g walk (#1904) Review follow-up. The element branch of both resolvers still counted live child lists (`childNodes.length`, `children.length`) and indexed `children[i]`. In Blink each of those creates a collection and keeps it on the node. Each parent now keeps a cursor to its next unclaimed child. Validation reads `firstChild` and `nextSibling` only, and a final check rejects any child the server topology does not have. A parent without a cursor (opaque, text, or not yet visited) claims nothing, which replaces two explicit parent checks. Error codes are unchanged for compiler-issued descriptors. New tests pin #318 and #321 for an extra child, a stray text node, a missing child, reordered children, and a child under a childless element. Unbound children still adopt. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…1904) Bugbot review: isTextLeaf accepted a leading <font> even when other nodes followed it. Those leaves used to fail #318/#321, and a structural text hole already requires a single node. Chrome Translate replaces one Text node with one wrapper, so a text leaf now holds no child, or exactly one: a Text node or a <font> element. The negative tests cover a <font> followed by text in every fixed lane, and two wrappers in an addressed view. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…1909) * fix(octane): adopt DOM bindings over browser-translated text leaves (#1904) Chrome's page translation replaces a text leaf's Text node with nested <font> wrappers. Fixed and addressed adoption rejected that leaf (#318, #321), and a leaf translated after adoption silently dropped every later write, because nodeValue is a no-op on an element. Adoption now accepts a text leaf whose first child is a <font> element and writes nothing to it, so the page neither flashes back to its source language nor shifts. The writer receives the channel's previous value and, once that value exists, replaces any non-Text leaf content on change. Any other element in a text leaf still throws. Document the behavior and the translate="no" opt-out in docs/deferred-hydration.md, and add a website-only catalog note to #318 and #321 that never reaches a runtime bundle. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(octane): adopt structural binding programs over translated text (#1904) Structural programs had the same Chrome Translate failure as fixed views. A static text proof or a text hole whose Text node was replaced by <font> wrappers failed adoption with #286, and a text hole translated after adoption silently kept its translation, because writeText set the data of a detached node. - resolveFragment accepts a <font> element in a static text slot. The marker id already hashes the template source, including that text. - adoptRegion accepts a <font>-wrapped text hole and records `undefined`. The first commit stores the value in a detached Text node and writes nothing. - writeText replaces the range content with its node only when the value changes and the node is no longer the range's only child. Any other element in either slot still throws #286. Extend the deferred-hydration paragraph and the website-only error note, now also on #286, to structural views. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(octane): check a text leaf in O(1) and read its nodeValue once (#1904) Review follow-up. The fixed and addressed resolvers share an isTextLeaf predicate. It reads firstChild once and uses nextSibling instead of childNodes.length, which is not O(1). The fixed-scalar writer reads nodeValue once. A null nodeValue identifies an element first child, such as Chrome Translate's <font>, so the changed write no longer reads nodeType. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(octane): validate fixed and addressed binding topology by sibling walk (#1904) Review follow-up. The element branch of both resolvers still counted live child lists (`childNodes.length`, `children.length`) and indexed `children[i]`. In Blink each of those creates a collection and keeps it on the node. Each parent now keeps a cursor to its next unclaimed child. Validation reads `firstChild` and `nextSibling` only, and a final check rejects any child the server topology does not have. A parent without a cursor (opaque, text, or not yet visited) claims nothing, which replaces two explicit parent checks. Error codes are unchanged for compiler-issued descriptors. New tests pin #318 and #321 for an extra child, a stray text node, a missing child, reordered children, and a child under a childless element. Unbound children still adopt. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(octane): reuse stable member reads in the binding write and adoption paths (#1904) Apply performance-audit's "Reuse stable member reads" (#1913) to the code this PR adds. - Both adopters' write loops read `next[i]` and `previous[i]` once. - writeOperation reads `instance.previous[index]` once, after its disposed guards. - writeText no longer reads `region.range` on the unchanged path, and caches `range.end` in the branches that use it. - adoptRegion caches `range.end`. - resolveFixedNodes destructures its open-children flag rather than indexing `descriptor.nodes[i]` again. Minified adopters shrink by 12–14 B. gzip moves 4–11 B, so this is a read-count change, not a size claim. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(octane): accept only a single translated wrapper in a text leaf (#1904) Bugbot review: isTextLeaf accepted a leading <font> even when other nodes followed it. Those leaves used to fail #318/#321, and a structural text hole already requires a single node. Chrome Translate replaces one Text node with one wrapper, so a text leaf now holds no child, or exactly one: a Text node or a <font> element. The negative tests cover a <font> followed by text in every fixed lane, and two wrappers in an addressed view. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>


Summary
A spike proving that a single-module compile can answer a question about an import by reading it instead of assuming.
Opt-in via
crossModuleHookFacts: trueon the Vite or Rspack plugin. Off by default on measurement, not principle — the numbers are at the bottom. With it off the transform path is byte-identical to before this PR.Everything the earlier revisions flagged as blocking is resolved: the pre-scan no longer parses, watch invalidation no longer uses
addWatchFile, and HMR re-inference is now covered by a dev-server test.Why
plainCalleeIsMemoizablestates the constraint plainly today — an imported binding's "body is across a module boundary we cannot read". Every cross-module question the compiler faces is currently answered by assumption. This reads the module.The immediate consumer is dependency inference.
hook-deps.jshas a hardcodedSTABLE_TUPLE_RESULTStable for Octane's own built-ins; extraction generalises exactly that table to user-defined and third-party hooks:useDispatchanduseStoreRefare proven stable and drop out.useSelectedreturns live state, so it correctly survives — the analysis distinguishes them by reading their bodies.Two design calls, both load-bearing
Demand-driven, not a pre-pass. Bundlers transform an importer before its dependencies — the import graph is discovered by transforming — so a passive "pass 1 collects, pass 2 consumes" is always exactly one build too late. The importer pre-scans its own source and pulls only the imports that could change an answer.
Source text, not bundler metadata. The void-component proof next door rides Rollup module-graph
metaviacontext.load, which is precisely whyrspack-plugin-octanehas no equivalent. This needs onlyresolve+readFile, which Vite (this.resolve) and rspack (getResolve) both supply — so the identical analysis runs on each and the rspack adapter is ~30 lines.Soundness
Every fact is a property of one module's own source, provable by reading that module alone. That is what makes it cacheable per file and sound with no closed-world assumption.
Absence of a fact means "assume nothing", so the failure mode of the whole mechanism is the behaviour that predates it — never a missed dependency. Cycles, unresolvable specifiers, unparseable dependencies, and disagreeing return paths all resolve to absence, and each has a test.
Facts that need every call site — "this component's
onSelectprop is always passed a stable value" — are a different class. They are only sound under a closed world (no dynamic rendering, no prop spreads, nothing re-exported to an unseen consumer), so they need a whole-graph pass with explicit escape analysis. The module header says so explicitly rather than leaving the schema looking like it already supports them.Changes
module-facts.js(new): extraction, the synchronous candidate pre-scan, and the bundler-agnostic async graph walk with per-file cache, cycle guard, and depth cap.hook-deps.js: exports the scope walk + invariance lattice asanalyzeBindings, so a hook's return value is judged by exactly the rules a capture in the same module would be. Records import origin on bindings, and consumes a fact whereSTABLE_TUPLE_RESULTSis consulted for built-ins.vite.js/rspack-plugin-octane/src/loader.js: adapters supplying onlyresolve/readFile, both gated.module-facts.test.ts: 25 cases × 2 projects.Dev and production cannot diverge
The setting is per project, not per mode: the same analysis, the same build-scoped cache, and the same code path run in dev and in build.
hotUpdateis the mechanism that enforces that. Without it a long-lived dev server keeps the answer it inferred at first transform, while a fresh production build re-derives a new one from changed sources — the divergence is the absence of invalidation, not its presence. A dev-server test now proves it: boot Vite in middleware mode, transform a component, rewrite the imported hook so its result stops being provably stable, fire the watcher, re-transform. Removing the invalidation fails the second assertion; disabling facts fails the first.Both original blockers, solved
1. The pre-scan was a second parse of every module (+27% on compile). Now +0.1%.
The scan runs on every module the bundler transforms, so parsing there duplicated the parse of the entire program — 290ms of a 298ms pre-scan was the parse, only 9ms the walk.
The fix was to stop parsing. A candidate list only has to be a superset: precision comes later, from actually reading the dependency. Both error directions are safe — over-matching costs one cached analysis that yields no fact, under-matching loses an optimisation but can never produce a wrong answer, because a missing fact means "assume nothing". That is what makes a lexical scan the right tool rather than a corner cut. 361ms → 1ms over 300 modules.
2.
addWatchFileperturbed Vite's module graph. NowhotUpdate.Registering a resolved dependency as a watch file pushes Vite into re-resolving that absolute path against the importer, which trips any
resolveIdplugin policing what a module may import — the user-app eval sandbox is exactly such a plugin, and it broke. I instrumented the sandbox to confirm the mechanism rather than guess at it.Every file read is already a real import of the module, so the graph edge exists. What was missing is only re-transforming the importer when the dependency's contents change, and
hotUpdatedoes that directly without touching resolution. The full suite passes with the gate forced on.Validation
pnpm format:checkpnpm typecheckpnpm test— 14,261 passed, 0 failed (and separately, green with the gate forced ON)No changeset: with the gate off there is no user-facing behaviour change, and a changelog entry announcing a feature nobody can enable would be misleading. One goes in with the PR that turns it on.
Risk / follow-ups
Why it is off by default
I set out to enable it and the benchmark said not to. On the Octane website build:
and that buys 2 proven facts out of 315 candidate imports. Roughly half the cost is the transform having to go async at all, not the fact work — so a synchronous fast path over the build-scoped cache (returning a lookup without a promise when every candidate is already cached) is the route to a default-on version. Until then this would tax every Octane build for a benefit almost no app collects.
One earlier cost is already fixed:
resolveHookStabilitycreated a resolver per module, so every importer re-read and re-parsed the same dependencies — that alone was +29%. The cache is now build-scoped and pruned byhotUpdate.Off by default, so the risk of merging is confined to the new exports on
octane/compiler/bundlerand one plugin option per bundler.The cheapest first real consumer is probably not dependency inference but verifying autoMemo's blanket "imported callees are pure projections" assumption —
moduleHelperIsPureProjectionalready performs that analysis for same-module helpers, and its failure mode is benign (unproven → today's behaviour). That turns a documented assumption into a checked one.Happy to flip this to draft if you'd rather it not be mergeable while the gate is closed.
🤖 Generated with Claude Code
Note
Medium Risk
Touches compiler dependency inference and async bundler transforms when enabled; soundness relies on fail-closed proofs and cache invalidation, with broad test coverage but meaningful build-time and watch-mode complexity.
Overview
Adds opt-in cross-module hook facts (
crossModuleHookFacts: trueon the Vite compiler plugin,@octanejs/vite-plugin, and@octanejs/rspack-plugin). When enabled, omitted hook dependency lists can treat imported custom hooks like same-file built-ins: the bundler resolves the defining module, extracts provable stability (refs, setters, emptyuseMemo/useCallback, module constants, stable tuple slots, transparent re-exports), and passes a synchronousimportedHookStabilitylookup into client and server compiles.New
module-facts.jsimplements lexicalfindFactCandidates, per-moduleextractModuleFacts(reusing exportedanalyzeBindingsfromhook-deps.js), build-scoped cache/invalidation, andresolveHookStability.hook-deps.jsrecords import origins on bindings and applies facts in the invariance lattice (including tuple slots). Integrations wireresolve+readFile, track importers for HMR / watch re-transforms (VitehotUpdate+watchChange; RspackaddDependency+ per-compilation cache).Off by default — no candidates keeps the prior sync transform path; unproven or missing facts preserve old behavior. Docs and a changeset describe the feature;
module-facts.test.tsand a Vite dev-server test cover extraction, cycles, cache races, and re-inference when a hook stops being stable.Reviewed by Cursor Bugbot for commit e2754b6. Bugbot is set up for automated code reviews on this repo. Configure here.