Skip to content

The agent that grows with you

fix(cron): recovery books a missing admission failed and lifts its own unknown pause

Tekniumeef16d28c8ff
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 7d445a3325e..bcd93d8d1a5 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -3422,8 +3422,8 @@ def _run_one_job_body(
from cron.scheduler_authority import CronExecutionUnknown
if isinstance(e, CronExecutionUnknown):
from cron.executions import give_up_execution
- from cron.jobs import pause_job
- pause_job(job["id"], reason=str(e))
+ from cron.scheduler_authority import pause_for_unknown
+ pause_for_unknown(job["id"], execution_id, str(e))
give_up_execution(execution_id, reason=str(e))
logger.error("Cron %s paused with unverified admission: %s", job["id"], e)
return False
diff --git a/cron/scheduler_authority.py b/cron/scheduler_authority.py
index f2bb545e3f1..8628fae8a15 100644
--- a/cron/scheduler_authority.py
+++ b/cron/scheduler_authority.py
@@ -15,6 +15,37 @@ def journal_path(job_id, request_id):
return get_hermes_home() / 'cron' / 'admissions' / (key + '.json')
+def _pause_identity(paused):
+ """The exact pause this recovery uncertainty caused, so only that pause is ever lifted."""
+ return {'paused_at': paused.get('paused_at'), 'reason': paused.get('paused_reason')} if paused else True
+
+
+def pause_for_unknown(job_id, execution_id, reason):
+ """The firer pauses the job for this fire's unverified admission and records that exact pause
+ on the fire's journal, so the receipt that later proves the run terminal can lift it."""
+ from cron.jobs import pause_job
+ from utils import atomic_json_write
+ paused = pause_job(job_id, reason=reason)
+ journal = journal_path(job_id, execution_id)
+ if paused and journal.exists():
+ record = json.loads(journal.read_text(encoding='utf-8-sig'))
+ record['pause_recorded'] = _pause_identity(paused)
+ atomic_json_write(journal, record, mode=0o600, fsync_dir=True)
+
+
+def _lift_pause(job_id, pause):
+ """A verified terminal receipt resolved the uncertainty that paused the schedule: resume it iff
+ the job is still held by exactly that pause (an operator's own pause/resume is never touched)."""
+ from cron.jobs import get_job, resume_job
+ job = get_job(job_id) if isinstance(pause, dict) else None
+ if (job is not None and job.get('state') == 'paused'
+ and (job.get('paused_at'), job.get('paused_reason')) == (pause['paused_at'], pause['reason'])):
+ try:
+ resume_job(job_id)
+ except ValueError: # a one-shot whose instant has passed stays paused for the operator
+ pass
+
+
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 connect_gateway
@@ -119,7 +150,7 @@ def reconcile_pending(*, allow_connect=True):
from hermes_constants import get_hermes_home
from hermes_cli.gateway_client import connect_gateway
from cron.executions import execution_owner_live, get_execution
- from cron.jobs import pause_job
+ from cron.jobs import get_job, pause_job
from cron.scheduler import (_RunDelivery, _FireOwnership, _apply_agent_failure_marker,
_save_compose_deliver)
from cron.scheduler_bookkeeping import fail_empty_response, finish_completed_run
@@ -158,10 +189,20 @@ def reconcile_pending(*, allow_connect=True):
state = asyncio.run_coroutine_threadsafe(observe(), owner[1]).result(timeout=20)
else:
state = asyncio.run(observe())
+ if state['status'] == 'missing':
+ # The owner holds no admission for this fire: a definite non-admission, booked as
+ # the same failed run the in-submit refusal books. Only ``unknown`` pauses.
+ current = get_job(params['job_id'])
+ if current is None:
+ journal.unlink(missing_ok=True)
+ continue
+ error = 'Cron admission missing: the owner never admitted this fire'
+ state = {'status': 'terminal', 'job': current,
+ 'result': [False, f'# Cron Job: {params["job_id"]} (FAILED)\n\n{error}\n', '', error]}
if state['status'] != 'terminal':
- 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
+ if state['status'] == 'unknown' and not record.get('pause_recorded'):
+ reason = 'Canonical cron unknown; no automatic re-execution'
+ record['pause_recorded'] = _pause_identity(pause_job(params['job_id'], reason=reason))
atomic_json_write(journal, record, mode=0o600, fsync_dir=True)
continue
success, output, answer, error = state['result']
@@ -177,6 +218,7 @@ def reconcile_pending(*, allow_connect=True):
_save_compose_deliver(delivery, fence, answer, output, adapters=None, loop=None,
verbose=False, execution_token=None)
fail_empty_response(delivery, answer)
- finish_completed_run(delivery, None, params['request_id'], recovered=True)
+ if finish_completed_run(delivery, None, params['request_id'], recovered=True):
+ _lift_pause(params['job_id'], record.get('pause_recorded'))
except Exception:
logging.getLogger(__name__).warning('Cron receipt recovery deferred: %s', journal, exc_info=True)
diff --git a/tests/cron/test_cron_recover_pause.py b/tests/cron/test_cron_recover_pause.py
new file mode 100644
index 00000000000..99f35f0a61a
--- /dev/null
+++ b/tests/cron/test_cron_recover_pause.py
@@ -0,0 +1,82 @@
+"""Receipt recovery: a ``missing`` admission is a definite non-admission (booked failed, never a
+pause), and a verified terminal receipt lifts the pause its own ``CronExecutionUnknown`` caused."""
+from contextlib import asynccontextmanager
+import json
+
+from cron import executions, jobs, scheduler, scheduler_authority
+from hermes_cli import gateway_client
+
+
+def _peer(monkeypatch, answer):
+ class Peer:
+ async def rpc(self, method, **params):
+ return answer(method)
+
+ @asynccontextmanager
+ async def connected():
+ yield Peer()
+ monkeypatch.setattr(gateway_client, 'connect_gateway', connected)
+
+
+def _foreign_journal(job, fire):
+ with executions._transaction() as conn:
+ conn.execute('UPDATE executions SET process_id=?,pid=? WHERE id=?', ('old-owner', 999999, fire))
+ journal = scheduler_authority.journal_path(job['id'], fire)
+ journal.parent.mkdir(parents=True, exist_ok=True)
+ journal.write_text(json.dumps({'params': {'job_id': job['id'], 'request_id': fire, 'extra_prompt': None},
+ 'receipt': None}))
+ return journal
+
+
+def test_missing_admission_is_booked_failed_not_paused(tmp_path, monkeypatch):
+ """The firer died after writing its journal but before the owner admitted the fire."""
+ _peer(monkeypatch, lambda method: {'status': 'missing', 'result': None})
+ with jobs.use_cron_store(tmp_path / 'cron'):
+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local')
+ fire = executions.create_execution(job['id'], source='test')['id']
+ executions.mark_execution_running(fire)
+ journal = _foreign_journal(job, fire)
+ scheduler_authority.reconcile_pending()
+ saved = jobs.get_job(job['id'])
+ assert saved['state'] != 'paused' and saved['enabled'] is True
+ assert saved['last_status'] == 'error'
+ assert executions.get_execution(fire)['status'] == 'failed'
+ assert not journal.exists()
+
+
+def _unknown_fire(monkeypatch, job, fire):
+ """The firer journals the fire, then loses its observer: CronExecutionUnknown pauses the job."""
+ journal = scheduler_authority.journal_path(job['id'], fire)
+
+ def run_job(job, **kwargs):
+ journal.parent.mkdir(parents=True, exist_ok=True)
+ journal.write_text(json.dumps({'params': {'job_id': job['id'], 'request_id': fire,
+ 'extra_prompt': None}, 'receipt': None}))
+ raise scheduler_authority.CronExecutionUnknown('Cron execution unverified: observer dropped')
+ monkeypatch.setattr(scheduler, 'run_job', run_job)
+ assert scheduler._run_one_job_body(dict(jobs.get_job(job['id']), execution_id=fire)) is False
+ assert jobs.get_job(job['id'])['state'] == 'paused'
+ return journal
+
+
+def test_terminal_receipt_lifts_the_unknown_pause_it_caused(tmp_path, monkeypatch):
+ """Once the owner's receipt proves the run terminal, the recurring schedule resumes by itself;
+ an operator's own later pause is never lifted by a receipt."""
+ with jobs.use_cron_store(tmp_path / 'cron'):
+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local')
+ fire = executions.create_execution(job['id'], source='test')['id']
+ journal = _unknown_fire(monkeypatch, job, fire)
+ _peer(monkeypatch, lambda method: {'status': 'terminal', 'job': job,
+ 'result': [True, 'document', 'answer', None]})
+ scheduler_authority.reconcile_pending()
+ saved = jobs.get_job(job['id'])
+ assert (saved['state'], saved['enabled'], saved['paused_reason']) == ('scheduled', True, None)
+ assert executions.get_execution(fire)['status'] == 'completed'
+ assert not journal.exists()
+
+ second = executions.create_execution(job['id'], source='test')['id']
+ _unknown_fire(monkeypatch, job, second)
+ jobs.resume_job(job['id'])
+ jobs.pause_job(job['id'], reason='operator hold')
+ scheduler_authority.reconcile_pending()
+ assert jobs.get_job(job['id'])['paused_reason'] == 'operator hold'