Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions cron/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2869,14 +2869,6 @@ def tick(verbose: bool = True, adapters=None, loop=None, sync: bool = True) -> i
if verbose:
logger.info("%s - %s job(s) due", _hermes_now().strftime('%H:%M:%S'), len(due_jobs))

# Advance next_run_at for all recurring jobs FIRST, under the file lock,
# before any execution begins. This preserves at-most-once semantics.
# For parallel jobs that are already running, advance_next_run keeps
# bumping next_run_at forward so the grace window never expires.
# mark_job_run() overwrites next_run_at on completion.
for job in due_jobs:
advance_next_run(job["id"])

# Resolve max parallel workers: env var > config.yaml > unbounded.
# Set HERMES_CRON_MAX_PARALLEL=1 to restore old serial behaviour.
_max_workers: Optional[int] = None
Expand Down Expand Up @@ -2927,13 +2919,23 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor):
Returns the future, or None if the job was skipped because a prior
tick's run of the same job is still in flight. The running-set
membership is released in the worker's finally block.

advance_next_run is called ONLY when the job is successfully
claimed (not already running), preserving at-most-once semantics
without advancing next_run_at for silently-dropped jobs.
"""
job_id = job["id"]
with _running_lock:
if job_id in _running_job_ids:
logger.info("Job '%s' already running — skipping", job.get("name", job_id))
return None
_running_job_ids.add(job_id)

# Advance next_run_at NOW — this job is being dispatched, so the
# scheduler won't pick it up again until after it completes.
# (mark_job_run overwrites next_run_at on completion.)
advance_next_run(job_id)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

advance_next_run still runs before pool.submit. Current main has a shutdown-race path where submission fails and the in-memory claim is released; in that case this persistent advance means a job that was never enqueued is no longer due. Integrate this with the current submit-failure handling and add a regression test.


_ctx = contextvars.copy_context()

def _run_and_release(j=job, ctx=_ctx):
Expand Down
72 changes: 72 additions & 0 deletions tests/cron/test_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2967,6 +2967,78 @@ def mock_run_job(job):
assert start_s2 >= end_s1, "Jobs ran concurrently despite max_parallel=1"


def test_skipped_job_does_not_advance_next_run_at(self):
"""When a job is skipped because it's already running (in-flight guard),
advance_next_run must NOT be called — otherwise next_run_at gets bumped
forward and the job never retries, appearing to have run when it hasn't.

Regression: advance_next_run was historically called for ALL due jobs
BEFORE the in-flight dedup guard, so a job already running from a
previous tick would have its next_run_at advanced and silently skip an
entire scheduling window.
"""
import cron.scheduler as sched
from cron.scheduler import tick

# Create a recurring job that is "due" (next_run_at in the past).
job = {
"id": "skip-test-job",
"name": "skip-test",
"prompt": "hello",
"schedule": {"kind": "interval", "minutes": 60},
"enabled": True,
"next_run_at": "2020-01-01T00:00:00",
"deliver": "local",
}

# Simulate: this job is already running from a previous tick.
with sched._running_lock:
sched._running_job_ids.add("skip-test-job")

try:
with patch("cron.scheduler.get_due_jobs", return_value=[job]), \
patch("cron.scheduler.run_job", return_value=(True, "output", "ok", None)), \
patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
patch("cron.scheduler._deliver_result", return_value=None), \
patch("cron.scheduler.mark_job_run"), \
patch("cron.scheduler.advance_next_run") as mock_advance:
tick(verbose=False)

# The skipped job must NOT have had advance_next_run called —
# it was never dispatched so next_run_at must stay unchanged.
mock_advance.assert_not_called()
finally:
with sched._running_lock:
sched._running_job_ids.discard("skip-test-job")

def test_dispatched_job_still_advances_next_run_at(self):
"""A job that IS successfully dispatched should still have
advance_next_run called (preserving at-most-once semantics)."""
import cron.scheduler as sched
from cron.scheduler import tick

job = {
"id": "dispatch-test-job",
"name": "dispatch-test",
"prompt": "hello",
"schedule": {"kind": "interval", "minutes": 60},
"enabled": True,
"next_run_at": "2020-01-01T00:00:00",
"deliver": "local",
}

with patch("cron.scheduler.get_due_jobs", return_value=[job]), \
patch("cron.scheduler.run_job", return_value=(True, "output", "ok", None)), \
patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \
patch("cron.scheduler._deliver_result", return_value=None), \
patch("cron.scheduler.mark_job_run"), \
patch("cron.scheduler.advance_next_run") as mock_advance:
tick(verbose=False)

# The dispatched job MUST have advance_next_run called.
mock_advance.assert_called_once_with("dispatch-test-job")


class TestDeliverResultTimeoutCancelsFuture:
"""When future.result(timeout=60) raises TimeoutError in the live adapter
delivery path, the outcome depends on whether the coroutine was already
Expand Down