Skip to content

The agent that grows with you

fix(cron): preserve map keys as ids and skip junk values when flattening id-keyed jobs.json

Tekniumf2639f8872b9
diff --git a/cron/jobs.py b/cron/jobs.py
index ca076170d26..203d323f2d3 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1348,13 +1348,29 @@ def load_jobs() -> List[Dict[str, Any]]:
# external tools or hand edits, never by save_jobs(). The public
# load_jobs() contract and every CRUD/scheduler consumer expect a
# list; iterating the dict would yield bare id strings and blow up
- # downstream (e.g. _normalize_job_record -> dict(<str>)). The map
- # values already carry their own "id", so list(values) is
- # lossless. (_peek_jobs_unlocked() deliberately does NOT flatten —
+ # downstream (e.g. _normalize_job_record -> dict(<str>)). Flatten
+ # with an id-preserving merge: an inline "id" on the value wins,
+ # otherwise the map key is adopted as the id (external tools often
+ # key by id and omit the inline copy). Non-dict values are junk
+ # (a flattened record would not be a job) — skip them with a
+ # warning instead of crashing downstream.
+ # (_peek_jobs_unlocked() deliberately does NOT flatten —
# it returns None on a dict-shaped store so the save path never
# merges against an unrepaired baseline; the flatten lives only
# here at the load boundary.)
- jobs = list(jobs.values())
+ skipped = [k for k, v in jobs.items() if not isinstance(v, dict)]
+ if skipped:
+ logger.warning(
+ "Skipping %d non-dict entr%s in id-keyed jobs map: %s",
+ len(skipped),
+ "y" if len(skipped) == 1 else "ies",
+ ", ".join(map(repr, skipped)),
+ )
+ jobs = [
+ {**v, "id": v.get("id") or k}
+ for k, v in jobs.items()
+ if isinstance(v, dict)
+ ]
needs_shape_repair = True
if jobs and (_strict_retry or needs_shape_repair):
# Rewrite into the canonical {"jobs": [...]} form: either the parse
diff --git a/tests/cron/test_jobs.py b/tests/cron/test_jobs.py
index 91a317a11e9..df45211ed42 100644
--- a/tests/cron/test_jobs.py
+++ b/tests/cron/test_jobs.py
@@ -1381,6 +1381,92 @@ class TestJobsJsonIdKeyedMap:
assert load_jobs() == []
+ def test_map_value_without_inline_id_adopts_key(self, tmp_cron_dir):
+ """A value lacking an inline "id" gets the map key as its id."""
+ import json
+ from cron.jobs import JOBS_FILE, load_jobs
+
+ payload = {
+ "jobs": {
+ "cronkeyonly1": {
+ "name": "keyed only",
+ "enabled": True,
+ "prompt": "no inline id here",
+ "schedule": {"kind": "interval", "minutes": 15, "display": "every 15m"},
+ },
+ "cron-ignored-key": {
+ "id": "croninline99",
+ "name": "inline id wins",
+ "enabled": True,
+ "prompt": "inline id present",
+ "schedule": {"kind": "interval", "minutes": 5, "display": "every 5m"},
+ },
+ }
+ }
+ JOBS_FILE.parent.mkdir(parents=True, exist_ok=True)
+ JOBS_FILE.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = {j["id"]: j for j in load_jobs()}
+ # Key adopted when the value has no inline id.
+ assert "cronkeyonly1" in loaded
+ assert loaded["cronkeyonly1"]["name"] == "keyed only"
+ # Inline id wins over a differing map key.
+ assert "croninline99" in loaded
+ assert "cron-ignored-key" not in loaded
+
+ # Self-heal persisted the id-merged records.
+ on_disk = json.loads(JOBS_FILE.read_text(encoding="utf-8"))
+ assert isinstance(on_disk["jobs"], list)
+ assert {j["id"] for j in on_disk["jobs"]} == {"cronkeyonly1", "croninline99"}
+
+ def test_non_dict_map_values_skipped_with_warning(self, tmp_cron_dir, caplog):
+ """Junk (non-dict) values in the map are skipped, never crash."""
+ import json
+ import logging
+ from cron.jobs import JOBS_FILE, list_jobs, load_jobs
+
+ payload = {
+ "jobs": {
+ "goodjob1": {
+ "name": "survivor",
+ "enabled": True,
+ "prompt": "keep me",
+ "schedule": {"kind": "interval", "minutes": 60, "display": "every 60m"},
+ },
+ "junk-string": "i am not a job",
+ "junk-number": 42,
+ "junk-null": None,
+ }
+ }
+ JOBS_FILE.parent.mkdir(parents=True, exist_ok=True)
+ JOBS_FILE.write_text(json.dumps(payload), encoding="utf-8")
+
+ with caplog.at_level(logging.WARNING, logger="cron.jobs"):
+ loaded = load_jobs()
+ assert [j["id"] for j in loaded] == ["goodjob1"]
+ assert any("non-dict" in rec.getMessage() for rec in caplog.records)
+
+ # The reported traceback path also survives the junk.
+ jobs = list_jobs(include_disabled=True)
+ assert {j["id"] for j in jobs} == {"goodjob1"}
+
+ # Self-heal wrote only the valid record, canonical list shape.
+ on_disk = json.loads(JOBS_FILE.read_text(encoding="utf-8"))
+ assert isinstance(on_disk["jobs"], list)
+ assert [j["id"] for j in on_disk["jobs"]] == ["goodjob1"]
+
+ def test_all_junk_map_values_yield_empty_list(self, tmp_cron_dir):
+ """A map of only junk values flattens to [] without crashing."""
+ import json
+ from cron.jobs import JOBS_FILE, load_jobs
+
+ JOBS_FILE.parent.mkdir(parents=True, exist_ok=True)
+ JOBS_FILE.write_text(
+ json.dumps({"jobs": {"a": "junk", "b": 1}}), encoding="utf-8"
+ )
+
+ assert load_jobs() == []
+