The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): preserve direct-run liveness and registration ownership
cdb-review677e454c3d96
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex e2dd3296a39..2da0a402ac2 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -646,6 +646,8 @@ _running_futures: dict = {}# Installed in ``_running_futures`` at claim time so a sweep landing before ``pool.submit`` returns# never sees ``missing`` and releases a claim about to get its future._FUTURE_PENDING = object()+# Identity tokens fence cleanup and late future attachment after recovery.+_running_registration_owners: dict = {}# Forced-release count/history for ``get_inflight_guard_stats()``; mirrored to JSONL for probes._forced_release_count: int = 0@@ -825,10 +827,12 @@ def _record_external_cron_worker(job_id: str, pid: Any, *, scope_isolated: bool)_scope_isolated_job_ids.add(key)-def try_register_running_job(job_id: str) -> bool:+def try_register_running_job(job_id: str, *, owner=None, future=_FUTURE_PENDING) -> bool:"""Atomically add ``job_id`` to the in-flight set; False (caller must skip) if already mid-run.Single dedupe owner for ticker + manual runs (the fire claim's 300s TTL is outlived by realjobs). Callers MUST pair success with ``release_running_job`` in a ``finally``.+ Dispatchers pass a unique ``owner`` back on release. Direct workers register a running+ ``future`` atomically because no executor submission will replace the pending sentinel.This is the single dedupe owner shared by the ticker's ``_submit_with_guard`` and manual runs(``tools/cronjob_tools``): the fire claim alone cannot prevent a double-fire because its TTL (300s) is@@ -848,12 +852,15 @@ def try_register_running_job(job_id: str) -> bool:# Same critical section as the add: no window where an in-flight id lacks an age the sweep# can bound. Sentinel is replaced by the real future once ``pool.submit`` returns._running_since[key] = time.time()- _running_futures[key] = _FUTURE_PENDING+ _running_futures[key] = future+ _running_registration_owners[key] = ownerreturn True-def release_running_job(job_id: str, home: Optional[Union[Path, str]] = None) -> None:- """Remove ``job_id`` from the in-flight running set (idempotent).+def release_running_job(+ job_id: str, home: Optional[Union[Path, str]] = None, *, owner=None,+) -> None:+ """Remove the registration unless an explicit ``owner`` has been replaced.``home`` MUST be passed by any caller that does not run inside the same cron scope the claimwas registered under. The scope is a ContextVar the ticker binds per profile: a pool worker@@ -862,6 +869,9 @@ def release_running_job(job_id: str, home: Optional[Union[Path, str]] = None) ->"""key = _inflight_key(job_id, home)with _running_lock:+ if owner is not None and _running_registration_owners.get(key) is not owner:+ return+ _running_registration_owners.pop(key, None)_running_job_ids.discard(key)_running_since.pop(key, None)_running_allowance_s.pop(key, None)@@ -1110,6 +1120,7 @@ def sweep_stale_inflight(due_jobs: Optional[list] = None) -> list:reason = "age"else:continue+ _running_registration_owners.pop(key, None)_running_job_ids.discard(key)_running_since.pop(key, None)_running_allowance_s.pop(key, None)@@ -4307,7 +4318,8 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, p_not_dispatched_shutdown()_clear_run_claim_best_effort()return None- if not try_register_running_job(job_id):+ registration_owner = object()+ if not try_register_running_job(job_id, owner=registration_owner):logger.info("Job '%s' already running — skipping", job_label)return None# The home the claim was registered under. The pool worker's ``finally`` runs OUTSIDE@@ -4323,7 +4335,7 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, p_ctx = contextvars.copy_context()except Exception as execution_err:# Release the claim so the next tick retries instead of wedging "already running".- release_running_job(job_id, home=_claim_home)+ release_running_job(job_id, home=_claim_home, owner=registration_owner)_clear_run_claim_best_effort()logger.exception("Job '%s' not dispatched: execution creation failed: %s", job_label, execution_err)@@ -4333,12 +4345,12 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, ptry:return ctx.run(process_job, j)finally:- release_running_job(j["id"], home=home)+ release_running_job(j["id"], home=home, owner=registration_owner)try:fut = pool.submit(_run_and_release)except Exception as submit_err:- release_running_job(job_id, home=_claim_home)+ release_running_job(job_id, home=_claim_home, owner=registration_owner)_clear_run_claim_best_effort()finish_execution(execution["id"], success=False, error=f"Executor dispatch failed: {submit_err}")@@ -4350,7 +4362,7 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, pwith _running_lock:_submit_key = _inflight_key(job_id, _claim_home)- if _submit_key in _running_job_ids:+ if _running_registration_owners.get(_submit_key) is registration_owner:_running_futures[_submit_key] = futreturn futdiff --git a/tests/cron/test_registration_ownership.py b/tests/cron/test_registration_ownership.pynew file mode 100644index 00000000000..eaf6fbbf026--- /dev/null+++ b/tests/cron/test_registration_ownership.py@@ -0,0 +1,101 @@+"""Live direct runs and successor registrations must survive stale cleanup.++Narrow regressions for the in-memory ownership portion of #88688.+"""+from concurrent.futures import Future+import threading+import time+from unittest.mock import patch++import pytest++from cron import jobs, scheduler as sched+from tools import cronjob_tools as tools+++def test_live_direct_run_survives_stale_sweep(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ scripts = tmp_path / "scripts"+ scripts.mkdir()+ started, release = tmp_path / "started", tmp_path / "release"+ (scripts / "live.py").write_text(+ "from pathlib import Path\nimport time\n"+ f"Path({str(started)!r}).touch()\n"+ "deadline = time.monotonic() + 30\n"+ f"while not Path({str(release)!r}).exists():\n"+ " if time.monotonic() > deadline: raise RuntimeError('timed out')\n"+ " time.sleep(0.02)\n"+ "print('direct-run-ok')\n"+ )+ with jobs.use_cron_store(tmp_path):+ job = jobs.create_job(None, "every 15m", script=str(scripts / "live.py"),+ no_agent=True, deliver="local")+ result = {}+ def run():+ with jobs.use_cron_store(tmp_path):+ result.update(tools._execute_job_now(job))+ thread = threading.Thread(target=run)+ thread.start()+ try:+ deadline = time.monotonic() + 15+ while not started.exists() and thread.is_alive() and time.monotonic() < deadline:+ time.sleep(0.02)+ assert started.exists(), result+ key = sched._inflight_key(job["id"])+ with sched._running_lock:+ sched._running_since[key] -= 86400+ assert sched.sweep_stale_inflight([jobs.get_job(job["id"])]) == []+ saved = jobs.get_job(job["id"])+ assert saved is not None+ assert not tools._execute_job_now(saved)["claimed"]+ finally:+ release.touch()+ thread.join(35)+ assert not thread.is_alive()+ assert not sched.is_job_running(job["id"])+ assert result["success"], result+ saved = jobs.get_job(job["id"])+ assert saved is not None+ assert saved["last_status"] == "ok"+ assert not saved.get("fire_claim")+ outputs = (tmp_path / "cron" / "output").rglob("*.md")+ assert any("direct-run-ok" in output.read_text() for output in outputs)+ from cron.executions import latest_executions+ assert latest_executions([job["id"]])[job["id"]]["status"] == "completed"++[email protected]("path", ["direct", "direct-error", "ticker", "submit-error", "setup-error"])+def test_dispatch_cleanup_preserves_successor(path):+ job = jobs.create_job("offline", "every 15m", deliver="local")+ key = sched._inflight_key(job["id"])+ successor = []++ def replace(*args, **kwargs):+ sched.release_running_job(job["id"])+ assert sched.try_register_running_job(job["id"])+ successor.append(sched._running_futures[key])+ if path.endswith("error"):+ raise RuntimeError("old dispatch failed")+ return True++ class Pool:+ def submit(self, callback):+ if path == "submit-error":+ replace()+ future = Future()+ future.set_result(callback())+ return future++ try:+ if path.startswith("direct"):+ with patch.object(sched, "run_one_job", side_effect=replace):+ tools._run_claimed_job(job)+ elif path == "setup-error":+ with patch.object(sched, "create_execution", side_effect=replace):+ sched._submit_with_guard(job, Pool(), replace)+ else:+ sched._submit_with_guard(job, Pool(), replace)+ assert sched.is_job_running(job["id"])+ assert sched._running_futures[key] is successor[0]+ finally:+ sched.release_running_job(job["id"])diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex 5bad3d299db..00ec153a213 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -326,6 +326,11 @@ def _run_claimed_job(job: Dict[str, Any], extra_prompt: Optional[str] = None) ->job_id = job["id"]_registered = Falsefire_owner = None+ from concurrent.futures import Future++ registration_owner = object()+ running_future = Future()+ running_future.set_running_or_notify_cancel()try:from cron.scheduler import release_running_job, run_one_job, try_register_running_job@@ -335,7 +340,9 @@ def _run_claimed_job(job: Dict[str, Any], extra_prompt: Optional[str] = None) -># In-flight dedupe (idea from #53395 by @izumi0uu): the fire claim's TTL (300s) is routinely# outlived by real jobs, so it alone cannot stop a manual run from double-firing a job the ticker# (or another manual run) is still executing.- if not try_register_running_job(job_id):+ if not try_register_running_job(+ job_id, owner=registration_owner, future=running_future,+ ):return {"claimed": True, "success": False, "error": _ALREADY_RUNNING_ERROR}_registered = True@@ -375,7 +382,7 @@ def _run_claimed_job(job: Dict[str, Any], extra_prompt: Optional[str] = None) ->processed = run_one_job(job, adapters=adapters, loop=gateway_loop, extra_prompt=extra_prompt)finally:_registered = False- release_running_job(job_id)+ release_running_job(job_id, owner=registration_owner)refreshed = get_job(job_id) or {}execution = Noneexecution_id = job.get("execution_id")@@ -399,15 +406,14 @@ def _run_claimed_job(job: Dict[str, Any], extra_prompt: Optional[str] = None) ->return {"claimed": True, "success": bool(processed and ok), "error": run_error}except Exception as e:logger.error("Failed to execute cron job %s immediately: %s", job_id, e)- if _registered:- # Raised before the run's own release (e.g. heartbeat setup): don't leave the- # job marked in-flight. Only release registrations WE took — a bare discard- # could erase a ticker-owned entry.- with contextlib.suppress(Exception):- release_running_job(job_id)with contextlib.suppress(Exception):mark_job_run(job_id, False, str(e), expected_fire_owner=fire_owner)return {"claimed": True, "success": False, "error": str(e)}+ finally:+ # Setup failures and BaseException must release only our registration.+ if _registered:+ release_running_job(job_id, owner=registration_owner)+ running_future.set_result(None)def execute_job_for_event(