The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): recovered cron runs settle their execution history instead of staying running
Teknium770b5924a619
diff --git a/cron/executions.py b/cron/executions.pyindex bf42f87b588..f020230508a 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -311,20 +311,37 @@ def mark_execution_running(execution_id: str) -> Optional[Dict[str, Any]]:def finish_execution(execution_id: str, *, success: bool, error: Optional[str] = None,- delivery_outcome: Optional[str] = None,+ delivery_outcome: Optional[str] = None, departed_owner: bool = False,) -> Optional[Dict[str, Any]]:- """Write a terminal result once; terminal attempts cannot be rewritten."""+ """Write a terminal result once; terminal attempts cannot be rewritten.++ Only the owning process may finish its attempt. ``departed_owner`` is the one exception:+ receipt recovery (``cron.scheduler_authority.reconcile_pending``) holds the owner's+ terminal canonical result for an attempt whose firing process provably exited before its+ own bookkeeping. It settles that attempt with the receipt's verdict instead of leaving it+ ``running`` for the dead-owner sweep to rewrite as ``unknown``; a live or same-process+ owner still finishes its own row.+ """now = _hermes_now().isoformat()status = "completed" if success else "failed"detail = None if success else (str(error) if error else "unknown failure")with _transaction() as conn:+ owner = (_PROCESS_ID, os.getpid())+ if departed_owner:+ row = conn.execute(+ """SELECT process_id, pid, process_started_at FROM executions+ WHERE id=? AND status IN ('claimed','running')""", (execution_id,)).fetchone()+ if (row is None or row["process_id"] == _PROCESS_ID+ or _owner_is_live(int(row["pid"]), row["process_started_at"])):+ return None+ owner = (row["process_id"], row["pid"])cur = conn.execute("""UPDATE executionsSET status=?, finished_at=?, error=?, handoff_pending=0,handoff_started_at=NULL, delivery_outcome=?WHERE id=? AND status IN ('claimed','running')AND process_id=? AND pid=?""",- (status, now, detail, delivery_outcome, execution_id, _PROCESS_ID, os.getpid()),+ (status, now, detail, delivery_outcome, execution_id, *owner),)if cur.rowcount != 1:return Nonediff --git a/cron/scheduler_authority.py b/cron/scheduler_authority.pyindex 0db6d1f467e..a20006a084e 100644--- a/cron/scheduler_authority.py+++ b/cron/scheduler_authority.py@@ -89,6 +89,7 @@ def reconcile_pending(*, allow_connect=True):from cron.jobs import pause_job, mark_job_run, save_job_outputfrom cron.scheduler import _compose_run_delivery, _is_cron_silence_responsefrom cron.delivery_queue import enqueue+ from cron.executions import finish_executionimport loggingroot = get_hermes_home() / 'cron' / 'admissions'@@ -125,8 +126,13 @@ def reconcile_pending(*, allow_connect=True):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:- from cron.delivery_outcome import settle_quietlysettle_quietly(job['id'], params['request_id'])journal.unlink(missing_ok=True)except Exception:diff --git a/tests/cron/test_cron_recovery.py b/tests/cron/test_cron_recovery.pyindex bb440e35e29..8380a47e049 100644--- a/tests/cron/test_cron_recovery.py+++ b/tests/cron/test_cron_recovery.py@@ -68,3 +68,61 @@ def test_failed_manual_run_exits_nonzero(monkeypatch):from hermes_cli import cronmonkeypatch.setattr(cron, '_cron_api', lambda **kw: {'success': True, 'job': {'executed': True, 'execution_success': False}})assert cron._job_action('run', 'job', 'Triggered') == 1+++def _owner(tmp_path, monkeypatch):+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {}, 'platform_toolsets': {'cli': []}})+ 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,+ epoch=begin_runtime_epoch(db, instance_id='test'))+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ runner.session_authority = authority+ return authority, db+++def test_recovered_receipt_settles_the_departed_firers_execution_row(tmp_path, monkeypatch):+ """The firing process created and started the execution row, then exited after the owner+ finished. Recovery books the job from the receipt and must settle that SAME ledger row+ before the journal (its only link to the receipt) is deleted — not leave it running for+ the dead-owner sweep to rewrite as unknown."""+ import os+ import subprocess+ import sys+ from cron import scheduler_authority, executions+ with jobs.use_cron_store(tmp_path / 'cron'):+ job = jobs.create_job(prompt='original', schedule='every 1h', deliver='local')+ authority, db = _owner(tmp_path, monkeypatch)+ firer = subprocess.run([sys.executable, '-c', (+ 'import sys; from cron.executions import create_execution, mark_execution_running;'+ f'r = create_execution({job["id"]!r}, source="direct"); mark_execution_running(r["id"]);'+ 'print(r["id"])')], env={**os.environ, 'HERMES_HOME': str(tmp_path)},+ capture_output=True, text=True, check=True, timeout=60)+ fire = firer.stdout.strip().splitlines()[-1]+ assert executions.get_execution(fire)['status'] == 'running'++ async def probe():+ params = {'job_id': job['id'], 'request_id': fire, 'extra_prompt': None}+ receipt = await session_cron.operation(authority, 'submit', params)+ row = claim_session_input(db, epoch=authority.epoch, session_id=receipt['session_id'])+ settle_session_input(db, epoch=authority.epoch, admission_id=row['admission_id'], generation=row['generation'], outcome='completed',+ result={'result': {'cron_result': [True, 'document', 'answer', None]}, 'usage': {}})+ journal = scheduler_authority.journal_path(job['id'], fire)+ journal.parent.mkdir(parents=True)+ journal.write_text(json.dumps({'params': params, 'receipt': None}))+ session_cron.bind_owner(authority)+ try:+ await asyncio.to_thread(scheduler_authority.reconcile_pending)+ finally:+ session_cron.unbind_owner(authority)+ assert not journal.exists()+ try:+ asyncio.run(probe())+ finally:+ db.close()+ settled = executions.get_execution(fire)+ assert (settled['status'], settled['delivery_outcome']) == ('completed', 'queued')+ assert executions.recover_interrupted_executions() == 0+ assert executions.get_execution(fire)['status'] == 'completed'+