Skip to content

Commit 926d0f0

Browse files
zknprclaude
andcommitted
fix(codex): preserve cancellation across concurrent pid persistence (PR openai#346 review P1)
updateState was an unlocked load/mutate/save, so a /codex:cancel completing in another companion process between the launcher's read and its post-spawn pid write could be clobbered, resurrecting a cancelled job with a live detached worker. Introduce an interprocess state lock (pre-populated candidate dir published by atomic rename, pid-liveness stale recovery, token-scoped release), make state.json and per-job writes atomic via same-dir tmp+rename, and route launch/cancel through a locked updateJobStores transaction covering both job stores. Cancellation now wins by invariant: proposals that do not preserve a recorded cancelled status are refused, pid commit rechecks terminal state under the lock, kills the fresh worker when cancellation won, and repairs a partial cancellation. Corrupt state now throws instead of silently resetting. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 5c788fb commit 926d0f0

8 files changed

Lines changed: 717 additions & 114 deletions

File tree

‎plugins/codex/scripts/codex-companion.mjs‎

Lines changed: 20 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
getConfig,
3232
listJobs,
3333
setConfig,
34+
updateJobStores,
3435
updateState,
3536
upsertJob,
3637
writeJobFile
@@ -65,6 +66,7 @@ import {
6566
renderTaskResult
6667
} from "./lib/render.mjs";
6768
import { buildTaskDispatchedStatusToken } from "./lib/task-status-token.mjs";
69+
import { commitSpawnedTaskWorker } from "./lib/task-launch-state.mjs";
6870

6971
const ROOT_DIR = path.resolve(fileURLToPath(new URL("..", import.meta.url)));
7072
const REVIEW_SCHEMA = path.join(ROOT_DIR, "schemas", "review-output.schema.json");
@@ -334,15 +336,6 @@ function isTerminalJobRecord(stateJob, storedJob = null) {
334336
return !isActiveJobStatus(stateJob?.status) || Boolean(storedJob && !isActiveJobStatus(storedJob.status));
335337
}
336338

337-
function resolveLaunchStatus(stateJob, storedJob = null, fallback = "queued") {
338-
for (const status of [stateJob?.status, storedJob?.status]) {
339-
if (status && !isActiveJobStatus(status)) {
340-
return status;
341-
}
342-
}
343-
return stateJob?.status ?? storedJob?.status ?? fallback;
344-
}
345-
346339
function getCurrentClaudeSessionId() {
347340
return process.env[SESSION_ID_ENV] ?? null;
348341
}
@@ -849,50 +842,6 @@ function markTaskLaunchFailed(workspaceRoot, jobId, errorMessage, fallbackLogFil
849842
return preservedJob;
850843
}
851844

852-
function persistSpawnedTaskWorkerPid(workspaceRoot, jobId, childPid) {
853-
let shouldKillWorker = false;
854-
let launchStatus = "queued";
855-
let updatedJob = null;
856-
857-
// PR #346 review: pid persistence must re-check cancellation inside the same
858-
// state read-modify-write that writes the pid. A cancel that already made the
859-
// job terminal wins, and the just-spawned worker is killed after the state
860-
// update instead of being resurrected by stale launch data.
861-
updateState(workspaceRoot, (state) => {
862-
const jobIndex = state.jobs.findIndex((candidate) => candidate.id === jobId);
863-
if (jobIndex === -1) {
864-
shouldKillWorker = true;
865-
launchStatus = "cancelled";
866-
return;
867-
}
868-
869-
const stateJob = state.jobs[jobIndex];
870-
const storedJob = readStoredJob(workspaceRoot, jobId);
871-
if (isTerminalJobRecord(stateJob, storedJob)) {
872-
shouldKillWorker = true;
873-
launchStatus = resolveLaunchStatus(stateJob, storedJob, "cancelled");
874-
updatedJob = {
875-
...stateJob,
876-
...(storedJob ?? {})
877-
};
878-
return;
879-
}
880-
881-
const updatedAt = nowIso();
882-
updatedJob = {
883-
...(storedJob ?? {}),
884-
...stateJob,
885-
pid: childPid,
886-
updatedAt
887-
};
888-
state.jobs[jobIndex] = updatedJob;
889-
writeJobFile(workspaceRoot, jobId, updatedJob);
890-
launchStatus = updatedJob.status;
891-
});
892-
893-
return { shouldKillWorker, launchStatus, job: updatedJob };
894-
}
895-
896845
function spawnDetachedTaskWorker(cwd, jobId, options = {}) {
897846
const scriptPath = path.join(ROOT_DIR, "scripts", "codex-companion.mjs");
898847
let child = null;
@@ -903,6 +852,7 @@ function spawnDetachedTaskWorker(cwd, jobId, options = {}) {
903852
env: process.env,
904853
detached: true,
905854
stdio: "ignore",
855+
shell: false,
906856
windowsHide: true
907857
});
908858
} catch (error) {
@@ -979,10 +929,9 @@ function enqueueBackgroundTask(cwd, job, request) {
979929
};
980930
}
981931

982-
const { shouldKillWorker, launchStatus } = persistSpawnedTaskWorkerPid(job.workspaceRoot, job.id, child.pid);
932+
const { shouldKillWorker, launchStatus } = commitSpawnedTaskWorker(job.workspaceRoot, job.id, child.pid);
983933
if (shouldKillWorker) {
984934
appendLogLine(logFile, `Terminating background worker because job is ${launchStatus}.`);
985-
terminateProcessTree(child.pid);
986935
}
987936

988937
return {
@@ -1438,40 +1387,32 @@ async function handleCancel(argv) {
14381387
);
14391388
}
14401389

1441-
terminateProcessTree(job.pid ?? Number.NaN);
1442-
appendLogLine(job.logFile, "Cancelled by user.");
1443-
14441390
const completedAt = nowIso();
1445-
let nextJob = null;
1446-
// PR #346 review: cancellation is the terminal launch/cancel transition, so
1447-
// the state row and stored job file are updated from one read-modify-write
1448-
// instead of a stale stored-job write followed by a separate state patch.
1449-
updateState(workspaceRoot, (state) => {
1450-
const jobIndex = state.jobs.findIndex((candidate) => candidate.id === job.id);
1451-
const stateJob = jobIndex === -1 ? job : state.jobs[jobIndex];
1452-
const latestStoredJob = readStoredJob(workspaceRoot, job.id) ?? existing;
1453-
nextJob = {
1391+
const cancellation = updateJobStores(workspaceRoot, job.id, ({ stateJob, storedJob }) => {
1392+
const latestStateJob = stateJob ?? job;
1393+
const latestStoredJob = storedJob ?? existing;
1394+
const nextJob = {
14541395
...latestStoredJob,
1455-
...stateJob,
1396+
...latestStateJob,
14561397
status: "cancelled",
14571398
phase: "cancelled",
14581399
pid: null,
14591400
completedAt,
14601401
updatedAt: completedAt,
14611402
errorMessage: "Cancelled by user."
14621403
};
1463-
1464-
if (jobIndex === -1) {
1465-
state.jobs.unshift(nextJob);
1466-
} else {
1467-
state.jobs[jobIndex] = nextJob;
1468-
}
1469-
1470-
writeJobFile(workspaceRoot, job.id, {
1471-
...nextJob,
1472-
cancelledAt: completedAt
1473-
});
1404+
return {
1405+
stateJob: nextJob,
1406+
storedJob: { ...nextJob, cancelledAt: completedAt },
1407+
value: {
1408+
nextJob,
1409+
pid: latestStoredJob.pid ?? latestStateJob.pid ?? job.pid ?? Number.NaN
1410+
}
1411+
};
14741412
});
1413+
const { nextJob, pid } = cancellation.value;
1414+
terminateProcessTree(pid);
1415+
appendLogLine(nextJob.logFile ?? job.logFile, "Cancelled by user.");
14751416

14761417
const payload = {
14771418
jobId: job.id,

0 commit comments

Comments
 (0)