Skip to content

Stop concurrent session starts from retiring each other's new bridge - #7117

Merged
ymichael merged 1 commit into
get-bb:mainfrom
salemsayed:fix/retire-only-superseded-bridges
Nov 5, 2026
Merged

ymichael merged 1 commit into
get-bb:mainfrom
salemsayed:fix/retire-only-superseded-bridges

Conversation

@salemsayed

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

When two threads of one provider whose injected skill catalogs differ start or resume their sessions at the same time in one environment runtime, each one's ensureProvider retires the other's freshly spawned bridge, and both commands fail. Skill roots are part of the process key (packages/agent-runtime/src/runtime.ts:365-380), so the two threads get two bridge processes. ensureProvider ends with retireStaleBridgeProcesses (packages/agent-runtime/src/runtime-provider-process.ts:254-273), which shuts down every other process of the same provider with no registered thread. A thread is registered only after ensureProvider returns (packages/agent-runtime/src/runtime.ts:1549-1574), and that return waits for the sweep's own shutdowns, so each sweep sees the other's new bridge with zero threads. The victim either dies from SIGTERM while still initializing (exited unexpectedly (signal SIGTERM)) or exits gracefully once initialized (exited unexpectedly (code 0), or has exited (code 0) when the lookup lands between exit and close); the other command then reports is not running.

In practice this hits Claude Code threads with Composer Predictions installed: its hidden helper gets skills: [], every other thread gets its skill, and the helper starts about a second after a watched thread goes idle. A message sent to that thread, or to another idle thread in the same environment, about 0.5 to 4 s after the idle is rejected. On one server this lost 7 sends on long-lived threads in four days, and 6 of 10 sends in a controlled repro.

The sweep exists to retire bridges superseded by a plugin update (a new artifact hash). Bridges for another skill catalog of the same bridge launch are not superseded; they are released when their last thread ends. #6479 makes the same change to this filter as part of its larger session-config rework ("main killed a sibling catalog's freshly spawned process before its thread arrived"). This PR takes only that filter, so the crash can be fixed while #6479 is open; it applies to main on its own and the hunk matches #6479's, so either can rebase over the other.

What changed

  • packages/agent-runtime/src/runtime-provider-process.ts: each process records its bridge launch key (bridgeLaunchProcessKey: artifact digest, capabilities, bridge options) when it is spawned. retireStaleBridgeProcesses retires only a threadless process of the same provider whose bridge launch key differs from the one being ensured. Processes of the same launch with another skill catalog are left to the existing release-after-last-thread path.
  • packages/agent-runtime/src/runtime.process-lifecycle.test.ts:
    • "retires a threadless bridge process superseded by a new artifact hash" now ensures the fresh key with a launch whose digest differs (SUPERSEDING_BRIDGE_LAUNCH, as in Reconcile provider session tools and skills in one place, declared per bridge #6479). Before, it only changed the process key string while reusing the same launch, which no longer counts as superseded.
    • New "starts threads of two skill catalogs at once without retiring either bridge": two concurrent startThread calls on one runtime with different skillRoots; both must be hosted afterwards.
  • No daemon wire change, no HOST_DAEMON_PROTOCOL_VERSION change.

How you verified

  • New test without the production change (main's runtime-provider-process.ts): fails with ProviderProcessExitedError: Provider "scripted" exited unexpectedly (signal SIGTERM); the other 35 tests in the file pass. With the change: 36/36.

  • pnpm exec turbo run test --filter=@bb/agent-runtime --force: 23 files, 307 tests passed.

  • pnpm exec turbo run typecheck lint --filter=@bb/agent-runtime --filter=@bb/host-daemon --force: 7/7 tasks passed.

  • oxfmt --check on the test file reports the existing oom_score_adj test from Let the OOM killer take agent work before bb #7039, unchanged on main; the new code is formatter output and that hunk is left alone.

  • Standalone reproduction at the same code path, ten fresh runtimes per run, on main at fa30b0a7d: 0/10 without the change (every run lost one or both threads with exited unexpectedly (code 0), (signal SIGTERM) or is not running), 10/10 with it.

    pnpm exec turbo run generate:test-bridges --filter=@bb/agent-runtime
    cd packages/agent-runtime
    ../../node_modules/.bin/tsx /tmp/sibling-start-race.mts "$PWD/../.." 10
    /tmp/sibling-start-race.mts
    import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
    import { tmpdir } from "node:os";
    import { join } from "node:path";
    
    const root = process.argv[2]!;
    const trials = Number(process.argv[3] ?? 10);
    const { createAgentRuntime } = await import(`${root}/packages/agent-runtime/src/runtime.ts`);
    const harness = await import(`${root}/packages/agent-runtime/src/test/runtime-test-harness.ts`);
    
    function stage(dir: string, name: string) {
      const path = join(dir, name);
      mkdirSync(join(path, name), { recursive: true });
      writeFileSync(join(path, name, "SKILL.md"), `---\nname: ${name}\n---\n`);
      return [{ id: `skills:${name}`, path, skills: [{ name, description: name }] }];
    }
    
    let passed = 0;
    for (let trial = 1; trial <= trials; trial++) {
      const dir = mkdtempSync(join(tmpdir(), "sibling-start-race-"));
      const runtime = createAgentRuntime({
        workspacePath: dir,
        onEvent: () => {},
        onToolCall: async () => ({ contentItems: [], success: true }),
      });
      const bridgeLaunch = harness.createScriptedEchoLaunch();
      const start = (threadId: string, skillRoots: unknown) =>
        runtime.startThread({
          bridgeLaunch,
          skillRoots,
          environmentId: "env-1",
          threadId,
          projectId: "p1",
          providerId: "scripted",
          options: harness.fullRuntimeOptions,
        });
      const results = await Promise.allSettled([
        start("coordinator", stage(dir, "with-predictions-skill")),
        start("prediction-helper", stage(dir, "no-skills")),
      ]);
      const errors = results.flatMap((r) => (r.status === "rejected" ? [String((r.reason as Error).message ?? r.reason).split("\n")[0]] : []));
      const hosted = ["coordinator", "prediction-helper"].filter((t) => runtime.hasThread(t));
      const ok = errors.length === 0 && hosted.length === 2;
      if (ok) passed++;
      console.log(`trial ${trial}: ${ok ? "PASS" : "FAIL"} hosted=${hosted.join(",") || "none"}${errors.length ? ` errors=${JSON.stringify(errors)}` : ""}`);
      await runtime.shutdown();
      rmSync(dir, { recursive: true, force: true });
    }
    console.log(`${passed}/${trials} passed`);
    process.exit(0);
  • Live, on a bb-app 0.48.2 nightly (upstream 298e5d0): the daemon bundle built from 298e5d0 without the change is byte-identical to the shipped host-daemon/dist/daemon-bundle.mjs; with the change it differs only by this filter. The live reproduction (send to a watched Claude Code thread the moment it goes idle, Composer Predictions installed) failed 6 of 10 sends before. The patched daemon has not been deployed there yet.

Fixes #7116

AGENT GENERATED

…nch siblings

Two threads of one provider whose skill catalogs differ get different process
keys in the same environment runtime. When both start or resume at once, each
ensureProvider's stale sweep retired the other's freshly spawned bridge before
its thread was registered, and both commands failed with "exited unexpectedly
(code 0 | signal SIGTERM)", "has exited (code 0)" or "is not running".

Only a process whose bridge launch key (artifact digest, capabilities, bridge
options) differs is superseded now, the filter get-bb#6479 also carries. Processes of
the same launch are still released after their last thread ends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 7dbb66b into get-bb:main Nov 5, 2026
30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Send to an idle thread rejected with "exited unexpectedly (code 0)" when another thread with a different skill catalog starts in the same environment

2 participants