The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(rooms): bind room owner claim to the room insert transaction
Teknium932952d9d33d
diff --git a/gateway/hosted_rooms.py b/gateway/hosted_rooms.pyindex 5b181eb7dc6..34f3abe4b22 100644--- a/gateway/hosted_rooms.py+++ b/gateway/hosted_rooms.py@@ -14,7 +14,7 @@ import sqlite3from contextlib import closingfrom functools import partialfrom pathlib import Path-from typing import Any, Mapping+from typing import Any, Callable, Mappingfrom gateway.hosted_rooms_common import (DbPath, bounded_int, canonical_json, clock as _now, compact_json, connect, fenced_update as _fenced_update,@@ -863,15 +863,21 @@ def _adopt_legacy_room(def create_room(- db_path: DbPath, *, room_id: Any, name: Any, members: Any, authority_gateway_id: Any, now: float | None = None+ db_path: DbPath, *, room_id: Any, name: Any, members: Any, authority_gateway_id: Any, now: float | None = None,+ admit: Callable[[sqlite3.Connection], Any] | None = None,) -> dict[str, Any]:- """Create a room, or return the identical existing room idempotently."""+ """Create a room, or return the identical existing room idempotently.++ ``admit(conn)`` runs first inside the write transaction (after payload validation), so a+ caller's side effect such as an owner claim commits only together with this create."""room_id = _room_id(room_id)name = _validate_room_name(name)normalized_members, members_json = _validate_members(members)authority_gateway_id = _actor_id(authority_gateway_id, "authority_gateway_id")now = _now(now)with _transaction(db_path, immediate=True) as conn:+ if admit is not None:+ admit(conn)if _is_retired(conn, room_id):raise RoomConflictError("room_id belongs to a disbanded room")existing = conn.execute(_SELECT_ROOM_WITH_BYTES, (room_id,)).fetchone()diff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.pyindex 2bd347e7adf..7acf4413327 100644--- a/gateway/session_group_controls.py+++ b/gateway/session_group_controls.py@@ -93,10 +93,17 @@ def _group(authority, actor, home, method, params):service = Noneexecution_methods = {'groups.send', 'groups.stop', 'groups.retry', 'groups.discard', 'groups.approve'}+ admit = Noneif getattr(authority, 'hosted_room_service', None) is not None and 'room_id' in params:if room_authorizer is None:raise RuntimeStoreError('permission_denied')- room_authorizer(actor.subject, params['room_id'], create=method == 'groups.create')+ if method == 'groups.create':+ # Claim ownership inside the room insert's transaction: a create rejected by+ # validation or storage must not leave an owner-only reservation behind.+ def admit(conn):+ room_authorizer(actor.subject, params['room_id'], create=True, conn=conn)+ else:+ room_authorizer(actor.subject, params['room_id'])if method in {'groups.attachment.upload', 'groups.attachment.download'}:if service is None:raise RuntimeStoreError('runtime_coordination_required')@@ -138,7 +145,7 @@ def _group(authority, actor, home, method, params):def create():if service is not None:- return {'room': service.create_room(**params)}+ return {'room': service.create_room(**params, admit=admit)}from gateway.hosted_room_discussion import validate_rosterfrom gateway.session_authorities import served_profile_namename = served_profile_name(home)@@ -150,7 +157,8 @@ def _group(authority, actor, home, method, params):'target': dict(m.target or {}),**({'display_name': m.display_name} if m.display_name else {})} for m in members]return {'room': rooms.create_room(db_path, room_id=params.get('room_id'),- name=params.get('name'), members=normalized, authority_gateway_id=gateway_id)}+ name=params.get('name'), members=normalized, authority_gateway_id=gateway_id,+ admit=admit)}def disband():from gateway.hosted_room_driver import list_tasksdiff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.pyindex e43e0dd1a1b..0f38e3df50e 100644--- a/gateway/session_hosted_service.py+++ b/gateway/session_hosted_service.py@@ -100,7 +100,9 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):def _turn_lock(self, profile):return nullcontext()- def authorize_room(self, actor_subject, room_id, *, create=False):+ def authorize_room(self, actor_subject, room_id, *, create=False, conn=None):+ """Check (or, with ``create``, claim) room ownership. A ``conn`` runs the claim inside+ the caller's room-creation transaction, so owner and room commit or roll back together."""from gateway.hosted_rooms_common import IDENTIFIER_REif (not isinstance(actor_subject, str) or not actor_subjector not isinstance(room_id, str) or len(room_id) > 128@@ -121,7 +123,7 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):if row is None or row[0] != actor_subject:raise RuntimeStoreError('permission_denied')return True- return self.authority.db._execute_write(write)+ return write(conn) if conn is not None else self.authority.db._execute_write(write)def _owner(self, room_id):with self.authority.db._read_ctx() as conn:diff --git a/tests/gateway/test_session_group_execution_controls.py b/tests/gateway/test_session_group_execution_controls.pyindex 8d3a8cee50d..f1467d89b82 100644--- a/tests/gateway/test_session_group_execution_controls.py+++ b/tests/gateway/test_session_group_execution_controls.py@@ -14,15 +14,15 @@ class RoomService:self.calls = []self.runtime = SimpleNamespace(status=lambda: {'running': True, 'stopping': False})- def authorize_room(self, actor_subject, room_id, *, create=False):+ def authorize_room(self, actor_subject, room_id, *, create=False, conn=None):if actor_subject != self.owner or room_id != 'owned':raise RuntimeStoreError('permission_denied')- def create_room(self, *, room_id, name, members):+ def create_room(self, *, room_id, name, members, admit=None):from gateway.hosted_rooms import create_room, local_authority_gateway_idself.calls.append(('create', room_id))return create_room(self.db_path, room_id=room_id, name=name, members=members,- authority_gateway_id=local_authority_gateway_id())+ authority_gateway_id=local_authority_gateway_id(), admit=admit)def status(self, room_id):return {'running': True, 'working': False, 'blocked': True, 'counts': {}, 'peer_routes': [],diff --git a/tests/gateway/test_session_hosted_service.py b/tests/gateway/test_session_hosted_service.pyindex 43d8003cfcc..561893f221b 100644--- a/tests/gateway/test_session_hosted_service.py+++ b/tests/gateway/test_session_hosted_service.py@@ -113,3 +113,61 @@ async def test_service_does_not_plan_or_run_historical_unowned_rooms(tmp_path, m{'member_id': 'one', 'profile': 'default', 'handle': 'one'},{'member_id': 'two', 'profile': 'other', 'handle': 'two'}])assert [b.room_id for b in service.bindings()] == ['owned']+++[email protected]('driver', [False, True])+def test_rejected_create_never_leaves_owner_only_reservation(tmp_path, monkeypatch, driver):+ """Owner and room commit together: no failed create may fence a later valid creator."""+ import sqlite3+ from gateway import hosted_rooms+ from gateway.session_controls import AuthorityConnection+ from gateway.session_hosted_service import CanonicalHostedRoomService+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ (tmp_path / 'profiles' / 'two').mkdir(parents=True)+ (tmp_path / 'config.yaml').write_text(+ 'hosted_rooms:\n profiles:\n two: ' + str((tmp_path / 'profiles' / 'two').resolve()) + '\n')+ members = [{'member_id': 'one', 'profile': 'default', 'handle': 'one'},+ {'member_id': 'two', 'profile': 'two', 'handle': 'two'}]+ with SessionDB(tmp_path / 'state.db') as db:+ authority = SimpleNamespace(db=db, profile_id=str(tmp_path), instance_id='owner', events={},+ epoch=begin_runtime_epoch(db, instance_id='test'))+ service = authority.hosted_room_service = CanonicalHostedRoomService(authority, None)+ if driver:+ monkeypatch.setattr(service.runtime, 'status', lambda: {'running': True, 'stopping': False})+ alice, bob, carol = (AuthorityConnection(authority, object(), {'user_id': u})+ for u in ('alice', 'bob', 'carol'))++ async def create(connection, room_id, **params):+ reply = await connection.dispatch({'id': 1, 'method': 'groups.create',+ 'params': {'room_id': room_id, 'name': 'Room',+ 'members': members, **params}})+ return reply.get('error', {}).get('message') or 'ok'++ def counts():+ with db._read_ctx() as conn:+ return (conn.execute("SELECT COUNT(*) FROM state_meta WHERE key LIKE 'gateway.hosted.owner.v1:%'").fetchone()[0],+ conn.execute('SELECT COUNT(*) FROM hosted_rooms').fetchone()[0])++ async def probe():+ invalid = [{'members': []}, {'name': ''},+ {'members': [members[0], {**members[1], 'target': {'kind': 'local', 'profile': 'one'}}]}]+ for index, params in enumerate(invalid):+ assert await create(alice, f'bad-{index}', **params) == 'invalid_params'+ real_reload = hosted_rooms._reload+ def storage_failure(*args):+ raise sqlite3.OperationalError('disk I/O error')+ monkeypatch.setattr(hosted_rooms, '_reload', storage_failure)+ assert await create(alice, 'bad-3') == 'storage_unavailable'+ monkeypatch.setattr(hosted_rooms, '_reload', real_reload)+ assert counts() == (0, 0)+ # Every rejected ID stays claimable by any actor; an exact retry stays idempotent.+ for index in range(4):+ assert await create(bob, f'bad-{index}') == 'ok'+ assert await create(bob, f'bad-{index}') == 'ok'+ assert await create(alice, f'bad-{index}') == 'permission_denied'+ # First-writer fencing under a real race: exactly one valid creator wins.+ raced = await asyncio.gather(*(create(c, 'raced') for c in (alice, carol)))+ assert sorted(raced) == ['ok', 'permission_denied'], raced+ assert counts() == (5, 5)+ asyncio.run(probe())diff --git a/tui_gateway/hosted_room_service.py b/tui_gateway/hosted_room_service.pyindex 380f05eea06..442738cb9cb 100644--- a/tui_gateway/hosted_room_service.py+++ b/tui_gateway/hosted_room_service.py@@ -469,7 +469,7 @@ class HostedRoomService:self.prepare_room(binding)self.runtime.wakeup()- def create_room(self, *, room_id: str, name: str, members: Any) -> dict[str, Any]:+ def create_room(self, *, room_id: str, name: str, members: Any, admit: Any = None) -> dict[str, Any]:normalized = discussion.validate_roster(members, local_profiles=self.local_profiles())room = hosted_rooms.create_room(self.db_path, room_id=room_id, name=name,@@ -479,7 +479,7 @@ class HostedRoomService:"handle": member.handle, "target": dict(member.target or {}),**({"display_name": member.display_name} if member.display_name else {})}for member in normalized],- authority_gateway_id=hosted_rooms.local_authority_gateway_id())+ authority_gateway_id=hosted_rooms.local_authority_gateway_id(), admit=admit)self.runtime.wakeup()return room