The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e): two replicas contend for every cron fire claim
teknium17498546291ea
diff --git a/tests/e2e/core/delivery/_cron_clock.py b/tests/e2e/core/delivery/_cron_clock.pyindex e76dae0f697..df1b61aa5c5 100644--- a/tests/e2e/core/delivery/_cron_clock.py+++ b/tests/e2e/core/delivery/_cron_clock.py@@ -19,7 +19,13 @@ What is virtual and what stays real:``SchedulerHost`` runs the real ticker loop in a thread with a stepping ``stop_event``; runningthis 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.+files, so two processes can share one ``HERMES_HOME`` and one can be SIGKILLed mid-run. Two+tickers never contend for a FIRE: the tick lock admits one per instant and the winner advances+``next_run_at`` before it releases. Fire-claim contention is the external-provider path+(``CronScheduler.fire_due``, "exactly one of N replicas runs a job"): ``ReplicaHost`` runs a+replica in a second process, and ``install_claim_barrier`` parks each replica's+``claim_job_for_fire`` until every replica of the round is inside it, so the store CAS, not+timing, decides every fire."""from __future__ import annotations@@ -97,9 +103,11 @@ class Control:self.behaviors = self.root / "behaviors.json"self.gates = self.root / "gates"self.child = self.root / "child"+ self.replica = self.root / "replica"+ self.claims = self.root / "claims.jsonl"def ensure(self) -> "Control":- for d in (self.root, self.gates, self.child):+ for d in (self.root, self.gates, self.child, self.replica):d.mkdir(parents=True, exist_ok=True)if not self.behaviors.exists():self.set_behaviors({})@@ -440,7 +448,7 @@ class ChildHost: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)+ os.kill(self.proc.pid, signal.SIGKILL) # windows-footgun: ok (POSIX-only harness)self.proc.wait(timeout=DEADLINE_SECONDS)def stop(self) -> None:@@ -463,6 +471,124 @@ def tick_together(hosts: Iterable[Any]) -> None:host.wait_idle()+# --- external-provider replicas contending for one fire ----------------------------------------++_CLAIM_ROUND: List[Optional[int]] = [None] # one round in flight per process at a time+++def replica_scheduler():+ """A minimal external ``CronScheduler``: the base class's real ``fire_due`` (store CAS claim,+ audit attempt, shared ``run_one_job``) is the whole firing path; nothing ticks."""+ from cron.scheduler_provider import CronScheduler++ class ReplicaScheduler(CronScheduler):+ @property+ def name(self) -> str:+ return "replica"++ def start(self, stop_event, **_kwargs) -> None:+ stop_event.wait()++ return ReplicaScheduler()+++def install_claim_barrier(control: Control, setattr_fn=setattr, parties: int = 2) -> None:+ """Wrap ``cron.jobs.claim_job_for_fire`` (``claim_fire`` imports it at call time): each call+ waits until ``parties`` replicas have entered the claim for the current round, then runs the+ REAL claim and logs who won. It only delays, never changes a decision."""+ import cron.jobs as jobs++ real = jobs.claim_job_for_fire++ def claim(job_id, **kwargs):+ rnd = _CLAIM_ROUND[0]+ (control.replica / f"arrived-{rnd}-{os.getpid()}").touch()+ wait_until(lambda: len(list(control.replica.glob(f"arrived-{rnd}-*"))) >= parties,+ f"{parties} replicas inside the fire claim of round {rnd}")+ result = real(job_id, **kwargs)+ _append_jsonl(control.claims, {"round": rnd, "pid": os.getpid(), "job_id": job_id,+ "won": bool(result)})+ return result++ setattr_fn(jobs, "claim_job_for_fire", claim)+++def fire_as_replica(provider, job_id: str, rnd: int) -> bool:+ _CLAIM_ROUND[0] = rnd+ return provider.fire_due(job_id)+++class ReplicaHost:+ """A second replica in its own OS process: fires ``req-<n>.json`` requests in order and+ answers ``res-<n>.json`` with whether its ``fire_due`` claimed the fire."""++ def __init__(self, control: Control, env: Dict[str, str], repo_root: Path):+ self.control, self.env, self.repo_root = control, env, repo_root+ self.proc: Optional[subprocess.Popen] = None++ @property+ def pid(self) -> Optional[int]:+ return self.proc.pid if self.proc is not None else None++ def _check(self) -> None:+ if self.proc.poll() is not None:+ tail = (self.control.replica / "stderr.log").read_text(encoding="utf-8")[-4000:]+ raise AssertionError(f"replica exited rc={self.proc.returncode}:\n{tail}")++ def start(self) -> None:+ log = open(self.control.replica / "stderr.log", "a", encoding="utf-8") # noqa: SIM115+ self.proc = subprocess.Popen(+ [sys.executable, str(Path(__file__).resolve()), str(self.control.root), "replica"],+ cwd=str(self.repo_root), env=self.env, stdin=subprocess.DEVNULL, stdout=log, stderr=log)+ log.close()++ def ready():+ self._check()+ return (self.control.replica / "ready").exists()++ wait_until(ready, "replica process ready", timeout=180.0)++ def request(self, rnd: int, job_id: str) -> None:+ _atomic_write(self.control.replica / f"req-{rnd}.json", json.dumps({"job_id": job_id}))++ def result(self, rnd: int) -> bool:+ path = self.control.replica / f"res-{rnd}.json"++ def done():+ self._check()+ return path.exists()++ wait_until(done, f"replica result for round {rnd}")+ return json.loads(path.read_text(encoding="utf-8"))["won"]++ def stop(self) -> None:+ if self.proc is not None and self.proc.poll() is None:+ (self.control.replica / "stop").write_text("1", encoding="utf-8")+ try:+ self.proc.wait(timeout=DEADLINE_SECONDS)+ except subprocess.TimeoutExpired:+ self.proc.kill()+ self.proc.wait(timeout=DEADLINE_SECONDS)+++def _replica_main(control: Control) -> None:+ install(VirtualClock(control.clock_file), control)+ install_claim_barrier(control)+ provider = replica_scheduler()+ (control.replica / "ready").touch()+ rnd = 0+ while True:+ rnd += 1+ req = control.replica / f"req-{rnd}.json"+ deadline = _real_time.monotonic() + HOLD_DEADLINE_SECONDS+ while not req.exists():+ if (control.replica / "stop").exists() or _real_time.monotonic() >= deadline:+ return+ _real_time.sleep(POLL_SECONDS)+ won = fire_as_replica(provider, json.loads(req.read_text(encoding="utf-8"))["job_id"], rnd)+ _atomic_write(control.replica / f"res-{rnd}.json", json.dumps({"won": won}))++# --- ledger / store readers ------------------------------------------------------------------def ledger_rows(home: Path, where: str = "") -> List[dict]:@@ -500,6 +626,9 @@ def _child_main(control_root: str) -> None:InProcessCronScheduler().start(_FileGate(control), interval=60)-if __name__ == "__main__": # child ticker process+if __name__ == "__main__": # child ticker (or replica) processsys.path.insert(0, os.getcwd())- _child_main(sys.argv[1])+ if sys.argv[2:] == ["replica"]:+ _replica_main(Control(Path(sys.argv[1])))+ else:+ _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.pyindex eafb55d72f1..54bb41d9660 100644--- a/tests/e2e/core/delivery/test_cron_virtual_clock_soak.py+++ b/tests/e2e/core/delivery/test_cron_virtual_clock_soak.py@@ -2,7 +2,9 @@Real: ``InProcessCronScheduler.start`` (the gateway's ticker loop: startup recovery, tick, heartbeatbookkeeping), ``cron.scheduler.tick`` / due scan / pending slots / fire claims + heartbeat /-executions ledger / delivery routing / ``mark_job_run``, a second OS process sharing HERMES_HOME.+executions ledger / delivery routing / ``mark_job_run``, a second OS process sharing HERMES_HOME+(its ticker races the in-process one for every tick; the tick lock admits one). Fire-claim+contention between two OS processes is ``test_two_replicas_contend_for_every_fire``.Fake: the agent (``cron.scheduler.run_job``) and the platform wire (``_send_to_platform``), whichrecord what they were handed. Time: one file-backed virtual clock (see ``_cron_clock``).@@ -29,6 +31,7 @@ import dataclassesimport mathimport osimport sys+import threadingimport timefrom datetime import date, datetime, timedelta, timezonefrom pathlib import Path@@ -40,6 +43,7 @@ import pytestcroniter_mod = pytest.importorskip("croniter")from tests.e2e.core.delivery import _cron_clock as H # noqa: E402+from tests.e2e.core.delivery._pending_fixes import expect_gap # noqa: E402pytestmark = pytest.mark.skipif(sys.platform != "linux", reason="flock/SIGKILL multi-process soak is Linux-only")@@ -56,7 +60,7 @@ class Scenario:hermes_tz: Optional[str]process_tz: strstart: date # DST day is always start + 9- child: bool = False # two-process contention + SIGKILL/restart mid-run+ child: bool = False # a second ticker process + SIGKILL/restart mid-rundays: int = 30@@ -71,15 +75,18 @@ SCENARIOS = [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"),-]+# Scenario id -> (fix PR, gap). Strict xfail only while the PR's probe still reproduces the defect+# (see _pending_fixes); once the fix is in the tree the scenario must pass.+GAPS = {+ # the due gate compares same-zone wall clocks: a slot in the repeated fall-back hour fires up+ # to an hour early+ "newyork_on_shanghai_fall": (120314, "cron DST fall-back early fire (fixed by #120314)"),+ # #119969: with NO timezone configured the next occurrence keeps the base time's fixed UTC+ # offset, so a DST process zone fires 09:00 at 10:00 local after spring-forward+ "unset_on_newyork_spring": (119970, "#119969 no-tz DST fixed offset (fixed by #119970)"),+}+SCENARIOS.append(Scenario("unset_on_newyork_spring", None, "America/New_York", date(2026, 2, 27),+ days=12))def _iso(ts: float) -> str:@@ -439,7 +446,7 @@ class Soak:self.at(L(13, 7, 30, 5), "down") # 09:00 missed by 45 min -> fires late, onceself.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(15, 0, 0), "child_up") # both tickers tick every instant; the tick lock admits oneself.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@@ -571,20 +578,98 @@ def _run_scenario(sc: Scenario, soak_env) -> Dict[str, int]: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):[email protected]("sc", [pytest.param(s, id=s.id) for s in SCENARIOS])+def test_cron_virtual_clock_soak(sc, soak_env, request):+ if sc.id in GAPS:+ expect_gap(request, *GAPS[sc.id])stats = _run_scenario(sc, soak_env)print(f"C13 {sc.id}: {stats}")- assert stats["executions"] > 60+ assert sc.days < 30 or stats["executions"] > 60++# --- two replicas, one store: the fire claim decides every fire ---------------------------------++REPLICA_ROUNDS = 12+++def test_two_replicas_contend_for_every_fire(soak_env):+ """Two external-provider replicas (this process + a second OS process) receive the same fire+ for every due occurrence and call the real ``fire_due`` at once (a barrier parks each inside+ ``claim_job_for_fire`` until both are there). The winner's run is held open, so the loser+ always meets a live claim. Per round: exactly one replica claims, exactly one run starts for+ that slot and is delivered once, the loser's attempt is recorded as not acquired, and the+ store re-arms to a later slot, so no occurrence is fired twice or skipped."""+ tmp_path, hermes_home, monkeypatch = soak_env+ monkeypatch.setenv("TZ", "UTC")+ time.tzset()+ (hermes_home / "config.yaml").write_text(+ "platforms:\n telegram:\n enabled: true\n token: fake-soak-token\n", encoding="utf-8")+ control = H.Control(tmp_path / "control").ensure()+ import cron.jobs as jobs[email protected]("sc", KNOWN_BUG)-def test_cron_virtual_clock_soak_known_dst_bug(sc, soak_env):- _run_scenario(sc, soak_env)+ monkeypatch.setattr(jobs, "record_ticker_heartbeat", lambda **_kw: None)+ clock = H.VirtualClock(control.clock_file)+ H.install(clock, control, monkeypatch.setattr)+ H.install_claim_barrier(control, monkeypatch.setattr)+ env = {k: v for k, v in os.environ.items() if not k.startswith("PYTEST_")}+ env["PYTHONPATH"] = str(REPO_ROOT)+ clock.set(datetime(2026, 3, 1, 0, 0, 30, tzinfo=UTC).timestamp())+ names = {}+ for name, schedule in (("hourly", "0 * * * *"), ("every-45m", "every 45m")):+ names[name] = jobs.create_job(prompt=f"replica {name}", schedule=schedule, name=name,+ deliver="telegram:2000")["id"]+ provider = H.replica_scheduler()+ peer = H.ReplicaHost(control, env, REPO_ROOT)+ peer.start()+ fired = []+ try:+ for rnd in range(1, REPLICA_ROUNDS + 1):+ slot, name = min((datetime.fromisoformat(jobs.get_job(i)["next_run_at"]).timestamp(), n)+ for n, i in names.items()) # the next due occurrence of either job+ job_id = names[name]+ assert slot > clock.now_ts(), f"round {rnd} {name}: slot {_iso(slot)} already passed"+ clock.set(slot + 5) # the fire arrives 5 s after its slot at both replicas+ hold = control.hold_file(name)+ hold.write_text("1", encoding="utf-8")+ mine: Dict[str, bool] = {}++ def fire_here(job_id=job_id, rnd=rnd):+ mine["won"] = H.fire_as_replica(provider, job_id, rnd)++ t = threading.Thread(target=fire_here)+ t.start()+ peer.request(rnd, job_id)++ def both_claimed():+ return [c for c in H.read_jsonl(control.claims) if c["round"] == rnd][1:]++ H.wait_until(both_claimed, f"round {rnd}: both replicas' claim outcome")+ entered = control.gates / f"{name}.entered"+ H.wait_until(entered.exists, f"round {rnd}: the winner's run to start")+ hold.unlink()+ t.join(timeout=H.DEADLINE_SECONDS)+ assert not t.is_alive(), f"round {rnd}: in-process replica never finished"+ outcomes = sorted([mine["won"], peer.result(rnd)])+ entered.unlink()+ claims = [c for c in H.read_jsonl(control.claims) if c["round"] == rnd]+ assert sorted(c["pid"] for c in claims) == sorted([os.getpid(), peer.pid]), claims+ assert sorted(c["won"] for c in claims) == [False, True], f"round {rnd}: {claims}"+ assert outcomes == [False, True], f"round {rnd}: fire_due results {outcomes}"+ starts = [r for r in H.read_jsonl(control.runs) if r["event"] == "start"]+ fired.append((name, slot, next(c["pid"] for c in claims if c["won"])))+ assert len(starts) == rnd, f"round {rnd} {name}: {len(starts)} runs started for {rnd} fires"+ assert datetime.fromisoformat(starts[-1]["instant"]).timestamp() == slot, starts[-1]+ nxt = datetime.fromisoformat(jobs.get_job(job_id)["next_run_at"]).timestamp()+ assert nxt > clock.now_ts(), f"round {rnd} {name}: not re-armed past now ({_iso(nxt)})"+ finally:+ peer.stop()+ rows = H.ledger_rows(hermes_home)+ sink = H.read_jsonl(control.sink)+ starts = {r["exec"] for r in H.read_jsonl(control.runs) if r["event"] == "start"}+ won = [r for r in rows if r["id"] in starts]+ lost = [r for r in rows if r["id"] not in starts]+ assert len(won) == len(lost) == REPLICA_ROUNDS, (len(won), len(lost), rows)+ assert all((r["status"], r["delivery_outcome"]) == ("completed", "delivered") for r in won), won+ assert all(r["status"] == "failed" and "not acquired" in (r["error"] or "") for r in lost), lost+ assert sorted(s["exec"] for s in sink if s["ok"]) == sorted(starts), sink+ print(f"C13 replicas: winners by pid {[(n, pid) for n, _, pid in fired]}")