The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: virtual-clock soak of the real cron ticker loop (C13)
teknium1ac5577c09fd1
diff --git a/tests/e2e/core/delivery/__init__.py b/tests/e2e/core/delivery/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/delivery/_cron_clock.py b/tests/e2e/core/delivery/_cron_clock.pynew file mode 100644index 00000000000..e76dae0f697--- /dev/null+++ b/tests/e2e/core/delivery/_cron_clock.py@@ -0,0 +1,505 @@+"""Lane-private harness for the C13 virtual-clock cron soak (test_cron_virtual_clock_soak.py).++What is virtual and what stays real:++* ``VirtualClock`` is ONE epoch value in a file shared by every process of a scenario. It is+ installed at the single wall-clock seam — ``hermes_time.datetime`` (every ``_hermes_now``+ binding in cron/jobs.py, scheduler.py, executions.py, occurrences via jobs, ... resolves+ ``hermes_time.now()`` -> ``datetime.now(tz)`` at call time) — plus the ``time.time()`` reads of+ cron.jobs / cron.scheduler / cron.executions (in-flight ages, ledger handoff grace, ticker+ heartbeat marker). ``time.monotonic`` stays real on purpose: it only paces REAL waits (lock+ deadlines, heartbeat thread cadence, reap/GC throttles).+* The fire-claim heartbeat cadence is time-scaled (60 s -> ``HEARTBEAT_REAL_SECONDS``) so a+ run that spans many virtual minutes still refreshes its lease the way a real one would.+* Fakes: the agent (``cron.scheduler.run_job``, the one function that would build an AIAgent)+ and the platform wire (``tools.send_message_tool._send_to_platform``). Both append JSONL+ records. Everything between — the real ``InProcessCronScheduler.start`` ticker loop,+ ``tick()``, due scan, pending slots, fire claims, heartbeat, executions ledger, delivery+ routing, ``mark_job_run`` — is production code.++``SchedulerHost`` runs the real ticker loop in a thread with a stepping ``stop_event``; running+this file as a script runs the same loop in a separate OS process (``ChildHost``), stepped via+files, so two processes can contend for one ``HERMES_HOME`` and one can be SIGKILLed mid-run.+"""++from __future__ import annotations++import contextvars+import datetime as _dt+import json+import os+import signal+import sqlite3+import subprocess+import sys+import threading+import time as _real_time+from pathlib import Path+from typing import Any, Callable, Dict, Iterable, List, Optional++REAL_DATETIME = _dt.datetime+HEARTBEAT_REAL_SECONDS = 0.05+POLL_SECONDS = 0.005+DEADLINE_SECONDS = 120.0+HOLD_DEADLINE_SECONDS = 300.0++_CURRENT_EXECUTION: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar(+ "c13_current_execution", default=None)+++def wait_until(predicate: Callable[[], Any], what: str, timeout: float = DEADLINE_SECONDS):+ """Poll ``predicate`` until truthy (returned) or raise after a generous real deadline."""+ deadline = _real_time.monotonic() + timeout+ delay = POLL_SECONDS / 8+ while True:+ value = predicate()+ if value:+ return value+ if _real_time.monotonic() >= deadline:+ raise AssertionError(f"timed out after {timeout:.0f}s waiting for {what}")+ _real_time.sleep(delay)+ delay = min(delay * 2, POLL_SECONDS)+++def _atomic_write(path: Path, text: str) -> None:+ tmp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")+ tmp.write_text(text, encoding="utf-8")+ os.replace(tmp, path)+++def _append_jsonl(path: Path, record: dict) -> None:+ line = (json.dumps(record, sort_keys=True) + "\n").encode("utf-8")+ fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)+ try:+ os.write(fd, line)+ finally:+ os.close(fd)+++def read_jsonl(path: Path) -> List[dict]:+ if not path.exists():+ return []+ out = []+ for line in path.read_text(encoding="utf-8").splitlines():+ if line.strip():+ out.append(json.loads(line))+ return out+++class Control:+ """Filesystem layout of one scenario (shared by the parent and child hosts)."""++ def __init__(self, root: Path):+ self.root = Path(root)+ self.clock_file = self.root / "clock"+ self.runs = self.root / "runs.jsonl"+ self.sink = self.root / "sink.jsonl"+ self.behaviors = self.root / "behaviors.json"+ self.gates = self.root / "gates"+ self.child = self.root / "child"++ def ensure(self) -> "Control":+ for d in (self.root, self.gates, self.child):+ d.mkdir(parents=True, exist_ok=True)+ if not self.behaviors.exists():+ self.set_behaviors({})+ return self++ def set_behaviors(self, behaviors: Dict[str, dict]) -> None:+ _atomic_write(self.behaviors, json.dumps(behaviors))++ def behavior(self, name: str) -> dict:+ try:+ return json.loads(self.behaviors.read_text(encoding="utf-8")).get(name) or {}+ except (OSError, ValueError):+ return {}++ def hold_file(self, name: str) -> Path:+ return self.gates / f"{name}.hold"+++class VirtualClock:+ """File-backed epoch seconds; every process of a scenario reads the same instant."""++ def __init__(self, path: Path):+ self.path = Path(path)++ def now_ts(self) -> float:+ return float(self.path.read_text(encoding="utf-8"))++ def set(self, ts: float) -> None:+ _atomic_write(self.path, repr(float(ts)))++ def advance(self, seconds: float) -> float:+ ts = self.now_ts() + seconds+ self.set(ts)+ return ts+++def _virtual_datetime_class(clock: VirtualClock):+ class VirtualDatetime(REAL_DATETIME):+ @classmethod+ def now(cls, tz=None): # noqa: D401 - datetime API+ return REAL_DATETIME.fromtimestamp(clock.now_ts(), tz)++ return VirtualDatetime+++class _TimeProxy:+ """Stand-in for the ``time`` module inside cron modules: virtual ``time()``, real rest."""++ def __init__(self, clock: VirtualClock):+ self._clock = clock++ def time(self) -> float:+ return self._clock.now_ts()++ def __getattr__(self, name):+ return getattr(_real_time, name)+++class FakeAgent:+ """Replaces ``cron.scheduler.run_job``; returns the real 4-tuple contract."""++ def __init__(self, clock: VirtualClock, control: Control):+ self.clock = clock+ self.control = control++ def __call__(self, job, *, execution_id=None, **_kwargs):+ name = job.get("name") or job["id"]+ _CURRENT_EXECUTION.set(execution_id)+ record = {+ "event": "start", "exec": execution_id, "job_id": job["id"], "name": name,+ "instant": job.get("_scheduled_instant"), "fired_at": self.clock.now_ts(),+ "pid": os.getpid(),+ }+ _append_jsonl(self.control.runs, record)+ behavior = self.control.behavior(name)+ hold = self.control.hold_file(name)+ if hold.exists():+ _atomic_write(self.control.gates / f"{name}.entered", str(execution_id))+ deadline = _real_time.monotonic() + HOLD_DEADLINE_SECONDS+ while hold.exists() and _real_time.monotonic() < deadline:+ _real_time.sleep(POLL_SECONDS)+ _append_jsonl(self.control.runs, dict(record, event="end", ended_at=self.clock.now_ts()))+ output = f"# {name}\n\nexec={execution_id}\n"+ if behavior.get("agent") == "fail":+ return False, output, "", f"simulated provider outage exec={execution_id}"+ return True, output, f"report for {name} exec={execution_id}", None+++class FakeSink:+ """Replaces ``tools.send_message_tool._send_to_platform`` (the standalone wire)."""++ def __init__(self, clock: VirtualClock, control: Control):+ self.clock = clock+ self.control = control++ def _behavior_for(self, message: str) -> dict:+ try:+ behaviors = json.loads(self.control.behaviors.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}+ for name, behavior in behaviors.items():+ if name in message:+ return behavior or {}+ return {}++ async def __call__(self, platform, pconfig, chat_id, message, thread_id=None,+ media_files=None, **_kwargs):+ import asyncio++ execution_id = _CURRENT_EXECUTION.get()+ behavior = self._behavior_for(message)+ if behavior.get("delivery") == "slow":+ await asyncio.sleep(0.25)+ ok = behavior.get("delivery") != "fail"+ _append_jsonl(self.control.sink, {+ "exec": execution_id, "ok": ok, "chat_id": str(chat_id),+ "platform": getattr(platform, "value", str(platform)),+ "exec_in_text": bool(execution_id) and f"exec={execution_id}" in message,+ "at": self.clock.now_ts(), "pid": os.getpid(),+ })+ if not ok:+ return {"error": "simulated 502 from platform"}+ return {"success": True, "message_id": f"m-{execution_id}"}+++def install(clock: VirtualClock, control: Control, setattr_fn=setattr) -> None:+ """Install the virtual clock + fakes. ``setattr_fn`` is ``monkeypatch.setattr`` in pytest."""+ import cron.executions as executions+ import cron.jobs as jobs+ import cron.scheduler as scheduler+ import hermes_time+ import tools.send_message_tool as send_message_tool++ setattr_fn(hermes_time, "datetime", _virtual_datetime_class(clock))+ proxy = _TimeProxy(clock)+ for module in (jobs, scheduler, executions):+ setattr_fn(module, "time", proxy)+ setattr_fn(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", HEARTBEAT_REAL_SECONDS)+ setattr_fn(scheduler, "run_job", FakeAgent(clock, control))+ setattr_fn(send_message_tool, "_send_to_platform", FakeSink(clock, control))+ # Durability is not under test (SIGKILL keeps the page cache); per-write fsync of+ # jobs.json/markers dominates wall time at virtual cadence. Atomic renames stay real.+ setattr_fn(os, "fsync", lambda _fd: None)+ import hermes_cli.sqlite_util as sqlite_util++ real_open_db = sqlite_util.open_db++ def open_db_no_full_sync(*args, **kwargs): # same connection, WAL, schema; no per-commit fsync+ kwargs["synchronous_full"] = False+ conn = real_open_db(*args, **kwargs)+ conn.execute("PRAGMA synchronous=OFF") # also skips the checkpoint-on-close fsync+ return conn++ setattr_fn(sqlite_util, "open_db", open_db_no_full_sync)+ # Worktree GC prunes the REAL git checkout the test runs from; hygiene, not scheduling.+ setattr_fn(scheduler, "_maybe_run_worktree_maintenance", lambda: None)+ hermes_time.reset_cache()+++# --- stepping ticker hosts -------------------------------------------------------------------++class _StepGate:+ """``stop_event`` for ``InProcessCronScheduler.start``: each ``wait()`` parks the real ticker+ loop until the driver releases the next iteration."""++ def __init__(self):+ self.cv = threading.Condition()+ self.idle = 0+ self.go = 0+ self.stopped = False++ def is_set(self) -> bool:+ return self.stopped++ def set(self) -> None:+ with self.cv:+ self.stopped = True+ self.cv.notify_all()++ def wait(self, timeout=None) -> bool:+ with self.cv:+ self.idle += 1+ self.cv.notify_all()+ deadline = _real_time.monotonic() + HOLD_DEADLINE_SECONDS+ while not self.stopped and self.go < self.idle:+ remaining = deadline - _real_time.monotonic()+ if remaining <= 0:+ self.stopped = True+ break+ self.cv.wait(min(remaining, 1.0))+ return self.stopped+++class SchedulerHost:+ """The real in-process ticker loop, one iteration per ``release()``."""++ label = "inproc"++ def __init__(self):+ self.gate: Optional[_StepGate] = None+ self.thread: Optional[threading.Thread] = None+ self.errors: List[BaseException] = []++ @property+ def alive(self) -> bool:+ return self.thread is not None and self.thread.is_alive()++ def start(self) -> None:+ """Boot the loop (startup recovery + the boot tick run immediately)."""+ from cron.scheduler_provider import InProcessCronScheduler++ gate = self.gate = _StepGate()++ def _run():+ try:+ InProcessCronScheduler().start(gate, interval=60)+ except BaseException as exc: # pragma: no cover - surfaced by wait_idle+ self.errors.append(exc)++ self.thread = threading.Thread(target=_run, name="c13-ticker", daemon=True)+ self.thread.start()+ self.wait_idle()++ def release(self) -> None:+ with self.gate.cv:+ self.gate.go += 1+ self.gate.cv.notify_all()++ def wait_idle(self) -> None:+ gate = self.gate++ def _idle():+ if self.errors:+ raise AssertionError(f"ticker thread died: {self.errors[0]!r}")+ with gate.cv:+ return gate.idle >= gate.go + 1++ wait_until(_idle, "in-process ticker iteration")++ def tick(self) -> None:+ self.release()+ self.wait_idle()++ def stop(self) -> None:+ if self.gate is not None:+ self.gate.set()+ if self.thread is not None:+ self.thread.join(timeout=DEADLINE_SECONDS)+ assert not self.thread.is_alive(), "ticker thread did not stop"+ self.thread = None+++class _FileGate:+ """Child-process ``stop_event`` stepped through ``<control>/child/{go,idle,stop}``."""++ def __init__(self, control: Control):+ self.dir = control.child+ self.idle = 0++ def is_set(self) -> bool:+ return (self.dir / "stop").exists()++ def set(self) -> None:+ (self.dir / "stop").write_text("1", encoding="utf-8")++ def _go(self) -> int:+ try:+ return int((self.dir / "go").read_text(encoding="utf-8") or 0)+ except (OSError, ValueError):+ return 0++ def wait(self, timeout=None) -> bool:+ self.idle += 1+ _atomic_write(self.dir / "idle", str(self.idle))+ deadline = _real_time.monotonic() + HOLD_DEADLINE_SECONDS+ while not self.is_set() and self._go() < self.idle:+ if _real_time.monotonic() >= deadline:+ return True+ _real_time.sleep(POLL_SECONDS)+ return self.is_set()+++class ChildHost:+ """Same real ticker loop in a separate OS process sharing the scenario's HERMES_HOME."""++ label = "child"++ def __init__(self, control: Control, env: Dict[str, str], repo_root: Path):+ self.control = control+ self.env = env+ self.repo_root = repo_root+ self.proc: Optional[subprocess.Popen] = None+ self.go = 0++ @property+ def pid(self) -> Optional[int]:+ return self.proc.pid if self.proc is not None else None++ @property+ def alive(self) -> bool:+ return self.proc is not None and self.proc.poll() is None++ def _idle(self) -> int:+ try:+ return int((self.control.child / "idle").read_text(encoding="utf-8") or 0)+ except (OSError, ValueError):+ return 0++ def start(self) -> None:+ for name in ("go", "idle", "stop"):+ (self.control.child / name).unlink(missing_ok=True)+ self.go = 0+ log = open(self.control.child / "stderr.log", "a", encoding="utf-8") # noqa: SIM115+ self.proc = subprocess.Popen(+ [sys.executable, str(Path(__file__).resolve()), str(self.control.root)],+ cwd=str(self.repo_root), env=self.env, stdin=subprocess.DEVNULL,+ stdout=log, stderr=log)+ log.close()+ self.wait_idle(timeout=180.0)++ def release(self) -> None:+ self.go += 1+ _atomic_write(self.control.child / "go", str(self.go))++ def wait_idle(self, timeout: float = DEADLINE_SECONDS) -> None:+ def _idle():+ if self.proc.poll() is not None:+ tail = (self.control.child / "stderr.log").read_text(encoding="utf-8")[-4000:]+ raise AssertionError(f"child ticker exited rc={self.proc.returncode}:\n{tail}")+ return self._idle() >= self.go + 1++ wait_until(_idle, "child ticker iteration", timeout=timeout)++ def tick(self) -> None:+ self.release()+ self.wait_idle()++ def kill(self) -> None:+ """SIGKILL: the process dies with whatever it had in flight (a crash, not a drain)."""+ if self.proc is not None and self.proc.poll() is None:+ os.kill(self.proc.pid, signal.SIGKILL)+ self.proc.wait(timeout=DEADLINE_SECONDS)++ def stop(self) -> None:+ if self.proc is None:+ return+ if self.proc.poll() is None:+ (self.control.child / "stop").write_text("1", encoding="utf-8")+ try:+ self.proc.wait(timeout=DEADLINE_SECONDS)+ except subprocess.TimeoutExpired:+ self.kill()+++def tick_together(hosts: Iterable[Any]) -> None:+ """Release every live host at the same virtual instant, then wait for all of them."""+ live = [h for h in hosts if h is not None and h.alive]+ for host in live:+ host.release()+ for host in live:+ host.wait_idle()+++# --- ledger / store readers ------------------------------------------------------------------++def ledger_rows(home: Path, where: str = "") -> List[dict]:+ path = Path(home) / "cron" / "executions.db"+ if not path.exists():+ return []+ conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=30)+ try:+ conn.row_factory = sqlite3.Row+ sql = "SELECT * FROM executions" + (f" WHERE {where}" if where else "")+ return [dict(r) for r in conn.execute(sql)]+ finally:+ conn.close()+++def non_terminal(home: Path, ignore: Iterable[str] = ()) -> List[dict]:+ ignore = set(ignore)+ return [r for r in ledger_rows(home, "status IN ('claimed', 'running')")+ if r["id"] not in ignore]+++def store_jobs(home: Path) -> List[dict]:+ path = Path(home) / "cron" / "jobs.json"+ if not path.exists():+ return []+ return json.loads(path.read_text(encoding="utf-8")).get("jobs", [])+++def _child_main(control_root: str) -> None:+ control = Control(Path(control_root))+ clock = VirtualClock(control.clock_file)+ install(clock, control)+ from cron.scheduler_provider import InProcessCronScheduler++ InProcessCronScheduler().start(_FileGate(control), interval=60)+++if __name__ == "__main__": # child ticker process+ sys.path.insert(0, os.getcwd())+ _child_main(sys.argv[1])diff --git a/tests/e2e/core/delivery/test_cron_virtual_clock_soak.py b/tests/e2e/core/delivery/test_cron_virtual_clock_soak.pynew file mode 100644index 00000000000..eafb55d72f1--- /dev/null+++ b/tests/e2e/core/delivery/test_cron_virtual_clock_soak.py@@ -0,0 +1,590 @@+"""C13 — virtual-clock soak of the REAL cron ticker loop (~30 virtual days per scenario).++Real: ``InProcessCronScheduler.start`` (the gateway's ticker loop: startup recovery, tick, heartbeat+bookkeeping), ``cron.scheduler.tick`` / due scan / pending slots / fire claims + heartbeat /+executions ledger / delivery routing / ``mark_job_run``, a second OS process sharing HERMES_HOME.+Fake: the agent (``cron.scheduler.run_job``) and the platform wire (``_send_to_platform``), which+record what they were handed. Time: one file-backed virtual clock (see ``_cron_clock``).++Oracle (independent of cron/jobs.py): per job, the expected fire set is computed from croniter+over the job's configured zone (hermes ``timezone`` if set, else the process zone — "server+local"), stepping only through the tick instants the harness actually drove, with the documented+policies:+* a wall time that does not exist (spring-forward gap) fires once, shifted by the gap; a repeated+ wall time (fall-back fold) fires once, on its first occurrence;+* a missed recurring occurrence fires ONCE on the first tick after it (``catch_up_missed``+ default true), whether within grace (late) or beyond it (catch-up), then re-anchors on "now";+* intervals re-anchor on the fire instant; a one-shot beyond ``ONESHOT_GRACE_SECONDS`` never+ fires; manual runs (direct or trigger) never consume or re-stamp the next scheduled occurrence.+After every tick: the actual fires == expected fires, every stored ``next_run_at`` equals the+model's pending occurrence and is strictly after virtual now, and the ticker reported no error.+At the end: no execution is non-terminal; every row's status/delivery outcome matches what the+fake runner/sink actually saw (delivered => the sink got exactly that execution's message).+"""++from __future__ import annotations++import bisect+import dataclasses+import math+import os+import sys+import time+from datetime import date, datetime, timedelta, timezone+from pathlib import Path+from typing import Dict, List, Optional+from zoneinfo import ZoneInfo++import pytest++croniter_mod = pytest.importorskip("croniter")++from tests.e2e.core.delivery import _cron_clock as H # noqa: E402++pytestmark = pytest.mark.skipif(+ sys.platform != "linux", reason="flock/SIGKILL multi-process soak is Linux-only")++REPO_ROOT = Path(__file__).resolve().parents[4]+GRID_SECONDS = 6 * 3600 # sparse idle ticks; due/pre-due ticks are added per occurrence+HOLD_STEPS = 30 # long run: 30 x 30 s = 15 virtual minutes (> 5 min fire-claim TTL)+UTC = timezone.utc++[email protected](frozen=True)+class Scenario:+ id: str+ hermes_tz: Optional[str]+ process_tz: str+ start: date # DST day is always start + 9+ child: bool = False # two-process contention + SIGKILL/restart mid-run+ days: int = 30+++SCENARIOS = [+ # nothing configured, process in UTC: server-local == UTC+ Scenario("unset_utc_spring", None, "UTC", date(2026, 2, 27), child=True),+ # configured zone with no DST under a foreign DST process zone (process DST night inside)+ Scenario("shanghai_on_la_fall", "Asia/Shanghai", "America/Los_Angeles", date(2026, 10, 23)),+ # configured US zone across spring-forward, fixed +08:00 process zone+ Scenario("newyork_on_shanghai_spring", "America/New_York", "Asia/Shanghai", date(2026, 2, 27)),+ # configured US zone across fall-back, fixed +08:00 process zone, multi-process faults+ Scenario("newyork_on_shanghai_fall", "America/New_York", "Asia/Shanghai",+ date(2026, 10, 23), child=True),+]+KNOWN_BUG = [+ # #119969 (fix: PR #119970): with NO timezone configured the next occurrence is computed in+ # the base time's fixed UTC offset, so a DST process zone fires 09:00 at 10:00 local on the+ # spring-forward day. Strict: the day the fix lands this XPASSes and the mark must go.+ pytest.param(Scenario("unset_on_newyork_spring", None, "America/New_York",+ date(2026, 2, 27), days=12),+ marks=pytest.mark.xfail(strict=True, reason="#119969 no-tz DST fixed offset"),+ id="unset_on_newyork_spring"),+]+++def _iso(ts: float) -> str:+ return datetime.fromtimestamp(ts, UTC).isoformat()+++def _ceil_minute(ts: float) -> float:+ return math.ceil(ts / 60.0) * 60.0+++# --- independent schedule model --------------------------------------------------------------++class CronOccurrences:+ """All instants of a cron expr in ``zone`` over a window: wall times from croniter (naive),+ each mapped with fold=0 (gap -> shifted forward, fold -> first occurrence), deduped."""++ def __init__(self, expr: str, zone, start_ts: float, end_ts: float):+ wall = datetime.fromtimestamp(start_ts, zone).replace(tzinfo=None) - timedelta(days=2)+ stop = datetime.fromtimestamp(end_ts, zone).replace(tzinfo=None) + timedelta(days=2)+ it = croniter_mod.croniter(expr, wall)+ instants = set()+ while True:+ w = it.get_next(datetime)+ if w > stop:+ break+ instants.add(w.replace(tzinfo=zone, fold=0).timestamp())+ self.instants = sorted(instants)++ def first_after(self, ts: float) -> float:+ return self.instants[bisect.bisect_right(self.instants, ts)]+++class ModelJob:+ name: str+ kind: str # cron | interval | once+ pending: Optional[float]+ occ: Optional[CronOccurrences] = None+ interval: float = 0.0+ times: Optional[int] = None+ fired: int = 0+ trigger: bool = False+ done: bool = False++ def advance_from(self, t: float) -> None:+ if self.times is not None and self.fired >= self.times:+ self.done, self.pending = True, None+ elif self.kind == "cron":+ self.pending = self.occ.first_after(t)+ elif self.kind == "interval":+ self.pending = t + self.interval+ else:+ self.done, self.pending = True, None+++class Model:+ def __init__(self):+ self.jobs: Dict[str, ModelJob] = {}+ self.fires: List[tuple] = [] # (name, instant_iso | None, fired_at)++ def active(self):+ return [j for j in self.jobs.values() if not j.done]++ def tick(self, t: float) -> None:+ for job in self.active():+ if job.trigger:+ job.trigger = False+ job.fired += 1+ self.fires.append((job.name, None, t))+ job.advance_from(t)+ continue+ if job.pending is None or job.pending > t:+ continue+ if job.kind == "once" and t - job.pending > 120: # ONESHOT_GRACE_SECONDS+ job.done, job.pending = True, None+ continue+ job.fired += 1+ self.fires.append((job.name, _iso(job.pending), t))+ job.advance_from(t)++ def manual(self, name: str, t: float) -> None:+ job = self.jobs[name]+ job.fired += 1+ self.fires.append((name, None, t))+ if job.kind == "interval":+ job.pending = t + job.interval+ if job.times is not None and job.fired >= job.times:+ job.done, job.pending = True, None+++# --- the soak driver -------------------------------------------------------------------------+[email protected](order=True)+class Event:+ ts: float+ seq: int+ kind: str = dataclasses.field(compare=False)+ arg: object = dataclasses.field(compare=False, default=None)+++class Soak:+ def __init__(self, sc: Scenario, home: Path, control: H.Control, env: Dict[str, str]):+ self.sc, self.home, self.control = sc, home, control+ self.zone = ZoneInfo(sc.hermes_tz or sc.process_tz)+ self.clock = H.VirtualClock(control.clock_file)+ self.start_ts = self.local(0, 0, 0, 30)+ self.end_ts = self.local(sc.days, 0, 0, 0)+ self.model = Model()+ self.host = H.SchedulerHost()+ self.child = H.ChildHost(control, env, REPO_ROOT) if sc.child else None+ self.parent_up = False+ self.ids: Dict[str, str] = {}+ self.seen_runs = 0+ self.held: set = set()+ self.killed_execs: set = set()+ self.ticks = 0+ self.events: List[Event] = []+ self.stalled_heartbeat = False++ # helpers+ def local(self, day: int, hh: int, mm: int, ss: int = 0) -> float:+ d = self.sc.start + timedelta(days=day)+ return datetime(d.year, d.month, d.day, hh, mm, ss, tzinfo=self.zone).timestamp()++ def at(self, ts: float, kind: str, arg=None) -> None:+ self.events.append(Event(ts, len(self.events), kind, arg))++ def now(self) -> float:+ return self.clock.now_ts()++ def up_hosts(self):+ hosts = [self.host] if self.parent_up else []+ if self.child is not None and self.child.alive:+ hosts.append(self.child)+ return hosts++ def describe(self, t: float) -> str:+ return f"[{self.sc.id} @ {datetime.fromtimestamp(t, self.zone).isoformat()}]"++ # job creation through the real store API+ def create(self, name: str, schedule: str, *, repeat=None, chat="1000"):+ from cron.jobs import create_job++ job = create_job(prompt=f"soak {name}", schedule=schedule, name=name, repeat=repeat,+ deliver=f"telegram:{chat}")+ self.ids[name] = job["id"]+ t = self.now()+ from cron.jobs import parse_schedule++ parsed = parse_schedule(schedule)+ if parsed["kind"] == "cron":+ mj = ModelJob(name, "cron", None, occ=CronOccurrences(+ parsed["expr"], self.zone, self.start_ts, self.end_ts), times=repeat)+ mj.pending = mj.occ.first_after(t)+ elif parsed["kind"] == "interval":+ mj = ModelJob(name, "interval", t + parsed["minutes"] * 60,+ interval=parsed["minutes"] * 60, times=repeat)+ else:+ mj = ModelJob(name, "once", datetime.fromisoformat(parsed["run_at"]).timestamp(),+ times=1)+ self.model.jobs[name] = mj++ # stepping+ def next_tick(self, now: float) -> float:+ if not self.up_hosts():+ return math.inf+ cands = [(math.floor(now / GRID_SECONDS) + 1) * GRID_SECONDS]+ for job in self.model.active():+ if job.trigger:+ cands.append(now + 30)+ if job.pending is not None:+ due = _ceil_minute(job.pending)+ cands += [c for c in (due - 60, due) if c > now]+ return min(c for c in cands if c > now)++ def settle(self) -> None:+ import cron.scheduler as sched++ held_ids = {self.ids[n] for n in self.held}++ def quiet():+ if set(sched.get_running_job_ids()) - held_ids: # cheap in-process check first+ return False+ return not [r for r in H.non_terminal(self.home) if r["job_id"] not in held_ids]++ H.wait_until(quiet, f"scheduler quiescence {self.describe(self.now())}")++ def tick(self, hosts=None, entering: Optional[str] = None) -> None:+ t = self.now()+ H.tick_together(self.up_hosts() if hosts is None else hosts)+ self.ticks += 1+ if entering is not None: # a held run: wait until it has really started+ self._entered_exec(entering)+ self.settle()+ self.model.tick(t)+ self.check(t)++ def check(self, t: float) -> None:+ from cron.jobs import get_ticker_last_error++ where = self.describe(t)+ starts = [r for r in H.read_jsonl(self.control.runs) if r["event"] == "start"]+ actual = sorted((r["name"], r["instant"], r["fired_at"]) for r in starts[self.seen_runs:])+ self.seen_runs = len(starts)+ expected = sorted(self.model.fires)+ self.model.fires = []+ assert actual == expected, f"{where} fired set mismatch: actual={actual} expected={expected}"+ err = get_ticker_last_error()+ assert not err, f"{where} ticker recorded an error: {err}"+ by_id = {j["id"]: j for j in H.store_jobs(self.home)}+ for name, mj in self.model.jobs.items():+ stored = by_id.get(self.ids.get(name))+ if mj.done or stored is None:+ continue+ nra = stored.get("next_run_at")+ assert nra, f"{where} {name}: active job lost next_run_at: {stored}"+ nra_ts = datetime.fromisoformat(nra).timestamp()+ assert nra_ts > t, f"{where} {name}: next_run_at {nra} not after virtual now"+ assert nra_ts == mj.pending, (+ f"{where} {name}: next_run_at {nra} != expected {_iso(mj.pending)}")++ # fault handlers+ def handle(self, ev: Event) -> None:+ getattr(self, f"ev_{ev.kind}")(ev.arg)++ def ev_create(self, arg):+ self.create(*arg[:2], **arg[2])++ def ev_behavior(self, arg):+ self.control.set_behaviors(arg)++ def ev_manual(self, name):+ from cron.jobs import get_job+ from tools.cronjob_tools import _execute_job_now++ t = self.now()+ result = _execute_job_now(get_job(self.ids[name]))+ assert result.get("claimed") is not False, f"{self.describe(t)} manual run refused: {result}"+ self.settle()+ self.model.manual(name, t)+ self.check(t)++ def ev_trigger(self, name):+ from cron.jobs import trigger_job++ trigger_job(self.ids[name])+ self.model.jobs[name].trigger = True++ def ev_down(self, _arg):+ if self.parent_up:+ self.host.stop()+ self.parent_up = False++ def ev_up(self, _arg):+ self.host.start() # boot: startup recovery + immediate tick+ self.parent_up = True+ self.ticks += 1+ t = self.now()+ rows = {r["id"]: r for r in H.ledger_rows(self.home)}+ for exec_id in self.killed_execs:+ assert rows[exec_id]["status"] not in ("claimed", "running"), (+ f"{self.describe(t)} restart left the SIGKILLed run non-terminal: {rows[exec_id]}")+ self.settle()+ self.model.tick(t)+ self.check(t)++ def ev_child_up(self, _arg):+ t = self.now()+ self.child.start() # child's boot tick at t+ H.tick_together([self.host] if self.parent_up else [])+ self.ticks += 1+ self.settle()+ self.model.tick(t)+ self.check(t)++ def _entered_exec(self, name: str) -> str:+ entered = self.control.gates / f"{name}.entered"++ def exec_id(): # written atomically by the fake agent; never read a half-written file+ return entered.exists() and entered.read_text(encoding="utf-8").strip()++ return H.wait_until(exec_id, f"{name} run to start")++ def ev_long_run(self, name):+ """A run that outlives the fire-claim TTL while the ticker keeps ticking."""+ job_id = self.ids[name]+ hold = self.control.hold_file(name)+ hold.write_text("1", encoding="utf-8")+ self.held.add(name)+ self.tick(entering=name)+ exec_id = self._entered_exec(name)+ t0 = self.now()+ for k in range(1, HOLD_STEPS + 1):+ self.clock.set(t0 + 30 * k)+ if not self.stalled_heartbeat:+ want = t0 + 30 * k - 1++ def fresh():+ job = next(j for j in H.store_jobs(self.home) if j["id"] == job_id)+ claim = job.get("fire_claim") or {}+ return claim.get("at") and datetime.fromisoformat(claim["at"]).timestamp() >= want++ try:+ H.wait_until(fresh, "fire-claim heartbeat", timeout=3.0)+ except AssertionError:+ self.stalled_heartbeat = True+ self.tick()+ hold.unlink()+ self.held.discard(name)+ self.settle()+ self.long_run_exec = exec_id++ def ev_solo_child(self, _arg):+ """Only the child process ticks from here (the in-process gateway is down)."""+ self.ev_down(None)++ def ev_child_kill_run(self, name):+ """The child fires ``name``, and is SIGKILLed while the run holds a live claim."""+ hold = self.control.hold_file(name)+ hold.write_text("1", encoding="utf-8")+ self.held.add(name)+ t = self.now()+ H.tick_together([self.child])+ self.ticks += 1+ exec_id = self._entered_exec(name)+ self.model.tick(t)+ self.child.kill()+ self.killed_execs.add(exec_id)+ rows = {r["id"]: r for r in H.ledger_rows(self.home)}+ assert rows[exec_id]["status"] == "running", rows[exec_id]+ hold.unlink()+ (self.control.gates / f"{name}.entered").unlink()+ self.held.discard(name)+ self.check(t)++ # main+ def schedule_faults(self) -> None:+ L = self.local+ self.at(L(2, 12, 17, 30), "manual", "brief-0900")+ self.at(L(3, 8, 59, 30), "manual", "brief-0900") # inside the 60 s pre-due skew+ self.at(L(4, 8, 0), "behavior", {"brief-0900": {"delivery": "fail"}})+ self.at(L(4, 10, 0), "behavior", {})+ self.at(L(5, 2, 0), "behavior", {"gap-0230": {"agent": "fail"}})+ self.at(L(5, 3, 0), "behavior", {})+ self.at(L(6, 8, 0), "behavior", {"brief-0900": {"delivery": "slow"}})+ self.at(L(6, 10, 0), "behavior", {})+ self.at(L(8, 0, 0, 10), "create", ("every-2h", "every 2h", {"repeat": 48, "chat": "1003"}))+ self.at(L(8, 20, 10, 10), "trigger", "every-2h")+ self.at(L(9, 0, 5), "create", ("quarter", "*/15 * * * *", {"repeat": 24, "chat": "1004"}))+ self.at(L(10, 9, 0), "long_run", "brief-0900")+ once_b = datetime.fromtimestamp(L(11, 10, 0), self.zone).isoformat()+ self.at(L(11, 6, 0), "create", ("oneshot-missed", once_b, {"chat": "1006"}))+ self.at(L(11, 7, 0, 5), "down") # 5 h outage: 09:00 beyond 2 h grace -> one catch-up+ self.at(L(11, 12, 0, 20), "up")+ if self.sc.days <= 13:+ return+ self.at(L(13, 7, 30, 5), "down") # 09:00 missed by 45 min -> fires late, once+ self.at(L(13, 9, 45, 20), "up")+ if self.child is not None:+ self.at(L(15, 0, 0), "child_up") # two processes contend for every fire+ self.at(L(17, 2, 0, 5), "solo_child")+ self.at(L(17, 2, 30), "child_kill_run", "gap-0230")+ self.at(L(17, 3, 10, 20), "up") # gateway restart: startup recovery+ self.events.sort()++ def run(self) -> None:+ self.clock.set(self.start_ts)+ self.create("brief-0900", "0 9 * * *", chat="1001")+ self.create("gap-0230", "30 2 * * *", chat="1002")+ once_a = datetime.fromtimestamp(self.local(5, 12, 34), self.zone).isoformat()+ self.create("oneshot", once_a, chat="1005")+ self.schedule_faults()+ self.events.sort()+ self.ev_up(None)+ while True:+ now = self.now()+ nxt_tick = self.next_tick(now)+ nxt_ev = self.events[0].ts if self.events else math.inf+ target = min(nxt_tick, nxt_ev)+ if target >= self.end_ts:+ break+ self.clock.set(max(target, now))+ if nxt_ev <= nxt_tick:+ self.handle(self.events.pop(0))+ else:+ self.tick()+ self.clock.set(self.end_ts)+ self.settle()+ if self.child is not None:+ self.child.stop()+ self.ev_down(None)++ # final truth checks+ def final_checks(self) -> Dict[str, int]:+ rows = {r["id"]: r for r in H.ledger_rows(self.home)}+ runs = H.read_jsonl(self.control.runs)+ starts = {r["exec"]: r for r in runs if r["event"] == "start"}+ ends = {r["exec"] for r in runs if r["event"] == "end"}+ sink = H.read_jsonl(self.control.sink)+ where = f"[{self.sc.id} final]"+ stuck = [r for r in rows.values() if r["status"] in ("claimed", "running")]+ assert not stuck, f"{where} non-terminal executions left: {stuck}"+ assert set(starts) - ends == self.killed_execs, f"{where} runs without an end"+ assert len(starts) == len(set(starts)), f"{where} duplicate execution ids"+ for exec_id, start in starts.items():+ row = rows.get(exec_id)+ assert row is not None, f"{where} run {exec_id} ({start['name']}) has no ledger row"+ sent = [s for s in sink if s["exec"] == exec_id]+ ok_sent = [s for s in sent if s["ok"]]+ label = f"{where} {start['name']} exec={exec_id} status={row['status']} " \+ f"outcome={row['delivery_outcome']} sink={sent} error={row.get('error')!r}"+ if exec_id in self.killed_execs:+ assert row["status"] == "unknown", label+ assert not sent, label+ continue+ assert len(sent) <= 1, f"{label}: delivered more than once"+ if row["delivery_outcome"] == "delivered":+ assert len(ok_sent) == 1, f"{label}: 'delivered' but the sink never got it"+ if ok_sent:+ assert row["delivery_outcome"] == "delivered", f"{label}: sink got it, ledger says not"+ if sent and not ok_sent:+ assert row["delivery_outcome"] == "failed", f"{label}: failed send not recorded"+ assert "nterrupt" not in str(row.get("error") or ""), f"{label}: marked interrupted"+ agent_failed = "provider outage" in str(row.get("error") or "")+ if agent_failed:+ assert row["status"] == "failed", label+ else:+ assert row["status"] == "completed", label+ assert ok_sent or sent, f"{label}: successful run never reached the platform"+ assert not ok_sent or ok_sent[0]["exec_in_text"], f"{label}: wrong body delivered"+ for exec_id, row in rows.items():+ if exec_id not in starts: # attempts that never ran must say so truthfully+ assert row["status"] in ("failed", "unknown", "skipped"), f"{where} ghost row {row}"+ if hasattr(self, "long_run_exec"):+ row = rows[self.long_run_exec]+ assert (row["status"], row["delivery_outcome"]) == ("completed", "delivered"), (+ f"{where} long run lost its lease: {row}")+ for job in H.store_jobs(self.home):+ assert not job.get("pending_slot"), f"{where} leftover pending_slot {job}"+ return {"ticks": self.ticks, "executions": len(rows), "sink": len(sink)}+++def soak_env(tmp_path, monkeypatch):+ for key in list(os.environ):+ if key.endswith("_API_KEY") or key in ("INVOCATION_ID", "HERMES_TIMEZONE"):+ monkeypatch.delenv(key, raising=False)+ home_root = tmp_path / "home"+ hermes_home = home_root / ".hermes"+ hermes_home.mkdir(parents=True)+ monkeypatch.setenv("HOME", str(home_root))+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ original_tz = os.environ.get("TZ")+ yield tmp_path, hermes_home, monkeypatch+ if original_tz is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = original_tz+ time.tzset()+ import hermes_time++ hermes_time.reset_cache()+++def _run_scenario(sc: Scenario, soak_env) -> Dict[str, int]:+ tmp_path, hermes_home, monkeypatch = soak_env+ monkeypatch.setenv("TZ", sc.process_tz)+ time.tzset()+ lines = ["platforms:", " telegram:", " enabled: true", " token: fake-soak-token"]+ if sc.hermes_tz:+ lines.insert(0, f"timezone: {sc.hermes_tz}")+ (hermes_home / "config.yaml").write_text("\n".join(lines) + "\n", encoding="utf-8")+ control = H.Control(tmp_path / "control").ensure()+ import cron.jobs as jobs++ # Liveness markers fsync twice per loop iteration (the dominant wall cost at virtual+ # cadence); they are diagnostics, not scheduling, and are covered by tests/cron.+ monkeypatch.setattr(jobs, "record_ticker_heartbeat", lambda **_kw: None)+ H.install(H.VirtualClock(control.clock_file), control, monkeypatch.setattr)+ env = {k: v for k, v in os.environ.items() if not k.startswith("PYTEST_")}+ env["PYTHONPATH"] = str(REPO_ROOT)+ soak = Soak(sc, hermes_home, control, env)+ try:+ soak.run()+ finally:+ if soak.child is not None:+ soak.child.kill()+ soak.ev_down(None)+ return soak.final_checks()+++# Red until #120314 lands: the due gate compares same-zone wall clocks, so a slot in the repeated+# fall-back hour fires up to an hour early. Delete with #120314.+UNLANDED_FIX = {"newyork_on_shanghai_fall": "fixed by #120314"}++[email protected]("sc", [+ pytest.param(s, id=s.id, marks=[pytest.mark.xfail(strict=True, reason=UNLANDED_FIX[s.id])]+ if s.id in UNLANDED_FIX else []) for s in SCENARIOS])+def test_cron_virtual_clock_soak(sc, soak_env):+ stats = _run_scenario(sc, soak_env)+ print(f"C13 {sc.id}: {stats}")+ assert stats["executions"] > 60++[email protected]("sc", KNOWN_BUG)+def test_cron_virtual_clock_soak_known_dst_bug(sc, soak_env):+ _run_scenario(sc, soak_env)