Skip to content

The agent that grows with you

fix: ledger-terminal release only for rows belonging to THIS claim

kshitij6370134bfea9
diff --git a/cron/scheduler.py b/cron/scheduler.py
index ed3a1cf86db..4f5c924d462 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -857,21 +857,44 @@ def sweep_stale_inflight(due_jobs: Optional[list] = None) -> list:
# Latest durable execution per in-flight job id, loaded in one indexed
# query. Used for the persisted-state reconciliation below (t_8b5480b3):
- # an in-memory claim whose job's MOST RECENT execution row is terminal
+ # an in-memory claim whose OWN run's execution row is terminal
# (completed/failed/unknown) cannot represent a live run — the durable
# ledger proves that run already ended — so the claim is stale by
- # construction, regardless of its in-memory age. This closes the
- # restart-survival gap that the age-only sweep left open: the ledger is
- # written by the worker that ran the job and read by ANY ticker process
- # (including one that started AFTER the leak), so a leaked claim is
- # recoverable without force-run/resume and without depending on which
- # process happens to still hold it in memory.
+ # construction, regardless of its in-memory age. A leaked claim is then
+ # recoverable without force-run/resume. The snapshot for the query is
+ # taken under _running_lock: list(set) over a set concurrently mutated by
+ # try_register/release_running_job can raise RuntimeError mid-iteration.
+ with _running_lock:
+ _inflight_snapshot = list(_running_job_ids)
try:
from cron.executions import latest_executions as _latest_execs
- _latest = _latest_execs(list(_running_job_ids))
+ _latest = _latest_execs(_inflight_snapshot)
except Exception:
_latest = {}
+ def _row_belongs_to_claim(row: dict, claim_started: float) -> bool:
+ """True when the ledger row was claimed at/after this in-memory claim.
+
+ The latest terminal row proves THIS claim's run ended only if it was
+ created by this claim's dispatch (create_execution runs moments AFTER
+ try_register_running_job). A terminal row older than the in-memory
+ claim is the PREVIOUS run's outcome — for a recurring job that is the
+ common case in the window between try_register and create_execution,
+ and releasing on it would double-dispatch a healthy fresh claim.
+ Unparseable timestamps fail closed (row treated as previous-run; the
+ age-based path below still bounds the claim).
+ """
+ claimed_at = row.get("claimed_at")
+ if not claimed_at:
+ return False
+ try:
+ row_ts = datetime.fromisoformat(claimed_at)
+ if row_ts.tzinfo is None:
+ row_ts = row_ts.astimezone()
+ return row_ts.timestamp() >= claim_started
+ except (ValueError, TypeError, OSError):
+ return False
+
# Precompute job intervals OUTSIDE _running_lock so croniter evaluation
# does not block try_register/release_running_job for other jobs.
_intervals = {jid: _job_interval_minutes(j) for jid, j in by_id.items()}
@@ -899,17 +922,24 @@ def sweep_stale_inflight(due_jobs: Optional[list] = None) -> list:
elif fut is not None and not fut.done():
continue # genuinely still executing
# Persisted-state reconciliation: if the durable executions ledger
- # shows this job's last run reached a terminal state, the claim is
+ # shows THIS claim's run reached a terminal state, the claim is
# provably stale even if it is still inside its in-memory age
# allowance (or was adopted fresh this tick). Release it now so
# the job re-dispatches on the next tick without force-run/resume
- # (t_8b5480b3 — the 2026-08-14 recurring-router wedge that
- # survived a gateway restart because the in-memory age bound alone
- # could not see a run the ledger had already finished).
+ # (t_8b5480b3 — the 2026-08-14 recurring-router wedge where the
+ # in-memory age bound alone could not see a run the ledger had
+ # already finished). The row must belong to THIS claim
+ # (claimed_at >= claim registration): for a recurring job the
+ # latest terminal row is usually the PREVIOUS run's outcome —
+ # a fresh claim in the try_register→create_execution window, or a
+ # finished run whose worker finally hasn't released yet, would
+ # otherwise be force-released and double-dispatched.
if fut is None or fut is _FUTURE_PENDING or fut.done():
latest = _latest.get(job_id)
- if latest is not None and latest.get("status") in (
- "completed", "failed", "unknown",
+ if (
+ latest is not None
+ and latest.get("status") in ("completed", "failed", "unknown")
+ and _row_belongs_to_claim(latest, started)
):
_running_job_ids.discard(job_id)
_running_since.pop(job_id, None)
diff --git a/tests/cron/test_inflight_stale_guard.py b/tests/cron/test_inflight_stale_guard.py
index 08e4f2e1c16..c84b2994941 100644
--- a/tests/cron/test_inflight_stale_guard.py
+++ b/tests/cron/test_inflight_stale_guard.py
@@ -38,6 +38,7 @@ Design notes
"""
import time
+from datetime import datetime, timezone
from unittest.mock import patch
import pytest
@@ -367,8 +368,22 @@ class TestLedgerTerminalReconciliation:
claim with a terminal ledger row is NOT released — it stays wedged. With
the ledger reconciliation it IS released (and, because a terminal ledger
row is authoritative, WITHOUT a synthetic mark_job_run failure).
+
+ Race guard (salvage follow-up): the terminal row must belong to THIS
+ claim — ``claimed_at >= _running_since[job_id]``. A terminal row OLDER
+ than the in-memory claim is the PREVIOUS run's outcome (the normal state
+ for a recurring job between try_register_running_job and
+ create_execution, or while the worker's finally block hasn't released
+ yet) and must never force-release a healthy fresh claim.
"""
+ @staticmethod
+ def _row_at(offset_seconds: float) -> str:
+ """ISO claimed_at at now+offset (aware, local tz)."""
+ return datetime.fromtimestamp(
+ time.time() + offset_seconds, tz=timezone.utc
+ ).isoformat()
+
def _inject_young_claim(self, job_id: str) -> None:
"""Claim is YOUNG (inside the 30m floor) so only the ledger-terminal
path, never the age path, can release it."""
@@ -377,16 +392,18 @@ class TestLedgerTerminalReconciliation:
sched._running_since[job_id] = time.time() - 60 # 1 minute old
def test_young_claim_with_terminal_ledger_row_is_released(self, tmp_path):
- """RED/GREEN: a terminal ledger row proves the run ended, so a young
- leaked claim must be force-released even though its in-memory age is
- inside the allowance (the age-only sweep alone would leave it)."""
+ """RED/GREEN: a terminal ledger row from THIS claim's run proves the
+ run ended, so a young leaked claim must be force-released even though
+ its in-memory age is inside the allowance (the age-only sweep alone
+ would leave it)."""
job = _job(job_id="ledger-terminal", minutes=10)
job_id = job["id"]
self._inject_young_claim(job_id)
with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
patch("cron.executions.latest_executions", return_value={
- job_id: {"status": "failed", "id": "exec-x"},
+ job_id: {"status": "failed", "id": "exec-x",
+ "claimed_at": self._row_at(-30)}, # after claim (-60)
}), \
patch.object(sched, "mark_job_run") as mark:
released = sched.sweep_stale_inflight([job])
@@ -398,6 +415,47 @@ class TestLedgerTerminalReconciliation:
# Ledger-terminal is authoritative: no synthetic failure written.
mark.assert_not_called()
+ def test_terminal_row_from_previous_run_does_not_release_fresh_claim(self, tmp_path):
+ """RACE GUARD: a terminal row OLDER than the in-memory claim is the
+ PREVIOUS run's outcome — the fresh claim (e.g. in the window between
+ try_register_running_job and create_execution, or a finished run whose
+ worker finally hasn't run) must NOT be force-released; releasing it
+ would double-dispatch the job."""
+ job = _job(job_id="prev-run-terminal", minutes=10)
+ job_id = job["id"]
+ self._inject_young_claim(job_id)
+
+ with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
+ patch("cron.executions.latest_executions", return_value={
+ job_id: {"status": "completed", "id": "exec-prev",
+ "claimed_at": self._row_at(-600)}, # before claim (-60)
+ }), \
+ patch.object(sched, "mark_job_run"):
+ released = sched.sweep_stale_inflight([job])
+
+ assert job_id not in released, (
+ "previous run's terminal row must not release a fresh claim"
+ )
+ assert job_id in sched.get_running_job_ids()
+
+ def test_terminal_row_without_claimed_at_fails_closed(self, tmp_path):
+ """A terminal row with no parseable claimed_at cannot be attributed to
+ this claim — the ledger path must fail closed and leave the claim to
+ the age bound."""
+ job = _job(job_id="no-claimed-at", minutes=10)
+ job_id = job["id"]
+ self._inject_young_claim(job_id)
+
+ with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
+ patch("cron.executions.latest_executions", return_value={
+ job_id: {"status": "failed", "id": "exec-x"},
+ }), \
+ patch.object(sched, "mark_job_run"):
+ released = sched.sweep_stale_inflight([job])
+
+ assert job_id not in released
+ assert job_id in sched.get_running_job_ids()
+
def test_young_claim_without_ledger_row_is_not_released(self, tmp_path):
"""A young claim whose job has NO execution row at all (the claim was
taken but create_execution never ran) is left to the age bound — the
@@ -443,7 +501,8 @@ class TestLedgerTerminalReconciliation:
with patch.object(sched, "_get_hermes_home", return_value=tmp_path), \
patch("cron.executions.latest_executions", return_value={
- job_id: {"status": "completed", "id": "exec-z"},
+ job_id: {"status": "completed", "id": "exec-z",
+ "claimed_at": self._row_at(-3 * 60 * 60)}, # after claim (-6h)
}), \
patch.object(sched, "mark_job_run") as mark:
released = sched.sweep_stale_inflight([job])