#5729 · Source server cache compiles before lookup
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
The source-build cache preserves the finished plugin artifact but does not avoid compiling it again. Two fresh Node processes using identical source, SDK version, bb version, and a shared cache each invoke the real compiler. They return exactly the same artifact path and digest, so this is a compile-before-cache-lookup defect, not a failure to retain the output. A plugin whose prebuilt bundle fails the SDK compatibility check reaches this source-build path. The focused regression fails for this precise reason in two clean trusted-main checkouts.
2. Claims vs findings
| Claim | Status | Evidence |
|---|---|---|
| An unchanged source plugin compiles again in a later process. | Verified | Two child processes, two compiler calls, identical returned path/digest; repeated in a second checkout. |
| Pre-1.0 prebuilt bundles require an exact SDK version. | Verified | pre-1.0 SDK compatibility check; the existing runtime suite also passes the differing-minor and differing-major fallback cases. |
| Output hashing happens before the cache check. | Verified | cache: compile, hash, then look up; compilation precedes hashing, which precedes checking the existing cache entry. |
| Seven affected plugins caused noticeable user startup delay. | Unverified | No access to the reporter's plugins or instance; no end-to-end startup timing was measured. |
| Historical release-to-SDK version mappings. | Unverified | Not needed for the defect; the checked main SDK package is 0.6.54. |
3. Environment
- Trusted public repository:
get-bb/bb, detachedorigin/mainatf9eae1c44cd67e3dcbf807809bda8999926f7967. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; Turbo 2.10.12; Vitest 4.1.1; pinned esbuild 0.28.1.
- Both checkouts completed
pnpm install --frozen-lockfile --prefer-offlineandpnpm exec turbo run build: 67 build tasks successful in each. - No real user instance, provider, network-facing development app, or listening port was used. Each run allocates a new temporary plugin and data directory, shared only by its own two child processes, and removes them afterward.
4. Minimal reproduction
- Clone the trusted repository, check out the recorded base, install and build:
git clone https://github.com/get-bb/bb.git bb-repro-5729 cd bb-repro-5729 git checkout --detach f9eae1c44cd67e3dcbf807809bda8999926f7967 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build
- Save the test below as
apps/server/test/services/plugins/plugin-server-cache-reuse.test.ts. - Run from the repository root:
pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-server-cache-reuse.test.ts
The instrumentation delegates to the actual esbuild module. It records real build() calls in a file shared by both child processes; it does not mock the cache, compiler output, or persistence.
Expected after the first process: "build\n" Actual after the first process: "build\n" Expected after the second process: "build\n" Actual after the second process: "build\nbuild\n" AssertionError: expected 'build\nbuild\n' to be 'build\n' // Object.is equality
The assertion that both processes return identical serialized path/digest succeeds before the compile-count assertion fails. The cached artifact is reused, but the compilation work is repeated.
Complete reproduction test
import { execFile } from "node:child_process";
import {
appendFile,
mkdir,
mkdtemp,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { resolvePluginBuildToolchain } from "@bb/plugin-build";
import { expect, it } from "vitest";
const run = promisify(execFile);
it("reuses a source-built server across fresh processes without compiling again", async () => {
const workDir = await mkdtemp(join(tmpdir(), "bb-server-cache-reuse-"));
try {
const rootDir = join(workDir, "plugin");
await mkdir(rootDir);
await writeFile(join(rootDir, "server.ts"), "export default () => 42;\n");
const marker = join(workDir, "builds.txt");
await appendFile(marker, "");
const toolchain = await resolvePluginBuildToolchain(
join(workDir, "toolchain"),
);
const compilerPath = join(workDir, "compiler.mjs");
await writeFile(
compilerPath,
`import * as compiler from ${JSON.stringify(toolchain.esbuild)};
import { appendFile } from "node:fs/promises";
export const transform = compiler.transform;
export async function build(options) {
await appendFile(${JSON.stringify(marker)}, "build\\n");
return compiler.build(options);
}
`,
);
const workerPath = join(workDir, "worker.mjs");
const cacheModule = new URL(
"../../../src/services/plugins/plugin-server-cache.ts",
import.meta.url,
).href;
await writeFile(
workerPath,
`import { buildCachedPluginServer } from ${JSON.stringify(cacheModule)};
const result = await buildCachedPluginServer({
rootDir: ${JSON.stringify(rootDir)},
dataDir: ${JSON.stringify(join(workDir, "data"))},
pluginId: "cache-reuse",
sdkVersion: "0.6.54",
bbVersion: "0.46.1",
validatedConfig: ${JSON.stringify({ serverEntry: join(rootDir, "server.ts"), packageName: "bb-plugin-cache-reuse", pluginVersion: "1.0.0" })},
toolchain: async () => (${JSON.stringify({ ...toolchain, esbuild: pathToFileURL(compilerPath).href })}),
runtimeImports: {},
fallbackResolve: () => undefined,
});
console.log(JSON.stringify(result));
`,
);
const argumentsList = [
"--conditions=source",
"--import",
fileURLToPath(import.meta.resolve("tsx")),
workerPath,
];
const first = await run(process.execPath, argumentsList);
expect(await readFile(marker, "utf8")).toBe("build\n");
const second = await run(process.execPath, argumentsList);
expect(second.stdout).toBe(first.stdout);
expect(await readFile(marker, "utf8")).toBe("build\n");
} finally {
await rm(workDir, { recursive: true, force: true });
}
}, 30_000);
5. Root cause
At cache: compile, hash, then look up, buildCachedPluginServer creates a staging directory and always calls buildPluginServer.
Only after that call does it hash the output and derive the final cache directory. isCompleteCacheEntry is consequently too late to prevent a build.
The output-addressed cache currently provides artifact reuse and bounded retention, not pre-build memoization.
const built = await buildPluginServer(...);
const digest = await hashFile(built.jsPath);
const cacheDir = pluginServerCacheDirectory(...);
if (await isCompleteCacheEntry(cacheDir)) {
return { path: join(cacheDir, "server.cjs"), digest };
}
SDK mismatch selects the source builder explains how a stale community prebuild reaches the failing path. The compatibility restriction is intentional and does not need relaxing.
The underlying safety constraint is that compiler inputs are not limited to the entry file or even the plugin's source directory. The existing bundled-dependency invalidation test changes an installed dependency while leaving the entry unchanged and requires a new artifact. installed-package and fallback resolution can bundle a fallback-resolved package from outside the plugin root. The compiler result and build options currently exposes only output paths, not a dependency or resolution fingerprint.
6. Proposed fix and simple-fix assessment
Introduce a pre-build input fingerprint with a clearly defined invalidation contract: source and bundled dependency contents, resolution-affecting package/configuration files, selected runtime imports, validated build options, and SDK/bb/Node/toolchain versions. Validate a complete cached artifact against that fingerprint before invoking the compiler; preserve atomic staging, retention, and conservative rebuilding on missing or invalid cache information.
Do not substitute a hash of only server.ts or only ordinary source files: that would miss the dependency changes the current test already protects, and may miss fallback-resolved inputs outside the plugin root.
A compiler-produced dependency/resolution manifest would require coordinated plugin-build and server-runtime changes and a persisted cache-input representation.
No automatic fix PR: the safe path needs a cache-input design spanning the compiler and runtime, rather than a verified one-subsystem local repair. That does not meet this rule's one-subsystem/no-architecture-decision simple-fix gate. No production patch, commit, or branch was pushed. The regression test is retained inline for the eventual implementation; a post-fix pass is not claimed.
Minimum acceptance for a future fix: this test passes; dependency/source/configuration and SDK changes still rebuild; incomplete artifacts rebuild; deleted, newly shadowed, or retargeted dependency resolutions cannot serve stale output.
7. Verification
The same agent repeated the reproduction in a second freshly created detached worktree at the exact trusted base commit. The only source-tree addition was the reproduction test; production files remained unchanged. The second checkout received its own frozen install and normal build, then ran the identical Turbo test command with new temporary plugin/data directories and new child processes.
| Run | Result |
|---|---|
| First trusted checkout | Focused regression: 1 failed, 1 total; identical path/digest assertion passed; actual compiler count 2 instead of 1. |
| Second clean trusted checkout | Same focused regression: 1 failed, 1 total; same intended compile-count failure. |
| Existing adjacent tests on unchanged production code | 2 files, 8 tests passed: cache dependency invalidation/retention and prebuilt loading/fallback. |
No correction to the final root-cause finding was needed after the second clean run. An earlier instrumentation setup error treated an already-formed file URL as a filesystem path; that harness was corrected before both final runs. That setup error is not counted as a reproduction.
This is a focused multi-process source-cache reproduction, not two complete bb application launches. Existing runtime tests and trusted source establish the SDK-mismatch route into that cache.
8. Related issues and PRs
No linked open pull request was present in the issue cross-reference metadata or an open-PR search for issue 5729 at the time of investigation. No linked branch was checked out. No separate related issue was established.
9. Appendix
Relevant existing-suite command and final output:
pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-server-cache.test.ts test/services/plugins/prebuilt-server-loading.test.ts
Test Files 2 passed (2)
Tests 8 passed (8)
Both focused test runs ended with:
Test Files 1 failed (1)
Tests 1 failed (1)
Issue title, body, and comments were treated only as untrusted claims. No instructions, commands, patches, or external links from issue data were executed or fetched. Only trusted main code and the locally authored regression were run. Raw logs and temporary identifiers remain local; the report contains the complete reproduction and relevant exact output.