Skip to content

The agent that grows with you

fix(cron): a stopped run stays stopped in every ledger reader

Teknium249a90c0375b
diff --git a/agent/monitoring/cron_health.py b/agent/monitoring/cron_health.py
index 9979fd38dba..6eb1b49eea5 100644
--- a/agent/monitoring/cron_health.py
+++ b/agent/monitoring/cron_health.py
@@ -22,10 +22,11 @@ from cron.store_health import degraded_records
from hermes_time import now as _now
logger = logging.getLogger(__name__)
-_KNOWN_STATUSES = {"claimed", "running", "completed", "failed", "unknown"}
+# ``cancelled``: an operator stopped the run; ``missed``: the scheduler skipped past its slots.
+_KNOWN_STATUSES = {"claimed", "running", "completed", "failed", "unknown", "cancelled", "missed"}
_KNOWN_SOURCES = {"builtin", "direct", "external"}
_KNOWN_DELIVERY_OUTCOMES = {"queued", "delivered", "failed", "suppressed", "suppressed_acked", "not_configured"}
-_TERMINAL_STATUSES = {"completed", "failed", "unknown"}
+_TERMINAL_STATUSES = {"completed", "failed", "unknown", "cancelled", "missed"}
@dataclass(frozen=True, slots=True)
diff --git a/cron/cancellation.py b/cron/cancellation.py
index 5ea941eaadb..d19d5dbc77e 100644
--- a/cron/cancellation.py
+++ b/cron/cancellation.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import contextlib
import os
+import tempfile
import time
from pathlib import Path
from typing import Any, Dict, Optional, Protocol
@@ -62,9 +63,16 @@ def request_cancel(execution_id: str, *, reason: Optional[str] = None) -> Path:
path = _marker_path(execution_id)
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
- tmp = path.with_suffix(".cancel.tmp")
- tmp.write_text((reason or _DEFAULT_REASON).strip(), encoding="utf-8")
- os.replace(tmp, path)
+ # A private temp file published with link(): create-if-absent, so overlapping requests
+ # never share a temp path and the first reason is never overwritten or seen half-written.
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f"{path.name}.", suffix=".tmp")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write((reason or _DEFAULT_REASON).strip())
+ with contextlib.suppress(FileExistsError):
+ os.link(tmp, path)
+ finally:
+ os.unlink(tmp)
_prune_stale_markers()
return path
@@ -151,14 +159,30 @@ def finish_cancelled_run(job: dict[str, Any], execution_id: str, fire_owner: Opt
job's ``last_status`` — without a failure alert or a failure-streak bump, since the operator
asked for it. A job removed mid-run has no record left to mark; its ledger row still lands."""
from cron import scheduler
+ from cron.unreachable_retry import is_retry_run
reason = CancelRequest(execution_id).reason
if not scheduler.self_removal_delivery_allowed(job["id"]):
owner = {"expected_fire_owner": fire_owner} if fire_owner is not None else {}
- scheduler.mark_job_run(job["id"], False, f"Cancelled: {reason}", status="cancelled", **owner)
+ # A stopped ladder re-run re-ran an occurrence that already counted: no second repeat slot.
+ rung = {"ladder_rung": True} if is_retry_run(job) else {}
+ scheduler.mark_job_run(
+ job["id"], False, f"Cancelled: {reason}", status="cancelled", **owner, **rung)
scheduler.finish_execution(execution_id, success=False, error=reason, cancelled=True)
+def finish_lost_execution(execution_id: str, error: str) -> Optional[dict[str, Any]]:
+ """Close an attempt whose fire claim vanished. Removing a job mid-run cancels it AND drops the
+ claim, so a run that finds its claim gone books the operator's ``cancelled`` (with the reason)
+ when a cancel marker is waiting, and ``failed`` with ``error`` only for a real claim loss."""
+ from cron import scheduler
+
+ if cancel_requested(execution_id):
+ return scheduler.finish_execution(
+ execution_id, success=False, error=CancelRequest(execution_id).reason, cancelled=True)
+ return scheduler.finish_execution(execution_id, success=False, error=error)
+
+
def run_job_unless_cancelled(run_job, job, run_kwargs, teardown, fence, execution_id, fire_owner):
"""``run_job``'s result, or None once an operator cancel stopped the run and was booked.
diff --git a/cron/executions.py b/cron/executions.py
index ca60622cca9..231b0a1d4ec 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -38,6 +38,9 @@ LIVE_OWNER_STALE_CLAIM_FLOOR_SECONDS = 7200.0
# ``missed``: never started — one row books every occurrence the scheduler skipped past.
_TERMINAL_STATES = ("completed", "failed", "unknown", "cancelled", "missed")
_STATUS_CHECK = "('claimed','running','completed','failed','unknown','cancelled','missed')"
+# Outcomes the attempt's own firer booked: receipt recovery, the external-worker waiter and the
+# dead-owner sweep must treat these as final, never replay or re-book them.
+FIRER_FINISHED_STATES = frozenset({"completed", "failed", "cancelled"})
_lock = threading.RLock()
_PROCESS_ID = uuid.uuid4().hex
@@ -682,7 +685,15 @@ def live_inflight_execution(job_id: str) -> Optional[dict[str, Any]]:
heartbeat yet stays owned, while a run whose process died (watchdog kill, crash) does not.
Read-only — unlike ``recover_interrupted_executions`` it never rewrites a row.
"""
- record = latest_execution(job_id)
+ # A ``missed`` row is the due scan's note about skipped slots, not an attempt: one booked while
+ # a long run is still live (machine slept through its next slots) must not hide that run.
+ with _transaction() as conn:
+ row = conn.execute(
+ """SELECT * FROM executions WHERE job_id=? AND status != 'missed'
+ ORDER BY julianday(claimed_at) DESC, claimed_at DESC, id DESC LIMIT 1""",
+ (job_id,),
+ ).fetchone()
+ record = dict(row) if row is not None else None
if not record or record.get("status") not in ("claimed", "running"):
return None
if not _owner_is_live(int(record["pid"]), record.get("process_started_at")):
diff --git a/cron/missed_runs.py b/cron/missed_runs.py
index 471dd16e8b4..9cde76420c6 100644
--- a/cron/missed_runs.py
+++ b/cron/missed_runs.py
@@ -56,10 +56,14 @@ def count_missed_slots(schedule: dict[str, Any], first: str, now: datetime) -> i
return count
-def _book_missed(job: dict[str, Any], count: int, first: Optional[str], detail: str) -> None:
+def _book_missed(
+ job: dict[str, Any], count: int, first: Optional[str], detail: str, *, capped: bool,
+) -> None:
+ """``capped``: counting hit ``_MAX_COUNTED_SLOTS``, so ``count`` is a floor, not exact. Passed
+ separately because the collapse branch books one fewer than it counted."""
from cron.executions import record_missed_occurrences
- if count >= _MAX_COUNTED_SLOTS:
+ if capped:
detail = f"{detail}; counting stopped at {_MAX_COUNTED_SLOTS}"
try:
record_missed_occurrences(str(job.get("id")), count=count, first_instant=first, detail=detail)
@@ -84,6 +88,7 @@ def fast_forward_missed_recurring(d: Any, grace: int) -> bool:
return False
d.scan.persist(d.job["id"], next_run_at=new_next)
missed = count_missed_slots(d.schedule, d.next_run, d.scan.now)
+ capped = missed >= _MAX_COUNTED_SLOTS
if (_instant_after(_ensure_aware(datetime.fromisoformat(new_next)), d.scan.now)
and not job_catches_up(d.job)):
logger.info(
@@ -92,7 +97,7 @@ def fast_forward_missed_recurring(d: Any, grace: int) -> bool:
d.label, d.next_run, grace, missed, new_next)
d.scan.on_saved.append(lambda job=d.job: record_cron_missed(job))
d.scan.on_saved.append(lambda job=d.job, first=d.next_run: _book_missed(
- job, missed, first, f"skipped, catch-up off; next run {new_next}"))
+ job, missed, first, f"skipped, catch-up off; next run {new_next}", capped=capped))
return True
logger.info(
"Job '%s' missed its scheduled time (%s, grace=%ds). "
@@ -102,7 +107,7 @@ def fast_forward_missed_recurring(d: Any, grace: int) -> bool:
d.scan.on_saved.append(record_catch_up_occurrence)
if missed > 1:
d.scan.on_saved.append(lambda job=d.job, first=d.next_run: _book_missed(
- job, missed - 1, first, "collapsed into one catch-up run"))
+ job, missed - 1, first, "collapsed into one catch-up run", capped=capped))
return False
@@ -138,5 +143,5 @@ def retire_expired_oneshot(d: Any) -> bool:
d.scan.retire(d.job["id"])
d.scan.on_saved.append(lambda job=d.job: record_cron_missed(job))
d.scan.on_saved.append(lambda job=d.job, first=d.next_run: _book_missed(
- job, 1, first, "one-shot past its grace window; catch-up off"))
+ job, 1, first, "one-shot past its grace window; catch-up off", capped=False))
return True
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 4532003fda6..ff780ef6ac2 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -526,13 +526,14 @@ from cron.jobs import (
from cron import store_health
from cron.execution_identity import enter_cron_execution, exit_cron_execution
from cron.executions import (
- _TERMINAL_STATES, HANDOFF_ADOPTION_GRACE_SECONDS, create_execution, finish_execution,
+ FIRER_FINISHED_STATES, _TERMINAL_STATES, HANDOFF_ADOPTION_GRACE_SECONDS, create_execution, finish_execution,
get_execution, mark_execution_handoff_pending, mark_execution_running,
recover_interrupted_executions, settle_unstarted_execution, terminalize_dead_owner)
from cron.scheduler_liveness import ExecutionProgressStamper, _inactivity_watchdog_loop
from cron.scheduler_bookkeeping import _classify_delivery_outcome
from cron.cancellation import (CancelRequest, _CancelEventLike, _CombinedCancelEvent, cancel_reason,
- clear_cancel, run_job_unless_cancelled as _run_job_unless_cancelled)
+ clear_cancel, finish_lost_execution,
+ run_job_unless_cancelled as _run_job_unless_cancelled)
# Response marker that suppresses delivery (output is still saved locally for audit).
SILENT_MARKER = "[SILENT]"
@@ -2725,7 +2726,7 @@ def _run_with_fire_claim_heartbeat(job: dict, run) -> bool:
if not execution_id:
return
try:
- finish_execution(execution_id, success=False, error=error)
+ finish_lost_execution(execution_id, error)
except Exception:
logger.warning(
"Job '%s': failed to close unstarted execution ledger row",
@@ -2918,9 +2919,8 @@ def _record_fire_ownership_lost(
)
finish_execution(execution_id, success=False, error=_OWNERSHIP_LOST_INTERRUPTED)
else:
- finish_execution(
- execution_id, success=False,
- error="Fire claim ownership lost; stale result was discarded.")
+ finish_lost_execution(
+ execution_id, "Fire claim ownership lost; stale result was discarded.")
def _compose_run_delivery(
@@ -3534,7 +3534,7 @@ def _wait_for_external_cron_worker_body(
# read and wait(). Re-read the exact attempt before declaring that
# it died without terminalizing.
current = get_execution(execution_id)
- if current and current.get("status") in ("completed", "failed"):
+ if current and current.get("status") in FIRER_FINISHED_STATES:
return True
# If the adopted worker died without terminalizing, its owner is
# now provably gone. Recover to ``unknown`` rather than routing the
@@ -3556,7 +3556,7 @@ def _wait_for_external_cron_worker_body(
# A concurrent sweep may have won the unknown transition. Still
# surface this waiter's exit code and stderr instead of discarding them.
current = get_execution(execution_id)
- if current and current.get("status") in ("completed", "failed"):
+ if current and current.get("status") in FIRER_FINISHED_STATES:
return True
stderr_tail = ""
if stderr_path is not None:
diff --git a/cron/scheduler_authority.py b/cron/scheduler_authority.py
index eea00d6598a..9b5b5eca934 100644
--- a/cron/scheduler_authority.py
+++ b/cron/scheduler_authority.py
@@ -155,7 +155,7 @@ def reconcile_pending(*, allow_connect=True):
from gateway.session_cron import owner_for_home, operation
from hermes_constants import get_hermes_home
from hermes_cli.gateway_client import connect_gateway
- from cron.executions import execution_owner_live, get_execution
+ from cron.executions import FIRER_FINISHED_STATES, execution_owner_live, get_execution
from cron.jobs import get_job, pause_job
from cron.scheduler import (_RunDelivery, _FireOwnership, _apply_agent_failure_marker,
_save_compose_deliver)
@@ -175,7 +175,7 @@ def reconcile_pending(*, allow_connect=True):
# output or re-marking the job on every tick would duplicate its side effects.
continue
row = get_execution(params['request_id'])
- if row is not None and row['job_id'] == params['job_id'] and row['status'] in {'completed', 'failed'}:
+ if row is not None and row['job_id'] == params['job_id'] and row['status'] in FIRER_FINISHED_STATES:
# The firer booked this attempt's terminal outcome itself (ownership lost, shutdown
# interrupt, a crashed tail): the receipt is not a result to save or deliver again.
journal.unlink(missing_ok=True)
diff --git a/cron/scheduler_bookkeeping.py b/cron/scheduler_bookkeeping.py
index 61715ac814f..b6f6dcfb8f0 100644
--- a/cron/scheduler_bookkeeping.py
+++ b/cron/scheduler_bookkeeping.py
@@ -112,7 +112,7 @@ def finish_completed_run(d, fire_owner: Optional[str], execution_id: str, *, rec
# Failure ping left the process (or had a configured target): mark the incident alerted.
scheduler._mark_incident_alerted(d.failure_incident_id)
from functools import partial
- from cron.executions import get_execution, recover_receipted_execution
+ from cron.executions import FIRER_FINISHED_STATES, get_execution, recover_receipted_execution
finish = partial(recover_receipted_execution, job_id=job['id']) if recovered else scheduler.finish_execution
finished = finish(
execution_id, success=d.success, error=d.error, delivery_outcome=delivery_outcome)
@@ -120,7 +120,7 @@ def finish_completed_run(d, fire_owner: Optional[str], execution_id: str, *, rec
current = get_execution(execution_id)
# A live foreign firer still owns this row. Keep its only recovery link until settlement.
# Legacy direct calls may have no execution row; an already-finished row is also safe.
- if current is not None and current['status'] not in {'completed', 'failed'}:
+ if current is not None and current['status'] not in FIRER_FINISHED_STATES:
return False
if job.get("last_delivery_queued"):
# A drain that settled before this run's own bookkeeping landed found nothing to fence on.
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 3ba33ea41b1..d05af295bf1 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -334,7 +334,7 @@ PLATFORM_ERROR_CLASSES = frozenset({"none", "auth", "network", "rate_limited", "
DELIVERY_OUTCOMES = frozenset({"sent", "failed"})
DELIVERY_FAILURE_CLASSES = frozenset({"none", "rate_limited", "too_long", "auth", "network", "forbidden", "other"})
REPLY_LATENCY_BUCKETS = frozenset({"lt_2s", "2s_to_5s", "5s_to_15s", "15s_to_60s", "gte_60s"})
-CRON_RUN_OUTCOMES = frozenset({"success", "failed", "missed", "skipped"})
+CRON_RUN_OUTCOMES = frozenset({"success", "failed", "missed", "skipped", "cancelled"})
CRON_DELIVERY_KINDS = frozenset({"local", "platform", "webhook", "none", "other"})
# ---- v4 install ----
diff --git a/hermes_cli/observability/shared_metrics_gateway.py b/hermes_cli/observability/shared_metrics_gateway.py
index 479dd5f2cee..55cd3d50eda 100644
--- a/hermes_cli/observability/shared_metrics_gateway.py
+++ b/hermes_cli/observability/shared_metrics_gateway.py
@@ -464,7 +464,9 @@ def record_cron_finish(record: Any, delivery_outcome: Any = None) -> None:
_cron_skipped.discard(execution_id)
started = record.get("started_at")
success = record.get("status") == "completed"
- if gated or (not started and not success and delivery_outcome is None):
+ if record.get("status") == "cancelled": # an operator stop, not a failure
+ outcome = "cancelled"
+ elif gated or (not started and not success and delivery_outcome is None):
outcome = "skipped"
else:
outcome = "success" if success else "failed"
diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.py
index b7315d3bb5d..3e60b8c9828 100644
--- a/hermes_cli/web_routers/cron.py
+++ b/hermes_cli/web_routers/cron.py
@@ -569,7 +569,7 @@ def _reconcile_cron_runs(
terminal = [(index, a) for index, a in enumerate(attempts) if a["status"] in _OUTCOME_STATES]
represented = {index for index, a in terminal if a["id"] in by_execution}
paired: set = set()
- merged = list(session_runs)
+ merged = _with_cancel_reasons(session_runs, terminal)
for doc in docs:
doc_ts = float(doc.get("started_at") or 0)
@@ -605,6 +605,23 @@ def _reconcile_cron_runs(
return merged[:limit]
+def _with_cancel_reasons(
+ session_runs: list[dict[str, Any]], terminal: list[tuple[int, dict[str, Any]]],
+) -> list[dict[str, Any]]:
+ """Session rows, with a stopped agent run's title naming the stop and its reason.
+
+ The session stands in for its ledger attempt (richer record), so the attempt's own row is
+ dropped; without this, a cancelled agent run would read like any finished one.
+ """
+ cancelled = {a["id"]: a for _, a in terminal if a["status"] == "cancelled"}
+ return [
+ {**s, "title": _execution_status_title(
+ "cancelled", cancelled[s["cron_execution_id"]]["error"], s.get("title") or "")}
+ if s.get("cron_execution_id") in cancelled else s
+ for s in session_runs
+ ]
+
+
def _doc_writer(doc_ts: float, attempt: dict[str, Any], session: Optional[dict[str, Any]]) -> tuple:
"""Sort key over a doc's candidate attempts, likeliest writer first.
diff --git a/tests/cron/test_cron_cancel_bookkeeping.py b/tests/cron/test_cron_cancel_bookkeeping.py
new file mode 100644
index 00000000000..8d4943bd997
--- /dev/null
+++ b/tests/cron/test_cron_cancel_bookkeeping.py
@@ -0,0 +1,188 @@
+"""A stopped cron run stays stopped in every reader of the ledger.
+
+Real store, real execution ledger, real cancel markers under the test HERMES_HOME: a cancel must not
+be replayed by receipt recovery, read as a crashed worker, counted as a failure, spend an extra
+repeat, or hide behind the due scan's ``missed`` rows.
+"""
+
+from __future__ import annotations
+
+import json
+from contextlib import asynccontextmanager
+from datetime import timedelta
+
+import pytest
+
+from cron import executions, jobs, scheduler, scheduler_authority
+
+
+def store(tmp_path):
+ with jobs.use_cron_store(tmp_path / "cron"):
+ yield tmp_path
+
+
+def _cancelled_run(job: dict) -> str:
+ from cron.cancellation import finish_cancelled_run, request_cancel
+
+ fire = executions.create_execution(job["id"], source="test")["id"]
+ executions.mark_execution_running(fire)
+ request_cancel(fire, reason="operator asked")
+ finish_cancelled_run(dict(jobs.get_job(job["id"])), fire, None)
+ return fire
+
+
+def test_receipt_recovery_does_not_replay_a_cancelled_agent_run(store, monkeypatch):
+ from hermes_cli import gateway_client
+
+ calls: list = []
+
+ class Peer:
+ async def rpc(self, method, **params):
+ calls.append(method)
+ return {"status": "terminal", "job": job, "result": [False, "doc", "", "stopped"]}
+
+ @asynccontextmanager
+ async def connected():
+ yield Peer()
+
+ monkeypatch.setattr(gateway_client, "connect_gateway", connected)
+ job = jobs.create_job(prompt="report", schedule="every 1h", deliver="local")
+ fire = _cancelled_run(job)
+ journal = scheduler_authority.journal_path(job["id"], fire)
+ journal.parent.mkdir(parents=True, exist_ok=True)
+ journal.write_text(json.dumps({
+ "params": {"job_id": job["id"], "request_id": fire, "extra_prompt": None},
+ "receipt": {"session_id": "s", "admission_id": "a"}}))
+ booked = jobs.get_job(job["id"])
+
+ scheduler_authority.reconcile_pending()
+
+ after = jobs.get_job(job["id"])
+ assert calls == []
+ assert (after["last_status"], after["repeat"], after.get("failure_streak")) == (
+ booked["last_status"], booked["repeat"], booked.get("failure_streak"))
+ assert executions.get_execution(fire)["status"] == "cancelled"
+ assert not journal.exists()
+
+
+def test_the_external_worker_waiter_accepts_a_cancelled_row(store):
+ """The detached worker books ``cancelled`` and exits 0; that is a finished attempt, not a
+ worker that died without terminalizing."""
+ job = jobs.create_job(prompt="report", schedule="every 1h", deliver="local")
+ fire = _cancelled_run(job)
+
+ class Exited:
+ def wait(self, timeout=None):
+ return 0
+
+ def poll(self):
+ return 0
+
+ assert scheduler._wait_for_external_cron_worker_body(
+ Exited(), execution_id=fire, stderr_path=None) is True
+
+
+def test_a_missed_row_does_not_hide_a_live_run(store):
+ job = jobs.create_job(prompt="long", schedule="every 1h", deliver="local")
+ live = executions.create_execution(job["id"], source="test")["id"]
+ executions.mark_execution_running(live)
+ executions.record_missed_occurrences(job["id"], count=3, first_instant=None, detail="slept")
+
+ assert executions.live_inflight_execution(job["id"])["id"] == live
+
+
+def test_stopping_a_ladder_rerun_does_not_spend_another_repeat(store):
+ from cron.cancellation import finish_cancelled_run, request_cancel
+ from cron.unreachable_retry import STATE_KEY
+
+ job = jobs.create_job(prompt="ping", schedule="every 1h", deliver="local", repeat=2)
+ stored = jobs.load_jobs()
+ stored[0]["repeat"]["completed"] = 1 # the original occurrence already counted
+ jobs.save_jobs(stored)
+ instant = jobs.get_job(job["id"])["next_run_at"]
+ rerun = dict(jobs.get_job(job["id"]), _scheduled_instant=instant,
+ **{STATE_KEY: {"at": instant, "expr": job["schedule"].get("expr")}})
+ fire = executions.create_execution(job["id"], source="test")["id"]
+ request_cancel(fire)
+
+ finish_cancelled_run(rerun, fire, None)
+
+ after = jobs.get_job(job["id"])
+ assert after["repeat"]["completed"] == 1
+ assert after["enabled"]
+
+
+def test_removal_before_the_run_starts_books_cancelled_not_claim_loss(store, monkeypatch):
+ """remove_job writes the marker and drops the claim; the worker's first claim check must book
+ the operator's stop, not "Fire claim ownership lost before execution started"."""
+ from cron.cancellation import request_cancel
+
+ job = jobs.create_job(prompt="long", schedule="every 1h", deliver="local")
+ fire = executions.create_execution(job["id"], source="test")["id"]
+ request_cancel(fire, reason="job removed while running")
+ monkeypatch.setattr(scheduler, "heartbeat_fire_claim", lambda *a, **k: False)
+ ran: list = []
+
+ claimed = dict(job, execution_id=fire, fire_claim={"by": "me", "at": "now"})
+ assert scheduler._run_with_fire_claim_heartbeat(claimed, ran.append) is True
+
+ assert ran == []
+ row = executions.get_execution(fire)
+ assert (row["status"], row["error"]) == ("cancelled", "job removed while running")
+
+
+def test_overlapping_cancel_requests_keep_the_first_reason(store, monkeypatch):
+ """Both callers can pass the existence check before either publishes its marker."""
+ from pathlib import Path
+
+ from cron.cancellation import CancelRequest, request_cancel
+
+ real_exists = Path.exists
+ monkeypatch.setattr(
+ Path, "exists", lambda self: False if self.name == "exec-race.cancel" else real_exists(self))
+
+ request_cancel("exec-race", reason="first ask")
+ request_cancel("exec-race", reason="second ask")
+
+ assert CancelRequest("exec-race").reason == "first ask"
+
+
+def test_monitoring_reports_stops_and_misses_as_themselves(monkeypatch):
+ from agent.monitoring.cron_health import project_execution_event
+ from hermes_cli.observability import shared_metrics_gateway as metrics
+
+ assert project_execution_event({"status": "cancelled", "job_id": "j"}).status == "cancelled"
+ assert project_execution_event({"status": "missed", "job_id": "j"}).status == "missed"
+
+ sent: list = []
+ monkeypatch.setattr(metrics, "_submit", lambda emit, mark, fields, **kw: sent.append(fields(**kw)))
+ metrics.record_cron_finish({"id": "e1", "status": "cancelled", "started_at": "2026-01-01T00:00:00",
+ "finished_at": "2026-01-01T00:00:05"})
+ assert sent[0]["outcome"] == "cancelled"
+
+
+def test_a_cancelled_agent_run_names_its_reason_in_history():
+ from hermes_cli.web_routers.cron import _reconcile_cron_runs
+
+ session = {"id": "s1", "title": "Morning brief", "cron_execution_id": "ex1",
+ "started_at": 100.0}
+ attempts = [{"id": "ex1", "status": "cancelled", "error": "cancelled on request (Stop)",
+ "claimed_at": 99.0, "finished_at": 120.0}]
+
+ rows = _reconcile_cron_runs([session], [], attempts, "job", 10)
+
+ assert [r["title"] for r in rows] == ["CANCELLED · cancelled on request (Stop)"]
+
+
+def test_a_capped_count_says_so_after_a_catch_up(store):
+ job = jobs.create_job(prompt="tick", schedule="every 1m", deliver="local", catch_up=True)
+ stored = jobs.load_jobs()
+ stored[0]["next_run_at"] = (jobs._hermes_now() - timedelta(minutes=1100)).isoformat()
+ jobs.save_jobs(stored)
+
+ jobs.get_due_jobs()
+
+ missed = [r for r in executions.list_executions(job_id=job["id"]) if r["status"] == "missed"]
+ assert len(missed) == 1
+ assert "counting stopped at 1000" in missed[0]["error"]