fix(gateway): owner cron execution binds the scheduler's cron identity and execution id

Main's run_one_job binds ctx.current_cron_execution() (enter_cron_execution) in
the firing thread once it wins claimed->running. Agent cron now executes inside
the profile owner: run_canonical_job hands the fire to the owner's loop and
session_cron.execute runs run_job on a to_thread worker copied from THAT loop's
context, which never saw the binding. Plugins' pre_tool_call hooks in an owned
cron run read None. execute also passed the admission id as run_job's
execution_id, so the per-run task id (cron:<job>:<id>) and the owner execution
tuple carried an id the cron/executions ledger has never heard of.

execute now derives the scheduler execution id from the admission's request id
(_create admits under cron:<job>:<request_id>, and the ticker's request_id IS
the executions row id), and _run_identified re-binds enter_cron_execution(job,
id, get_execution(id)) around run_job in the worker thread — inside the profile
scope, so the row and profile name are this profile's — and resets it in finally.

Test: test_session_cron.py::
test_owner_execution_binds_the_scheduler_cron_identity_inside_run_job
  red on r6-base: AssertionError: assert '<admission id>' == '<execution id>'
  (identity None as well); green after.
Adjacent: 10 files (session_cron, canonical_cron, cron_execution_identity, workdir,
provider_pin, mcp_toolset, pinned_fallback, codex paths, memory_contract,
config_guard_surfaces): 63 passed, 0 failed.

Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5462648005
This commit is contained in:
Teknium
2026-10-08 15:58:15 -07:00
parent 51d50e18e9
commit df12cce832
2 changed files with 75 additions and 4 deletions

View File

@@ -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_job
from 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}

View File

@@ -85,3 +85,51 @@ async def test_cron_cancel_between_claim_and_execution_registration_stops_the_jo
await session_cron.execute(authority, ref, row, policy)
assert seen == {'cancelled_at_start': True}
assert authority._cron_cancellations == {}
@pytest.mark.asyncio
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