← reports

#5404 · Launcher continues startup after detecting a live runtime owner

BugHighEffort: Lowhost · cli · confirmed-reproIssueOctober 12, 2026 · base b5618353309df57e67794e64ca275dccc88b2d34

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

Starting a second launcher against a data directory already served by a live launcher prints a warning, but still starts a server child. The child fails because the first server already owns the local port. Both clean runs produced a new server uncaught-exception diagnostic containing EADDRINUSE; the original instance stayed healthy. The runtime-record claim detects the other live process, but its false return is only used to print a warning. A small launcher guard now checks the existing health endpoint and exits with status 1 before any server launch when that endpoint is healthy.

2. Claims vs findings

ClaimStatusEvidence
A second launcher warns but attempts server startup.VerifiedReal packaged launchers in two fresh stores; the regression reaches the public pre-launch callback on unchanged main.
The duplicate child fails on the occupied port and writes a diagnostic.VerifiedOne new server uncaught-exception diagnostic containing EADDRINUSE in each base run.
Server initialization opens the shared store and runs recovery before binding.Verified by code orderingThe launcher passes the same data directory to its child; server startup performs the recovery sweep before creating its listener.
Recovery can interfere with another process's pending starts.Not reproducedThe guard for starts in flight is process-local, but no workload or resulting damage was tested.
Reported macOS CPU, memory, historical crash counts, and service-manager retry cadence.UnverifiedThis investigation ran on Linux, without launchd or the reporter's store. Those measurements are not needed to establish the launcher defect.

3. Environment

RunServer / daemon portsDuplicate exitServer launch attemptedNew server diagnosticsOwner healthy afterward
First trusted base run40325 / 386921true1true
Second clean trusted base run54560 / 232431true1true
Patched run30043 / 264471false0true

4. Minimal reproduction

  1. Clone only trusted main and install/build:
    git clone https://github.com/get-bb/bb.git bb-repro
    cd bb-repro
    git checkout --detach b5618353309df57e67794e64ca275dccc88b2d34
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=bb-app
  2. Save the following investigator-authored script as reproduce.mjs outside the checkout, then run it with the checkout and an empty evidence-output directory. It starts the real owner, waits for health, starts the duplicate, records outcomes, and stops only its own process groups.
    node /path/to/reproduce.mjs /path/to/bb-repro /path/to/evidence-output
    Complete reproduction script
    import { spawn } from "node:child_process";
    import { once } from "node:events";
    import { mkdtemp, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
    import { createServer } from "node:net";
    import { tmpdir } from "node:os";
    import { join, resolve } from "node:path";
    import { setTimeout as delay } from "node:timers/promises";
    
    const checkout = resolve(process.argv[2]);
    const output = resolve(process.argv[3]);
    const root = await mkdtemp(join(tmpdir(), "bb-5404-runtime-"));
    await mkdir(join(root, "home"));
    await mkdir(output, { recursive: true });
    async function freePort() {
      const listener = createServer();
      listener.listen(0, "127.0.0.1");
      await once(listener, "listening");
      const address = listener.address();
      if (address === null || typeof address === "string") throw new Error("No TCP address");
      await new Promise((resolveClose) => listener.close(resolveClose));
      return address.port;
    }
    const serverPort = await freePort();
    let daemonPort = await freePort();
    while (daemonPort === serverPort) daemonPort = await freePort();
    const dataDir = join(root, "data");
    const env = {
      PATH: process.env.PATH,
      HOME: join(root, "home"),
      XDG_CONFIG_HOME: join(root, "home", ".config"),
      NODE_ENV: "production",
      BB_DATA_DIR: dataDir,
      BB_SERVER_PORT: String(serverPort),
      BB_HOST_DAEMON_PORT: String(daemonPort),
      BB_TELEMETRY: "false",
    };
    const entry = join(checkout, "packages", "bb-app", "dist", "bb-app.js");
    const args = [entry, "start", "--no-in-app-updates", "--data-dir", dataDir,
      "--server-port", String(serverPort), "--host-daemon-port", String(daemonPort)];
    const owner = spawn(process.execPath, args, { env, detached: true, stdio: "ignore" });
    const ownerExit = once(owner, "exit");
    let duplicate;
    try {
      let healthy = false;
      for (let attempt = 0; attempt < 240; attempt += 1) {
        if (owner.exitCode !== null) throw new Error(`Owner exited ${owner.exitCode}`);
        try {
          const response = await fetch(`http://127.0.0.1:${serverPort}/health`, {
            signal: AbortSignal.timeout(500),
          });
          healthy = response.ok && (await response.json()).ok === true;
        } catch {}
        if (healthy) break;
        await delay(250);
      }
      if (!healthy) throw new Error("Owner never became healthy");
      const runtimeBefore = await readFile(join(dataDir, "bb-app-runtime.json"), "utf8");
      const beforeFiles = await readdir(join(dataDir, "logs"));
      let text = "";
      duplicate = spawn(process.execPath, args, { env, detached: true, stdio: ["ignore", "pipe", "pipe"] });
      duplicate.stdout.on("data", (chunk) => { text += chunk; });
      duplicate.stderr.on("data", (chunk) => { text += chunk; });
      const timeout = setTimeout(() => process.kill(-duplicate.pid, "SIGTERM"), 30_000);
      const [exitCode, signal] = await once(duplicate, "exit");
      clearTimeout(timeout);
      const afterFiles = await readdir(join(dataDir, "logs"));
      const addedDiagnostics = afterFiles.filter((name) =>
        name.startsWith("process-server-uncaughtException-") && !beforeFiles.includes(name));
      const diagnosticEvidence = [];
      for (const name of addedDiagnostics) {
        const diagnostic = await readFile(join(dataDir, "logs", name), "utf8");
        diagnosticEvidence.push({ name, containsAddressInUse: diagnostic.includes("EADDRINUSE") });
      }
      const runtimeAfter = await readFile(join(dataDir, "bb-app-runtime.json"), "utf8");
      const response = await fetch(`http://127.0.0.1:${serverPort}/health`);
      const result = {
        serverPort, daemonPort, exitCode, signal,
        attemptedServerStartup: text.includes("Starting server"),
        newServerDiagnostics: diagnosticEvidence,
        ownerRecordUnchanged: runtimeBefore === runtimeAfter,
        ownerStillHealthy: response.ok && (await response.json()).ok === true,
      };
      await writeFile(join(output, "duplicate-output.txt"), text.replaceAll(root, "<temporary-runtime>"));
      await writeFile(join(output, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
      console.log(JSON.stringify(result, null, 2));
    } finally {
      for (const child of [duplicate, owner]) {
        if (child && child.exitCode === null && child.signalCode === null) {
          try { process.kill(-child.pid, "SIGTERM"); } catch {}
        }
      }
      await Promise.race([ownerExit, delay(15_000)]);
      if (owner.exitCode === null && owner.signalCode === null) {
        try { process.kill(-owner.pid, "SIGKILL"); } catch {}
      }
    }
    
  3. Expected: duplicate exit status 1, no server launch attempt, no new server diagnostic, owner still healthy and record unchanged. Actual on unchanged main:
    bb
    
      !  Another bb already runs on this data directory
         record: <temporary-runtime>/data/bb-app-runtime.json
         Run `bb-app stop` to stop it.
    
      ○  Starting server
      ✗  Server failed to start
         Server failed to become healthy: Process exited before becoming healthy: another server is already answering at http://127.0.0.1:40325/health
         Check logs: <temporary-runtime>/data/logs/
    
      ●  Shutting down
    {
      "serverPort": 40325,
      "daemonPort": 38692,
      "exitCode": 1,
      "attemptedServerStartup": true,
      "newServerDiagnostics": 1,
      "addressInUseDiagnostics": 1,
      "ownerRecordUnchanged": true,
      "ownerStillHealthy": true
    }

Focused regression

Save the complete test below at packages/bb-app/test/startup-runtime-record.test.ts. It exercises the real launcher with an actual temporary runtime record and HTTP health listener. Only package-artifact existence is substituted so the unit test does not require generated bundles. The existing public pre-server-start callback aborts before any child can spawn. The healthy live-owner case requires that this callback never run; unhealthy-owner and no-owner controls require startup to remain reachable. No database is mocked and no production test seam was added.

pnpm exec turbo run test --filter=bb-app -- test/startup-runtime-record.test.ts
Complete regression test
import { once } from "node:events";
import { mkdtemp, rm } from "node:fs/promises";
import type { PathLike } from "node:fs";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { basename, join } from "node:path";
import {
  readBbAppRuntimeFile,
  writeBbAppRuntimeFile,
} from "@bb/config/app-runtime-file";
import { expect, it, vi } from "vitest";
import { runBbApp } from "../src/launcher.js";

vi.mock("node:fs", async (importOriginal) => {
  const actual = await importOriginal<typeof import("node:fs")>();
  const artifacts = new Set([
    "daemon-bundle.mjs",
    "bb",
    "bb-provider-bridge-worker.mjs",
    "bb-parcel-watcher-child.mjs",
    "bb-plugin-host-worker.mjs",
    "index.js",
    "index.html",
  ]);
  return {
    ...actual,
    existsSync: (filePath: PathLike) =>
      (typeof filePath === "string" && artifacts.has(basename(filePath))) ||
      actual.existsSync(filePath),
    readdirSync: (filePath: PathLike) =>
      typeof filePath === "string" && basename(filePath) === "bb-chunks"
        ? ["chunk.js"]
        : actual.readdirSync(filePath),
  };
});

it.each([
  { liveOwner: true, healthy: true, shouldStart: false },
  { liveOwner: true, healthy: false, shouldStart: true },
  { liveOwner: false, healthy: true, shouldStart: true },
])(
  "startup with live owner=$liveOwner and healthy=$healthy attempts server=$shouldStart",
  async ({ liveOwner, healthy, shouldStart }) => {
    const dataDir = await mkdtemp(join(tmpdir(), "bb-startup-owner-"));
    const server = createServer((_request, response) => {
      response.writeHead(200, { "content-type": "application/json" });
      response.end(JSON.stringify({ ok: healthy }));
    });
    const previousExitCode = process.exitCode;
    const output = vi.spyOn(process.stdout, "write").mockReturnValue(true);
    const beforeServerStart = vi.fn(() => {
      throw new Error("Startup reached the server launch boundary");
    });
    try {
      server.listen(0, "127.0.0.1");
      await once(server, "listening");
      const address = server.address();
      if (address === null || typeof address === "string") {
        throw new Error("Expected a TCP listener");
      }
      if (liveOwner) {
        await writeBbAppRuntimeFile({
          dataDir,
          entryPath: process.execPath,
          pid: process.ppid,
          serverUrl: `http://127.0.0.1:${address.port}`,
          startedAt: new Date().toISOString(),
          surface: "web",
          version: "0.0.0-test",
        });
      }
      const recordBefore = await readBbAppRuntimeFile(dataDir);
      await runBbApp(
        [
          "start",
          "--no-in-app-updates",
          "--data-dir",
          dataDir,
          "--server-port",
          String(address.port),
          "--host-daemon-port",
          String(address.port),
        ],
        { beforeServerStart, worktreePolicy: null },
      );
      expect(beforeServerStart).toHaveBeenCalledTimes(shouldStart ? 1 : 0);
      expect(process.exitCode).toBe(1);
      expect(await readBbAppRuntimeFile(dataDir)).toEqual(recordBefore);
    } finally {
      process.exitCode = previousExitCode;
      output.mockRestore();
      server.closeAllConnections();
      await new Promise<void>((resolveClose) =>
        server.close(() => resolveClose()),
      );
      await rm(dataDir, { recursive: true, force: true });
    }
  },
);
Unchanged production code, both clean checkouts:
FAIL: startup with live owner=true and healthy=true attempts server=false
AssertionError: expected "vi.fn()" to be called +0 times, but got 1 times
Tests: 1 failed | 2 passed (3)

After the launcher guard:
Test Files: 1 passed (1)
Tests: 3 passed (3)

5. Root cause

claimBbAppRuntimeFile returns false when an existing record names another running process. runBbApp's runtime-record handling prints the warning but continues into full-stack supervision. That supervision reaches startFullStackServerProcess and spawns a real server before the health check can reject the foreign listener.

The child receives the same data directory, opens the store at initDb, and reaches startup recovery and listener creation in that order. Listener creation is asynchronous, so the listening log can occur before the bind error is known. The verified problem is missing launcher short-circuiting, not an in-process supervisor restart.

runStartupRecoverySweep re-drives environment and thread work. The in-flight thread guard does not prove inter-process coordination. The report does not claim observed corruption or duplicate thread starts.

6. Proposed fix and proof

When the runtime claim is rejected, use the launcher's existing validated health check against its configured local listener. If healthy, log the duplicate-instance error, set exit status 1 and return before constructing managed processes. Preserve startup when the record is unclaimed or the existing health check fails. This retains restart-on-failure takeover behavior while avoiding the doomed child and its shared-store initialization.

The implemented change stays within packages/bb-app: launcher, README, and one regression test. It changes 112 text lines across three files (13 production/documentation additions and 99 test additions), with no dependency, generated file, stored-data or public protocol change.

bb

  !  Another bb already runs on this data directory
     record: <temporary-runtime>/data/bb-app-runtime.json
     Run `bb-app stop` to stop it.

  ✗  bb already serves http://127.0.0.1:30043 from this data directory
{
  "serverPort": 30043,
  "daemonPort": 26447,
  "exitCode": 1,
  "attemptedServerStartup": false,
  "newServerDiagnostics": 0,
  "addressInUseDiagnostics": 0,
  "ownerRecordUnchanged": true,
  "ownerStillHealthy": true
}

Full relevant verification: pnpm exec turbo run test typecheck --filter=bb-app passed; 22 test files and 206 tests passed. The packaged rebuild passed, and the same real-process reproduction after the fix reported no startup attempt and zero new server diagnostics. git diff --check passed. This guard does not solve concurrent runtime-record claim races or impose a new policy on unhealthy live owners.

7. Verification

The same investigator repeated the reproduction in a second clean worktree at the exact trusted base commit, using a new store, HOME, and ports (54560/23243). Frozen install and Turbo build succeeded. The live-process reproduction again yielded exit 1, an attempted server launch, one new EADDRINUSE diagnostic, unchanged owner record and a healthy incumbent. The authored regression was then copied into that second worktree and again failed only the healthy live-owner case. This is a second clean verification by the same agent, not an independent review. No report correction was required.

8. Related issues

Startup retry handling in #3340 concerns a different failure boundary. This reproduction requires a foreign healthy listener and occurs before full-stack readiness; an internal supervisor retry budget cannot prevent an external manager from launching another process.

9. Appendix and scope

No open pull request referencing #5404 was found in repository metadata when the fix check began. Linked branches and issue-supplied scripts were not fetched or executed. Issue content was treated as untrusted claims; its commands and instructions were not followed. All executable code came from trusted origin/main or this investigator's own changes.

Report evidence is included inline. Raw temporary logs, diagnostics, and test files remain local and are not committed to the public reports repository. macOS, launchd cadence, workload recovery effects, and performance percentages are not verified. Browser and mobile checks are not relevant to this headless launcher change.

Second base run and patched run results
{
  "second": {
    "serverPort": 54560,
    "daemonPort": 23243,
    "exitCode": 1,
    "attemptedServerStartup": true,
    "newServerDiagnostics": 1,
    "addressInUseDiagnostics": 1,
    "ownerRecordUnchanged": true,
    "ownerStillHealthy": true
  },
  "patched": {
    "serverPort": 30043,
    "daemonPort": 26447,
    "exitCode": 1,
    "attemptedServerStartup": false,
    "newServerDiagnostics": 0,
    "addressInUseDiagnostics": 0,
    "ownerRecordUnchanged": true,
    "ownerStillHealthy": true
  }
}