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

Mechanism: operation('submit') runs on the owner loop (the in-process
firer uses run_coroutine_threadsafe onto it, so does the cron.submit RPC).
For a new fire, session_cron._create called commit_local_session
synchronously; only the later admission went through tracked_write. While
another connection held the SQLite writer (up to _WRITE_PATIENCE_S) every
session, Stop, approval and socket on the owner stalled.

Fix: extend f9028147749's split to cron. _create stays in owner_scope for
the job/config reads and returns the staged creation receipt (or the
existing ref on an exact retry); operation('submit') commits it with
tracked_write(commit_local_session) (retirement joins it), restores on the
loop, then admits as before. Exact retry, commit-before-ACK and recover
after a lost submit are unchanged.

Red on r13-base2: tests/gateway/test_owner_loop_writes_cron_create.py (a
held writer freezes the owner loop for the full hold; green: max tick gap
< 0.5 s).

Review: dokterdok N90
This commit is contained in:
Teknium
2026-10-11 18:36:17 -07:00
parent 2cc784937d
commit a84cedb53b
2 changed files with 79 additions and 5 deletions

View File

@@ -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 ''},

View File

@@ -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()