fix: setCheckpoint overwrites concurrent job state updates causing completed jobs to appear as running
Bug Description
When a plan has multiple jobs running and one fails, the other jobs that have already sent mc_report(status: "completed") remain stuck as running in the plan status. The plan shows 1 failed and N running, even though the running jobs have completed.
Root Cause
Race condition in Orchestrator.setCheckpoint() → savePlan() that overwrites concurrent updatePlanJob() updates.
When a job fails, handleJobFailed in orchestrator.ts:
- Fire-and-forgets
updatePlanJob(planId, failedJob, { status: 'failed' }) - Calls
loadPlan()outside the mutex — gets a stale snapshot (other jobs still showrunning) - Passes that stale snapshot to
setCheckpoint(), which mutatesplan.status = 'paused'and callssavePlan(plan) savePlan()writes the entire stale plan object to disk — overwriting anyupdatePlanJob()changes thathandleJobCompletemade for the other jobs
Race sequence
1. Monitor poll detects: Job A = failed, Job B = completed (report), Job C = completed (report)
2. emit('failed', A) → handleJobFailed starts async chain
3. emit('complete', B) → handleJobComplete calls updatePlanJob(B, 'completed')
4. emit('complete', C) → handleJobComplete calls updatePlanJob(C, 'completed')
Possible ordering:
a. handleJobFailed: loadPlan() → snapshot has A=running, B=running, C=running
b. updatePlanJob(A, 'failed') → plan file: A=failed, B=running, C=running
c. updatePlanJob(B, 'completed') → plan file: A=failed, B=completed, C=running
d. updatePlanJob(C, 'completed') → plan file: A=failed, B=completed, C=completed
e. setCheckpoint → savePlan(staleSnapshot) → plan file: A=failed, B=running, C=running ← OVERWRITES
Result: plan shows 1 failed, 2 running.
The planMutex in savePlan doesn't help because it reads the existing plan only for transition validation — it still writes the passed-in stale object. And since the monitor marks jobs as completed in jobs.json (removing them from getRunningJobs()), they are never re-checked on subsequent polls. There is no recovery path.
Affected Code
src/lib/orchestrator.ts—setCheckpoint(),clearCheckpoint(),_doReconcile()savePlan callssrc/lib/plan-state.ts—savePlan()does blind overwrite of entire plan object
Proposed Fix
- Add
updatePlanFields()toplan-state.ts— atomic read-modify-write for plan-level fields only (status, checkpoint, completedAt, prUrl) inside the mutex, preserving job states - Replace
savePlan(staleSnapshot)insetCheckpointwithupdatePlanFields(planId, { status: 'paused', checkpoint: type }) - Apply same fix to
clearCheckpointand_doReconcilesavePlan calls - Add reconciliation safety net in
_doReconcile— cross-referencejobs.jsonfor plan jobs stuck asrunningwhen they've already completed