Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): stop OpenCode servers left behind by a crashed server #13879

Mergedjuliusmarmingemerged 2 commits intot3code/codex-turn-mapping fromrefs/pull/13879/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

When the T3 server is SIGKILLed or crashes, every opencode serve it started keeps running. Those servers are spawned detached into their own process group, so they get re-parented to init and nothing reaps them on the next start. Each one holds several hundred MB. A graceful shutdown doesn't leak, because the scope finalizer stops the group.

What changed

  • New OpenCodeServerLedger (apps/server/src/provider/OpenCodeServerLedger.ts). When startOpenCodeServerProcess spawns a server, it writes <stateDir>/opencode-servers/<pid>.json holding the pid, pgid, process start time, port, serve argv, state dir, and the owning T3 server's pid + start time. The entry is removed after the group is stopped on a graceful close. The finalizer is registered before the group kill, so it runs after it.
  • At startup the layer reaps entries in the background, so startup isn't blocked. It skips entries whose owner is still running, so a second server on the same home is left alone. It signals the group (SIGTERM, then SIGKILL after 2s) only when the recorded member still has the same pid, start time, pgid, and full command line (which includes the unique --port T3 chose). Otherwise it just drops the entry. A recycled pid is never signalled.
  • If the spawned process already exited by the time it is recorded (a wrapper that leaves serve running), the group is recorded through any live member, since a group id is not reused while it has members. The group kill finalizer is registered before recording, so an interrupt during recording still stops the group; the entry is forgotten only after the group is stopped.
  • Start time comes from /proc/<pid>/stat field 22 on Linux and from LC_ALL=C TZ=UTC /bin/ps -o lstart on macOS. macOS lstart has whole-second precision; nothing finer is available from ps, and sysctl kern.proc.pid has no CLI, so the command-line match is what rules out a same-second pid reuse. Residual risk: an unrelated process would have to reuse the pid within the same second, land in a group with the same id, and run opencode serve on the same port. On Windows the server is not detached (detached: hostPlatform !== "win32"), so nothing is recorded and reaping does nothing.
  • The detach itself stays. It was added in 35822884d1 so T3 can stop the whole group, including any serve process the wrapper leaves behind.
  • The service is a Context.Service without a default, so building OpenCodeRuntimeLive requires a ledger. server.ts provides the real layer; tests that start servers without a state directory provide OpenCodeServerLedger.layerTest.

I looked for an existing registry to reuse first. AcpSessionRuntime has Linux-only /proc identity helpers for its in-process ownership ledger, but nothing persists across restarts and nothing covers macOS, so this adds a small dedicated one.

Verification

  • OpenCodeServerLedger.test.ts: 11/11 pass (the review follow-up added a wrapper-exited group, a different-port command line, and an interrupt during recording that must still stop the group; the first and last fail with their fix reverted). The tests use real detached process groups (/bin/sh -c "sleep 600 & wait" serve --hostname=… --port=…), run once with the /proc path and once with the ps path. procps accepts the same flags as macOS ps, so Linux CI covers both.
    • A server that died leaves an entry. A fresh ledger reaps it, the group exits on SIGTERM, and the entry is gone.
    • Recycled pid: the entry's start time is rewritten, and the live group is not signalled. The entry is dropped.
    • Entries whose owning T3 server is still running are left alone. forget removes the entry.
  • Real OpenCode 1.18.32 end-to-end (throwaway script against a temp state dir, not committed):
    • Server A started opencode serve (pid 341712), then A was SIGKILLed. The server was still alive, ppid 1287 (subreaper), 376 MB RSS.
    • Server B started on the same state dir. The orphan was gone and only B's entry remained.
    • B was stopped with SIGTERM. Its server was gone and no entries were left.
  • Checked that the macOS ps output format parses with the ledger's regex on a real macOS host (mac mini).
  • vp exec tsc --noEmit -p apps/server: no errors. vp lint on touched files: clean. knip --workspace apps/server --exports: clean.
  • Existing OpenCode tests pass: opencodeRuntime.environment, opencodeRuntime.inventory, OpenCodeServerOwner, OpenCodeProvider (50 tests total).
  • Not run: the full server suite (CI owns it), and a macOS run of the test file itself.

Closes #5241

Model: Claude Opus 5.5 (Claude Code)

🤖 Generated with Claude Code


Devin Review
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    2. @@ -0,0 +158,21 @@
      158+ if (platform === "darwin")
      159+ return observeDarwin(pid).pipe(Effect.orElseSucceed(() => undefined));
      160+ return Effect.succeed(undefined);
      161+ };
      162+
      163+ const isRunning = (identity: ProcessIdentity) =>
      164+ observe(identity.pid).pipe(
      165+ Effect.map(
      166+ (observed) =>
      167+ observed !== undefined && !observed.zombie && observed.startTime === identity.startTime,
      168+ ),
      169+ );
      170+
      171+ const ownerPid = input.ownerPid ?? process.pid;
      172+ const ownerProcess = yield* observe(ownerPid);
      173+ const owner =
      174+ ownerProcess === undefined ? undefined : { pid: ownerPid, startTime: ownerProcess.startTime };
      175+
      176+ const track: OpenCodeServerLedgerShape["track"] = (server) =>
      177+ Effect.gen(function* () {
      178+ const observed = yield* observe(server.pid);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High provider/OpenCodeServerLedger.ts:178

      The detached OpenCode process group survives scope interruption when track is suspended in observe or filesystem I/O, because startOpenCodeServerProcess has not yet installed the later terminateChild finalizer (and may not have written a ledger entry). Register the kill finalizer immediately after spawning child, before awaiting serverLedger.track, so scope closure cannot leak the group.

      Also found in 1 other location(s)

      apps/server/src/provider/opencodeRuntime.ts:728

      serverLedger.track performs process observation and filesystem I/O before any termination finalizer is installed for child. If the caller scope is interrupted/closed while this effect is suspended (for example, during a slow or hung state-directory operation), execution never reaches the later Scope.addFinalizer for terminateChild; the detached process group therefore survives the scope close. Register the kill finalizer immediately after spawning, before awaiting ledger I/O, so cancellation cannot recreate the server-leak the ledger is meant to prevent.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/provider/OpenCodeServerLedger.ts around line 178:
      
      The detached OpenCode process group survives scope interruption when `track` is suspended in `observe` or filesystem I/O, because `startOpenCodeServerProcess` has not yet installed the later `terminateChild` finalizer (and may not have written a ledger entry). Register the kill finalizer immediately after spawning `child`, before awaiting `serverLedger.track`, so scope closure cannot leak the group.
      
      Also found in 1 other location(s):
      - apps/server/src/provider/opencodeRuntime.ts:728 -- `serverLedger.track` performs process observation and filesystem I/O before any termination finalizer is installed for `child`. If the caller scope is interrupted/closed while this effect is suspended (for example, during a slow or hung state-directory operation), execution never reaches the later `Scope.addFinalizer` for `terminateChild`; the detached process group therefore survives the scope close. Register the kill finalizer immediately after spawning, before awaiting ledger I/O, so cancellation cannot recreate the server-leak the ledger is meant to prevent.
      
      @@ -0,0 +129,21 @@
      129+ .string(
      130+ ChildProcess.make(
      131+ "/bin/ps",
      132+ ["-ww", "-o", "pgid=", "-o", "stat=", "-o", "lstart=", "-o", "args=", "-p", String(pid)],
      133+ {
      134+ env: { LC_ALL: "C", TZ: "UTC" },
      135+ extendEnv: true,
      136+ stdin: "ignore",
      137+ stderr: "ignore",
      138+ },
      139+ ),
      140+ )
      141+ .pipe(
      142+ Effect.timeout("5 seconds"),
      143+ Effect.map((output): ObservedProcess | undefined => {
      144+ const match = DARWIN_PS_LINE.exec(output.trim());
      145+ if (match === null) return undefined;
      146+ return {
      147+ pgid: Number(match[1]),
      148+ startTime: match[3]!,
      149+ command: match[4]!,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High provider/OpenCodeServerLedger.ts:149

      On macOS, stopOrphan can signal a newly started, unrelated opencode serve process after PID reuse within the same second. ps lstart at line 149 preserves only whole-second precision, so the replacement can match the recorded PID, pgid, startTime, and argv; use a process identity with subsecond or otherwise collision-resistant start information before signaling.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/provider/OpenCodeServerLedger.ts around line 149:
      
      On macOS, `stopOrphan` can signal a newly started, unrelated `opencode serve` process after PID reuse within the same second. `ps lstart` at `line 149` preserves only whole-second precision, so the replacement can match the recorded PID, `pgid`, `startTime`, and argv; use a process identity with subsecond or otherwise collision-resistant start information before signaling.
    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This change adds persistent process tracking, asynchronous startup reaping, and SIGTERM/SIGKILL handling for detached OpenCode groups, substantially changing production lifecycle behavior. The new test also suppresses a static-analysis diagnostic, while unresolved concerns remain around cancellation cleanup and macOS process identity matching.

      Not approved because:

      • 2 blocking correctness issues found at or above your repo's Minimum Blocking Severity
      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. @@ -0,0 +77,21 @@
      77+ // The group may already be gone.
      78+ }
      79+};
      80+
      81+const groupExists = (pgid: number) => {
      82+ try {
      83+ process.kill(-pgid, 0);
      84+ return true;
      85+ } catch (cause) {
      86+ return (cause as NodeJS.ErrnoException | undefined)?.code !== "ESRCH";
      87+ }
      88+};
      89+
      90+const isOpenCodeServeCommand = (command: string, args: ReadonlyArray<string>) =>
      91+ args[0] === "serve" && command.endsWith(` ${args.join(" ")}`);
      92+
      93+/**
      94+ * Builds a ledger for one state directory. `ownerPid` is the T3 server that
      95+ * owns the servers it tracks; it defaults to this process.
      96+ */
      97+export const makeOpenCodeServerLedger = Effect.fn("OpenCodeServerLedger.make")(function* (input: {

      This implementation-specific service module should export its constructor as make, not makeOpenCodeServerLedger. Rename the export and update the layer and callers (including tests) to use OpenCodeServerLedger.make.

      Posted via Macroscope — Effect Service Conventions
    5. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ℹ️ No successful main baseline artifact is available yet. This run establishes the initial measurement.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire—4.9 KiB—6.8 KiB✅
      CodexThread snapshot wire—3.7 KiB—4.9 KiB✅
      CodexLive turn WebSocket wire—1.2 KiB—2.0 KiB✅
      CodexLive turn WebSocket decoded—20.4 KiB—29.3 KiB✅
      CodexLive turn messages—2—8✅
      ClaudeTotal thread wire—4.9 KiB—6.8 KiB✅
      ClaudeThread snapshot wire—3.7 KiB—4.9 KiB✅
      ClaudeLive turn WebSocket wire—1.2 KiB—2.0 KiB✅
      ClaudeLive turn WebSocket decoded—20.7 KiB—29.3 KiB✅
      ClaudeLive turn messages—1—8✅

      Baseline: unavailable · PR result: 24fe658 · Source CI: success

      Scenario and decoded snapshot size

      10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.

      • Codex decoded thread snapshot: 106.1 KiB
      • Claude decoded thread snapshot: 106.4 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

    6. juliusmarminge merged thisfe6553e

    7. juliusmarminge closed this

Sign in to join this conversation.