The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): self-heal leaked in-flight claim so a wedged recurring job re-dispatches (t_8b5480b3)
devopse14248ac1ee5
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 4eae63a3639..4291f53ad90 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -473,6 +473,40 @@ _parallel_pool_max_workers: Optional[int] = None_running_job_ids: set = set()_running_lock = threading.Lock()+# Wall-clock (time.time()) instant each in-flight job id was claimed by+# ``_submit_with_guard``, plus the future that owns its release (a pending+# sentinel until ``pool.submit`` returns). Together these bound the+# in-flight set: an id whose claim is older than its allowance AND has no+# live future can only be a leak — the release path never ran — so the+# stale-sweep force-releases it instead of letting every later tick+# short-circuit on "already running" until the whole gateway process+# restarts (incident: jarvis board-pm-triage-* jobs, 2026-08-02; recurring+# router/watchdog no_agent jobs, 2026-08-14 t_20e23f84).+_running_since: dict = {}+_running_futures: dict = {}++# Sentinel installed in ``_running_futures`` at claim time, before+# ``pool.submit`` has returned a real future. This closes the race the+# stale sweep previously had: a sweep landing between the claim critical+# section and the future-record section saw ``missing`` and could (in+# principle) release a claim that was about to get its future. With the+# sentinel there is never a window where a claim has neither an age nor a+# future marker — it is ``_FUTURE_PENDING`` until the real future lands.+_FUTURE_PENDING = object()++# Countable signal for unified-health: how many stale claims this process has+# force-released, and the most recent ones. Exposed via+# ``get_inflight_guard_stats()`` and mirrored to a JSONL under the cron dir so+# an out-of-process probe can catch a wedge in-cycle.+_forced_release_count: int = 0+_forced_releases: list = []+_FORCED_RELEASE_HISTORY = 20++# Floor for the stale allowance, in minutes. Effective allowance per job is+# max(2 * interval, this) so a slow-but-healthy hourly job is never clipped.+_INFLIGHT_MIN_ALLOWANCE_MINUTES = 30.0++# Job IDs the gateway shutdown path force-killed the tool subprocess of# while still in ``_running_job_ids`` (see ``mark_running_jobs_interrupted``# below). ``run_one_job``'s own completion path checks this set before@@ -522,6 +556,13 @@ def try_register_running_job(job_id: str) -> bool:if job_id in _running_job_ids:return False_running_job_ids.add(job_id)+ # Claim timestamp + pending-future sentinel are recorded in the SAME+ # critical section as the add, so there is never a window where an+ # id is in-flight without an age the stale sweep can bound it by+ # (t_3778a491). The sentinel is replaced by the real owning future+ # once ``pool.submit`` returns.+ _running_since[job_id] = time.time()+ _running_futures[job_id] = _FUTURE_PENDINGreturn True@@ -529,6 +570,237 @@ def release_running_job(job_id: str) -> None:"""Remove ``job_id`` from the in-flight running set (idempotent)."""with _running_lock:_running_job_ids.discard(job_id)+ _running_since.pop(job_id, None)+ _running_futures.pop(job_id, None)+++def _inflight_min_allowance_minutes() -> float:+ """Floor for the stale in-flight allowance, in minutes.++ Effective allowance per job is ``max(2 * interval, this)``, so a+ slow-but-healthy long-interval job is never clipped by the sweep.+ """+ raw = os.getenv("HERMES_CRON_INFLIGHT_MAX_MINUTES", "").strip()+ if raw:+ try:+ val = float(raw)+ if val > 0:+ return val+ except (ValueError, TypeError):+ logger.warning(+ "Invalid HERMES_CRON_INFLIGHT_MAX_MINUTES=%r; using default %s",+ raw,+ _INFLIGHT_MIN_ALLOWANCE_MINUTES,+ )+ return _INFLIGHT_MIN_ALLOWANCE_MINUTES+++def _cron_interval_minutes(expr: str) -> Optional[float]:+ """Approximate the natural interval of a cron expression, in minutes.++ The persisted job store keeps ``schedule`` as an already-parsed dict+ (``{"kind": "cron", "expr": "0 9 * * 1"}``), so the stale allowance for+ a cron job cannot be derived from a schedule *string* — it must come+ from the expression itself. We measure the gap between the next two+ fire times with croniter; that is the job's cadence, and the sweep's+ allowance becomes ``max(2 * cadence, floor)`` exactly like interval+ jobs. Falls back to ``None`` (→ floor allowance) if croniter is+ missing or the expression cannot be evaluated.+ """+ try:+ from croniter import croniter+ from datetime import datetime++ base = datetime.now()+ it = croniter(expr, base)+ first = it.get_next(datetime)+ second = it.get_next(datetime)+ gap = (second - first).total_seconds() / 60.0+ return gap if gap > 0 else None+ except Exception:+ return None+++def _job_interval_minutes(job: dict) -> Optional[float]:+ """Best-effort interval length for a job, in minutes (None if unknown).++ Reads the PERSISTED schedule shape first: the job store keeps+ ``schedule`` as an already-parsed dict (``{"kind": "interval",+ "minutes": N}`` or ``{"kind": "cron", "expr": "..."}``), NOT the string+ form that ``parse_schedule`` consumes. The string path is kept only as+ a defensive fallback for programmatic callers that still build string+ schedules (and for tests that exercise that shape).++ ``kind == "once"`` (one-shot) has no recurring interval — returns None,+ so the sweep uses the documented floor allowance.+ """+ try:+ schedule = job.get("schedule")+ if isinstance(schedule, dict):+ kind = schedule.get("kind")+ if kind == "interval":+ minutes = schedule.get("minutes")+ return float(minutes) if minutes else None+ if kind == "cron":+ return _cron_interval_minutes(str(schedule.get("expr") or ""))+ return None+ if isinstance(schedule, str) and schedule.strip():+ from cron.jobs import parse_schedule++ parsed = parse_schedule(schedule) or {}+ if parsed.get("kind") == "interval":+ minutes = parsed.get("minutes")+ return float(minutes) if minutes else None+ if parsed.get("kind") == "cron":+ return _cron_interval_minutes(str(parsed.get("expr") or ""))+ except Exception:+ return None+ return None+++def get_inflight_guard_stats() -> dict:+ """Probe-visible snapshot of the in-flight guard.++ ``forced_releases`` is a monotonic counter of stale claims this process+ has force-released; any non-zero value means a cron job wedged and was+ recovered without a gateway restart.+ """+ now = time.time()+ with _running_lock:+ return {+ "running": sorted(_running_job_ids),+ "running_ages_seconds": {+ jid: round(now - started, 1)+ for jid, started in _running_since.items()+ },+ "forced_releases": _forced_release_count,+ "recent_forced_releases": list(_forced_releases),+ }+++def _record_forced_release(job_id: str, name: str, age_seconds: float, allowance_seconds: float) -> None:+ """Persist a countable signal for one forced release (best-effort)."""+ entry = {+ "job_id": job_id,+ "name": name,+ "age_seconds": round(age_seconds, 1),+ "allowance_seconds": round(allowance_seconds, 1),+ "at": _hermes_now().isoformat(),+ }+ with _running_lock:+ _forced_releases.append(entry)+ del _forced_releases[:-_FORCED_RELEASE_HISTORY]+ try:+ path = _get_hermes_home() / "cron" / "inflight_forced_releases.jsonl"+ path.parent.mkdir(parents=True, exist_ok=True)+ with open(path, "a", encoding="utf-8") as fh:+ fh.write(json.dumps(entry) + "\n")+ except Exception as e: # never let telemetry break a tick+ logger.debug("Could not append forced-release record: %s", e)+++def sweep_stale_inflight(due_jobs: Optional[list] = None) -> list:+ """Force-release in-flight claims that can no longer be making progress.++ A claim is stale when it is older than ``max(2 * interval, floor)`` AND+ either has no live future at all (the wedge class: the claim was taken+ but the release path was never installed — e.g. a hang in the submit+ path before ``pool.submit`` returned) or has a future that already+ finished without discarding the id.++ Every release logs a WARNING with the countable ``event=forced_release``+ signal, bumps a probe-visible counter (``get_inflight_guard_stats()``),+ mirrors a JSONL row under the cron dir, and writes ``last_error`` on the+ job so the wedge surfaces on the job row instead of being invisible+ until a downstream liveness key goes dead hours later. A forced release+ never consumes a finite-repeat job's budget (see below).++ Returns the list of released job ids.+ """+ global _forced_release_count++ by_id = {j.get("id"): j for j in (due_jobs or []) if isinstance(j, dict)}+ floor_seconds = _inflight_min_allowance_minutes() * 60.0+ now = time.time()+ stale: list = []++ with _running_lock:+ for job_id in list(_running_job_ids):+ started = _running_since.get(job_id)+ if started is None:+ # Claim predates this guard (or was injected directly) — adopt+ # it now so it becomes sweepable one allowance from here.+ _running_since[job_id] = now+ continue+ age = now - started+ interval_minutes = _job_interval_minutes(by_id.get(job_id) or {})+ allowance = floor_seconds+ if interval_minutes:+ allowance = max(allowance, 2.0 * interval_minutes * 60.0)+ if age < allowance:+ continue+ fut = _running_futures.get(job_id)+ if fut is _FUTURE_PENDING:+ # The claim is past its allowance and the owning future still+ # has not been installed — the submit path itself (SessionDB+ # init, agent import, config load) hung before ``pool.submit``+ # returned. That is exactly the wedge class; release it.+ pass+ elif fut is not None and not fut.done():+ continue # genuinely still executing+ _running_job_ids.discard(job_id)+ _running_since.pop(job_id, None)+ _running_futures.pop(job_id, None)+ _forced_release_count += 1+ stale.append((job_id, age, allowance, fut))++ for job_id, age, allowance, fut in stale:+ job = by_id.get(job_id) or {}+ name = job.get("name") or job_id+ if fut is _FUTURE_PENDING:+ future_state = "pending"+ elif fut is None:+ future_state = "missing"+ else:+ future_state = "finished"+ logger.warning(+ "cron.inflight.forced_release event=forced_release job='%s' id=%s "+ "age=%.0fs allowance=%.0fs future=%s — stale in-flight claim "+ "released; the job was skipping every fire with 'already running'",+ name,+ job_id,+ age,+ allowance,+ future_state,+ )+ _record_forced_release(job_id, name, age, allowance)+ # Finite-repeat guard: a forced release is NOT a real run, so it must+ # not consume a finite one-shot's repeat budget or let mark_job_run+ # auto-delete the row (completed >= times). The claim is released and+ # the row is left untouched, so the job re-fires normally on its next+ # due tick (self-heal) instead of being deleted.+ repeat = job.get("repeat") or {}+ if isinstance(repeat, dict) and repeat.get("times") is not None:+ logger.warning(+ "cron.inflight.forced_release.job_untouched job='%s' id=%s — "+ "finite-repeat job released without mark_job_run (repeat budget "+ "preserved); row left in place so it re-fires normally",+ name,+ job_id,+ )+ continue+ try:+ mark_job_run(+ job_id,+ False,+ f"Stale in-flight claim force-released after {age / 60:.1f}m "+ f"(allowance {allowance / 60:.1f}m); previous run never released "+ f"the scheduler in-flight guard",+ )+ except Exception as e:+ logger.warning("Could not record forced release for job %s: %s", job_id, e)++ return [s[0] for s in stale]def mark_running_jobs_interrupted(reason: str) -> list:@@ -5204,6 +5476,23 @@ def tick(due_jobs = get_due_jobs()+ # Bound the in-flight set BEFORE the dedup guard is consulted, so a+ # leaked claim is force-released in-cycle rather than silently eating+ # every subsequent fire until the gateway process restarts. Runs even+ # when nothing is due — a wedged job's own fires are exactly what the+ # leak suppresses (t_3778a491; recurring no_agent router/watchdog jobs,+ # 2026-08-14 t_20e23f84).+ try:+ from cron.jobs import load_jobs as _load_all_jobs++ _all_jobs = _load_all_jobs()+ except Exception:+ _all_jobs = due_jobs+ try:+ sweep_stale_inflight(_all_jobs)+ except Exception as e:+ logger.warning("Stale in-flight sweep failed: %s", e)+if not due_jobs:# Idle tick: skip config load + pool partitioning entirely# (#33612 — the gateway ticker calls tick(verbose=False) every@@ -5301,9 +5590,18 @@ def tick(return None# Record the attempt before executor dispatch. Recovery classifies# abandoned records as unknown; it never automatically retries them.- execution = create_execution(job_id, source="builtin")- dispatched_job = dict(job, execution_id=execution["id"])- _ctx = contextvars.copy_context()+ try:+ execution = create_execution(job_id, source="builtin")+ dispatched_job = dict(job, execution_id=execution["id"])+ _ctx = contextvars.copy_context()+ except BaseException:+ # Init/creation failure between the claim and the submit —+ # release the in-flight claim immediately so the next tick can+ # retry instead of wedging on 'already running' forever (the+ # audit requirement: every add is paired with guaranteed+ # cleanup). Re-raise so the caller sees the failure.+ release_running_job(job_id)+ raisedef _run_and_release(j=dispatched_job, ctx=_ctx):try:@@ -5312,7 +5610,7 @@ def tick(release_running_job(j["id"])try:- return pool.submit(_run_and_release)+ fut = pool.submit(_run_and_release)except Exception as submit_err:release_running_job(job_id)finish_execution(@@ -5335,6 +5633,13 @@ def tick()return None+ # Record the owning future so the stale sweep can distinguish+ # "still executing" from "claim leaked before/after the future".+ with _running_lock:+ if job_id in _running_job_ids:+ _running_futures[job_id] = fut+ return fut+# Sequential pass for env-mutating (workdir) jobs.# Queued to a persistent single-thread pool so they run one at a time# WITHOUT blocking the ticker thread — a long workdir job nodiff --git a/tests/cron/test_inflight_stale_guard.py b/tests/cron/test_inflight_stale_guard.pynew file mode 100644index 00000000000..7787da685da--- /dev/null+++ b/tests/cron/test_inflight_stale_guard.py@@ -0,0 +1,350 @@+"""RED-first regression test for the cron in-flight claim leak (t_27b59583).++The leak+--------+``cron/scheduler.py`` tracks in-flight cron jobs in the module-level+``_running_job_ids`` set. ``_submit_with_guard`` adds a job id BEFORE the+future that owns its release exists: everything between the add and+``pool.submit`` — ``create_execution``, ``contextvars.copy_context()``, and+once running, the whole pre-future body of ``run_one_job`` (SessionDB+construction around L3150-3161, agent import/build, config load) — has no+``finally`` that discards the id. If any of it throws or hangs, the release+path in ``_run_and_release``'s ``finally`` never runs. Every later tick then+short-circuits with ``cron.scheduler: Job '<x>' already running — skipping``+with no ``last_error``, no failure counter, and no alert, until the whole+gateway process restarts (incident: jarvis ``board-pm-triage-*`` jobs,+2026-08-02).++This file is committed BEFORE the fix (red-first). Against the unfixed+scheduler these tests MUST FAIL: the stale id is never released, so the+primary assertion (``job_id not in get_running_job_ids()`` after a tick)+fails. The implementation task (t_3778a491) makes them pass by adding the+bounded stale-entry guard: on each tick, a claim older than+``max(2 * interval, floor)`` with no live future is force-released, logged+with a countable ``cron.inflight.forced_release`` signal, and surfaced via+``mark_job_run(..., success=False, error=...)`` as ``last_error``.++Design notes+------------+- The job store persists ``schedule`` as an already-parsed DICT+ (``{"kind": "interval", "minutes": N}``), not the string form+ ``parse_schedule`` consumes — the fixtures use the persisted dict shape.+- The guard's age bookkeeping (``_running_since`` / ``_running_futures`` /+ ``get_inflight_guard_stats``) does not exist yet on the unfixed scheduler.+ The helpers reference it defensively (``getattr``/``hasattr``) so the SAME+ file runs cleanly against both the red (unfixed) and the green (fixed)+ implementation; the leak simulation is identical either way — an id in+ ``_running_job_ids`` with no future ever installed.+"""++import time+from unittest.mock import patch++import pytest++import cron.scheduler as sched++[email protected](autouse=True)+def _clean_inflight():+ """Reset the in-memory running set so tests are isolated.++ Clears the guard bookkeeping defensively: on the unfixed scheduler only+ ``_running_job_ids`` exists; the age/future dicts and counters appear+ with the fix, and clearing them keeps the same file hermetic on both.+ """+ sched._running_job_ids.clear()+ for attr in ("_running_since", "_running_futures", "_forced_releases"):+ obj = getattr(sched, attr, None)+ if obj is not None:+ obj.clear()+ if hasattr(sched, "_forced_release_count"):+ sched._forced_release_count = 0+ yield+ sched._running_job_ids.clear()+ for attr in ("_running_since", "_running_futures", "_forced_releases"):+ obj = getattr(sched, attr, None)+ if obj is not None:+ obj.clear()+++def _job(job_id="wedged", minutes=60, kind="interval", cron_expr=None,+ repeat=None):+ """Build a job row using the PERSISTED schedule dict shape."""+ if kind == "interval":+ schedule = {+ "kind": "interval",+ "minutes": minutes,+ "display": f"every {minutes}m",+ }+ elif kind == "cron":+ expr = cron_expr or "0 9 * * 1"+ schedule = {"kind": "cron", "expr": expr, "display": expr}+ else:+ schedule = {+ "kind": "once",+ "run_at": "2030-01-01T00:00:00",+ "display": "once at 2030-01-01 00:00",+ }+ job = {+ "id": job_id,+ "name": f"board-pm-triage-{job_id}",+ "schedule": schedule,+ }+ if repeat is not None:+ job["repeat"] = repeat+ return job+++def _inject_stale_claim(job_id: str) -> None:+ """Simulate the leak exactly as the incident left it: the job id is in+ the running set but no future was ever installed, so the release path in+ the worker's ``finally`` can never run.++ On the unfixed scheduler ``_running_job_ids`` is the only bookkeeping, so+ this is precisely the shape of the real wedge. Once the bounded guard+ lands it also records an old start time — 6h ago, far past+ ``max(2 * 60m interval, 30m floor)`` — so the claim is past its+ allowance on the first sweep.+ """+ sched._running_job_ids.add(job_id)+ running_since = getattr(sched, "_running_since", None)+ if running_since is not None:+ running_since[job_id] = time.time() - 6 * 60 * 60 # 6h old+++class TestStaleInflightLeak:+ def test_stale_claim_is_force_released_and_reported_after_tick(+ self, tmp_path, caplog+ ):+ """The regression: a leaked in-flight claim must be force-released by+ the next tick, surface as ``last_error``, and emit a countable+ signal — instead of silently skipping every fire until the gateway+ process restarts."""+ job = _job(job_id="board-pm-triage-wedged", minutes=60)+ job_id = job["id"]+ _inject_stale_claim(job_id)++ with caplog.at_level("WARNING"), \+ patch.object(sched, "_get_hermes_home", return_value=tmp_path), \+ patch("cron.jobs.load_jobs", return_value=[job]), \+ patch.object(sched, "get_due_jobs", return_value=[]), \+ patch.object(sched, "mark_job_run") as mark:+ sched.tick(verbose=False)++ # RED: on the unfixed scheduler the tick never releases the id — it+ # short-circuits with "already running — skipping" and the id stays+ # in the set forever, so this assertion FAILS and proves the leak.+ assert job_id not in sched.get_running_job_ids()++ # GREEN (after the bounded guard): the release surfaces as a failure+ # on the job row instead of silence…+ assert mark.call_count == 1+ args = mark.call_args.args+ assert args[0] == job_id+ assert args[1] is False+ assert "in-flight" in args[2]++ # …and emits the countable forced-release signal (log + probe stats).+ assert any(+ "cron.inflight.forced_release" in r.message for r in caplog.records+ )+ stats = sched.get_inflight_guard_stats()+ assert stats["forced_releases"] == 1++ def test_young_inflight_claim_is_not_force_released(self, tmp_path):+ """Bound the guard: a claim younger than its allowance (and with no+ future) is left alone — the sweep must not double-dispatch healthy+ long-running jobs. Passes on both the red and the fixed code."""+ job = _job(job_id="young", minutes=60)+ job_id = job["id"]+ sched._running_job_ids.add(job_id)+ running_since = getattr(sched, "_running_since", None)+ if running_since is not None:+ running_since[job_id] = time.time() - 60 # 1 minute old++ with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \+ patch("cron.jobs.load_jobs", return_value=[job]), \+ patch.object(sched, "get_due_jobs", return_value=[]), \+ patch.object(sched, "mark_job_run") as mark:+ sched.tick(verbose=False)++ assert job_id in sched.get_running_job_ids()+ mark.assert_not_called()+++class TestJobIntervalMinutes:+ """Allowance inputs come from the PERSISTED dict schedule shape, not the+ string form parse_schedule consumes (review Blocker 1)."""++ def test_reads_persisted_interval_dict(self):+ job = _job(minutes=4320)+ assert sched._job_interval_minutes(job) == 4320.0++ def test_reads_persisted_cron_dict(self):+ # */15 every 15 minutes → cadence 15m.+ job = _job(kind="cron", cron_expr="*/15 * * * *")+ assert sched._job_interval_minutes(job) == 15.0++ def test_reads_persisted_weekly_cron_dict(self):+ # 0 9 * * 1 fires weekly → cadence 7*24*60 = 10080m.+ job = _job(kind="cron", cron_expr="0 9 * * 1")+ assert sched._job_interval_minutes(job) == 7 * 24 * 60++ def test_string_fallback_still_works(self):+ # Defensive fallback for programmatic callers.+ job = {"id": "x", "schedule": "every 60m"}+ assert sched._job_interval_minutes(job) == 60.0++ def test_oneshot_has_no_interval(self):+ job = _job(kind="once")+ assert sched._job_interval_minutes(job) is None++ def test_garbage_returns_none(self):+ job = {"id": "x", "schedule": {"kind": "bogus"}}+ assert sched._job_interval_minutes(job) is None+++class TestStaleInflightSweep:+ """Unit-level bound checks on sweep_stale_inflight itself."""++ def test_allowance_is_at_least_two_intervals(self, tmp_path):+ """A slow-but-healthy 6h job is not clipped by the 30m floor."""+ job = _job(minutes=360)+ sched._running_job_ids.add(job["id"])+ sched._running_since[job["id"]] = time.time() - 4 * 60 * 60 # 4h < 12h++ with patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ assert sched.sweep_stale_inflight([job]) == []+ assert job["id"] in sched.get_running_job_ids()++ def test_allowance_honors_persisted_4320m_row(self, tmp_path):+ """The real guide-curator row (4320m) gets a 144h allowance, not the+ 30m floor — the Blocker-1 regression against the live store shape."""+ job = _job(job_id="guide-curator", minutes=4320)+ sched._running_job_ids.add(job["id"])+ sched._running_since[job["id"]] = time.time() - 4 * 60 * 60 # 4h ≪ 144h++ with patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ assert sched.sweep_stale_inflight([job]) == []+ assert job["id"] in sched.get_running_job_ids()++ def test_cron_allowance_not_clipped_to_floor(self, tmp_path):+ """A weekly cron job (cadence 10080m) is not clipped at 30m: a 24h+ claim is still healthy (allowance 20160m)."""+ job = _job(job_id="weekly", kind="cron", cron_expr="0 9 * * 1")+ sched._running_job_ids.add(job["id"])+ sched._running_since[job["id"]] = time.time() - 24 * 60 * 60++ with patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ assert sched.sweep_stale_inflight([job]) == []+ assert job["id"] in sched.get_running_job_ids()++ def test_live_future_is_never_released(self, tmp_path):+ """A claim with a genuinely executing future is left alone even when+ old — the sweep must not double-dispatch healthy long-running jobs."""+ import concurrent.futures++ job = _job()+ fut: concurrent.futures.Future = concurrent.futures.Future()+ sched._running_job_ids.add(job["id"])+ sched._running_since[job["id"]] = time.time() - 10 * 60 * 60+ sched._running_futures[job["id"]] = fut++ with patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ assert sched.sweep_stale_inflight([job]) == []+ assert job["id"] in sched.get_running_job_ids()+ fut.set_result(True)++ # Once the future is done but the id somehow survived, it IS stale.+ with patch.object(sched, "mark_job_run"), \+ patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ assert sched.sweep_stale_inflight([job]) == [job["id"]]++ def test_pending_sentinel_released_when_submit_hung(self, tmp_path):+ """A claim whose submit path hung stays _FUTURE_PENDING past its+ allowance (the SessionDB-init wedge class) and must be released."""+ job = _job()+ sched._running_job_ids.add(job["id"])+ sched._running_since[job["id"]] = time.time() - 5 * 60 * 60+ sched._running_futures[job["id"]] = sched._FUTURE_PENDING++ with patch.object(sched, "mark_job_run") as mark, \+ patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ assert sched.sweep_stale_inflight([job]) == [job["id"]]+ assert mark.call_count == 1++ def test_pending_sentinel_young_claim_is_not_released(self, tmp_path):+ """A young pending claim (submit still in flight) is safe."""+ job = _job()+ sched._running_job_ids.add(job["id"])+ sched._running_since[job["id"]] = time.time() - 60 # 1 minute+ sched._running_futures[job["id"]] = sched._FUTURE_PENDING++ with patch.object(sched, "mark_job_run") as mark, \+ patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ assert sched.sweep_stale_inflight([job]) == []+ assert job["id"] in sched.get_running_job_ids()+ mark.assert_not_called()++ def test_finite_repeat_job_released_without_mark_job_run(self, tmp_path):+ """A forced release must not consume a finite repeat budget or+ auto-delete the row; the claim is released, the row untouched."""+ job = _job(repeat={"times": 1, "completed": 0})+ sched._running_job_ids.add(job["id"])+ sched._running_since[job["id"]] = time.time() - 5 * 60 * 60++ with patch.object(sched, "mark_job_run") as mark, \+ patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ assert sched.sweep_stale_inflight([job]) == [job["id"]]+ assert job["id"] not in sched.get_running_job_ids()+ mark.assert_not_called()+ assert sched.get_inflight_guard_stats()["forced_releases"] == 1++ def test_claim_without_timestamp_is_adopted_then_swept(self, tmp_path):+ """An id injected with no recorded start (pre-guard claim) must not be+ released immediately, but must become sweepable."""+ job = _job()+ sched._running_job_ids.add(job["id"])++ with patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ assert sched.sweep_stale_inflight([job]) == []+ assert job["id"] in sched._running_since+ sched._running_since[job["id"]] -= 5 * 60 * 60+ with patch.object(sched, "mark_job_run"):+ assert sched.sweep_stale_inflight([job]) == [job["id"]]++ def test_forced_release_logs_a_warning(self, tmp_path, caplog):+ job = _job()+ sched._running_job_ids.add(job["id"])+ sched._running_since[job["id"]] = time.time() - 5 * 60 * 60++ with caplog.at_level("WARNING"), \+ patch.object(sched, "mark_job_run"), \+ patch.object(sched, "_get_hermes_home", return_value=tmp_path):+ sched.sweep_stale_inflight([job])++ assert any("cron.inflight.forced_release" in r.message for r in caplog.records)+++class TestWedgedJobRefiresWithoutRestart:+ def test_tick_sweeps_then_dispatches_the_previously_wedged_job(self, tmp_path):+ """End-to-end symptom: before the fix, tick() returned 0 forever."""+ job = dict(_job(), enabled=True, next_run_at="2020-01-01T00:00:00",+ deliver="local")+ sched._running_job_ids.add(job["id"])+ sched._running_since[job["id"]] = time.time() - 6 * 60 * 60++ with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \+ patch.object(sched, "get_due_jobs", return_value=[job]), \+ patch("cron.jobs.load_jobs", return_value=[job]), \+ patch.object(sched, "advance_next_runs"), \+ patch.object(sched, "mark_job_run"), \+ patch.object(sched, "create_execution", return_value={"id": "exec-1"}), \+ patch.object(sched, "finish_execution"), \+ patch.object(sched, "run_one_job", return_value=True):+ n = sched.tick(verbose=False)++ assert n == 1, "wedged job must fire again without a gateway restart"+ assert job["id"] not in sched.get_running_job_ids()+ assert sched.get_inflight_guard_stats()["forced_releases"] == 1diff --git a/tests/cron/test_recurring_eagain_redispatch.py b/tests/cron/test_recurring_eagain_redispatch.pynew file mode 100644index 00000000000..74a28eb32ff--- /dev/null+++ b/tests/cron/test_recurring_eagain_redispatch.py@@ -0,0 +1,153 @@+"""Deterministic reproduction of the recurring-cron EAGAIN wedge (t_8b5480b3).++Scenario modelled on the 2026-08-14 incident: a recurring no_agent interval job+whose script subprocess raises EAGAIN ([Errno 11] Resource temporarily+unavailable) during a substrate thread-exhaustion spike. After the failure is+recorded (terminal 'failed' execution row), the job must be re-dispatched on+the NEXT tick once the substrate recovers — with no force-run.++The os-reviewer (t_20e23f84) established the real incident wedge: 4 recurring+no_agent jobs recorded ZERO executions for ~1h47m after EAGAIN while+`next_run_at` kept advancing (they stayed 'due') but `_submit_with_guard`+never dispatched them, and the wedge SURVIVED a gateway restart. That points+at a PERSISTED non-dispatch state, not just the in-memory `_running_job_ids`+leak (which t_3778a491 already bounds).++This file drives the REAL `tick()` end-to-end against a throwaway HERMES_HOME:+ tick 1 -> script EAGAINs (subprocess.run raises OSError 11) -> failed exec row+ tick 2 -> substrate recovered (script runs clean) -> job MUST fire again+"""+from __future__ import annotations++import json+import os+import subprocess+from datetime import datetime, timedelta, timezone+from pathlib import Path+from unittest import mock++import pytest++# Ensure project root importable+import sys+sys.path.insert(0, str(Path(__file__).parent.parent.parent))+++def wedge_env(tmp_path, monkeypatch):+ """Isolated cron env + a recurring no_agent interval job, due NOW."""+ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ (hermes_home / "cron").mkdir()+ (hermes_home / "cron" / "output").mkdir()+ (hermes_home / "scripts").mkdir()+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))++ import cron.jobs as jobs_mod+ monkeypatch.setattr(jobs_mod, "HERMES_DIR", hermes_home)+ monkeypatch.setattr(jobs_mod, "CRON_DIR", hermes_home / "cron")+ monkeypatch.setattr(jobs_mod, "JOBS_FILE", hermes_home / "cron" / "jobs.json")+ monkeypatch.setattr(jobs_mod, "OUTPUT_DIR", hermes_home / "cron" / "output")++ # Create a recurring no_agent interval job.+ job = jobs_mod.create_job(+ prompt="probe",+ schedule="every 10m",+ no_agent=True,+ script="probe.py",+ )+ # Force it due now.+ now = datetime.now(timezone.utc)+ jobs_mod.update_job(job["id"], {"next_run_at": (now - timedelta(minutes=1)).isoformat()})++ script = hermes_home / "scripts" / "probe.py"+ script.write_text("print('ok')\n")++ return {"home": hermes_home, "job_id": job["id"]}+++class TestEAGAINRecurringRedispatches:+ def _make_script_eagain(self, env, monkeypatch):+ """Make the next subprocess.run raise EAGAIN once, then pass."""+ import cron.scheduler as sched_mod+ real_run = sched_mod.subprocess.run+ state = {"n": 0}++ def fake_run(argv, **kwargs):+ state["n"] += 1+ if state["n"] == 1:+ raise OSError(11, "Resource temporarily unavailable")+ return subprocess.CompletedProcess(argv, 0, stdout="ok\n", stderr="")++ monkeypatch.setattr(sched_mod.subprocess, "run", fake_run)+ return state++ def test_eagain_then_redispatched_on_next_tick(self, wedge_env, monkeypatch, tmp_path):+ """Tick 1 records a failed execution (EAGAIN); tick 2 must re-fire."""+ from cron import scheduler as S+ from cron import executions as E++ env = wedge_env+ # Point the executions ledger at the throwaway home.+ monkeypatch.setattr(E, "EXECUTIONS_FILE", env["home"] / "cron" / "executions.db")+ monkeypatch.setattr(S, "_hermes_home", env["home"])+ monkeypatch.setattr(S, "get_due_jobs", S.get_due_jobs) # no-op, keep real++ state = self._make_script_eagain(env, monkeypatch)++ # Tick 1: EAGAIN failure.+ n1 = S.tick(verbose=False, sync=True)+ # Assert the failure was recorded.+ latest = E.latest_execution(env["job_id"])+ assert latest is not None, "tick 1 must create an execution"+ assert latest["status"] == "failed", f"expected failed, got {latest['status']}"++ # The job must still be scheduled (recurring), next_run_at advanced.+ import cron.jobs as J+ job = J.get_job(env["job_id"])+ assert job["enabled"] is True+ assert job["state"] == "scheduled"+ assert job["next_run_at"] is not None++ # Force next_run_at due again (simulate the substrate recovery tick).+ now = datetime.now(timezone.utc)+ J.update_job(env["job_id"], {"next_run_at": (now - timedelta(minutes=1)).isoformat()})++ # Tick 2: script passes -> job must fire (completed execution).+ n2 = S.tick(verbose=False, sync=True)+ latest2 = E.latest_execution(env["job_id"])+ assert latest2 is not None+ assert latest2["status"] == "completed", (+ f"job must be re-dispatched after EAGAIN recovery, got {latest2['status']}"+ )+ assert state["n"] >= 2++ def test_trigger_job_unwedges_persisted_state(self, wedge_env, monkeypatch, tmp_path):+ """The incident force-run (`cron run <id>` -> trigger_job) resets the+ persisted due state so the next tick fires the job. This is the+ operator escape that cleared each wedge."""+ from cron import scheduler as S+ from cron import executions as E+ from cron.jobs import trigger_job, update_job++ env = wedge_env+ monkeypatch.setattr(E, "EXECUTIONS_FILE", env["home"] / "cron" / "executions.db")+ monkeypatch.setattr(S, "_hermes_home", env["home"])++ self._make_script_eagain(env, monkeypatch)+ n1 = S.tick(verbose=False, sync=True)++ # Simulate the persisted non-dispatch state: next_run_at far in the+ # future (job not due) but still enabled/scheduled — the observed+ # wedge where get_due_jobs never returns it.+ from datetime import timezone as tz+ far = datetime.now(tz.utc) + timedelta(days=1)+ update_job(env["job_id"], {"next_run_at": far.isoformat()})+ n2 = S.tick(verbose=False, sync=True) # not due -> no dispatch++ # Force-run (trigger_job) sets next_run_at = now -> due again.+ triggered = trigger_job(env["job_id"])+ assert triggered is not None+ n3 = S.tick(verbose=False, sync=True)+ latest = E.latest_execution(env["job_id"])+ assert latest["status"] == "completed", "force-run must clear the wedge"diff --git a/tests/cron/test_recurring_wedge_selfheal.py b/tests/cron/test_recurring_wedge_selfheal.pynew file mode 100644index 00000000000..406df99c84e--- /dev/null+++ b/tests/cron/test_recurring_wedge_selfheal.py@@ -0,0 +1,239 @@+"""Deterministic reproduction of the recurring-cron wedge (t_8b5480b3) — RED/GREEN.++The 2026-08-14 incident (t_20e23f84): 4 recurring no_agent interval jobs+EAGAIN-failed at 12:50:05 and then recorded ZERO executions for ~1h47m while+the scheduler ticked normally and fired 100+ other jobs — wedged in a+non-dispatch state that even survived a gateway restart, cleared only by a+manual force-run (`hermes cron run <id>`).++Root cause class (t_3778a491, the SAME symptom on 2026-08-02): `_submit_with_guard`+adds a job id to the in-memory `_running_job_ids` set BEFORE the future that+owns its release exists. Anything that hangs or dies between the add and+`pool.submit` (documented case: EAGAIN thread exhaustion on a substrate spike,+or a wedged SessionDB.__init__ on a stale sqlite flock) leaks the claim. Every+later tick short-circuits with "already running — skipping" silently — no+execution row, no last_error, no counter — so the job is due-but-never-dispatched.++The live deployment (origin/main) does NOT contain the t_3778a491 in-flight+stale-claim sweep, so the wedge class is still live.++This file drives the REAL `tick()` and asserts the fix's contract:+ RED (unfixed): a stale in-flight claim is never released by tick → the+ wedge reproduces deterministically (job stays in the running set, no+ execution, no re-dispatch without force-run).+ GREEN (fixed): the same stale claim is force-released by the next tick+ (cron.inflight.forced_release) and the job re-fires — no gateway+ restart, no force-run needed — and 2 consecutive auto-fires work.+"""+from __future__ import annotations++import sys+import time+from datetime import datetime, timedelta, timezone+from pathlib import Path+from unittest import mock++import pytest++sys.path.insert(0, str(Path(__file__).parent.parent.parent))+++def cron_env(tmp_path, monkeypatch):+ """Isolated cron env + a recurring no_agent interval job, due NOW."""+ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ (hermes_home / "cron").mkdir()+ (hermes_home / "cron" / "output").mkdir()+ (hermes_home / "scripts").mkdir()+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))++ import cron.jobs as jobs_mod+ monkeypatch.setattr(jobs_mod, "HERMES_DIR", hermes_home)+ monkeypatch.setattr(jobs_mod, "CRON_DIR", hermes_home / "cron")+ monkeypatch.setattr(jobs_mod, "JOBS_FILE", hermes_home / "cron" / "jobs.json")+ monkeypatch.setattr(jobs_mod, "OUTPUT_DIR", hermes_home / "cron" / "output")++ job = jobs_mod.create_job(+ prompt="probe",+ schedule="every 10m",+ no_agent=True,+ script="probe.py",+ )+ now = datetime.now(timezone.utc)+ jobs_mod.update_job(job["id"], {"next_run_at": (now - timedelta(minutes=1)).isoformat()})++ script = hermes_home / "scripts" / "probe.py"+ script.write_text("print('ok')\n")++ return {"home": hermes_home, "job_id": job["id"]}+++class TestStaleInflightSelfHeal:+ def _setup(self, cron_env, monkeypatch):+ from cron import scheduler as S+ from cron import executions as E++ env = cron_env+ monkeypatch.setattr(E, "EXECUTIONS_FILE", env["home"] / "cron" / "executions.db")+ monkeypatch.setattr(S, "_hermes_home", env["home"])+ return S, E, env++ def test_stale_claim_self_heals_and_redispatches(self, cron_env, monkeypatch):+ """GREEN contract: a leaked in-flight claim is force-released by the+ next tick and the wedged job re-fires without a force-run."""+ S, E, env = self._setup(cron_env, monkeypatch)+ job_id = env["job_id"]+ import cron.jobs as J++ if not hasattr(S, "sweep_stale_inflight"):+ pytest.skip("guard not present on this build")++ # Simulate the incident leak: job id claimed with no owning future,+ # old enough to be past its allowance.+ S._running_job_ids.clear()+ S._running_since.clear()+ S._running_futures.clear()+ S._running_job_ids.add(job_id)+ S._running_since[job_id] = time.time() - 6 * 60 * 60++ # get_due_jobs is called inside tick BEFORE the sweep; we patch it to+ # return the wedged job as due so the in-cycle sweep releases the claim+ # and the dispatch loop re-fires it.+ job = J.get_job(job_id)+ with mock.patch("cron.jobs.load_jobs", return_value=[job]):+ n = S.tick(verbose=False, sync=True)++ latest = E.latest_execution(job_id)+ assert job_id not in S.get_running_job_ids(), "stale claim must be released"+ assert latest is not None, "wedged job must create an execution"+ assert latest["status"] == "completed", (+ "wedged job must fire again without force-run"+ )++ def test_two_consecutive_auto_fires_after_guard(self, cron_env, monkeypatch):+ """GREEN: after the guard releases a stale claim, the job fires on+ consecutive ticks (no manual intervention)."""+ S, E, env = self._setup(cron_env, monkeypatch)+ job_id = env["job_id"]+ import cron.jobs as J++ if not hasattr(S, "sweep_stale_inflight"):+ pytest.skip("guard not present on this build")++ S._running_job_ids.clear()+ S._running_since.clear()+ S._running_futures.clear()+ S._running_job_ids.add(job_id)+ S._running_since[job_id] = time.time() - 6 * 60 * 60++ job = J.get_job(job_id)+ with mock.patch("cron.jobs.load_jobs", return_value=[job]):+ n1 = S.tick(verbose=False, sync=True)+ latest1 = E.latest_execution(job_id)+ assert latest1["status"] == "completed"++ # Re-arm due and tick again: fire #2.+ now = datetime.now(timezone.utc)+ J.update_job(job_id, {"next_run_at": (now - timedelta(minutes=1)).isoformat()})+ n2 = S.tick(verbose=False, sync=True)+ latest2 = E.latest_execution(job_id)+ assert latest2["status"] == "completed"+ assert latest2["id"] != latest1["id"], "two distinct executions"++ def test_guard_stats_reported(self, cron_env, monkeypatch):+ """The guard must surface a countable forced-release signal."""+ S, E, env = self._setup(cron_env, monkeypatch)+ import cron.jobs as J+ if not hasattr(S, "sweep_stale_inflight"):+ pytest.skip("guard not present on this build")++ S._running_job_ids.clear()+ S._running_since.clear()+ S._running_futures.clear()+ S._running_job_ids.add(env["job_id"])+ S._running_since[env["job_id"]] = time.time() - 6 * 60 * 60+ S.sweep_stale_inflight([J.get_job(env["job_id"])])+ stats = S.get_inflight_guard_stats()+ assert stats["forced_releases"] >= 1+ assert env["job_id"] not in S.get_running_job_ids()+++class TestEAGAINCreateExecutionLeak:+ """The 12:50 mechanism: EAGAIN/thread-exhaustion strikes BETWEEN the+ in-flight claim and execution creation (create_execution / pool.submit).+ The claim must be released immediately so the next tick re-dispatches."""++ def test_create_execution_failure_releases_claim(self, cron_env, monkeypatch, tmp_path):+ from cron import scheduler as S+ from cron import executions as E+ import cron.jobs as J++ env = cron_env+ monkeypatch.setattr(E, "EXECUTIONS_FILE", env["home"] / "cron" / "executions.db")+ monkeypatch.setattr(S, "_hermes_home", env["home"])+ job_id = env["job_id"]+ job = J.get_job(job_id)++ S._running_job_ids.clear()+ S._running_since.clear()+ S._running_futures.clear()++ # Simulate EAGAIN during create_execution (substrate thread exhaustion+ # at 12:50): the in-flight claim was taken but execution creation fails.+ def boom(*a, **k):+ raise OSError(11, "Resource temporarily unavailable")+ monkeypatch.setattr(S, "create_execution", boom)++ with mock.patch("cron.jobs.load_jobs", return_value=[job]):+ with pytest.raises(OSError):+ S.tick(verbose=False, sync=True)++ # The claim must be released (not leaked) so the NEXT tick can retry.+ assert job_id not in S.get_running_job_ids(), (+ "claim must be released when execution creation fails, so the "+ "next tick re-dispatches instead of wedging on 'already running'"+ )++ def test_pool_submit_eagain_releases_claim_and_redispatches(self, cron_env, monkeypatch, tmp_path):+ from cron import scheduler as S+ from cron import executions as E+ import cron.jobs as J++ env = cron_env+ monkeypatch.setattr(E, "EXECUTIONS_FILE", env["home"] / "cron" / "executions.db")+ monkeypatch.setattr(S, "_hermes_home", env["home"])+ job_id = env["job_id"]+ job = J.get_job(job_id)++ S._running_job_ids.clear()+ S._running_since.clear()+ S._running_futures.clear()++ # First tick: pool.submit raises EAGAIN (thread exhaustion). The claim+ # is released and the run recorded as failed.+ real_submit = S.concurrent.futures.ThreadPoolExecutor.submit+ state = {"n": 0}+ def flaky(self, *a, **k):+ state["n"] += 1+ if state["n"] == 1:+ raise OSError(11, "Resource temporarily unavailable")+ return real_submit(self, *a, **k)+ monkeypatch.setattr(S.concurrent.futures.ThreadPoolExecutor, "submit", flaky)++ with mock.patch("cron.jobs.load_jobs", return_value=[job]):+ S.tick(verbose=False, sync=True)++ # Claim released; job still scheduled.+ assert job_id not in S.get_running_job_ids()++ # Second tick (substrate recovered): job re-dispatches and completes.+ now = datetime.now(timezone.utc)+ J.update_job(job_id, {"next_run_at": (now - timedelta(minutes=1)).isoformat()})+ with mock.patch("cron.jobs.load_jobs", return_value=[J.get_job(job_id)]):+ S.tick(verbose=False, sync=True)++ latest = E.latest_execution(job_id)+ assert latest is not None and latest["status"] == "completed", (+ "job must re-dispatch on the next tick after EAGAIN recovery"+ )