Skip to content

The agent that grows with you

fix(profiles): reject an unschedulable shipped cron job before any file is replaced

kshitijk4poorbb0650e54113
diff --git a/cron/job_definition.py b/cron/job_definition.py
index 1f8b84df16b..2695de4b35b 100644
--- a/cron/job_definition.py
+++ b/cron/job_definition.py
@@ -6,7 +6,7 @@ into a live one (profile distributions) import this rather than duplicating the
"""
from typing import Any, Dict
-from cron.jobs import _apply_schedule_update
+from cron.jobs import _apply_schedule_update, parse_schedule
from cron.quota_hold import clear_state as _clear_quota_hold
# Persisted fields authored by create_job rather than advanced by the scheduler.
@@ -20,7 +20,10 @@ JOB_DEFINITION_FIELDS = frozenset({
def merge_job_definition(local: Dict[str, Any], authored: Dict[str, Any]) -> Dict[str, Any]:
- """Refresh authored fields while preserving this store's scheduler-owned state."""
+ """Refresh authored fields while preserving this store's scheduler-owned state.
+
+ Raises ValueError when the authored schedule cannot be scheduled (unparseable string,
+ past one-shot for a live job)."""
merged = {
key: value for key, value in local.items()
if key not in JOB_DEFINITION_FIELDS and key != "repeat"
@@ -30,16 +33,17 @@ def merge_job_definition(local: Dict[str, Any], authored: Dict[str, Any]) -> Dic
"completed": (local.get("repeat") or {}).get("completed", 0),
"times": (authored.get("repeat") or {}).get("times"),
}
+ if isinstance(merged.get("schedule"), str):
+ merged["schedule"] = parse_schedule(merged["schedule"])
if local.get("schedule") != merged.get("schedule"):
merged.pop("pending_slot", None)
_clear_quota_hold(merged)
if merged.get("enabled", True) and merged.get("state") != "paused":
- _apply_schedule_update(
- merged,
- {"schedule": merged["schedule"], "schedule_display": merged.get("schedule_display")},
- str(merged.get("id") or "imported job"),
- )
+ updates = {"schedule": merged["schedule"]}
+ if "schedule_display" in authored:
+ updates["schedule_display"] = authored["schedule_display"]
+ _apply_schedule_update(merged, updates, str(merged.get("id") or "imported job"))
else:
merged["next_run_at"] = None
return merged
diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.py
index 7448482ab65..ee43fe23d89 100644
--- a/hermes_cli/profile_distribution.py
+++ b/hermes_cli/profile_distribution.py
@@ -393,11 +393,34 @@ def _replace_entry(src: Path, dest: Path) -> None:
shutil.copy2(src, dest)
+def _shipped_cron_store(entries: List[Tuple[Path, Tuple[str, ...]]]) -> Optional[Path]:
+ """Return the staged ``cron/jobs.json`` when the distribution owns it (via ``cron/`` or exactly)."""
+ for src, rel_parts in entries:
+ if rel_parts == _CRON_STORE_REL:
+ return src
+ if rel_parts == _CRON_STORE_REL[:1] and (src / _CRON_STORE_REL[1]).is_file():
+ return src / _CRON_STORE_REL[1]
+ return None
+
+
def _merge_cron_store(src: Path, dest: Path) -> None:
- """Merge a distribution's cron store by job id; new jobs arrive paused."""
+ """Merge a distribution's cron store by job id; new jobs arrive paused.
+
+ Nothing is written when a shipped job cannot be scheduled (unparseable schedule, past
+ one-shot for a job the installer resumed); the error names the job."""
+ from hermes_time import now as _hermes_now
+
from cron import jobs as cron_jobs
from cron.job_definition import merge_job_definition
+ def merge(local: Dict[str, Any], incoming: Dict[str, Any]) -> Dict[str, Any]:
+ try:
+ return merge_job_definition(local, incoming)
+ except ValueError as exc:
+ raise DistributionError(
+ f"Could not merge cron job {incoming.get('name') or local.get('id')!r} into {dest}: {exc}"
+ ) from exc
+
try:
with tempfile.TemporaryDirectory(prefix="hermes_dist_cron_") as tmp:
staged_store = Path(tmp) / "cron"
@@ -409,7 +432,7 @@ def _merge_cron_store(src: Path, dest: Path) -> None:
if isinstance(job, dict) and job.get("id")
}
- now = datetime.now(timezone.utc).isoformat()
+ now = _hermes_now().isoformat()
new_state = {
"enabled": False,
"state": "paused",
@@ -422,13 +445,13 @@ def _merge_cron_store(src: Path, dest: Path) -> None:
merged = []
for local in cron_jobs.load_jobs():
incoming = shipped.pop(local.get("id"), None)
- merged.append(local if incoming is None else merge_job_definition(local, incoming))
+ merged.append(local if incoming is None else merge(local, incoming))
merged.extend(
- merge_job_definition({"id": job_id, **new_state}, incoming)
+ merge({"id": job_id, **new_state}, incoming)
for job_id, incoming in shipped.items()
)
cron_jobs.save_jobs(merged)
- except RuntimeError as exc: # load_jobs: corrupt/unreadable store; OSError/ValueError propagate as-is
+ except RuntimeError as exc: # load_jobs: corrupt/unreadable store; OSError propagates as-is
raise DistributionError(f"Could not merge cron jobs into {dest}: {exc}") from exc
@@ -470,8 +493,8 @@ def _merge_dir(src: Path, dest: Path, rel: Tuple[str, ...]) -> None:
if _is_distribution_runtime_path(parts):
continue
if parts == _CRON_STORE_REL:
- _merge_cron_store(child, dest / child.name)
- elif _is_container(child):
+ continue # merged up front by _copy_dist_payload
+ if _is_container(child):
_merge_dir(child, _real_dir(dest, (child.name,)), parts)
else:
_replace_entry(child, dest / child.name)
@@ -517,7 +540,15 @@ def _copy_dist_payload(staged: Path, target: Path, manifest: DistributionManifes
entries = list(_owned_entries(staged, manifest))
_refuse_symlinked_targets(target, entries)
+ # The cron merge runs first: it is the one step that can reject shipped content
+ # (an unschedulable job), and rejecting before any file is replaced keeps the profile whole.
+ cron_store = _shipped_cron_store(entries)
+ if cron_store is not None:
+ _merge_cron_store(cron_store, _real_dir(target, _CRON_STORE_REL[:-1]) / _CRON_STORE_REL[-1])
+
for src, rel_parts in entries:
+ if rel_parts == _CRON_STORE_REL:
+ continue
if len(rel_parts) == 1:
name = rel_parts[0]
if name == ENV_TEMPLATE_FILENAME:
@@ -529,11 +560,7 @@ def _copy_dist_payload(staged: Path, target: Path, manifest: DistributionManifes
if src.is_dir():
_merge_dir(src, _real_dir(target, rel_parts), rel_parts)
continue
- parent = _real_dir(target, rel_parts[:-1])
- if rel_parts == _CRON_STORE_REL:
- _merge_cron_store(src, parent / rel_parts[-1])
- else:
- _replace_entry(src, parent / rel_parts[-1])
+ _replace_entry(src, _real_dir(target, rel_parts[:-1]) / rel_parts[-1])
# Emit .env.EXAMPLE from manifest if the staged tree didn't ship one
if manifest.env_requires and not (target / ENV_EXAMPLE_FILENAME).exists():
diff --git a/tests/hermes_cli/test_profile_distribution.py b/tests/hermes_cli/test_profile_distribution.py
index 5a6ebe48dcc..a82058039f8 100644
--- a/tests/hermes_cli/test_profile_distribution.py
+++ b/tests/hermes_cli/test_profile_distribution.py
@@ -10,6 +10,7 @@ mocking git would just test the mock.
from __future__ import annotations
+import json
import shutil
import stat
import subprocess
@@ -495,6 +496,25 @@ class TestUpdate:
assert jobs[shipped["id"]]["next_run_at"] != old_next_run
assert jobs[shipped["id"]]["enabled"] is True
+ # An authored schedule the live job cannot take (past one-shot) is rejected as a
+ # job-labelled DistributionError before any other file is replaced.
+ (staged / "SOUL.md").write_text("upstream v3\n")
+ store = staged / "cron" / "jobs.json"
+ data = json.loads(store.read_text(encoding="utf-8"))
+ data["jobs"][0]["schedule"] = {"kind": "once", "run_at": "2020-01-01T00:00:00+00:00", "display": "once"}
+ store.write_text(json.dumps(data), encoding="utf-8")
+ with pytest.raises(DistributionError, match="cron job 'daily'"):
+ update_distribution("cron_merge")
+ assert (plan.target_dir / "SOUL.md").read_text() != "upstream v3\n"
+ with use_cron_store(plan.target_dir):
+ assert {j["id"]: j for j in list_jobs(include_disabled=True)}[shipped["id"]]["schedule"] == \
+ jobs[shipped["id"]]["schedule"]
+
+ # A corrupt target store surfaces as DistributionError too, not a raw RuntimeError.
+ (plan.target_dir / "cron" / "jobs.json").write_text("42", encoding="utf-8")
+ with pytest.raises(DistributionError, match="Could not merge cron jobs"):
+ update_distribution("cron_merge")
+
def test_update_refuses_symlinked_owned_container(self, profile_env):
staged = _make_staging_dir(profile_env, "src")