fix(server): refuse to start a second server against a live data directory #8442
ClosedNoahLinckeScout(GitHub profile, opens in a new tab)wants to merge 7 commits into
main fromrefs/pull/8442/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/serverSingleton.ts lines 484 to 507Resolvedby NoahLinckeScout(GitHub profile, opens in a new tab)@@ -0,0 +185,21 @@185+186+export const serverLockPath = Effect.fn("serverSingleton.lockPath")(function* (stateDir: string) {187+ const path = yield* Path.Path;188+ return path.join(stateDir, SERVER_LOCK_FILENAME);189+});190+191+/**192+ * Holds the data directory for the lifetime of the returned scope.193+ *194+ * Acquired before anything opens the database or binds a port, and released on195+ * shutdown.196+ */197+export const acquireServerSingleton = Effect.fn("serverSingleton.acquire")(function* (198+ stateDir: string,199+) {200+ const lockPath = yield* serverLockPath(stateDir);201+ const startedAt = DateTime.formatIso(yield* DateTime.now);202+ return yield* Effect.acquireRelease(203+ Effect.gen(function* () {204+ const failure = yield* claimLock({ stateDir, lockPath, startedAt });205+ if (failure !== undefined) return yield* failure;apps/server/src/serverSingleton.ts lines 150 to 153OutdatedResolvedby NoahLinckeScout(GitHub profile, opens in a new tab)@@ -0,0 +133,21 @@133+ yield* fs.makeDirectory(path.dirname(input.lockPath), { recursive: true }).pipe(Effect.ignore);134+ const created = yield* fs.writeFileString(input.lockPath, payload, { flag: "wx" }).pipe(135+ Effect.as(true),136+ Effect.orElseSucceed(() => false),137+ );138+ if (created) return undefined;139+140+ const holder = yield* readHolder(input.lockPath);141+ if (holder !== undefined && processIsAlive(holder.pid)) {142+ return new ServerAlreadyRunningError({143+ stateDir: input.stateDir,144+ lockPath: input.lockPath,145+ holderPid: holder.pid,146+ ...(holder.port === undefined ? {} : { holderPort: holder.port }),147+ holderStartedAt: holder.startedAt,148+ });149+ }150+ // Owner is gone, or the file is unreadable because a crash tore a write in151+ // half. Reclaim and re-race the exclusive create, which still yields one152+ // winner when two servers start together.153+ yield* fs.remove(input.lockPath).pipe(Effect.ignore);apps/server/src/serverSingleton.ts lines 181 to 183OutdatedResolvedby NoahLinckeScout(GitHub profile, opens in a new tab)@@ -0,0 +163,21 @@163+ const fs = yield* FileSystem.FileSystem;164+ const holder = yield* readHolder(lockPath);165+ if (holder !== undefined && holder.pid !== process.pid) return;166+ yield* fs.remove(lockPath).pipe(Effect.ignore);167+});168+169+/**170+ * Records the bound port on the lock we already hold.171+ *172+ * Only for the error message a *later* server prints: knowing the holder's port173+ * turns "something else is running" into an address the user can open. Failure174+ * is ignored — the lock's job is done once it is held.175+ */176+export const recordServerLockPort = Effect.fn("serverSingleton.recordPort")(function* (177+ lockPath: string,178+ port: number,179+) {180+ const fs = yield* FileSystem.FileSystem;181+ const holder = yield* readHolder(lockPath);182+ if (holder === undefined || holder.pid !== process.pid) return;183+ yield* fs.writeFileString(lockPath, encodeHolder({ ...holder, port })).pipe(Effect.ignore);
- apps/server/src/serverSingleton.ts line 183OutdatedResolvedby NoahLinckeScout(GitHub profile, opens in a new tab)@@ -0,0 +163,21 @@163+ const fs = yield* FileSystem.FileSystem;164+ const holder = yield* readHolder(lockPath);165+ if (holder !== undefined && holder.pid !== process.pid) return;166+ yield* fs.remove(lockPath).pipe(Effect.ignore);167+});168+169+/**170+ * Records the bound port on the lock we already hold.171+ *172+ * Only for the error message a *later* server prints: knowing the holder's port173+ * turns "something else is running" into an address the user can open. Failure174+ * is ignored — the lock's job is done once it is held.175+ */176+export const recordServerLockPort = Effect.fn("serverSingleton.recordPort")(function* (177+ lockPath: string,178+ port: number,179+) {180+ const fs = yield* FileSystem.FileSystem;181+ const holder = yield* readHolder(lockPath);182+ if (holder === undefined || holder.pid !== process.pid) return;183+ yield* fs.writeFileString(lockPath, encodeHolder({ ...holder, port })).pipe(Effect.ignore);apps/server/src/serverSingleton.ts line 153OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +133,21 @@133+ yield* fs.makeDirectory(path.dirname(input.lockPath), { recursive: true }).pipe(Effect.ignore);134+ const created = yield* fs.writeFileString(input.lockPath, payload, { flag: "wx" }).pipe(135+ Effect.as(true),136+ Effect.orElseSucceed(() => false),137+ );138+ if (created) return undefined;139+140+ const holder = yield* readHolder(input.lockPath);141+ if (holder !== undefined && processIsAlive(holder.pid)) {142+ return new ServerAlreadyRunningError({143+ stateDir: input.stateDir,144+ lockPath: input.lockPath,145+ holderPid: holder.pid,146+ ...(holder.port === undefined ? {} : { holderPort: holder.port }),147+ holderStartedAt: holder.startedAt,148+ });149+ }150+ // Owner is gone, or the file is unreadable because a crash tore a write in151+ // half. Reclaim and re-race the exclusive create, which still yields one152+ // winner when two servers start together.153+ yield* fs.remove(input.lockPath).pipe(Effect.ignore);
- apps/server/src/serverSingleton.ts lines 84 to 89OutdatedResolvedby NoahLinckeScout(GitHub profile, opens in a new tab)@@ -0,0 +69,21 @@69+ ` held by: ${where}`,70+ ` since: ${this.holderStartedAt}`,71+ "",72+ "Two servers sharing one data directory overwrite each other's state.sqlite",73+ "and settings.json. Stop the running server, or start this one with a",74+ "different --base-dir.",75+ "",76+ `If that process is gone, remove ${this.lockPath} and start again.`,77+ ].join("\n");78+ }79+}80+81+export class ServerLockUnavailableError extends Schema.TaggedErrorClass<ServerLockUnavailableError>()(82+ "ServerLockUnavailableError",83+ {84+ lockPath: Schema.String,85+ reason: Schema.String,86+ },87+) {88+ override get message(): string {89+ return `Could not claim the server lock at ${this.lockPath}: ${this.reason}`;apps/server/src/serverSingleton.ts lines 269 to 274Resolvedby NoahLinckeScout(GitHub profile, opens in a new tab)@@ -0,0 +117,21 @@117+ * Claims the directory, or explains who holds it.118+ *119+ * A lock file whose owner is gone — or which is unreadable, which means a120+ * half-written file from a crash mid-write — is reclaimed rather than treated as121+ * a permanent block. Reclaiming re-races the exclusive create, so two servers122+ * starting together still produce exactly one winner.123+ */124+const claimLock = Effect.fn("serverSingleton.claimLock")(function* (input: {125+ readonly stateDir: string;126+ readonly lockPath: string;127+ readonly startedAt: string;128+}) {129+ const fs = yield* FileSystem.FileSystem;130+ const path = yield* Path.Path;131+ const payload = encodeHolder({ version: 1, pid: process.pid, startedAt: input.startedAt });132+ for (let attempt = 0; attempt < 2; attempt += 1) {133+ yield* fs.makeDirectory(path.dirname(input.lockPath), { recursive: true }).pipe(Effect.ignore);134+ const created = yield* fs.writeFileString(input.lockPath, payload, { flag: "wx" }).pipe(135+ Effect.as(true),136+ Effect.orElseSucceed(() => false),137+ );
- apps/server/src/serverSingleton.ts line 153OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +133,21 @@133+ yield* fs.makeDirectory(path.dirname(input.lockPath), { recursive: true }).pipe(Effect.ignore);134+ const created = yield* fs.writeFileString(input.lockPath, payload, { flag: "wx" }).pipe(135+ Effect.as(true),136+ Effect.orElseSucceed(() => false),137+ );138+ if (created) return undefined;139+140+ const holder = yield* readHolder(input.lockPath);141+ if (holder !== undefined && processIsAlive(holder.pid)) {142+ return new ServerAlreadyRunningError({143+ stateDir: input.stateDir,144+ lockPath: input.lockPath,145+ holderPid: holder.pid,146+ ...(holder.port === undefined ? {} : { holderPort: holder.port }),147+ holderStartedAt: holder.startedAt,148+ });149+ }150+ // Owner is gone, or the file is unreadable because a crash tore a write in151+ // half. Reclaim and re-race the exclusive create, which still yields one152+ // winner when two servers start together.153+ yield* fs.remove(input.lockPath).pipe(Effect.ignore);
- apps/server/src/serverSingleton.ts lines 355 to 365OutdatedResolvedby NoahLinckeScout(GitHub profile, opens in a new tab)@@ -0,0 +345,21 @@345+ Effect.gen(function* () {346+ const failure = yield* claimLock({347+ stateDir,348+ lockPath,349+ legacyRuntimeStatePath,350+ startedAt,351+ }).pipe(352+ // The message names `server-runtime.json` (not `server.lock`) as the353+ // file to remove if the process is gone — that is all a pre-lock354+ // server ever wrote.355+ Effect.catchTag("LiveLegacyServerRuntime", (legacy) =>356+ Effect.fail(357+ new ServerAlreadyRunningError({358+ stateDir,359+ lockPath: legacyRuntimeStatePath,360+ holderPid: legacy.state.pid,361+ holderPort: legacy.state.port,362+ holderStartedAt: legacy.state.startedAt,363+ }),364+ ),365+ ),
- apps/server/src/serverSingleton.ts line 233OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +213,21 @@213+ );214+ if (created) return undefined;215+216+ const holder = yield* readHolder(input.lockPath);217+ if (holder !== undefined && processIsAlive(holder.pid)) {218+ return new ServerAlreadyRunningError({219+ stateDir: input.stateDir,220+ lockPath: input.lockPath,221+ holderPid: holder.pid,222+ ...(holder.port === undefined ? {} : { holderPort: holder.port }),223+ holderStartedAt: holder.startedAt,224+ });225+ }226+227+ if (reclaimRefreshes >= MAX_CLAIM_ATTEMPTS) {228+ // The lock stayed untouched across every observation round, which only a229+ // dead holder allows — a live one's heartbeat always refreshes inside230+ // one round. Removing it now frees the directory for the winner of the231+ // next create, and cannot delete a successor's claim.232+ yield* fs.remove(input.lockPath, { force: true });233+ return new ServerLockUnavailableError({
- apps/server/src/serverSingleton.ts line 419Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +260,21 @@260+ */261+const holdServerLock = Effect.fn("serverSingleton.hold")(function* (lockPath: string) {262+ const fs = yield* FileSystem.FileSystem;263+ // `Effect.repeat` with a spaced schedule (rather than `Effect.schedule`) so264+ // a failure wakes the loop on the next tick instead of terminating it: the265+ // holder must keep refreshing for as long as it owns the lock, through266+ // whatever transient filesystem errors come and go.267+ const reschedule = Schedule.spaced(RECLAIM_OBSERVATION_DELAY_MILLIS);268+ yield* Effect.forkScoped(269+ Effect.gen(function* () {270+ const holder = yield* readHolder(lockPath);271+ if (holder === undefined || holder.pid !== process.pid) return;272+ const now = yield* DateTime.now;273+ const date = DateTime.toDateUtc(now);274+ yield* fs.utimes(lockPath, date, date);275+ }).pipe(276+ Effect.repeat({ schedule: reschedule, while: () => true }),277+ Effect.catch(() => Effect.void),278+ ),279+ );280+});apps/server/src/serverSingleton.ts line 251OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +231,21 @@231+ // next create, and cannot delete a successor's claim.232+ yield* fs.remove(input.lockPath, { force: true });233+ return new ServerLockUnavailableError({234+ lockPath: input.lockPath,235+ attempts: reclaimRefreshes,236+ });237+ }238+239+ // Owner is gone, or the file is unreadable because a crash tore a write240+ // in half. Never unlink unconditionally: between this starter's read and241+ // its remove, a successor can win the re-race and recreate its own live242+ // lock, and the unlink would delete that. Reclaim instead refreshes the243+ // file's mtime once per observation round and only removes it after it has244+ // stayed untouched across `MAX_CLAIM_ATTEMPTS` rounds — a live245+ // successor's heartbeat always refreshes inside that window, so the file246+ // this starter removes is provably still a dead one's. The wait lands in247+ // the *next* loop head's `Effect.yieldNow`, which keeps `claimLock`248+ // real-time-only so tests can drive it without a fake clock.249+ reclaimRefreshes += 1;250+ const now = yield* DateTime.now;251+ yield* fs.utimes(input.lockPath, DateTime.toDateUtc(now), DateTime.toDateUtc(now));
- apps/server/src/server.ts lines 644 to 649OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -622,3 +637,13 @@622637 }623638624639 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;640+641+ // Stamp the port onto the lock we already hold. It is only ever read642+ // by a *later* server's refusal message, which turns "something else643+ // is running" into an address the user can open.644+ yield* ServerSingleton.serverLockPath(config.stateDir).pipe(645+ Effect.flatMap((lockPath) =>646+ ServerSingleton.recordServerLockPort(lockPath, address.port),647+ ),648+ Effect.ignore,649+ );@@ -794,4 +820,4 @@794820 Layer.provideMerge(runtimeServicesLive),795821 Layer.provide(activationLayer),796822 Layer.provideMerge(serverRelayBrokerTracingLayer),797- Layer.provideMerge(HttpServerLive),823+ Layer.provideMerge(HttpServerLive.pipe(Layer.provide(ServerSingletonLive))),apps/server/src/serverSingleton.ts lines 247 to 253OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +233,21 @@233+ }234+235+ // The read found no live owner — either a decodeable dead holder, or236+ // `undefined` because the file is missing (another starter mid-reclaim)237+ // or undecodable (a crash tore a write in half). Never unlink after one238+ // read: between this starter's read and its remove, a successor can win239+ // the re-race and recreate its own live lock, and the unlink would delete240+ // that. The candidate is mtime-refreshed and re-observed across241+ // `MAX_CLAIM_ATTEMPTS` rounds, and only a file that stayed untouched242+ // through every round is removed — a live successor's heartbeat always243+ // refreshes inside one round, so the file a reclaimer finally removes is244+ // provably still dead. The wait lands in the *next* loop head's245+ // `Effect.yieldNow`, which keeps `claimLock` real-time-only so tests can246+ // drive it without a fake clock.247+ if (reclaimRefreshes >= MAX_CLAIM_ATTEMPTS) {248+ // Removing frees the directory, and the create is retried on the next249+ // pass: a cleanly restarted server after a crash claims its directory250+ // here, not on a later manual retry. Bounded, so a lock another starter251+ // keeps recreating (or a permissions wall keeps failing to remove for)252+ // still surfaces as itself.253+ yield* fs.remove(input.lockPath, { force: true });
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/serverSingleton.ts line 178OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +158,21 @@158+159+const isNotFound = (error: PlatformError.PlatformError): boolean => error.reason._tag === "NotFound";160+161+const reclaimGatePath = (lockPath: string): string => `${lockPath}.reclaim`;162+163+/**164+ * Serialize stale-lock takeover. Two reclaimers can both finish the last165+ * stale read, then both `remove` — the second deletes the first's fresh166+ * claim. An exclusive gate file makes exactly one reclaimer allowed to167+ * touch `server.lock`; everyone else backs off and retries the create.168+ */169+const takeReclaimGate = Effect.fn("serverSingleton.takeReclaimGate")(function* (lockPath: string) {170+ const fs = yield* FileSystem.FileSystem;171+ const gatePath = reclaimGatePath(lockPath);172+ const existing = yield* fs.readFileString(gatePath).pipe(173+ Effect.catch((error) => (isNotFound(error) ? Effect.succeed(undefined) : Effect.fail(error))),174+ );175+ if (existing !== undefined) {176+ const gatePid = Number.parseInt(existing.trim(), 10);177+ if (processIsAlive(gatePid)) return false;178+ yield* fs.remove(gatePath, { force: true }).pipe(Effect.ignore);apps/server/src/serverSingleton.ts lines 330 to 347Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +284,21 @@284+ if (reclaimCycles >= MAX_RECLAIM_CYCLES) {285+ return new ServerLockUnavailableError({286+ lockPath: input.lockPath,287+ attempts: reclaimCycles,288+ });289+ }290+ continue;291+ }292+ const gatePath = reclaimGatePath(input.lockPath);293+ const takeover = yield* Effect.gen(function* () {294+ const holderAfterGate = yield* readHolder(input.lockPath);295+ if (holderAfterGate !== undefined && processIsAlive(holderAfterGate.pid)) {296+ return new ServerAlreadyRunningError({297+ stateDir: input.stateDir,298+ lockPath: input.lockPath,299+ holderPid: holderAfterGate.pid,300+ ...(holderAfterGate.port === undefined ? {} : { holderPort: holderAfterGate.port }),301+ holderStartedAt: holderAfterGate.startedAt,302+ });303+ }304+ yield* fs.remove(input.lockPath, { force: true });
juliusmarminge added labelsmacroscope-review
- @@ -0,0 +258,21 @@258+ // Counts how often this starter was forced to refresh a candidate stale lock259+ // before believing it is really dead, and how often a confirmed-dead lock260+ // bounced it back to another round (see the constants above).261+ let reclaimRefreshes = 0;262+ let reclaimCycles = 0;263+ while (true) {264+ // A scheduler yield between attempts, so a reclaim observation round lets265+ // other starters (and the holder's heartbeat) run before this starter266+ // concludes a lock never changed. Real time only — resolvable under267+ // `TestClock`.268+ yield* Effect.yieldNow;269+ const created = yield* fs.writeFileString(input.lockPath, payload, { flag: "wx" }).pipe(270+ Effect.as(true),271+ Effect.catch((error) =>272+ isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),273+ ),274+ );275+ if (created) return undefined;276+277+ const holder = yield* readHolder(input.lockPath);278+ if (holder !== undefined && processIsAlive(holder.pid)) {
juliusmarminge closed this
Sign in to join this conversation.


No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
a68c549b-1909-41e3-b7a3-ecae9404d3c3📥 Commits
Reviewing files that changed from the base of the PR and between 455dcf4b2d44b5bfa1eef29de67f57e3b41c603e and 2feefe653f1ccf090878022023e8a2e19bc0183c.
📒 Files selected for processing (2)
apps/server/src/serverSingleton.test.tsapps/server/src/serverSingleton.ts🚧 Files skipped from review as they are similar to previous changes (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
📝 Walkthrough
Walkthrough#
The server now claims a data-directory lock before HTTP binding and SQLite initialization. The lock supports stale-lock reclamation, heartbeat refresh, ownership-safe release, legacy runtime detection, and atomic port recording. Tests cover concurrent reclaimers and lock lifecycle behavior.
Changes#
Server Singleton Lock
apps/server/src/serverSingleton.tsapps/server/src/serverSingleton.tsapps/server/src/server.tsapps/server/src/serverSingleton.test.tsPriority: ➖ Normal
Estimated code review effort: 4 (Complex) | ~60 minutes
Change: Bug fix · Severity of issue fixed: Medium
Sequence Diagram(s)#
Merge Risk: ⚪ Minimal · up to
2feefThis change adds a startup-time lock so two server processes cannot bind to the same data directory at once, with tests confirming that stale, crashed, and legacy locks are reclaimed correctly while live holders and their successors are protected. No unresolved correctness or availability issue was found in the reviewed lock, heartbeat, release, or port-recording logic, so this is ready to merge from a review standpoint; the previously discussed narrow race with an unmodified, lock-unaware older binary is an acknowledged limitation already deferred to a separate follow-up PR rather than a defect in this change.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.