Skip to content

The agent that grows with you

fix(gateway): session.create and an API turn's settings commit off the owner loop

Tekniumf9028147749a
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index 22e90385632..3ea5cb831c8 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -11,7 +11,7 @@ import uuid
from gateway.config import Platform
from gateway.session_api import bind_api_steps, restore_api_session, run_steps, run_steps_off_loop
from gateway.session_results import admission_result
-from hermes_state_runtime import RuntimeStoreError, admit_session_input, _epoch, _json
+from hermes_state_runtime import RuntimeStoreError, admit_session_input, _json
api_execution: ContextVar[dict | None] = ContextVar('api_execution', default=None)
_SETTINGS_PREFIX = 'gateway.api.settings.v1.'
@@ -243,10 +243,19 @@ def _admit_api_payload(authority, adapter, sid, request_id, payload, settings, d
check_api_turn(authority, ref, payload)
row = yield partial(admit_session_input, authority.db, epoch=authority.epoch, principal_id='api',
session_id=sid, request_id=request_id, payload=payload,
- _authorize_write=authority._admission_gate(partial(_one_target, sid, request_id)))
+ _authorize_write=authority._admission_gate(partial(_admit_target, sid, request_id, payload['api_turn_v1']['settings'])))
return authority, ref, row
+def _admit_target(session_id, request_id, settings, conn):
+ """Inside the admission's own off-loop transaction: one target per request id, and the
+ session's settings for its later payload-less (internal) turns, committed with the admitted
+ turn rather than by the drain on the owner loop (N50)."""
+ _one_target(session_id, request_id, conn)
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',
+ (_SETTINGS_PREFIX + session_id, _json(settings)))
+
+
def _one_target(session_id, request_id, conn):
"""One API request id (an Idempotency-Key) names one admission. The ledger keys identity by
target too, so the same key aimed at another session would otherwise run the work again."""
@@ -423,13 +432,6 @@ def prepare_api_execution(authority, ref, payload):
adapter = check_api_turn(authority, ref, payload)
data = payload.get('api_turn_v1')
settings = data['settings'] if data else api_settings(authority, ref)
- if data:
- def write(conn):
- _epoch(conn, authority.epoch)
- conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) '
- 'ON CONFLICT(key) DO UPDATE SET value=excluded.value',
- (_SETTINGS_PREFIX + ref.session_id, _json(settings)))
- authority.db._execute_write(write)
content = payload['text']
if data and isinstance(content, list):
from gateway.session_api_media import restore_api_images
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 5cca84a4c8e..27896596a46 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -1,6 +1,7 @@
"""Authenticated WS projection of the gateway authority; no TUI execution fallback."""
import asyncio
from dataclasses import asdict
+from functools import partial
from pathlib import Path
import sqlite3
import uuid
@@ -244,11 +245,24 @@ class AuthorityConnection:
return await readiness(self.authority, self.actor, params, runtime=True)
async def create(self, ref, params):
- from gateway.session_local import create_local_session
- from gateway.session_local_title import resolve_titled_session, title_new_session, validate_title
- # ``-c <title> --create-if-missing``: resolve-or-create is one owner step (no await
- # between lookup and creation), so concurrent programmatic callers converge.
+ from gateway.session_local_title import validate_title
title = validate_title(params.pop('title')) if 'title' in params else None
+ if title is None:
+ return await self._create(params, None)
+ # ``-c <title> --create-if-missing``: resolve -> create -> title is one owner step per
+ # authority (the commits run off the loop), so concurrent programmatic callers converge.
+ lock = getattr(self.authority, '_titled_create_lock', None)
+ if lock is None:
+ lock = self.authority._titled_create_lock = asyncio.Lock()
+ async with lock:
+ return await self._create(params, title)
+
+ async def _create(self, params, title):
+ from gateway.session_local import stage_local_session
+ from gateway.session_local_recovery import restore_local_session
+ from gateway.session_local_title import resolve_titled_session, title_new_session
+ from gateway.session_runtime_workers import tracked_write
+ from hermes_state_local import commit_local_session
# Bot Mode's forever-chat mint: born hidden from the sidebar; `follow_profile_config` is
# the canonical default (a local session's runtime is built from the profile's current
# config on every attach), so the flag is accepted for the legacy contract and implied.
@@ -268,7 +282,14 @@ class AuthorityConnection:
sid = local_identity(self.authority.profile_id, self.actor.subject, params['request_id'])
if self.authority.db.get_session(sid) is None:
skills_prompt = await asyncio.to_thread(render_launch_skills, params, sid)
- ref = create_local_session(self.authority, self.actor, params, skills_prompt=skills_prompt)
+ ref = stage_local_session(self.authority, self.actor, params, skills_prompt=skills_prompt)
+ if isinstance(ref, dict):
+ # The creation commit runs off the owner loop: a held writer must not freeze
+ # every session behind one new chat (N50).
+ receipt = ref
+ await tracked_write(self.authority, partial(
+ commit_local_session, self.authority.db, epoch=self.authority.epoch, receipt=receipt))
+ ref = restore_local_session(self.authority, receipt['session_id'])
if params.get('accept_hooks') is True:
from gateway.session_policy import accept_launch_hooks, restore_policy
from hermes_state_local import local_receipt
diff --git a/gateway/session_local.py b/gateway/session_local.py
index 16a0d3f5e49..f14db919dea 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -145,6 +145,20 @@ def _bypass_policy(params, *, private_secrets):
def create_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None):
+ """Stage, commit and publish a local session inline (synchronous callers)."""
+ from gateway.session_local_recovery import restore_local_session
+ from hermes_state_local import commit_local_session
+ staged = stage_local_session(authority, actor, params, trusted_policy=trusted_policy,
+ trusted_secrets=trusted_secrets, skills_prompt=skills_prompt)
+ if isinstance(staged, dict):
+ commit_local_session(authority.db, epoch=authority.epoch, receipt=staged)
+ staged = restore_local_session(authority, staged['session_id'])
+ return staged
+
+
+def stage_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None):
+ """Everything before the creation commit: the existing session's ref on an exact retry, else the
+ receipt ``commit_local_session`` writes (the async RPC commits it off the owner loop)."""
if actor.profile_id != authority.profile_id:
raise RuntimeStoreError('profile_mismatch')
if 'session:create' not in actor.capabilities:
@@ -171,7 +185,6 @@ def create_local_session(authority, actor, params, *, trusted_policy=None, trust
from gateway.session import SessionEntry
from gateway.session_lifecycle import _now
from gateway.session_local_recovery import local_identity, restore_local_session
- from hermes_state_local import commit_local_session
authority._require_admission_open()
sid = local_identity(authority.profile_id, actor.subject, request_id)
from gateway.session_policy import bind_launch_key, restore_policy, launch_key
@@ -201,10 +214,8 @@ def create_local_session(authority, actor, params, *, trusted_policy=None, trust
# naive cutoff, and one aware entry aborts the whole iteration.
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)
+ 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)}
def publish_local_policy(authority, session_id):
diff --git a/tests/gateway/test_owner_loop_writes_create_api.py b/tests/gateway/test_owner_loop_writes_create_api.py
new file mode 100644
index 00000000000..139a539229b
--- /dev/null
+++ b/tests/gateway/test_owner_loop_writes_create_api.py
@@ -0,0 +1,83 @@
+"""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'
+
+
+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()
+
+
+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'