Skip to content

The agent that grows with you

fix: share in-flight cron dedupe between ticker and manual runs

Teknium3671c9f188e1
diff --git a/cron/scheduler.py b/cron/scheduler.py
index f64adde27cb..ec865b75aed 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -363,6 +363,35 @@ def get_running_job_ids() -> "frozenset[str]":
return frozenset(_running_job_ids)
+def try_register_running_job(job_id: str) -> bool:
+ """Atomically add ``job_id`` to the in-flight running set.
+
+ Returns False (without registering) when the job is already mid-run —
+ the caller must skip the fire. This is the single dedupe owner shared by
+ the ticker's ``_submit_with_guard`` and manual runs
+ (``tools/cronjob_tools``): the fire claim alone cannot prevent a
+ double-fire because its TTL (300s) is routinely outlived by real jobs,
+ after which a manual ``cronjob(action='run')`` would claim successfully
+ and run the same job concurrently (idea from #53395 by @izumi0uu).
+
+ Registration also makes the run visible to ``get_running_job_ids`` (the
+ gateway shutdown drain, #60432) and ``mark_running_jobs_interrupted``.
+ Callers MUST pair a successful registration with
+ ``release_running_job`` in a ``finally`` block.
+ """
+ with _running_lock:
+ if job_id in _running_job_ids:
+ return False
+ _running_job_ids.add(job_id)
+ return True
+
+
+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)
+
+
def mark_running_jobs_interrupted(reason: str) -> list:
"""Best-effort: mark every currently in-flight cron job interrupted.
@@ -4288,11 +4317,9 @@ def tick(
job.get("name", job_id),
)
return None
- 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)
+ if not try_register_running_job(job_id):
+ logger.info("Job '%s' already running — skipping", job.get("name", job_id))
+ 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")
@@ -4303,14 +4330,12 @@ def tick(
try:
return ctx.run(_process_job, j)
finally:
- with _running_lock:
- _running_job_ids.discard(j["id"])
+ release_running_job(j["id"])
try:
return pool.submit(_run_and_release)
except Exception as submit_err:
- with _running_lock:
- _running_job_ids.discard(job_id)
+ release_running_job(job_id)
finish_execution(
execution["id"],
success=False,
diff --git a/tests/tools/test_cronjob_run_background.py b/tests/tools/test_cronjob_run_background.py
index cdba7ed13c0..a185cfc299b 100644
--- a/tests/tools/test_cronjob_run_background.py
+++ b/tests/tools/test_cronjob_run_background.py
@@ -26,6 +26,18 @@ _JOB = {"id": "job-bg-1", "name": "bg run", "prompt": "hi",
"schedule": {"kind": "cron", "expr": "0 9 * * *"}}
+def _job(job_id):
+ """Per-test job dict with a UNIQUE id.
+
+ Background workers outlive their test (daemon executor) and hold the id
+ in the scheduler's shared running set until the run finishes; reusing one
+ id across tests makes the in-flight dedupe guard see a phantom
+ 'already running' from a previous test's straggler worker.
+ """
+ return {"id": job_id, "name": f"bg run {job_id}", "prompt": "hi",
+ "schedule": {"kind": "cron", "expr": "0 9 * * *"}}
+
+
def _bound_session_key(key="agent:main:telegram:dm:123"):
"""Context manager binding the approval session key contextvar."""
import contextlib
@@ -59,7 +71,7 @@ class TestBackgroundDispatch:
patch("cron.scheduler.run_one_job", side_effect=slow_run_one_job), \
patch("tools.cronjob_tools.get_job",
return_value={"last_status": "ok", "last_error": None}):
- res = _try_dispatch_background_run(dict(_JOB))
+ res = _try_dispatch_background_run(_job('job-bg-01'))
try:
# Returned BEFORE the job finished — that's the whole point.
@@ -67,7 +79,7 @@ class TestBackgroundDispatch:
assert res["claimed"] is True
assert res["dispatched"] is True
assert res["delegation_id"]
- m_claim.assert_called_once_with("job-bg-1")
+ m_claim.assert_called_once_with("job-bg-01")
# The job actually starts on the daemon executor.
assert run_started.wait(timeout=5.0), "job never started in background"
finally:
@@ -88,7 +100,7 @@ class TestBackgroundDispatch:
patch("tools.cronjob_tools.get_job",
return_value={"last_status": "ok", "last_error": None,
"next_run_at": "2026-08-07T09:00:00"}):
- res = _try_dispatch_background_run(dict(_JOB))
+ res = _try_dispatch_background_run(_job('job-bg-02'))
assert res["dispatched"] is True
found = None
@@ -121,7 +133,7 @@ class TestBackgroundDispatch:
patch("tools.cronjob_tools.get_job",
return_value={"last_status": "error",
"last_error": "provider exploded"}):
- res = _try_dispatch_background_run(dict(_JOB))
+ res = _try_dispatch_background_run(_job('job-bg-03'))
assert res["dispatched"] is True
found = None
@@ -148,7 +160,7 @@ class TestBackgroundDispatch:
patch("tools.cronjob_tools.get_job",
return_value={**_JOB, "enabled": False}), \
patch("tools.async_delegation.dispatch_async_delegation") as m_disp:
- res = _try_dispatch_background_run(dict(_JOB))
+ res = _try_dispatch_background_run(_job('job-bg-04'))
assert res["claimed"] is False
assert "paused/disabled" in res["error"]
m_disp.assert_not_called()
@@ -157,7 +169,7 @@ class TestBackgroundDispatch:
class TestSyncFallbacks:
def test_no_session_key_falls_back_to_sync(self):
"""Direct Python callers (no agent session) keep the sync path."""
- res = _try_dispatch_background_run(dict(_JOB))
+ res = _try_dispatch_background_run(_job('job-bg-05'))
assert res is None
def test_async_delivery_unsupported_falls_back_to_sync(self):
@@ -165,7 +177,7 @@ class TestSyncFallbacks:
with _bound_session_key():
with patch("gateway.session_context.async_delivery_supported",
return_value=False):
- res = _try_dispatch_background_run(dict(_JOB))
+ res = _try_dispatch_background_run(_job('job-bg-06'))
assert res is None
def test_pool_at_capacity_runs_inline(self):
@@ -177,23 +189,101 @@ class TestSyncFallbacks:
patch("cron.scheduler.run_one_job", return_value=True) as m_run, \
patch("tools.cronjob_tools.get_job",
return_value={"last_status": "ok", "last_error": None}):
- res = _try_dispatch_background_run(dict(_JOB))
+ res = _try_dispatch_background_run(_job('job-bg-07'))
assert res["dispatched"] is False
assert res["success"] is True
m_run.assert_called_once() # ran inline on this thread
+class TestInFlightDedupe:
+ """Manual runs must not double-fire a job that is already mid-run
+ (salvaged from #53395 by @izumi0uu): the fire claim's 300s TTL is
+ routinely outlived by real jobs, so the claim alone can't prevent it."""
+
+ def test_run_claimed_job_skips_when_already_running(self):
+ """The authoritative guard: _run_claimed_job refuses to fire a job
+ whose id is already registered in the scheduler running set."""
+ from cron import scheduler as sched
+ from tools.cronjob_tools import _run_claimed_job
+
+ assert sched.try_register_running_job("job-bg-08") # simulate ticker mid-run
+ try:
+ with patch("cron.scheduler.run_one_job") as m_run:
+ res = _run_claimed_job(_job('job-bg-08'))
+ assert res["success"] is False
+ assert "already running" in res["error"]
+ m_run.assert_not_called()
+ finally:
+ sched.release_running_job("job-bg-08")
+
+ def test_run_claimed_job_registers_and_releases(self):
+ """A normal run holds the registration for run_one_job's duration and
+ releases it after — visible to get_running_job_ids mid-run."""
+ from cron import scheduler as sched
+ from tools.cronjob_tools import _run_claimed_job
+
+ seen_during_run = {}
+
+ def probe_run(job):
+ seen_during_run["registered"] = "job-bg-09" in sched.get_running_job_ids()
+ return True
+
+ with patch("cron.scheduler.run_one_job", side_effect=probe_run), \
+ patch("tools.cronjob_tools.get_job",
+ return_value={"last_status": "ok", "last_error": None}):
+ res = _run_claimed_job(_job('job-bg-09'))
+
+ assert res["success"] is True
+ assert seen_during_run["registered"] is True
+ assert "job-bg-09" not in sched.get_running_job_ids() # released after
+
+ def test_background_dispatch_reports_running_job_immediately(self):
+ """The dispatch path pre-checks the running set so a mid-run job
+ reports in the tool response, not as a delayed completion event."""
+ from cron import scheduler as sched
+
+ assert sched.try_register_running_job("job-bg-10")
+ try:
+ with _bound_session_key():
+ with patch("tools.cronjob_tools.claim_job_for_fire") as m_claim, \
+ patch("tools.async_delegation.dispatch_async_delegation") as m_disp:
+ res = _try_dispatch_background_run(_job('job-bg-10'))
+ assert res["claimed"] is False
+ assert "already running" in res["error"]
+ m_claim.assert_not_called() # no claim consumed for a skipped run
+ m_disp.assert_not_called()
+ finally:
+ sched.release_running_job("job-bg-10")
+
+ def test_ticker_guard_uses_shared_helpers(self):
+ """The ticker's _submit_with_guard and manual runs share ONE dedupe
+ owner: registration through either side blocks the other."""
+ from cron import scheduler as sched
+
+ # Manual-run registration…
+ assert sched.try_register_running_job("job-shared-1")
+ try:
+ # …is exactly what the ticker-side helper consults.
+ assert not sched.try_register_running_job("job-shared-1")
+ assert "job-shared-1" in sched.get_running_job_ids()
+ finally:
+ sched.release_running_job("job-shared-1")
+ assert "job-shared-1" not in sched.get_running_job_ids()
+ # Idempotent release: never raises on a non-member.
+ sched.release_running_job("job-shared-1")
+
+
class TestCronjobRunToolIntegration:
def test_run_action_returns_background_note(self):
"""cronjob(action='run') surfaces the handle + do-not-wait note."""
with _bound_session_key():
- with patch("tools.cronjob_tools.resolve_job_ref", return_value=dict(_JOB)), \
+ with patch("tools.cronjob_tools.resolve_job_ref", return_value=_job('job-bg-12')), \
patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
patch("cron.scheduler.run_one_job", return_value=True), \
patch("tools.cronjob_tools.get_job",
- return_value={"id": "job-bg-1", "name": "bg run",
+ return_value={"id": "job-bg-12", "name": "bg run",
"last_status": "ok", "last_error": None}):
- out = json.loads(cronjob(action="run", job_id="job-bg-1"))
+ out = json.loads(cronjob(action="run", job_id="job-bg-12"))
assert out["success"] is True
assert out["job"]["executed"] is True
@@ -205,14 +295,14 @@ class TestCronjobRunToolIntegration:
"""No session context → the legacy synchronous behavior (executed +
execution_success populated from the completed run)."""
ran = {"job": "after-run", "last_status": "ok", "last_error": None}
- with patch("tools.cronjob_tools.resolve_job_ref", return_value=dict(_JOB)), \
+ with patch("tools.cronjob_tools.resolve_job_ref", return_value=_job('job-bg-13')), \
patch("tools.cronjob_tools.claim_job_for_fire", return_value=True) as m_claim, \
patch("cron.scheduler.run_one_job", return_value=True) as m_run, \
patch("tools.cronjob_tools.get_job", return_value=ran):
- out = json.loads(cronjob(action="run", job_id="job-bg-1"))
+ out = json.loads(cronjob(action="run", job_id="job-bg-13"))
assert out["success"] is True
assert out["job"]["executed"] is True
assert out["job"]["execution_success"] is True
- m_claim.assert_called_once_with("job-bg-1")
+ m_claim.assert_called_once_with("job-bg-13")
m_run.assert_called_once()
diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.py
index f86db92c1a9..cd2c0ffe43e 100644
--- a/tools/cronjob_tools.py
+++ b/tools/cronjob_tools.py
@@ -643,8 +643,31 @@ def _run_claimed_job(job: Dict[str, Any]) -> Dict[str, Any]:
Returns {"claimed": True, "success": bool, "error": str|None}.
"""
job_id = job["id"]
+ _registered = False
try:
- from cron.scheduler import run_one_job
+ from cron.scheduler import (
+ release_running_job,
+ run_one_job,
+ try_register_running_job,
+ )
+
+ # In-flight dedupe (idea from #53395 by @izumi0uu): the fire claim's
+ # TTL (300s) is routinely outlived by real jobs, so it alone cannot
+ # stop a manual run from double-firing a job the ticker (or another
+ # manual run) is still executing. Register in the scheduler's shared
+ # running set — the same guard _submit_with_guard uses — which also
+ # makes this run visible to the gateway shutdown drain
+ # (get_running_job_ids, #60432) and mark_running_jobs_interrupted.
+ if not try_register_running_job(job_id):
+ return {
+ "claimed": True,
+ "success": False,
+ "error": (
+ "Job is already running (a scheduler tick or another "
+ "manual run is executing it); not started again."
+ ),
+ }
+ _registered = True
# run_one_job records last_run_at/last_status via mark_job_run (which
# also clears the fire claim) and returns True iff it processed the job.
@@ -707,11 +730,15 @@ def _run_claimed_job(job: Dict[str, Any]) -> Dict[str, Any]:
_heartbeat_thread.start()
try:
- processed = run_one_job(job)
+ try:
+ processed = run_one_job(job)
+ finally:
+ _heartbeat_stop.set()
+ if _heartbeat_thread is not None:
+ _heartbeat_thread.join(timeout=_CRON_RUN_HEARTBEAT_INTERVAL + 1)
finally:
- _heartbeat_stop.set()
- if _heartbeat_thread is not None:
- _heartbeat_thread.join(timeout=_CRON_RUN_HEARTBEAT_INTERVAL + 1)
+ _registered = False
+ release_running_job(job_id)
refreshed = get_job(job_id) or {}
ok = refreshed.get("last_status") == "ok"
return {
@@ -722,6 +749,17 @@ def _run_claimed_job(job: Dict[str, Any]) -> Dict[str, Any]:
except Exception as e:
logger.error("Failed to execute cron job %s immediately: %s", job_id, e)
+ if _registered:
+ # Registration succeeded but we raised before the run's own
+ # release ran (e.g. heartbeat setup) — don't leave the job
+ # permanently marked in-flight. Only release registrations WE
+ # took: a bare discard here could erase a ticker-owned entry.
+ try:
+ from cron.scheduler import release_running_job as _release
+
+ _release(job_id)
+ except Exception:
+ pass
try:
mark_job_run(job_id, False, str(e))
except Exception:
@@ -827,6 +865,25 @@ def _try_dispatch_background_run(
# ---- synchronous claim (same semantics as _execute_job_now) ----
try:
+ # Best-effort early dedupe so a mid-run job reports in THIS tool
+ # response instead of as a delayed error completion event. The
+ # authoritative (atomic) check is try_register_running_job inside
+ # _run_claimed_job on the worker.
+ try:
+ from cron.scheduler import get_running_job_ids
+
+ if job_id in get_running_job_ids():
+ return {
+ "claimed": False,
+ "success": False,
+ "error": (
+ "Job is already running (a scheduler tick or another "
+ "manual run is executing it); not started again."
+ ),
+ }
+ except Exception:
+ pass
+
if not claim_job_for_fire(job_id):
refreshed = get_job(job_id)
if refreshed is None: