Skip to content

The agent that grows with you

fix(cron): fail closed inside the merge peek; keep merge on mergeable repairs

kshitijk4poorc642f42bc3b6
diff --git a/cron/jobs.py b/cron/jobs.py
index 2a525292b16..5f46d4510c0 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1357,11 +1357,13 @@ def load_jobs() -> List[Dict[str, Any]]:
# under the lock below), so each warning is emitted once per repair.
repair = "had invalid control characters" if _strict_retry else None
notes: List[str] = []
+ unmergeable = False # disk shape _peek_jobs_unlocked cannot read: only a replace save fixes it
if isinstance(data, dict):
jobs = data.get("jobs", [])
if isinstance(jobs, dict):
# ID-keyed map from external tools: flatten (inline "id" wins, else the key), skip junk.
- # _peek_jobs_unlocked deliberately does NOT flatten, so saves never merge against it.
+ # _peek_jobs_unlocked deliberately does NOT flatten, so a merging save refuses this
+ # shape; the repair below rewrites it with replace=True.
skipped = [k for k, v in jobs.items() if not isinstance(v, dict)]
if skipped:
notes.append("Skipping %d non-dict entr%s in id-keyed jobs map: %s" % (
@@ -1369,11 +1371,13 @@ def load_jobs() -> List[Dict[str, Any]]:
", ".join(map(repr, skipped))))
jobs = [{**v, "id": v.get("id") or k} for k, v in jobs.items() if isinstance(v, dict)]
repair = "id-keyed jobs map flattened to list"
+ unmergeable = True
elif not isinstance(jobs, list):
notes.append("Replacing invalid jobs.json 'jobs' field (%s) with an empty list"
% type(jobs).__name__)
jobs = []
repair = "invalid jobs field replaced with list"
+ unmergeable = True
elif isinstance(data, list):
jobs = data
repair = "bare list wrapped as dict"
@@ -1412,7 +1416,9 @@ def load_jobs() -> List[Dict[str, Any]]:
return load_jobs()
for note in notes:
logger.warning("%s", note)
- save_jobs(jobs, replace=True) # locked full-store read: the repaired list is authoritative
+ # Keep the shrink-merge (a degraded-lock sibling's create may have landed since the read)
+ # unless disk is a shape the merge would refuse as corrupt.
+ save_jobs(jobs, replace=unmergeable)
logger.warning("Auto-repaired jobs.json (%s)", repair)
_record_load_stamp(pre_read_stamp)
return jobs
@@ -1462,14 +1468,15 @@ def _unmerged_disk_jobs(
jobs: List[Dict[str, Any]], removed_ids: Optional[Collection[str]]
) -> List[Dict[str, Any]]:
"""On-disk jobs missing from *jobs* and not intentionally removed. Stamp match => nothing
- landed, return without parsing; unreadable store => ``[]`` (never merge against an unknown
- baseline)."""
+ landed, return without parsing; unreadable store => raise RuntimeError (fail closed: writing
+ over an unknown baseline would silently drop every job in it)."""
stamp = getattr(_jobs_lock_state, "load_stamp", None)
if stamp is not None and _jobs_file_stamp(_current_cron_store().jobs_file) == stamp:
return []
disk_jobs = _peek_jobs_unlocked()
if disk_jobs is None:
- return []
+ raise RuntimeError(
+ f"Cron database corrupted; refusing to overwrite {_current_cron_store().jobs_file}")
seen = {str(j["id"]) for j in jobs if isinstance(j, dict) and j.get("id")}
seen |= {str(i) for i in (removed_ids or ()) if i}
recovered: List[Dict[str, Any]] = []
@@ -1530,13 +1537,10 @@ def _save_jobs_unlocked(
replace: bool = False,
):
"""Save all jobs; caller must hold _jobs_lock(). ``removed_ids`` = intentional deletes;
- ``replace=True`` skips the shrink-merge guard (wholesale rewrite for tests/disaster
- recovery)."""
+ ``replace=True`` skips the shrink-merge guard and the corrupt-store refusal (wholesale
+ rewrite for tests, disaster recovery and load_jobs' auto-repair of unmergeable shapes)."""
jobs_file = _current_cron_store().jobs_file
ensure_dirs()
- # Fail closed: merging against an unreadable store would silently overwrite every job in it.
- if not replace and jobs_file.exists() and _peek_jobs_unlocked() is None:
- raise RuntimeError(f"Cron database corrupted; refusing to overwrite {jobs_file}")
# Owner snapshot BEFORE replace so a root writer can hand the file back to the gateway user.
_stat_before = None
for probe in (jobs_file, jobs_file.parent):
@@ -1560,9 +1564,10 @@ def _save_jobs_unlocked(
_unlink_quiet(tmp_path)
tmp_path = None
continue
- atomic_replace(tmp_path, jobs_file)
+ # fsync the directory the rename actually landed in (atomic_replace resolves symlinks).
+ replaced = Path(atomic_replace(tmp_path, jobs_file))
tmp_path = None
- fsync_directory(jobs_file.parent)
+ fsync_directory(replaced.parent)
_secure_file(jobs_file)
_preserve_file_ownership(jobs_file, _stat_before)
# Invalidate (never refresh) the stamp: a refresh would let a nested save certify disk
diff --git a/tests/cron/test_jobs_shrink_merge.py b/tests/cron/test_jobs_shrink_merge.py
index e7e94bc9b94..7512bc2e9f8 100644
--- a/tests/cron/test_jobs_shrink_merge.py
+++ b/tests/cron/test_jobs_shrink_merge.py
@@ -178,7 +178,7 @@ def test_save_over_corrupt_store_fails_closed(hermes_env):
jobs_file = jobs._current_cron_store().jobs_file
corrupt = b'{"jobs": [{"id": "ccc'
jobs_file.write_bytes(corrupt)
- with pytest.raises(RuntimeError):
+ with pytest.raises(RuntimeError, match="refusing to overwrite"):
save_jobs([{"id": "aaaaaaaaaaaa", "name": "a"}])
assert jobs_file.read_bytes() == corrupt