Skip to content

The agent that grows with you

fix(cron): receipt recovery never acts for a live firer, this process included

Teknium5d8dbc5ccffa
diff --git a/cron/executions.py b/cron/executions.py
index ec5bdafbfb6..553201cef50 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -355,16 +355,13 @@ def finish_execution(
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.
+ Terminal verdicts stay immutable. A live firer still owns its bookkeeping
+ (``execution_owner_live``).
"""
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'])):
+ row = _recoverable_row(conn, execution_id, job_id)
+ if row is None or _row_owner_live(row):
return None
conn.execute(
"""UPDATE executions SET status=?, finished_at=?, error=?, handoff_pending=0,
@@ -378,6 +375,29 @@ def recover_receipted_execution(execution_id, job_id, *, success, error=None, de
return record
+def _recoverable_row(conn, execution_id, job_id):
+ return conn.execute(
+ """SELECT status, process_id, pid, process_started_at FROM executions
+ WHERE id=? AND job_id=? AND status IN ('claimed','running','unknown')""",
+ (str(execution_id), str(job_id))).fetchone()
+
+
+def _row_owner_live(row) -> bool:
+ if row['process_id'] == _PROCESS_ID:
+ # The in-gateway ticker fires on pool threads: a claimed/running row of THIS process is
+ # still in flight here. Only an unknown row was given up by its own firer.
+ return row['status'] != 'unknown'
+ return _owner_is_live(int(row['pid']), row['process_started_at'])
+
+
+def execution_owner_live(execution_id: str, job_id: str) -> bool:
+ """True while the attempt's own firer (this process included) can still finish it, so receipt
+ recovery must not act for it: no output re-save, no job mark, no ledger write."""
+ with _transaction() as conn:
+ row = _recoverable_row(conn, execution_id, job_id)
+ return row is not None and _row_owner_live(row)
+
+
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_authority.py b/cron/scheduler_authority.py
index 5a623993ddc..f87b434ab1d 100644
--- a/cron/scheduler_authority.py
+++ b/cron/scheduler_authority.py
@@ -106,6 +106,7 @@ def reconcile_pending(*, allow_connect=True):
from gateway.session_cron import owner_for_home, operation
from hermes_constants import get_hermes_home
from hermes_cli.gateway_client import connect_gateway
+ from cron.executions import execution_owner_live
from cron.jobs import pause_job
from cron.scheduler import _RunDelivery, _FireOwnership, _save_compose_deliver, _finish_completed_run
from utils import atomic_json_write
@@ -118,6 +119,10 @@ 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')
+ if execution_owner_live(params['request_id'], params['job_id']):
+ # Its firer (this process included) still owns the row and its tail: re-saving the
+ # output or re-marking the job on every tick would duplicate its side effects.
+ continue
if 'refusal' in record:
state = {'status': 'terminal', 'result': record['refusal'], 'job': record['job']}
else:
diff --git a/tests/cron/test_canonical_receipt_bookkeeping.py b/tests/cron/test_canonical_receipt_bookkeeping.py
index d6f6857fb8a..f325f6ba608 100644
--- a/tests/cron/test_canonical_receipt_bookkeeping.py
+++ b/tests/cron/test_canonical_receipt_bookkeeping.py
@@ -55,12 +55,37 @@ def test_definite_refusal_is_booked_and_journal_retired(tmp_path, monkeypatch):
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.
+ with executions._transaction() as conn:
+ conn.execute('UPDATE executions SET process_id=?,pid=? WHERE id=?', ('old-owner', 999999, execution['id']))
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_in_process_firer_keeps_its_row_journal_and_output(tmp_path, monkeypatch):
+ """The in-gateway ticker fires on pool threads: a tick must not act for a firer still in flight
+ in THIS process (770b5924a61's "never this process" fence), nor redo its side effects."""
+ 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)
+ params = {'job_id': job['id'], 'request_id': fire, 'extra_prompt': None}
+ journal = scheduler_authority.journal_path(job['id'], fire)
+ journal.parent.mkdir(parents=True, exist_ok=True)
+ journal.write_text(json.dumps({'params': params, 'receipt': {'x': 1}}))
+ calls = []
+ peer(monkeypatch, lambda method, params: calls.append(method) or {
+ 'status': 'terminal', 'job': job, 'result': [True, 'document', 'answer', None]})
+ scheduler_authority.reconcile_pending()
+ assert executions.get_execution(fire)['status'] == 'running'
+ assert journal.exists() and calls == []
+ assert not list(jobs._job_output_dir(job['id']).glob('*.md'))
+ assert jobs.get_job(job['id'])['last_run_at'] is None
+ # The firer's own tail still finishes its row with its real outcome.
+ assert executions.finish_execution(fire, success=False, error='interrupted') is not None
+
+
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')
diff --git a/tests/cron/test_live_firer_receipt_recovery.py b/tests/cron/test_live_firer_receipt_recovery.py
index 0409726fda1..1ea5f9117f1 100644
--- a/tests/cron/test_live_firer_receipt_recovery.py
+++ b/tests/cron/test_live_firer_receipt_recovery.py
@@ -33,9 +33,13 @@ def test_live_firer_journal_survives_until_its_execution_can_settle(tmp_path, mo
async def connect():
yield Peer()
monkeypatch.setattr('hermes_cli.gateway_client.connect_gateway', connect)
- scheduler_authority.reconcile_pending()
+ for _ in range(2):
+ scheduler_authority.reconcile_pending()
assert journal.exists(), 'the live firer left running execution without its recovery receipt'
assert executions.get_execution(fire)['status'] == 'running'
+ # Retaining the journal must not replay the receipt's side effects on every tick.
+ assert not list(jobs._job_output_dir(job['id']).glob('*.md'))
+ assert jobs.get_job(job['id'])['last_run_at'] is None
child.stdin.close()
child.wait(timeout=10)
scheduler_authority.reconcile_pending()