The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): reconcile durable receipts through terminal bookkeeping
David Dudok de Wita65200e3aae4
diff --git a/cron/executions.py b/cron/executions.pyindex f020230508a..ec5bdafbfb6 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -352,6 +352,32 @@ def finish_execution(return record+def recover_receipted_execution(execution_id, job_id, *, success, error=None, delivery_outcome=None):+ """Settle a verified canonical receipt after owner loss, including its unknown audit row.++ Terminal verdicts stay immutable. A live foreign firing process still owns its bookkeeping.+ """+ now = _hermes_now().isoformat()+ with _transaction() as conn:+ row = conn.execute(+ """SELECT process_id, pid, process_started_at FROM executions+ WHERE id=? AND job_id=? AND status IN ('claimed','running','unknown')""",+ (execution_id, job_id)).fetchone()+ if row is None or (row['process_id'] != _PROCESS_ID+ and _owner_is_live(int(row['pid']), row['process_started_at'])):+ return None+ conn.execute(+ """UPDATE executions SET status=?, finished_at=?, error=?, handoff_pending=0,+ handoff_started_at=NULL, delivery_outcome=? WHERE id=?""",+ ('completed' if success else 'failed', now, None if success else (str(error) if error else 'unknown failure'),+ delivery_outcome, execution_id))+ _prune_unlocked(conn)+ record = _fetch(conn, execution_id)+ _emit_execution_state(record, delivery_outcome=delivery_outcome)+ record_cron_finish(record, delivery_outcome)+ return record++def settle_delivery_outcome(execution_id: str, outcome: str) -> bool:"""Replace a terminal attempt's ``queued`` delivery outcome with the drain's real one.diff --git a/cron/scheduler.py b/cron/scheduler.pyindex ba28b167b9d..1823442fcfd 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -3179,27 +3179,7 @@ def _save_compose_deliver(logger.error("Delivery failed for job %s: %s", job["id"], de)-def _finish_interrupted_run(job: dict, execution_id: str, delivery_error: Optional[str]) -> None:- """Shutdown already wrote last_status, so mark_job_run is skipped (a second call would skip a- fire or auto-delete the job); an unsent notice is recorded via update_job instead."""- if delivery_error:- try:- # The gateway shutdown already wrote last_status for this run, so mark_job_run is skipped below- # — but it could not know that the notice we just tried to send never left the process (the- # adapters were torn down first, #82232). Record the delivery failure on its own via update_job:- # mark_job_run also advances next_run_at and the repeat counter, and running that a second time- # for one run would skip a fire or auto-delete the job early.- from cron.jobs import update_job- update_job(job["id"], {"last_delivery_error": delivery_error})- except Exception as _rec_err:- logger.debug(- "Failed recording delivery_error for interrupted job %s: %s", job["id"], _rec_err)- finish_execution(- execution_id, success=False,- error="Interrupted by gateway shutdown before terminal completion.")---def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_id: str) -> bool:+def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_id: str, *, recovered=False) -> bool:"""mark_job_run (owner-fenced) + execution ledger row for a run that reached delivery."""job = d.jobif not d.should_deliver and job.get("last_delivery_queued"):@@ -3256,7 +3236,10 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_if delivery_outcome in ("delivered", "not_configured") and not d.success:# Failure ping left the process (or had a configured target): mark the incident alerted._mark_incident_alerted(d.failure_incident_id)- finish_execution(+ from functools import partial+ from cron.executions import recover_receipted_execution+ finish = partial(recover_receipted_execution, job_id=job['id']) if recovered else finish_execution+ finish(execution_id, success=d.success, error=d.error, delivery_outcome=delivery_outcome)if job.get("last_delivery_queued"):# A drain that settled before this run's own bookkeeping landed found nothing to fence on.@@ -3513,7 +3496,8 @@ def _run_one_job_body(return Trueif _consume_interrupted_flag(job["id"], execution_token):- _finish_interrupted_run(job, execution_id, delivery_error)+ from cron.scheduler_bookkeeping import finish_interrupted_run+ finish_interrupted_run(job, execution_id, delivery_error)return Truereturn _finish_completed_run(d, fire_owner, execution_id)diff --git a/cron/scheduler_authority.py b/cron/scheduler_authority.pyindex 7c5a97c4c0e..5a623993ddc 100644--- a/cron/scheduler_authority.py+++ b/cron/scheduler_authority.py@@ -17,12 +17,14 @@ def journal_path(job_id, request_id):def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_id=None):from gateway.session_cron import owner_for_home, operation- from hermes_cli.gateway_client import GatewayClientError, connect_gateway+ from hermes_cli.gateway_client import connect_gatewayfrom hermes_constants import get_hermes_home- from hermes_state_runtime import RuntimeStoreErrorfrom utils import atomic_json_write- params = {'job_id': job['id'], 'request_id': execution_id or job.get('execution_id') or uuid.uuid4().hex,+ request_id = execution_id or job.get('execution_id')+ if not request_id:+ request_id = job['execution_id'] = uuid.uuid4().hex+ params = {'job_id': job['id'], 'request_id': request_id,'extra_prompt': extra_prompt}root = get_hermes_home() / 'cron' / 'admissions'journal = journal_path(params['job_id'], params['request_id'])@@ -36,31 +38,30 @@ def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_iddef save():root.mkdir(parents=True, exist_ok=True)- # The journal is the only evidence a lost reply was admitted: survive power loss.atomic_json_write(journal, record, mode=0o600, fsync_dir=True)- async def refused(call, exc):- # A lost reply may still have been admitted. Only the owner's own verdict (a bounded- # reason code, never a disconnect/timeout) that its ledger holds no admission for this- # fire is a refusal: book it as an ordinary failed run, never unknown.- verdict = isinstance(exc, RuntimeStoreError) or (- isinstance(exc, GatewayClientError) and str(exc).replace('_', '').isalnum())- return verdict and (await call('recover', params))['status'] == 'missing'-async def observe(call):nonlocal attemptedattempted = Truesave()try:receipt = await call('submit', params)- except (RuntimeStoreError, GatewayClientError) as exc:- if await refused(call, exc):- journal.unlink(missing_ok=True)- attempted = False+ except Exception as exc:+ from hermes_cli.gateway_client import GatewayRPCError+ # A returned owner exception is definite; a transport disconnect is not. Even an+ # owner error after commit must retain the admitted identity, so verify its absence.+ if owner is not None or isinstance(exc, GatewayRPCError):+ state = await call('recover', params)+ if state['status'] == 'missing':+ error = f'{type(exc).__name__}: {exc}'+ result = [False, f'# Cron Job: {job["id"]} (FAILED)\n\n{error}\n', '', error]+ record['refusal'] = result+ record['job'] = dict(job)+ save()+ return tuple(result)raiserecord['receipt'] = receiptsave()- # Cron turns run for minutes: back the status read off to 2 s instead of 10 reads/s.delay = .1while True:if cancel_event is not None and cancel_event.is_set():@@ -72,7 +73,7 @@ def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_idif state['status'] == 'unknown':raise CronExecutionUnknown('unknown_execution: cron admission was not replayed')await asyncio.sleep(delay)- delay = min(delay * 1.5, 2.0)+ delay = min(delay * 2, 2.0)async def remote():async with connect_gateway() as client:@@ -105,10 +106,9 @@ def reconcile_pending(*, allow_connect=True):from gateway.session_cron import owner_for_home, operationfrom hermes_constants import get_hermes_homefrom hermes_cli.gateway_client import connect_gateway- from cron.jobs import pause_job, mark_job_run, save_job_output- from cron.scheduler import _compose_run_delivery, _is_cron_silence_response- from cron.delivery_queue import enqueue- from cron.executions import finish_execution+ from cron.jobs import pause_job+ from cron.scheduler import _RunDelivery, _FireOwnership, _save_compose_deliver, _finish_completed_run+ from utils import atomic_json_writeimport loggingroot = get_hermes_home() / 'cron' / 'admissions'@@ -118,41 +118,36 @@ def reconcile_pending(*, allow_connect=True):params = record['params']if journal != journal_path(params['job_id'], params['request_id']):raise ValueError('cron journal identity conflict')- owner = owner_for_home(get_hermes_home())- if owner is None and not allow_connect:- continue- async def observe():- if owner is not None:- return await operation(owner[0], 'recover', params)- async with connect_gateway() as client:- return await client.rpc('cron.recover', **params)- if owner is not None:- state = asyncio.run_coroutine_threadsafe(observe(), owner[1]).result(timeout=20)+ if 'refusal' in record:+ state = {'status': 'terminal', 'result': record['refusal'], 'job': record['job']}else:- state = asyncio.run(observe())+ owner = owner_for_home(get_hermes_home())+ if owner is None and not allow_connect:+ continue+ async def observe():+ if owner is not None:+ return await operation(owner[0], 'recover', params)+ async with connect_gateway() as client:+ return await client.rpc('cron.recover', **params)+ if owner is not None:+ state = asyncio.run_coroutine_threadsafe(observe(), owner[1]).result(timeout=20)+ else:+ state = asyncio.run(observe())if state['status'] != 'terminal':- if state['status'] in {'unknown', 'missing'}:+ if state['status'] in {'unknown', 'missing'} and not record.get('pause_recorded'):pause_job(params['job_id'], reason='Canonical cron ' + state['status'] + '; no automatic re-execution')+ record['pause_recorded'] = True+ atomic_json_write(journal, record, mode=0o600, fsync_dir=True)continuesuccess, output, answer, error = state['result']- job = state['job']+ job = dict(state['job'], **(state.get('job_flags') or {}))job['execution_id'] = params['request_id']- output_file = save_job_output(job['id'], output)- content, _, silent, _, _ = _compose_run_delivery(- job, success=success, error=error, final_response=answer, output_file=output_file)- deliver = bool(content.strip()) and not silent and not (success and _is_cron_silence_response(content))- if deliver:- enqueue(params['request_id'], job, content, for_failure=not success)- mark_job_run(job['id'], success, error, status='delivery_queued' if deliver else None,- execution_id=params['request_id'])- # The journal is the only link from the firer's ledger row to this receipt: settle- # the row (when its firer exited before its own bookkeeping) before deleting it.- from cron.delivery_outcome import settle_quietly, settled_outcome- finish_execution(params['request_id'], success=success, error=error, departed_owner=True,- delivery_outcome=(settled_outcome(params['request_id']) or 'queued')- if deliver else 'suppressed')- if deliver:- settle_quietly(job['id'], params['request_id'])- journal.unlink(missing_ok=True)+ delivery = _RunDelivery(job, success, error)+ # The canonical receipt supplies the result; a dead scheduler's fire claim does not+ # authorize replay and must not prevent finishing its durable bookkeeping.+ fence = _FireOwnership(dict(job, fire_claim=None))+ _save_compose_deliver(delivery, fence, answer, output, adapters=None, loop=None,+ verbose=False, execution_token=None)+ _finish_completed_run(delivery, None, params['request_id'], recovered=True)except Exception:logging.getLogger(__name__).warning('Cron receipt recovery deferred: %s', journal, exc_info=True)diff --git a/cron/scheduler_bookkeeping.py b/cron/scheduler_bookkeeping.pynew file mode 100644index 00000000000..37a11277c60--- /dev/null+++ b/cron/scheduler_bookkeeping.py@@ -0,0 +1,15 @@+"""Terminal bookkeeping phases shared by scheduler execution paths."""+++def finish_interrupted_run(job, execution_id, delivery_error):+ """Shutdown already advanced this run; update a failed notice without spending another fire."""+ from cron import scheduler+ logger = scheduler.logger+ if delivery_error:+ try:+ from cron.jobs import update_job+ update_job(job['id'], {'last_delivery_error': delivery_error})+ except Exception as exc:+ logger.debug('Failed recording delivery_error for interrupted job %s: %s', job['id'], exc, exc_info=True)+ scheduler.finish_execution(execution_id, success=False,+ error='Interrupted by gateway shutdown before terminal completion.')diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.pyindex 866c033867b..893c6a103d5 100644--- a/hermes_cli/gateway_client.py+++ b/hermes_cli/gateway_client.py@@ -13,6 +13,10 @@ class GatewayClientError(ValueError):pass+class GatewayRPCError(GatewayClientError):+ """A received owner refusal, distinct from an ambiguous transport failure."""++class GatewayClient:def __init__(self, websocket):self.websocket = websocket@@ -42,7 +46,7 @@ class GatewayClient:reason = frame["error"].get("message", "request_failed")if not isinstance(reason, str) or not reason.replace("_", "").isalnum() or len(reason) > 80:reason = "request_failed"- future.set_exception(GatewayClientError(reason))+ future.set_exception(GatewayRPCError(reason))else:future.set_result(frame.get("result", {}))elif "method" in frame:diff --git a/tests/cron/test_canonical_receipt_bookkeeping.py b/tests/cron/test_canonical_receipt_bookkeeping.pynew file mode 100644index 00000000000..d6f6857fb8a--- /dev/null+++ b/tests/cron/test_canonical_receipt_bookkeeping.py@@ -0,0 +1,92 @@+"""Canonical cron recovery settles attempts and never re-pauses an explicitly resumed job."""+from contextlib import asynccontextmanager+import json++import pytest++from cron import jobs, executions, scheduler_authority+from hermes_cli import gateway_client+++def peer(monkeypatch, call):+ class Peer:+ async def rpc(self, method, **params):+ return call(method, params)+ @asynccontextmanager+ async def connected():+ yield Peer()+ monkeypatch.setattr(gateway_client, 'connect_gateway', connected)+++def test_recovered_receipt_finishes_foreign_execution_and_is_idempotent(tmp_path, monkeypatch):+ with jobs.use_cron_store(tmp_path / 'cron'):+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local')+ execution = executions.create_execution(job['id'], source='test')+ executions.mark_execution_running(execution['id'])+ with executions._transaction() as conn:+ conn.execute('UPDATE executions SET process_id=?,pid=? WHERE id=?', ('old-owner', 999999, execution['id']))+ params = {'job_id': job['id'], 'request_id': execution['id'], 'extra_prompt': None}+ journal = scheduler_authority.journal_path(job['id'], execution['id'])+ journal.parent.mkdir(parents=True, exist_ok=True)+ saved = json.dumps({'params': params, 'receipt': None})+ journal.write_text(saved)+ peer(monkeypatch, lambda method, params: {'status': 'terminal', 'job': job,+ 'result': [True, 'document', 'answer', None]})+ scheduler_authority.reconcile_pending()+ assert executions.get_execution(execution['id'])['status'] == 'completed'+ assert not journal.exists()+ completed = jobs.get_job(job['id'])['repeat']['completed']+ journal.write_text(saved)+ scheduler_authority.reconcile_pending()+ assert jobs.get_job(job['id'])['repeat']['completed'] == completed+ assert executions.get_execution(execution['id'])['delivery_outcome'] == 'suppressed'+++def test_definite_refusal_is_booked_and_journal_retired(tmp_path, monkeypatch):+ with jobs.use_cron_store(tmp_path / 'cron'):+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local')+ execution = executions.create_execution(job['id'], source='test')+ def call(method, params):+ if method == 'cron.submit':+ raise gateway_client.GatewayRPCError('invalid_workdir')+ assert method == 'cron.recover'+ return {'status': 'missing', 'result': None}+ peer(monkeypatch, call)+ result = scheduler_authority.run_canonical_job(job, execution_id=execution['id'])+ assert result[0] is False and 'invalid_workdir' in result[3]+ # Recovery must also finish a refusal if the scheduler exited before its normal tail.+ scheduler_authority.reconcile_pending()+ assert executions.get_execution(execution['id'])['status'] == 'failed'+ assert jobs.get_job(job['id'])['state'] != 'paused'+ assert not scheduler_authority.journal_path(job['id'], execution['id']).exists()+++def test_resume_survives_recovery_of_old_unknown_journal(tmp_path, monkeypatch):+ with jobs.use_cron_store(tmp_path / 'cron'):+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local')+ params = {'job_id': job['id'], 'request_id': 'lost-fire', 'extra_prompt': None}+ journal = scheduler_authority.journal_path(job['id'], 'lost-fire')+ journal.parent.mkdir(parents=True, exist_ok=True)+ journal.write_text(json.dumps({'params': params, 'receipt': None}))+ peer(monkeypatch, lambda method, params: {'status': 'unknown', 'result': None})+ scheduler_authority.reconcile_pending()+ assert jobs.get_job(job['id'])['state'] == 'paused'+ jobs.resume_job(job['id'])+ scheduler_authority.reconcile_pending()+ assert jobs.get_job(job['id'])['enabled'] is True+ assert jobs.get_job(job['id'])['state'] == 'scheduled'+ assert journal.exists() # uncertain work is observed, never submitted again++[email protected]('initial', [{}, {'execution_id': None}])+def test_direct_retry_reuses_generated_fire_identity(monkeypatch, initial):+ requests = []+ def lose_reply(method, params):+ requests.append(params['request_id'])+ raise gateway_client.GatewayClientError('disconnected')+ peer(monkeypatch, lose_reply)+ job = {'id': 'direct-fire', **initial}+ for _ in range(2):+ with pytest.raises(scheduler_authority.CronExecutionUnknown):+ scheduler_authority.run_canonical_job(job)+ assert requests[0] == requests[1]diff --git a/tests/cron/test_cron_recovery.py b/tests/cron/test_cron_recovery.pyindex 4b3e635e8cc..0af361b97e9 100644--- a/tests/cron/test_cron_recovery.py+++ b/tests/cron/test_cron_recovery.py@@ -17,7 +17,7 @@ def test_lost_ack_reconciles_frozen_delivery_once(tmp_path, monkeypatch):monkeypatch.setenv('HERMES_HOME', str(tmp_path))monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {}, 'platform_toolsets': {'cli': []}})with jobs.use_cron_store(tmp_path / 'cron'):- job = jobs.create_job(prompt='original', schedule='every 1h', deliver='local')+ job = jobs.create_job(prompt='original', schedule='every 1h', deliver='telegram:123')db = SessionDB(tmp_path / 'state.db')runner = SimpleNamespace(_draining=False, session_store=SessionStore(tmp_path / 'sessions', GatewayConfig()), adapters={})authority = SessionAuthority(runner, profile_id=str(tmp_path), instance_id='test', db=db,@@ -122,7 +122,7 @@ def test_recovered_receipt_settles_the_departed_firers_execution_row(tmp_path, mfinally:db.close()settled = executions.get_execution(fire)- assert (settled['status'], settled['delivery_outcome']) == ('completed', 'queued')+ assert (settled['status'], settled['delivery_outcome']) == ('completed', 'suppressed')assert executions.recover_interrupted_executions() == 0assert executions.get_execution(fire)['status'] == 'completed'@@ -146,8 +146,10 @@ def test_owner_refused_fire_is_booked_failed_and_retires_its_journal(tmp_path, mresult = await asyncio.to_thread(scheduler_authority.run_canonical_job, jobs.get_job(job['id']), execution_id='fire')assert result[0] is False and 'invalid_params' in result[3]- assert not scheduler_authority.journal_path(job['id'], 'fire').exists()+ # Keep the definitive refusal until terminal bookkeeping, including a firing-process crash.+ assert scheduler_authority.journal_path(job['id'], 'fire').exists()await asyncio.to_thread(scheduler_authority.reconcile_pending)+ assert not scheduler_authority.journal_path(job['id'], 'fire').exists()finally:session_cron.unbind_owner(authority)try: