The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): owner cron execution binds the scheduler's cron identity and execution id
Tekniumdf12cce832c3
diff --git a/gateway/session_cron.py b/gateway/session_cron.pyindex e4efefcd842..eb237510f89 100644--- a/gateway/session_cron.py+++ b/gateway/session_cron.py@@ -179,6 +179,28 @@ async def rpc(connection, name, params):return await operation(connection.authority, name, params, connection.actor)+def scheduler_execution_id(job_id, request_id):+ """The scheduler's execution id this admission carries: ``_create`` admits under+ ``cron:<job>:<request_id>`` and the ticker's ``request_id`` IS its ``cron/executions`` row id."""+ prefix = 'cron:' + job_id + ':'+ return request_id[len(prefix):] if request_id.startswith(prefix) else request_id+++def _run_identified(run_job, job, execution_id, **kwargs):+ """``run_job`` inside this fire's cron identity (``ctx.current_cron_execution()``).++ The scheduler binds it in the FIRING thread, but the owner executes on its own loop, whose+ context never saw that binding; re-bind it here from the same ledger row, in the profile scope+ the caller entered (so the row and the profile name are this profile's)."""+ from cron.execution_identity import enter_cron_execution, exit_cron_execution+ from cron.executions import get_execution+ token = enter_cron_execution(job, execution_id, get_execution(execution_id) or {})+ try:+ return run_job(job, execution_id=execution_id, **kwargs)+ finally:+ exit_cron_execution(token)++async def execute(authority, ref, row, policy):from cron.scheduler import run_jobfrom gateway.run import _profile_runtime_scope@@ -189,13 +211,14 @@ async def execute(authority, ref, row, policy):raise RuntimeStoreError('admission_conflict')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']))+ job = data['cron_job']+ execution_id = scheduler_execution_id(job['id'], row['request_id'])+ token = _execution.set((authority, ref.session_id, job['id'], execution_id))try:- job = data['cron_job']db_path = await asyncio.to_thread(Path(authority.db.db_path).resolve)with _profile_runtime_scope(db_path.parent):- result = await asyncio.to_thread(run_job, job, extra_prompt=data['extra_prompt'],- execution_id=row['admission_id'], cancel_event=cancel)+ result = await asyncio.to_thread(_run_identified, run_job, job, execution_id,+ extra_prompt=data['extra_prompt'], cancel_event=cancel)# run_job stamps run-side verdicts on ITS job copy (quota hold, unreachable model); the# firing scheduler's bookkeeping reads them off its own dict, so they ride the result.flags = {key: job[key] for key in RUN_JOB_FLAGS if key in job}diff --git a/tests/gateway/test_session_cron.py b/tests/gateway/test_session_cron.pyindex db35e333f20..b7b2b2c9eb4 100644--- a/tests/gateway/test_session_cron.py+++ b/tests/gateway/test_session_cron.py@@ -85,3 +85,51 @@ async def test_cron_cancel_between_claim_and_execution_registration_stops_the_joawait session_cron.execute(authority, ref, row, policy)assert seen == {'cancelled_at_start': True}assert authority._cron_cancellations == {}+++async def test_owner_execution_binds_the_scheduler_cron_identity_inside_run_job(tmp_path, monkeypatch):+ """The owner runs the job on its own loop thread, which never saw the firing scheduler's+ ``enter_cron_execution``: ``ctx.current_cron_execution()`` must still name this fire, keyed on+ the scheduler's execution id (the admission's request id), never on the admission id."""+ from contextlib import nullcontext+ import json+ from cron import scheduler+ from cron.execution_identity import current_cron_execution+ from cron.executions import create_execution, mark_execution_running+ from gateway import run, session_cron+ from gateway.session_authority import LiveSession, SessionAuthority+ from gateway.session_contract import 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))+ execution = create_execution('job', source='builtin', scheduled_instant='2026-10-08T09:00:00')+ record = mark_execution_running(execution['id'])+ 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')+ monkeypatch.setattr(run, '_profile_runtime_scope', lambda home: nullcontext())+ seen = {}++ def run_job(job, *, extra_prompt, execution_id, cancel_event):+ seen['execution_id'] = execution_id+ seen['identity'] = current_cron_execution()+ return (True, 'doc', 'answer', None)+ monkeypatch.setattr(scheduler, 'run_job', run_job)+ request_id = 'cron:job:' + execution['id']+ with db:+ admit_session_input(db, epoch=authority.epoch, principal_id='cron-owner', session_id='s',+ request_id=request_id, payload={'text': ''})+ row = claim_session_input(db, epoch=authority.epoch, session_id='s')+ policy = SimpleNamespace(request_json=json.dumps({+ 'extra_prompt': None, 'request_id': request_id, 'cron_job': {'id': 'job', 'name': 'Job'}}))+ assert await session_cron.execute(authority, SessionRef('p', 's'), row, policy) == 'answer'+ ident = seen['identity']+ assert seen['execution_id'] == execution['id'] != row['admission_id']+ assert ident is not None and (ident.job_id, ident.job_name, ident.execution_id) == ('job', 'Job', execution['id'])+ assert (ident.source, ident.scheduled_instant, ident.started_at) == (+ 'builtin', record['scheduled_instant'], record['started_at'])+ assert current_cron_execution() is None