Skip to content

The agent that grows with you

fix(cron): an owner-side cron run stamps progress on the firer's ledger row

Tekniume74bb8bf6572
diff --git a/cron/scheduler_authority.py b/cron/scheduler_authority.py
index a28082ecf36..cd2f4c2dd8e 100644
--- a/cron/scheduler_authority.py
+++ b/cron/scheduler_authority.py
@@ -62,11 +62,18 @@ def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_id
raise
record['receipt'] = receipt
save()
- delay = .1
+ delay, progress = .1, None
while True:
if cancel_event is not None and cancel_event.is_set():
await call('cancel', receipt)
state = await call('status', receipt)
+ if state.get('progress_at') not in (None, progress):
+ # The owner's agent is still working: refresh OUR ledger row (the owner's stamp is
+ # fenced to the row's owner), once per owner stamp, so the stale-claim sweep measures
+ # the run's silence. A wedged owner stops stamping and the sweep still fires.
+ from cron.executions import touch_execution_progress
+ progress = state['progress_at']
+ await asyncio.to_thread(touch_execution_progress, request_id)
if state['status'] == 'terminal':
job.update(state.get('job_flags') or {})
return tuple(state['result'])
diff --git a/cron/scheduler_liveness.py b/cron/scheduler_liveness.py
index 9602f5253c4..1b7b009589e 100644
--- a/cron/scheduler_liveness.py
+++ b/cron/scheduler_liveness.py
@@ -21,6 +21,11 @@ from cron.executions import touch_execution_progress
logger = logging.getLogger(__name__)
+# execution id -> wall time of the stamper's last progress verdict. A canonical cron run executes in
+# the gateway owner, but its ledger row belongs to the firer (an external worker), so the owner's own
+# stamp is fenced off it; ``cron.status`` reports this and the firer stamps its row itself.
+owner_progress: dict[str, float] = {}
+
def _inactivity_watchdog_loop(
*, get_idle_seconds: Callable[[], float], limit_s: float, poll_s: float, stop: threading.Event,
@@ -71,6 +76,7 @@ class ExecutionProgressStamper:
if self._idle_seconds() >= self._every:
return
self._last = now
+ owner_progress[self._execution_id] = time.time()
try:
touch_execution_progress(self._execution_id)
except Exception:
diff --git a/gateway/session_cron.py b/gateway/session_cron.py
index 84b4d7774e7..d30f23267cb 100644
--- a/gateway/session_cron.py
+++ b/gateway/session_cron.py
@@ -172,7 +172,9 @@ async def operation(authority, name, params, actor=None):
flags = (saved['result'].get('cron_job_flags') or {}) if saved else {}
if result is None:
result = [False, '', '', row.get('outcome') or 'unknown_execution']
- return {'status': row['status'], 'result': result, 'job_flags': flags}
+ from cron.scheduler_liveness import owner_progress
+ return {'status': row['status'], 'result': result, 'job_flags': flags,
+ 'progress_at': owner_progress.get(row['request_id'].rsplit(':', 1)[-1])}
def _cancellations(authority):
@@ -218,8 +220,9 @@ async def execute(authority, ref, row, policy):
raise RuntimeStoreError('admission_conflict')
cancellations = _cancellations(authority)
cancel = cancellations.setdefault(row['admission_id'], threading.Event())
- job = data['cron_job']
- execution_id = scheduler_execution_id(job['id'], row['request_id'])
+ execution_id = scheduler_execution_id(data['cron_job']['id'], row['request_id'])
+ # The frozen snapshot predates the fire's ledger row; the run's progress stamps need its id.
+ job = dict(data['cron_job'], execution_id=execution_id)
token = _execution.set((authority, ref.session_id, job['id'], execution_id))
try:
db_path = await asyncio.to_thread(Path(authority.db.db_path).resolve)
@@ -236,5 +239,7 @@ async def execute(authority, ref, row, policy):
raise RuntimeError(result[3] or 'cron execution failed')
return result[2]
finally:
+ from cron.scheduler_liveness import owner_progress
+ owner_progress.pop(execution_id, None)
_execution.reset(token)
cancellations.pop(row['admission_id'], None)
diff --git a/tests/gateway/test_cron_owner_progress_stamp.py b/tests/gateway/test_cron_owner_progress_stamp.py
new file mode 100644
index 00000000000..18c9b461b92
--- /dev/null
+++ b/tests/gateway/test_cron_owner_progress_stamp.py
@@ -0,0 +1,77 @@
+"""An owner-side canonical cron run proves progress on the FIRER's ledger row.
+
+The owner executes the job, but the execution row belongs to the firer (an external worker), and
+``touch_execution_progress`` is fenced to the row's owner. Before this fix the owner's job dict had
+no execution id at all (its stamper returned early) and the firer never stamped, so a long, healthy
+run was swept ``unknown`` once the derived stale bound passed."""
+import asyncio
+import threading
+import time
+from types import SimpleNamespace
+
+import cron.executions as executions_mod
+
+
+def test_owner_progress_reaches_the_firers_ledger_row(tmp_path, monkeypatch):
+ from cron import jobs, scheduler, scheduler_liveness
+ from cron.executions import _transaction, create_execution, mark_execution_running
+ from cron.scheduler_authority import run_canonical_job
+ from gateway import run, session_cron
+ from gateway.config import GatewayConfig, Platform
+ from gateway.session import SessionStore
+ from gateway.session_authority import SessionAuthority
+ from gateway.session_contract import SessionRef
+ from gateway.session_local_recovery import local_adapter_map
+ from hermes_state import SessionDB
+ from hermes_state_runtime import begin_runtime_epoch, claim_session_input, settle_session_input
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(executions_mod, 'EXECUTIONS_FILE', tmp_path / 'cron' / 'executions.db')
+ monkeypatch.setattr(jobs, 'get_job', lambda jid: {'id': jid, 'prompt': 'p', 'model': 'm'})
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {}, 'platform_toolsets': {'cli': []}})
+ # The owner is not the row's owner: its own stamp never lands on the firer's row.
+ monkeypatch.setattr(scheduler_liveness, 'touch_execution_progress', lambda execution_id: False)
+ execution = create_execution('job', source='cron')
+ mark_execution_running(execution['id'])
+ 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'))
+ runner.session_authority = authority
+ admitted = threading.Event()
+ monkeypatch.setattr(authority, '_schedule', lambda ref: admitted.set())
+
+ def run_job(job, *, extra_prompt, execution_id, cancel_event):
+ stamper = scheduler_liveness.ExecutionProgressStamper(
+ str(job.get('execution_id') or ''), 'job', idle_seconds=lambda: 0.0, every_seconds=0.001)
+ time.sleep(0.01)
+ stamper.tick()
+ time.sleep(0.6) # the firer polls status while the agent works
+ return (True, 'doc', 'answer', None)
+ monkeypatch.setattr(scheduler, 'run_job', run_job)
+
+ async def probe():
+ session_cron.bind_owner(authority)
+ try:
+ firer = asyncio.create_task(asyncio.to_thread(run_canonical_job, {'id': 'job'},
+ execution_id=execution['id']))
+ assert await asyncio.to_thread(admitted.wait, 10), firer
+ sid = next(iter(authority.sessions))
+ row = claim_session_input(db, epoch=authority.epoch, session_id=sid)
+ policy = local_adapter_map(authority)[Platform.LOCAL].policies[sid]
+ await session_cron.execute(authority, SessionRef(authority.profile_id, sid), row, policy)
+ settle_session_input(db, epoch=authority.epoch, admission_id=row['admission_id'],
+ generation=row['generation'], outcome='completed',
+ result={'result': {'cron_result': [True, 'doc', 'answer', None]}, 'usage': {}})
+ assert await asyncio.wait_for(firer, 10) == (True, 'doc', 'answer', None)
+ finally:
+ session_cron.unbind_owner(authority)
+
+ try:
+ asyncio.run(probe())
+ finally:
+ db.close()
+ with _transaction() as conn:
+ stamped = conn.execute('SELECT progress_at FROM executions WHERE id=?', (execution['id'],)).fetchone()[0]
+ assert stamped is not None, "the firer's row never saw the owner's progress"