Skip to content

The agent that grows with you

fix(cron): keep the ticker thread alive through startup recovery and marker writes (#111010)

Konstantin Khlopkov8fce4baf8c59
diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.py
index 43e40f7ee2e..9f8ac8ee55f 100644
--- a/cron/scheduler_provider.py
+++ b/cron/scheduler_provider.py
@@ -50,6 +50,20 @@ def _note_tick_failure(exc: BaseException, consecutive_failures: int) -> int:
return 0
+def _guarded_store_write(action, description, *args, **kwargs):
+ """Run a ticker status-marker write so a failing store never ends the ticker thread.
+
+ The gateway runs the provider on an unsupervised daemon thread: one escaping exception
+ there stops cron silently while the gateway keeps serving (#111010). Heartbeat/error
+ markers are diagnostics for ``hermes cron status`` — losing one write to a broken store
+ must degrade to a logged warning, not thread death.
+ """
+ try:
+ action(*args, **kwargs)
+ except BaseException as e: # noqa: BLE001 - mirror the tick body's BaseException policy
+ logger.warning("Cron %s write failed: %s", description, e, exc_info=True)
+
+
def _profile_entry(entry) -> tuple:
"""Normalize a ``profile_homes`` entry (``(name, home)`` tuple or bare home) to ``(name,
home)``."""
@@ -409,13 +423,23 @@ class InProcessCronScheduler(CronScheduler):
)
return
- recovered = self.recover_interrupted()
- if recovered:
- logger.warning(
- "Marked %d interrupted cron execution(s) unknown after restart", recovered
+ # Startup recovery and the initial heartbeat run before the guarded loop; a broken
+ # store here must not take the whole ticker thread down (#111010) — the loop's own
+ # per-tick handling logs, persists the reason and keeps the thread alive.
+ try:
+ recovered = self.recover_interrupted()
+ if recovered:
+ logger.warning(
+ "Marked %d interrupted cron execution(s) unknown after restart", recovered
+ )
+ # Heartbeat before the first sleep so `hermes cron status` sees a live ticker
+ # immediately.
+ record_ticker_heartbeat()
+ except BaseException as e:
+ logger.error("Cron startup recovery error: %s", e, exc_info=True)
+ _guarded_store_write(
+ record_ticker_error, "startup error", f"{type(e).__name__}: {e}"
)
- # Heartbeat before the first sleep so `hermes cron status` sees a live ticker immediately.
- record_ticker_heartbeat()
# EMFILE backoff: don't hammer the store while fds are exhausted; a clean tick resets it.
consecutive_failures = 0
while not stop_event.is_set():
@@ -443,16 +467,18 @@ class InProcessCronScheduler(CronScheduler):
else:
logger.error("Cron tick error: %s", e, exc_info=True)
# Persist the reason so `hermes cron status` (separate process) shows WHY.
- record_ticker_error(f"{type(e).__name__}: {e}")
+ _guarded_store_write(
+ record_ticker_error, "tick error", f"{type(e).__name__}: {e}"
+ )
consecutive_failures = _note_tick_failure(e, consecutive_failures)
# Liveness every iteration; success marker only on a clean tick.
# EMFILE: reclaim fds + back off exponentially so the exhausted process stops hammering the
# store while it has no chance of making progress (#87644).
# Record liveness every iteration; bump the success marker only on a clean tick, so status can
# tell "alive but failing every tick" from "actually firing jobs" (#32612, #32895).
- record_ticker_heartbeat(success=ok)
+ _guarded_store_write(record_ticker_heartbeat, "heartbeat", success=ok)
if ok:
- clear_ticker_error()
+ _guarded_store_write(clear_ticker_error, "error clear")
consecutive_failures = 0
stop_event.wait(_backoff_wait_seconds(interval, consecutive_failures))
@@ -516,11 +542,21 @@ class InProcessCronScheduler(CronScheduler):
# Worst failure this cycle (fd exhaustion wins); backoff applied once per cycle.
# See #87644.
_cycle_exc: BaseException | None = None
- cycle_homes = [_profile_entry(e) for e in _existing_profile_homes(profile_homes)]
- if profile_gate is not None:
+ # Enumeration and gating run on the ticker thread; a raising gate callable must
+ # fail THIS cycle (logged, no heartbeats), not end the thread (#111010).
+ cycle_homes: list = []
+ try:
cycle_homes = [
- (name, home) for name, home in cycle_homes if profile_gate(name, home)
+ _profile_entry(e) for e in _existing_profile_homes(profile_homes)
]
+ if profile_gate is not None:
+ cycle_homes = [
+ (name, home) for name, home in cycle_homes if profile_gate(name, home)
+ ]
+ except BaseException as e:
+ logger.error("Cron profile enumeration error: %s", e, exc_info=True)
+ _tick_error = f"{type(e).__name__}: {e}"
+ consecutive_failures = _note_tick_failure(e, consecutive_failures)
try:
if can_dispatch is not None and not can_dispatch():
logger.debug("Cron dispatch paused while gateway drains existing work")
@@ -556,13 +592,21 @@ class InProcessCronScheduler(CronScheduler):
for _, home in cycle_homes:
with _profile_cron_scope(home):
_home_ok = _tick_error is None and str(home) not in _profile_errors
- record_ticker_heartbeat(success=_home_ok)
+ _guarded_store_write(
+ record_ticker_heartbeat, "heartbeat", success=_home_ok
+ )
if _home_ok:
- clear_ticker_error()
+ _guarded_store_write(clear_ticker_error, "error clear")
elif str(home) in _profile_errors:
- record_ticker_error(_profile_errors[str(home)])
+ _guarded_store_write(
+ record_ticker_error,
+ "tick error",
+ _profile_errors[str(home)],
+ )
elif _tick_error:
- record_ticker_error(_tick_error)
+ _guarded_store_write(
+ record_ticker_error, "tick error", _tick_error
+ )
if ok:
consecutive_failures = 0
stop_event.wait(_backoff_wait_seconds(interval, consecutive_failures))
diff --git a/tests/cron/test_ticker_startup_survival.py b/tests/cron/test_ticker_startup_survival.py
new file mode 100644
index 00000000000..a12361fe22b
--- /dev/null
+++ b/tests/cron/test_ticker_startup_survival.py
@@ -0,0 +1,149 @@
+"""The ticker's own contract — "an exception must not silently kill the daemon thread" —
+must hold for every step that runs on the cron-scheduler thread, not just the tick body:
+startup recovery, per-cycle profile enumeration/gating, and the status-marker writes.
+The gateway starts this thread without a supervisor, so any escaping exception ends cron
+silently while the gateway keeps running (#111010).
+"""
+
+import threading
+import time
+from unittest.mock import patch
+
+
+def _wait_until(predicate, timeout=10.0, interval=0.005):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ value = predicate()
+ if value:
+ return value
+ time.sleep(interval)
+ return predicate()
+
+
+def test_ticker_survives_startup_recovery_crash(tmp_path):
+ """A store that blows up during startup recovery must not kill the ticker thread:
+ the gateway keeps running and cron silently stops firing forever (#111010)."""
+ from cron.scheduler_provider import InProcessCronScheduler
+
+ ticks = []
+
+ def fake_tick(*args, **kwargs):
+ ticks.append(1)
+ return 0
+
+ def broken_recover(self):
+ raise RuntimeError("sqlite3.DatabaseError: database disk image is malformed")
+
+ stop = threading.Event()
+ provider = InProcessCronScheduler()
+ with (
+ patch("cron.scheduler.tick", side_effect=fake_tick),
+ patch("cron.jobs.record_ticker_heartbeat", lambda **kw: None),
+ patch("cron.jobs.record_ticker_error", lambda *a, **kw: None),
+ patch.object(InProcessCronScheduler, "recover_interrupted", broken_recover),
+ ):
+ thread = threading.Thread(
+ target=provider.start,
+ args=(stop,),
+ kwargs={"interval": 0},
+ daemon=True,
+ name="cron-scheduler",
+ )
+ thread.start()
+ _wait_until(lambda: len(ticks) >= 1)
+ alive_after_first_tick = thread.is_alive()
+ stop.set()
+ thread.join(timeout=5)
+
+ assert alive_after_first_tick, "ticker thread died during startup recovery"
+ assert ticks, "ticker never ticked after startup recovery crashed"
+ assert not thread.is_alive()
+
+
+def test_multiplex_ticker_survives_profile_gate_crash(tmp_path):
+ """A raising profile_gate callable runs on the ticker thread outside the guarded
+ tick body; its failure must degrade to a failed cycle, not a dead thread."""
+ from cron.scheduler_provider import InProcessCronScheduler
+
+ home = tmp_path / "default"
+ (home / "cron").mkdir(parents=True)
+
+ ticks = []
+
+ def fake_tick(*args, **kwargs):
+ ticks.append(1)
+ return 0
+
+ def broken_gate(name, home):
+ raise RuntimeError("gate boom")
+
+ stop = threading.Event()
+ provider = InProcessCronScheduler()
+ with (
+ patch("cron.scheduler.tick", side_effect=fake_tick),
+ patch("cron.jobs.record_ticker_heartbeat", lambda **kw: None),
+ ):
+ thread = threading.Thread(
+ target=provider.start,
+ args=(stop,),
+ kwargs={
+ "interval": 0,
+ "profile_homes": [("default", home)],
+ "profile_gate": broken_gate,
+ },
+ daemon=True,
+ name="cron-scheduler",
+ )
+ thread.start()
+ time.sleep(0.5)
+ alive_after_failed_cycles = thread.is_alive()
+ stop.set()
+ thread.join(timeout=5)
+
+ assert alive_after_failed_cycles, "ticker thread died when profile_gate raised"
+ assert not thread.is_alive()
+
+
+def test_ticker_survives_marker_write_crash(tmp_path):
+ """A misbehaving marker write (SystemExit from the store layer) must not end the
+ ticker — the loop body already swallows exactly this class of failure from the
+ provider SDKs (#32612); the marker writes deserve the same protection."""
+ from cron.scheduler_provider import InProcessCronScheduler
+
+ ticks = []
+ heartbeat_calls = {"n": 0}
+
+ def fake_tick(*args, **kwargs):
+ ticks.append(1)
+ return 0
+
+ def flaky_heartbeat(**kwargs):
+ heartbeat_calls["n"] += 1
+ if heartbeat_calls["n"] == 2:
+ raise SystemExit("misbehaving marker write")
+
+ stop = threading.Event()
+ provider = InProcessCronScheduler()
+ with (
+ patch("cron.scheduler.tick", side_effect=fake_tick),
+ patch("cron.jobs.record_ticker_heartbeat", side_effect=flaky_heartbeat),
+ patch.object(InProcessCronScheduler, "recover_interrupted", lambda self: 0),
+ patch("cron.jobs.record_ticker_error", lambda *a, **kw: None),
+ ):
+ thread = threading.Thread(
+ target=provider.start,
+ args=(stop,),
+ kwargs={"interval": 0},
+ daemon=True,
+ name="cron-scheduler",
+ )
+ thread.start()
+ _wait_until(lambda: len(ticks) >= 2)
+ alive_past_crash = thread.is_alive()
+ stop.set()
+ thread.join(timeout=5)
+
+ assert heartbeat_calls["n"] >= 2, "flaky heartbeat write never fired"
+ assert alive_past_crash, "ticker thread died on a marker-write SystemExit"
+ assert len(ticks) >= 2, "ticker stopped ticking after the marker-write crash"
+ assert not thread.is_alive()