Skip to content

The agent that grows with you

fix(cron): commit a fire's session creation off the owner loop

Tekniuma84cedb53bd2
diff --git a/gateway/session_cron.py b/gateway/session_cron.py
index 62e4b116e85..3c6440d51e1 100644
--- a/gateway/session_cron.py
+++ b/gateway/session_cron.py
@@ -60,7 +60,6 @@ def _create(authority, actor, params):
from gateway.session_policy import build_policy, bind_launch_key
from gateway.run import _load_gateway_config
from cron.scheduler import _load_cron_job_config
- from hermes_state_local import commit_local_session
from gateway.config import Platform
from gateway.session import SessionSource, SessionEntry
from gateway.session_lifecycle import _now
@@ -92,10 +91,9 @@ def _create(authority, actor, params):
route = authority.runner.session_store._generate_session_key(source)
now = _now()
entry = SessionEntry(route, sid, now, now, origin=source, platform=Platform.LOCAL)
- commit_local_session(authority.db, epoch=authority.epoch, receipt={
- 'profile_id': authority.profile_id, 'principal_id': actor.subject, 'request_id': request_id,
- 'session_id': sid, 'route': route, 'entry': entry.to_dict(), 'policy': asdict(policy)})
- return restore_local_session(authority, sid), request_id
+ # The staged creation receipt: ``operation('submit')`` commits it off the owner loop.
+ return {'profile_id': authority.profile_id, 'principal_id': actor.subject, 'request_id': request_id,
+ 'session_id': sid, 'route': route, 'entry': entry.to_dict(), 'policy': asdict(policy)}, request_id
# Run-side verdicts run_job stamps on the job dict for the firing scheduler's bookkeeping tail
@@ -145,6 +143,12 @@ async def operation(authority, name, params, actor=None):
ref, request_id = _create(authority, actor, params)
from functools import partial
from gateway.session_runtime_workers import tracked_write
+ if isinstance(ref, dict):
+ # The creation commit waits on the writer off the owner loop, like session.create (N50).
+ from gateway.session_local_recovery import restore_local_session
+ from hermes_state_local import commit_local_session
+ await tracked_write(authority, partial(commit_local_session, authority.db, epoch=authority.epoch, receipt=ref))
+ ref = restore_local_session(authority, ref['session_id'])
receipt = await tracked_write(authority, partial(
admit_session_input, authority.db, epoch=authority.epoch, principal_id=actor.subject,
session_id=ref.session_id, request_id=request_id, payload={'text': params['extra_prompt'] or ''},
diff --git a/tests/gateway/test_owner_loop_writes_cron_create.py b/tests/gateway/test_owner_loop_writes_cron_create.py
new file mode 100644
index 00000000000..e87c05a2411
--- /dev/null
+++ b/tests/gateway/test_owner_loop_writes_cron_create.py
@@ -0,0 +1,70 @@
+"""Cron fire creation commits its session off the owner loop: a held SQLite writer must not stall
+every session, Stop and socket the owner serves while ``cron.submit`` creates the fire's session."""
+import asyncio
+import sqlite3
+import threading
+import time
+from types import SimpleNamespace
+
+from cron import jobs
+from gateway import run, session_cron
+from gateway.config import GatewayConfig
+from gateway.session import SessionStore
+from gateway.session_authority import SessionAuthority
+from hermes_state import SessionDB
+from hermes_state_runtime import begin_runtime_epoch, list_session_admissions
+
+
+def test_cron_submit_creation_commit_waits_off_the_owner_loop(tmp_path, monkeypatch):
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {}, 'platform_toolsets': {'cli': []}})
+ with jobs.use_cron_store(tmp_path / 'cron'):
+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local', model='fixture')
+ 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'))
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ runner.session_authority = authority
+
+ async def probe():
+ # Warm the creation path (cold imports are not the write under test).
+ await session_cron.operation(authority, 'submit', {'job_id': job['id'], 'request_id': 'warm',
+ 'extra_prompt': None})
+ held, release = threading.Event(), threading.Event()
+
+ def hold_writer(): # another process's writer
+ other = sqlite3.connect(db.db_path, timeout=10)
+ other.execute('BEGIN IMMEDIATE')
+ held.set()
+ release.wait(5)
+ other.rollback()
+ other.close()
+ threading.Thread(target=hold_writer, daemon=True).start()
+ assert await asyncio.to_thread(held.wait, 5)
+ gaps = []
+
+ async def ticker():
+ last = time.monotonic()
+ while True:
+ await asyncio.sleep(0.02) # health: allow HX013 -- the ticker's period is the owner-loop stall measurement
+ now = time.monotonic()
+ gaps.append(now - last)
+ last = now
+ tick = asyncio.create_task(ticker())
+ submit = asyncio.create_task(session_cron.operation(
+ authority, 'submit', {'job_id': job['id'], 'request_id': 'fire', 'extra_prompt': None}))
+ try:
+ await asyncio.sleep(1.0) # health: allow HX013 -- the writer hold IS the stall window the ticker measures
+ release.set()
+ receipt = await asyncio.wait_for(submit, 30)
+ finally:
+ release.set()
+ tick.cancel()
+ assert len(list_session_admissions(db, session_id=receipt['session_id'], pending_only=False)) == 1
+ assert max(gaps) < 0.5, max(gaps)
+ try:
+ asyncio.run(probe())
+ finally:
+ db.close()