Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions test/js/node/vm/vm-import-callback-lifetime-fixture.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions test/js/node/vm/vm-script-fetcher-leak.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ describe("node:vm importModuleDynamically lifetime", () => {
"alive-runInContext": { result: "hooked", referrer: "Script" },
"alive-compileFunction": { result: "hooked", referrer: "function" },
"alive-module": { result: "hooked", referrer: "SourceTextModule" },
"alive-sameSourceModules": {
first: { result: "hooked by first", referrer: "SourceTextModule" },
second: { result: "hooked by second", referrer: "SourceTextModule" },
},
"freed-perScriptClosures": { alive: 0 },
"stringFilename": { result: "ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING" },
};
Expand All @@ -134,6 +138,7 @@ describe("node:vm importModuleDynamically lifetime", () => {
"alive-runInContext",
"alive-compileFunction",
"alive-module",
"alive-sameSourceModules",
])("%s while collecting continuously", async scenario => {
const result = await bunRun([fixture, scenario], { BUN_JSC_collectContinuously: "1" });
expect(result).toSpawn(JSON.stringify(expected[scenario]));
Expand Down
70 changes: 70 additions & 0 deletions test/js/node/vm/vm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
runInThisContext,
Script,
SourceTextModule,
SyntheticModule,
} from "node:vm";

function capture(_: any, _1?: any) {}
Expand Down Expand Up @@ -1075,6 +1076,75 @@ test.each([
},
);

describe("SourceTextModules with the same identifier and source", () => {
// JSC lets module records with the same key and source text run one ModuleProgramExecutable, which keeps the source
// of the record that linked it. import() and stack traces read that source, and node:vm keeps each module's
// importModuleDynamically hook and line/column offsets there, so two SourceTextModules must never run one executable.
// JSC finds an executable to share through a weak map, and a module's functions keep it alive: every source here
// exports a function and every module stays reachable, so the earlier module's executable is there to be found.
const modules: SourceTextModule[] = [];
// No module here has a static import, so link() never calls its linker.
const noDependencies = () => {
throw new Error("unreachable");
};

async function load(tag: string) {
const dependency = new SyntheticModule(["tag"], function () {
this.setExport("tag", tag);
});
await dependency.link(noDependencies);
await dependency.evaluate();

const calls: { specifier: string; referrerIsThisModule: boolean }[] = [];
const module = new SourceTextModule(
`export const fromTopLevel = import("dep");
export function fromFunction() { return import("dep"); }`,
{
identifier: "same-identifier-and-source.mjs",
importModuleDynamically(specifier, referrer) {
calls.push({ specifier, referrerIsThisModule: referrer === module });
return dependency;
},
},
);
modules.push(module);
await module.link(noDependencies);
await module.evaluate();
const namespace = module.namespace as any;
return { calls, imported: [(await namespace.fromTopLevel).tag, (await namespace.fromFunction()).tag] };
}

test("each call their own importModuleDynamically", async () => {
const first = await load("first");
const second = await load("second");
const calls = [
{ specifier: "dep", referrerIsThisModule: true },
{ specifier: "dep", referrerIsThisModule: true },
];
expect({ first, second }).toEqual({
first: { calls, imported: ["first", "first"] },
second: { calls, imported: ["second", "second"] },
});
});
Comment on lines +1117 to +1128

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 nit (optional): maintainers get coverage for same-identifier executable sharing only in the main context, while the sibling test directly above runs both contexts. The new describe block at test/js/node/vm/vm.test.ts:1079 never passes a context option, so both tests only exercise the Zig global object. Fix: run the new hook and lineOffset tests over the same ["the main context", false], ["a new context", true] matrix the sibling at vm.test.ts:1033 uses, passing context to every SourceTextModule and SyntheticModule it creates. The executable map that enabled the old sharing is per JSGlobalObject, so a vm context is a separate instance of the hazard. [also at: test/js/node/vm/vm.test.ts:1079 - nit: two same-identifier modules sharing one vm.createContext() are not covered, so a regression limited to non-main contexts would pass this suite.]

Why this was flagged

The existing test at test/js/node/vm/vm.test.ts:1033-1077 covers the same-identifier-and-source hazard with test.each over the main context and a createContext({}) context, because the module executable map lives on each JSGlobalObject. The new describe at test/js/node/vm/vm.test.ts:1079 adds the hook and lineOffset variants but load() at vm.test.ts:1091 and lineOfThrow at vm.test.ts:1131 never set context, so every module lands on the main Zig::GlobalObject. A vm context is a NodeVMGlobalObject with its own executable map and its own import() entry at src/jsc/bindings/NodeVM.cpp:1700. If executable sharing came back for records on a NodeVMGlobalObject only, the second module in a context would again run the first module's importModuleDynamically hook and report the first module's lineOffset, and neither new test would fail. On the base branch there is no coverage for either context; after merging there is coverage for one of the two the sibling test treats as distinct.

Verification: A future regression of same-identifier executable sharing that is specific to vm contexts would go uncaught, because the new tests only run on the main global. The new describe block (test/js/node/vm/vm.test.ts:1079-1145) constructs every SourceTextModule and SyntheticModule without a context option. The sibling test directly above (vm.test.ts:1033-1077) runs a test.each matrix over both contexts.


test("each report positions with their own lineOffset", async () => {
async function lineOfThrow(identifier: string, lineOffset: number) {
const module = new SourceTextModule(`export function where() { return new Error("here").stack; }`, {
identifier,
lineOffset,
});
modules.push(module);
await module.link(noDependencies);
await module.evaluate();
return Number(/:(\d+):\d+\)?$/m.exec((module.namespace as any).where())![1]);
}
const shifted = await lineOfThrow("same-identifier-other-offset.mjs", 100);
const unshifted = await lineOfThrow("same-identifier-other-offset.mjs", 0);
expect(unshifted).toBe(await lineOfThrow("never-seen-identifier.mjs", 0));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 nit (optional): a wrong lineOffset applied to the second same-identifier module (off by one, doubled, partially shifted) still passes this test. The assertion at test/js/node/vm/vm.test.ts:1144 only checks shifted > unshifted, although lineOffset 100 must shift the reported line by exactly 100. Fix: assert the exact invariant, expect(shifted).toBe(unshifted + 100), which stays independent of absolute line numbers and matches the exact-line assertions the existing lineOffset test at vm.test.ts:2544 already makes. [also at: test/js/node/vm/vm.test.ts:1146 - nit: the lineOffset test only checks shifted is greater than unshifted, so a module that applied a wrong non-zero offset would still pass.]

Why this was flagged

The test at test/js/node/vm/vm.test.ts:1130-1145 compiles two SourceTextModules with identifier "same-identifier-other-offset.mjs", lineOffset 100 then 0, and reads the line from new Error("here").stack. At vm.test.ts:1144 it asserts only expect(shifted).toBeGreaterThan(unshifted). Any regression where the offset of a shared or re-used executable is applied wrongly but still positive (for example line 2, 50 or 201 instead of 101) passes. The repository review rules ask for the strongest invariant; the sibling test at vm.test.ts:2544 asserts the exact line for lineOffset 5. The base branch has no test here, so this is a weaker-than-necessary new assertion rather than a regression.

Verification: nit. Triggering condition: any regression that applies a SourceTextModule lineOffset of 100 as some other positive shift (off by one, doubled, partial) at function-call time. Mechanism verified: /home/claude/bun/test/js/node/vm/vm.test.ts:1144 reads expect(shifted).toBeGreaterThan(unshifted);. Line 1144 accepts 2, 50 or 201 just as readily as 101.

expect(shifted).toBeGreaterThan(unshifted);
});
});

// NodeVMSourceTextModule::createModuleRecord pairs import declarations with requestedModules() by position, but JSC lists
// a specifier once however many declarations name it: builds with assertions enabled abort on "More attributes nodes
// than requests" (other builds go on, with the attributes lined up by that position). In a subprocess, since the abort
Expand Down
Loading