diff --git a/cron/scheduler.py b/cron/scheduler.py index cfa2a7024661c..ac716707e0a60 100644 --- a/cron/scheduler.py +++ b/cron/scheduler.py @@ -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 @@ -2927,6 +2919,10 @@ 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: @@ -2934,6 +2930,12 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor): 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) + _ctx = contextvars.copy_context() def _run_and_release(j=job, ctx=_ctx): diff --git a/tests/cron/test_scheduler.py b/tests/cron/test_scheduler.py index 935533b11b971..f8e7fe4a9abe1 100644 --- a/tests/cron/test_scheduler.py +++ b/tests/cron/test_scheduler.py @@ -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