Repository navigation
Description
Summary
After a skill catalog change (or a base shell env change), the host daemon replaces an idle environment runtime. While the old runtime shuts down, a second command for the same environment creates its own runtime. When the first call resumes, it creates one more runtime and entries.set overwrites the second one. The overwritten runtime keeps running its turn as an orphan.
The next message for that thread reaches the new runtime. That runtime does not host the thread, so it resumes the same provider session and starts a second root turn in parallel. We saw two root turns run at once in one thread for 4–8 minutes. The orphaned turn never saw later messages and acted on stale context: it spawned a duplicate child thread and made a duplicate commit. The thread showed idle while the second turn was still running, and a message sent in that window was rejected with competing_turn and lost.
Versions and environment
- bb 0.44.0 via
npx bb-app; server and host daemon on the same Linux host, daemon as a systemd user service; one more machine (a container) is enrolled. - Ubuntu 26.04.1 LTS, kernel 7.0.0, Node 22.22.1.
- Provider: Claude Code (2.1.285 at filing time). The race is in
RuntimeManager, so it should not depend on the provider. - The code is unchanged in 0.46.0 (bundle compared) and on
mainat 3912f4a. - Setup: several agent threads message one coordinator thread with
bb thread tell(default steer and--mode auto); skills and plugins are edited during the day.
Steps to reproduce
The live repro depends on timing: we saw it 3 times in one day, on two threads. I could not reproduce it on demand, and I could not run the test below: installing the monorepo is not allowed on this host. Unverified. The closest faithful repro is a unit test at the exact code path, written for apps/host-daemon/src/runtime-manager.test.ts at 3912f4a with that file's helpers:
it("does not orphan a runtime created while a stale-catalog runtime shuts down", async () => {
const dataDir = await makeTempDir("bb-runtime-manager-swap-race-");
const source = await writeInjectedSkillSource({ dataDir, name: "release-notes", token: "first-token" });
const runtimes = [createFakeRuntime(), createFakeRuntime(), createFakeRuntime()];
const [firstRuntime] = runtimes;
const createRuntime = vi.fn(() => runtimes.shift()!);
const manager = new RuntimeManager({ dataDir, provisionWorkspace: createProvisionWorkspaceMock("/tmp/env-1"), createRuntime });
const args = { environmentId: "env-skills", injectedSkillSources: [source], workspacePath: "/tmp/env-1" };
await manager.ensureEnvironment(args);
let releaseShutdown!: () => void;
firstRuntime.shutdown.mockImplementationOnce(() => new Promise<void>((resolve) => { releaseShutdown = resolve; }));
await fs.writeFile(source.skillFilePath, "---\nname: release-notes\ndescription: Use release-notes when runtime manager tests run.\n---\n\nsecond-token\n", "utf8");
const swapping = manager.ensureEnvironment(args); // deletes the entry, awaits shutdown()
await vi.waitFor(() => expect(firstRuntime.shutdown).toHaveBeenCalledTimes(1));
const concurrent = await manager.ensureEnvironment(args); // sees no entry and no pending creation
releaseShutdown();
const swapped = await swapping;
expect(swapped).toBe(concurrent); // today: a third runtime
expect(createRuntime).toHaveBeenCalledTimes(2); // today: 3
expect(manager.get("env-skills")).toBe(concurrent);
});Expected vs actual
**Expected:** one runtime per environment. A call that arrives during the swap waits for it or reuses the runtime created meanwhile. A thread never has two root turns at once.
**Actual** — one thread, `bb thread log --json`, times UTC+3, turn and request ids shortened:
08:33:55.434 turn/completed T0 completed (thread idle)
08:34:03.217 client/turn/requested R1 tell from agent thread A, target new-turn
08:34:03.738 thread/identity provider session S resumed
08:34:12.968 turn/started T1 (session S)
08:34:13.020 client/turn/requested R2 tell from agent thread B, target {auto, expectedTurnId: T1}
08:34:15.161 thread/identity session S resumed again
08:34:20.456 turn/started T2 (session S) <- second root turn while T1 runs
08:38:28.149 client/turn/requested R3 steer, expectedTurnId T2 -> accepted into T2
08:38:31.663 turn/completed T1 completed -> thread shown idle, T2 still running
08:38:37.838 client/turn/requested R4 [bb system] child-thread completion notice, target new-turn
08:38:37.941 client/turn/rejected R4 competing_turn -> never delivered later
08:42:58.583 turn/completed T2 completed
R2 should have been steered into T1. Instead the session was resumed again and T2 started.
Evidence
Code on main (3912f4a):
ensureCompatibleEntrydeletes the entry and awaitsshutdown()without registering anything inpendingEntries(shell env path):— same inbb/apps/host-daemon/src/runtime-manager.ts
Lines 690 to 703 in 3912f4a
private async ensureCompatibleEntry( args: EnsureCompatibleEntryArgs, ): Promise<RuntimeEntry | null> { if ( args.entry.shellEnvGeneration !== this.shellEnvGeneration && !this.entryHasActiveRuntimeWork(args.entry) && !this.hasInFlightThreadCommand(args.entry, args.targetThreadId) ) { this.entries.delete(args.entry.environmentId); await args.entry.runtime.shutdown(); await this.cleanupUnusedInjectedSkillStagingDirs( args.skillConfig ? [args.skillConfig.catalogHash] : [], ); return null; replaceEntryForSkillCatalog(catalog path):bb/apps/host-daemon/src/runtime-manager.ts
Lines 669 to 687 in 3912f4a
private async replaceEntryForSkillCatalog( args: ReplaceEntryForSkillCatalogArgs, ): Promise<void> { if ( this.entryHasActiveRuntimeWork(args.entry) || this.hasInFlightThreadCommand(args.entry, args.targetThreadId) ) { throw new SkillCatalogConflictError({ environmentId: args.entry.environmentId, activeCatalogHash: args.entry.skillCatalogHash, requestedCatalogHash: args.skillConfig.catalogHash, }); } this.entries.delete(args.entry.environmentId); await args.entry.runtime.shutdown(); await this.cleanupUnusedInjectedSkillStagingDirs([ args.skillConfig.catalogHash, ]); ensureEnvironmentchecksentriesandpendingEntriesonly before that await, then sets the entry without checking it again:(the set is at L917).bb/apps/host-daemon/src/runtime-manager.ts
Lines 874 to 921 in 3912f4a
async ensureEnvironment(args: EnsureEnvironmentArgs): Promise<RuntimeEntry> { const skillConfig = await this.resolveRuntimeSkillConfig(args); const existing = this.entries.get(args.environmentId); if (existing) { const compatible = await this.ensureCompatibleEntry({ entry: existing, skillConfig, ...(args.targetThreadId !== undefined ? { targetThreadId: args.targetThreadId } : {}), }); if (compatible) { return compatible; } } const pending = this.pendingEntries.get(args.environmentId); if (pending) { const entry = await pending; const compatible = await this.ensureCompatibleEntry({ entry, skillConfig, ...(args.targetThreadId !== undefined ? { targetThreadId: args.targetThreadId } : {}), }); if (compatible) { return compatible; } } const pendingProvision = this.createPendingEnvironmentProvision( args.environmentId, ); const creation = Promise.resolve() .then(() => this.createEntry({ ...args, provisionSignal: pendingProvision.abortController.signal, skillConfig, }), ) .then((entry) => { this.entries.set(args.environmentId, entry); return entry; }) .finally(() => { this.pendingEntries.delete(args.environmentId); - The orphaned runtime is not in
entriesany more. So thecompeting_turncheck sees only the new runtime's turns:. Idle reaping misses it too.COMPETING_TURN_ERROR_CODE, - A root
turn/completedmoves the thread toidleeven while another root turn of the same thread runs:bb/apps/server/src/internal/turn-completed-events.ts
Lines 33 to 64 in 3912f4a
export function applyTurnCompletedEvent( deps: Pick<AppDeps, "db" | "hub" | "logger" | "providerRegistry">, payload: Extract<ThreadEvent, { type: "turn/completed" }>, ): ApplyTurnCompletedEventResult { const thread = getThread(deps.db, payload.threadId); if (!thread) { return { isRootTurnCompletion: false, nextStatus: null, thread: null }; } const turnId = requireThreadEventScopeTurnId({ type: payload.type, scope: payload.scope, }); const isRootTurnCompletion = hasRootStoredTurnStarted(deps.db, { threadId: payload.threadId, turnId, }); if (!isRootTurnCompletion) { return { isRootTurnCompletion, nextStatus: null, thread }; } const outcome = applyLoggedThreadLifecycleEvent(deps, { event: lifecycleEventForTurnCompletion(payload.status), threadId: payload.threadId, }); const nextStatus = outcome.applied ? outcome.thread.status : null; if (nextStatus) { resetActiveThreadEventPruningState(payload.threadId); } if (nextStatus === "idle") {
Occurrences: 3 times on 2026-10-10, on two coordinator threads (overlaps at 08:34–08:38, 09:32–09:33, 20:06). Found by scanning bb thread log --json --all for a root turn/started that came before the previous root turn's turn/completed. The second overlap also lost a message (competing_turn). The third began from an explicit steer.
Not established: which call started the swap each time. The daemon logs neither runtime creation nor replacement.
What you ruled out
- Not a duplicate send: R1 and R2 are different requests from different sender threads.
- Not a provider double start: each turn follows its own
thread/identityresume of the same provider session, which fits two runtimes hosting the thread. - Still in 0.46.0 (daemon bundle compared) and on
mainat 3912f4a (source above). - No existing issue found: searched "competing_turn", "concurrent turn", "two turns", "runtime race".
Suggested fix: serialize ensureEnvironment per environmentId with a promise chain. Or register the replacement in pendingEntries before awaiting shutdown(), and check entries again before the set. Two related points may deserve their own issues: a root turn/completed should not set idle while another root turn of the thread runs, and input rejected with competing_turn is dropped instead of being queued.
Investigation: a local bb thread on our host, not public; the findings are summarized above.
AGENT GENERATED
Suggested priority and effort (optional)
Medium-High: rare and timing-dependent, but when it hits, an agent acts twice (duplicate threads, commits, automations) and a message is lost silently; no user workaround.
Checks
- I reproduced this on the latest release or on
main, or I say above that I could not. - I searched open and closed issues for the same problem.
- If an agent wrote this, the body ends with
> AGENT GENERATEDand links the thread or report.
Activity
bb-slop-cop commentedon Oct 11, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilothost,threads. Applied missing values and verified the final Type.confirmed-repro.Serialize complete host runtime ensure operations (get-bb#5355)