Skip to content

Evict compiled plugin modules by their resolved filename - #4494

Merged
ymichael merged 1 commit into
get-bb:mainfrom
luketraas:fix/plugin-cjs-cache-realpath
Sep 30, 2026
Merged

ymichael merged 1 commit into
get-bb:mainfrom
luketraas:fix/plugin-cjs-cache-realpath

Conversation

@luketraas

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

Since #3681, path plugins compile to a content-addressed server.cjs under the data directory and load with require. After loading, the runtime deleted the require.cache entry using the artifact path as built from BB_DATA_DIR, but Node keys require.cache by the resolved real path. When the data directory path contains a symlink (for example Fedora Silverblue's /home → /var/home, a symlinked ~/.bb or BB_DATA_DIR, or macOS /var in tests), the delete missed. Each edited reload left the previous generation in require.cache, and a reload with unchanged content returned the stale cached module without re-running its top-level code.

What changed

  • apps/server/src/services/plugins/plugin-runtime.ts: resolve the artifact with require.resolve before requiring it, and evict that key. A missing artifact still reaches the existing catch, which rolls back and keeps the previous instance.
  • prebuilt-server-loading.test.ts: new case with a symlinked data directory. It checks that top-level code re-runs on every reload and that no require.cache entry or parent children reference remains under the real cache root. (The existing eviction test builds its prefix from the unresolved temp path, so on macOS it cannot see this.)
  • No wire, CLI, or SDK changes.

How you verified

  • The new test fails on main (expected 1 to be 3: two reloads reused the stale module) and passes with the fix.
  • vitest run test/services/plugins: 50 files, 529 tests passed. turbo run typecheck --filter=@bb/server passed.
  • Heap harness below: in-process createPluginService, a generated path plugin of 110 TypeScript modules, --expose-gc, 8 forced GCs per sample, heapUsed + external, Node 22.22.3 on macOS. Default compiled loader, symlinked data directory, plugin edited before each reload:
    • main: +11.3 MiB per reload; with --max-old-space-size=230, 30 reloads end in FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory.
    • this branch: the same capped run completes with no steady growth (−0.5 to +0.04 MiB per reload across runs).
    • unchanged-content reloads: about +0.1 MiB per reload on both.

Command, with the harness below saved as apps/server/bench-4159.mts: node --expose-gc --max-old-space-size=230 --conditions=source --import tsx bench-4159.mts default 30 changed from apps/server. The harness creates its own symlinked data directory; BENCH_SYMLINK=0 uses the real path instead, and same in place of changed reloads without edits.

Heap harness
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import pino from "pino";
import {
  createConnection,
  getExperiments,
  migrate,
  setExperiments,
} from "@bb/db";
import { createPluginService } from "./src/services/plugins/plugin-service.ts";
import { createAiServiceRegistry } from "./src/services/ai/ai-service-registry.ts";
import { createNoopTelemetryService } from "./src/services/system/telemetry.ts";

process.setSourceMapsEnabled(false);
const mode = process.argv[2] ?? "default";
const reloads = Number(process.argv[3] ?? "12");
const changeContent = process.argv[4] === "changed";
const gc = (globalThis as { gc?: () => void }).gc;
if (gc === undefined) throw new Error("run with --expose-gc");

async function settle(): Promise<number> {
  for (let i = 0; i < 8; i += 1) {
    gc!();
    await new Promise((resolve) => setImmediate(resolve));
  }
  const usage = process.memoryUsage();
  return (usage.heapUsed + usage.external) / 1024 / 1024;
}

const MODULES = 110;
const workDir = await mkdtemp(join(tmpdir(), "bb-bench-4159-"));
const useSymlink = process.env.BENCH_SYMLINK !== "0";
await mkdir(join(workDir, "real-data"));
await symlink(join(workDir, "real-data"), join(workDir, "linked-data"), "dir");
const dataDir = join(workDir, useSymlink ? "linked-data" : "real-data");
const rootDir = join(workDir, "bb-plugin-heavy");
await mkdir(join(rootDir, "src"), { recursive: true });
await writeFile(
  join(rootDir, "package.json"),
  JSON.stringify({
    name: "bb-plugin-heavy",
    version: "0.1.0",
    bb: {
      name: "Heavy",
      description: "Heavy source plugin",
      branding: { icon: "Zap" },
      server: "./server.ts",
    },
  }),
);
async function writeModules(generation: number) {
  for (let m = 0; m < MODULES; m += 1) {
    const rows = Array.from(
      { length: 400 },
      (_, r) =>
        `  { id: ${r}, label: "module ${m} row ${r} ${"payload".repeat(10)}", value: ${r * m} },`,
    ).join("\n");
    await writeFile(
      join(rootDir, "src", `m${m}.ts`),
      `export interface Row${m} { id: number; label: string; value: number }\nexport const rows${m}: Row${m}[] = [\n${rows}\n];\nexport function sum${m}(): number { return rows${m}.reduce((t, r) => t + r.value, 0) + ${m === 0 ? generation : 0}; }\n`,
    );
  }
  const imports = Array.from(
    { length: MODULES },
    (_, m) => `import { sum${m} } from "./src/m${m}.ts";`,
  ).join("\n");
  const calls = Array.from({ length: MODULES }, (_, m) => `sum${m}()`).join(
    " + ",
  );
  await writeFile(
    join(rootDir, "server.ts"),
    `${imports}\nexport default function plugin(bb: any) {\n  const total = ${calls};\n  bb.log.info("heavy loaded " + total);\n}\n`,
  );
}
await writeModules(0);

const db = createConnection(":memory:");
migrate(db);
if (mode === "legacy") {
  setExperiments(db, { ...getExperiments(db), legacyJitiPluginLoader: true });
}
const service = createPluginService({
  aiServices: createAiServiceRegistry(),
  telemetry: createNoopTelemetryService(),
  db,
  hub: {
    getDaemonSessionIdForHost: () => null,
    notifyPluginSignal: () => 0,
    notifySystem: () => {},
  },
  logger: pino({ enabled: false }),
  dataDir,
  appVersion: "0.9.0",
  loadTimeoutMs: 60_000,
});
const baseline = await settle();
const entry = await service.installPath(rootDir);
if (entry.status !== "running") {
  throw new Error(`plugin not running: ${entry.status} ${entry.statusDetail}`);
}
const samples: number[] = [await settle()];
for (let i = 1; i <= reloads; i += 1) {
  if (changeContent) await writeModules(i);
  const reloaded = await service.reload(entry.id);
  if (!reloaded.ok) throw new Error(`reload ${i}: ${reloaded.error}`);
  samples.push(await settle());
}
const deltas = samples.slice(1).map((v, i) => v - samples[i]!);
const steady = deltas.slice(Math.floor(deltas.length / 2));
const meanSteady = steady.reduce((a, b) => a + b, 0) / steady.length;
console.log(
  JSON.stringify({
    mode,
    symlinkedDataDir: useSymlink,
    changeContent,
    reloads,
    baselineMiB: +baseline.toFixed(1),
    afterInstallMiB: +samples[0]!.toFixed(1),
    finalMiB: +samples.at(-1)!.toFixed(1),
    totalGrowthMiB: +(samples.at(-1)! - samples[0]!).toFixed(1),
    steadyPerReloadMiB: +meanSteady.toFixed(2),
    perReloadMiB: deltas.map((d) => +d.toFixed(1)),
  }),
);
await service.stop();
await rm(workDir, { recursive: true, force: true });

Follow-ups not changed here: source-module eviction under --preserve-symlinks and the built-in Zod parent URL set also compare unresolved paths.

Refs #4159

AGENT GENERATED

After requiring a compiled plugin server artifact, the runtime deleted
its require.cache entry using the artifact path as built from the data
directory. Node keys require.cache by the resolved real path, so when
the data directory path contains a symlink (for example /home on
Fedora Atomic, a symlinked ~/.bb or BB_DATA_DIR, or macOS /var in
tests) the delete missed. Every edited reload then kept the previous
generation's module graph alive, and a reload with unchanged content
returned the stale cached module without re-running its top-level
code.

Resolve the artifact filename with require.resolve before requiring it
and evict that key.

Measured with a 110-module, 4.8 MB TypeScript path plugin, symlinked
data directory, edited before each reload: main retained 11.3 MiB per
reload and died with "JavaScript heap out of memory" under a 230 MiB
heap cap within 30 reloads; with this change the same run completes
at 0.04 MiB per reload.

The JITI and ESM registry retention reported in get-bb#4159 no longer
applies to the default loader since get-bb#3681; this fixes the remaining
CommonJS eviction gap.

Refs get-bb#4159

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit adbce96 into get-bb:main Sep 30, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants