Skip to content

The agent that grows with you

fix(cron): a firer that gives up on a canonical run records its attempt as given up

Teknium2b3c8aef77f4
diff --git a/cron/executions.py b/cron/executions.py
index 0d679bce2f4..3e1090abbd7 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -562,6 +562,26 @@ def terminalize_dead_owner(execution_id: str, *, reason: str) -> bool:
return True
+def give_up_execution(execution_id: str, *, reason: str) -> bool:
+ """The firer itself gave up on its in-flight attempt (``CronExecutionUnknown``): record it
+ ``unknown`` now, owner-fenced to this process, instead of leaving it ``running`` until a
+ restart's dead-owner sweep. Receipt recovery never acts for a same-process running row, so
+ the owner's later terminal receipt can settle it only once it is marked given up."""
+ now = _hermes_now().isoformat()
+ with _transaction() as conn:
+ cur = conn.execute(
+ """UPDATE executions SET status='unknown', finished_at=?, error=?,
+ handoff_pending=0, handoff_started_at=NULL
+ WHERE id=? AND status IN ('claimed','running') AND process_id=? AND pid=?""",
+ (now, reason, str(execution_id), _PROCESS_ID, os.getpid()))
+ if cur.rowcount != 1:
+ return False
+ record = _fetch(conn, str(execution_id))
+ _prune_unlocked(conn)
+ _emit_execution_state(record)
+ return True
+
+
def list_executions(
*, job_id: Optional[str] = None, limit: int = 50, before_claimed_at: Optional[str] = None,
) -> list[dict[str, Any]]:
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 515b17b38c9..39783b2a0d1 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -3421,8 +3421,10 @@ def _run_one_job_body(
except BaseException as e:
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))
+ give_up_execution(execution_id, reason=str(e))
logger.error("Cron %s paused with unverified admission: %s", job["id"], e)
return False
# BaseException, not Exception: CancelledError/KeyboardInterrupt/SystemExit propagate here.
diff --git a/tests/cron/test_canonical_firer_give_up.py b/tests/cron/test_canonical_firer_give_up.py
new file mode 100644
index 00000000000..b17fb211b08
--- /dev/null
+++ b/tests/cron/test_canonical_firer_give_up.py
@@ -0,0 +1,39 @@
+"""An in-gateway firer that gives up on a canonical run records its own attempt as given up."""
+from contextlib import asynccontextmanager
+import json
+
+from cron import executions, jobs, scheduler, scheduler_authority
+from hermes_cli import gateway_client
+
+
+def test_given_up_fire_leaves_its_attempt_recoverable_not_running(tmp_path, monkeypatch):
+ """CronExecutionUnknown pauses the job, but the firer's own ``running`` row must not stay in
+ flight until a restart: receipt recovery skips a same-process running row, so the owner's
+ later terminal receipt could never settle it (R17 residual)."""
+ 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 = 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: owner lost')
+ 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'
+ given_up = executions.get_execution(fire)
+ assert given_up['status'] == 'unknown' and 'owner lost' in given_up['error']
+
+ class Peer:
+ async def rpc(self, method, **params):
+ return {'status': 'terminal', 'job': job, 'result': [True, 'document', 'answer', None]}
+
+ @asynccontextmanager
+ async def connected():
+ yield Peer()
+ monkeypatch.setattr(gateway_client, 'connect_gateway', connected)
+ scheduler_authority.reconcile_pending()
+ assert executions.get_execution(fire)['status'] == 'completed'
+ assert not journal.exists()