#7360 · Concurrent server startup removes another live server's pending fork
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
A second real server process can start against a directory already used by a healthy server. On a different port, both processes answer health checks after the newcomer soft-deletes a pending fork. On the same port, the newcomer still soft-deletes the fork before reporting a listener conflict. These observations were repeated by the same investigator from a second clean checkout, using fresh data directories and new temporary ports.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Different ports permit concurrent ownership of the same database. | Verified live | Both processes healthy; pendingForkRetained=false in both runs. |
| Recovery can destroy a live owner's incomplete fork. | Verified for a seeded in-progress marker | The first server remains healthy while the second sets deletedAt and logs one discarded fork. |
| A same-port failure happens too late to prevent recovery. | Verified live | EADDRINUSE and pendingForkRetained=false in both runs. |
| Database initialization and import boot precede the listener. | Verified in trusted source | runServer calls initDb and applyServerImportAtBoot before recovery and listening. No pending import was exercised. |
| Another process's queued-message claims can be released. | Source-supported, not separately reproduced | The recovery step releases old claims using a process-local protection set. No live dispatch was used. |
3. Environment
- Public repository get-bb/bb; trusted origin/main at
7c1353d80729983b86ea1555d18b42407f320406, re-fetched after verification with no change. - Linux 4.19.0-gvisor x86_64; Node v22.19.0; pnpm 9.15.0.
- Two separate temporary source checkouts, named base and verify. The latter was clean before the authored test was copied in.
- Each test case creates its own OS temporary data directory and isolated HOME, binds only to IPv4 loopback, disables telemetry, redirects marketplace requests to a closed loopback port, and enables plugin safe mode. No production data, credentials, providers, or real turns are used.
- Ports are allocated dynamically and recorded in each log. All owned child processes are killed and the case's temporary database is removed in finally.
4. Minimal reproduction
- Prepare the recorded trusted checkout and server build, then save the complete authored reproduction shown below at the specified path.
git clone --branch main https://github.com/get-bb/bb.git bb-7360 cd bb-7360 git checkout 7c1353d80729983b86ea1555d18b42407f320406 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk pnpm exec turbo run build --filter=@get-bb/plugin-sdk pnpm exec turbo run build --filter=@bb/server # Save the complete inline reproduction below as apps/server/repro-7360.mjs. node --conditions=source --import tsx apps/server/repro-7360.mjs
- The script migrates a new on-disk SQLite database, starts the first server and waits for /health, then inserts the same in-progress history-copy state used by the existing fork-history recovery test. It launches a second server on that data directory and waits for either a second healthy listener or an address conflict.
- It records whether the first server remains healthy and whether the fork's deletedAt is still null. It repeats with a new data directory using the same-port case.
Expected: the competing process refuses startup before database/recovery work; the first process stays healthy and pendingForkRetained is true. Actual: pendingForkRetained is false in both cases; the safety assertion exits with status 1.
{"mode":"different-port","firstPort":50821,"secondPort":61566,"firstAlive":true,"firstHealthy":true,"secondHealthy":true,"secondExitCode":null,"secondPortConflict":false,"pendingForkRetained":false,"recoveryDeletedFork":true}
{"mode":"same-port","firstPort":58926,"secondPort":58926,"firstAlive":true,"firstHealthy":true,"secondHealthy":false,"secondExitCode":null,"secondPortConflict":true,"pendingForkRetained":false,"recoveryDeletedFork":true}
node:internal/modules/run_main:123
triggerUncaughtException(
^
AssertionError [ERR_ASSERTION]: A competing server must not delete a live owner's pending fork
at file://<first-checkout>/apps/server/repro-7360.mjs:150:1 {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '==',
diff: 'simple'
}
Node.js v22.19.0
This is a nonvisual backend defect; no screenshot is needed. Evidence is embedded inline under this public report repository's artifact policy.
Complete repeatable reproduction source
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdtemp, mkdir, readFile, readdir, rm } from "node:fs/promises";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { setTimeout as sleep } from "node:timers/promises";
import {
createConnection,
createThread,
ensurePersonalProject,
getThread,
migrate,
noopNotifier,
setPluginSafeMode,
} from "@bb/db";
const serverDir = dirname(fileURLToPath(import.meta.url));
async function freePort() {
const listener = createServer();
await new Promise((resolve) => listener.listen(0, "127.0.0.1", resolve));
const address = listener.address();
assert(address !== null && typeof address === "object");
await new Promise((resolve) => listener.close(resolve));
return address.port;
}
async function healthy(port) {
try {
const response = await fetch(`http://127.0.0.1:${port}/health`, {
signal: AbortSignal.timeout(500),
});
return response.ok;
} catch {
return false;
}
}
async function until(predicate) {
const deadline = Date.now() + 30_000;
while (Date.now() < deadline) {
if (await predicate()) return;
await sleep(50);
}
throw new Error("Timed out waiting for a server outcome");
}
async function runCase(mode) {
const directory = await mkdtemp(join(tmpdir(), "bb-7360-data-"));
const home = join(directory, "home");
await mkdir(home);
const db = createConnection(join(directory, "bb.db"));
migrate(db);
setPluginSafeMode(db, true);
const project = ensurePersonalProject(db);
const firstPort = await freePort();
const secondPort = mode === "same-port" ? firstPort : await freePort();
const hostPort = await freePort();
const children = [];
const outputs = [];
const launch = (port) => {
const child = spawn(process.execPath, ["dist/index.js"], {
cwd: serverDir,
env: {
PATH: process.env.PATH,
HOME: home,
NODE_ENV: "test",
BB_DATA_DIR: directory,
BB_SERVER_PORT: String(port),
BB_HOST_DAEMON_PORT: String(hostPort),
BB_SERVER_BIND_HOST: "127.0.0.1",
BB_TELEMETRY: "false",
BB_MARKETPLACE_URL: "http://127.0.0.1:9/marketplace.json",
},
stdio: ["ignore", "pipe", "pipe"],
});
children.push(child);
const output = [];
outputs.push(output);
child.stdout.on("data", (chunk) => output.push(chunk.toString()));
child.stderr.on("data", (chunk) => output.push(chunk.toString()));
return child;
};
try {
const first = launch(firstPort);
await until(async () => {
assert.equal(first.exitCode, null, outputs[0].join(""));
return healthy(firstPort);
});
const pending = createThread(db, noopNotifier, {
projectId: project.id,
providerId: "codex",
status: "pending",
startupContext: JSON.stringify({
kind: "pending",
environmentIntent: { type: "reuse", environmentId: "env_repro" },
fork: null,
historyCopy: "copying",
startedOnBehalfOf: null,
titleProvided: false,
}),
});
assert.notEqual(getThread(db, pending.id), null);
const second = launch(secondPort);
await until(async () => {
if (second.exitCode !== null) return true;
if (mode === "different-port") return healthy(secondPort);
return outputs[1].join("").includes("EADDRINUSE");
});
await sleep(100);
const logs = [];
for (const name of await readdir(join(directory, "logs"))) {
if (/^server\.\d+\.log$/.test(name)) {
logs.push(await readFile(join(directory, "logs", name), "utf8"));
}
}
const recovery = logs.join("\n").split("\n").find((line) =>
line.includes("Deleted forks whose history copy"),
);
const result = {
mode,
firstPort,
secondPort,
firstAlive: first.exitCode === null,
firstHealthy: await healthy(firstPort),
secondHealthy: mode === "different-port" && await healthy(secondPort),
secondExitCode: second.exitCode,
secondPortConflict: outputs[1].join("").includes("EADDRINUSE"),
pendingForkRetained: getThread(db, pending.id)?.deletedAt === null,
recoveryDeletedFork: recovery !== undefined,
};
console.log(JSON.stringify(result));
return result;
} finally {
for (const child of children) child.kill("SIGKILL");
await Promise.all(children.map((child) => child.exitCode !== null || child.signalCode !== null
? Promise.resolve()
: new Promise((resolve) => child.once("exit", resolve))));
db.$client.close();
await rm(directory, { recursive: true, force: true });
}
}
const results = [];
for (const mode of ["different-port", "same-port"]) {
results.push(await runCase(mode));
}
assert(results.every((result) => result.pendingForkRetained),
"A competing server must not delete a live owner's pending fork");
5. Root cause
Server startup does not acquire data-directory ownership before migrations and recovery; recovery treats every copying fork as abandoned, even while another server is alive.
- apps/server/src/start-server.ts:133 creates the logger, checks interrupted-import state, initializes the database, and applies import boot with no exclusive data-directory claim.
- apps/server/src/db.ts:32 executes migrate(db) during initialization.
- apps/server/src/start-server.ts:504 awaits startup recovery before starting the HTTP listener.
- apps/server/src/services/system/periodic-sweeps.ts:881 runs interrupted-fork cleanup and queued-claim release.
- apps/server/src/services/threads/thread-create.ts:419 marks each copying fork deleted and requests its storage deletion, without checking whether another process owns the work.
- apps/server/src/services/threads/queued-messages.ts:747 protects only this process's active claim tokens when releasing stale claims.
- packages/bb-app/src/launcher.ts:4206 refuses only after an occupied runtime record and a healthy response at the candidate's own listener URL. The reproduction bypasses the launcher through the real standalone server entrypoint.
The deeper invariant is single live ownership of recovery-sensitive state, not uniqueness of a listening TCP port. SQLite's normal write locking does not express ownership of the entire server lifecycle.
6. Proposed fix and autopilot gate
Introduce atomic OS-backed lifetime ownership before database initialization, retain it until all server work stops, and release it on startup failure and shutdown. Reuse the shared native-lock implementation rather than adding a second dependency or relying on a racy PID probe.
No automatic PR: the available OS-backed lock is private to the shared configuration subsystem and scoped to short file mutations. Safely reusing it needs a new shared locking contract plus server-lifecycle integration, beyond this rule's one-existing-subsystem limit. A PID-only probe would leave simultaneous-start races and standalone servers uncovered.
The reusable native lock currently lives in packages/config/src/file-lock.ts:50 and is called by packages/config/src/managed-json-file.ts:11. It is not exposed through a config package subpath, and the server does not declare the native locking dependency. Do not deep-import it or introduce an undeclared dependency to force a smaller diff. A proper change must also test concurrent starts, startup failure, abrupt exit, stale artifacts, separate directories, and import/move/shutdown interactions. No production patch or fix branch was created or pushed.
7. Related issues and PR check
No open linked pull request was present in issue timeline metadata or an open-PR search for issue 7360 when checked. Existing launcher safeguards do not cover the standalone entrypoint or a distinct candidate port. No linked PR code was checked out or run.
8. Verification
The same investigator repeated the script in a second clean temporary checkout at the exact recorded base commit, after a fresh frozen install and a Turbo server/SDK build. The same command node --conditions=source --import tsx apps/server/repro-7360.mjs used new temporary directories and newly allocated ports, produced the same two destructive outcomes, and exited 1 at the safety assertion. This is a repeated check, not independent verification.
{"mode":"different-port","firstPort":31180,"secondPort":34216,"firstAlive":true,"firstHealthy":true,"secondHealthy":true,"secondExitCode":null,"secondPortConflict":false,"pendingForkRetained":false,"recoveryDeletedFork":true}
{"mode":"same-port","firstPort":48204,"secondPort":48204,"firstAlive":true,"firstHealthy":true,"secondHealthy":false,"secondExitCode":null,"secondPortConflict":true,"pendingForkRetained":false,"recoveryDeletedFork":true}
node:internal/modules/run_main:123
triggerUncaughtException(
^
AssertionError [ERR_ASSERTION]: A competing server must not delete a live owner's pending fork
at file://<second-checkout>/apps/server/repro-7360.mjs:150:1 {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '==',
diff: 'simple'
}
Node.js v22.19.0
During preparation, an initial row-existence assertion was corrected: deletion is a tombstone, not necessarily physical row removal. The final test checks deletedAt, matching the existing recovery test. Both published runs use that corrected assertion. The same-port newcomer emitted EADDRINUSE but had not exited at observation time; the report does not claim a prompt process exit.
Relevant existing tests also pass on unchanged production code:
pnpm exec turbo run test --filter=@bb/server -- test/app/startup-diagnostics.test.ts test/services/threads/thread-fork-history.test.ts test/services/periodic-sweeps.test.ts @bb/server:test: ✓ |@bb/server| test/app/startup-diagnostics.test.ts (4 tests) 11ms @bb/server:test: ✓ |@bb/server| test/services/threads/thread-fork-history.test.ts (4 tests) 775ms @bb/server:test: ✓ |@bb/server| test/services/periodic-sweeps.test.ts (9 tests) 1215ms @bb/server:test: Test Files 3 passed (3) @bb/server:test: Tests 17 passed (17) Tasks: 10 successful, 10 total Cached: 0 cached, 10 total Time: 31.128s
9. Appendix and limits
The copying marker is inserted through the real database API while the first server is healthy; this is not a real provider performing a concurrent history transfer. The test demonstrates erroneous classification and destructive recovery against another live owner's state, not completed user-data loss or a live queued-message duplicate. Database initialization/import ordering is established by source, without fabricating a pending migration or imported data set.
The initial whole-repository build failed because the GitHub plugin required missing plugin-SDK runtime entries. Building SDK types alone did not resolve that unrelated prerequisite; a Turbo SDK runtime build followed by the focused server build succeeded. The second checkout also completed the focused build. No dependency or lockfile was changed. Existing tests: 17 passed in three files. The new regression fails on unchanged production code in both clean runs. Tracked diffs passed git diff --check.
Issue content was treated as untrusted claims, not executable instructions. No issue-supplied command, patch, external link, or PR branch was executed. No workflows or other agents were started.
The complete reproduction source, both run results, and the targeted-test summary are embedded above. Raw local evidence stays outside the public reports repository.
> AGENT GENERATED