← reports

#5733 · Mutable plugin loads rewrite unchanged host artifacts

BugPriority: MediumEffort: Lowplugins · perf · confirmed-reproGitHub issue

October 19, 2026 · trusted origin/main base 9937c46f5c7e369de3563eb864c8cbc4c3b9c231

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

A local plugin's host bundle is compiled again even when its sources and SDK have not changed. The plugin lifecycle loader unconditionally requests a host build for path plugins and source-built builtins. A regression test exercises the real plugin service, builds a temporary fixture, then reloads it or stops and starts the service. Both operations leave the bundle bytes identical but change its modification timestamp. The same two failures occur in a second clean checkout at the same trusted commit.

2. Claims vs findings

ClaimFindingEvidence
Unchanged host artifacts are rebuilt during mutable plugin loading.VerifiedReload and stop/start tests both fail the unchanged-mtime assertion after the identical-bytes assertion passes, in both checkouts.
Frontend loading already avoids fresh builds, unlike host loading.VerifiedThe frontend checks metadata and source timestamps; the host branch directly calls the builder.
Path plugins and source-built builtins share this path; packaged builtins are excluded.Verified in sourceThe loader's eligibility condition explicitly names path and builtin kinds and excludes packaged builtin host entries. The dynamic reproduction uses a path fixture.
Specific warm-build timing, CPU, or startup-speed numbers.Not measured hereThis investigation establishes actual redundant compilation/replacement, not whole-server startup latency or the reporter's benchmark figures.

3. Environment

4. Minimal reproduction

  1. Clone the trusted repository and select the recorded base:
git clone https://github.com/get-bb/bb.git bb-repro
cd bb-repro
git checkout 9937c46f5c7e369de3563eb864c8cbc4c3b9c231
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build

Save the following investigator-authored test as apps/server/test/services/plugins/plugin-host-build-policy.test.ts. It is reproduced inline so the public report needs no external script or private fixture.

import {
  mkdir,
  mkdtemp,
  readFile,
  rm,
  stat,
  writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { PLUGIN_SDK_VERSION } from "@bb/domain";
import { createMigratedConnection } from "@bb/db/testing";
import { createAiServiceRegistry } from "../../../src/services/ai/ai-service-registry.js";
import {
  createPluginService,
  type PluginService,
} from "../../../src/services/plugins/plugin-service.js";
import { createNoopTelemetryService } from "../../../src/services/system/telemetry.js";
import { testLogger } from "../../helpers/test-app.js";

describe("mutable plugin host build policy", () => {
  let service: PluginService;
  let db: ReturnType<typeof createMigratedConnection>;
  let workDir: string;
  let rootDir: string;
  let artifactPath: string;
  let metaPath: string;

  beforeEach(async () => {
    db = createMigratedConnection();
    workDir = await mkdtemp(join(tmpdir(), "bb-host-build-policy-"));
    service = createPluginService({
      db,
      dataDir: join(workDir, "data"),
      appVersion: "0.9.0",
      bundledPlugins: [],
      aiServices: createAiServiceRegistry(),
      telemetry: createNoopTelemetryService(),
      logger: testLogger,
      hub: {
        getDaemonSessionIdForHost: () => null,
        notifyPluginSignal: () => 0,
        notifySystem: () => {},
      },
    });
    rootDir = join(workDir, "bb-plugin-host-policy");
    artifactPath = join(rootDir, "dist", "host.js");
    metaPath = join(rootDir, "dist", "host.meta.json");
    await mkdir(rootDir, { recursive: true });
    await writeFile(
      join(rootDir, "package.json"),
      JSON.stringify({
        name: "bb-plugin-host-policy",
        version: "0.1.0",
        bb: {
          name: "Host policy fixture",
          description: "Host build lifecycle fixture.",
          branding: { icon: "Zap" },
          server: "./server.ts",
          host: "./host.ts",
        },
      }),
    );
    await writeFile(
      join(rootDir, "server.ts"),
      "export default function plugin() {}",
    );
    await writeFile(
      join(rootDir, "host.ts"),
      'export default { experimental_apiVersion: 1, value: "initial" };',
    );
    const installed = await service.installPath(rootDir);
    expect(installed.status).toBe("running");
  });

  afterEach(async () => {
    await service.stop();
    db.$client.close();
    await rm(workDir, { recursive: true, force: true });
  });

  it.each(["reload", "restart"])(
    "reuses an unchanged host artifact on %s",
    async (operation) => {
      const before = await stat(artifactPath);
      const bytes = await readFile(artifactPath);
      if (operation === "restart") {
        await service.stop();
        await service.start();
      } else {
        expect((await service.reload("host-policy")).ok).toBe(true);
      }
      expect(
        service.list().find((entry) => entry.id === "host-policy")?.status,
      ).toBe("running");
      expect(await readFile(artifactPath)).toEqual(bytes);
      expect((await stat(artifactPath)).mtimeMs).toBe(before.mtimeMs);
    },
  );

  it.each(["source", "artifact", "metadata", "invalid metadata", "SDK"])(
    "rebuilds when the %s changes or disappears",
    async (target) => {
      if (target === "source") {
        await writeFile(
          join(rootDir, "host.ts"),
          'export default { experimental_apiVersion: 1, value: "updated" };',
        );
      } else if (target === "artifact") {
        await rm(artifactPath);
      } else if (target === "metadata") {
        await rm(metaPath);
      } else {
        await writeFile(
          metaPath,
          target === "SDK"
            ? JSON.stringify({ sdkMajor: 0, sdkVersion: "0.0.0-stale" })
            : "not json",
        );
      }

      expect((await service.reload("host-policy")).ok).toBe(true);
      const metadata: unknown = JSON.parse(await readFile(metaPath, "utf8"));
      expect(metadata).toMatchObject({ sdkVersion: PLUGIN_SDK_VERSION });
      const artifact = await readFile(artifactPath, "utf8");
      expect(artifact).toContain(target === "source" ? "updated" : "initial");
    },
  );
});

Run from the repository root:

pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-host-build-policy.test.ts

Expected: all seven tests pass. Reloading or starting the plugin service preserves the bytes and modification timestamp of a fresh host artifact. Changes to source, missing output, missing/invalid metadata, or a stale SDK rebuild successfully.

Actual: two reuse tests fail at the mtime assertion, after byte equality succeeds; all five invalidation cases pass. Exit status is 1. The exact first-run output follows; checkout paths are redacted.

@bb/server:test:  RUN  v4.1.1 CHECKOUT/apps/server
@bb/server:test: 
@bb/server:test: (node:9022) ExperimentalWarning: SQLite is an experimental feature and might change at any time
@bb/server:test: (Use `node --trace-warnings ...` to show where the warning was created)
@bb/server:test:  ❯ |@bb/server| test/services/plugins/plugin-host-build-policy.test.ts (7 tests | 2 failed) 2556ms
@bb/server:test:      × reuses an unchanged host artifact on reload 129ms
@bb/server:test:      × reuses an unchanged host artifact on restart 52ms
@bb/server:test:      ✓ rebuilds when the source changes or disappears 45ms
@bb/server:test:      ✓ rebuilds when the artifact changes or disappears 44ms
@bb/server:test:      ✓ rebuilds when the metadata changes or disappears 41ms
@bb/server:test:      ✓ rebuilds when the invalid metadata changes or disappears 41ms
@bb/server:test:      ✓ rebuilds when the SDK changes or disappears 39ms
@bb/server:test: 
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯
@bb/server:test: 
@bb/server:test:  FAIL  |@bb/server| test/services/plugins/plugin-host-build-policy.test.ts > mutable plugin host build policy > reuses an unchanged host artifact on reload
@bb/server:test: AssertionError: expected 1792371110595.0032 to be 1792371110564.0503 // Object.is equality
@bb/server:test: 
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test: 
@bb/server:test: - 1792371110564.0503
@bb/server:test: + 1792371110595.0032
@bb/server:test: 
@bb/server:test:  ❯ test/services/plugins/plugin-host-build-policy.test.ts:98:50
@bb/server:test:      96|       ).toBe("running");
@bb/server:test:      97|       expect(await readFile(artifactPath)).toEqual(bytes);
@bb/server:test:      98|       expect((await stat(artifactPath)).mtimeMs).toBe(before.mtimeMs);
@bb/server:test:        |                                                  ^
@bb/server:test:      99|     },
@bb/server:test:     100|   );
@bb/server:test: 
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯
@bb/server:test: 
@bb/server:test:  FAIL  |@bb/server| test/services/plugins/plugin-host-build-policy.test.ts > mutable plugin host build policy > reuses an unchanged host artifact on restart
@bb/server:test: AssertionError: expected 1792371110652.4846 to be 1792371110633.379 // Object.is equality
@bb/server:test: 
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test: 
@bb/server:test: - 1792371110633.379
@bb/server:test: + 1792371110652.4846
@bb/server:test: 
@bb/server:test:  ❯ test/services/plugins/plugin-host-build-policy.test.ts:98:50
@bb/server:test:      96|       ).toBe("running");
@bb/server:test:      97|       expect(await readFile(artifactPath)).toEqual(bytes);
@bb/server:test:      98|       expect((await stat(artifactPath)).mtimeMs).toBe(before.mtimeMs);
@bb/server:test:        |                                                  ^
@bb/server:test:      99|     },
@bb/server:test:     100|   );
@bb/server:test: 
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯
@bb/server:test: 
@bb/server:test: 
@bb/server:test:  Test Files  1 failed (1)
@bb/server:test:       Tests  2 failed | 5 passed (7)
@bb/server:test:    Start at  00:51:11
@bb/server:test:    Duration  39.65s (transform 32.11s, setup 4.87s, import 26.73s, tests 2.56s, environment 0ms)
@bb/server:test: 
@bb/server:test:  ELIFECYCLE  Test failed. See above for more details.
@bb/server#test:  ERROR  command (CHECKOUT/apps/server) /usr/local/bin/pnpm run test test/services/plugins/plugin-host-build-policy.test.ts exited (1)

 Tasks:    8 successful, 9 total
Cached:    7 cached, 9 total
  Time:    41.324s 
Failed:    @bb/server#test

 ERROR  run failed: command  exited (1)

5. Root cause

The mutable host loader invokes the host builder on every load without checking SDK metadata or source freshness; the builder recompiles and replaces the artifact. The host artifact is still checked for size, metadata validity, and digest after building, but these checks happen too late to avoid compiling it. Frontend loading already has the freshness guard missing here.

if ((kind === "path" || kind === "builtin") && !isPackagedBuiltinEntry(...)) {
  await buildPluginHost(...);
  setDevBuildProblem(row.id, "host", null);
}

The runtime test, rather than a direct builder benchmark, proves the redundant call happens at the actual plugin lifecycle boundary. Static inspection shows the builder has no reuse shortcut. Identical bytes plus changed mtime are therefore an externally observable effect of the needless build, not an assumption based only on code shape.

6. Proposed fix

Reuse the existing mutable-artifact freshness walk with an app/host target. In the mutable host loader, parse existing metadata and build only when it is absent/invalid, its SDK differs, the output is missing, or plugin sources/directories are newer. Keep packaged-builtin eligibility, digest validation, artifact size limits, and explicit build commands unchanged. Preserve the current ignored directories (dist, node_modules, .git) rather than changing dependency or packaging policy.

The focused test intentionally covers both reload and startup, plus five invalidation cases. Existing frontend, prebuilt-server, host artifact serving, and build-problem tests are relevant compatibility checks.

7. Verification

The same investigator created a second clean detached worktree at the full base commit, performed a separate frozen installation and full Turbo build, copied only this investigator-authored test, and ran the identical Turbo test command. No production patch was present in either baseline run. This is a repeat by the same agent, not an independent review. The second run again has exactly two mtime failures and five passing invalidation cases. No correction to the final root-cause claim was needed.

@bb/server:test:  RUN  v4.1.1 VERIFY_CHECKOUT/apps/server
@bb/server:test: 
@bb/server:test: (node:9233) ExperimentalWarning: SQLite is an experimental feature and might change at any time
@bb/server:test: (Use `node --trace-warnings ...` to show where the warning was created)
@bb/server:test:  ❯ |@bb/server| test/services/plugins/plugin-host-build-policy.test.ts (7 tests | 2 failed) 2163ms
@bb/server:test:      × reuses an unchanged host artifact on reload 152ms
@bb/server:test:      × reuses an unchanged host artifact on restart 52ms
@bb/server:test:      ✓ rebuilds when the source changes or disappears 45ms
@bb/server:test:      ✓ rebuilds when the artifact changes or disappears 43ms
@bb/server:test:      ✓ rebuilds when the metadata changes or disappears 42ms
@bb/server:test:      ✓ rebuilds when the invalid metadata changes or disappears 39ms
@bb/server:test:      ✓ rebuilds when the SDK changes or disappears 38ms
@bb/server:test: 
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯
@bb/server:test: 
@bb/server:test:  FAIL  |@bb/server| test/services/plugins/plugin-host-build-policy.test.ts > mutable plugin host build policy > reuses an unchanged host artifact on reload
@bb/server:test: AssertionError: expected 1792371118146.8315 to be 1792371118115.7004 // Object.is equality
@bb/server:test: 
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test: 
@bb/server:test: - 1792371118115.7004
@bb/server:test: + 1792371118146.8315
@bb/server:test: 
@bb/server:test:  ❯ test/services/plugins/plugin-host-build-policy.test.ts:98:50
@bb/server:test:      96|       ).toBe("running");
@bb/server:test:      97|       expect(await readFile(artifactPath)).toEqual(bytes);
@bb/server:test:      98|       expect((await stat(artifactPath)).mtimeMs).toBe(before.mtimeMs);
@bb/server:test:        |                                                  ^
@bb/server:test:      99|     },
@bb/server:test:     100|   );
@bb/server:test: 
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯
@bb/server:test: 
@bb/server:test:  FAIL  |@bb/server| test/services/plugins/plugin-host-build-policy.test.ts > mutable plugin host build policy > reuses an unchanged host artifact on restart
@bb/server:test: AssertionError: expected 1792371118204.0789 to be 1792371118183.7742 // Object.is equality
@bb/server:test: 
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test: 
@bb/server:test: - 1792371118183.7742
@bb/server:test: + 1792371118204.0789
@bb/server:test: 
@bb/server:test:  ❯ test/services/plugins/plugin-host-build-policy.test.ts:98:50
@bb/server:test:      96|       ).toBe("running");
@bb/server:test:      97|       expect(await readFile(artifactPath)).toEqual(bytes);
@bb/server:test:      98|       expect((await stat(artifactPath)).mtimeMs).toBe(before.mtimeMs);
@bb/server:test:        |                                                  ^
@bb/server:test:      99|     },
@bb/server:test:     100|   );
@bb/server:test: 
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯
@bb/server:test: 
@bb/server:test: 
@bb/server:test:  Test Files  1 failed (1)
@bb/server:test:       Tests  2 failed | 5 passed (7)
@bb/server:test:    Start at  00:51:22
@bb/server:test:    Duration  35.95s (transform 28.91s, setup 4.64s, import 24.14s, tests 2.16s, environment 0ms)
@bb/server:test: 
@bb/server:test:  ELIFECYCLE  Test failed. See above for more details.
@bb/server#test:  ERROR  command (VERIFY_CHECKOUT/apps/server) /usr/local/bin/pnpm run test test/services/plugins/plugin-host-build-policy.test.ts exited (1)

 Tasks:    8 successful, 9 total
Cached:    7 cached, 9 total
  Time:    37.529s 
Failed:    @bb/server#test

 ERROR  run failed: command  exited (1)

Fix verification

A local fix adds the freshness guard without changing artifact validation or packaging behavior. After the production change, all seven focused cases pass. The relevant existing frontend build-policy, host artifact route, build-problem, and prebuilt-server tests also pass: 33 tests across five files. Server Turbo typecheck passes (five tasks). The broader verification inventory has pre-existing unmapped browser-CLI drift; it was not changed, and no browser/UI verification is claimed.

pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-host-build-policy.test.ts test/services/plugins/plugin-app-bundle.test.ts test/internal/internal-plugin-host-artifacts.test.ts test/services/plugins/plugin-dev-build-problems.test.ts test/services/plugins/prebuilt-server-loading.test.ts
Test Files  5 passed (5)
Tests       33 passed (33)

pnpm exec turbo run typecheck --filter=@bb/server
Tasks:      5 successful, 5 total

8. Related issues

#5729 concerns managed server-bundle caching, not this mutable host-loader branch. GitHub issue metadata and the repository's separate server-cache implementation distinguish the two. There were no linked or matching open pull requests for #5733 when checked; no pull-request branch or patch was run.

9. Appendix and trust boundary

The issue body was treated as untrusted claims, including its embedded reproduction and suggested edits; neither was executed or copied. The test was designed from trusted origin/main code and existing repository test conventions. All linked source locations were checked against the recorded trusted commit. The report does not validate specific performance savings, an OS-level server restart, or a dynamic source-built-builtin fixture.

Commands used: GitHub read-only metadata queries; fetch trusted main; create a detached worktree; frozen installs; full Turbo builds; the exact focused test command above in both checkouts; targeted source inspection. Initial fixture setup was refined before the two final baseline runs to supply the required server entry and isolate builtin/provider state. Public output omits local checkout identifiers, home paths, and unrelated logs.