Skip to content

The agent that grows with you

perf(gateway): A2A forward and hosted-room member creation commit off the owner loop

Tekniuma369bcfeb62f
diff --git a/gateway/session_a2a.py b/gateway/session_a2a.py
index 26a6a9bdd55..e4cad8b11e8 100644
--- a/gateway/session_a2a.py
+++ b/gateway/session_a2a.py
@@ -2,6 +2,7 @@
import asyncio
from contextvars import ContextVar
from dataclasses import asdict, replace
+from functools import partial
import hashlib
import json
import logging
@@ -83,8 +84,9 @@ async def forward(connection, params):
identity = [params[k] for k in ('agent', 'tenant', 'peer', 'context_id')]
key = 'a2a:' + hashlib.sha256(json.dumps(identity, separators=(',', ':')).encode()).hexdigest()
from gateway.session_local_recovery import local_identity, restore_local_session
- from gateway.session_local import create_local_session
- from hermes_state_local import local_receipt
+ from gateway.session_local import stage_local_session
+ from gateway.session_runtime_workers import tracked_write
+ from hermes_state_local import commit_local_session, local_receipt
sid = local_identity(authority.profile_id, actor.subject, key)
authority._require_admission_open()
if authority.db.get_session(sid) is not None:
@@ -106,9 +108,12 @@ async def forward(connection, params):
'forwarding into a new session instead of adopting it', legacy['id'], title)
token = _forward_identity.set(identity)
try:
- ref = create_local_session(authority, actor, {'source': 'a2a', 'request_id': key})
+ ref = stage_local_session(authority, actor, {'source': 'a2a', 'request_id': key})
finally:
_forward_identity.reset(token)
+ if isinstance(ref, dict): # the creation commit runs off the owner loop (N90); a duplicate converges
+ await tracked_write(authority, partial(commit_local_session, authority.db, epoch=authority.epoch, receipt=ref))
+ ref = restore_local_session(authority, ref['session_id'])
if ref.session_id not in connection.subscriptions:
await connection.resume(ref, {})
receipt = await authority.submit(actor, Submission(params['input_id'], ref, {'text': params['text']}, 'queue'))
diff --git a/gateway/session_hosted_rpc.py b/gateway/session_hosted_rpc.py
index f7e3698bf64..71c55d16147 100644
--- a/gateway/session_hosted_rpc.py
+++ b/gateway/session_hosted_rpc.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import asyncio
from dataclasses import asdict, replace
+from functools import partial
import hashlib
import json
@@ -77,7 +78,10 @@ class HostedRoomAuthorityRPC:
return await self._resume(params)
from gateway.run import _load_gateway_config, _resolve_gateway_model
from gateway.session_policy import build_policy
- from gateway.session_local import create_local_session
+ from gateway.session_local import stage_local_session
+ from gateway.session_local_recovery import restore_local_session
+ from gateway.session_runtime_workers import tracked_write
+ from hermes_state_local import commit_local_session
from agent.skill_utils import parse_config_string_list
private = {}
config = _load_gateway_config()
@@ -91,14 +95,19 @@ class HostedRoomAuthorityRPC:
policy = replace(policy, source='bot_room', platform='bot_room',
model=policy.model or _resolve_gateway_model(policy.config()),
toolsets=tuple(sorted(set(policy.toolsets) | {'bot_room'})))
- create_local_session(self.authority, self.principal, {'request_id': self.creation_id},
- trusted_policy=policy, trusted_secrets=private)
+ staged = stage_local_session(self.authority, self.principal, {'request_id': self.creation_id},
+ trusted_policy=policy, trusted_secrets=private)
+ # Creation commit and label run off the owner loop (N90); a concurrent duplicate converges.
+ if isinstance(staged, dict):
+ await tracked_write(self.authority, partial(
+ commit_local_session, self.authority.db, epoch=self.authority.epoch, receipt=staged))
+ restore_local_session(self.authority, staged['session_id'])
from hermes_state_runtime import _epoch
def label(conn):
_epoch(conn, self.authority.epoch)
conn.execute('UPDATE sessions SET title=?, hidden=1 WHERE id=?',
(f'Group: {self.room_id}', self.ref.session_id))
- self.authority.db._execute_write(label)
+ await tracked_write(self.authority, partial(self.authority.db._execute_write, label))
return await self._resume(params)
async def _resume(self, params):
diff --git a/tests/gateway/test_owner_loop_writes_a2a_hosted_create.py b/tests/gateway/test_owner_loop_writes_a2a_hosted_create.py
new file mode 100644
index 00000000000..6c03f0c0afe
--- /dev/null
+++ b/tests/gateway/test_owner_loop_writes_a2a_hosted_create.py
@@ -0,0 +1,99 @@
+"""A2A forward and hosted-room member creation commit their session off the owner loop (N90 siblings):
+a held SQLite writer must not stall every session, Stop and socket while either creates."""
+import asyncio
+import sqlite3
+import threading
+import time
+from types import SimpleNamespace
+
+import pytest
+
+
+def _hold(db_path):
+ held, release = threading.Event(), threading.Event()
+
+ def hold_writer(): # another process's writer
+ other = sqlite3.connect(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 held.wait(5)
+ return release
+
+
+async def _max_gap_while(create, release):
+ 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())
+ await asyncio.sleep(0)
+ task = asyncio.ensure_future(create())
+ try:
+ await asyncio.sleep(1.0) # health: allow HX013 -- the writer hold IS the stall window the ticker measures
+ release.set()
+ result = await asyncio.wait_for(task, 30)
+ finally:
+ release.set()
+ tick.cancel()
+ return max(gaps), result
+
+
+async def test_a2a_forward_creation_commits_off_the_owner_loop(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_controls import AuthorityConnection
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {'default': 'fixture'}, 'platform_toolsets': {'cli': []}})
+ monkeypatch.setattr(run, '_resolve_gateway_model', lambda config: 'fixture')
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = run.GatewayRunner.__new__(run.GatewayRunner)
+ runner.adapters, runner.session_store, runner._session_db, runner._draining = {}, store, store._db, False
+ authority = await initialize_session_authority(runner, profile_id='target', instance_id='test')
+ authority._schedule = lambda ref: None
+ conn = AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None), {'user_id': 'producer'})
+ params = dict(agent='dev', tenant='team', peer='alice', context_id='ctx', text='hello')
+ warm = await conn.dispatch({'id': 0, 'method': 'a2a.forward', 'params': dict(params, context_id='warm', input_id='w')})
+ assert 'result' in warm, warm # cold imports are not the write under test
+ release = await asyncio.to_thread(_hold, authority.db.db_path)
+ gap, response = await _max_gap_while(
+ lambda: conn.dispatch({'id': 1, 'method': 'a2a.forward', 'params': dict(params, input_id='first')}), release)
+ try:
+ assert 'result' in response, response
+ assert gap < 0.5, f'the owner loop stalled {gap:.2f}s behind a held writer'
+ finally:
+ await conn.close()
+ authority.db.close()
+
+
+def test_hosted_member_creation_commits_off_the_owner_loop(hosted_owner):
+ from gateway.session_hosted_rpc import HostedRoomAuthorityRPC
+
+ authority, loop, principal, _ = hosted_owner
+
+ def rpc(room):
+ return HostedRoomAuthorityRPC(authority, loop, room_id=room, member_id='one', profile='default',
+ principal=principal, authorize=lambda *a: True)
+ coords = {'profile': 'default', 'source': 'bot_room'}
+ rpc('warm').create(**coords, title='Group: warm') # cold imports are not the write under test
+ member = rpc('room')
+ release = _hold(authority.db.db_path)
+
+ async def probe():
+ return await _max_gap_while(lambda: member._dispatch('create', dict(coords, title='Group: room')), release)
+ gap, created = asyncio.run_coroutine_threadsafe(probe(), loop).result(40)
+ assert created['session_id'] == member.ref.session_id
+ assert authority.db.get_session(member.ref.session_id)['title'] == 'Group: room'
+ assert gap < 0.5, f'the owner loop stalled {gap:.2f}s behind a held writer'