Mechanism: two synchronous SQLite writes still ran on the owner's event loop. session.create (AuthorityConnection.create) called create_local_session inline, whose commit_local_session takes the writer lock; and the API drain's prepare_api_execution upserted the session's `gateway.api.settings.v1.<sid>` row with db._execute_write before _handle_message. A writer held by another process (up to _WRITE_PATIENCE_S) froze every session, timer, socket, Stop and approval the shared owner serves. Fix: create_local_session is split at the commit: stage_local_session does the validation, policy build and replay lookup and returns either the existing ref or the receipt; the RPC commits that receipt through tracked_write (worker thread, tracked for retirement) and restores on the loop. Synchronous callers (a2a, kanban, bot, hosted RPC) keep create_local_session = stage + commit + restore. A titled `--create-if-missing` now awaits between lookup and creation, so resolve -> create -> title holds a per-authority asyncio.Lock to keep concurrent callers converging. The API settings row is written inside the admission's own off-loop transaction (the _authorize_write guard, next to the one-target check), so it commits with the admitted turn and the drain only reads it. Test: tests/gateway/test_owner_loop_writes_create_api.py records the thread of each named state_meta write while driving the real session.create RPC and a real admitted+drained API turn. Red on r12-integ1 (both writes ran on the owner-loop thread). Review: dokterdok N50 Review: dokterdok class-2 (cherry picked from commit 2e49a979902cb740261dc6e3df939ebc70874845)
84 lines
3.3 KiB
Python
84 lines
3.3 KiB
Python
"""N50: session.create's creation commit and an API turn's settings write run off the owner loop.
|
|
|
|
Same class as test_owner_loop_writes_class.py: each row drives the real verb end to end and
|
|
records the thread every named SQLite write ran on; on the owner-loop thread a contended writer
|
|
lock (up to _WRITE_PATIENCE_S) freezes every session, timer and socket the owner serves.
|
|
"""
|
|
import asyncio
|
|
import threading
|
|
|
|
import pytest
|
|
|
|
from tests.gateway.test_owner_loop_writes_class import _owner
|
|
|
|
|
|
async def _create(authority, owner, tmp_path, api):
|
|
reply = await owner.dispatch({'id': 1, 'method': 'session.create', 'params': {
|
|
'request_id': 'plain', 'source': 'cli', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []}})
|
|
assert 'result' in reply, reply
|
|
|
|
|
|
async def _api_turn(authority, owner, tmp_path, api):
|
|
from gateway.session_api_turn import admit_api_turn_async
|
|
_, ref, row = await admit_api_turn_async(api, session_id='api', user_message='hi', conversation_history=[])
|
|
await authority._drain(ref)
|
|
from hermes_state_runtime import get_session_admission
|
|
assert get_session_admission(authority.db, admission_id=row['admission_id'])['status'] == 'terminal'
|
|
|
|
|
|
def _writes_state_meta(prefix, threads):
|
|
"""Wrap a ``_execute_write`` callback so a statement naming *prefix* records its thread."""
|
|
class Conn:
|
|
def __init__(self, conn):
|
|
self._conn = conn
|
|
|
|
def execute(self, sql, params=()):
|
|
if 'state_meta' in sql and any(isinstance(p, str) and p.startswith(prefix) for p in params):
|
|
threads.append(threading.get_ident())
|
|
return self._conn.execute(sql, params)
|
|
|
|
def __getattr__(self, name):
|
|
return getattr(self._conn, name)
|
|
return Conn
|
|
|
|
|
|
def _record(monkeypatch, prefix):
|
|
from hermes_state import SessionDB
|
|
threads = []
|
|
wrap = _writes_state_meta(prefix, threads)
|
|
real = SessionDB._execute_write
|
|
monkeypatch.setattr(SessionDB, '_execute_write',
|
|
lambda self, fn, *a, **k: real(self, lambda conn: fn(wrap(conn)), *a, **k))
|
|
return threads
|
|
|
|
|
|
async def _handle(event):
|
|
from gateway.session_results import execution_result
|
|
execution_result.get()['result'] = {'final_response': 'ok', 'messages': []}
|
|
return 'ok'
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_session_create_commit_never_runs_on_the_owner_loop_thread(tmp_path, monkeypatch):
|
|
from hermes_state_local import POLICY_PREFIX
|
|
store, authority, owner = _owner(tmp_path, monkeypatch, _handle)
|
|
threads = _record(monkeypatch, POLICY_PREFIX)
|
|
try:
|
|
async with asyncio.timeout(20):
|
|
await _create(authority, owner, tmp_path, None)
|
|
assert threads, 'the creation commit never ran'
|
|
assert threading.get_ident() not in threads, 'the creation commit ran on the owner loop thread'
|
|
finally:
|
|
await owner.close()
|
|
store.close_all_db_handles()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_api_settings_write_never_runs_on_the_owner_loop_thread(api, owner, monkeypatch, tmp_path):
|
|
owner.runner._handle_message = _handle
|
|
threads = _record(monkeypatch, 'gateway.api.settings.v1.')
|
|
async with asyncio.timeout(20):
|
|
await _api_turn(owner, None, tmp_path, api)
|
|
assert threads, 'the API settings write never ran'
|
|
assert threading.get_ident() not in threads, 'the API settings write ran on the owner loop thread'
|