Skip to content

The agent that grows with you

fix(cron): drift-guard skips alert once per job, not once per tick

Victor Kyriazakose6ce8c37f151
diff --git a/cron/jobs.py b/cron/jobs.py
index 7d91ec35ed1..d225fe4ec7c 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -2073,24 +2073,25 @@ def remove_job(job_id: str) -> bool:
return False
-def _set_preflight_alerted(job_id: str, value: bool) -> bool:
- """Set/clear the preflight alert-dedup marker; return the PRIOR value.
+def _set_alert_flag(job_id: str, field: str, value: bool) -> bool:
+ """Set/clear a persisted alert-dedup marker; return the PRIOR value.
The marker records that the operator was already alerted about this
- job's blocked configuration, so the scheduler alerts exactly once and
- stays silent on subsequent ticks until the config heals (same
- alert-once shape as the dead-pin auto-pause in #73506). Persisted on
- the job record so the dedup survives gateway restarts.
+ job's condition, so the scheduler alerts exactly once and stays silent
+ on subsequent ticks until the condition heals (same alert-once shape as
+ the dead-pin auto-pause in #73506). Persisted on the job record so the
+ dedup survives gateway restarts. Fields: ``preflight_alerted`` (blocked
+ config, T1-26) and ``drift_alerted`` (#44585 drift-guard skip).
"""
with _jobs_lock():
jobs = load_jobs()
for i, job in enumerate(jobs):
if job["id"] == job_id:
- prior = bool(job.get("preflight_alerted"))
+ prior = bool(job.get(field))
if value:
- job["preflight_alerted"] = True
+ job[field] = True
else:
- job.pop("preflight_alerted", None)
+ job.pop(field, None)
if prior != value:
jobs[i] = job
save_jobs(jobs)
@@ -2098,6 +2099,11 @@ def _set_preflight_alerted(job_id: str, value: bool) -> bool:
return False
+def _set_preflight_alerted(job_id: str, value: bool) -> bool:
+ """Set/clear the preflight alert-dedup marker; return the PRIOR value."""
+ return _set_alert_flag(job_id, "preflight_alerted", value)
+
+
def mark_preflight_alerted(job_id: str) -> bool:
"""Mark the job as preflight-alerted; return True if it already was."""
return _set_preflight_alerted(job_id, True)
@@ -2108,6 +2114,16 @@ def clear_preflight_alerted(job_id: str) -> None:
_set_preflight_alerted(job_id, False)
+def mark_drift_alerted(job_id: str) -> bool:
+ """Mark the job as drift-alerted; return True if it already was."""
+ return _set_alert_flag(job_id, "drift_alerted", True)
+
+
+def clear_drift_alerted(job_id: str) -> None:
+ """Clear the drift alert-dedup marker (resolution matches again)."""
+ _set_alert_flag(job_id, "drift_alerted", False)
+
+
def mark_job_run(job_id: str, success: bool, error: Optional[str] = None,
delivery_error: Optional[str] = None,
status: Optional[str] = None):
@@ -2136,9 +2152,12 @@ def mark_job_run(job_id: str, success: bool, error: Optional[str] = None,
job["last_error"] = error if not success else None
# A healthy run means the configuration validates again — drop
# the preflight alert-dedup marker so a FUTURE config break
- # re-alerts instead of being silently swallowed.
+ # re-alerts instead of being silently swallowed. Same contract
+ # for the drift marker (#44585 alert-once): a run that made it
+ # through the guard means resolution matches again.
if success:
job.pop("preflight_alerted", None)
+ job.pop("drift_alerted", None)
# Track delivery failures separately — cleared on successful delivery
job["last_delivery_error"] = delivery_error
# Clear any external-fire claim so a re-armed recurring job can
diff --git a/cron/scheduler.py b/cron/scheduler.py
index d096b5f252c..a3686ca7fa7 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -3138,6 +3138,13 @@ def _guard_job_credential_exfil(job: dict) -> None:
BLOCKED_CONFIG_MARKER = "[blocked_config]"
BLOCKED_CONFIG_SILENT_MARKER = "[blocked_config:silent]"
+# Marker prefix for a #44585 drift-guard skip. Same alert-once contract as
+# blocked_config: run_one_job keys off it to record last_status and the
+# ``:silent`` variant means "already alerted on a previous tick — do not
+# deliver again" (the drift_alerted bit on the job record, #73506 shape).
+DRIFT_SKIP_MARKER = "[drift_skip]"
+DRIFT_SKIP_SILENT_MARKER = "[drift_skip:silent]"
+
def _cron_preflight_enabled(cfg: dict) -> bool:
"""Whether cron pre-dispatch configuration validation is enabled.
@@ -4194,13 +4201,30 @@ def run_job(
_changes,
job_id,
)
+ # Alert-once (#73506 shape): persist the drift_alerted bit so
+ # only the FIRST drifted tick delivers; run_one_job suppresses
+ # delivery on the silent marker. mark_job_run clears the bit
+ # when a run succeeds (drift healed), re-arming the alert.
+ _drift_already_alerted = False
+ try:
+ from cron.jobs import mark_drift_alerted
+
+ _drift_already_alerted = mark_drift_alerted(job_id)
+ except Exception:
+ pass # fail open: better a duplicate alert than none
+ _drift_marker = (
+ DRIFT_SKIP_SILENT_MARKER if _drift_already_alerted
+ else DRIFT_SKIP_MARKER
+ )
raise RuntimeError(
- f"Skipped to prevent unintended spend: global inference config "
- f"drifted since this job was created ({_changes}), and this job "
- f"is unpinned. No inference call was made. To run on the new "
- f"config, pin it explicitly: `cronjob action=update "
- f"job_id={job_id} provider=<provider> model=<model>` "
- f"(or pin the original values to keep them). See #44585."
+ f"{_drift_marker} Skipped to prevent unintended spend: global "
+ f"inference config drifted since this job was created "
+ f"({_changes}), and this job is unpinned. No inference call "
+ f"was made. To run on the new config, pin it explicitly: "
+ f"`cronjob action=update job_id={job_id} provider=<provider> "
+ f"model=<model>` (or pin the original values to keep them). "
+ f"This alert is sent once; the job stays skipped until the "
+ f"config is pinned or restored. See #44585."
)
fallback_model = get_fallback_chain(_cfg) or None
@@ -4828,6 +4852,15 @@ def run_one_job(
blocked_config = blocked_config_silent or (
bool(error) and BLOCKED_CONFIG_MARKER in str(error)
)
+ # Drift-guard skip (#44585): same alert-once contract as
+ # blocked_config — the silent marker means the operator already
+ # got the alert on a previous tick.
+ drift_skip_silent = (
+ bool(error) and DRIFT_SKIP_SILENT_MARKER in str(error)
+ )
+ drift_skip = drift_skip_silent or (
+ bool(error) and DRIFT_SKIP_MARKER in str(error)
+ )
if blocked_config and not success:
# Blocked-config alert: bypass the generic failure summarizer
# (whose auth/timeout heuristics would mislabel this as a
@@ -4845,11 +4878,18 @@ def run_one_job(
)
else:
deliver_content = final_response if success else _summarize_cron_failure_for_delivery(job, error)
+ if drift_skip and not success:
+ # Drift-skip alert: strip the internal marker from the
+ # user-facing text (the summarizer passes the message
+ # through its generic tail).
+ deliver_content = re.sub(
+ r"\[drift_skip[^\]]*\]\s*", "", deliver_content
+ ).strip()
# Treat whitespace-only final responses the same as empty
# responses: do not deliver a blank message, and let the
# empty-response guard below mark the run as a soft failure.
should_deliver = bool(deliver_content.strip())
- if blocked_config_silent:
+ if blocked_config_silent or drift_skip_silent:
should_deliver = False
unresolved_origin = False
# Cron silence suppression — see _is_cron_silence_response. Replaces the
diff --git a/tests/cron/test_cron_drift_alert_once.py b/tests/cron/test_cron_drift_alert_once.py
new file mode 100644
index 00000000000..4a1ad8820f7
--- /dev/null
+++ b/tests/cron/test_cron_drift_alert_once.py
@@ -0,0 +1,155 @@
+"""Drift-guard skips must alert once per job, not once per tick (#44585 + #73506).
+
+Coatue field report (2026-08-11): a profile redeploy changed the global
+default provider and every unpinned cron started alerting on every tick —
+40 jobs x N ticks of identical "Skipped to prevent unintended spend" spam.
+The #44585 drift guard correctly fails closed; this wires the existing
+#73506 alert-once shape (persisted per-job bit, cleared when the condition
+heals) to the drift branch, exactly as pre-dispatch preflight already does
+for blocked_config.
+
+Contract:
+- First drifted tick delivers ONE loud, actionable alert.
+- Subsequent drifted ticks deliver nothing.
+- When drift heals (guard passes again), the bit clears, so a FUTURE drift
+ re-alerts instead of being silently swallowed.
+- Only the drift branch gets the bit — other failures keep alerting per tick.
+"""
+
+import sys
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+import cron.jobs as cron_jobs
+import cron.scheduler as sched
+
+
+def _job(**overrides):
+ job = {
+ "id": "drift-once-test",
+ "name": "drift once test",
+ "prompt": "hello",
+ "enabled": True,
+ "state": "scheduled",
+ "schedule": {"kind": "interval", "minutes": 5, "display": "every 5m"},
+ "deliver": "local",
+ "model": None,
+ "provider": None,
+ "provider_snapshot": "openrouter",
+ "base_url": None,
+ }
+ job.update(overrides)
+ return job
+
+
+def _tick(job, tmp_path, current_provider, deliveries):
+ """Run one run_one_job tick with the provider resolution pinned."""
+ fake_db = MagicMock()
+
+ def fake_deliver(job, content, adapters=None, loop=None):
+ deliveries.append(content)
+ return None
+
+ with patch("cron.scheduler._hermes_home", tmp_path), \
+ patch("cron.scheduler._resolve_origin", return_value=None), \
+ patch("hermes_cli.env_loader.load_hermes_dotenv"), \
+ patch("hermes_cli.env_loader.reset_secret_source_cache"), \
+ patch("hermes_state.SessionDB", return_value=fake_db), \
+ patch("tools.mcp_tool.discover_mcp_tools", return_value=[]), \
+ patch("hermes_cli.runtime_provider.resolve_runtime_provider",
+ return_value={
+ "api_key": "test-key",
+ "base_url": "https://example.invalid/v1",
+ "provider": current_provider,
+ "api_mode": "chat_completions",
+ }), \
+ patch.object(sched, "_deliver_result", side_effect=fake_deliver), \
+ patch("run_agent.AIAgent") as mock_agent_cls:
+ mock_agent = MagicMock()
+ mock_agent.run_conversation.return_value = {"final_response": "ok"}
+ mock_agent_cls.return_value = mock_agent
+ ok = sched.run_one_job(job)
+ return ok, mock_agent_cls.called
+
+
+class TestDriftAlertOnce:
+ def test_two_drifted_ticks_alert_exactly_once(self, tmp_path):
+ job = _job()
+ deliveries = []
+ with cron_jobs.use_cron_store(tmp_path):
+ cron_jobs.save_jobs([job])
+ for _ in range(2):
+ fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]
+ ok, agent_called = _tick(fresh, tmp_path, "nous", deliveries)
+ assert agent_called is False, "drifted tick must not spend"
+
+ stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]
+ assert stored.get("drift_alerted") is True
+
+ assert len(deliveries) == 1, f"expected 1 alert, got {len(deliveries)}: {deliveries}"
+ blob = deliveries[0].lower()
+ assert "drift" in blob
+ assert "pin" in blob
+
+ def test_healed_drift_clears_bit_and_redrift_realerts(self, tmp_path):
+ job = _job()
+ deliveries = []
+ with cron_jobs.use_cron_store(tmp_path):
+ cron_jobs.save_jobs([job])
+ # Tick 1: drifted -> one alert, bit set.
+ fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]
+ _tick(fresh, tmp_path, "nous", deliveries)
+ assert len(deliveries) == 1
+
+ # Tick 2: drift healed (resolution matches snapshot) -> runs, bit cleared.
+ fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]
+ ok, agent_called = _tick(fresh, tmp_path, "openrouter", deliveries)
+ assert agent_called is True
+ stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]
+ assert not stored.get("drift_alerted")
+
+ # Tick 3: drifts again -> re-alerts (not swallowed).
+ fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]
+ _tick(fresh, tmp_path, "nous", deliveries)
+
+ drift_alerts = [d for d in deliveries if "drift" in d.lower()]
+ assert len(drift_alerts) == 2, f"expected re-alert after heal: {deliveries}"
+
+ def test_non_drift_failures_untouched_by_the_bit(self, tmp_path):
+ """A job with the drift bit set whose run fails for another reason
+ still alerts — only the drift branch consults the bit."""
+ job = _job(provider_snapshot=None, drift_alerted=True)
+ deliveries = []
+
+ def fake_deliver(jb, content, adapters=None, loop=None):
+ deliveries.append(content)
+ return None
+
+ fake_db = MagicMock()
+ with cron_jobs.use_cron_store(tmp_path):
+ cron_jobs.save_jobs([job])
+ fresh = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]
+ with patch("cron.scheduler._hermes_home", tmp_path), \
+ patch("cron.scheduler._resolve_origin", return_value=None), \
+ patch("hermes_cli.env_loader.load_hermes_dotenv"), \
+ patch("hermes_cli.env_loader.reset_secret_source_cache"), \
+ patch("hermes_state.SessionDB", return_value=fake_db), \
+ patch("tools.mcp_tool.discover_mcp_tools", return_value=[]), \
+ patch("hermes_cli.runtime_provider.resolve_runtime_provider",
+ return_value={
+ "api_key": "test-key",
+ "base_url": "https://example.invalid/v1",
+ "provider": "openrouter",
+ "api_mode": "chat_completions",
+ }), \
+ patch.object(sched, "_deliver_result", side_effect=fake_deliver), \
+ patch("run_agent.AIAgent") as mock_agent_cls:
+ mock_agent = MagicMock()
+ mock_agent.run_conversation.side_effect = RuntimeError("boom unrelated")
+ mock_agent_cls.return_value = mock_agent
+ sched.run_one_job(fresh)
+
+ assert len(deliveries) == 1, "non-drift failure must still deliver"
+ assert "boom unrelated" in deliveries[0]