fix: give the app-server broker an idle timeout, and kill the one it replaces
Stacked on #577 — it contains the taskkill fix this one's kill path depends on, so the diff to review here is the last commit only. Without #577 the new
replacing a stale broker kills the process it replacestest fails on a Git Bash host; that is not a hypothetical, it is how the dependency was found.
An app-server broker is spawned detached + unref and exits only on a broker/shutdown RPC or SIGTERM/SIGINT. Anything that loses track of one strands it — and the ~9-process codex stack under it — permanently. One Windows host reached 2257 processes against a ~330 baseline. Two independent causes:
1. No idle timeout. Nothing reaps a broker whose parent was hard-killed. Now it exits after 30 minutes with zero connected sockets. That is safe to do: a turn holds its socket open for its whole duration, so zero sockets means nothing is in flight, and the thread itself lives in $CODEX_HOME/sessions and stays resumable — the next caller just respawns a broker. This is the only fix that covers every way a broker gets stranded.
2. The stale-replacement path never killed. teardownBrokerSession's kill is opt-in and the sole production caller (app-server.mjs, via ensureBrokerSession) passed no killProcess. It deleted the broker's pid, log and state files anyway, so the survivor became invisible to every later reaper — including session-lifecycle-hook.mjs, which finds brokers through the state file this path had just cleared. Note that hook already passes killProcess: terminateProcessTree: same helper, one call site wired, the other not.
Observed live, unprompted, mid-investigation: four brokers alive for a single cwd while broker.json named one. The session then ended, the SessionEnd hook reaped only the named broker, and the other three stayed up with no state file at all.
ensureBrokerSession now defaults killProcess to terminateProcessTree on both teardown paths — replacing a stale broker, and cleaning up one we just spawned that never became ready.
Probe change. The readiness check that declares a broker stale now retries at 1s after the 150 ms attempt. A healthy broker answers the first probe immediately, so the retry only costs time when the broker is already in trouble — and without it a merely busy broker on a loaded host gets replaced for missing 150 ms, which is how a stranded broker gets created in the first place.
Tests (tests/broker-idle.test.mjs, three, all spawning a real broker over the fake-codex fixture):
- a broker nobody connects to exits on its own — waits on the pid file, never on the endpoint, since probing the endpoint would connect and exercise the other path
- replacing a stale broker kills the process it replaces
- a connected client holds the broker open, and releases it on disconnect
Each was checked by breaking the line it protects and confirming that test — and only that test — fails. The idle timeout is overridable through CODEX_COMPANION_BROKER_IDLE_MS so the tests can watch a real broker exit; 30 minutes is the shipped value.
Full suite on Windows: 116 tests, 107 pass, 9 fail — the 9 are pre-existing and unrelated (platform-specific: unix sockets, temp-dir layout, transfer/native-import).
Both findings on this PR are fixed.
Clear broker state on idle self-shutdown — real, and a regression this PR introduced rather than a pre-existing one: shutdown() never cleared broker.json, which was harmless while a broker only exited on an explicit shutdown or a signal. The idle timeout makes self-exit routine, so the stale record became routine too. e2dabb1 clears it on idle exit, matched on the endpoint rather than the pid — by the time an idle broker exits a replacement may already own the cwd, and pids get recycled. Two tests: it clears its own record, and it leaves a replacement's alone.
Validate stale broker pid before killing (P1) — also real, and the more serious of the two. Fixed in 0073980. The broker's OS process start time is recorded at spawn and must still match before anything is killed; unverifiable identity skips the kill and only clears the stale files, while a live-but-unreachable broker is still killed, which is what the kill was added for.
Two things that came out of fixing it, both worth flagging:
session-lifecycle-hook.mjskilled by recorded pid with no check at all, so the same defect survived on a path your comment did not cover and the first fix did not reach. Both call sites now share the check.- The start-time probe shells out, and
runCommandhad no timeout option at all, so on Windows a wedged PowerShell (~228 ms typical) would have hungensureBrokerSessionand therefore every/codex:command indefinitely. It is bounded at 2 s now; a timeout is simply an unverifiable identity and takes the same path.
Known residual, recorded at the call site rather than papered over: macOS ps -o lstart= has only second granularity, so a pid recycled inside the same second still verifies. Windows Ticks and Linux /proc jiffies do not have that problem, and no portable finer field exists.
The finding on 0073980 — the freshly-spawned broker being killed by pid without verifying it — is real and fixed in 125b019. (The branch was rebased onto the updated #577 head, so the shas moved.)
You were right that this is a separate path from the stale-state check, and I had missed it: 0073980 said "both teardown paths" and meant the stale record plus session-lifecycle-hook.mjs. This spawn-failure path is a third one, and it was the only one still killing an unverified pid.
Both halves of your premise check out. waitForBrokerEndpoint (lib/broker-lifecycle.mjs:29) polls the socket and never watches the child, so a broker that dies at startup — codex app-server failing to launch does exactly this — still costs the full 2 s before teardown fires, and node reaps the child in the meantime. The pid is free for essentially that whole window.
The fix skips the kill unless node still holds the child open:
const childStillRunning = child.exitCode === null && child.signalCode === null;
I used this rather than re-reading the start time, for two reasons. It is strictly stronger — while exitCode is null the process has not been reaped, so the pid cannot have been reassigned — and it avoids a second synchronous powershell.exe probe on a path that is already at its timeout. I checked that exitCode is observable on a detached: true + unref() child; unref() only stops the handle from holding the loop open, the exit event still lands.
The trade-off, stated plainly: if the child is already gone, anything it managed to spawn underneath is not reaped either. Leaking an orphan beats killing a recycled pid, so that is the side I took.
tests/broker-idle.test.mjs gains a case that spawns a script which exits immediately and asserts killProcess is never called. Reverting the guard makes it fail (a reaped pid was killed), so it holds the line rather than just exercising it.
Two adjacent things I noticed while verifying, neither addressed here — say the word if you want either split out:
readProcessStartTimeatlib/broker-lifecycle.mjs:233runs a synchronousspawnSync("powershell.exe", …)on every broker spawn, before the endpoint wait. That is a few hundred ms added to every cold start, introduced by this PR.- If that probe races the child's death,
processStartTimeis recorded asnull, andbrokerProcessMatchesRecordedStartthen returns false permanently — so the stale teardown would never be able to kill that broker.
The entry-point guard finding on session-lifecycle-hook.mjs is real and fixed in 7f962cd. It is a defect this PR introduced — making the hook importable is what put main() behind a guard in the first place — so it belongs here.
I reproduced the mechanism directly rather than reasoning about it. A probe script run through a directory junction:
--- direct ---
argv[1] : ...\real\probe.mjs
meta.url : ...\real\probe.mjs
guard : true
--- via junction ---
argv[1] : ...\link\probe.mjs
meta.url : ...\real\probe.mjs
guard : false
So process.argv[1] is resolved to an absolute path — which is why the existing hooks.json test passes despite spelling the path with forward slashes — but never through symlinks, while import.meta.url always is. Your description of the consequence is right and it is the bad kind: the hook exits 0 having done nothing, which is indistinguishable from a hook with nothing to do. The session env stays unset and no broker or job is ever reaped, with nothing logged.
The fix compares real paths and falls back to the literal comparison if either path is unreadable:
function invokedAsEntryPoint() {
try {
return fs.realpathSync(process.argv[1] ?? "") === fs.realpathSync(fileURLToPath(import.meta.url));
} catch {
return process.argv[1] === fileURLToPath(import.meta.url);
}
}
import.meta.main would be the one-liner, but it lands in Node 24 and this package declares >=18.18.0, so it is not available.
tests/broker-idle.test.mjs gains a case that links the scripts directory and invokes the hook through the link. Restoring the old guard makes it fail (the hook did not run through the symlink), so it holds the line. The link is created with fs.symlinkSync(target, link, "junction"), which gives a junction on Windows without needing elevation and a plain symlink elsewhere; it is deliberately kept outside the suite's temp-dir reaper, since that reaper deletes recursively and a link pointing at the real scripts directory is not something to hand a recursive delete.
I checked for the same pattern elsewhere in the repo — this is the only entry-point guard; stop-review-gate-hook.mjs has none. Suite: same 9 pre-existing failures before and after, none in these paths.
Cross-linking #566, which overlaps this PR on two exact lines. Flagging it here so triage does not have to reconstruct the choice.
Where they collide. Both rewrite ensureBrokerSession's two killProcess: options.killProcess ?? null teardown arguments in broker-lifecycle.mjs. Whichever lands first conflicts the other; both report mergeable today only because that is measured against main, not against each other.
Where they differ.
#566 (1b3264f) |
this PR (7f962cd) |
|
|---|---|---|
| stale-replacement teardown | ?? terminateProcessTree |
kills only if the recorded pid's start time still matches |
| spawn-timeout teardown | ?? terminateProcessTree |
kills only if the child is still running |
teardownBrokerSession default |
defaulted to terminateProcessTree |
unchanged |
| idle timeout | — | exits after 30 min at zero connected sockets |
The identity check is the one substantive disagreement. broker.json can name a pid that has since died and had its number reused; #566 signals it unconditionally, so that teardown path can tree-kill an unrelated process. This PR reads the pid's start time (/proc/<pid>/stat field 22 on Linux, ps -o lstart= on macOS, Get-Process .StartTime on Windows) and skips the kill when it does not match what was recorded — which is why the argument here is brokerPidVerified ? … : null rather than a plain default. The macOS path is second-resolution, so a same-pid same-second replacement remains outside what it can distinguish.
It runs the other way on one point. #566 defaults teardownBrokerSession itself, which covers every caller including ones neither PR knows about. This PR only fixes the two call sites that leak today, so that gap stays open here.
Resolution, whichever suits you:
- take #566 first — I rebase on top, drop the two overlapping lines, keep the idle timeout and the identity check;
- take this one — I open a one-line follow-up moving #566's
teardownBrokerSessiondefault in, credited to @srdrkr; - I fold both into this PR now, if one diff is easier to review than two.
No preference between them; flagging the fork rather than assuming it.
Separately: #563 touches the same files with a much larger ownership-registry design. If that is the intended direction, both this and #566 are moot and I am happy to close.