Jobs killed by host timeouts stay "running" forever (no pid liveness check); concurrent state writers can wipe all job state and silently disable stopReviewGate
Repo: github.com/openai/codex-plugin-cc Plugin version: 1.0.6 (latest; main = db52e28 at time of writing — bug present there) Environment: Claude Code 2.1.209 (desktop app), macOS (darwin 25.5.0), node 26.5.0, shared session runtime (unix-socket broker)
Summary
Two consecutive long-running task jobs (adversarial reviews of a markdown spec, 15–25 min workloads) died silently while codex-companion.mjs status --json reported them as running indefinitely. Investigation shows a cluster of related defects:
- No pid-liveness check anywhere.
runTrackedJob(lib/tracked-jobs.mjs) recordspid: process.pidand only writes a terminal status when its runner promise settles. A SIGKILLed job process never runs the catch handler, sostate.jsonkeepsstatus: "running"forever.buildStatusSnapshot(lib/job-control.mjs) trusts that field blindly — noprocess.kill(pid, 0), no heartbeat, no staleness cutoff. - Foreground execution inside the host's Bash tool guarantees death for long jobs. The rescue agent doc says "prefer foreground for a small, clearly bounded request", but in practice the model launches 20-minute reviews foreground. Claude Code's Bash tool kills the process tree at its timeout (default 120 s, max 600 s). Both observed failures line up with those timeouts to the second (details below).
- The shared broker can be spawned as a descendant of a job's Bash process tree.
ensureBrokerSessionspawns the brokerdetached: truefrom whichever companion invocation first needs it.detachedprotects against process-group kills, but Claude Code's tree-kill walks children by ppid while the parent is still alive — so killing the foreground job also killed the shared broker and itscodex app-serverchild, destroying every thread in the runtime (observed: job 1 took down the whole runtime; cancel later reportedthread not found). captureTurnawaits a promise only aturn/completednotification can resolve (lib/codex.mjs,state.completion). It never races the client'sexitPromise. When the broker socket closes mid-turn, pending requests are rejected (handleExit), but a worker sitting incaptureTurnjust loses its last event-loop handle and node exits silently with code 0 — no catch runs, job stays "running". This bites--backgroundworkers too, whenever the broker dies.- Turns keep running server-side with zero listeners, and the result is discarded. The broker's
routeNotificationdrops notifications when no owner socket exists. Job 2's review kept running for 8 more minutes after its client died and completed successfully (task_completein the rollout at 22:12:56Z); the finished review went nowhere while status still said "running". It was recoverable only by hand from~/.codex/sessions/.../rollout-*.jsonl. - Minor:
ensureBrokerSession's readiness probe gives an existing broker only 150 ms to accept a connection before tearing it down and replacing it. A busy broker (large JSONL payloads stall the event loop) can be misjudged as dead. - Separate high-severity hazard found while testing: concurrent state writers can wipe ALL job state, logs, and the stopReviewGate config. The chain (all upstream code):
saveStatewritesstate.jsonwith a plain non-atomicfs.writeFileSync; a concurrentloadStatecan read the file mid-write,JSON.parsethrows, and the catch returnsdefaultState()(empty jobs,stopReviewGate: false); if that reader is a writer (upsertJob→updateStateis an unlocked read-modify-write), it then saves the near-empty state — andsaveState's pruning loop deletes the job file and log file of every job absent from the state being saved. Net effect: full history wipe, all job logs deleted, review gate silently disabled. We reproduced this with 6 concurrentupsertJobwriters (it destroyed the real state for this workspace, including the evidence logs for the two jobs above — their content survives in this report and in the~/.codex/sessionsrollouts). Real-world trigger: any two Claude sessions sharing a workspace whose stop-gate hooks or job workers write state simultaneously. Fixes: temp-file +renameSyncinsaveState(atomic replace), retry/fail-closed instead ofdefaultState()on parse errors of an existing file, and a lock (or at least last-writer-wins semantics that never delete files based on a possibly-stale view).
Evidence (timestamps UTC)
Job 1 — task-mro16p6v-nx7uod (foreground CLI, pid 20782)
- 21:38:33 job starts (job log has no "Queued for background execution" line → foreground path).
- 21:40:36 job log AND the thread rollout (
rollout-...019f6cdd-f82c....jsonl) stop mid-turn within 113 ms of each other; no error, no task_complete. 21:38:33 + ~120 s ≈ default Bash-tool timeout; CLI + broker + app-server died together (tree kill; broker was a descendant of this CLI's Bash call — see §3). - 21:42:20 the next companion invocation (stop-gate hook) finds the broker endpoint dead, tears down the remains, spawns a fresh broker (pid 23179, sessionDir mtime 17:42 local) — works fine.
- 21:55:34
/codex:cancel:Codex turn interrupt failed: thread not found: 019f6cdd-...— the replacement app-server never had the thread. Job had shownrunningthe whole time;ps -p 20782empty.
Job 2 — task-mro1t9r6-xe003h (foreground CLI, pid 30867)
- 21:56:06 job starts (foreground, same signature), thread 019f6cee created in the NEW broker's app-server (pid 23182).
- 22:04:48.9 last job-log line ("Command completed").
- Rollout shows the thread then performed a ~100 s context compaction (22:06:30) and kept working; events from 22:06:32 onward never reached the job log → client disconnected in [22:04:49, 22:06:32]. 21:56:06 + 600 s = 22:06:06, dead-center in that window = max Bash-tool timeout. Broker survived this kill (it was spawned by the 21:42 stop-gate process and had been reparented to pid 1 — out of the killed tree).
- 22:12:56 rollout records
task_completewith the full 23.9 KB review — delivered to nobody. - 22:17:20
/codex:cancel:Codex turn interrupt failed: no active turn to interrupt(thread known, turn already over). Status showedrunningfor the whole 21 minutes;ps -p 30867empty.
No crash reports (~/Library/Logs/DiagnosticReports), no OOM/jetsam entries — consistent with external SIGKILL of the process tree, not a crash.
Suggested fixes
- Liveness reconciliation in status paths: when a job is
queued/runningandprocess.kill(job.pid, 0)throwsESRCH, mark itfailedwith a clear message. Two TOCTOU details matter: (a) re-check the job is still active inside theupdateStatemutation (a job can complete between the status snapshot and the write — a naive patch overwritescompletedwithfailed); (b) if the per-job file already holds a terminal status (process died betweenwriteJobFileandupsertJobinrunTrackedJob), adopt that status instead offailed. (~60 lines in lib/job-control.mjs; we've verified both cases locally.) - Refuse or warn on foreground for long-lived work, or make
--backgroundthe default fortask/reviews when invoked from a hook/agent context. The CLI cannot survive the host Bash timeout; the docs should say so explicitly. - Spawn the broker from a stable parent (or double-fork / re-spawn via an intermediate that exits immediately) so it is reparented to pid 1 before the job's Bash tree can be killed.
- Race
captureTurnagainstclient.exitPromiseso a socket close fails the job (status: failed, "runtime connection lost") instead of a silent code-0 exit. - Interrupt ownerless turns or persist their result: when the owning socket closes mid-turn, either
turn/interruptor capture the completion server-side and write it into the job record. Job 2's completed review should not have been lost. - Raise the broker readiness probe timeout above 150 ms.
Local workaround applied (for other affected users)
- Always launch long codex tasks with
--background(the detached worker is immune to Bash-tool timeouts; it remains vulnerable to defect 4 only if the broker itself dies). - Patched into the local plugin cache (overwritten on plugin update):
scripts/lib/job-control.mjs:reconcileStaleJobs()in the status paths — an active job with a dead pid is markedfailed(or adopts the terminal status already in its job file); the still-active check re-runs inside the state mutation to avoid overwriting a job that completes concurrently; plus a self-heal pass that repairs any reconciliation write that raced a completion.scripts/lib/state.mjs:saveStateandwriteJobFilewrite via temp file +renameSync(atomic; readers never see torn JSON); parse failures are retried, then writers fail closed —updateStatethrows rather than proceed from an empty default whenstate.jsonexists but cannot be parsed (readers still degrade gracefully);updateStateserializes read-modify-write behind an advisory lock dir (mkdir-based). Reaping of dead holders is liveness-based and non-displacing: a lock is reap-eligible only if its owner pid is dead (after a 500 ms grace) or it exceeds a 60 s hard cap; the reap is claimed by creating areap-claimfile inside the lock dir withO_EXCL— exactly one reaper can win, the claim is pinned to that dir incarnation, the owner record is re-verified in place before deletion, and a mistaken claim is undone by unlinking (a live lock never leaves the namespace — a rename-based steal was tried and rejected because the displaced window let a third waiter acquire and forced the real holder to abort). Abandoned claims are recovered only when the claim's reaper pid is DEAD (a dead reaper can never wake and race the recovery; a live-but-stalled reaper defers to the 60 s hard cap), and the claim winner re-verifies both the owner record and its own claim record in place immediately before the destructive remove. On contention past the 10 s acquisition deadline the writer throws instead of writing unlocked; release is owner-token-guarded; ownership is re-verified at commit time, aborting rather than overlapping if the lock was somehow lost. The unlocked path remains only for filesystem errors (e.g. EACCES), where the state write itself would fail anyway.scripts/session-lifecycle-hook.mjs:cleanupSessionJobsremoves the session's jobs through the lockedupdateStateinstead of saving a snapshot read earlier (a stale-snapshot save deletes other sessions' job files viasaveStatepruning).- Verified: dead-pid phantom → failed; running-in-state/completed-in-file race → completed preserved; clobbered-to-failed entry → healed back to completed; writer against corrupted
state.json→ throws, corrupt file and all job/log files untouched; reader against corrupted state → renders, deletes nothing; lock owned by a dead pid → reaped and acquired in ~640 ms; abandoned claim from a dead reaper → recovered and acquired in ~1.3 s; claim held by a live (stalled) reaper → never recovered, writer fails closed at 10 s; lock owned by a LIVE process → never stolen, writer throws at the 10 s deadline instead of writing unlocked; lock lost mid-update (owner record replaced during the mutation) → commit aborts with the state file unchanged; reap-storm (a dead lock placed in front of 8 concurrent writers × 20 updates, 3 rounds) → every write landed, zero spurious lock-lost aborts, no leftovers; plain 8-writer hammer → no lost updates, no wipe, config preserved.
🤖 Generated with Claude Code
Another repro corroborating §2 (foreground Bash-timeout kill) and §5 (turn keeps running server-side; result is recoverable), from a delegation session.
A write-mode task job was launched foreground from an orchestrator's Bash call. The Bash call hit the host's 10-minute cap and was killed, but the job kept running server-side and nearly finished (it reached passing unit + integration tests). Its progressPreview.updatedAt then froze while status's elapsed kept advancing — at the ~1h mark the job had shown no updatedAt movement for ~51 minutes, yet still reported running. After a cancel, the working-tree artifacts left behind were healthy and fully reviewable/repairable.
Practical takeaway for consumers, on top of the fixes proposed here: after a host-timeout kill, it's worth not cancelling immediately — comparing status's updatedAt against elapsed distinguishes "still progressing server-side" from "stalled", and in the stalled-but-completed case the work can be salvaged from the working tree (or, as §5 notes, from the rollout).
Independent confirmation on Windows (plugin 1.0.6, codex-cli 0.146.0, node 24.x, win32) — with one consequence that deserves emphasis beyond stale status output: a dead job's record hard-blocks every subsequent task --resume-last in that workspace until you hand-edit state.json.
Incident timeline (from state.json + job log, UTC)
-
19:47:21— long-running backgroundtaskjobtask-msas9b5x-om02f4launched (--background, worker pid recorded). -
Worker logged normal progress for ~2.5 min, then died silently (log stops mid-turn; process gone; no terminal status ever written — same mechanism as this issue's defect 1).
-
Job record stays
status: "running"indefinitely. -
20:09:59,20:10:37,20:11:53— three consecutivetask --resume-lastattempts each failed instantly with:Task task-msas9b5x-om02f4 is still running. Use /codex:status before continuing it. -
Only recovery: manually editing the job's
statusto"failed"instate.json. After that, resume worked and the thread completed normally — proving the underlying Codex thread was fine all along; only the stale record was blocking it.
The throw comes from resolveLatestTrackedTaskThread (scripts/codex-companion.mjs, ~line 336–344): it rejects when any visible task job has status queued/running, with no pid-liveness check. The stop-review-gate hook additionally nags "Codex task … is still running" at every turn end for the phantom job.
Deterministic minimal repro (no crash needed, Windows)
Windows pids are always multiples of 4, so an odd pid can never exist:
- In a scratch workspace's state dir, write a
state.jsoncontaining one job:{"id":"task-dead","jobClass":"task","status":"running","pid":99999,"sessionId":"<your session id>","threadId":null}. - Run
node scripts/codex-companion.mjs task --resume-last --json(matchingCODEX_COMPANION_SESSION_ID). - Result:
Task task-dead is still running. Use /codex:status before continuing it.— permanently, on every retry. Verified on 1.0.6.
Fix sketch (tested locally)
In resolveLatestTrackedTaskThread, before throwing, verify the recorded worker is alive: process.kill(pid, 0) (treat EPERM as alive); for foreground jobs with pid == null, fall back to an updatedAt staleness cutoff (progress events bump it continuously during an active turn). If dead, mark the job failed via upsertJob and continue — the resume then correctly picks up the dead job's threadId as the resumable candidate. With this change the repro above resolves cleanly instead of wedging.
Also reproduces the Windows half of #478 (its Bug 2).
Confirming this on 1.0.6, macOS 15.7.7, Claude Code 2.1.236, from the operator side, and the mechanism you name matches exactly — no process.kill(pid, 0) anywhere, terminal status written only when the runner promise settles.
What it looks like in use: five non-terminal records with dead PIDs, the oldest lying there for two days, blocking twelve consecutive session-end attempts through the stop-review gate. /codex:cancel could not clear them (that part is #636/#684 — the commands were reading a different state root than the hook).
Evidence and the jq reconcile that cleared it:
Summary
state.json keeps job records at status: "running" (and phase: "investigating") with PIDs
that no longer exist. Nothing reconciles a record against the liveness of its process, so the
stop-review gate reads a non-terminal record and refuses to let the session end. /codex:cancel
cannot clear it, because of a separate state-directory issue filed as its own report.
Environment
openai-codexClaude Code plugin 1.0.6- Codex CLI 0.153.0, Claude Code 2.1.236, Node v26.8.1
- macOS 15.7.7 (Darwin 24.6.0)
- Stop-time review gate enabled (
config.stopReviewGate: true)
What was observed
~/.claude/plugins/data/codex-openai-codex/state/<workspace>/state.json held five non-terminal
records, every one of them with a dead PID (confirmed with ps -p):
| Job | Phase | PID | Started |
|---|---|---|---|
task-mtsc9wfb-2i1y6g |
investigating | 33227 | 2026-09-08 07:19 |
task-mts90r0u-patp6n |
investigating | 64937 | 2026-09-08 05:48 |
task-mts75p38-bzcmo4 |
running | 36975 | 2026-09-08 04:56 |
task-mtrlaazr-gomnha |
investigating | 30424 | 2026-09-07 18:43 |
task-mtq85c25-8c978y |
investigating | 75316 | 2026-09-06 19:48 |
The oldest had been claiming to run since the evening of 2026-09-06. The stop hook blocked twelve consecutive session-end attempts, each time printing:
Codex task task-mtrlaazr-gomnha is still running. Check /codex:status and use
/codex:cancel task-mtrlaazr-gomnha if you want to stop it before ending the session.
Steps to reproduce
- Enable the stop-time review gate.
- Start a Codex-backed job, then kill its process, or let a crash or machine sleep end it without a clean completion. A broker that outlives its session produces this too.
- Try to end the Claude Code session.
The gate blocks, naming a job whose PID is gone, and blocks again on every subsequent attempt.
Expected
Before a record is treated as blocking, its PID is checked. A record whose process is gone is
reconciled to a terminal state (failed) and does not block session end.
Actual
The record is trusted indefinitely. A dead job blocks every session end until the file is edited by hand.
Impact
The session cannot be ended through any supported route. /codex:cancel <id> reports
No job found for "<id>" for the exact ID the hook just printed. The only escape is editing
plugin state or disabling the gate.
Workaround
F=~/.claude/plugins/data/codex-openai-codex/state/<workspace>/state.json
cp "$F" "$F.bak" && jq '(.jobs[] | select(.status=="running")) |= (.status="failed" | .phase="done" | .pid=null)' "$F" > "$F.tmp" && mv "$F.tmp" "$F"
Note that phase: "investigating" records also need clearing; selecting only on
status == "running" happens to cover them because status and phase are tracked separately.
Suggested fix
Reconcile on read: when the hook or a command loads state.json, mark any non-terminal record
whose PID is not alive as failed, and persist that. A start-up sweep would also work. As a
belt-and-braces measure, a maximum job age after which a record is no longer allowed to block
would prevent a record from lying for two days as the oldest one here did.