The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(gateway): the Bot Chat a first delivery mints commits off the owner loop
Teknium876a65ec71f2
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 176eff1030f..73961d10c0e 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -4,6 +4,7 @@ The mailbox is a delivery receipt, not an execution queue. A committed canonicaladmission is the only consumer; unknown execution is never retried as inference."""import asyncio+from functools import partialimport loggingfrom pathlib import Path@@ -84,11 +85,12 @@ def _home(authority, actor, profile):return home-def _target(authority, actor):- row = authority.db.get_session_by_title('Bot Chat')- if row is None:- ref = _create_bot_chat(authority, actor)- else:+async def _target(authority, actor):+ ref = None+ if authority.db.get_session_by_title('Bot Chat') is None:+ ref = await _create_bot_chat(authority, actor) # None: a concurrent delivery created it first+ if ref is None:+ row = authority.db.get_session_by_title('Bot Chat')tip = authority.db.get_compression_tip(row['id'])target = authority.db.get_session(tip)if target is None:@@ -103,20 +105,33 @@ def _target(authority, actor):return ref, live, entry-def _create_bot_chat(authority, actor):+async def _create_bot_chat(authority, actor):"""No Bot Chat yet: mint it the way ``hermes chat --in ~ -c "Bot Chat" --create-if-missing``did on the CLI lane this door replaced, so a fresh profile's first delivery has somewhereto land instead of being recorded as failed. Same owner step as ``session.create`` with a- title: no await between the lookup and the titled creation. Creation is the actor's own- capability; a submit-only principal (owner recovery) still gets ``not_found``."""+ title: lookup, creation and title run under the authority's titled-create lock, with the+ commits off the owner loop (N90). Creation is the actor's own capability; a submit-only+ principal (owner recovery) still gets ``not_found``."""if 'session:create' not in actor.capabilities:raise RuntimeStoreError('not_found')- from gateway.session_local import create_local_session+ from gateway.session_local import stage_local_session+ from gateway.session_local_recovery import restore_local_sessionfrom gateway.session_local_title import title_new_session- ref = create_local_session(authority, actor, {- 'request_id': _bot_chat_creation_id(authority, actor), 'source': 'cli', 'cwd': str(Path.home())})- title_new_session(authority, ref, 'Bot Chat')- return ref+ from gateway.session_runtime_workers import tracked_write+ from hermes_state_local import commit_local_session+ lock = getattr(authority, '_titled_create_lock', None)+ if lock is None:+ lock = authority._titled_create_lock = asyncio.Lock()+ async with lock:+ if authority.db.get_session_by_title('Bot Chat') is not None:+ return None+ ref = stage_local_session(authority, actor, {+ 'request_id': _bot_chat_creation_id(authority, actor), 'source': 'cli', 'cwd': str(Path.home())})+ if isinstance(ref, dict):+ await tracked_write(authority, partial(commit_local_session, authority.db, epoch=authority.epoch, receipt=ref))+ ref = restore_local_session(authority, ref['session_id'])+ await tracked_write(authority, partial(title_new_session, authority, ref, 'Bot Chat'))+ return refdef _bot_chat_creation_id(authority, actor):@@ -124,7 +139,7 @@ def _bot_chat_creation_id(authority, actor):``bot-chat:<profile>`` id; a generation is spent once its session was deleted (retired: a retrymust never resurrect it) or renamed (titled, but not "Bot Chat" — or the lookup had found it),and a replacement takes the next one. Derived from durable rows only, so a restart and two- concurrent deliveries (this runs on the owner loop with no await) pick the same identity. An+ concurrent deliveries (serialized by the titled-create lock) pick the same identity. Anexisting UNtitled session is the same creation interrupted before its title: it is reused."""from gateway.session_local_recovery import local_identityfrom hermes_state_mutation_retirement import retired_session@@ -275,7 +290,7 @@ async def _maybe_retry(authority, home, path, record):'bot-delivery-retry')try:authority._require_admission_open()- ref, live, entry = _target(authority, actor)+ ref, live, entry = await _target(authority, actor)if ref.session_id != record['session_id']:raise RuntimeStoreError('admission_conflict')if authority.db.latest_conversation_role(entry.session_id) == 'user':@@ -380,7 +395,7 @@ async def _migrate(authority, actor, home, root):and record['status'] in {'queued', 'claimed'}]if not legacy:return- ref, live, entry = _target(authority, actor)+ ref, live, entry = await _target(authority, actor)for path, record in sorted(legacy, key=lambda item: (item[1].get('sequence', item[1]['created_at']), item[0].name)):owner = record['owner']if owner['profile_home'] != str(home):@@ -502,7 +517,7 @@ async def _deliver(connection, params):return await _publish_result(authority, home, record)if record is not None:raise RuntimeStoreError('unknown_execution')- ref, live, entry = _target(authority, actor)+ ref, live, entry = await _target(authority, actor)if params.get('session_id', entry.session_id) != entry.session_id:raise RuntimeStoreError('admission_conflict')return await _admit(authority, actor, home, root, key, message, ref, live, entry, author=author,diff --git a/tests/gateway/test_bot_receipt_corruption.py b/tests/gateway/test_bot_receipt_corruption.pyindex 940df20ed62..02a94110748 100644--- a/tests/gateway/test_bot_receipt_corruption.py+++ b/tests/gateway/test_bot_receipt_corruption.py@@ -145,10 +145,9 @@ async def test_legacy_migration_skips_structurally_corrupt_neighbor(monkeypatch,ref = SimpleNamespace(session_id="tip")live = object()entry = SimpleNamespace(session_id="tip")- monkeypatch.setattr(- "gateway.session_bot._target",- lambda authority, actor: (ref, live, entry),- )+ async def target(authority, actor):+ return ref, live, entry+ monkeypatch.setattr("gateway.session_bot._target", target)@contextmanagerdef inactive_session(*args, **kwargs):diff --git a/tests/gateway/test_legacy_session_migration.py b/tests/gateway/test_legacy_session_migration.pyindex 0a210d714b7..9b1fc773d3c 100644--- a/tests/gateway/test_legacy_session_migration.py+++ b/tests/gateway/test_legacy_session_migration.py@@ -125,7 +125,7 @@ async def test_legacy_adoption_refuses_live_owner_and_foreign_profile_without_wrreset_local_target(db, epoch=authority.epoch, parent_session_id=ref.session_id, entry=entry)from gateway.session_bot import _targetsubmitter = Principal(native.subject, native.profile_id, native.capabilities | {'session:submit'}, native.transport_id)- assert _target(authority, submitter)[2].session_id == 'reset-tip'+ assert (await _target(authority, submitter))[2].session_id == 'reset-tip'@pytest.mark.asynciodiff --git a/tests/gateway/test_owner_loop_writes_bot_chat_create.py b/tests/gateway/test_owner_loop_writes_bot_chat_create.pynew file mode 100644index 00000000000..2b0d3156139--- /dev/null+++ b/tests/gateway/test_owner_loop_writes_bot_chat_create.py@@ -0,0 +1,56 @@+"""The Bot Chat a first delivery mints commits off the owner loop (N90): a held SQLite writer must+not stall every session, Stop and socket the owner serves while the profile's Bot Chat is created;+concurrent first deliveries and a titled ``session.create`` still converge on one Bot Chat."""+import asyncio+import sqlite3+import threading+import time++import pytest++from tests.gateway.test_session_bot_target_lifecycle import bot # noqa: F401 (fixture)+++async def _resolve(bot):+ from gateway.session_bot import _target+ return (await _target(bot.authority, bot.owner))[0].session_id+++async def test_bot_chat_creation_commits_off_the_owner_loop(bot): # noqa: F811+ db = bot.authority.db+ 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())+ await asyncio.sleep(0)+ first = asyncio.ensure_future(_resolve(bot))+ second = asyncio.ensure_future(_resolve(bot))+ try:+ await asyncio.sleep(1.0) # health: allow HX013 -- the writer hold IS the stall window the ticker measures+ release.set()+ ids = await asyncio.wait_for(asyncio.gather(first, second), 30)+ finally:+ release.set()+ tick.cancel()+ assert max(gaps) < 0.5, f'the owner loop stalled {max(gaps):.2f}s behind a held writer'+ assert ids[0] == ids[1] and db.get_session(ids[0])['title'] == 'Bot Chat'+ with db._read_ctx() as c:+ assert c.execute("SELECT COUNT(*) FROM sessions WHERE title='Bot Chat'").fetchone()[0] == 1diff --git a/tests/gateway/test_session_bot_target_lifecycle.py b/tests/gateway/test_session_bot_target_lifecycle.pyindex 5b4606dadde..8d5ae5fb0c8 100644--- a/tests/gateway/test_session_bot_target_lifecycle.py+++ b/tests/gateway/test_session_bot_target_lifecycle.py@@ -37,28 +37,28 @@ async def bot(tmp_path, monkeypatch):store._db.close()-def _target_id(bot):+async def _target_id(bot):from gateway.session_bot import _target- ref, _live, _entry = _target(bot.authority, bot.owner)+ ref, _live, _entry = await _target(bot.authority, bot.owner)return ref.session_id@pytest.mark.asyncioasync def test_renamed_or_deleted_bot_chat_gets_a_fresh_replacement(bot):db = bot.authority.db- first = _target_id(bot)- assert _target_id(bot) == first # converges: resolved by title, never re-created+ first = await _target_id(bot)+ assert await _target_id(bot) == first # converges: resolved by title, never re-createddb.set_session_title(first, 'Planning notes')- second = _target_id(bot)+ second = await _target_id(bot)assert second != firstassert db.get_session(first)['title'] == 'Planning notes' # the rename standsassert db.get_session(second)['title'] == 'Bot Chat'assert db.delete_session(second, sessions_dir=bot.home / 'sessions')bot.authority.sessions.pop(second, None)- third = _target_id(bot)+ third = await _target_id(bot)assert third not in (first, second) # a replacement, not the retired idassert db.get_session(second) is Noneassert db.get_session(third)['title'] == 'Bot Chat'- assert _target_id(bot) == third+ assert await _target_id(bot) == third