Skip to content

The agent that grows with you

refactor(cron): move tick-yield logging and catch-up counter into topical siblings

kshitijk4poor90b0540d412c
diff --git a/agent/monitoring/cron_health.py b/agent/monitoring/cron_health.py
index 6be34b861c0..2ef46893090 100644
--- a/agent/monitoring/cron_health.py
+++ b/agent/monitoring/cron_health.py
@@ -12,11 +12,11 @@ from agent.monitoring.events import CronExecutionEvent
from agent.monitoring.gateway_health import GatewayMetric, _contains_any, _safe_instance_id
from cron.jobs import (
_compute_grace_seconds,
- get_catch_up_occurrence_count,
get_ticker_heartbeat_age,
get_ticker_success_age,
load_jobs,
)
+from cron.occurrences import get_catch_up_occurrence_count
from cron.scheduler import get_running_job_ids
from hermes_time import now as _now
diff --git a/cron/jobs.py b/cron/jobs.py
index 3c588967b22..3cc13df1f73 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -1313,20 +1313,6 @@ def get_ticker_success_age() -> Optional[float]:
return _epoch_file_age("ticker_last_success")
-def get_catch_up_occurrence_count() -> int:
- """Return the profile-local stale-schedule catch-up count."""
- path = _current_cron_store().cron_dir / "catch_up_occurrences"
- try:
- return max(0, int(path.read_text(encoding="utf-8-sig").strip()))
- except (OSError, ValueError):
- return 0
-
-
-def record_catch_up_occurrence() -> None:
- """Increment the profile-local stale-schedule catch-up counter, best effort."""
- _write_marker("catch_up_occurrences", str(get_catch_up_occurrence_count() + 1), ".count_")
-
-
def record_ticker_error(message: str) -> None:
"""Persist the latest tick failure so `cron status` (another process) can show WHY, not just
staleness."""
@@ -3164,6 +3150,7 @@ def _fast_forward_missed_recurring(d: _DueJob, grace: int) -> bool:
"Job '%s' missed its scheduled time (%s, grace=%ds). "
"Running now; next run provisionally set to: %s (re-anchored on completion)",
d.label, d.next_run, grace, new_next)
+ from cron.occurrences import record_catch_up_occurrence
record_catch_up_occurrence()
return False
diff --git a/cron/occurrences.py b/cron/occurrences.py
index c083b759ed6..cb622b5a98d 100644
--- a/cron/occurrences.py
+++ b/cron/occurrences.py
@@ -100,3 +100,21 @@ def unclaimed_pending_slot(job, now):
if pending.get("by") != _machine_id() and _claim_is_live(pending, now, FIRE_CLAIM_TTL_SECONDS):
return None
return slot
+
+
+def get_catch_up_occurrence_count() -> int:
+ """Return the profile-local stale-schedule catch-up count."""
+ from cron.jobs import _current_cron_store
+
+ path = _current_cron_store().cron_dir / "catch_up_occurrences"
+ try:
+ return max(0, int(path.read_text(encoding="utf-8-sig").strip()))
+ except (OSError, ValueError):
+ return 0
+
+
+def record_catch_up_occurrence() -> None:
+ """Increment the profile-local stale-schedule catch-up counter, best effort."""
+ from cron.jobs import _write_marker
+
+ _write_marker("catch_up_occurrences", str(get_catch_up_occurrence_count() + 1), ".count_")
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 6d96c5bba52..cdf62ebe612 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -215,11 +215,6 @@ def stale_code_yield_labels(recorded_error: str | None) -> tuple[str, str] | Non
return (match.group(1), match.group(2)) if match else None
-# Log the yield at most once per episode (reset when the skew changes) to avoid per-interval spam.
-_YIELD_LOG_INTERVAL_SECONDS = 3600.0
-_last_yield_log: dict[str, object] = {}
-
-
def _should_yield_tick_to_fresh_gateway() -> tuple[str, str] | None:
"""``(boot_rev, disk_rev)`` when THIS profile's tick must yield to a fresher gateway, else None.
@@ -258,21 +253,6 @@ def _should_yield_tick_to_fresh_gateway() -> tuple[str, str] | None:
return skew
-def _log_tick_yield_once(reason: str) -> None:
- """Log the yield at error level once per episode (skew signature)."""
- global _last_yield_log
- now = time.monotonic()
- last_reason = _last_yield_log.get("reason")
- last_at = _last_yield_log.get("at", 0.0)
- if last_reason != reason or (now - float(last_at)) >= _YIELD_LOG_INTERVAL_SECONDS:
- logger.error(
- "Cron tick yielded: this process is running stale code (%s) and a "
- "fresher gateway owns the runtime lock — jobs will fire from that "
- "process. Restart this one to reclaim its ticks.",
- reason)
- _last_yield_log = {"reason": reason, "at": now}
-
-
def _summarize_cron_failure_for_delivery(job: dict, error: str | None) -> str:
"""One-line failure notice for chat delivery (full details stay in the run output).
diff --git a/cron/scheduler_tick.py b/cron/scheduler_tick.py
index ced12adc967..cd342fbc9c9 100644
--- a/cron/scheduler_tick.py
+++ b/cron/scheduler_tick.py
@@ -12,6 +12,27 @@ _STORE_WARN_INTERVAL_SECONDS = 900.0
_last_store_warning: dict = {}
+# Log the yield at most once per episode (reset when the skew changes) to avoid per-interval spam.
+_YIELD_LOG_INTERVAL_SECONDS = 3600.0
+_last_yield_log: dict[str, object] = {}
+
+
+def _log_tick_yield_once(reason: str) -> None:
+ """Log the yield at error level once per episode (skew signature)."""
+ global _last_yield_log
+ now = time.monotonic()
+ last_reason = _last_yield_log.get("reason")
+ last_at = _last_yield_log.get("at", 0.0)
+ if last_reason != reason or (now - float(last_at)) >= _YIELD_LOG_INTERVAL_SECONDS:
+ logger.error(
+ "Cron tick yielded: this process is running stale code (%s) and a "
+ "fresher gateway owns the runtime lock — jobs will fire from that "
+ "process. Restart this one to reclaim its ticks.",
+ reason)
+ _last_yield_log = {"reason": reason, "at": now}
+
+
+
def warn_store_unwritable(exc: OSError, skipped: str) -> None:
"""Rate-limited WARNING for a cron store write that failed (ENOSPC/EROFS/EACCES). The caller
skips the dispatch that needed the write: no job runs without a durable advance/fire claim."""
@@ -48,7 +69,7 @@ def _tick_admitted(
# lock, ITS ticker dispatches. With no fresh holder (desktop-standalone) the tick proceeds.
_skew = _sched._should_yield_tick_to_fresh_gateway()
if _skew is not None:
- _sched._log_tick_yield_once(f"boot={_skew[0]} disk={_skew[1]}")
+ _log_tick_yield_once(f"boot={_skew[0]} disk={_skew[1]}")
raise _sched.CronTickYielded(_skew[0], _skew[1])
lock_dir, lock_file = _sched._get_lock_paths()
diff --git a/tests/cron/test_due_stale_cron_edit.py b/tests/cron/test_due_stale_cron_edit.py
index 01dd2804e4d..0a9e6f9c59b 100644
--- a/tests/cron/test_due_stale_cron_edit.py
+++ b/tests/cron/test_due_stale_cron_edit.py
@@ -98,12 +98,8 @@ def test_manual_trigger_bypasses_stale_schedule_guard(temp_home, monkeypatch):
def test_delayed_manual_trigger_is_not_counted_as_catch_up(temp_home, monkeypatch):
"""Run-now intent remains explicit even when the next scan is hours later."""
- from cron.jobs import (
- create_job,
- get_catch_up_occurrence_count,
- get_due_jobs,
- trigger_job,
- )
+ from cron.jobs import create_job, get_due_jobs, trigger_job
+ from cron.occurrences import get_catch_up_occurrence_count
trigger_time = _SATURDAY_0700 + timedelta(seconds=30)
monkeypatch.setattr("cron.jobs._hermes_now", lambda: trigger_time)