Skip to content

Commit fa1e404

Browse files
siimveneclaude
andcommitted
Make broker.json lifecycle follow the broker, not the session
The state record now lives and dies with the broker it points at: - SessionEnd no longer clears the workspace-wide broker.json. The record is shared by every session on the cwd, so a session ending must not delete it out from under a peer whose turn is still running. - The broker retires its own record at the start of shutdown(), guarded on the endpoint still matching, so a clean exit (idle, broker/shutdown, SIGTERM/SIGINT) leaves no stale pointer and a record that was already replaced is never touched. - The reuseExistingBroker path validates the recorded endpoint before handing it out, so a record left by an uncleanly killed broker degrades to a direct app server instead of erroring against a dead socket. - getSessionRuntimeStatus checks the unix socket file exists before reporting a shared runtime. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent fe08482 commit fa1e404

5 files changed

Lines changed: 50 additions & 16 deletions

File tree

‎plugins/codex/scripts/app-server-broker.mjs‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import process from "node:process";
88
import { parseArgs } from "./lib/args.mjs";
99
import { BROKER_BUSY_RPC_CODE, CodexAppServerClient } from "./lib/app-server.mjs";
1010
import { parseBrokerEndpoint } from "./lib/broker-endpoint.mjs";
11+
import { clearBrokerSession, loadBrokerSession } from "./lib/broker-lifecycle.mjs";
1112

1213
const STREAMING_METHODS = new Set(["turn/start", "review/start", "thread/compact/start"]);
1314

@@ -73,7 +74,7 @@ async function main() {
7374
const sockets = new Set();
7475

7576
// Forward a request to the app server while counting it as in-flight, so idle
76-
// self-shutdown can never fire while real work is running — even if the calling
77+
// self-shutdown can never fire while real work is running, even if the calling
7778
// client disconnected mid-request (which clears activeRequestSocket).
7879
async function forwardAppRequest(method, params) {
7980
inFlightRequests += 1;
@@ -114,6 +115,19 @@ async function main() {
114115
}
115116

116117
async function shutdown(server) {
118+
// Retire this broker's state record first, while its socket is still the
119+
// live one for this cwd: no replacement broker can have been spawned yet,
120+
// so the guarded clear cannot race a newer record, and clients probing
121+
// from here on fall back to starting a fresh broker instead of connecting
122+
// to a dying one. Guarded on the endpoint matching, so a record that was
123+
// already replaced (e.g. this broker was deemed unresponsive) is kept.
124+
try {
125+
if (loadBrokerSession(cwd)?.endpoint === endpoint) {
126+
clearBrokerSession(cwd);
127+
}
128+
} catch {
129+
// Ignore unreadable or already-removed state records.
130+
}
117131
for (const socket of sockets) {
118132
socket.end();
119133
}

‎plugins/codex/scripts/lib/app-server.mjs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import process from "node:process";
1313
import { spawn } from "node:child_process";
1414
import readline from "node:readline";
1515
import { parseBrokerEndpoint } from "./broker-endpoint.mjs";
16-
import { ensureBrokerSession, loadBrokerSession } from "./broker-lifecycle.mjs";
16+
import { ensureBrokerSession, loadBrokerSession, waitForBrokerEndpoint } from "./broker-lifecycle.mjs";
1717
import { terminateProcessTree } from "./process.mjs";
1818

1919
const PLUGIN_MANIFEST_URL = new URL("../../.claude-plugin/plugin.json", import.meta.url);
@@ -338,7 +338,14 @@ export class CodexAppServerClient {
338338
if (!options.disableBroker) {
339339
brokerEndpoint = options.brokerEndpoint ?? options.env?.[BROKER_ENDPOINT_ENV] ?? process.env[BROKER_ENDPOINT_ENV] ?? null;
340340
if (!brokerEndpoint && options.reuseExistingBroker) {
341-
brokerEndpoint = loadBrokerSession(cwd)?.endpoint ?? null;
341+
// Validate the recorded endpoint before reusing it: the record can be
342+
// stale when the broker died without a clean exit. A stale record then
343+
// behaves like no record, and the caller falls back to a direct app
344+
// server instead of erroring against a dead socket.
345+
const recordedEndpoint = loadBrokerSession(cwd)?.endpoint ?? null;
346+
if (recordedEndpoint && (await waitForBrokerEndpoint(recordedEndpoint, 150).catch(() => false))) {
347+
brokerEndpoint = recordedEndpoint;
348+
}
342349
}
343350
if (!brokerEndpoint && !options.reuseExistingBroker) {
344351
const brokerSession = await ensureBrokerSession(cwd, { env: options.env });

‎plugins/codex/scripts/lib/broker-lifecycle.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,12 +252,12 @@ export async function reapBrokerSessions({ tmpDir = os.tmpdir() } = {}) {
252252
}
253253
const sessionDir = path.join(tmpDir, entry.name);
254254
if (!fs.existsSync(path.join(sessionDir, "broker.pid"))) {
255-
continue; // a broker removes its own dir on clean exit — nothing to do
255+
continue; // a broker removes its own dir on clean exit; nothing to do
256256
}
257257

258258
const pid = readBrokerPid(sessionDir);
259259
if (pid !== null && isPidAlive(pid)) {
260-
continue; // live broker — leave it entirely alone (it self-exits when idle)
260+
continue; // live broker: leave it entirely alone (it self-exits when idle)
261261
}
262262

263263
// The broker process is gone but left its directory behind (killed, not a

‎plugins/codex/scripts/lib/codex.mjs‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import path from "node:path";
4141

4242
import { readJsonFile } from "./fs.mjs";
4343
import { BROKER_BUSY_RPC_CODE, BROKER_ENDPOINT_ENV, CodexAppServerClient } from "./app-server.mjs";
44+
import { parseBrokerEndpoint } from "./broker-endpoint.mjs";
4445
import { loadBrokerSession } from "./broker-lifecycle.mjs";
4546
import { binaryAvailable } from "./process.mjs";
4647

@@ -903,8 +904,23 @@ export function getCodexAvailability(cwd) {
903904
};
904905
}
905906

907+
// An endpoint reference can outlive its broker when the process died without a
908+
// clean exit. For unix sockets the broker removes its socket on clean shutdown
909+
// and the session-start reaper removes it after an unclean death, so a missing
910+
// socket file means no shared runtime is live. Pipe endpoints (Windows) cannot
911+
// be checked without connecting and are reported as-is.
912+
function isBrokerEndpointPresent(endpoint) {
913+
try {
914+
const target = parseBrokerEndpoint(endpoint);
915+
return target.kind === "unix" ? fs.existsSync(target.path) : true;
916+
} catch {
917+
return false;
918+
}
919+
}
920+
906921
export function getSessionRuntimeStatus(env = process.env, cwd = process.cwd()) {
907-
const endpoint = env?.[BROKER_ENDPOINT_ENV] ?? loadBrokerSession(cwd)?.endpoint ?? null;
922+
const recorded = env?.[BROKER_ENDPOINT_ENV] ?? loadBrokerSession(cwd)?.endpoint ?? null;
923+
const endpoint = recorded && isBrokerEndpointPresent(recorded) ? recorded : null;
908924
if (endpoint) {
909925
return {
910926
mode: "shared",

‎plugins/codex/scripts/session-lifecycle-hook.mjs‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@ import fs from "node:fs";
44
import process from "node:process";
55

66
import { terminateProcessTree } from "./lib/process.mjs";
7-
import {
8-
clearBrokerSession,
9-
reapBrokerSessions
10-
} from "./lib/broker-lifecycle.mjs";
7+
import { reapBrokerSessions } from "./lib/broker-lifecycle.mjs";
118
import { loadState, resolveStateFile, saveState } from "./lib/state.mjs";
129
import { TRANSCRIPT_PATH_ENV } from "./lib/claude-session-transfer.mjs";
1310
import { resolveWorkspaceRoot } from "./lib/workspace.mjs";
@@ -81,12 +78,12 @@ async function handleSessionStart(input) {
8178
async function handleSessionEnd(input) {
8279
const cwd = input.cwd || process.cwd();
8380
cleanupSessionJobs(cwd, input.session_id || process.env[SESSION_ID_ENV]);
84-
// Do not shut down or kill this cwd's broker: it may be shared with a
85-
// concurrent session, and it exits itself once idle (app-server-broker.mjs).
86-
// Just drop this session's pointer to it.
87-
clearBrokerSession(cwd);
88-
// GC the directories of brokers that have already exited. A live broker —
89-
// including one a concurrent session is still using — is never touched.
81+
// Do not shut down or kill this cwd's broker, and do not clear its state
82+
// record: both are shared with any concurrent session on the same cwd. The
83+
// broker exits itself once idle and removes its own record then
84+
// (app-server-broker.mjs), so a session ending leaves it entirely alone.
85+
// GC the directories of brokers that have already exited. A live broker,
86+
// including one a concurrent session is still using, is never touched.
9087
await reapBrokerSessions();
9188
}
9289

0 commit comments

Comments
 (0)