Skip to content

Host daemon: a second ensureEnvironment during a runtime swap orphans a runtime, so one thread runs two root turns at once #5354

Closed

Description

@nimph977

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 main at 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):

  • ensureCompatibleEntry deletes the entry and awaits shutdown() without registering anything in pendingEntries (shell env path):
    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;
    — same in replaceEntryForSkillCatalog (catalog path):
    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,
    ]);
  • ensureEnvironment checks entries and pendingEntries only before that await, then sets the entry without checking it again:
    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 set is at L917).
  • The orphaned runtime is not in entries any more. So the competing_turn check sees only the new runtime's turns:
    COMPETING_TURN_ERROR_CODE,
    . Idle reaping misses it too.
  • A root turn/completed moves the thread to idle even while another root turn of the same thread runs:
    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/identity resume of the same provider session, which fits two runtimes hosting the thread.
  • Still in 0.46.0 (daemon bundle compared) and on main at 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 GENERATED and links the thread or report.

Activity

  1. added theissue type on Oct 11, 2026
  2. added
    host
    threads
    confirmed-repro
    on Oct 11, 2026
  3. bb-slop-cop commented on Oct 11, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Priority High · Effort Medium; areas host, threads. Applied missing values and verified the final Type.
    • Report: Reproduction and root cause — REPRODUCED, high root-cause confidence; reproduced on trusted main in two clean checkouts. Reproduction label: confirmed-repro.
    • Root cause: Replacement deletes the resident entry before awaited shutdown without tracking the complete ensure operation. Overlapping callers create three runtimes instead of two, overwrite a live replacement, and leave it outside manager shutdown coverage.
    • Fix: Ready PR #5355 serializes complete ensures while preserving shared provisioning cancellation: 90 changed text lines, two files. Not merged.
    • Verification: Both catalog and shell replacement regressions fail before and pass after; 157 relevant tests, typecheck, build, formatting, and diff checks pass. Two unrelated server-move failures also reproduce on unchanged main. Live provider double turns and duplicate side effects were not recreated.

    AGENT GENERATED

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-reprohostthreads

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions