Skip to content

The agent that grows with you

fix(cron): let a skewed early fire own its armed slot

teknium1fcbdcdb4281b
diff --git a/cron/jobs.py b/cron/jobs.py
index 9142d99054f..98e26aa0b24 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -928,6 +928,10 @@ _TELEMETRY_RECENT_HISTORY = 20
# A fire_claim younger than this is a live run (heartbeat cadence is 60 s). One value
# for claiming, one-shot re-arm, and stale-error recovery so they cannot disagree.
FIRE_CLAIM_TTL_SECONDS = 300
+# A hosted/webhook fire for the armed slot can arrive a few seconds before the stored
+# ``next_run_at`` (the fire scheduler's clock runs ahead of ours). Claims that early still own
+# the slot; only claims further ahead are off-tick manual/dashboard fires.
+FIRE_CLAIM_SKEW_SECONDS = 60
_persisted_error_recoveries_recent: list = []
@@ -2736,7 +2740,11 @@ def claim_job_for_fire(
# are then refused ("Job is already being fired by the scheduler") and
# the scheduled tick dedupe-skips its real delivery (2026-09-08 live:
# a manual run at 19:53 consumed the next day's 19:00 occurrence).
- if instant is not None and datetime.fromisoformat(instant) > now:
+ # A claim within FIRE_CLAIM_SKEW_SECONDS of the slot is the fire for that slot
+ # (provider clock skew); dropping its identity would leave the slot unrecorded, so
+ # mark_job_run recomputes the same cron slot and the misfire backstop runs it twice.
+ if (instant is not None
+ and datetime.fromisoformat(instant) - now >= timedelta(seconds=FIRE_CLAIM_SKEW_SECONDS)):
instant = None
if instant and completed_occurrence(job, instant):
if job.get("schedule", {}).get("kind") in {"cron", "interval"}:
diff --git a/cron/occurrences.py b/cron/occurrences.py
index 0ca675ca873..846419ba54d 100644
--- a/cron/occurrences.py
+++ b/cron/occurrences.py
@@ -1,5 +1,5 @@
"""Exact scheduled identities, independent of mutable jobs.json dispatch stamps."""
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
import logging
logger = logging.getLogger(__name__)
@@ -21,11 +21,13 @@ def scheduled_instant(value):
def completed_occurrence(job, instant):
"""Unknown/failed/pruned attempts cannot prove completion: keep them eligible."""
from cron.executions import _transaction
+ from cron.jobs import FIRE_CLAIM_SKEW_SECONDS
instant = scheduled_instant(instant)
if instant is None:
return False
- instant_dt = datetime.fromisoformat(instant)
+ # A skewed early fire (see claim_job_for_fire) legitimately completes just before its slot.
+ earliest_real = datetime.fromisoformat(instant) - timedelta(seconds=FIRE_CLAIM_SKEW_SECONDS)
try:
with _transaction() as conn:
rows = conn.execute(
@@ -37,7 +39,7 @@ def completed_occurrence(job, instant):
completed_at = scheduled_instant(row["finished_at"] or row["claimed_at"])
# Legacy or malformed timestamps remain proof; only positively identified poison
# rows — completions recorded before their claimed occurrence — are ignored.
- if completed_at is None or datetime.fromisoformat(completed_at) >= instant_dt:
+ if completed_at is None or datetime.fromisoformat(completed_at) >= earliest_real:
return True
return False
except Exception:
diff --git a/tests/cron/test_claim_job_for_fire.py b/tests/cron/test_claim_job_for_fire.py
index 7b21a0a9332..af958bc9ee7 100644
--- a/tests/cron/test_claim_job_for_fire.py
+++ b/tests/cron/test_claim_job_for_fire.py
@@ -300,6 +300,37 @@ def test_unclassified_off_tick_claim_does_not_stamp_a_future_occurrence(temp_hom
assert claimed["_scheduled_instant"] is None
+def test_claim_seconds_before_the_slot_owns_it_once(temp_home, monkeypatch):
+ """A hosted fire arriving seconds early (provider clock skew) IS the fire for the armed
+ slot: it must carry the slot identity so the misfire backstop cannot run the slot again."""
+ from datetime import datetime, timedelta, timezone
+
+ import cron.executions as executions
+ import cron.jobs as jobs
+ from cron.occurrences import scheduled_instant
+
+ monkeypatch.setattr(executions, "EXECUTIONS_FILE", temp_home / "cron" / "executions.db")
+ job = jobs.create_job(prompt="x", schedule="0 19 * * *", name="skew")
+ slot = jobs.get_job(job["id"])["next_run_at"]
+ slot_dt = datetime.fromisoformat(slot)
+
+ monkeypatch.setattr(jobs, "_hermes_now", lambda: slot_dt - timedelta(seconds=2))
+ monkeypatch.setattr(executions, "_hermes_now", lambda: slot_dt - timedelta(seconds=2))
+ claimed = jobs.claim_job_for_fire(job["id"], return_job=True)
+ assert claimed["_scheduled_instant"] == scheduled_instant(slot)
+ row = executions.create_execution(
+ job["id"], source="chronos", scheduled_instant=claimed["_scheduled_instant"])
+ executions.finish_execution(row["id"], success=True)
+ jobs.mark_job_run(job["id"], True)
+
+ backstop = slot_dt.astimezone(timezone.utc) + timedelta(minutes=11)
+ monkeypatch.setattr(jobs, "_hermes_now", lambda: backstop)
+ monkeypatch.setattr(executions, "_hermes_now", lambda: backstop)
+ assert jobs.claim_job_for_fire(job["id"], return_job=True) is False, (
+ "misfire backstop re-ran the slot a skewed early fire already completed")
+ assert datetime.fromisoformat(jobs.get_job(job["id"])["next_run_at"]) > slot_dt
+
+
def test_manual_claim_still_refuses_a_paused_job(temp_home):
"""``manual=True`` suppresses only the occurrence stamp — unlike ``force=True`` it
must not resume a paused job, which the run-now tool relies on to refuse it."""