diff --git a/contributors/emails/holny@foxmail.com b/contributors/emails/holny@foxmail.com new file mode 100644 index 0000000000..b03aa6ac9c --- /dev/null +++ b/contributors/emails/holny@foxmail.com @@ -0,0 +1,2 @@ +holny +# Issue #104790 and occurrence guard #104323 diff --git a/cron/executions.py b/cron/executions.py index f905153379..14c1d40e2e 100644 --- a/cron/executions.py +++ b/cron/executions.py @@ -115,6 +115,11 @@ def _initialize_schema(conn: sqlite3.Connection) -> None: "CREATE INDEX IF NOT EXISTS idx_executions_status_claimed " "ON executions(status, claimed_at DESC, id DESC)" ) + add_column_if_missing(conn, "executions", "scheduled_instant", "scheduled_instant TEXT") + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_executions_occurrence " + "ON executions(job_id, scheduled_instant) WHERE status='completed'" + ) @contextmanager @@ -172,8 +177,12 @@ def _prune_unlocked(conn: sqlite3.Connection) -> None: ) -def create_execution(job_id: str, *, source: str) -> Dict[str, Any]: +def create_execution( + job_id: str, *, source: str, scheduled_instant: Optional[str] = None, +) -> Dict[str, Any]: """Persist a claimed attempt before executor/provider dispatch.""" + from cron.occurrences import scheduled_instant as canonical_instant + now = _hermes_now().isoformat() execution_id = uuid.uuid4().hex pid = os.getpid() @@ -181,16 +190,30 @@ def create_execution(job_id: str, *, source: str) -> Dict[str, Any]: conn.execute( """INSERT INTO executions (id, job_id, source, process_id, pid, process_started_at, - status, claimed_at) - VALUES (?, ?, ?, ?, ?, ?, 'claimed', ?)""", + status, claimed_at, scheduled_instant) + VALUES (?, ?, ?, ?, ?, ?, 'claimed', ?, ?)""", (execution_id, str(job_id), str(source), _PROCESS_ID, pid, - _process_start_time(pid), now), + _process_start_time(pid), now, canonical_instant(scheduled_instant)), ) record = _fetch(conn, execution_id) _emit_execution_state(record) return record # type: ignore[return-value] +def set_execution_occurrence(execution_id: str, instant: Optional[str]) -> None: + """Bind the store-claimed snapshot before a provider hands it to a worker.""" + from cron.occurrences import scheduled_instant + + with _transaction() as conn: + cur = conn.execute( + "UPDATE executions SET scheduled_instant=? WHERE id=? AND status='claimed' " + "AND handoff_pending=0 AND process_id=? AND pid=?", + (scheduled_instant(instant), execution_id, _PROCESS_ID, os.getpid()), + ) + if cur.rowcount != 1: + raise RuntimeError("Cron occurrence could not be bound before dispatch") + + def mark_execution_handoff_pending(execution_id: str) -> Optional[Dict[str, Any]]: """Fence restart recovery while an external worker is adopting a claim.""" with _transaction() as conn: diff --git a/cron/jobs.py b/cron/jobs.py index adb75eea2d..50faa4a05d 100644 --- a/cron/jobs.py +++ b/cron/jobs.py @@ -2503,6 +2503,17 @@ def claim_job_for_fire( now = _hermes_now() if _claim_is_live(job.get("fire_claim"), now, claim_ttl_seconds): return False # someone holds a fresh claim + from cron.occurrences import completed_occurrence, scheduled_instant + + manual = force or job.get("manual_run_at") == job.get("next_run_at") + instant = None if manual else scheduled_instant(job.get("next_run_at")) + if instant and completed_occurrence(job, instant): + if job.get("schedule", {}).get("kind") in {"cron", "interval"}: + nxt = compute_next_run(job["schedule"], now.isoformat()) + if nxt: + job["next_run_at"] = nxt + save_jobs(jobs) + return False if force: _activate_job_record(job) # Per-acquisition token: a process may legitimately reclaim its own stale lease, and the @@ -2513,7 +2524,7 @@ def claim_job_for_fire( if nxt: job["next_run_at"] = nxt save_jobs(jobs) - return copy.deepcopy(job) if return_job else True + return dict(copy.deepcopy(job), _scheduled_instant=instant) if return_job else True return _under_fire_fence(job_id, lambda: _with_job(job_id, apply, False)) @@ -2914,12 +2925,22 @@ def _evaluate_due_job(job: Dict[str, Any], scan: _DueScan, run_claim_ttl: float) # into both fields, and any rewrite of next_run_at (edit, re-anchor, fire-claim advance) must # invalidate the marker. Do not "fix" this with _ensure_aware normalization. manual_run = job.get("manual_run_at") == next_run + from cron.occurrences import completed_occurrence, scheduled_instant + + if not manual_run and completed_occurrence(job, next_run): + new_next = d.recompute_next() if recurring else None + if new_next: + scan.persist(job["id"], next_run_at=new_next) + return False if kind == "cron" and not manual_run and _repair_timezone_shifted_cron(d): return False d.next_run_dt = _rearm_stale_error_recurring(d) if d.next_run_dt > now: return False + # Only the dispatch snapshot carries this field; never infer it from a later stamp. + job["_scheduled_instant"] = None if manual_run else scheduled_instant(d.next_run_dt.isoformat()) + if not manual_run and kind == "cron" and _reanchor_stale_cron(d): return False grace = _compute_grace_seconds(d.schedule) diff --git a/cron/occurrences.py b/cron/occurrences.py new file mode 100644 index 0000000000..8b86a706ae --- /dev/null +++ b/cron/occurrences.py @@ -0,0 +1,36 @@ +"""Exact scheduled identities, independent of mutable jobs.json dispatch stamps.""" +from datetime import datetime, timezone +import logging + +logger = logging.getLogger(__name__) + + +def scheduled_instant(value): + """Canonicalize aware instants; legacy/ambiguous values carry no exact identity.""" + if not isinstance(value, str): + return None + try: + instant = datetime.fromisoformat(value) + if instant.tzinfo is None: + return None + return instant.astimezone(timezone.utc).isoformat() + except ValueError: + return None + + +def completed_occurrence(job, instant): + """Unknown/failed/pruned attempts cannot prove completion: keep them eligible.""" + from cron.executions import _transaction + + instant = scheduled_instant(instant) + if instant is None: + return False + try: + with _transaction() as conn: + return conn.execute( + "SELECT 1 FROM executions WHERE job_id=? AND scheduled_instant=? " + "AND status='completed' LIMIT 1", (str(job['id']), instant) + ).fetchone() is not None + except Exception: + logger.warning("Cannot check completed occurrence for job %s", job['id'], exc_info=True) + return False diff --git a/cron/scheduler.py b/cron/scheduler.py index 3a1b383952..d9ed063f7b 100644 --- a/cron/scheduler.py +++ b/cron/scheduler.py @@ -2517,7 +2517,8 @@ def run_one_job( # API fires) crosses this seam. Ensure the detached worker has a durable # attempt to adopt before any launch can occur. if not job.get("execution_id"): - execution = create_execution(job["id"], source="direct") + execution = create_execution( + job["id"], source="direct", scheduled_instant=job.get("_scheduled_instant")) job["execution_id"] = execution["id"] execution_id = str(job["execution_id"]) @@ -2878,7 +2879,8 @@ def _run_one_job_body( execution_id = job.get("execution_id") if not execution_id: - execution_id = create_execution(job["id"], source="direct")["id"] + execution_id = create_execution( + job["id"], source="direct", scheduled_instant=job.get("_scheduled_instant"))["id"] delivery_attempted = False delivery_error = None from agent.secret_scope import ( @@ -3628,6 +3630,7 @@ def _process_due_job(job: dict, adapters, loop, verbose: bool) -> bool: # CAS returns the persisted record; bool fallback only for older test doubles. claimed_job = dict(claimed) if isinstance(claimed, dict) else dict(job) claimed_job["execution_id"] = job["execution_id"] + claimed_job["_scheduled_instant"] = job.get("_scheduled_instant") return run_one_job(claimed_job, adapters=adapters, loop=loop, verbose=verbose) @@ -3681,7 +3684,8 @@ def _submit_with_guard(job: dict, pool: concurrent.futures.ThreadPoolExecutor, p return None # Record the attempt before dispatch; recovery marks abandoned rows unknown (no retry). try: - execution = create_execution(job_id, source="builtin") + execution = create_execution( + job_id, source="builtin", scheduled_instant=job.get("_scheduled_instant")) dispatched_job = dict(job, execution_id=execution["id"]) _ctx = contextvars.copy_context() except Exception as execution_err: diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.py index fc02d14fce..6f13778382 100644 --- a/cron/scheduler_provider.py +++ b/cron/scheduler_provider.py @@ -148,7 +148,7 @@ class CronScheduler(ABC): def claim_fire(self, job_id: str, *, force: bool = False) -> dict | None: """Durably claim one fire + create its audit attempt. Transports call this synchronously before acknowledging, then pass the exact snapshot to ``fire_claimed`` off-thread.""" - from cron.executions import create_execution, finish_execution + from cron.executions import create_execution, finish_execution, set_execution_occurrence from cron.jobs import claim_job_for_fire execution = create_execution(job_id, source=self.name) @@ -157,6 +157,8 @@ class CronScheduler(ABC): claim_kwargs["force"] = True try: claimed_job = claim_job_for_fire(job_id, **claim_kwargs) + if isinstance(claimed_job, dict): + set_execution_occurrence(execution["id"], claimed_job.get("_scheduled_instant")) except BaseException as exc: finish_execution( execution["id"], success=False, diff --git a/tests/cron/test_parallel_pool.py b/tests/cron/test_parallel_pool.py index 9853dbc229..3f8a8df707 100644 --- a/tests/cron/test_parallel_pool.py +++ b/tests/cron/test_parallel_pool.py @@ -164,7 +164,7 @@ class TestRunningJobGuard: called = [] - def create_execution_side_effect(job_id, source): + def create_execution_side_effect(job_id, source, **kwargs): if job_id == "failing-job": raise RuntimeError("execution ledger unavailable") return {"id": f"{job_id}-execution"} diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.py index 68143eb910..30cf2ed067 100644 --- a/tests/cron/test_restart_safe_worker.py +++ b/tests/cron/test_restart_safe_worker.py @@ -426,7 +426,7 @@ def test_gateway_tool_run_without_adapter_objects_hands_off(monkeypatch): assert scheduler.run_one_job(job, adapters=None) is True - created.assert_called_once_with("tool-job", source="direct") + created.assert_called_once_with("tool-job", source="direct", scheduled_instant=None) assert job["execution_id"] == "exec-tool" launch.assert_called_once_with(job) run.assert_not_called() @@ -443,7 +443,7 @@ def test_shared_run_path_creates_execution_before_managed_handoff(monkeypatch): assert scheduler.run_one_job(job, adapters={"discord": object()}) is True - created.assert_called_once_with("manual-job", source="direct") + created.assert_called_once_with("manual-job", source="direct", scheduled_instant=None) assert job["execution_id"] == "exec-new" launch.assert_called_once_with(job) diff --git a/tests/cron/test_scheduled_occurrence.py b/tests/cron/test_scheduled_occurrence.py new file mode 100644 index 0000000000..afa85449ca --- /dev/null +++ b/tests/cron/test_scheduled_occurrence.py @@ -0,0 +1,127 @@ +"""Completed scheduled attempts survive a jobs.json rollback, not just a process restart.""" +import json +import os +from pathlib import Path +import subprocess +import sys + +import pytest + + +_FIRE = """ +import sys +from cron import jobs, scheduler +from cron.scheduler_provider import InProcessCronScheduler +if sys.argv[1] == 'builtin': + scheduler.tick(verbose=False, sync=True) +else: + provider = InProcessCronScheduler() + for job in jobs.load_jobs(): + provider.fire_due(job['id'], force=sys.argv[1] == 'manual') +""" + + +def _fire(home, mode): + env = {k: v for k, v in os.environ.items() + if not k.startswith(('HERMES_', '_HERMES_')) + and not k.endswith(('_API_KEY', '_TOKEN'))} + env['HERMES_HOME'] = str(home) + env['PYTHONPATH'] = str(Path(__file__).resolve().parents[2]) + result = subprocess.run([sys.executable, '-c', _FIRE, mode], env=env, + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=90) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize('mode', ['builtin', 'provider']) +def test_completed_occurrence_survives_restart_and_prestamp_rollback(tmp_path, mode): + from datetime import timedelta + from hermes_time import now + + home = tmp_path / mode + cron = home / 'cron' + cron.mkdir(parents=True) + effect = home / 'effects.txt' + (home / 'scripts').mkdir() + script = home / 'scripts' / 'effect.py' + script.write_text(f"from pathlib import Path\np = Path({str(effect)!r})\n" + "with p.open('a') as f: f.write('effect\\n')\nprint('done')\n") + slot = (now() - timedelta(minutes=30)).isoformat() + job = {'id': 'occurrence', 'name': 'occurrence', 'prompt': '', + 'schedule': {'kind': 'interval', 'minutes': 240}, + 'next_run_at': slot, 'enabled': True, 'state': 'scheduled', + 'script': str(script), 'no_agent': True, 'deliver': 'local', + 'repeat': {'times': None, 'completed': 0}} + snapshot = json.dumps({'jobs': [job]}) + store = cron / 'jobs.json' + store.write_text(snapshot) + _fire(home, mode) + assert effect.read_text().splitlines() == ['effect'] + store.write_text(snapshot) # no last_dispatch stamp, no post-completion fields + _fire(home, mode) # a fresh interpreter, same authoritative ledger + assert effect.read_text().splitlines() == ['effect'], 'completed occurrence executed twice' + + # A different missed slot must remain runnable despite the completed row. + job['next_run_at'] = (now() - timedelta(minutes=10)).isoformat() + store.write_text(json.dumps({'jobs': [job]})) + _fire(home, mode) + assert len(effect.read_text().splitlines()) == 2 + # Manual force is not a completion of the pending scheduled slot. + job['next_run_at'] = (now() - timedelta(minutes=5)).isoformat() + pending = json.dumps({'jobs': [job]}) + store.write_text(pending) + _fire(home, 'manual') + store.write_text(pending) + _fire(home, mode) + assert len(effect.read_text().splitlines()) == 4 + + +def test_ledger_migration_and_completion_identity(tmp_path, monkeypatch): + import sqlite3 + from cron import executions, jobs + from cron.occurrences import completed_occurrence + from cron.scheduler_provider import InProcessCronScheduler + + db = tmp_path / 'executions.db' + monkeypatch.setattr(executions, 'EXECUTIONS_FILE', db) + # Pre-migration schema, not initialized by the implementation under test. + with sqlite3.connect(db) as conn: + conn.execute('''CREATE TABLE executions ( + id TEXT PRIMARY KEY, job_id TEXT NOT NULL, source TEXT NOT NULL, + process_id TEXT NOT NULL, pid INTEGER NOT NULL, process_started_at INTEGER, + status TEXT NOT NULL, claimed_at TEXT NOT NULL, + started_at TEXT, finished_at TEXT, error TEXT)''') + conn.execute("INSERT INTO executions VALUES " + "('legacy','job','builtin','old',-1,NULL,'completed'," + "'2026-01-01T00:00:00Z',NULL,NULL,NULL)") + slot = '2026-01-01T00:00:00+00:00' + job = {'id': 'job'} + assert not completed_occurrence(job, slot) + with sqlite3.connect(db) as conn: + assert conn.execute('SELECT id, scheduled_instant FROM executions').fetchall() == [('legacy', None)] + for status in ('failed', 'unknown', 'running', 'claimed'): + row = executions.create_execution('job', source='control', scheduled_instant=slot) + with sqlite3.connect(db) as conn: + conn.execute('UPDATE executions SET status=? WHERE id=?', (status, row['id'])) + assert not completed_occurrence(job, slot) + row = executions.create_execution('job', source='builtin', scheduled_instant=slot) + executions.finish_execution(row['id'], success=True) + executions.create_execution('job', source='manual') # latest row is not the completed one + assert completed_occurrence(job, '2026-01-01T08:00:00+0800') + assert not completed_occurrence(job, '2026-01-01T00:00:01Z') + assert not completed_occurrence({'id': 'other'}, slot) + + # Provider capture is before next_run_at advances; adoption cannot lose identity. + with jobs.use_cron_store(tmp_path / 'cron'): + stored = jobs.create_job(prompt='test', schedule='every 4h') + rows = jobs.load_jobs() + rows[0]['next_run_at'] = slot + jobs.save_jobs(rows) + claim = InProcessCronScheduler().claim_fire(stored['id']) + assert claim is not None + assert claim['_scheduled_instant'] == slot + assert claim['next_run_at'] != slot + assert '_scheduled_instant' not in jobs.load_jobs()[0] + executions.mark_execution_handoff_pending(claim['execution_id']) + adopted = executions.adopt_claimed_execution(claim['execution_id']) + assert adopted is not None + assert adopted['scheduled_instant'] == slot diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md index e9a24600c1..9d9608cdaa 100644 --- a/website/docs/user-guide/features/cron.md +++ b/website/docs/user-guide/features/cron.md @@ -334,6 +334,19 @@ Inspect recent attempts with `hermes cron runs [job-id] --limit 20` (alias: `history`). Terminal history is bounded; active attempts are never pruned. The ledger is included in quick backups. +Scheduled attempts also record their exact scheduled instant, separately from +the time they were claimed. If an old `jobs.json` snapshot re-arms an occurrence +that the retained ledger records as completed, Hermes skips that replay and +re-anchors recurring jobs. This works even when the snapshot predates the +dispatch stamp or the original run started late. Explicit manual runs do not +consume a scheduled occurrence's identity. + +This is not an exactly-once side-effect guarantee: legacy rows without an +identity, pruned history, unavailable ledgers, and interrupted attempts cannot +prove completion. Restoring the ledger itself to an older backup also removes +that evidence. External fire callbacks identify the currently accepted store +claim, not an upstream scheduled slot absent from the callback. + ### Repeated-failure review nudge Each job tracks a `failure_streak` — consecutive failed runs (delivery