codex-plugin-cc icon indicating copy to clipboard operation
codex-plugin-cc copied to clipboard

state.json job index: unguarded read-modify-write race loses concurrent jobs and deletes their artifacts

Open piero-dev25 opened this issue 4 months ago • 5 comments

Summary

scripts/lib/state.mjs persists the per-workspace job index (state.json) with an unguarded read-modify-write (loadState → mutate → fs.writeFileSync, no lock, no atomic rename, no compare-and-swap). When two or more companion invocations register or update jobs on the same workspace root concurrently, the last writer wins and every other writer's job entry is silently dropped from the index.

Because saveState also treats "job missing from the retained list" as "job pruned" (state.mjs ~lines 105–112), the winning writer then deletes the losing jobs' .json payload and .log files via removeJobFile/removeFileIfExists — so the lost work isn't just unindexed, its artifacts are destroyed.

Downstream, /codex:status, /codex:result, and /codex:cancel resolve jobs exclusively through this index (job-control.mjs, matchJobReference), so a completed --background task can become permanently unretrievable through the documented interface with no error surfaced anywhere.

Reproduction (plugin v1.0.6, codex-cli 0.143.0, macOS, Node 22)

// upsert-one.mjs — calls the plugin's real upsertJob
import { upsertJob } from "<plugin-root>/scripts/lib/state.mjs";
const [cwd, id] = process.argv.slice(2);
upsertJob(cwd, { id, status: "running", kind: "repro" });
mkdir -p /tmp/race/ws && cd /tmp/race/ws && git init -q
export CLAUDE_PLUGIN_DATA=/tmp/race/plugin-data

# Sequential — control
for i in $(seq 1 20); do node upsert-one.mjs "$PWD" "seq-$i"; done
# → listJobs(): 20 of 20 survive

rm -rf /tmp/race/plugin-data

# Concurrent
for i in $(seq 1 20); do node upsert-one.mjs "$PWD" "con-$i" & done; wait
# → listJobs(): 1 of 20 survives

Observed across three independent runs on this machine: sequential = 20/20; concurrent = 1/20, 1/20, 1/20.

Impact

  • Two Claude Code sessions (or one session plus a background job) sharing a checkout and using /codex:rescue --background, /codex:review --background, or any concurrent task invocations can silently lose each other's job registrations.
  • Status transitions racing against registrations have the same window: a runTrackedJob completion update can be overwritten by an unrelated writer, or vice versa.
  • The pruning side effect deletes the losing job's payload/log files, so the result is unrecoverable even by hand.
  • Nothing fails loudly — the caller sees No job found for <id> later, or simply never finds the job.

Suggested direction

Any of these would close the window:

  1. Atomic replace: write to state.json.tmp.<pid> then fs.renameSync — removes torn reads, though not lost updates.
  2. Advisory lock (e.g. mkdir-based or proper-lockfile) around updateState's load→mutate→save critical section — removes lost updates.
  3. Treat the per-job jobs/<id>.json files as the source of truth and rebuild the index from a directory scan, reserving state.json for config only — sidesteps the shared-file contention entirely and makes the pruning deletion safe.

Found during an automated concurrency audit of the plugin before adopting it for multi-session workflows. Happy to provide the full harness or re-run against a patched branch.

piero-dev25 avatar Jul 08 '26 19:07 piero-dev25

I opened #460 to fix this. The CI workflow is currently waiting on maintainer approval to run (first-time contributor). Could a maintainer approve the workflow run so the tests can execute? Happy to address any feedback.

hsms4710-pixel avatar Jul 14 '26 03:07 hsms4710-pixel

Two natural (non-synthetic) reproductions of this on plugin 1.0.6 (codex-cli 0.144.5, macOS, single ordinary dispatches — no concurrent hammering needed), plus a downstream consequence not yet noted here.

Repro A — foreground task, then a second companion invocation in the same second. Job completed per its own record, but the index kept the pre-completion snapshot:

  • jobs/task-mrpfzae6-39uev8.json: status: "completed", completedAt: 21:20:51.653Z
  • state.json: status: "running", phase: "finalizing", entry updatedAt: 21:20:51.637Z — while the file's mtime is 21:20:51.733, i.e. state.json was written after completion yet contains pre-completion content. Classic lost update.

Repro B — a single task --background --fresh --prompt-file … --json, nothing else running. The turn finished in 13s (Turn completed + Final output in the log, job file completed), but state.json again stayed running/finalizing permanently. Effects observed:

  • status <jobId> --wait --timeout-ms 240000 burned the full 240s on a job that was done in 13s.
  • result <jobId> threw No job found for "<jobId>" — not the intended "still running" message. Mechanism: resolveResultJob (lib/job-control.mjs:256-263) first calls matchJobReference with the finished-statuses predicate; for an explicit reference that doesn't survive the filter, matchJobReference throws at :210 before the active branch at :269 can run. With the clobbered index, the "still running, try again" path is unreachable for a referenced job — the user gets a not-found error for work that succeeded.
  • The stale entry also retains a pid, so the SessionEnd hook's terminateProcessTree() later targets a long-dead (recyclable) pid.

So the blast radius includes the serial single-job case, not only concurrent dispatches — plausibly via a status/poll invocation racing the worker's final upsert. Job files were the reliable source of truth in both cases; everything routed through state.json (status --wait, result, the Stop/SessionEnd hooks) misreported.

hahuyhoang411 avatar Jul 17 '26 22:07 hahuyhoang411

Reproduced on plugin 1.0.6, codex-cli 0.159.2, Windows 11.

Two Claude Code sessions in the same repo (distinct CODEX_COMPANION_SESSION_ID), each running task --json --fresh at the same moment, then task --json --resume-last later. After the concurrent writes one session's job record is gone from state.json, and its resume fails with:

No previous Codex task thread was found for this repository.

The Codex thread itself is intact: resuming it by id through runAppServerTurn(cwd, { resumeThreadId }) from scripts/lib/codex.mjs works and the thread still has its context. So only the pointer in the shared index is lost. The lock + atomic write in #460 would cover this case.

osamamnagiub avatar Sep 30 '26 11:09 osamamnagiub

Reproduced on Windows 11 with plugin 1.0.3: six background tasks launched at once in one workspace all completed (their logs end in the result), but status --all listed only two, one still queued. The window is wide on Windows because every load/save resolves the workspace through git (~1 s per call). Wrapping updateState in a cross-process lock (an exclusive mkdirSync of state.json.lock, ~100 ms jittered retry, 30 s wait, a lock older than 60 s treated as stale) fixed it locally: the same six-job test then listed all six as completed.

Asromer-biology avatar Oct 02 '26 12:10 Asromer-biology

Update 2: harness contract completed after a second review of it. Exit codes: 0 = reproduced; 1 = not reproduced (both participants ran, timestamps show A loaded < B started < A released, B's request file, log and index entry intact, the real codex-companion status <B> exited 0, and the stress part lost nothing); 2 = inconclusive (the plugin module cannot be imported, an API is missing, a participant failed, ordering or CLI result not as required). Never read 2 as "fixed".

Deterministic multi-process repro against the released 1.0.6 scripts/lib/state.mjs (Node 22, Linux). Writer A calls the real updateState() and is parked (barrier inside mutate) between loadState() and saveState(). Only after A records that it has loaded does writer B, a second real process, record started and do what enqueueBackgroundTask() does for a new job (writeJobFile() then upsertJob()). A is released; saveState reloads the job list, sees B's job missing from A's older snapshot, deletes B's job file and log, and overwrites the index without B. Isolated store via CLAUDE_PLUGIN_DATA.

1.0.6 (exit 0):

plugin: 1.0.6  node v22.23.3
before:      A {"file":true,"log":false,"indexed":true}
B published: B {"file":true,"log":true,"indexed":true}
after A:     B {"file":false,"log":false,"indexed":false}  A {"file":true,"log":false,"indexed":true}
real CLI: codex-companion status task-bbbb-B -> exit 1: No job found for "task-bbbb-B". Run /codex:status to list known jobs.
part 1: B's request file, log and/or index entry was destroyed by an unrelated writer
part 2 stress: 40 jobs enqueued while another writer upserts its own progress 400 times; request files lost: 17, logs lost: 17, missing from index: 21
REPRODUCED

PR #460's state.mjs in a 1.0.6 tree (exit 1; B waits for A's lock, nothing lost):

plugin: 1.0.6  node v22.23.3
before:      A {"file":true,"log":false,"indexed":true}
B published: B {"file":true,"log":true,"indexed":true}
after A:     B {"file":true,"log":true,"indexed":true}  A {"file":true,"log":false,"indexed":true}
real CLI: codex-companion status task-bbbb-B -> exit 0: {
part 1: B survived in full
part 2 stress: 40 jobs enqueued while another writer upserts its own progress 400 times; request files lost: 0, logs lost: 0, missing from index: 0
NOT REPRODUCED

PR #689's state.mjs (exit 2): INCONCLUSIVE: state.mjs lacks updateState -- this harness cannot drive it -- it removes the updateState export; no claim either way. An unimportable tree also exits 2: INCONCLUSIVE: cannot import candidates/plugin-broken/scripts/lib/state.mjs: Unexpected token ';'

repro-458.mjs (node repro-458.mjs <plugin-root>)
// Repro for openai/codex-plugin-cc#458: unlocked read-modify-write in lib/state.mjs loses another
// writer's job file and index entry.  Uses the given plugin tree's real state.mjs, an isolated
// CLAUDE_PLUGIN_DATA under a scratch dir (never a real store), and real OS processes.
//
//   node repro-458.mjs <plugin-root>      e.g. ~/.claude/plugins/cache/openai-codex/codex/1.0.6
//
// Exit 0 = REPRODUCED  (both participants ran, the ordering A loaded < B started < A released was observed
//                       by timestamps, and B's request
//                       file, log or index entry is gone -- or the stress part lost one);
// Exit 1 = NOT REPRODUCED (both participants ran, the same ordering was observed, B survived in full, the
//                       real `codex-companion status <B>` exited 0, and the stress part lost nothing);
// Exit 2 = INCONCLUSIVE (a participant failed, the plugin lacks the API this harness drives -- updateState,
//                       upsertJob, writeJobFile, listJobs, resolve*File -- or the ordering was not observed).
//                       Never read exit 2 as "fixed".
//
// Part 1 (deterministic): process A is a writer going through updateState() -- the primitive upsertJob and
//   setConfig use, and what the detached worker's progress updates and the lifecycle hook call.  A is parked
//   between loadState() and saveState() (a barrier inside the mutate callback is where an OS preemption
//   lands) and records `loaded`.  Only then does process B record `started` and perform the SAME two calls enqueueBackgroundTask()
//   makes for a new job: writeJobFile() then upsertJob().  A records `released` and saves when B finishes,
//   or after 2 s (a fixed plugin makes B wait for A's lock).
// Part 2 (stress, no barrier): the same two roles in tight loops, 40 jobs + 1 <= MAX_JOBS (50), so retention
//   pruning cannot explain a loss.
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";

const [, , pluginRoot, role, ...rest] = process.argv;
if (!pluginRoot) { console.error("usage: node repro-458.mjs <plugin-root>"); process.exit(2); }
const SELF = new URL(import.meta.url).pathname;
const NEEDED = ["updateState", "upsertJob", "writeJobFile", "listJobs", "resolveJobFile", "resolveJobLogFile"];
let state;
try { state = await import(pathToFileURL(path.join(pluginRoot, "scripts", "lib", "state.mjs")).href); }
catch (e) { console.log(`INCONCLUSIVE: cannot import ${pluginRoot}/scripts/lib/state.mjs: ${e.message.split("\n")[0]}`); process.exit(2); }
const missing = NEEDED.filter((n) => typeof state[n] !== "function");
if (missing.length) { console.log(`INCONCLUSIVE: state.mjs lacks ${missing.join(", ")} -- this harness cannot drive it`); process.exit(2); }
const ws = () => process.env.REPRO_WS;
const record = (id) => ({ id, status: "queued", logFile: state.resolveJobLogFile(ws(), id), request: { prompt: `request for ${id}` } });
const present = (id) => ({ file: fs.existsSync(state.resolveJobFile(ws(), id)), log: fs.existsSync(state.resolveJobLogFile(ws(), id)), indexed: state.listJobs(ws()).some((j) => j.id === id) });
const publish = (id) => {                 // enqueueBackgroundTask(): log, then request file, then index
  fs.writeFileSync(state.resolveJobLogFile(ws(), id), "Queued for background execution.\n");
  state.writeJobFile(ws(), id, record(id));
  state.upsertJob(ws(), record(id));
};

if (role === "A") {
  const [loadedFile, goFile, idA] = rest;
  state.updateState(ws(), (s) => {
    fs.writeFileSync(loadedFile, String(Date.now()));  // snapshot taken: B is not in it
    const spin = Date.now();
    while (!fs.existsSync(goFile) && Date.now() - spin < 2000);
    fs.writeFileSync(`${goFile}.released`, String(Date.now()));
    const i = s.jobs.findIndex((j) => j.id === idA);  // upsertJob's own mutation for job A
    s.jobs[i] = { ...s.jobs[i], phase: "running", updatedAt: new Date().toISOString() };
  });
  process.exit(0);
}
if (role === "B") {
  const [goFile, idB] = rest;
  fs.writeFileSync(`${goFile}.started`, String(Date.now()));
  publish(idB);
  console.log("B published: B", JSON.stringify(present(idB)));
  fs.writeFileSync(goFile, "go");
  process.exit(0);
}
if (role === "stressA") {
  const [idA, n] = rest;
  for (let i = 0; i < +n; i++) state.upsertJob(ws(), { id: idA, phase: `p${i}` });
  process.exit(0);
}
if (role === "stressB") {
  const [prefix, n] = rest;
  for (let i = 0; i < +n; i++) publish(`${prefix}-${i}`);
  process.exit(0);
}

// ---- driver ----
const exited = (child) => new Promise((r) => { child.on("exit", (code) => r(code)); child.on("error", () => r(-1)); });
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const scratch = fs.mkdtempSync(path.join(process.env.REPRO_SCRATCH ?? os.tmpdir(), "repro458-"));
const env = { ...process.env, CLAUDE_PLUGIN_DATA: path.join(scratch, "plugin-data"), REPRO_WS: path.join(scratch, "workspace") };
fs.mkdirSync(env.REPRO_WS, { recursive: true });
Object.assign(process.env, env);
const child = (...args) => spawn(process.execPath, [SELF, pluginRoot, ...args], { env, stdio: "inherit" });
const finish = (code, msg) => { console.log(msg); fs.rmSync(scratch, { recursive: true, force: true }); process.exit(code); };

console.log(`plugin: ${JSON.parse(fs.readFileSync(path.join(pluginRoot, ".claude-plugin", "plugin.json"))).version}  node ${process.version}`);
const idA = "task-aaaa-A", idB = "task-bbbb-B";
const loaded = path.join(scratch, "loaded"), go = path.join(scratch, "go");
state.writeJobFile(env.REPRO_WS, idA, record(idA));
state.upsertJob(env.REPRO_WS, record(idA));
console.log("before:      A", JSON.stringify(present(idA)));

const a = child("A", loaded, go, idA), aExit = exited(a);
for (let i = 0; i < 100 && !fs.existsSync(loaded); i++) await sleep(50);
if (!fs.existsSync(loaded)) { a.kill(); finish(2, "INCONCLUSIVE: writer A never reached its load/save window (ordering not observed)"); }
const b = child("B", go, idB);
const [bCode, aCode] = [await exited(b), await aExit];
if (aCode !== 0 || bCode !== 0) finish(2, `INCONCLUSIVE: participant failed (A exit ${aCode}, B exit ${bCode})`);
const [tLoaded, tStarted, tReleased] = [loaded, `${go}.started`, `${go}.released`].map((f) => (fs.existsSync(f) ? +fs.readFileSync(f, "utf8") : NaN));
if (!(tLoaded <= tStarted && tStarted <= tReleased)) finish(2, `INCONCLUSIVE: ordering A loaded < B started < A released not observed (${tLoaded}, ${tStarted}, ${tReleased})`);
const after = present(idB);
console.log("after A:     B", JSON.stringify(after), " A", JSON.stringify(present(idA)));
const lost1 = !(after.file && after.log && after.indexed);
const cli = await new Promise((r) => {
  const c = spawn(process.execPath, [path.join(pluginRoot, "scripts", "codex-companion.mjs"), "status", idB, "--json", "--cwd", env.REPRO_WS], { env });
  let out = ""; c.stdout.on("data", (d) => (out += d)); c.stderr.on("data", (d) => (out += d)); c.on("exit", (code) => r({ code, out }));
});
console.log(`real CLI: codex-companion status ${idB} -> exit ${cli.code}: ${cli.out.trim().split("\n")[0].slice(0, 160)}`);
if (!lost1 && cli.code !== 0) finish(2, `INCONCLUSIVE: B is intact but the real CLI status exited ${cli.code}`);
console.log(lost1 ? "part 1: B's request file, log and/or index entry was destroyed by an unrelated writer" : "part 1: B survived in full");

const N = 40;
fs.rmSync(path.join(scratch, "plugin-data"), { recursive: true, force: true });
state.writeJobFile(env.REPRO_WS, idA, record(idA)); state.upsertJob(env.REPRO_WS, record(idA));
const [pa, pb] = [child("stressA", idA, "400"), child("stressB", "task-s", String(N))];
const [paCode, pbCode] = await Promise.all([exited(pa), exited(pb)]);
if (paCode !== 0 || pbCode !== 0) finish(2, `INCONCLUSIVE: stress participant failed (A exit ${paCode}, B exit ${pbCode})`);
let lostFile = 0, lostIdx = 0, lostLog = 0;
const idx = new Set(state.listJobs(env.REPRO_WS).map((j) => j.id));
for (let i = 0; i < N; i++) {
  const id = `task-s-${i}`;
  if (!fs.existsSync(state.resolveJobFile(env.REPRO_WS, id))) lostFile++;
  if (!fs.existsSync(state.resolveJobLogFile(env.REPRO_WS, id))) lostLog++;
  if (!idx.has(id)) lostIdx++;
}
console.log(`part 2 stress: ${N} jobs enqueued while another writer upserts its own progress 400 times; request files lost: ${lostFile}, logs lost: ${lostLog}, missing from index: ${lostIdx}`);
const reproduced = lost1 || lostFile + lostLog + lostIdx > 0;
finish(reproduced ? 0 : 1, reproduced ? "REPRODUCED" : "NOT REPRODUCED");

Drak0 avatar Oct 09 '26 05:10 Drak0