The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): cron.cancel latches against a started admission before execute registers (X13, reported by @Xipong)
teknium10409376f9649
diff --git a/gateway/session_cron.py b/gateway/session_cron.pyindex 351b6e043d7..902dbf2f031 100644--- a/gateway/session_cron.py+++ b/gateway/session_cron.py@@ -144,11 +144,12 @@ async def operation(authority, name, params, actor=None):if row is None or row['target_session_id'] != ref.session_id or row['principal_id'] != actor.subject:raise RuntimeStoreError('permission_denied')if name == 'cancel':- event = getattr(authority, '_cron_cancellations', {}).get(row['admission_id'])- if event is not None:- event.set()- elif row['status'] == 'queued':+ if row['status'] == 'queued':await authority.cancel_queued(actor, ref, row['admission_id'])+ elif row['status'] == 'started':+ # The claim commits before execute() registers its event; latching the+ # cancellation on the admission here means that window cannot lose it.+ _cancellations(authority).setdefault(row['admission_id'], threading.Event()).set()return {'ok': True}result = Noneif row['status'] == 'terminal':@@ -160,6 +161,13 @@ async def operation(authority, name, params, actor=None):return {'status': row['status'], 'result': result}+def _cancellations(authority):+ cancellations = getattr(authority, '_cron_cancellations', None)+ if cancellations is None:+ cancellations = authority._cron_cancellations = {}+ return cancellations++async def rpc(connection, name, params):return await operation(connection.authority, name, params, connection.actor)@@ -172,10 +180,8 @@ async def execute(authority, ref, row, policy):or row['request_id'] != data['request_id']or row['principal_id'] != authority.sessions[ref.session_id].source.user_id):raise RuntimeStoreError('admission_conflict')- cancellations = getattr(authority, '_cron_cancellations', None)- if cancellations is None:- cancellations = authority._cron_cancellations = {}- cancel = cancellations[row['admission_id']] = threading.Event()+ cancellations = _cancellations(authority)+ cancel = cancellations.setdefault(row['admission_id'], threading.Event())token = _execution.set((authority, ref.session_id, data['cron_job']['id'], row['admission_id']))try:with _profile_runtime_scope(Path(authority.db.db_path).resolve().parent):diff --git a/tests/gateway/test_session_cron.py b/tests/gateway/test_session_cron.pyindex 53b4321a42b..db35e333f20 100644--- a/tests/gateway/test_session_cron.py+++ b/tests/gateway/test_session_cron.py@@ -42,3 +42,46 @@ def test_cron_admission_uses_job_model_and_exact_retry(tmp_path, monkeypatch):asyncio.run(probe())finally:db.close()+++async def test_cron_cancel_between_claim_and_execution_registration_stops_the_job(tmp_path, monkeypatch):+ """A started admission whose execute() has not registered its event yet still honours cancel."""+ from contextlib import nullcontext+ import json+ from cron import scheduler+ from gateway import run, session_cron+ from gateway.session_authority import LiveSession, SessionAuthority+ from gateway.session_contract import Principal, SessionRef+ from hermes_state import SessionDB+ from hermes_state_runtime import admit_session_input, begin_runtime_epoch, claim_session_input++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ db = SessionDB(tmp_path / 'state.db')+ db.create_session('s', source='cron')+ authority = SessionAuthority(SimpleNamespace(_draining=False), profile_id='p', instance_id='test', db=db,+ epoch=begin_runtime_epoch(db, instance_id='test'))+ authority.sessions['s'] = LiveSession(SimpleNamespace(platform=None, user_id='cron-owner'), 'route')+ actor = Principal('cron-owner', 'p', frozenset({'session:create', 'session:submit', 'session:control'}), 'ticker')+ ref = SessionRef('p', 's')+ monkeypatch.setattr(run, '_profile_runtime_scope', lambda home: nullcontext())+ seen = {}++ def run_job(job, *, extra_prompt, execution_id, cancel_event):+ seen['cancelled_at_start'] = cancel_event.is_set()+ return (False, '', '', 'cancelled')+ monkeypatch.setattr(scheduler, 'run_job', run_job)++ with db:+ admit_session_input(db, epoch=authority.epoch, principal_id='cron-owner', session_id='s',+ request_id='cron:job:fire', payload={'text': ''})+ row = claim_session_input(db, epoch=authority.epoch, session_id='s')+ # The claim is committed and visible as `started`; execute() has not run yet.+ params = {'session_id': 's', 'admission_id': row['admission_id']}+ assert await session_cron.operation(authority, 'cancel', params, actor) == {'ok': True}+ policy = SimpleNamespace(request_json=json.dumps({+ 'extra_prompt': None, 'request_id': 'cron:job:fire', 'cron_job': {'id': 'job'}}))+ with pytest.raises(RuntimeError):+ await session_cron.execute(authority, ref, row, policy)+ assert seen == {'cancelled_at_start': True}+ assert authority._cron_cancellations == {}