Skip to content

The agent that grows with you

fix(cron): run the load_jobs repair save under the job-store lock

John Paul Solivaa51d7f7bead1
diff --git a/cron/jobs.py b/cron/jobs.py
index 4cf8b4c4f73..4b6cdc0e380 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1391,9 +1391,13 @@ def load_jobs() -> List[Dict[str, Any]]:
", ".join(sorted({type(j).__name__ for j in junk})))
jobs = [j for j in jobs if isinstance(j, dict)]
repair = repair or "non-object entries dropped"
- # Persist even an empty result, or an all-junk store repeats the repair on every tick; the
- # save's shrink-merge still keeps any valid job a sibling wrote meanwhile.
+ # Persist even an empty result, or an all-junk store repeats the repair on every tick.
if repair:
+ if not getattr(_jobs_lock_state, "depth", 0):
+ # An unlocked snapshot may predate a locked writer's update to a job it already holds
+ # (the shrink-merge only restores missing ids), so re-read and repair under the lock.
+ with _jobs_lock():
+ return load_jobs()
save_jobs(jobs)
logger.warning("Auto-repaired jobs.json (%s)", repair)
_record_load_stamp(pre_read_stamp)
diff --git a/tests/cron/test_jobs.py b/tests/cron/test_jobs.py
index 72aba65557d..54e5528b4e3 100644
--- a/tests/cron/test_jobs.py
+++ b/tests/cron/test_jobs.py
@@ -1764,6 +1764,36 @@ class TestJobsJsonIdKeyedMap:
assert json.loads(JOBS_FILE.read_text(encoding="utf-8"))["jobs"] == []
assert type(bad_jobs).__name__ in caplog.text
+ def test_unlocked_reader_repair_does_not_revert_a_concurrent_update(
+ self, tmp_cron_dir, monkeypatch
+ ):
+ """A lock-free reader's repair must not save its stale snapshot over a writer that
+ landed after the reader parsed the file."""
+ import json
+ import cron.jobs as jobs_mod
+ from cron.jobs import JOBS_FILE, update_job
+
+ job = create_job(prompt="keep me", schedule="every 1h", name="racer")
+ payload = json.loads(JOBS_FILE.read_text(encoding="utf-8"))
+ payload["jobs"].append(None)
+ JOBS_FILE.write_text(json.dumps(payload), encoding="utf-8")
+
+ real_parse = jobs_mod._parse_jobs_file
+ raced = []
+
+ def parse_then_race(path):
+ parsed = real_parse(path)
+ if not raced:
+ raced.append(True)
+ update_job(job["id"], {"enabled": False})
+ return parsed
+
+ monkeypatch.setattr(jobs_mod, "_parse_jobs_file", parse_then_race)
+ list_jobs(include_disabled=True)
+
+ on_disk = json.loads(JOBS_FILE.read_text(encoding="utf-8"))["jobs"]
+ assert [j["enabled"] for j in on_disk] == [False]
+