Skip to content

The agent that grows with you

refactor(cron): resolve the jobs.json symlink inside _stage_jobs_payload

kshitijk4poor773b1118ad18
diff --git a/cron/jobs.py b/cron/jobs.py
index 64608751b50..513ca5dcc3f 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1534,8 +1534,16 @@ def _unlink_quiet(path: Optional[str]) -> None:
def _stage_jobs_payload(jobs_file: Path, jobs: List[Dict[str, Any]]) -> str:
- """Serialize the store payload to a fsynced temp file next to *jobs_file*; return its path."""
- fd, tmp_path = tempfile.mkstemp(dir=str(jobs_file.parent), suffix=".tmp", prefix=".jobs_")
+ """Serialize the store payload to a fsynced temp file beside the RESOLVED *jobs_file*; return
+ its path. A temp next to a symlink whose target is on another filesystem makes the rename
+ EXDEV, and atomic_replace's copy fallback then rewrites the store in place (torn on crash)."""
+ try:
+ fd, tmp_path = tempfile.mkstemp(
+ dir=os.path.dirname(os.path.realpath(jobs_file)), suffix=".tmp", prefix=".jobs_")
+ except PermissionError:
+ # The link target's directory may be read-only to us while the file itself is writable;
+ # staging beside the link keeps saves working (non-atomic copy fallback, as before).
+ fd, tmp_path = tempfile.mkstemp(dir=str(jobs_file.parent), suffix=".tmp", prefix=".jobs_")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(
@@ -1574,9 +1582,7 @@ def _save_jobs_unlocked(
for attempt in range(_SAVE_JOBS_MERGE_ATTEMPTS + 1):
if not replace:
jobs = _merge_unexpected_disk_jobs(jobs, removed_ids=removed_ids)
- # Stage beside the resolved store: a temp next to a symlink on another filesystem
- # makes the rename EXDEV, and atomic_replace's copy fallback rewrites in place.
- tmp_path = _stage_jobs_payload(Path(os.path.realpath(jobs_file)), jobs)
+ tmp_path = _stage_jobs_payload(jobs_file, jobs)
# Verify-after-stage: a sibling landing during serialization forces another merge round.
if (
not replace
diff --git a/tests/cron/test_jobs_file_ownership.py b/tests/cron/test_jobs_file_ownership.py
index 883917e4ac3..81fb5db0638 100644
--- a/tests/cron/test_jobs_file_ownership.py
+++ b/tests/cron/test_jobs_file_ownership.py
@@ -139,37 +139,6 @@ class TestSaveJobsOwnershipPreservation:
mode = stat.S_IMODE(os.stat(cron_store / "jobs.json").st_mode)
assert mode == 0o600
- def test_symlinked_store_saves_by_rename_not_in_place_copy(self, cron_store, tmp_path, monkeypatch):
- """jobs.json symlinked into another dir (treated as another filesystem) must still
- be published by an atomic rename — never the EXDEV in-place copy fallback, which tears
- the store on a crash mid-copy."""
- import errno
- import shutil
-
- real_dir = tmp_path / "elsewhere"
- real_dir.mkdir()
- (real_dir / "jobs.json").write_text('{"jobs": []}')
- cron_store.mkdir(parents=True, exist_ok=True)
- (cron_store / "jobs.json").symlink_to(real_dir / "jobs.json")
-
- real_replace = os.replace
-
- def replace_same_dir_only(src, dst):
- if os.path.dirname(os.path.realpath(src)) != os.path.dirname(os.path.realpath(dst)):
- raise OSError(errno.EXDEV, os.strerror(errno.EXDEV))
- return real_replace(src, dst)
-
- def no_copy(*a, **k):
- raise AssertionError("in-place copy fallback used")
-
- monkeypatch.setattr(os, "replace", replace_same_dir_only)
- monkeypatch.setattr(shutil, "copyfile", no_copy)
-
- jobs.save_jobs([{"id": "a", "prompt": "x"}], replace=True)
-
- assert (cron_store / "jobs.json").is_symlink()
- assert [j["id"] for j in jobs.load_jobs()] == ["a"]
-
# =========================================================================
# 2. Zombie-ticker surfacing (ticker_last_error marker)
diff --git a/tests/cron/test_jobs_shrink_merge.py b/tests/cron/test_jobs_shrink_merge.py
index 7512bc2e9f8..1e5da6b61bc 100644
--- a/tests/cron/test_jobs_shrink_merge.py
+++ b/tests/cron/test_jobs_shrink_merge.py
@@ -8,7 +8,10 @@ unexpected on-disk ids back unless the caller passes ``removed_ids``.
from __future__ import annotations
+import errno
import json
+import os
+import shutil
import pytest
@@ -207,3 +210,34 @@ def test_nested_create_survives_outer_stale_save(hermes_env):
ids = {j["id"] for j in load_jobs()}
assert created["id"] in ids, "nested create was clobbered by outer stale save"
assert seed["id"] in ids
+
+
+def test_symlinked_store_saves_by_rename_not_in_place_copy(hermes_env, tmp_path, monkeypatch):
+ """jobs.json symlinked into another dir (treated as another filesystem) must still be
+ published by an atomic rename — never the EXDEV in-place copy fallback, which tears the
+ store on a crash mid-copy."""
+ from cron.jobs import load_jobs, save_jobs
+
+ real_dir = tmp_path / "elsewhere"
+ real_dir.mkdir()
+ (real_dir / "jobs.json").write_text('{"jobs": []}')
+ link = hermes_env / "cron" / "jobs.json"
+ link.symlink_to(real_dir / "jobs.json")
+
+ real_replace = os.replace
+
+ def replace_same_dir_only(src, dst):
+ if os.path.dirname(os.path.realpath(src)) != os.path.dirname(os.path.realpath(dst)):
+ raise OSError(errno.EXDEV, os.strerror(errno.EXDEV))
+ return real_replace(src, dst)
+
+ def no_copy(*a, **k):
+ raise AssertionError("in-place copy fallback used")
+
+ monkeypatch.setattr(os, "replace", replace_same_dir_only)
+ monkeypatch.setattr(shutil, "copyfile", no_copy)
+
+ save_jobs([{"id": "a", "prompt": "x"}], replace=True)
+
+ assert link.is_symlink()
+ assert [j["id"] for j in load_jobs()] == ["a"]