Skip to content
Merged
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
11 changes: 5 additions & 6 deletions src/js_parser/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ pub mod Macro {
/// `bun_js_parser_jsc` reinterprets the bits as a `JSValue`.
pub javascript_object: MacroJSCtx,
/// Opaque pointer to the higher-tier macro-runner state
/// (resolver/env/macros/remap/bump). Allocated by `init` and leaked
/// (process lifetime); `bun_js_parser` never dereferences it.
/// (resolver/env/macros/remap/bump). Allocated by `init`, freed by
/// `deinit`; `bun_js_parser` never dereferences it.
pub data: *mut core::ffi::c_void,
}
impl Default for MacroContext {
Expand Down Expand Up @@ -180,10 +180,9 @@ pub mod Macro {
)
}
}
/// Free the boxed higher-tier state behind `data`. Only call when the
/// owning `Transpiler` is a short-lived bytewise clone (e.g. the
/// off-thread `RuntimeTranspilerStore` worker) — the long-lived
/// `vm.transpiler` instance leaks it intentionally (process-lifetime).
/// Free the boxed higher-tier state behind `data`. Its arena backs the
/// strings of every `Expr` its macros returned, so only call once the
/// ASTs that hold them are printed.
#[inline]
pub fn deinit(self) {
// SAFETY: `self.data` is either null (callee no-ops) or the exact
Expand Down
4 changes: 2 additions & 2 deletions src/js_parser_jsc/Macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub(crate) struct MacroContext {
/// UTF-16 string data / `from_blob` JSON sub-parse), so we own the backing arena here
/// — `MacroContext` is stored in the long-lived `Transpiler` and outlives
/// every `Expr` it produces (the parser splices the result into the AST and
/// prints it before the `Transpiler` drops).
/// prints it before the context is freed).
///
/// Lazy: `Arena::new()` calls `mi_heap_new()`, and `MacroContext::init`
/// runs once per `RuntimeTranspilerStore::TranspilerJob::run` iteration
Expand Down Expand Up @@ -273,7 +273,7 @@ fn __bun_macro_context_init(transpiler: *mut core::ffi::c_void) -> js_parser::Ma
// SAFETY: every caller of `js_parser::Macro::MacroContext::init<T>` passes a
// `&mut bun_bundler::Transpiler<'_>`; the lifetime parameter is erased at
// runtime so reading it as `'static` is layout-identical. The boxed state
// is leaked for the long-lived `vm.transpiler` instance — but callers that run on a
// stays with the long-lived `vm.transpiler` instance — but callers that run on a
// short-lived bytewise-cloned `Transpiler` (e.g.
// `RuntimeTranspilerStore::TranspilerJob::run`) MUST pair this with
// `__bun_macro_context_deinit` or the `Box<MacroContext>` (and, if a macro
Expand Down
2 changes: 1 addition & 1 deletion src/jsc/RuntimeTranspilerStore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -721,7 +721,7 @@ impl TranspilerJob {
// Note: `parse_maybe` re-creates the macro context per-iteration
// when `macro_context.is_none()`. It boxes a
// higher-tier `MacroContext` via `__bun_macro_context_init`; that Box
// is intentionally leaked for the long-lived `vm.transpiler`, but here
// stays with the long-lived `vm.transpiler`, but here
// we operate on a per-iteration `ManuallyDrop` bytewise copy, so we
// MUST free what `parse_maybe` allocates or every dynamic `import()`
// leaks one `Box<MacroContext>` (require-cache.test.ts "files
Expand Down
10 changes: 10 additions & 0 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6107,6 +6107,16 @@ impl VirtualMachine {
self.main_resolved_path = bun_core::String::EMPTY;
self.unhandled_error_counter = 0;

// Loaded macros are functions of the outgoing realm. The macro context
// remembers which ones are loaded, so the next file loads its own.
for callback in self.macros.values() {
callback.unprotect();
}
self.macros.clear_retaining_capacity();
if let Some(ctx) = self.transpiler.macro_context.take() {
ctx.deinit();
}
Comment thread
dylan-conway marked this conversation as resolved.
Comment thread
dylan-conway marked this conversation as resolved.

let old_global = self.global;
// `old_global` valid for VM lifetime (safe ZST-handle deref);
// `console` is the live per-VM ConsoleObject.
Expand Down
57 changes: 55 additions & 2 deletions test/cli/test/isolation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,42 @@ describe.concurrent("bun test --isolate", () => {
expect(exitCode).toBe(0);
});

test.each([
["--isolate", ["--isolate"], {}],
// One worker takes all three files (scale-up gated), so the second and third come after the worker's own swap.
["--parallel worker", ["--parallel=2"], { BUN_TEST_PARALLEL_SCALE_MS: "60000" }],
])("a test file's macros are loaded again for each file (%s)", async (_, args, env) => {
const files: Record<string, string> = {
"macro.ts": `
let calls = 0;
export function mark(name: string) { return name + ":" + ++calls; }
`,
};
const names = ["a", "b", "c"];
for (const name of names) {
files[`required-${name}.ts`] = `
import { mark } from "./macro.ts" with { type: "macro" };
export const required = mark("required-${name}");
`;
files[`${name}.test.ts`] = `
import { test, expect } from "bun:test";
import { mark } from "./macro.ts" with { type: "macro" };
const marks = [mark("${name}"), mark("${name}"), require("./required-${name}.ts").required];
test("${name}", () => { expect(marks).toEqual(["${name}:1", "${name}:2", "required-${name}:3"]); });
`;
}
using dir = tempDir("isolate-macro", files);
const { stderr, exitCode } = await runTests(
String(dir),
args,
names.map(name => `./${name}.test.ts`),
{ ...bunEnv, ...env },
);
expect(normalizeBunSnapshot(stderr, dir)).toContain("3 pass");
expect(normalizeBunSnapshot(stderr, dir)).toContain("0 fail");
expect(exitCode).toBe(0);
});

// The cached module record carries each name as Latin-1 or UTF-16; the second file links from that record.
test("with --isolate, cached module records keep short, Latin-1 and UTF-16 names", async () => {
using dir = tempDir("isolate-module-names", {
Expand Down Expand Up @@ -1643,13 +1679,13 @@ describe.concurrent("--isolate: a finished file's late completions do not run in
describe.concurrent("--isolate: collects globals pinned by leaked handles", () => {
const LEAK_FILE_COUNT = 8;

function makeLeakFixture(dirt: string): Record<string, string> {
function makeLeakFixture(dirt: string | ((i: number) => string)): Record<string, string> {
const files: Record<string, string> = {};
for (let i = 1; i <= LEAK_FILE_COUNT; i++) {
files[`file_${i}.test.js`] = `
import { test, expect } from "bun:test";
import { heapStats } from "bun:jsc";
${dirt}
${typeof dirt === "string" ? dirt : dirt(i)}
test("leak-${i}", () => {
Bun.gc(true);
Bun.gc(true);
Expand Down Expand Up @@ -1774,6 +1810,23 @@ describe.concurrent("--isolate: collects globals pinned by leaked handles", () =
expect(await maxLiveGlobals(String(dir))).toBeLessThanOrEqual(4);
});

// A macro that no later file loads again is never replaced, so each file has its own.
test("a macro left loaded", async () => {
using dir = tempDir("isolate-leak-macro", {
...makeLeakFixture(
i => `
import { macro${i} } from "./macro.ts" with { type: "macro" };
macro${i}();
`,
),
"macro.ts": Array.from(
{ length: LEAK_FILE_COUNT },
(_, i) => `export const macro${i + 1} = () => ${i + 1};`,
).join("\n"),
});
expect(await maxLiveGlobals(String(dir))).toBeLessThanOrEqual(4);
});

// The loader builds a module from only one of the two sources. The other source's value references its global.
test("two concurrent import() calls for the same data file", async () => {
using dir = tempDir("isolate-leak-data-import", {
Expand Down
Loading