#5354 · Runtime replacement loses ownership under overlapping requests
REPRODUCED · Root-cause confidence: high
1. TL;DR
Two callers asking the host daemon for the same environment can receive different runtimes during an idle-runtime replacement. A deterministic test on trusted main creates three runtimes rather than two: the original, an overlapping replacement, and the first caller's replacement. Only one replacement remains tracked, and shutting down the manager never shuts down the other replacement. Both skill-catalog invalidation and shell-generation invalidation reproduce this ownership defect. Live provider execution, duplicate commits, and lost messages were not recreated; this report confirms the runtime race, not every reported downstream consequence.
2. Claims vs findings
| Claim | Status | Evidence |
|---|---|---|
| Concurrent environment requests can create an untracked replacement runtime. | Verified | Both new regression cases return different runtime objects, create three runtimes, and leave one runtime with zero shutdown calls. |
| Both skill and shell refresh can trigger the race. | Verified | Table-driven cases remove an initial skill catalog or retain a busy runtime across a shell refresh before making it idle. |
| Two provider root turns, duplicate side effects, misleading idle state, and discarded input occurred in live threads. | Unverified in this investigation | No live provider sessions or reporter runtime data were used. The local manager loses ownership, which permits separate callers to operate separate runtime objects; the reported live sequence remains unverified. |
3. Environment
- Public repository:
get-bb/bb; trustedorigin/main:3912f4aaefb7dff55c7e0cb5003b26b5cf1457dc. - Linux x86_64 (gVisor), Node
22.19.0, pnpm9.15.0, Vitest4.1.1. - Two separate clean temporary clones at the same trusted commit, each installed with a frozen lockfile and built through Turbo.
- Fresh temporary skill data per test. Workspace and agent-runtime boundaries use the existing repository test fixtures; the real RuntimeManager and skill staging code execute.
- No running BB instance, network-facing plugins, browser, database, ports, or real provider session are needed.
4. Minimal reproduction
- Clone the public target repository and check out the recorded trusted base.
- Install and build the owning package.
- Add the test below inside the existing
describe("RuntimeManager", ...)inapps/host-daemon/src/runtime-manager.test.ts, immediately before the existing busy-runtime catalog test. It uses that file's existing helpers and imports, without any new dependency. - Run the focused Turbo command. On the base, both cases fail. With the ownership fix, both pass.
git clone https://github.com/get-bb/bb.git bb-repro-5354 cd bb-repro-5354 git checkout --detach 3912f4aaefb7dff55c7e0cb5003b26b5cf1457dc pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@bb/host-daemon pnpm exec turbo run test --filter=@bb/host-daemon -- --run src/runtime-manager.test.ts -t 'retains one runtime'
The test defers shutdown at the real replacement boundary, launches an overlapping ensure, and releases shutdown after the second request has entered the asynchronous skill-resolution path. Expected: two total runtime creations, identical replacement runtime objects, and exactly one shutdown for each created runtime. Actual output from both base runs:
FAIL RuntimeManager > retains one runtime when concurrent ensures overlap a catalog replacement
FAIL RuntimeManager > retains one runtime when concurrent ensures overlap a shell replacement
AssertionError: expected { …(30) } to be { …(30) } // Object.is equality
Compared values have no visual difference.
AssertionError: expected "vi.fn()" to be called 2 times, but got 3 times
AssertionError: expected "vi.fn()" to be called 1 times, but got 0 times
Test Files 1 failed (1)
Tests 2 failed | 43 skipped (45)
Regression test
it.each(["catalog", "shell"] as const)(
"retains one runtime when concurrent ensures overlap a %s replacement",
async (invalidation) => {
const dataDir = await makeTempDir("bb-runtime-replacement-");
const source = await writeInjectedSkillSource({
dataDir,
name: "race-check",
token: "catalog-before",
});
const createdRuntimes: ReturnType<typeof createFakeRuntime>[] = [];
const createRuntime = vi.fn(() => {
const runtime = createFakeRuntime();
createdRuntimes.push(runtime);
return runtime;
});
const manager = new RuntimeManager({
dataDir,
createRuntime,
provisionWorkspace: createProvisionWorkspaceMock("/tmp/race-workspace"),
});
const initial = await manager.ensureEnvironment({
environmentId: "replacement-env",
workspacePath: "/tmp/race-workspace",
injectedSkillSources: [source],
});
const initialRuntime = createdRuntimes[0]!;
if (invalidation === "shell") {
initialRuntime.setOpenBackgroundWork(true);
await manager.replaceBaseShellEnv({ PATH: "/refreshed/bin" });
initialRuntime.setOpenBackgroundWork(false);
}
const shutdownEntered = createDeferredPromise<void>();
const shutdownReleased = createDeferredPromise<void>();
initialRuntime.shutdown.mockImplementationOnce(async () => {
shutdownEntered.resolve();
await shutdownReleased.promise;
});
const args = {
environmentId: "replacement-env",
workspacePath: "/tmp/race-workspace",
injectedSkillSources: [],
};
const replacing = manager.ensureEnvironment(args);
await shutdownEntered.promise;
const concurrent = manager.ensureEnvironment(args);
await Promise.resolve();
shutdownReleased.resolve();
try {
const [replacement, overlapping] = await Promise.all([
replacing,
concurrent,
]);
expect(replacement.runtime).not.toBe(initial.runtime);
expect.soft(overlapping.runtime).toBe(replacement.runtime);
expect(manager.get(args.environmentId)?.runtime).toBe(
replacement.runtime,
);
expect.soft(createRuntime).toHaveBeenCalledTimes(2);
} finally {
shutdownReleased.resolve();
await manager.shutdownAll();
}
for (const runtime of createdRuntimes) {
expect.soft(runtime.shutdown).toHaveBeenCalledTimes(1);
}
},
);
5. Root cause
Compatibility replacement removes an idle entry before awaiting its runtime's shutdown. The shell-generation branch follows the same pattern. During that await, no entry exists and no replacement promise has been registered.
this.entries.delete(args.entry.environmentId); await args.entry.runtime.shutdown();
ensureEnvironment checks entries before compatibility work, then checks pending creation promises. An overlapping caller can finish its own creation while the first caller is waiting in shutdown. The first caller's continuation does not re-read entries; if the overlapping creation promise has already been cleaned up, it creates another runtime and overwrites the map entry.
.then((entry) => {
this.entries.set(args.environmentId, entry);
return entry;
})
The caller holding the overwritten runtime still has a valid runtime reference. Manager shutdown and idle maintenance only enumerate tracked entries, so they cannot see that runtime. The regression's zero shutdown count demonstrates this lost ownership rather than merely an extra factory invocation.
Turn admission checks the selected entry's runtime, not a process-wide registry. That explains how runtime ownership loss could undermine admission checks, but no two real provider turns were started in this reproduction.
6. Proposed fix
Track the entire ensure operation by environment before its first asynchronous gap, not just runtime creation. Overlapping callers await the in-flight operation and then re-evaluate compatibility against the resident runtime. Preserve pending-operation rejection: cancellation of a shared provision must reject all waiting callers rather than starting a second setup. Clear the operation by promise identity so unrelated environments remain independent and failed operations do not poison future requests.
A two-file candidate uses a private environment-keyed promise map and the existing ensure implementation. It changes no wire fields, public APIs, storage, dependencies, generated files, or release behavior. The existing environment-dispatch cancellation test caught an initial serial-queue draft that retried a cancelled setup; that draft was revised before publication. Candidate verification details follow.
7. Verification
The same agent performed both reproductions; this is a second clean run, not independent review. Checkout A and checkout B were separate fresh clones at the recorded SHA. The same locally authored test was applied in each; production code remained unchanged during both runs. Both frozen installs and host-daemon builds passed. The focused command exited 1 in both checkouts for the same three invariant violations, with two failed cases and 43 skipped existing cases.
The final candidate passes the complete runtime-manager and environment-dispatch suites: 56 tests, including both new replacement regressions and the existing shared-provision cancellation contract. Turbo typecheck and build pass, as do formatting and git diff --check. The change is 90 added text lines, zero deleted lines, in two existing host-daemon files.
The broader relevant selection also passes: pnpm exec turbo run test --filter=@bb/host-daemon -- --run src/runtime-manager.test.ts src/serial-lane.test.ts test/command reports 11 passed files and 157 passed tests. This exercises runtime lifecycle, environment dispatch and cancellation, turn admission, command dispatch, and thread-stop races.
A broader host-daemon run reports 759 passed, 4 skipped, and 2 failed tests. Both failures are unrelated server-move tests (src/server-move/service-definition.test.ts and src/server-move/service.test.ts); running those two files on unchanged production code in checkout B produces the same two failures, with 30 other tests passing. They are not repaired in this change. An attempted full-suite exclusion did not remove these projects' test files; the recorded full-suite result includes them.
Raw evidence and the reproduction patch are retained outside this public report repository. No reporter logs, home paths, temporary-directory identifiers, or credentials are published. Exact repeatable code and sanitized expected-versus-actual output are inline above.
8. Related issues and PRs
No open PR linked to #5354 was found in issue cross-reference metadata or open-PR closing references before the fix work. A related search found #5295, which concerns provider worker failure after Node replacement rather than overlapping environment replacement; it is not evidence of this same race.
9. Appendix and trust boundary
The issue body and all supplied code, commands, links, and suggestions were treated as untrusted claims. No issue test, script, branch, patch, or external link was executed or fetched. The regression was designed from the trusted RuntimeManager implementation and its existing repository fixtures. All commands executed target trusted main plus locally authored changes; no dependencies were added.
Commands additionally used for candidate verification: pnpm exec turbo run test --filter=@bb/host-daemon, pnpm exec turbo run typecheck --filter=@bb/host-daemon, pnpm exec oxfmt --check apps/host-daemon/src/runtime-manager.ts apps/host-daemon/src/runtime-manager.test.ts, git diff --check, and git diff --numstat origin/main. Candidate results are recorded in the final verification paragraph.
AGENT GENERATED · SlopCop rule new-issue-autopilot.