fix(server): preserve newer runtime state on shutdown #9045
main fromrefs/pull/9045/head·opened View on GitHubWhat Changed#
- Return the persisted runtime owner from the server resource acquisition.
- Remove runtime state only when
pidandstartedAtstill match that owner. - Keep unconditional cleanup for callers that deliberately clear confirmed stale state.
- Add tests for matching-owner cleanup and newer-owner preservation.
Why#
Two T3 servers can overlap briefly during an SSH reconnect. An older server previously removed the shared server-runtime.json during shutdown, even after a newer server replaced it. This left endpoint discovery without the current server record.
The owner check keeps the newer record while preserving existing stale-state cleanup behavior.
Checklist#
- This PR is small and focused
- I explained what changed and why
- UI screenshots are not applicable
- Animation or interaction video is not applicable
Validation:
vp test run apps/server/src/serverRuntimeState.test.ts: 8 tests passed.vp run --filter t3 typecheck: passed with existing suggestions in unrelated files.- Focused lint passed.
- Context documentation is not needed. This change does not add domain language or a durable product decision.
Note
Medium Risk Changes shared runtime-state lifecycle on shutdown; incorrect owner matching could leave stale files or skip needed cleanup, though behavior is covered by new tests and CLI paths stay unconditional.
Overview
Fixes a race where an older server process could delete server-runtime.json on shutdown after a newer server had already written it (e.g. brief overlap on SSH reconnect), breaking endpoint discovery.
clearPersistedServerRuntimeState now accepts an optional owner (pid + startedAt). When provided, it reads the file and skips removal unless the on-disk record still matches that owner. Callers that omit the owner (e.g. CLI stale cleanup) still delete unconditionally.
The server acquireRelease hook returns the persisted state (or null when no port was written) and passes it into shutdown cleanup so only the stopping instance clears its own record.
Note
Fix clearPersistedServerRuntimeState to skip clearing newer server state on shutdown#
- On shutdown the server now passes the state it acquired at startup as an
expectedOwnertoclearPersistedServerRuntimeState(path, expectedOwner)so it only deletes the persisted file whenpidandstartedAtstill match the current instance - If the server had no numeric port/address, the release phase receives
nulland skips the clear entirely - Adds tests verifying the file is removed on owner match and preserved when the stored state belongs to a different/newer server
- Behavioral Change:
clearPersistedServerRuntimeStatesignature gains a second optionalexpectedOwnerparameter; callers that omit it keep the old unconditional-delete behavior
📊 Macroscope summarized 0d22f86. 2 files reviewed, 2 issues evaluated, 1 issue filtered, 1 comment posted
🗂️ Filtered Issues#
apps/server/src/serverRuntimeState.ts — 0 comments posted, 1 evaluated, 1 filtered
- line 96: The owner check is a time-of-check/time-of-use race: after
readPersistedServerRuntimeState(path)confirms that the old instance owns the file, a newer server can atomically replace the state beforefs.remove(path)runs. The old shutdown then unlinks the newer server's record, recreating the endpoint-discovery failure this guard is intended to prevent. [ Cross-file consolidated ]
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:S
- @@ -510,10 +510,9 @@510510 Effect.logWarning("Failed to persist server runtime state", { cause }),511511 ),512512 );513+ return state;513514 }),514- () =>515- clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(516- Effect.catchCause((cause) =>517- Effect.logWarning("Failed to clear server runtime state", { cause }),518- ),519- ),515+ (state) =>516+ state === null517+ ? Effect.void518+ : clearPersistedServerRuntimeState(config.serverRuntimeStatePath, state).pipe(
🟠 High
src/server.ts:518The old server can delete a newer server's runtime-state file:
clearPersistedServerRuntimeStateverifies ownership withreadPersistedServerRuntimeState, then performsfs.removeseparately, allowing an overlapping startup to replace the file between those operations. This removes the active endpoint record and breaks discovery; the check-and-remove must be atomic (or otherwise revalidate ownership immediately before deletion).Also found in 1 other location(s)
apps/server/src/serverRuntimeState.ts:96The owner check is a time-of-check/time-of-use race: after
readPersistedServerRuntimeState(path)confirms that the old instance owns the file, a newer server can atomically replace the state beforefs.remove(path)runs. The old shutdown then unlinks the newer server's record, recreating the endpoint-discovery failure this guard is intended to prevent.🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/server/src/server.ts around line 518: The old server can delete a newer server's runtime-state file: `clearPersistedServerRuntimeState` verifies ownership with `readPersistedServerRuntimeState`, then performs `fs.remove` separately, allowing an overlapping startup to replace the file between those operations. This removes the active endpoint record and breaks discovery; the check-and-remove must be atomic (or otherwise revalidate ownership immediately before deletion). Also found in 1 other location(s): - apps/server/src/serverRuntimeState.ts:96 -- The owner check is a time-of-check/time-of-use race: after `readPersistedServerRuntimeState(path)` confirms that the old instance owns the file, a newer server can atomically replace the state before `fs.remove(path)` runs. The old shutdown then unlinks the newer server's record, recreating the endpoint-discovery failure this guard is intended to prevent. Approvability#
Verdict: Would Approve
Macroscope's review found this PR approvable — This is a focused three-file shutdown bug fix that preserves newer runtime-state records while retaining existing unconditional cleanup for other callers, with targeted tests and no schema, deployment, security, billing, or default changes. An unresolved High-severity finding still identifies a possible check-then-remove race in the ownership guard, which is a separate blocking correctness concern.
Not approved because:
- 1 blocking correctness issue found at or above your repo's Minimum Blocking Severity
juliusmarminge added labelsmacroscope-review
This fixes one of the triggers in #5749. There, three reports (Sep 15, 24 and 26) describe a stopped server deleting the live service's
server-runtime.json, which leads the next SSH reconnect to start a second server. I checked this PR against that sequence end to end, with real servers.Setup: two worktrees:
mainat8ed276c24andmainwith this PR merged (clean merge, andpackages/sshis identical in both). I ran realnode apps/server/src/bin.ts serveprocesses. The launch and stop scripts came frombuildRemoteLaunchScript/buildRemoteStopScriptin the same checkout.HOMEwas an isolated directory under/tmp. Ubuntu 24.04 x86_64, Node 24.19.Sequence:
- The launcher starts a managed server.
- A service-style server starts on the same base dir and records itself in
server-runtime.json. - The launcher runs again. It adopts the service as
externaland stops its own managed server. - The desktop treats the tunnel as stale, so the stop script runs, then the launch script.
mainmain+ this PRserver-runtime.jsonafter step 3missing (the managed server's shutdown removed the service's record) kept (service PID) Step 4 result serverKind: "managed": a second server starts next to the live serviceserverKind: "external": the service is adoptedEach build gave the same result in 3 out of 3 runs.
This matches what I saw on a real host (0.0.45, macOS desktop → SSH → systemd service). The launcher adopted the service at 14:28, and the old managed server shut down at 14:28:58. At 14:40 a stale-tunnel stop and relaunch started a managed server on 3774, while the service was still healthy (
NRestarts=0).Not covered:
- The check-then-remove race Macroscope flagged. These runs don't overlap a startup with a shutdown.
- I used a placeholder
apps/web/dist/index.htmlso that the launcher'sGET /readiness probe returns 200, as it does with the release binary. - I only tested the SSH launcher path.
Note
Written by
claude-opus-5-5on behalf of MariaThanks for this. I'm closing it as part of PR triage. This is already fixed on main.
From the review: Main now holds an exclusive state-directory lock and checks the runtime record's owner ID before removing it, preserving records published by another server.
If you think this was a mistake, message me on Twitter at @maria_rcks and I'll take another look.
maria-rcks closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed