Skip to content

Move plugin compilation off the server event loop - #3681

Merged
ymichael merged 9 commits into
mainfrom
bb/investigate-modal-sandbox-plugin-error-thr_7eghypnuzb
Sep 25, 2026
Merged

ymichael merged 9 commits into
mainfrom
bb/investigate-modal-sandbox-plugin-error-thr_7eghypnuzb

Conversation

@ymichael

@ymichael ymichael commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

The plugin runtime loaded every server entry, including compatible prebuilt marketplace and bundled artifacts, through JITI. Its synchronous transformation and module loading could block the server event loop while loading a large bundle such as Modal Sandbox, causing BB Connect heartbeats to time out and report the tunnel client as offline.

What changed

  • Load compatible prebuilt ESM server artifacts with native import. Compile source/path plugins and compatible prebuilds without ESM package scope asynchronously through esbuild, then load the compiled CommonJS artifact.
  • Publish compiled artifacts atomically into a content-addressed cache, prune old artifacts, and evict loaded source modules on reload. Preserve source module locations and cross-plugin dynamic imports; reject static source imports that escape the plugin directory.
  • Pass runtime-validated manifest metadata into compilation without weakening release asset validation. Resolve BB-owned runtime imports through native hooks and bundle SDK subpaths from the plugin's installed SDK.
  • Preserve esbuild's external classification for bare Node built-ins during runtime dependency resolution. Use runtime Zod fallback only when the plugin has no installed copy; release builds still reject missing Zod dependencies.
  • Preserve the shared server Zod runtime for prebuilt builtin plugins with both native and legacy loaders. Keep Zod dependency resolution out of the generic fallback resolver to prevent recursive resolution.
  • Retain JITI behind the persisted legacyJitiPluginLoader experiment, with Settings UI, CLI coverage, configuration docs, and BB guide content. Changes apply on the next plugin load, install, update, enable, reload, or server restart.
  • Keep each file's module format when preserving source locations, so CommonJS dependencies keep their named exports (Modal Sandbox's modal → nice-grpc failed with 39 build errors otherwise).
  • Skip the source-boundary check for importers inside the plugin's own node_modules, matching symlinked dependencies. It and the Zod locale stub re-resolved ../locales/index.js with each other's markers forever, exhausting the server heap whenever Zod was installed inside the plugin root (the normal git/npm layout); the server crash-looped on boot.
  • Define __dirname and __filename per module alongside the preserved import.meta values, so plugin sources and bundled dependencies resolve adjacent files from their original locations rather than the runtime cache.
  • Accept a CommonJS entry whose module.exports is the factory, as JITI did.
  • Plugin factories still execute in-process with the existing timeout. There are no server/host-daemon wire changes, so HOST_DAEMON_PROTOCOL_VERSION is unchanged.

How you verified

Commandeered and verified on head e36b9560fe (base 9781a2126a) against an isolated pnpm start:worktree server with a fresh data directory.

Automated

  • pnpm exec turbo run test --filter=@bb/server --filter=@bb/plugin-build --filter=@bb/cli: plugin-build 170 passed; CLI 860 passed; server 3,188 passed. The three install-machine-script.test.ts failures differed between runs, passed 2/2 in isolation, and passed on the unmodified head.
  • After the factory-export change, test/services/plugins: 531 passed.
  • App tests touched by this PR: 12 passed. Typecheck and lint passed for @bb/server and @bb/plugin-build; Prettier passed on changed files.
  • New regression tests fail on the previous head and pass now: CommonJS dependency named exports, Zod inside the plugin root, __dirname/__filename in source and dependencies, and a module.exports factory.

Live app

  • Modal Sandbox from source: legacy JITI stalled /health for 984 ms; the compiled loader's maximum was 18 ms. Source edits appear after reload, cache entries are content-addressed and pruned to four, and a failed reload keeps the previous instance.
  • A plugin without installed Zod and one with its own Zod 4.1.12: server-side RPC validation rejects invalid input and accepts valid input.
  • The Legacy plugin loader (JITI) switch toggles in Settings, persists after reload, and matches bb settings show. With it enabled, plugins load through JITI without new compiled artifacts.

Community marketplace sweep
Installed 251 of 255 bb-community plugins. The four failures were plugin-side: an unsupported bb range, two frontend bundles, and a private repository.

  • Prebuilt ESM, enabled one at a time: 244/251 load; maximum /health latency 122 ms, with none above 500 ms.
  • Forced compile from source through the server: 245/251 load. Every plugin that loads prebuilt also loads compiled; cloud-sandbox works only from source because its prebuilt bundle is missing a script under both loaders.
  • The same source through the compiled loader and JITI in isolated processes: no plugin fails only when compiled. Maximum event-loop delay was 566 ms compiled versus 12.3 s under JITI; delays over 500 ms occurred 3 times versus 22.
  • The seven remaining errors are plugin-side under both loaders: removed SDK APIs (experimental_statusLabels, AI-service declarations) and cloud-sandbox's missing prebuilt asset.
  • Before __dirname/__filename preservation, claude-auth failed compiled. Discord's bundled @discordjs/ws worker path also pointed into the cache.
  • A static scan of 245 compiled bundles found no computed import() or require() calls. No plugin failed on top-level await.

Known limitations (follow-ups)

  • Top-level await in source-compiled graphs fails with esbuild's CommonJS-format error. Prebuilt ESM is unaffected.
  • A bare package name passed to import() through a variable resolves from the runtime cache in source-compiled plugins. No community plugin currently does this.

🤖 Generated with Claude Code

AGENT GENERATED

@ymichael
ymichael force-pushed the bb/investigate-modal-sandbox-plugin-error-thr_7eghypnuzb branch from 5510db1 to 3cba405 Compare September 14, 2026 23:44
@ymichael

Copy link
Copy Markdown
Collaborator Author

@bb-code-review

@bb-code-review

Copy link
Copy Markdown

🚨 SLOP COP 🚨 · bb-code-review

I’m the bb code review bot. I’m reviewing this PR now and will follow up with findings.

ymichael added a commit that referenced this pull request Sep 15, 2026
## Human comments

## What was wrong

The published-bridge regression built a real 682 KB host artifact and
then imported that generated artifact through Vitest's transform/module
pipeline. The package already externalized builtin generated host
artifacts for native Node loading, but the bridge fixture was omitted.
On the contended package shard, the necessary esbuild lifecycle plus
this avoidable second processing pass crossed Vitest's ordinary 5-second
test boundary. The failing CI run reported 5.500 seconds; the unchanged
test reproduced on the required Intel host at 5.142 seconds under 48
bounded CPU workers.

## What changed

Load the generated bridge host artifact through a cache-busted file URL
and include that fixture path in Vitest's existing native-artifact
externalization rule. Declare the fixture package as ESM so Node loads
the emitted ESM directly without reparsing or warning.

The real host build and all published bridge, bundled dependency, and
executed SemVer assertions remain intact. There are no server/daemon
wire changes, so `HOST_DAEMON_PROTOCOL_VERSION` does not change. PR
#3681 is the only open PR touching `packages/plugin-build`; it changes
the server builder and does not overlap these host-test files.

## How you verified

- CI evidence: https://github.com/get-bb/bb/actions/runs/35011632112,
`Tests (packages, ubuntu-latest, Node 22.x)`, exact 5.500-second timeout
at `build-plugin-host.test.ts:235`.
- Deterministic local red: unchanged test timed out at 5.142 seconds
under 48 bounded CPU workers on Intel `host_nwqfteeqz4`.
- Unloaded before/after: 1.281 seconds to 0.923 seconds.
- Same-load before/after: 5.142-second timeout to 2.731 seconds; three
further 48-worker runs passed at 2.755, 2.681, and 4.988 seconds.
- Complete focused file: 9/9 tests passed; target completed in 871 ms.
- `pnpm exec turbo run test typecheck build --filter=@bb/plugin-build
--output-logs=full`: 9/9 Turbo tasks passed; package tests passed 139
tests with 1 skipped, and typecheck/build passed.
- PR CI Node 22: the target passed in 2.720 seconds and all 139
`@bb/plugin-build` tests passed. The first run had unrelated Account
Pool toast-test and runner-download failures; rerunning only the failed
jobs passed, and CI run 35016480290 is green.
- `pnpm exec oxfmt --check
packages/plugin-build/src/build-plugin-host.test.ts
packages/plugin-build/vitest.config.ts` and `git diff --check` passed.
- Every load/test/build command had an external process-group deadline
with TERM/KILL cleanup. Post-run survivor scans were empty.

> AGENT GENERATED: by GPT-5.6-Sol.

@bb-code-review bb-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🚨 SLOP COP 🚨 · bb-code-review

This PR replaces synchronous JITI loading with native imports and an asynchronous, content-addressed esbuild cache, while retaining JITI behind an experiment. That should prevent large compatible bundles from stalling the server heartbeat, and the UI/CLI fallback is wired through correctly. The default loader still has several compatibility and lifecycle defects that can break valid plugins or keep stale code running, though.

Findings

  1. P1 — Compatible prebuilt plugins fail when their package is CommonJS. packages/plugin-build/src/build-plugin-server.ts:127-133 always emits ESM to dist/server.js, and apps/server/src/services/plugins/plugin-runtime.ts:1673 now imports that file natively. The manifest schema accepts packages with "type": "commonjs", so Node treats the generated .js as CommonJS and fails on its first import statement. A focused plain Node 22.19 probe using the actual builder reproduced SyntaxError: Cannot use import statement outside a module. These packages loaded through JITI before this change; emit an unambiguously ESM artifact (for example .mjs or an ESM-scoped cache location), or reject the package type at the manifest boundary.

  2. P1 — Computed relative dynamic imports resolve from the cache directory instead of the plugin. Source bundles are relocated by apps/server/src/services/plugins/plugin-server-cache.ts:104, but esbuild leaves a non-static expression such as const target = "./helper.js"; await import(target) in the output. Node then looks for <cache>/helper.js and throws ERR_MODULE_NOT_FOUND; under JITI it resolved beside the source file. The new cross-plugin test covers only an absolute target. The cached artifact needs to preserve the source module's base for unresolved dynamic imports.

  3. P1 — The import.meta.url compatibility transform corrupts valid source and only preserves one use per file. packages/plugin-build/src/build-plugin-server.ts:154 performs a single raw text replacement before parsing. An occurrence in a string, template, regex, or comment can consume the replacement and can make the file invalid ("import.meta.url" becomes ""file:///…""); when a file has multiple actual meta-properties, later ones still point into the cache. plugins/monaco-editor/server.ts already contains two uses. The isolated browser run also installed a valid fixture that failed with Expected ";" but found "file", then loaded unchanged under the legacy JITI experiment. This needs a syntax-aware, per-module transform, including the equivalent import.meta.dirname/filename semantics.

  4. P1 — The cache key does not cover the full input graph esbuild compiles. apps/server/src/services/plugins/plugin-server-cache.ts:29-39 ignores every dist and node_modules path, records symlinks without hashing their targets, and hashes only the plugin root. Meanwhile esbuild can compile a bb.server entry under dist, bundle SDK subpaths from node_modules, follow symlinks, and bundle ../shared.js because the outside-root resolver at packages/plugin-build/src/build-plugin-server.ts:240 only sees absolute specifiers. In the live isolated app, changing only ../shared.js from outside-v1 to outside-v2 and successfully reloading still returned outside-v1. Key the cache from esbuild's complete resolved input graph, or externalize/reject every input outside the hashed tree.

  5. P1 — Reload generations accumulate permanently in memory, resolver state, and on disk. Each load at apps/server/src/services/plugins/plugin-runtime.ts:1671 creates a new query-qualified ESM identity, which Node cannot evict; a focused 500-generation probe retained about 60 MB of heap and 117 MB of RSS after forced GC. Each changed source digest also adds another mutable root that every later module resolution scans, and plugins/runtime/server has no retention or GC path. A normal long-running bb plugin dev session therefore grows memory and disk continuously and makes resolution progressively more expensive. Superseded roots/cache entries need bounded cleanup, and reloadable code needs a reclaimable worker/process/realm rather than permanent module-map identities.

The security pass found no separate authentication, authorization, injection, SSRF, unsafe-deserialization, or secret-handling regression; accepted server plugins were already full-trust code. The wider architecture scan's concrete concerns are included above rather than repeated.

Verification

The isolated source app, server, and daemon passed health/ownership checks. Through real browser input, the Legacy plugin loader experiment toggled and persisted, affected the next reload, and was restored; a disposable plugin also installed, disabled, re-enabled, reloaded, and changed from lifecycle-v1 to lifecycle-v2, with matching source CLI results. Focused tests passed (@bb/plugin-build 6/6 and selected server plugin suites 45/45), and the PR's GitHub checks are green. The verification inventory reported the pre-existing unrelated drift Unmapped CLI family: browser; nothing was changed to hide it. All fixtures, the isolated store, browser, and dev processes were cleaned up.

@ymichael

Copy link
Copy Markdown
Collaborator Author

Addressed all five review findings in acd2986:

  1. Release builds now place ESM in an explicit module scope, and existing compatible ESM prebuilds inside CommonJS packages are recompiled to a cached CJS runtime artifact.
  2. Computed relative dynamic imports are syntax-aware rewritten against their original source module URL.
  3. import.meta.url, import.meta.dirname, and import.meta.filename are transformed through esbuild parsing; strings, templates, regexes, and repeated uses remain intact.
  4. Runtime cache identity is derived from the compiled artifact, covering the actual bundled graph; static imports escaping the plugin tree are rejected explicitly.
  5. Source factories load through reclaimable CJS, are removed from both require.cache and parent.children, mutable resolver roots are owned per loaded plugin, and disk artifacts are capped at four generations.

Verification:

  • @bb/server plugin suite: 45 files / 501 tests passed
  • @bb/plugin-build: 11 files / 144 passed / 1 skipped
  • @bb/server and @bb/plugin-build typechecks passed
  • @bb/server, @bb/plugin-build, and @bb/cli production builds passed
  • Live worktree server: 30 plugins, zero error statuses; Modal reload succeeds in expected unconfigured state
  • Live source fixture verified computed relative import refresh and source-relative import.meta values across reload

@bb-code-review please re-review the latest commit.

@bb-code-review

Copy link
Copy Markdown

🚨 SLOP COP 🚨 · bb-code-review

I’m the bb code review bot. I’m reviewing this PR now and will follow up with findings.

@bb-code-review bb-code-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🚨 SLOP COP 🚨 · bb-code-review

This PR changes how BB starts plugin backends: compatible packaged plugins are loaded directly by Node, while source-only or incompatible plugins are compiled asynchronously into a runtime cache instead of being transformed synchronously by JITI. The goal is to keep large plugin loads from freezing the server and dropping Connect heartbeats, with a documented experiment available to restore the old loader. The direction is good, but the new default path still changes valid plugin behavior and contains work that can block or repeat unnecessarily.

Findings

  1. P1 — The cached source path does not preserve the existing server-module contract. apps/server/src/services/plugins/plugin-server-cache.ts:118 forces every path plugin and source fallback through format: "cjs", even though plugin server entries and the normal release builder are ESM. That causes several independently reproduced failures:

    • a valid entry using top-level await fails during install with Top-level await is currently not supported with the "cjs" output format;
    • import.meta.resolve(...) becomes import_meta.resolve is not a function;
    • CommonJS-scoped source using __dirname or __filename sees the data-directory cache rather than the source directory, so adjacent assets fail with ENOENT;
    • a computed bare import such as import(packageName) resolves from the cache and cannot find a dependency installed in the plugin's own node_modules.

    The same fixtures load under the legacy JITI path. In the isolated app, the __dirname and import.meta.resolve failures were visible in Installed Plugins; enabling the legacy-loader experiment and reloading made both plugins healthy. This needs a module-loading design that preserves ESM and CommonJS source semantics, rather than adding more one-off replacements. The Plugin Guide should also be corrected: it currently says the cached artifact is native ESM while still saying path entries load TypeScript directly without a build step.

  2. P1 — Explicit reload can retain module-scoped state from the disposed ESM generation. apps/server/src/services/plugins/plugin-runtime.ts:269 returns a no-op when the digest is unchanged. The following native import therefore reuses the same query-qualified URL from Node's module cache. A focused service reproduction called reload twice: the plugin factory ran twice, but top-level module evaluation ran only once. Module-level singletons, counters, and resources can consequently leak from the old instance into the replacement even though reload previously used JITI with moduleCache: false.

  3. P1 — The computed-import compatibility rewrite can itself freeze the event loop. In packages/plugin-build/src/build-plugin-server.ts:115-119, every non-literal dynamic import reconstructs the entire transformed module with two slices and a concatenation. This callback runs in the server process, so the work is quadratic in module size and import count. A focused 304 KB / 5,000-import benchmark took 5.59 seconds and delayed a 2 ms timer by 5.41 seconds; the same build without this rewrite took 93 ms with 8 ms maximum lag. That recreates the class of heartbeat stall this PR is meant to remove. Build the rewritten output in one pass instead of repeatedly copying the full string.

  4. P2 — A warm cache hit still recompiles the whole plugin. apps/server/src/services/plugins/plugin-server-cache.ts:112-135 invokes buildPluginServer before calculating the digest and checking whether that artifact already exists. Unchanged source plugins are therefore read, transformed, bundled, source-mapped, and hashed on every reload and server start; only the final promotion is skipped. An instrumented repeat call returned the same cache path and unchanged mtime but invoked the toolchain twice. Because startup awaits plugin loads serially, warm-start cost grows with the sum of all source-plugin builds.

No separate authentication, authorization, injection, secret-handling, traversal, SSRF, unsafe-deserialization, or cache-poisoning regression was found. The wider architecture scan found no existing abstraction that removes the issues above.

The focused plugin-build, server loader/cache, plugin-service, builtin-plugin, and typecheck runs passed, and the PR's GitHub checks are green. The end-to-end worker was cancelled by a plugin restart before it could submit its structured result; I recovered its recorded browser/CLI evidence described above and verified cleanup myself. The isolated data directory, fixtures, browser, and dev processes are gone, all three ports are free, and the worktree is clean. The verification inventory also still reports the unrelated pre-existing drift Unmapped CLI family: browser.

@ymichael
ymichael force-pushed the bb/investigate-modal-sandbox-plugin-error-thr_7eghypnuzb branch from acd2986 to 6a497fc Compare September 24, 2026 23:24
ymichael and others added 5 commits September 24, 2026 17:10
The source-location transform forced every loaded file to ESM, so
CommonJS dependencies lost their named exports; Modal Sandbox failed to
build because modal imports ClientError and Status from nice-grpc.

The source-boundary resolver also re-resolved imports from dependencies
installed inside the plugin root. With Zod there, it and the Zod locale
stub re-resolved ../locales/index.js with each other's markers forever,
exhausting the server heap. Treat in-root node_modules like symlinked
dependencies and leave them to the normal resolver.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
JITI evaluated each plugin module in place, so __dirname and __filename
named its own file. The compiled loader bundles into the runtime cache,
which made them point there instead. The claude-auth community plugin
could no longer find its helper script, and the Discord plugin's bundled
@discordjs/ws would look for its worker file in the cache.

Define both per module alongside the preserved import.meta values.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
JITI treated a CommonJS entry's module.exports as its default export.
The compiled loader required the entry and read only .default, so a
plugin written as module.exports = function plugin() {} failed to load.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@ymichael
ymichael merged commit 51d0e97 into main Sep 25, 2026
18 checks passed
@ymichael
ymichael deleted the bb/investigate-modal-sandbox-plugin-error-thr_7eghypnuzb branch September 25, 2026 18:38
ymichael pushed a commit that referenced this pull request Sep 30, 2026
## 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.

<details><summary>Heap harness</summary>

```ts
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 });
```

</details>

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

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

1 participant