Skip to content

The agent that grows with you

feat(bot-mode): add durable Group Chat authority and replay

David Dudok de Witcbc67b939f71
diff --git a/gateway/hosted_rooms.py b/gateway/hosted_rooms.py
new file mode 100644
index 00000000000..d0a38e2ae85
--- /dev/null
+++ b/gateway/hosted_rooms.py
@@ -0,0 +1,1456 @@
+"""Durable state for gateway-hosted Bot Mode rooms.
+
+This module owns only hosted-room identity and its append-only event log. It
+does not deliver events, lease relay work, or run agent turns; those concerns
+belong to the relay and the future hosted-room driver. Keeping that boundary
+explicit lets the room log compose with a durable relay without creating a
+second transport queue.
+
+The caller supplies the database path so tests and alternate gateway layouts
+can isolate state. Production handlers use the gateway's root ``state.db``.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+import sqlite3
+import time
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Any, Iterator
+
+
+PROTOCOL_VERSION = 2
+MAX_ROOM_ID_CHARS = 128
+MAX_EVENT_ID_CHARS = 128
+MAX_ROOM_NAME_CHARS = 200
+MAX_EVENT_KIND_CHARS = 64
+MAX_ACTOR_ID_CHARS = 128
+MAX_ACTOR_LABEL_CHARS = 200
+MAX_MEMBERS = 128
+MAX_MEMBERS_JSON_BYTES = 128 * 1024
+MAX_EVENT_JSON_BYTES = 256 * 1024
+MAX_LOG_LIMIT = 500
+MAX_LOG_PAGE_BYTES = 2 * 1024 * 1024
+MAX_ROOM_LIST_LIMIT = 500
+MAX_ACTIVE_ROOMS = 256
+MAX_DISBANDED_ROOM_TOMBSTONES = 512
+DISBANDED_ROOM_RETENTION_SECONDS = 90 * 24 * 60 * 60
+MAX_EVENTS_PER_ROOM = 50_000
+MAX_ROOM_EVENT_BYTES = 256 * 1024 * 1024
+# Leave substantial headroom below the pre-update state.db snapshot ceiling.
+# Event accounting does not include SQLite indexes or repeated room ids, so the
+# logical budget must stay well below the physical-file limit.
+MAX_GATEWAY_EVENT_BYTES = 16 * 1024 * 1024
+CONTROL_EVENT_COUNT_RESERVE = 64
+CONTROL_EVENT_BYTE_RESERVE = 1024 * 1024
+_JOURNAL_MODE_LOCK_RETRIES = 8
+
+_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]*$")
+_EVENT_KIND_RE = re.compile(r"^[a-z][a-z0-9_.-]*$")
+_ROOM_SCHEMA_COLUMNS = frozenset({
+ "room_id",
+ "name",
+ "members_json",
+ "authority_gateway_id",
+ "authority_epoch",
+ "next_seq",
+ "event_bytes",
+ "revision",
+ "created_at",
+ "updated_at",
+ "disbanded_at",
+})
+_EVENT_SCHEMA_COLUMNS = frozenset({
+ "room_id",
+ "seq",
+ "event_id",
+ "kind",
+ "actor_json",
+ "authority_epoch",
+ "payload_json",
+ "created_at",
+})
+_RETIRED_ROOM_SCHEMA_COLUMNS = frozenset({"room_id", "retired_at"})
+
+_EVENT_KINDS_BY_ACTOR = {
+ "user": frozenset({"message.user"}),
+ "member": frozenset({"message.member"}),
+ "gateway": frozenset({
+ "member.unavailable",
+ "room.activity",
+ "turn.deferred",
+ "turn.reassigned",
+ "turn.cancelled",
+ "turn.failed",
+ "turn.settled",
+ "turn.started",
+ }),
+ "system": frozenset({
+ "authority.claimed",
+ "authority.lost",
+ "room.created",
+ "room.disbanded",
+ "room.members_changed",
+ "room.renamed",
+ }),
+}
+_ACTOR_FIELDS = frozenset({"kind", "id", "display_name", "profile", "connection_id"})
+
+
+class HostedRoomError(ValueError):
+ """Base class for invalid or conflicting hosted-room operations."""
+
+
+class RoomNotFoundError(HostedRoomError):
+ """Raised when a room does not exist or has been disbanded."""
+
+
+class RoomHistoryExpiredError(RoomNotFoundError):
+ """Raised when a retired room remains reserved after history compaction."""
+
+ reason = "room_history_expired"
+
+
+class RoomConflictError(HostedRoomError):
+ """Raised when an idempotency key is reused for different room state."""
+
+
+class EventConflictError(HostedRoomError):
+ """Raised when an event id is reused with different immutable content."""
+
+
+class AuthorityConflictError(HostedRoomError):
+ """Raised when a stale room authority attempts to mutate hosted state."""
+
+ reason = "authority_conflict"
+
+
+class AuthoritySupersededError(AuthorityConflictError):
+ """Raised when a successful authority claim was later superseded."""
+
+
+def default_db_path() -> Path:
+ """Return the gateway-wide state database for the active install."""
+ from hermes_constants import get_hermes_home
+
+ home = get_hermes_home()
+ root = home.parent.parent if home.parent.name == "profiles" else home
+ return root / "state.db"
+
+
+def local_authority_gateway_id() -> str:
+ """Return the stable server-owned identity for hosted-room authority."""
+ from hermes_cli.install_identity import get_install_id
+
+ install_id = get_install_id()
+ if not install_id:
+ raise HostedRoomError("stable gateway install identity is unavailable")
+ return _validate_identifier(
+ f"install:{install_id}",
+ label="authority_gateway_id",
+ max_chars=MAX_ACTOR_ID_CHARS,
+ )
+
+
+def _canonical_json(value: Any, *, label: str, max_bytes: int) -> str:
+ try:
+ encoded = json.dumps(
+ value,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ except (TypeError, ValueError, RecursionError) as exc:
+ raise HostedRoomError(f"{label} must be JSON-serializable") from exc
+ if len(encoded.encode("utf-8")) > max_bytes:
+ raise HostedRoomError(f"{label} is too large")
+ return encoded
+
+
+def _validate_identifier(value: Any, *, label: str, max_chars: int) -> str:
+ if not isinstance(value, str):
+ raise HostedRoomError(f"{label} must be a string")
+ value = value.strip()
+ if not value or len(value) > max_chars or not _IDENTIFIER_RE.fullmatch(value):
+ raise HostedRoomError(f"invalid {label}")
+ return value
+
+
+def user_event_id(client_event_id: Any) -> str:
+ """Map a client retry key into the server-owned user-event namespace."""
+ normalized = _validate_identifier(
+ client_event_id,
+ label="event_id",
+ max_chars=MAX_EVENT_ID_CHARS,
+ )
+ digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest()
+ return f"user:{digest}"
+
+
+def _validate_room_name(value: Any) -> str:
+ if not isinstance(value, str):
+ raise HostedRoomError("name must be a string")
+ value = value.strip()
+ if not value or len(value) > MAX_ROOM_NAME_CHARS:
+ raise HostedRoomError("invalid room name")
+ return value
+
+
+def _validate_members(value: Any) -> tuple[list[dict[str, Any]], str]:
+ if not isinstance(value, list):
+ raise HostedRoomError("members must be a list")
+ if len(value) > MAX_MEMBERS:
+ raise HostedRoomError("too many room members")
+ members: list[dict[str, Any]] = []
+ for member in value:
+ if not isinstance(member, dict):
+ raise HostedRoomError("each room member must be an object")
+ members.append(dict(member))
+ encoded = _canonical_json(
+ members,
+ label="members",
+ max_bytes=MAX_MEMBERS_JSON_BYTES,
+ )
+ return members, encoded
+
+
+def _validate_event_kind(value: Any) -> str:
+ if not isinstance(value, str):
+ raise HostedRoomError("kind must be a string")
+ value = value.strip()
+ if (
+ not value
+ or len(value) > MAX_EVENT_KIND_CHARS
+ or not _EVENT_KIND_RE.fullmatch(value)
+ ):
+ raise HostedRoomError("invalid event kind")
+ return value
+
+
+def _optional_actor_field(actor: dict[str, Any], field: str, max_chars: int) -> str:
+ value = actor.get(field)
+ if value is None:
+ return ""
+ if not isinstance(value, str):
+ raise HostedRoomError(f"actor.{field} must be a string")
+ value = value.strip()
+ if len(value) > max_chars:
+ raise HostedRoomError(f"actor.{field} is too long")
+ return value
+
+
+def _validate_actor(value: Any, *, kind: str) -> tuple[dict[str, str], str]:
+ if not isinstance(value, dict):
+ raise HostedRoomError("actor must be an object")
+ unknown = set(value) - _ACTOR_FIELDS
+ if unknown:
+ raise HostedRoomError(f"unknown actor fields: {', '.join(sorted(unknown))}")
+
+ actor_kind = value.get("kind")
+ if not isinstance(actor_kind, str) or actor_kind not in _EVENT_KINDS_BY_ACTOR:
+ raise HostedRoomError("invalid actor.kind")
+ if kind not in _EVENT_KINDS_BY_ACTOR[actor_kind]:
+ raise HostedRoomError(f"actor kind '{actor_kind}' cannot append '{kind}'")
+
+ actor_id = _validate_identifier(
+ value.get("id"),
+ label="actor.id",
+ max_chars=MAX_ACTOR_ID_CHARS,
+ )
+ actor = {"kind": actor_kind, "id": actor_id}
+ for field, max_chars in (
+ ("display_name", MAX_ACTOR_LABEL_CHARS),
+ ("profile", MAX_ACTOR_ID_CHARS),
+ ("connection_id", MAX_ACTOR_ID_CHARS),
+ ):
+ field_value = _optional_actor_field(value, field, max_chars)
+ if field_value:
+ actor[field] = field_value
+ encoded = _canonical_json(
+ actor,
+ label="actor",
+ max_bytes=4 * 1024,
+ )
+ return actor, encoded
+
+
+def _initialize_schema(conn: sqlite3.Connection) -> None:
+ conn.execute(
+ """CREATE TABLE IF NOT EXISTS hosted_rooms (
+ room_id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ members_json TEXT NOT NULL,
+ authority_gateway_id TEXT NOT NULL,
+ authority_epoch INTEGER NOT NULL DEFAULT 1 CHECK (authority_epoch >= 1),
+ next_seq INTEGER NOT NULL DEFAULT 1 CHECK (next_seq >= 1),
+ event_bytes INTEGER NOT NULL DEFAULT 0 CHECK (event_bytes >= 0),
+ revision INTEGER NOT NULL DEFAULT 1 CHECK (revision >= 1),
+ created_at REAL NOT NULL,
+ updated_at REAL NOT NULL,
+ disbanded_at REAL
+ )"""
+ )
+ conn.execute(
+ """CREATE TABLE IF NOT EXISTS hosted_room_events (
+ room_id TEXT NOT NULL,
+ seq INTEGER NOT NULL CHECK (seq >= 1),
+ event_id TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ actor_json TEXT NOT NULL,
+ authority_epoch INTEGER CHECK (authority_epoch IS NULL OR authority_epoch >= 1),
+ payload_json TEXT NOT NULL,
+ created_at REAL NOT NULL,
+ PRIMARY KEY (room_id, seq),
+ UNIQUE (room_id, event_id),
+ FOREIGN KEY (room_id) REFERENCES hosted_rooms(room_id)
+ )"""
+ )
+ conn.execute(
+ """CREATE TABLE IF NOT EXISTS hosted_room_retired_ids (
+ room_id TEXT PRIMARY KEY,
+ retired_at REAL NOT NULL
+ )"""
+ )
+ room_columns = {row[1] for row in conn.execute("PRAGMA table_info(hosted_rooms)")}
+ if "authority_gateway_id" not in room_columns:
+ conn.execute(
+ "ALTER TABLE hosted_rooms "
+ "ADD COLUMN authority_gateway_id TEXT NOT NULL DEFAULT 'legacy'"
+ )
+ if "authority_epoch" not in room_columns:
+ conn.execute(
+ "ALTER TABLE hosted_rooms "
+ "ADD COLUMN authority_epoch INTEGER NOT NULL DEFAULT 1"
+ )
+ backfill_event_bytes = "event_bytes" not in room_columns
+ if backfill_event_bytes:
+ conn.execute(
+ "ALTER TABLE hosted_rooms ADD COLUMN event_bytes INTEGER NOT NULL DEFAULT 0"
+ )
+
+ event_columns = {
+ row[1] for row in conn.execute("PRAGMA table_info(hosted_room_events)")
+ }
+ if "actor_json" not in event_columns:
+ # Draft builds before the actor contract carried no identity. Preserve
+ # their inert replay rows explicitly as legacy system events rather
+ # than guessing a user or Bot author.
+ legacy_actor = _canonical_json(
+ {"kind": "system", "id": "legacy"},
+ label="actor",
+ max_bytes=4 * 1024,
+ )
+ escaped_actor = legacy_actor.replace("'", "''")
+ conn.execute(
+ "ALTER TABLE hosted_room_events "
+ f"ADD COLUMN actor_json TEXT NOT NULL DEFAULT '{escaped_actor}'"
+ )
+ if "authority_epoch" not in event_columns:
+ conn.execute(
+ "ALTER TABLE hosted_room_events ADD COLUMN authority_epoch INTEGER"
+ )
+ if backfill_event_bytes:
+ conn.execute(
+ """UPDATE hosted_rooms
+ SET event_bytes=COALESCE((
+ SELECT SUM(
+ length(CAST(event_id AS BLOB)) +
+ length(CAST(kind AS BLOB)) +
+ length(CAST(actor_json AS BLOB)) +
+ length(CAST(payload_json AS BLOB))
+ )
+ FROM hosted_room_events
+ WHERE hosted_room_events.room_id=hosted_rooms.room_id
+ ), 0)"""
+ )
+ # Old schemas kept the final identity tombstone in hosted_rooms itself.
+ # Copy those identities before bounded history pruning can remove their
+ # heavier room/event payloads. This compact registry is intentionally
+ # permanent: a stale coordinate must never name a different Group Chat.
+ conn.execute(
+ """INSERT OR IGNORE INTO hosted_room_retired_ids (room_id, retired_at)
+ SELECT room_id, disbanded_at FROM hosted_rooms
+ WHERE disbanded_at IS NOT NULL"""
+ )
+ conn.execute(
+ """CREATE INDEX IF NOT EXISTS idx_hosted_room_events_cursor
+ ON hosted_room_events(room_id, seq)"""
+ )
+ if not _schema_is_current(conn):
+ raise HostedRoomError("hosted room schema migration did not complete")
+
+
+def _schema_is_current(conn: sqlite3.Connection) -> bool:
+ room_columns = frozenset(
+ row[1] for row in conn.execute("PRAGMA table_info(hosted_rooms)")
+ )
+ event_columns = frozenset(
+ row[1] for row in conn.execute("PRAGMA table_info(hosted_room_events)")
+ )
+ retired_room_columns = frozenset(
+ row[1] for row in conn.execute("PRAGMA table_info(hosted_room_retired_ids)")
+ )
+ if not _ROOM_SCHEMA_COLUMNS.issubset(room_columns):
+ return False
+ if not _EVENT_SCHEMA_COLUMNS.issubset(event_columns):
+ return False
+ if not _RETIRED_ROOM_SCHEMA_COLUMNS.issubset(retired_room_columns):
+ return False
+ index = conn.execute(
+ """SELECT 1 FROM sqlite_master
+ WHERE type='index' AND name='idx_hosted_room_events_cursor'"""
+ ).fetchone()
+ return index is not None
+
+
+def _connect(db_path: Path | str) -> sqlite3.Connection:
+ from hermes_state import apply_wal_with_fallback
+
+ path = Path(db_path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ conn = sqlite3.connect(path, timeout=10)
+ conn.row_factory = sqlite3.Row
+ try:
+ for attempt in range(_JOURNAL_MODE_LOCK_RETRIES):
+ try:
+ apply_wal_with_fallback(conn, db_label="state.db (hosted_rooms)")
+ break
+ except sqlite3.OperationalError as exc:
+ if (
+ str(exc).lower() != "database is locked"
+ or attempt + 1 == _JOURNAL_MODE_LOCK_RETRIES
+ ):
+ raise
+ # SQLite's journal-mode pragma may not honor the connection's
+ # busy timeout while another first opener initializes the DB,
+ # especially on Windows. Retry only that transient lock class.
+ time.sleep(0.01 * (2**attempt))
+ conn.execute("PRAGMA foreign_keys=ON")
+ if _schema_is_current(conn):
+ return conn
+ # Multiple profile gateways share this root database. Serialize every
+ # draft-schema transition in SQLite itself so a crash rolls back the
+ # whole DDL/data migration and another process can safely retry it.
+ conn.execute("BEGIN IMMEDIATE")
+ _initialize_schema(conn)
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ conn.close()
+ raise
+ return conn
+
+
+@contextmanager
+def _transaction(
+ db_path: Path | str, *, immediate: bool = False
+) -> Iterator[sqlite3.Connection]:
+ conn = _connect(db_path)
+ try:
+ if immediate:
+ conn.execute("BEGIN IMMEDIATE")
+ yield conn
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def _raise_room_not_found(conn: sqlite3.Connection, room_id: str) -> None:
+ retained = conn.execute(
+ "SELECT 1 FROM hosted_rooms WHERE room_id=?",
+ (room_id,),
+ ).fetchone()
+ if retained is not None:
+ # A retained disband tombstone still has replayable history. The
+ # caller simply did not opt into reading disbanded rooms.
+ raise RoomNotFoundError("hosted room not found")
+ retired = conn.execute(
+ "SELECT 1 FROM hosted_room_retired_ids WHERE room_id=?",
+ (room_id,),
+ ).fetchone()
+ if retired is not None:
+ raise RoomHistoryExpiredError(
+ "Group Chat history expired; room_id remains permanently retired"
+ )
+ raise RoomNotFoundError("hosted room not found")
+
+
+def _room_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str, Any]:
+ room = {
+ "room_id": row["room_id"],
+ "name": row["name"],
+ "members": json.loads(row["members_json"]),
+ "authority_gateway_id": row["authority_gateway_id"],
+ "authority_epoch": int(row["authority_epoch"]),
+ "revision": int(row["revision"]),
+ "created_at": float(row["created_at"]),
+ "updated_at": float(row["updated_at"]),
+ "idempotent": idempotent,
+ }
+ if "disbanded_at" in row.keys() and row["disbanded_at"] is not None:
+ room["disbanded_at"] = float(row["disbanded_at"])
+ if "next_seq" in row.keys():
+ room["latest_seq"] = int(row["next_seq"]) - 1
+ return room
+
+
+def _event_storage_bytes(
+ *, event_id: str, kind: str, actor_json: str, payload_json: str
+) -> int:
+ return len((event_id + kind + actor_json + payload_json).encode("utf-8"))
+
+
+def _assert_event_capacity(
+ conn: sqlite3.Connection,
+ *,
+ room: sqlite3.Row,
+ additional_bytes: int,
+ allow_control: bool = False,
+) -> None:
+ event_limit = MAX_EVENTS_PER_ROOM + (
+ CONTROL_EVENT_COUNT_RESERVE if allow_control else 0
+ )
+ room_byte_limit = MAX_ROOM_EVENT_BYTES + (
+ CONTROL_EVENT_BYTE_RESERVE if allow_control else 0
+ )
+ gateway_byte_limit = MAX_GATEWAY_EVENT_BYTES + (
+ CONTROL_EVENT_BYTE_RESERVE if allow_control else 0
+ )
+ if int(room["next_seq"]) - 1 >= event_limit:
+ raise HostedRoomError(
+ "This Group Chat reached its history limit. Start a new Group Chat to continue."
+ )
+ room_bytes = int(room["event_bytes"])
+ if room_bytes + additional_bytes > room_byte_limit:
+ raise HostedRoomError(
+ "This Group Chat reached its storage limit. Start a new Group Chat to continue."
+ )
+ gateway_bytes = int(
+ conn.execute(
+ "SELECT COALESCE(SUM(event_bytes), 0) FROM hosted_rooms"
+ ).fetchone()[0]
+ )
+ if gateway_bytes + additional_bytes > gateway_byte_limit:
+ _prune_disbanded_rooms_locked(
+ conn,
+ now=None,
+ max_gateway_event_bytes=max(0, gateway_byte_limit - additional_bytes),
+ )
+ gateway_bytes = int(
+ conn.execute(
+ "SELECT COALESCE(SUM(event_bytes), 0) FROM hosted_rooms"
+ ).fetchone()[0]
+ )
+ if gateway_bytes + additional_bytes > gateway_byte_limit:
+ raise HostedRoomError(
+ "Group Chat storage is full on this host. Delete an old Group Chat and try again."
+ )
+
+
+def _prune_disbanded_rooms_locked(
+ conn: sqlite3.Connection,
+ *,
+ now: float | None,
+ max_gateway_event_bytes: int | None = None,
+) -> int:
+ candidates: set[str] = set()
+ if now is not None:
+ cutoff = now - DISBANDED_ROOM_RETENTION_SECONDS
+ candidates.update(
+ str(row["room_id"])
+ for row in conn.execute(
+ """SELECT room_id FROM hosted_rooms
+ WHERE disbanded_at IS NOT NULL AND disbanded_at<=?""",
+ (cutoff,),
+ ).fetchall()
+ )
+ candidates.update(
+ str(row["room_id"])
+ for row in conn.execute(
+ """SELECT room_id FROM hosted_rooms
+ WHERE disbanded_at IS NOT NULL
+ ORDER BY disbanded_at DESC, room_id ASC
+ LIMIT -1 OFFSET ?""",
+ (MAX_DISBANDED_ROOM_TOMBSTONES,),
+ ).fetchall()
+ )
+ if max_gateway_event_bytes is not None:
+ retained_bytes = int(
+ conn.execute(
+ "SELECT COALESCE(SUM(event_bytes), 0) FROM hosted_rooms"
+ ).fetchone()[0]
+ )
+ if retained_bytes > max_gateway_event_bytes:
+ for row in conn.execute(
+ """SELECT room_id, event_bytes FROM hosted_rooms
+ WHERE disbanded_at IS NOT NULL
+ ORDER BY disbanded_at ASC, room_id ASC"""
+ ).fetchall():
+ room_id = str(row["room_id"])
+ if room_id not in candidates:
+ candidates.add(room_id)
+ retained_bytes -= int(row["event_bytes"])
+ if retained_bytes <= max_gateway_event_bytes:
+ break
+ if not candidates:
+ return 0
+
+ placeholders = ",".join("?" for _ in candidates)
+ room_ids = tuple(sorted(candidates))
+ conn.execute(
+ f"""INSERT OR IGNORE INTO hosted_room_retired_ids (room_id, retired_at)
+ SELECT room_id, disbanded_at FROM hosted_rooms
+ WHERE room_id IN ({placeholders}) AND disbanded_at IS NOT NULL""",
+ room_ids,
+ )
+ conn.execute(
+ f"DELETE FROM hosted_room_events WHERE room_id IN ({placeholders})",
+ room_ids,
+ )
+ conn.execute(
+ f"DELETE FROM hosted_rooms WHERE room_id IN ({placeholders})",
+ room_ids,
+ )
+ return len(room_ids)
+
+
+def prune_disbanded_rooms(
+ db_path: Path | str,
+ *,
+ now: float | None = None,
+) -> int:
+ """Purge deleted Group Chat payloads while reserving their identities."""
+
+ timestamp = time.time() if now is None else float(now)
+ with _transaction(db_path, immediate=True) as conn:
+ return _prune_disbanded_rooms_locked(conn, now=timestamp)
+
+
+def _event_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str, Any]:
+ return {
+ "room_id": row["room_id"],
+ "seq": int(row["seq"]),
+ "event_id": row["event_id"],
+ "kind": row["kind"],
+ "actor": json.loads(row["actor_json"]),
+ "authority_epoch": (
+ int(row["authority_epoch"]) if row["authority_epoch"] is not None else None
+ ),
+ "payload": json.loads(row["payload_json"]),
+ "created_at": float(row["created_at"]),
+ "idempotent": idempotent,
+ }
+
+
+def create_room(
+ db_path: Path | str,
+ *,
+ room_id: Any,
+ name: Any,
+ members: Any,
+ authority_gateway_id: Any,
+ now: float | None = None,
+) -> dict[str, Any]:
+ """Create a room, or return the identical existing room idempotently."""
+ room_id = _validate_identifier(
+ room_id,
+ label="room_id",
+ max_chars=MAX_ROOM_ID_CHARS,
+ )
+ name = _validate_room_name(name)
+ normalized_members, members_json = _validate_members(members)
+ authority_gateway_id = _validate_identifier(
+ authority_gateway_id,
+ label="authority_gateway_id",
+ max_chars=MAX_ACTOR_ID_CHARS,
+ )
+ now = time.time() if now is None else float(now)
+
+ with _transaction(db_path, immediate=True) as conn:
+ if conn.execute(
+ "SELECT 1 FROM hosted_room_retired_ids WHERE room_id=?",
+ (room_id,),
+ ).fetchone():
+ raise RoomConflictError("room_id belongs to a disbanded room")
+ existing = conn.execute(
+ """SELECT room_id, name, members_json, authority_gateway_id,
+ authority_epoch, next_seq, event_bytes, revision,
+ created_at, updated_at, disbanded_at
+ FROM hosted_rooms WHERE room_id=?""",
+ (room_id,),
+ ).fetchone()
+ if existing is not None:
+ if existing["disbanded_at"] is not None:
+ raise RoomConflictError("room_id belongs to a disbanded room")
+ if existing["name"] != name or existing["members_json"] != members_json:
+ raise RoomConflictError("room_id already exists with different state")
+ if (
+ existing["authority_gateway_id"] == "legacy"
+ and authority_gateway_id != "legacy"
+ ):
+ target_epoch = int(existing["authority_epoch"]) + 1
+ seq = int(existing["next_seq"])
+ claim_actor_json = _canonical_json(
+ {"kind": "system", "id": "authority-control"},
+ label="actor",
+ max_bytes=4 * 1024,
+ )
+ claim_payload_json = _canonical_json(
+ {
+ "previous_gateway_id": "legacy",
+ "authority_gateway_id": authority_gateway_id,
+ "authority_epoch": target_epoch,
+ },
+ label="payload",
+ max_bytes=MAX_EVENT_JSON_BYTES,
+ )
+ claim_bytes = _event_storage_bytes(
+ event_id="system:authority-adopted",
+ kind="authority.claimed",
+ actor_json=claim_actor_json,
+ payload_json=claim_payload_json,
+ )
+ _assert_event_capacity(
+ conn,
+ room=existing,
+ additional_bytes=claim_bytes,
+ allow_control=True,
+ )
+ conn.execute(
+ """INSERT INTO hosted_room_events
+ (room_id, seq, event_id, kind, actor_json,
+ authority_epoch, payload_json, created_at)
+ VALUES (?, ?, 'system:authority-adopted',
+ 'authority.claimed', ?, ?, ?, ?)""",
+ (
+ room_id,
+ seq,
+ claim_actor_json,
+ target_epoch,
+ claim_payload_json,
+ now,
+ ),
+ )
+ adopted = conn.execute(
+ """UPDATE hosted_rooms
+ SET authority_gateway_id=?, authority_epoch=?,
+ next_seq=next_seq+1, revision=revision+1,
+ event_bytes=event_bytes+?, updated_at=?
+ WHERE room_id=? AND authority_gateway_id='legacy'
+ AND authority_epoch=? AND next_seq=?
+ AND disbanded_at IS NULL""",
+ (
+ authority_gateway_id,
+ target_epoch,
+ claim_bytes,
+ now,
+ room_id,
+ int(existing["authority_epoch"]),
+ seq,
+ ),
+ )
+ if adopted.rowcount != 1:
+ raise AuthorityConflictError("legacy room adoption lost its fence")
+ existing = conn.execute(
+ """SELECT room_id, name, members_json, authority_gateway_id,
+ authority_epoch, next_seq, revision, created_at,
+ updated_at, disbanded_at
+ FROM hosted_rooms WHERE room_id=?""",
+ (room_id,),
+ ).fetchone()
+ if existing is None: # pragma: no cover - row updated above
+ raise RuntimeError("adopted room could not be reloaded")
+ result = _room_from_row(existing, idempotent=True)
+ result["adopted"] = True
+ claim_event = conn.execute(
+ """SELECT room_id, seq, event_id, kind, actor_json,
+ authority_epoch, payload_json, created_at
+ FROM hosted_room_events
+ WHERE room_id=? AND event_id='system:authority-adopted'""",
+ (room_id,),
+ ).fetchone()
+ if claim_event is None: # pragma: no cover - inserted above
+ raise RuntimeError("legacy adoption event could not be reloaded")
+ result["claim_event"] = _event_from_row(claim_event)
+ return result
+ if existing["authority_gateway_id"] != authority_gateway_id:
+ raise RoomConflictError(
+ "room_id already belongs to a different authority"
+ )
+ return _room_from_row(existing, idempotent=True)
+
+ active_rooms = int(
+ conn.execute(
+ "SELECT COUNT(*) FROM hosted_rooms WHERE disbanded_at IS NULL"
+ ).fetchone()[0]
+ )
+ if active_rooms >= MAX_ACTIVE_ROOMS:
+ raise HostedRoomError(
+ "This host has too many active Group Chats. Delete one and try again."
+ )
+
+ conn.execute(
+ """INSERT INTO hosted_rooms
+ (room_id, name, members_json, authority_gateway_id,
+ authority_epoch, next_seq, event_bytes, revision,
+ created_at, updated_at, disbanded_at)
+ VALUES (?, ?, ?, ?, 1, 1, 0, 1, ?, ?, NULL)""",
+ (room_id, name, members_json, authority_gateway_id, now, now),
+ )
+ row = conn.execute(
+ """SELECT room_id, name, members_json, authority_gateway_id,
+ authority_epoch, revision, created_at, updated_at
+ FROM hosted_rooms WHERE room_id=?""",
+ (room_id,),
+ ).fetchone()
+ if row is None: # pragma: no cover - guarded by the insert above
+ raise RuntimeError("created room could not be reloaded")
+ result = _room_from_row(row)
+ result["members"] = normalized_members
+ return result
+
+
+def list_rooms(
+ db_path: Path | str,
+ *,
+ include_disbanded: bool = False,
+ limit: int = MAX_ROOM_LIST_LIMIT,
+ offset: int = 0,
+) -> list[dict[str, Any]]:
+ """Return one bounded page of rooms ordered by most recent change."""
+ if (
+ isinstance(limit, bool)
+ or not isinstance(limit, int)
+ or not 1 <= limit <= MAX_ROOM_LIST_LIMIT
+ ):
+ raise HostedRoomError(f"limit must be between 1 and {MAX_ROOM_LIST_LIMIT}")
+ if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:
+ raise HostedRoomError("offset must be a non-negative integer")
+ with _transaction(db_path, immediate=True) as conn:
+ _prune_disbanded_rooms_locked(conn, now=None)
+ rows = conn.execute(
+ """SELECT room_id, name, members_json, authority_gateway_id,
+ authority_epoch, next_seq, revision, created_at, updated_at,
+ disbanded_at
+ FROM hosted_rooms
+ WHERE disbanded_at IS NULL OR ?
+ ORDER BY updated_at DESC, room_id ASC
+ LIMIT ? OFFSET ?""",
+ (int(include_disbanded), limit, offset),
+ ).fetchall()
+ return [_room_from_row(row) for row in rows]
+
+
+def append_event(
+ db_path: Path | str,
+ *,
+ room_id: Any,
+ event_id: Any,
+ kind: Any,
+ actor: Any,
+ payload: Any,
+ authority_gateway_id: Any = None,
+ authority_epoch: Any = None,
+ now: float | None = None,
+) -> dict[str, Any]:
+ """Append one immutable event and allocate its per-room sequence atomically.
+
+ Repeating the same ``event_id`` and immutable content returns the original
+ event. Reusing the id for different content fails closed.
+ """
+ room_id = _validate_identifier(
+ room_id,
+ label="room_id",
+ max_chars=MAX_ROOM_ID_CHARS,
+ )
+ event_id = _validate_identifier(
+ event_id,
+ label="event_id",
+ max_chars=MAX_EVENT_ID_CHARS,
+ )
+ kind = _validate_event_kind(kind)
+ normalized_actor, actor_json = _validate_actor(actor, kind=kind)
+ authority_scoped = normalized_actor["kind"] in {
+ "user",
+ "member",
+ "gateway",
+ "system",
+ }
+ normalized_authority_gateway_id: str | None = None
+ normalized_authority_epoch: int | None = None
+ if authority_scoped:
+ normalized_authority_gateway_id = _validate_identifier(
+ authority_gateway_id,
+ label="authority_gateway_id",
+ max_chars=MAX_ACTOR_ID_CHARS,
+ )
+ if (
+ normalized_actor["kind"] == "gateway"
+ and normalized_actor["id"] != normalized_authority_gateway_id
+ ):
+ raise HostedRoomError("gateway actor.id must match authority_gateway_id")
+ if (
+ isinstance(authority_epoch, bool)
+ or not isinstance(authority_epoch, int)
+ or authority_epoch < 1
+ ):
+ raise HostedRoomError("authority_epoch must be a positive integer")
+ normalized_authority_epoch = authority_epoch
+ elif authority_gateway_id is not None or authority_epoch is not None:
+ raise HostedRoomError(
+ "authority fields are only valid for room-scoped events"
+ )
+ if not isinstance(payload, dict):
+ raise HostedRoomError("payload must be an object")
+ payload_json = _canonical_json(
+ payload,
+ label="payload",
+ max_bytes=MAX_EVENT_JSON_BYTES,
+ )
+ now = time.time() if now is None else float(now)
+
+ with _transaction(db_path, immediate=True) as conn:
+ existing = conn.execute(
+ """SELECT room_id, seq, event_id, kind, actor_json, authority_epoch,
+ payload_json, created_at
+ FROM hosted_room_events WHERE room_id=? AND event_id=?""",
+ (room_id, event_id),
+ ).fetchone()
+ if existing is not None:
+ if (
+ existing["kind"] != kind
+ or existing["actor_json"] != actor_json
+ or existing["authority_epoch"] != normalized_authority_epoch
+ or existing["payload_json"] != payload_json
+ ):
+ raise EventConflictError(
+ "event_id already exists with different content"
+ )
+ return _event_from_row(existing, idempotent=True)
+
+ room = conn.execute(
+ """SELECT next_seq, event_bytes, authority_gateway_id, authority_epoch
+ FROM hosted_rooms
+ WHERE room_id=? AND disbanded_at IS NULL""",
+ (room_id,),
+ ).fetchone()
+ if room is None:
+ _raise_room_not_found(conn, room_id)
+ if authority_scoped and (
+ room["authority_gateway_id"] != normalized_authority_gateway_id
+ or int(room["authority_epoch"]) != normalized_authority_epoch
+ ):
+ raise AuthorityConflictError("stale hosted room authority")
+ seq = int(room["next_seq"])
+ event_bytes = _event_storage_bytes(
+ event_id=event_id,
+ kind=kind,
+ actor_json=actor_json,
+ payload_json=payload_json,
+ )
+ _assert_event_capacity(
+ conn,
+ room=room,
+ additional_bytes=event_bytes,
+ allow_control=kind
+ in {
+ "authority.claimed",
+ "authority.lost",
+ "room.disbanded",
+ },
+ )
+ conn.execute(
+ """INSERT INTO hosted_room_events
+ (room_id, seq, event_id, kind, actor_json, authority_epoch,
+ payload_json, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ room_id,
+ seq,
+ event_id,
+ kind,
+ actor_json,
+ normalized_authority_epoch,
+ payload_json,
+ now,
+ ),
+ )
+ advanced = conn.execute(
+ """UPDATE hosted_rooms
+ SET next_seq=?, event_bytes=event_bytes+?, updated_at=?
+ WHERE room_id=? AND next_seq=?""",
+ (seq + 1, event_bytes, now, room_id, seq),
+ )
+ if advanced.rowcount != 1:
+ raise RuntimeError("hosted room sequence advance lost its write fence")
+ row = conn.execute(
+ """SELECT room_id, seq, event_id, kind, actor_json, authority_epoch,
+ payload_json, created_at
+ FROM hosted_room_events WHERE room_id=? AND seq=?""",
+ (room_id, seq),
+ ).fetchone()
+ if row is None: # pragma: no cover - guarded by the insert above
+ raise RuntimeError("appended event could not be reloaded")
+ result = _event_from_row(row)
+ result["actor"] = normalized_actor
+ return result
+
+
+def room_state(
+ db_path: Path | str,
+ *,
+ room_id: Any,
+ include_disbanded: bool = False,
+) -> dict[str, Any]:
+ """Return durable replay and authority state for one room."""
+ room_id = _validate_identifier(
+ room_id,
+ label="room_id",
+ max_chars=MAX_ROOM_ID_CHARS,
+ )
+ with _transaction(db_path) as conn:
+ row = conn.execute(
+ """SELECT room_id, name, members_json, authority_gateway_id,
+ authority_epoch, next_seq, revision, created_at, updated_at,
+ disbanded_at
+ FROM hosted_rooms
+ WHERE room_id=? AND (disbanded_at IS NULL OR ?)""",
+ (room_id, int(include_disbanded)),
+ ).fetchone()
+ if row is None:
+ _raise_room_not_found(conn, room_id)
+ claim_row = conn.execute(
+ """SELECT room_id, seq, event_id, kind, actor_json, authority_epoch,
+ payload_json, created_at
+ FROM hosted_room_events
+ WHERE room_id=? AND kind='authority.claimed'
+ AND authority_epoch=?
+ ORDER BY seq DESC LIMIT 1""",
+ (room_id, int(row["authority_epoch"])),
+ ).fetchone()
+ state = _room_from_row(row)
+ state["latest_seq"] = int(row["next_seq"]) - 1
+ if claim_row is not None:
+ state["authority_claim"] = _event_from_row(claim_row)
+ return state
+
+
+def claim_authority(
+ db_path: Path | str,
+ *,
+ room_id: Any,
+ expected_gateway_id: Any,
+ expected_epoch: Any,
+ new_gateway_id: Any,
+ event_id: Any,
+ now: float | None = None,
+) -> dict[str, Any]:
+ """Fence a verified authority transfer with a compare-and-swap epoch.
+
+ This storage primitive does not decide *when* takeover is safe. A future
+ replicated driver must call it only after its lease/quorum policy has
+ established that the previous owner can no longer commit.
+ """
+ room_id = _validate_identifier(
+ room_id,
+ label="room_id",
+ max_chars=MAX_ROOM_ID_CHARS,
+ )
+ expected_gateway_id = _validate_identifier(
+ expected_gateway_id,
+ label="expected_gateway_id",
+ max_chars=MAX_ACTOR_ID_CHARS,
+ )
+ new_gateway_id = _validate_identifier(
+ new_gateway_id,
+ label="new_gateway_id",
+ max_chars=MAX_ACTOR_ID_CHARS,
+ )
+ event_id = _validate_identifier(
+ event_id,
+ label="event_id",
+ max_chars=MAX_EVENT_ID_CHARS,
+ )
+ if (
+ isinstance(expected_epoch, bool)
+ or not isinstance(expected_epoch, int)
+ or expected_epoch < 1
+ ):
+ raise HostedRoomError("expected_epoch must be a positive integer")
+ now = time.time() if now is None else float(now)
+ target_epoch = expected_epoch + 1
+ claim_actor = {"kind": "system", "id": "authority-control"}
+ claim_actor_json = _canonical_json(
+ claim_actor,
+ label="actor",
+ max_bytes=4 * 1024,
+ )
+ claim_payload = {
+ "previous_gateway_id": expected_gateway_id,
+ "authority_gateway_id": new_gateway_id,
+ "authority_epoch": target_epoch,
+ }
+ claim_payload_json = _canonical_json(
+ claim_payload,
+ label="payload",
+ max_bytes=MAX_EVENT_JSON_BYTES,
+ )
+
+ with _transaction(db_path, immediate=True) as conn:
+ row = conn.execute(
+ """SELECT authority_gateway_id, authority_epoch, next_seq, event_bytes
+ FROM hosted_rooms
+ WHERE room_id=? AND disbanded_at IS NULL""",
+ (room_id,),
+ ).fetchone()
+ if row is None:
+ _raise_room_not_found(conn, room_id)
+ current_gateway = str(row["authority_gateway_id"])
+ current_epoch = int(row["authority_epoch"])
+ existing_event = conn.execute(
+ """SELECT room_id, seq, event_id, kind, actor_json, authority_epoch,
+ payload_json, created_at
+ FROM hosted_room_events WHERE room_id=? AND event_id=?""",
+ (room_id, event_id),
+ ).fetchone()
+ if existing_event is not None:
+ if (
+ existing_event["kind"] != "authority.claimed"
+ or existing_event["actor_json"] != claim_actor_json
+ or existing_event["authority_epoch"] != target_epoch
+ or existing_event["payload_json"] != claim_payload_json
+ ):
+ raise EventConflictError(
+ "event_id already exists with different content"
+ )
+ if current_gateway != new_gateway_id or current_epoch != target_epoch:
+ raise AuthoritySupersededError(
+ "authority claim succeeded but was later superseded"
+ )
+ idempotent = True
+ elif current_gateway != expected_gateway_id or current_epoch != expected_epoch:
+ raise AuthorityConflictError("hosted room authority changed")
+ else:
+ seq = int(row["next_seq"])
+ claim_bytes = _event_storage_bytes(
+ event_id=event_id,
+ kind="authority.claimed",
+ actor_json=claim_actor_json,
+ payload_json=claim_payload_json,
+ )
+ _assert_event_capacity(
+ conn,
+ room=row,
+ additional_bytes=claim_bytes,
+ allow_control=True,
+ )
+ conn.execute(
+ """INSERT INTO hosted_room_events
+ (room_id, seq, event_id, kind, actor_json, authority_epoch,
+ payload_json, created_at)
+ VALUES (?, ?, ?, 'authority.claimed', ?, ?, ?, ?)""",
+ (
+ room_id,
+ seq,
+ event_id,
+ claim_actor_json,
+ target_epoch,
+ claim_payload_json,
+ now,
+ ),
+ )
+ updated = conn.execute(
+ """UPDATE hosted_rooms
+ SET authority_gateway_id=?, authority_epoch=authority_epoch+1,
+ next_seq=next_seq+1, event_bytes=event_bytes+?,
+ revision=revision+1, updated_at=?
+ WHERE room_id=? AND disbanded_at IS NULL
+ AND authority_gateway_id=? AND authority_epoch=?""",
+ (
+ new_gateway_id,
+ claim_bytes,
+ now,
+ room_id,
+ expected_gateway_id,
+ expected_epoch,
+ ),
+ )
+ if updated.rowcount != 1:
+ raise AuthorityConflictError("hosted room authority changed")
+ idempotent = False
+ existing_event = conn.execute(
+ """SELECT room_id, seq, event_id, kind, actor_json,
+ authority_epoch, payload_json, created_at
+ FROM hosted_room_events WHERE room_id=? AND event_id=?""",
+ (room_id, event_id),
+ ).fetchone()
+ state_row = conn.execute(
+ """SELECT room_id, name, members_json, authority_gateway_id,
+ authority_epoch, next_seq, revision, created_at, updated_at
+ FROM hosted_rooms WHERE room_id=?""",
+ (room_id,),
+ ).fetchone()
+ if state_row is None: # pragma: no cover - room exists in this transaction
+ raise RuntimeError("claimed room could not be reloaded")
+ state = _room_from_row(state_row, idempotent=idempotent)
+ state["latest_seq"] = int(state_row["next_seq"]) - 1
+ if existing_event is None: # pragma: no cover - both claim paths set it
+ raise RuntimeError("authority claim event could not be reloaded")
+ state["claim_event"] = _event_from_row(
+ existing_event,
+ idempotent=idempotent,
+ )
+ return state
+
+
+def disband_room(
+ db_path: Path | str,
+ *,
+ room_id: Any,
+ expected_gateway_id: Any,
+ expected_epoch: Any,
+ now: float | None = None,
+) -> dict[str, Any]:
+ """Tombstone a room id permanently and idempotently."""
+ room_id = _validate_identifier(
+ room_id,
+ label="room_id",
+ max_chars=MAX_ROOM_ID_CHARS,
+ )
+ expected_gateway_id = _validate_identifier(
+ expected_gateway_id,
+ label="expected_gateway_id",
+ max_chars=MAX_ACTOR_ID_CHARS,
+ )
+ if (
+ isinstance(expected_epoch, bool)
+ or not isinstance(expected_epoch, int)
+ or expected_epoch < 1
+ ):
+ raise HostedRoomError("expected_epoch must be a positive integer")
+ now = time.time() if now is None else float(now)
+
+ with _transaction(db_path, immediate=True) as conn:
+ room = conn.execute(
+ """SELECT authority_gateway_id, authority_epoch, next_seq,
+ event_bytes, disbanded_at
+ FROM hosted_rooms WHERE room_id=?""",
+ (room_id,),
+ ).fetchone()
+ if room is None:
+ retired = conn.execute(
+ "SELECT retired_at FROM hosted_room_retired_ids WHERE room_id=?",
+ (room_id,),
+ ).fetchone()
+ if retired is None:
+ raise RoomNotFoundError("hosted room not found")
+ return {
+ "room_id": room_id,
+ "disbanded_at": float(retired["retired_at"]),
+ "idempotent": True,
+ "history_expired": True,
+ }
+ if room["disbanded_at"] is not None:
+ conn.execute(
+ """INSERT OR IGNORE INTO hosted_room_retired_ids
+ (room_id, retired_at) VALUES (?, ?)""",
+ (room_id, float(room["disbanded_at"])),
+ )
+ event = conn.execute(
+ """SELECT room_id, seq, event_id, kind, actor_json,
+ authority_epoch, payload_json, created_at
+ FROM hosted_room_events
+ WHERE room_id=? AND event_id='system:room-disbanded'""",
+ (room_id,),
+ ).fetchone()
+ return {
+ "room_id": room_id,
+ "disbanded_at": float(room["disbanded_at"]),
+ "idempotent": True,
+ **(
+ {"event": _event_from_row(event, idempotent=True)}
+ if event is not None
+ else {}
+ ),
+ }
+ if (
+ str(room["authority_gateway_id"]) != expected_gateway_id
+ or int(room["authority_epoch"]) != expected_epoch
+ ):
+ raise AuthorityConflictError("stale hosted room authority")
+ seq = int(room["next_seq"])
+ actor_json = _canonical_json(
+ {"kind": "system", "id": "room-control"},
+ label="actor",
+ max_bytes=4 * 1024,
+ )
+ payload_json = _canonical_json(
+ {"room_id": room_id},
+ label="payload",
+ max_bytes=MAX_EVENT_JSON_BYTES,
+ )
+ disband_bytes = _event_storage_bytes(
+ event_id="system:room-disbanded",
+ kind="room.disbanded",
+ actor_json=actor_json,
+ payload_json=payload_json,
+ )
+ _assert_event_capacity(
+ conn,
+ room=room,
+ additional_bytes=disband_bytes,
+ allow_control=True,
+ )
+ conn.execute(
+ """INSERT INTO hosted_room_events
+ (room_id, seq, event_id, kind, actor_json, authority_epoch,
+ payload_json, created_at)
+ VALUES (?, ?, 'system:room-disbanded', 'room.disbanded', ?, ?, ?, ?)""",
+ (
+ room_id,
+ seq,
+ actor_json,
+ int(room["authority_epoch"]),
+ payload_json,
+ now,
+ ),
+ )
+ updated = conn.execute(
+ """UPDATE hosted_rooms
+ SET disbanded_at=?, updated_at=?, revision=revision+1,
+ next_seq=next_seq+1, event_bytes=event_bytes+?
+ WHERE room_id=? AND disbanded_at IS NULL
+ AND authority_gateway_id=? AND authority_epoch=?""",
+ (
+ now,
+ now,
+ disband_bytes,
+ room_id,
+ expected_gateway_id,
+ expected_epoch,
+ ),
+ )
+ if updated.rowcount != 1:
+ raise RoomConflictError("hosted room disband lost its fence")
+ conn.execute(
+ """INSERT OR IGNORE INTO hosted_room_retired_ids
+ (room_id, retired_at) VALUES (?, ?)""",
+ (room_id, now),
+ )
+ event = conn.execute(
+ """SELECT room_id, seq, event_id, kind, actor_json,
+ authority_epoch, payload_json, created_at
+ FROM hosted_room_events
+ WHERE room_id=? AND event_id='system:room-disbanded'""",
+ (room_id,),
+ ).fetchone()
+ if event is None: # pragma: no cover - inserted in this transaction
+ raise RuntimeError("room disband event could not be reloaded")
+ _prune_disbanded_rooms_locked(
+ conn,
+ now=now,
+ max_gateway_event_bytes=MAX_GATEWAY_EVENT_BYTES,
+ )
+ return {
+ "room_id": room_id,
+ "disbanded_at": now,
+ "idempotent": False,
+ "event": _event_from_row(event),
+ }
+
+
+def read_events(
+ db_path: Path | str,
+ *,
+ room_id: Any,
+ since_seq: Any = 0,
+ limit: Any = 100,
+ include_disbanded: bool = False,
+) -> dict[str, Any]:
+ """Read a monotonic room-log delta after ``since_seq``."""
+ room_id = _validate_identifier(
+ room_id,
+ label="room_id",
+ max_chars=MAX_ROOM_ID_CHARS,
+ )
+ if isinstance(since_seq, bool) or not isinstance(since_seq, int) or since_seq < 0:
+ raise HostedRoomError("since_seq must be a non-negative integer")
+ if (
+ isinstance(limit, bool)
+ or not isinstance(limit, int)
+ or not 1 <= limit <= MAX_LOG_LIMIT
+ ):
+ raise HostedRoomError(f"limit must be between 1 and {MAX_LOG_LIMIT}")
+
+ with _transaction(db_path) as conn:
+ room = conn.execute(
+ """SELECT next_seq FROM hosted_rooms
+ WHERE room_id=? AND (disbanded_at IS NULL OR ?)""",
+ (room_id, int(include_disbanded)),
+ ).fetchone()
+ if room is None:
+ _raise_room_not_found(conn, room_id)
+ latest_seq = int(room["next_seq"]) - 1
+ if since_seq > latest_seq:
+ raise HostedRoomError("since_seq is ahead of the hosted room log")
+ rows = conn.execute(
+ """WITH candidates AS (
+ SELECT room_id, seq, event_id, kind, actor_json,
+ authority_epoch, payload_json, created_at,
+ SUM(
+ LENGTH(CAST(event_id AS BLOB)) +
+ LENGTH(CAST(kind AS BLOB)) +
+ LENGTH(CAST(actor_json AS BLOB)) +
+ LENGTH(CAST(payload_json AS BLOB))
+ ) OVER (ORDER BY seq ASC) AS cumulative_bytes
+ FROM hosted_room_events
+ WHERE room_id=? AND seq>?
+ ORDER BY seq ASC LIMIT ?
+ )
+ SELECT room_id, seq, event_id, kind, actor_json,
+ authority_epoch, payload_json, created_at
+ FROM candidates
+ WHERE cumulative_bytes<=?
+ ORDER BY seq ASC""",
+ (room_id, since_seq, limit, MAX_LOG_PAGE_BYTES),
+ ).fetchall()
+ events = [_event_from_row(row) for row in rows]
+
+ def build_page(page_events: list[dict[str, Any]]) -> dict[str, Any]:
+ cursor = page_events[-1]["seq"] if page_events else since_seq
+ return {
+ "events": page_events,
+ "cursor": cursor,
+ "latest_seq": latest_seq,
+ "has_more": cursor < latest_seq,
+ }
+
+ def page_bytes(page: dict[str, Any]) -> int:
+ return len(
+ json.dumps(
+ page,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ )
+
+ page = build_page(events)
+ if events and page_bytes(page) > MAX_LOG_PAGE_BYTES:
+ low, high = 1, len(events)
+ while low < high:
+ middle = (low + high + 1) // 2
+ candidate = build_page(events[:middle])
+ if page_bytes(candidate) <= MAX_LOG_PAGE_BYTES:
+ low = middle
+ else:
+ high = middle - 1
+ page = build_page(events[:low])
+ if page_bytes(page) > MAX_LOG_PAGE_BYTES:
+ raise HostedRoomError("hosted room event exceeds replay page limit")
+ return page
diff --git a/hermes_cli/install_identity.py b/hermes_cli/install_identity.py
new file mode 100644
index 00000000000..264f827ff25
--- /dev/null
+++ b/hermes_cli/install_identity.py
@@ -0,0 +1,153 @@
+"""Stable opaque identity shared by every profile in one Hermes install."""
+
+from __future__ import annotations
+
+import contextlib
+import os
+from pathlib import Path
+import re
+import tempfile
+import threading
+from typing import Optional
+import uuid
+
+from hermes_constants import get_default_hermes_root
+
+_INSTALL_ID_FILENAME = "install_id"
+_INSTALL_ID_RE = re.compile(r"^[0-9a-f]{32}$")
+_INSTALL_ID_CACHE: dict[str, Optional[str]] = {"root": None, "value": None}
+_INSTALL_ID_LOCK = threading.Lock()
+_INSTALL_ID_PUBLICATION_LOCK = threading.Lock()
+
+
+def _install_id_file_lock(root: Path):
+ """Serialize identity publication across processes on POSIX and Windows."""
+ lock_path = root / ".install_id.lock"
+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)
+ windows = os.name == "nt"
+ try:
+ if windows:
+ import msvcrt
+
+ if os.fstat(fd).st_size == 0:
+ os.write(fd, b"\0")
+ os.fsync(fd)
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fd, fcntl.LOCK_EX)
+ yield
+ finally:
+ try:
+ if windows:
+ import msvcrt
+
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ finally:
+ os.close(fd)
+
+
+def _fsync_directory(path: Path) -> None:
+ """Best-effort durability for the directory entry after replace."""
+ if os.name == "nt":
+ return
+ try:
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
+ except OSError:
+ return
+ try:
+ os.fsync(fd)
+ except OSError:
+ pass
+ finally:
+ os.close(fd)
+
+
+def read_or_create_install_id(root: Path | None = None) -> Optional[str]:
+ """Read or atomically mint the opaque id for the physical install.
+
+ ``None`` means the id could neither be read nor persisted. Returning an
+ ephemeral id would violate the authority and connection-registry contract.
+ """
+ root = get_default_hermes_root() if root is None else root
+ path = root / _INSTALL_ID_FILENAME
+ try:
+ existing = path.read_text(encoding="utf-8").strip().lower()
+ if _INSTALL_ID_RE.fullmatch(existing):
+ return existing
+ except FileNotFoundError:
+ pass
+ except (OSError, UnicodeDecodeError):
+ return None
+
+ try:
+ root.mkdir(parents=True, exist_ok=True)
+ except OSError:
+ return None
+
+ try:
+ # Windows byte-range locks can report a same-process lock conflict
+ # instead of waiting for another thread. Serialize threads here, then
+ # retain the file lock as the cross-process publication fence.
+ with _INSTALL_ID_PUBLICATION_LOCK, _install_id_file_lock(root):
+ try:
+ existing = path.read_text(encoding="utf-8").strip().lower()
+ if _INSTALL_ID_RE.fullmatch(existing):
+ return existing
+ except FileNotFoundError:
+ pass
+ except (OSError, UnicodeDecodeError):
+ return None
+
+ minted = uuid.uuid4().hex
+ fd, tmp_name = tempfile.mkstemp(dir=str(root), prefix=".install_id-")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(minted + "\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp_name, path)
+ _fsync_directory(root)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp_name)
+ raise
+
+ committed = path.read_text(encoding="utf-8").strip().lower()
+ return committed if _INSTALL_ID_RE.fullmatch(committed) else None
+ except OSError:
+ return None
+
+
+def get_install_id(
+ *,
+ cache: dict[str, Optional[str]] | None = None,
+) -> Optional[str]:
+ """Return the process-cached stable id for the active Hermes root."""
+ root = get_default_hermes_root()
+ root_key = str(root)
+ target_cache = _INSTALL_ID_CACHE if cache is None else cache
+ cached = target_cache.get("value")
+ if cached and target_cache.get("root") in (None, root_key):
+ return cached
+
+ with _INSTALL_ID_LOCK:
+ cached = target_cache.get("value")
+ if cached and target_cache.get("root") in (None, root_key):
+ return cached
+ value = read_or_create_install_id(root)
+ if value:
+ target_cache["root"] = root_key
+ target_cache["value"] = value
+ return value
+
+
+__all__ = ["get_install_id", "read_or_create_install_id"]
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index b38d60b33c9..fab84d150a0 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -48,6 +48,7 @@ import urllib.parse
import zipfile
from hermes_cli._subprocess_compat import windows_detach_flags, windows_hide_flags
+from hermes_cli.install_identity import get_install_id as _shared_get_install_id
import urllib.request
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Tuple
@@ -3523,66 +3524,12 @@ _TOPOLOGY_CACHE_TTL = 10.0
# fact it reveals is "these addresses are the same box", which is the feature.
# It must never change across restarts/updates, so reads are cached for the
# process lifetime and the file is written once, atomically.
-_INSTALL_ID_FILENAME = "install_id"
-_INSTALL_ID_RE = re.compile(r"^[0-9a-f]{32}$")
-_INSTALL_ID_CACHE: Dict[str, Optional[str]] = {"value": None}
-_INSTALL_ID_LOCK = threading.Lock()
-
-
-def _read_or_create_install_id() -> Optional[str]:
- """Read (or mint + persist) the install id under the root Hermes home.
-
- Returns ``None`` only when the id can neither be read nor persisted (e.g.
- a read-only filesystem) — an unpersisted id would violate the stability
- contract, so callers omit the field rather than emit a churning value.
- """
- import uuid
-
- from hermes_constants import get_default_hermes_root
-
- root = get_default_hermes_root()
- path = root / _INSTALL_ID_FILENAME
- try:
- existing = path.read_text(encoding="utf-8").strip().lower()
- if _INSTALL_ID_RE.match(existing):
- return existing
- except FileNotFoundError:
- pass
- except (OSError, UnicodeDecodeError):
- return None
-
- minted = uuid.uuid4().hex
- try:
- root.mkdir(parents=True, exist_ok=True)
- # Atomic replace so a crash mid-write can't leave a truncated id that
- # would be regenerated (i.e. changed) on the next boot.
- fd, tmp_name = tempfile.mkstemp(dir=str(root), prefix=".install_id-")
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as handle:
- handle.write(minted + "\n")
- os.replace(tmp_name, path)
- except BaseException:
- with contextlib.suppress(OSError):
- os.unlink(tmp_name)
- raise
- except OSError:
- return None
- return minted
+_INSTALL_ID_CACHE: Dict[str, Optional[str]] = {"root": None, "value": None}
def get_install_id() -> Optional[str]:
- """Process-lifetime-cached stable install id (see _read_or_create_install_id)."""
- cached = _INSTALL_ID_CACHE["value"]
- if cached:
- return cached
- with _INSTALL_ID_LOCK:
- cached = _INSTALL_ID_CACHE["value"]
- if cached:
- return cached
- value = _read_or_create_install_id()
- if value:
- _INSTALL_ID_CACHE["value"] = value
- return value
+ """Process-lifetime-cached stable install id."""
+ return _shared_get_install_id(cache=_INSTALL_ID_CACHE)
# Serializes read-modify-write cycles over config.yaml for handlers that run
diff --git a/tests/gateway/test_hosted_rooms.py b/tests/gateway/test_hosted_rooms.py
new file mode 100644
index 00000000000..3c2fd8fe03b
--- /dev/null
+++ b/tests/gateway/test_hosted_rooms.py
@@ -0,0 +1,1018 @@
+"""Behavior tests for the gateway-hosted room event log."""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
+
+import pytest
+
+from gateway import hosted_rooms as rooms
+import hermes_state
+from hermes_state import SessionDB
+
+USER = {"kind": "user", "id": "desktop-user", "display_name": "User"}
+GATEWAY_A = {"kind": "gateway", "id": "gateway-a"}
+GATEWAY_B = {"kind": "gateway", "id": "gateway-b"}
+
+
+def _create_pre_actor_database(path) -> None:
+ conn = sqlite3.connect(path)
+ try:
+ conn.execute(
+ """CREATE TABLE hosted_rooms (
+ room_id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ members_json TEXT NOT NULL,
+ next_seq INTEGER NOT NULL,
+ revision INTEGER NOT NULL,
+ created_at REAL NOT NULL,
+ updated_at REAL NOT NULL,
+ disbanded_at REAL
+ )"""
+ )
+ conn.execute(
+ """CREATE TABLE hosted_room_events (
+ room_id TEXT NOT NULL,
+ seq INTEGER NOT NULL,
+ event_id TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ payload_json TEXT NOT NULL,
+ created_at REAL NOT NULL,
+ PRIMARY KEY (room_id, seq),
+ UNIQUE (room_id, event_id)
+ )"""
+ )
+ conn.execute(
+ """INSERT INTO hosted_rooms
+ VALUES ('room-1', 'Legacy', '[]', 2, 1, 1, 1, NULL)"""
+ )
+ conn.execute(
+ """INSERT INTO hosted_room_events
+ VALUES ('room-1', 1, 'legacy-event', 'message.created', '{}', 1)"""
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def _read_legacy_state(path: str) -> tuple[str, int]:
+ state = rooms.room_state(path, room_id="room-1")
+ return state["authority_gateway_id"], state["latest_seq"]
+
+
+def _create(db, room_id="room-1"):
+ return rooms.create_room(
+ db,
+ room_id=room_id,
+ name="Release room",
+ members=[{"profile": "ops", "handle": "ops"}],
+ authority_gateway_id="gateway-a",
+ now=10,
+ )
+
+
+def _append(db, **kwargs):
+ if kwargs.get("kind") == "message.user":
+ kwargs.setdefault("authority_gateway_id", "gateway-a")
+ kwargs.setdefault("authority_epoch", 1)
+ return rooms.append_event(db, **kwargs)
+
+
+def _disband(db, **kwargs):
+ kwargs.setdefault("expected_gateway_id", "gateway-a")
+ kwargs.setdefault("expected_epoch", 1)
+ return rooms.disband_room(db, **kwargs)
+
+
+def _assert_retired_identity_stays_reserved(db, room_id, *, fresh_id):
+ # Reopen the database to prove the reservation is durable rather than a
+ # process-local cache, while the heavier room/event payload is gone.
+ with sqlite3.connect(db) as conn:
+ assert (
+ conn.execute(
+ "SELECT 1 FROM hosted_rooms WHERE room_id=?", (room_id,)
+ ).fetchone()
+ is None
+ )
+ assert (
+ conn.execute(
+ "SELECT retired_at FROM hosted_room_retired_ids WHERE room_id=?",
+ (room_id,),
+ ).fetchone()
+ is not None
+ )
+
+ with pytest.raises(rooms.RoomConflictError, match="disbanded"):
+ _create(db, room_id)
+ with pytest.raises(rooms.RoomHistoryExpiredError) as send_error:
+ _append(
+ db,
+ room_id=room_id,
+ event_id="stale-send",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "stale"},
+ )
+ assert send_error.value.reason == "room_history_expired"
+ with pytest.raises(rooms.RoomHistoryExpiredError) as log_error:
+ rooms.read_events(db, room_id=room_id, include_disbanded=True)
+ assert log_error.value.reason == "room_history_expired"
+ repeated = _disband(db, room_id=room_id, now=999)
+ assert repeated == {
+ "room_id": room_id,
+ "disbanded_at": 20.0,
+ "idempotent": True,
+ "history_expired": True,
+ }
+
+ assert _create(db, fresh_id)["room_id"] == fresh_id
+
+
+def test_create_room_is_idempotent_but_conflicts_fail_closed(tmp_path):
+ db = tmp_path / "state.db"
+ first = _create(db)
+ second = _create(db)
+
+ assert first["idempotent"] is False
+ assert second["idempotent"] is True
+ assert first["room_id"] == second["room_id"] == "room-1"
+
+ with pytest.raises(rooms.RoomConflictError):
+ rooms.create_room(
+ db,
+ room_id="room-1",
+ name="A different room",
+ members=[],
+ authority_gateway_id="gateway-a",
+ )
+
+
+def test_concurrent_first_database_open_keeps_every_room(tmp_path):
+ db = tmp_path / "state.db"
+
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ created = list(pool.map(lambda index: _create(db, f"room-{index}"), range(16)))
+
+ assert {room["room_id"] for room in created} == {
+ f"room-{index}" for index in range(16)
+ }
+ assert len(rooms.list_rooms(db)) == 16
+
+
+def test_first_database_open_retries_only_transient_journal_lock(
+ tmp_path,
+ monkeypatch,
+):
+ original = hermes_state.apply_wal_with_fallback
+ attempts = 0
+
+ def transient_lock(conn, **kwargs):
+ nonlocal attempts
+ attempts += 1
+ if attempts < 3:
+ raise sqlite3.OperationalError("database is locked")
+ return original(conn, **kwargs)
+
+ monkeypatch.setattr(hermes_state, "apply_wal_with_fallback", transient_lock)
+
+ assert _create(tmp_path / "state.db")["room_id"] == "room-1"
+ assert attempts == 3
+
+
+def test_first_database_open_does_not_retry_other_journal_errors(
+ tmp_path,
+ monkeypatch,
+):
+ attempts = 0
+
+ def configured_delete_refusal(conn, **kwargs):
+ nonlocal attempts
+ attempts += 1
+ raise sqlite3.OperationalError(
+ "could not verify configured journal_mode=delete (database is locked)"
+ )
+
+ monkeypatch.setattr(
+ hermes_state,
+ "apply_wal_with_fallback",
+ configured_delete_refusal,
+ )
+
+ with pytest.raises(sqlite3.OperationalError, match="configured"):
+ _create(tmp_path / "state.db")
+ assert attempts == 1
+
+
+def test_room_state_exposes_authority_and_replay_cursor(tmp_path):
+ db = tmp_path / "state.db"
+ room = _create(db)
+
+ assert room["authority_gateway_id"] == "gateway-a"
+ assert room["authority_epoch"] == 1
+ assert rooms.room_state(db, room_id="room-1") == {
+ **room,
+ "latest_seq": 0,
+ }
+
+
+def test_authority_claim_fences_stale_gateway_events(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+
+ first = _append(
+ db,
+ room_id="room-1",
+ event_id="turn-1",
+ kind="turn.started",
+ actor=GATEWAY_A,
+ authority_gateway_id="gateway-a",
+ authority_epoch=1,
+ payload={"member": "ops"},
+ )
+ claimed = rooms.claim_authority(
+ db,
+ room_id="room-1",
+ expected_gateway_id="gateway-a",
+ expected_epoch=1,
+ new_gateway_id="gateway-b",
+ event_id="claim-gateway-b",
+ now=30,
+ )
+ retried = rooms.claim_authority(
+ db,
+ room_id="room-1",
+ expected_gateway_id="gateway-a",
+ expected_epoch=1,
+ new_gateway_id="gateway-b",
+ event_id="claim-gateway-b",
+ now=40,
+ )
+
+ assert claimed["authority_gateway_id"] == "gateway-b"
+ assert claimed["authority_epoch"] == 2
+ assert claimed["idempotent"] is False
+ assert claimed["claim_event"]["kind"] == "authority.claimed"
+ assert claimed["claim_event"]["authority_epoch"] == 2
+ assert claimed["claim_event"]["payload"] == {
+ "previous_gateway_id": "gateway-a",
+ "authority_gateway_id": "gateway-b",
+ "authority_epoch": 2,
+ }
+ assert retried["authority_epoch"] == 2
+ assert retried["idempotent"] is True
+ assert retried["claim_event"]["seq"] == claimed["claim_event"]["seq"]
+ assert retried["claim_event"]["idempotent"] is True
+ state = rooms.room_state(db, room_id="room-1")
+ assert state["authority_claim"]["event_id"] == "claim-gateway-b"
+ assert state["authority_claim"]["payload"]["previous_gateway_id"] == "gateway-a"
+
+ # An exact retry admitted before takeover stays idempotent and cannot
+ # produce a second side effect, even though its epoch is now stale.
+ repeated = _append(
+ db,
+ room_id="room-1",
+ event_id="turn-1",
+ kind="turn.started",
+ actor=GATEWAY_A,
+ authority_gateway_id="gateway-a",
+ authority_epoch=1,
+ payload={"member": "ops"},
+ )
+ assert repeated["seq"] == first["seq"]
+ assert repeated["idempotent"] is True
+
+ with pytest.raises(rooms.AuthorityConflictError, match="stale"):
+ _append(
+ db,
+ room_id="room-1",
+ event_id="turn-2-stale",
+ kind="turn.started",
+ actor=GATEWAY_A,
+ authority_gateway_id="gateway-a",
+ authority_epoch=1,
+ payload={"member": "ops"},
+ )
+
+ with pytest.raises(rooms.AuthorityConflictError, match="stale"):
+ _append(
+ db,
+ room_id="room-1",
+ event_id="member-2-stale",
+ kind="message.member",
+ actor={"kind": "member", "id": "ops"},
+ authority_gateway_id="gateway-a",
+ authority_epoch=1,
+ payload={"text": "stale result"},
+ )
+
+ current = _append(
+ db,
+ room_id="room-1",
+ event_id="turn-2-current",
+ kind="turn.started",
+ actor=GATEWAY_B,
+ authority_gateway_id="gateway-b",
+ authority_epoch=2,
+ payload={"member": "ops"},
+ )
+ assert current["authority_epoch"] == 2
+ current_member = _append(
+ db,
+ room_id="room-1",
+ event_id="member-2-current",
+ kind="message.member",
+ actor={"kind": "member", "id": "ops"},
+ authority_gateway_id="gateway-b",
+ authority_epoch=2,
+ payload={"text": "current result"},
+ )
+ assert current_member["authority_epoch"] == 2
+
+
+def test_concurrent_authority_claim_has_one_winner(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+
+ def claim(gateway_id):
+ try:
+ return rooms.claim_authority(
+ db,
+ room_id="room-1",
+ expected_gateway_id="gateway-a",
+ expected_epoch=1,
+ new_gateway_id=gateway_id,
+ event_id=f"claim-{gateway_id}",
+ )
+ except rooms.AuthorityConflictError:
+ return None
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ results = list(pool.map(claim, ["gateway-b", "gateway-c"]))
+
+ winners = [result for result in results if result is not None]
+ assert len(winners) == 1
+ assert winners[0]["authority_epoch"] == 2
+ assert rooms.room_state(db, room_id="room-1")["authority_gateway_id"] in {
+ "gateway-b",
+ "gateway-c",
+ }
+
+
+def test_retry_of_successful_but_superseded_claim_is_distinct(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+ rooms.claim_authority(
+ db,
+ room_id="room-1",
+ expected_gateway_id="gateway-a",
+ expected_epoch=1,
+ new_gateway_id="gateway-b",
+ event_id="claim-b",
+ )
+ rooms.claim_authority(
+ db,
+ room_id="room-1",
+ expected_gateway_id="gateway-b",
+ expected_epoch=2,
+ new_gateway_id="gateway-c",
+ event_id="claim-c",
+ )
+
+ with pytest.raises(rooms.AuthoritySupersededError, match="later superseded"):
+ rooms.claim_authority(
+ db,
+ room_id="room-1",
+ expected_gateway_id="gateway-a",
+ expected_epoch=1,
+ new_gateway_id="gateway-b",
+ event_id="claim-b",
+ )
+
+
+def test_authority_scoped_events_require_gateway_and_epoch(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+
+ with pytest.raises(rooms.HostedRoomError, match="authority_gateway_id"):
+ _append(
+ db,
+ room_id="room-1",
+ event_id="turn-1",
+ kind="member.unavailable",
+ actor=GATEWAY_A,
+ payload={"member": "ops"},
+ )
+
+ with pytest.raises(rooms.HostedRoomError, match="actor.id"):
+ _append(
+ db,
+ room_id="room-1",
+ event_id="turn-2",
+ kind="turn.started",
+ actor=GATEWAY_B,
+ authority_gateway_id="gateway-a",
+ authority_epoch=1,
+ payload={"member": "ops"},
+ )
+
+ with pytest.raises(rooms.HostedRoomError, match="authority_gateway_id"):
+ rooms.append_event(
+ db,
+ room_id="room-1",
+ event_id="message-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "hello"},
+ )
+
+ appended = _append(
+ db,
+ room_id="room-1",
+ event_id="message-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "hello"},
+ )
+ assert appended["authority_epoch"] == 1
+
+
+def test_append_is_idempotent_and_conflicting_event_id_is_rejected(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+
+ first = _append(
+ db,
+ room_id="room-1",
+ event_id="event-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "hello"},
+ now=20,
+ )
+ repeated = _append(
+ db,
+ room_id="room-1",
+ event_id="event-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "hello"},
+ now=30,
+ )
+
+ assert first["seq"] == repeated["seq"] == 1
+ assert repeated["idempotent"] is True
+ assert rooms.read_events(db, room_id="room-1")["latest_seq"] == 1
+
+ with pytest.raises(rooms.EventConflictError):
+ _append(
+ db,
+ room_id="room-1",
+ event_id="event-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "changed"},
+ )
+
+
+def test_since_seq_returns_ordered_deltas_and_stable_cursor(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+ for index in range(1, 5):
+ _append(
+ db,
+ room_id="room-1",
+ event_id=f"event-{index}",
+ kind="message.user",
+ actor=USER,
+ payload={"index": index},
+ now=20 + index,
+ )
+
+ first = rooms.read_events(db, room_id="room-1", since_seq=0, limit=2)
+ assert [event["seq"] for event in first["events"]] == [1, 2]
+ assert first == {
+ "events": first["events"],
+ "cursor": 2,
+ "latest_seq": 4,
+ "has_more": True,
+ }
+
+ second = rooms.read_events(
+ db,
+ room_id="room-1",
+ since_seq=first["cursor"],
+ limit=2,
+ )
+ assert [event["seq"] for event in second["events"]] == [3, 4]
+ assert second["cursor"] == 4
+ assert second["has_more"] is False
+
+ settled = rooms.read_events(db, room_id="room-1", since_seq=4)
+ assert settled["events"] == []
+ assert settled["cursor"] == settled["latest_seq"] == 4
+
+
+def test_room_log_survives_store_reopen(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+ _append(
+ db,
+ room_id="room-1",
+ event_id="event-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "persist me"},
+ )
+
+ assert rooms.list_rooms(db)[0]["name"] == "Release room"
+ replay = rooms.read_events(db, room_id="room-1")
+ assert replay["events"][0]["payload"] == {"text": "persist me"}
+
+
[email protected]("session_first", [True, False])
+def test_room_tables_coexist_with_session_db_schema(tmp_path, session_first):
+ db = tmp_path / "state.db"
+ if session_first:
+ SessionDB(db_path=db).close()
+
+ _create(db)
+ _append(
+ db,
+ room_id="room-1",
+ event_id="event-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "shared database"},
+ )
+
+ SessionDB(db_path=db).close()
+ replay = rooms.read_events(db, room_id="room-1")
+ assert replay["latest_seq"] == 1
+ assert replay["events"][0]["payload"]["text"] == "shared database"
+
+
+def test_concurrent_appends_allocate_one_monotonic_sequence(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+
+ def append(index):
+ return _append(
+ db,
+ room_id="room-1",
+ event_id=f"event-{index}",
+ kind="message.user",
+ actor=USER,
+ payload={"index": index},
+ )
+
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ results = list(pool.map(append, range(24)))
+
+ assert sorted(result["seq"] for result in results) == list(range(1, 25))
+ replay = rooms.read_events(db, room_id="room-1", limit=100)
+ assert [event["seq"] for event in replay["events"]] == list(range(1, 25))
+
+
+def test_rolled_back_append_does_not_consume_sequence(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+
+ conn = sqlite3.connect(db)
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ conn.execute(
+ """INSERT INTO hosted_room_events
+ (room_id, seq, event_id, kind, actor_json, payload_json, created_at)
+ VALUES ('room-1', 1, 'crash-event', 'message.user',
+ '{"id":"desktop-user","kind":"user"}', '{}', 20)"""
+ )
+ conn.execute("UPDATE hosted_rooms SET next_seq=2 WHERE room_id='room-1'")
+ conn.rollback()
+ finally:
+ conn.close()
+
+ event = _append(
+ db,
+ room_id="room-1",
+ event_id="after-restart",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "safe"},
+ )
+ assert event["seq"] == 1
+
+
+ ("kwargs", "message"),
+ [
+ ({"room_id": "../escape"}, "invalid room_id"),
+ ({"event_id": "event id"}, "invalid event_id"),
+ ({"kind": "Message Created"}, "invalid event kind"),
+ ({"kind": "directive.run"}, "cannot append"),
+ ({"actor": {"kind": "member", "id": "ops"}}, "cannot append"),
+ ({"payload": []}, "payload must be an object"),
+ ],
+)
+def test_invalid_event_contract_is_rejected(tmp_path, kwargs, message):
+ db = tmp_path / "state.db"
+ _create(db)
+ params = {
+ "room_id": "room-1",
+ "event_id": "event-1",
+ "kind": "message.user",
+ "actor": USER,
+ "payload": {},
+ }
+ params.update(kwargs)
+
+ with pytest.raises(rooms.HostedRoomError, match=message):
+ _append(db, **params)
+
+
+def test_unknown_room_and_invalid_cursor_fail_closed(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+
+ with pytest.raises(rooms.RoomNotFoundError):
+ rooms.read_events(db, room_id="missing")
+ with pytest.raises(rooms.HostedRoomError, match="since_seq"):
+ rooms.read_events(db, room_id="room-1", since_seq=-1)
+ with pytest.raises(rooms.HostedRoomError, match="ahead"):
+ rooms.read_events(db, room_id="room-1", since_seq=1)
+ with pytest.raises(rooms.HostedRoomError, match="limit"):
+ rooms.read_events(db, room_id="room-1", limit=0)
+
+
+def test_actor_is_part_of_event_idempotency_and_replay(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+ event = _append(
+ db,
+ room_id="room-1",
+ event_id="event-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "hello"},
+ )
+
+ assert event["actor"] == USER
+ assert rooms.read_events(db, room_id="room-1")["events"][0]["actor"] == USER
+
+ with pytest.raises(rooms.EventConflictError):
+ _append(
+ db,
+ room_id="room-1",
+ event_id="event-1",
+ kind="message.user",
+ actor={"kind": "user", "id": "another-user"},
+ payload={"text": "hello"},
+ )
+
+
+def test_disband_is_idempotent_and_room_id_cannot_be_reused(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+
+ first = _disband(db, room_id="room-1", now=50)
+ repeated = _disband(db, room_id="room-1", now=60)
+
+ assert first["room_id"] == "room-1"
+ assert first["disbanded_at"] == 50.0
+ assert first["idempotent"] is False
+ assert first["event"]["kind"] == "room.disbanded"
+ assert first["event"]["seq"] == 1
+ assert first["event"]["payload"] == {"room_id": "room-1"}
+ assert repeated["idempotent"] is True
+ assert repeated["event"]["seq"] == first["event"]["seq"]
+ assert rooms.list_rooms(db) == []
+ deleted = rooms.list_rooms(db, include_disbanded=True)
+ assert deleted[0]["disbanded_at"] == 50.0
+ assert deleted[0]["latest_seq"] == 1
+ state = rooms.room_state(db, room_id="room-1", include_disbanded=True)
+ assert state["disbanded_at"] == 50.0
+ assert state["latest_seq"] == 1
+ replay = rooms.read_events(db, room_id="room-1", include_disbanded=True)
+ assert [event["kind"] for event in replay["events"]] == ["room.disbanded"]
+ with pytest.raises(rooms.RoomConflictError):
+ _create(db)
+ with pytest.raises(rooms.RoomNotFoundError) as missing:
+ rooms.read_events(db, room_id="room-1")
+ assert not isinstance(missing.value, rooms.RoomHistoryExpiredError)
+
+
+def test_disband_rejects_stale_authority(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db)
+ rooms.claim_authority(
+ db,
+ room_id="room-1",
+ expected_gateway_id="gateway-a",
+ expected_epoch=1,
+ new_gateway_id="gateway-b",
+ event_id="claim-b",
+ )
+
+ with pytest.raises(rooms.AuthorityConflictError, match="stale"):
+ _disband(db, room_id="room-1")
+
+ tombstone = _disband(
+ db,
+ room_id="room-1",
+ expected_gateway_id="gateway-b",
+ expected_epoch=2,
+ )
+ assert tombstone["event"]["authority_epoch"] == 2
+
+
+def test_room_log_pages_are_bounded_by_serialized_event_bytes(tmp_path, monkeypatch):
+ db = tmp_path / "state.db"
+ _create(db)
+ for index in range(4):
+ _append(
+ db,
+ room_id="room-1",
+ event_id=f"message-{index}",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "x" * 180, "index": index},
+ )
+
+ one_event = rooms.read_events(db, room_id="room-1", limit=1)
+ budget = len(
+ json.dumps(one_event, ensure_ascii=False, separators=(",", ":")).encode(
+ "utf-8"
+ )
+ ) + 1
+ monkeypatch.setattr(rooms, "MAX_LOG_PAGE_BYTES", budget)
+
+ first = rooms.read_events(db, room_id="room-1", limit=4)
+ assert len(first["events"]) == 1
+ assert first["has_more"] is True
+ second = rooms.read_events(
+ db,
+ room_id="room-1",
+ since_seq=first["cursor"],
+ limit=4,
+ )
+ assert second["events"][0]["seq"] == first["cursor"] + 1
+
+
+def test_room_log_pages_bound_multibyte_utf8_and_advance_cursor(tmp_path, monkeypatch):
+ db = tmp_path / "state.db"
+ _create(db)
+ for index in range(3):
+ _append(
+ db,
+ room_id="room-1",
+ event_id=f"unicode-{index}",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "😀漢é" * 40, "index": index},
+ )
+
+ def page_bytes(page):
+ return len(
+ json.dumps(page, ensure_ascii=False, separators=(",", ":")).encode(
+ "utf-8"
+ )
+ )
+
+ one_event_pages = [
+ rooms.read_events(db, room_id="room-1", since_seq=index, limit=1)
+ for index in range(3)
+ ]
+ budget = max(page_bytes(page) for page in one_event_pages) + 1
+ monkeypatch.setattr(rooms, "MAX_LOG_PAGE_BYTES", budget)
+ cursor = 0
+ replayed = []
+ while True:
+ page = rooms.read_events(db, room_id="room-1", since_seq=cursor, limit=3)
+ assert page["events"]
+ assert page_bytes(page) <= budget
+ replayed.extend(page["events"])
+ assert page["cursor"] > cursor
+ cursor = page["cursor"]
+ if not page["has_more"]:
+ break
+
+ assert [event["seq"] for event in replayed] == [1, 2, 3]
+
+
+def test_room_log_page_bound_includes_json_structure_overhead(tmp_path, monkeypatch):
+ db = tmp_path / "state.db"
+ _create(db)
+ for index in range(20):
+ _append(
+ db,
+ room_id="room-1",
+ event_id=f"small-{index:02d}",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "ok", "index": index},
+ )
+
+ budget = 1_000
+ monkeypatch.setattr(rooms, "MAX_LOG_PAGE_BYTES", budget)
+ cursor = 0
+ replayed = []
+ while True:
+ page = rooms.read_events(db, room_id="room-1", since_seq=cursor, limit=20)
+ assert page["events"]
+ assert len(
+ json.dumps(page, ensure_ascii=False, separators=(",", ":")).encode(
+ "utf-8"
+ )
+ ) <= budget
+ replayed.extend(page["events"])
+ assert page["cursor"] > cursor
+ cursor = page["cursor"]
+ if not page["has_more"]:
+ break
+
+ assert [event["seq"] for event in replayed] == list(range(1, 21))
+
+
+def test_active_rooms_and_event_storage_are_bounded(tmp_path, monkeypatch):
+ db = tmp_path / "state.db"
+ _create(db)
+ monkeypatch.setattr(rooms, "MAX_ACTIVE_ROOMS", 1)
+
+ with pytest.raises(rooms.HostedRoomError, match="too many active"):
+ _create(db, "room-2")
+
+ _disband(db, room_id="room-1", now=20)
+ _create(db, "room-2")
+ first = _append(
+ db,
+ room_id="room-2",
+ event_id="message-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "first"},
+ )
+ with sqlite3.connect(db) as conn:
+ current_bytes = conn.execute(
+ "SELECT event_bytes FROM hosted_rooms WHERE room_id='room-2'"
+ ).fetchone()[0]
+ monkeypatch.setattr(rooms, "MAX_ROOM_EVENT_BYTES", current_bytes)
+
+ with pytest.raises(rooms.HostedRoomError, match="storage limit"):
+ _append(
+ db,
+ room_id="room-2",
+ event_id="message-2",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "second"},
+ )
+ assert rooms.read_events(db, room_id="room-2")["events"] == [first]
+ assert _disband(db, room_id="room-2")["event"]["kind"] == "room.disbanded"
+
+
+def test_room_listing_is_paged_and_old_tombstones_are_pruned(tmp_path, monkeypatch):
+ db = tmp_path / "state.db"
+ monkeypatch.setattr(rooms, "MAX_DISBANDED_ROOM_TOMBSTONES", 1)
+ for index in range(3):
+ room_id = f"room-{index}"
+ _create(db, room_id)
+ if index < 2:
+ _disband(db, room_id=room_id, now=20 + index)
+
+ first_page = rooms.list_rooms(db, include_disbanded=True, limit=1)
+ second_page = rooms.list_rooms(
+ db,
+ include_disbanded=True,
+ limit=1,
+ offset=1,
+ )
+
+ assert [room["room_id"] for room in first_page + second_page] == [
+ "room-1",
+ "room-2",
+ ]
+ with pytest.raises(rooms.RoomNotFoundError):
+ rooms.room_state(db, room_id="room-0", include_disbanded=True)
+ _assert_retired_identity_stays_reserved(db, "room-0", fresh_id="room-new")
+
+
+def test_retention_pruning_keeps_retired_room_id_reserved(tmp_path):
+ db = tmp_path / "state.db"
+ _create(db, "room-old")
+ _disband(db, room_id="room-old", now=20)
+
+ assert (
+ rooms.prune_disbanded_rooms(
+ db,
+ now=20 + rooms.DISBANDED_ROOM_RETENTION_SECONDS + 1,
+ )
+ == 1
+ )
+
+ _assert_retired_identity_stays_reserved(db, "room-old", fresh_id="room-new")
+
+
+def test_byte_pressure_pruning_keeps_retired_room_id_reserved(
+ tmp_path,
+ monkeypatch,
+):
+ db = tmp_path / "state.db"
+ _create(db, "room-full")
+ monkeypatch.setattr(rooms, "MAX_GATEWAY_EVENT_BYTES", 0)
+
+ _disband(db, room_id="room-full", now=20)
+
+ _assert_retired_identity_stays_reserved(db, "room-full", fresh_id="room-new")
+
+
+def test_pre_actor_draft_database_migrates_with_explicit_legacy_identity(tmp_path):
+ db = tmp_path / "state.db"
+ _create_pre_actor_database(db)
+
+ replay = rooms.read_events(db, room_id="room-1")
+ assert replay["events"][0]["actor"] == {"kind": "system", "id": "legacy"}
+ state = rooms.room_state(db, room_id="room-1")
+ assert state["authority_gateway_id"] == "legacy"
+ assert state["authority_epoch"] == 1
+ adopted = rooms.create_room(
+ db,
+ room_id="room-1",
+ name="Legacy",
+ members=[],
+ authority_gateway_id="gateway-a",
+ now=2,
+ )
+ assert adopted["authority_gateway_id"] == "gateway-a"
+ assert adopted["authority_epoch"] == 2
+ assert adopted["adopted"] is True
+ assert adopted["claim_event"]["seq"] == 2
+ assert adopted["claim_event"]["payload"]["previous_gateway_id"] == "legacy"
+
+
+def test_migration_reserves_existing_disbanded_room_id_before_pruning(tmp_path):
+ db = tmp_path / "state.db"
+ _create_pre_actor_database(db)
+ with sqlite3.connect(db) as conn:
+ conn.execute("UPDATE hosted_rooms SET disbanded_at=20 WHERE room_id='room-1'")
+ conn.commit()
+
+ assert (
+ rooms.prune_disbanded_rooms(
+ db,
+ now=20 + rooms.DISBANDED_ROOM_RETENTION_SECONDS + 1,
+ )
+ == 1
+ )
+
+ _assert_retired_identity_stays_reserved(db, "room-1", fresh_id="room-new")
+
+
+def test_draft_schema_migration_is_safe_across_processes(tmp_path):
+ db = tmp_path / "state.db"
+ _create_pre_actor_database(db)
+
+ with ProcessPoolExecutor(max_workers=4) as pool:
+ results = list(pool.map(_read_legacy_state, [str(db)] * 4))
+
+ assert results == [("legacy", 1)] * 4
+ replay = rooms.read_events(db, room_id="room-1")
+ assert replay["events"][0]["actor"] == {"kind": "system", "id": "legacy"}
+
+
+def test_interrupted_draft_schema_migration_rolls_back_atomically(
+ tmp_path,
+ monkeypatch,
+):
+ db = tmp_path / "state.db"
+ _create_pre_actor_database(db)
+ original = rooms._initialize_schema
+
+ def interrupt_after_first_alter(conn):
+ conn.execute(
+ "ALTER TABLE hosted_rooms "
+ "ADD COLUMN authority_gateway_id TEXT NOT NULL DEFAULT 'legacy'"
+ )
+ raise RuntimeError("simulated migration interruption")
+
+ monkeypatch.setattr(rooms, "_initialize_schema", interrupt_after_first_alter)
+ with pytest.raises(RuntimeError, match="simulated migration interruption"):
+ rooms.list_rooms(db)
+ with sqlite3.connect(db) as conn:
+ columns = {row[1] for row in conn.execute("PRAGMA table_info(hosted_rooms)")}
+ assert "authority_gateway_id" not in columns
+
+ monkeypatch.setattr(rooms, "_initialize_schema", original)
+ assert rooms.room_state(db, room_id="room-1")["authority_gateway_id"] == "legacy"
+
+
+def test_gateway_event_budget_leaves_pre_update_snapshot_headroom():
+ from hermes_cli import update_cmd
+
+ # SQLite stores room ids and index entries beyond the logical payload
+ # accounting, while session data shares the same file. Keep at least an
+ # order-of-magnitude safety margin below the physical snapshot cutoff.
+ assert (
+ rooms.MAX_GATEWAY_EVENT_BYTES * 32
+ <= update_cmd._PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE
+ )
diff --git a/tests/hermes_cli/test_install_identity.py b/tests/hermes_cli/test_install_identity.py
new file mode 100644
index 00000000000..218b5156cea
--- /dev/null
+++ b/tests/hermes_cli/test_install_identity.py
@@ -0,0 +1,112 @@
+from concurrent.futures import ThreadPoolExecutor
+import multiprocessing
+from pathlib import Path
+import time
+
+from gateway.hosted_rooms import local_authority_gateway_id
+import hermes_cli.install_identity as install_identity
+from hermes_cli.install_identity import read_or_create_install_id
+
+
+def _race_first_install_id(
+ root_value,
+ minted,
+ results,
+ start_barrier=None,
+ writer_entered=None,
+ release_writer=None,
+):
+ root = Path(root_value)
+ install_identity.uuid.uuid4 = lambda: type("FixedUuid", (), {"hex": minted})()
+ if start_barrier is not None:
+ start_barrier.wait(timeout=10)
+ if writer_entered is not None:
+ original_mkstemp = install_identity.tempfile.mkstemp
+
+ def held_mkstemp(*args, **kwargs):
+ writer_entered.set()
+ assert release_writer.wait(timeout=10)
+ return original_mkstemp(*args, **kwargs)
+
+ install_identity.tempfile.mkstemp = held_mkstemp
+ results.put(read_or_create_install_id(root))
+
+
+def test_concurrent_first_use_returns_one_persisted_identity(tmp_path):
+ with ThreadPoolExecutor(max_workers=16) as executor:
+ values = list(executor.map(lambda _: read_or_create_install_id(tmp_path), range(64)))
+
+ assert len(set(values)) == 1
+ assert values[0]
+ assert (tmp_path / "install_id").read_text(encoding="utf-8").strip() == values[0]
+
+
+def test_independent_first_callers_return_the_single_committed_identity(tmp_path, monkeypatch):
+ context = multiprocessing.get_context("spawn")
+ results = context.Queue()
+ writer_entered = context.Event()
+ release_writer = context.Event()
+ winner = context.Process(
+ target=_race_first_install_id,
+ args=(
+ str(tmp_path),
+ "a" * 32,
+ results,
+ None,
+ writer_entered,
+ release_writer,
+ ),
+ )
+ loser = context.Process(
+ target=_race_first_install_id,
+ args=(str(tmp_path), "b" * 32, results),
+ )
+
+ winner.start()
+ assert writer_entered.wait(timeout=10)
+ loser.start()
+ time.sleep(0.25)
+ assert loser.is_alive()
+ release_writer.set()
+ processes = [winner, loser]
+ for process in processes:
+ process.join(timeout=15)
+ assert process.exitcode == 0
+
+ returned = [results.get(timeout=2) for _ in processes]
+ persisted = (tmp_path / "install_id").read_text(encoding="utf-8").strip()
+
+ assert returned == [persisted, persisted]
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(
+ install_identity,
+ "_INSTALL_ID_CACHE",
+ {"root": None, "value": None},
+ )
+ assert local_authority_gateway_id() == f"install:{persisted}"
+
+
+def test_concurrent_corrupt_file_repair_returns_one_committed_identity(tmp_path):
+ (tmp_path / "install_id").write_text("corrupt\n", encoding="utf-8")
+ context = multiprocessing.get_context("spawn")
+ barrier = context.Barrier(2)
+ results = context.Queue()
+ processes = [
+ context.Process(
+ target=_race_first_install_id,
+ args=(str(tmp_path), value, results, barrier),
+ )
+ for value in ("a" * 32, "b" * 32)
+ ]
+
+ for process in processes:
+ process.start()
+ for process in processes:
+ process.join(timeout=15)
+ assert process.exitcode == 0
+
+ returned = [results.get(timeout=2) for _ in processes]
+ persisted = (tmp_path / "install_id").read_text(encoding="utf-8").strip()
+
+ assert returned == [persisted, persisted]
diff --git a/tests/tui_gateway/test_groups_methods.py b/tests/tui_gateway/test_groups_methods.py
new file mode 100644
index 00000000000..9f58b612f5f
--- /dev/null
+++ b/tests/tui_gateway/test_groups_methods.py
@@ -0,0 +1,393 @@
+"""Tests for the gateway-hosted ``groups.*`` JSON-RPC contract."""
+
+from __future__ import annotations
+
+import pytest
+
+import tui_gateway.server as srv
+
+
+def home(tmp_path, monkeypatch):
+ path = tmp_path / ".hermes"
+ path.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(path))
+ return path
+
+
+def _result(envelope):
+ assert "error" not in envelope, envelope
+ return envelope["result"]
+
+
+def _server_authority():
+ from gateway.hosted_rooms import local_authority_gateway_id
+
+ return local_authority_gateway_id()
+
+
+def _create_room():
+ return _result(
+ srv._methods["groups.create"](
+ 1,
+ {
+ "room_id": "room-1",
+ "name": "Release room",
+ "members": [{"profile": "ops", "handle": "ops"}],
+ "authority_gateway_id": "gateway-a",
+ },
+ )
+ )["room"]
+
+
+def test_capabilities_are_honest_about_the_driver_boundary(home):
+ result = _result(srv._methods["groups.capabilities"](1, {}))
+
+ assert result["protocol_version"] == 2
+ assert result["driver"] is False
+ assert result["authority_gateway_id"] == _server_authority()
+ assert "authority_epoch" in result["features"]
+ assert "coordinator_fencing" in result["features"]
+ assert "monotonic_log" in result["features"]
+ assert "groups.state" in result["methods"]
+ assert "groups.send" in result["methods"]
+ assert "groups.send" in srv._LONG_HANDLERS
+
+
+def test_create_list_send_and_log_roundtrip(home):
+ room = _create_room()
+ assert room["idempotent"] is False
+
+ listed = _result(srv._methods["groups.list"](2, {}))
+ assert [item["room_id"] for item in listed["rooms"]] == ["room-1"]
+ state = _result(srv._methods["groups.state"](3, {"room_id": "room-1"}))
+ assert state["room"]["authority_gateway_id"] == _server_authority()
+ assert state["room"]["authority_epoch"] == 1
+ assert state["room"]["latest_seq"] == 0
+
+ sent = _result(
+ srv._methods["groups.send"](
+ 4,
+ {
+ "room_id": "room-1",
+ "event_id": "event-1",
+ "actor": {"kind": "user", "id": "desktop-user"},
+ "payload": {"text": "hello"},
+ },
+ )
+ )
+ assert sent["accepted"] is True
+ assert sent["driver_started"] is False
+ assert sent["event"]["seq"] == 1
+ assert sent["event"]["kind"] == "message.user"
+ assert sent["event"]["actor"] == {"kind": "user", "id": "desktop"}
+
+ replay = _result(
+ srv._methods["groups.log"](
+ 5,
+ {"room_id": "room-1", "since_seq": 0},
+ )
+ )
+ assert replay["latest_seq"] == replay["cursor"] == 1
+ assert replay["events"][0]["payload"] == {"text": "hello"}
+
+
+def test_groups_list_returns_bounded_pages(home):
+ _create_room()
+ _result(
+ srv._methods["groups.create"](
+ 2,
+ {
+ "room_id": "room-2",
+ "name": "Second room",
+ "members": [
+ {
+ "member_id": "default",
+ "profile": "default",
+ "handle": "hermes",
+ },
+ {"member_id": "ops", "profile": "ops", "handle": "ops"},
+ ],
+ },
+ )
+ )
+
+ first = _result(srv._methods["groups.list"](3, {"limit": 1}))
+ second = _result(
+ srv._methods["groups.list"](
+ 4,
+ {"limit": 1, "offset": first["next_offset"]},
+ )
+ )
+
+ assert first["next_offset"] == 1
+ assert second["next_offset"] == 2
+ assert {first["rooms"][0]["room_id"], second["rooms"][0]["room_id"]} == {
+ "room-1",
+ "room-2",
+ }
+ final = _result(srv._methods["groups.list"](5, {"limit": 1, "offset": 2}))
+ assert final["rooms"] == []
+ assert final["next_offset"] is None
+
+
+def test_rpc_retry_is_idempotent_and_conflict_is_visible(home):
+ _create_room()
+ params = {
+ "room_id": "room-1",
+ "event_id": "event-1",
+ "actor": {"kind": "user", "id": "desktop-user"},
+ "payload": {"text": "hello"},
+ }
+ first = _result(srv._methods["groups.send"](2, params))
+ repeated = _result(srv._methods["groups.send"](3, params))
+
+ assert first["event"]["seq"] == repeated["event"]["seq"] == 1
+ assert first["client_event_id"] == repeated["client_event_id"] == "event-1"
+ assert first["event"]["event_id"].startswith("user:")
+ assert repeated["event"]["idempotent"] is True
+
+ conflict = srv._methods["groups.send"](
+ 4,
+ {**params, "payload": {"text": "different"}},
+ )
+ assert conflict["error"]["code"] == 4111
+ assert "different content" in conflict["error"]["message"]
+
+
+def test_foreign_authority_cannot_send_or_disband(home):
+ from gateway.hosted_rooms import (
+ claim_authority,
+ default_db_path,
+ list_rooms,
+ read_events,
+ )
+
+ _create_room()
+ claim_authority(
+ default_db_path(),
+ room_id="room-1",
+ expected_gateway_id=_server_authority(),
+ expected_epoch=1,
+ new_gateway_id="foreign-gateway",
+ event_id="claim-foreign",
+ )
+ before = read_events(default_db_path(), room_id="room-1")
+
+ sent = srv._methods["groups.send"](
+ 2,
+ {
+ "room_id": "room-1",
+ "event_id": "stale-send",
+ "payload": {"text": "must not land"},
+ },
+ )
+ disbanded = srv._methods["groups.disband"](3, {"room_id": "room-1"})
+
+ assert sent["error"]["code"] == 4111
+ assert sent["error"]["data"] == {"reason": "authority_conflict"}
+ assert disbanded["error"]["code"] == 4113
+ assert disbanded["error"]["data"] == {"reason": "authority_conflict"}
+ assert read_events(default_db_path(), room_id="room-1") == before
+ assert list_rooms(default_db_path())[0]["room_id"] == "room-1"
+
+
+def test_client_event_id_cannot_squat_disband_receipt(home):
+ _create_room()
+ sent = _result(
+ srv._methods["groups.send"](
+ 2,
+ {
+ "room_id": "room-1",
+ "event_id": "system:room-disbanded",
+ "payload": {"text": "still a user message"},
+ },
+ )
+ )
+
+ assert sent["client_event_id"] == "system:room-disbanded"
+ assert sent["event"]["event_id"].startswith("user:")
+ assert sent["event"]["event_id"] != "system:room-disbanded"
+ first = _result(srv._methods["groups.disband"](3, {"room_id": "room-1"}))
+ repeated = _result(srv._methods["groups.disband"](4, {"room_id": "room-1"}))
+ assert first["tombstone"]["event"]["event_id"] == "system:room-disbanded"
+ assert repeated["tombstone"]["idempotent"] is True
+
+ replay = _result(
+ srv._methods["groups.log"](
+ 5,
+ {"room_id": "room-1", "include_disbanded": True},
+ )
+ )
+ assert [event["kind"] for event in replay["events"]] == [
+ "message.user",
+ "room.disbanded",
+ ]
+
+
+def test_send_does_not_trust_client_supplied_actor_identity(home):
+ _create_room()
+ sent = _result(
+ srv._methods["groups.send"](
+ 2,
+ {
+ "room_id": "room-1",
+ "event_id": "event-1",
+ "actor": {"kind": "user", "id": "spoofed-user"},
+ "payload": {"text": "hello"},
+ },
+ )
+ )
+
+ assert sent["event"]["actor"] == {"kind": "user", "id": "desktop"}
+
+
+def test_create_ignores_client_supplied_authority_identity(home):
+ created = _result(
+ srv._methods["groups.create"](
+ 1,
+ {"room_id": "legacy-room", "name": "Legacy", "members": []},
+ )
+ )["room"]
+ retried = _result(
+ srv._methods["groups.create"](
+ 2,
+ {
+ "room_id": "legacy-room",
+ "name": "Legacy",
+ "members": [],
+ "authority_gateway_id": "spoofed-gateway",
+ },
+ )
+ )["room"]
+
+ assert created["authority_gateway_id"] == _server_authority()
+ assert retried["authority_gateway_id"] == _server_authority()
+ assert retried["idempotent"] is True
+
+
+def test_legacy_room_adoption_emits_one_lineage_receipt(home):
+ from gateway.hosted_rooms import create_room, default_db_path
+
+ members = [{"profile": "ops", "handle": "ops"}]
+ create_room(
+ default_db_path(),
+ room_id="legacy-room",
+ name="Legacy",
+ members=members,
+ authority_gateway_id="legacy",
+ now=1,
+ )
+
+ adopted = _result(
+ srv._methods["groups.create"](
+ 2,
+ {"room_id": "legacy-room", "name": "Legacy", "members": members},
+ )
+ )["room"]
+ state = _result(
+ srv._methods["groups.state"](3, {"room_id": "legacy-room"})
+ )["room"]
+
+ assert adopted["adopted"] is True
+ assert adopted["authority_gateway_id"] == _server_authority()
+ assert adopted["authority_epoch"] == 2
+ assert adopted["claim_event"]["payload"] == {
+ "previous_gateway_id": "legacy",
+ "authority_gateway_id": _server_authority(),
+ "authority_epoch": 2,
+ }
+ assert state["authority_claim"]["event_id"] == "system:authority-adopted"
+ assert state["latest_seq"] == 1
+
+
+ ("method_name", "params"),
+ [
+ (
+ "groups.create",
+ {
+ "room_id": "",
+ "name": "x",
+ "members": [],
+ "authority_gateway_id": "gateway-a",
+ },
+ ),
+ (
+ "groups.send",
+ {
+ "room_id": "missing",
+ "event_id": "event-1",
+ "actor": {"kind": "user", "id": "desktop-user"},
+ "payload": {},
+ },
+ ),
+ ("groups.log", {"room_id": "missing", "since_seq": 0}),
+ ],
+)
+def test_invalid_or_unknown_room_returns_contract_error(home, method_name, params):
+ result = srv._methods[method_name](1, params)
+ assert result["error"]["code"] in {4110, 4111, 4112}
+
+
+def test_disband_tombstones_room(home):
+ _create_room()
+ first = _result(srv._methods["groups.disband"](3, {"room_id": "room-1"}))
+ repeated = _result(srv._methods["groups.disband"](4, {"room_id": "room-1"}))
+ assert first["tombstone"]["idempotent"] is False
+ assert repeated["tombstone"]["idempotent"] is True
+ assert _result(srv._methods["groups.list"](5, {}))["rooms"] == []
+ deleted = _result(
+ srv._methods["groups.list"](6, {"include_disbanded": True})
+ )["rooms"]
+ assert deleted[0]["disbanded_at"] == first["tombstone"]["disbanded_at"]
+ replay = _result(
+ srv._methods["groups.log"](
+ 7,
+ {"room_id": "room-1", "include_disbanded": True},
+ )
+ )
+ assert [event["kind"] for event in replay["events"]] == ["room.disbanded"]
+
+
+def test_pruned_room_send_and_log_report_expired_history(home, monkeypatch):
+ from gateway import hosted_rooms
+
+ _create_room()
+ monkeypatch.setattr(hosted_rooms, "MAX_DISBANDED_ROOM_TOMBSTONES", 0)
+ _result(srv._methods["groups.disband"](2, {"room_id": "room-1"}))
+ repeated = _result(
+ srv._methods["groups.disband"](3, {"room_id": "room-1"})
+ )["tombstone"]
+ assert repeated["idempotent"] is True
+ assert repeated["history_expired"] is True
+
+ sent = srv._methods["groups.send"](
+ 4,
+ {
+ "room_id": "room-1",
+ "event_id": "stale-send",
+ "payload": {"text": "stale"},
+ },
+ )
+ logged = srv._methods["groups.log"](
+ 5,
+ {"room_id": "room-1", "include_disbanded": True},
+ )
+
+ assert sent["error"]["data"] == {"reason": "room_history_expired"}
+ assert logged["error"]["data"] == {"reason": "room_history_expired"}
+ assert "permanently retired" in sent["error"]["message"]
+
+ recreated = srv._methods["groups.create"](
+ 6,
+ {"room_id": "room-1", "name": "Replacement", "members": []},
+ )
+ assert recreated["error"]["code"] == 4110
+ created = _result(
+ srv._methods["groups.create"](
+ 7,
+ {"room_id": "room-new", "name": "Fresh", "members": []},
+ )
+ )
+ assert created["room"]["room_id"] == "room-new"
diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.py
index b1baa40964f..cc5552a43c6 100644
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@ -212,3 +212,7 @@ def _(rid, params: dict) -> dict:
def register(server) -> None:
_registry.install(server)
+ from . import methods_groups
+
+ methods_groups.register(server)
+ server._LONG_HANDLERS = server._LONG_HANDLERS | methods_groups.LONG_HANDLERS
diff --git a/tui_gateway/methods_groups.py b/tui_gateway/methods_groups.py
new file mode 100644
index 00000000000..c2b6ecb4e9f
--- /dev/null
+++ b/tui_gateway/methods_groups.py
@@ -0,0 +1,266 @@
+"""Hosted-room JSON-RPC contract.
+
+These methods expose durable room identity and an append-only, monotonic room
+log. They deliberately do not drive Bot turns yet. ``groups.capabilities``
+makes that boundary machine-readable so a hosted-aware Desktop cannot mistake
+the log prototype for a complete gateway-side orchestrator.
+"""
+
+from .method_ctx import HandlerRegistry
+
+_registry = HandlerRegistry()
+method = _registry.method
+
+LONG_HANDLERS = frozenset({
+ "groups.list",
+ "groups.capabilities",
+ "groups.create",
+ "groups.state",
+ "groups.send",
+ "groups.log",
+ "groups.disband",
+})
+
+
+@method("groups.capabilities")
+def _(rid, params: dict) -> dict:
+ """Describe the hosted-room protocol implemented by this gateway."""
+ from gateway.hosted_rooms import (
+ MAX_LOG_LIMIT,
+ PROTOCOL_VERSION,
+ local_authority_gateway_id,
+ )
+
+ return _ok(
+ rid,
+ {
+ "protocol_version": PROTOCOL_VERSION,
+ "driver": False,
+ "authority_gateway_id": local_authority_gateway_id(),
+ "features": [
+ "authority_epoch",
+ "coordinator_fencing",
+ "room_identity",
+ "monotonic_log",
+ "idempotent_send",
+ "replayable_disband",
+ "typed_events",
+ "actor_identity",
+ ],
+ "methods": [
+ "groups.capabilities",
+ "groups.list",
+ "groups.create",
+ "groups.state",
+ "groups.send",
+ "groups.log",
+ "groups.disband",
+ ],
+ "max_log_limit": MAX_LOG_LIMIT,
+ },
+ )
+
+
+@method("groups.list")
+def _(rid, params: dict) -> dict:
+ """List rooms hosted by this gateway."""
+ try:
+ from gateway.hosted_rooms import (
+ MAX_ROOM_LIST_LIMIT,
+ default_db_path,
+ list_rooms,
+ )
+
+ limit = params.get("limit", MAX_ROOM_LIST_LIMIT)
+ offset = params.get("offset", 0)
+ rooms = list_rooms(
+ default_db_path(),
+ include_disbanded=params.get("include_disbanded") is True,
+ limit=limit,
+ offset=offset,
+ )
+
+ return _ok(
+ rid,
+ {
+ "rooms": rooms,
+ "next_offset": offset + limit if len(rooms) == limit else None,
+ },
+ )
+ except Exception as exc:
+ return _err(rid, 5110, str(exc))
+
+
+@method("groups.create")
+def _(rid, params: dict) -> dict:
+ """Create a hosted room idempotently.
+
+ Required params: ``room_id``, ``name``, and ``members``. Authority is
+ derived from this gateway's stable install identity, never from the client.
+ """
+ from gateway.hosted_rooms import (
+ HostedRoomError,
+ create_room,
+ default_db_path,
+ local_authority_gateway_id,
+ )
+
+ try:
+ room = create_room(
+ default_db_path(),
+ room_id=params.get("room_id"),
+ name=params.get("name"),
+ members=params.get("members"),
+ authority_gateway_id=local_authority_gateway_id(),
+ )
+ return _ok(rid, {"room": room})
+ except HostedRoomError as exc:
+ reason = getattr(exc, "reason", None)
+ return _err(rid, 4110, str(exc), {"reason": reason} if reason else None)
+ except Exception as exc:
+ return _err(rid, 5111, str(exc))
+
+
+@method("groups.state")
+def _(rid, params: dict) -> dict:
+ """Return one hosted room's replay cursor and fenced authority state."""
+ from gateway.hosted_rooms import HostedRoomError, default_db_path, room_state
+
+ try:
+ return _ok(
+ rid,
+ {
+ "room": room_state(
+ default_db_path(),
+ room_id=params.get("room_id"),
+ include_disbanded=params.get("include_disbanded") is True,
+ )
+ },
+ )
+ except HostedRoomError as exc:
+ reason = getattr(exc, "reason", None)
+ return _err(rid, 4114, str(exc), {"reason": reason} if reason else None)
+ except Exception as exc:
+ return _err(rid, 5115, str(exc))
+
+
+@method("groups.send")
+def _(rid, params: dict) -> dict:
+ """Append one typed event to a hosted room idempotently.
+
+ Required params: ``room_id``, ``event_id``, and object ``payload``. Only
+ inert ``message.user`` events are accepted through this client-facing
+ method. The actor is server-owned rather than trusted from params.
+ Admission is durable; no Bot turn is started by this slice.
+ """
+ from gateway.hosted_rooms import (
+ AuthorityConflictError,
+ HostedRoomError,
+ append_event,
+ default_db_path,
+ local_authority_gateway_id,
+ room_state,
+ user_event_id,
+ )
+
+ try:
+ room = room_state(default_db_path(), room_id=params.get("room_id"))
+ local_gateway_id = local_authority_gateway_id()
+ if str(room["authority_gateway_id"]) != local_gateway_id:
+ raise AuthorityConflictError(
+ "This Group Chat is managed by another gateway."
+ )
+ client_event_id = params.get("event_id")
+ event = append_event(
+ default_db_path(),
+ room_id=params.get("room_id"),
+ event_id=user_event_id(client_event_id),
+ kind="message.user",
+ actor={"kind": "user", "id": "desktop"},
+ payload=params.get("payload"),
+ authority_gateway_id=local_gateway_id,
+ authority_epoch=int(room["authority_epoch"]),
+ )
+ return _ok(
+ rid,
+ {
+ "event": event,
+ "client_event_id": client_event_id,
+ "accepted": True,
+ "driver_started": False,
+ },
+ )
+ except HostedRoomError as exc:
+ reason = getattr(exc, "reason", None)
+ return _err(rid, 4111, str(exc), {"reason": reason} if reason else None)
+ except Exception as exc:
+ return _err(rid, 5112, str(exc))
+
+
+@method("groups.disband")
+def _(rid, params: dict) -> dict:
+ """Permanently tombstone a hosted room id."""
+ from gateway.hosted_rooms import (
+ AuthorityConflictError,
+ HostedRoomError,
+ RoomHistoryExpiredError,
+ default_db_path,
+ disband_room,
+ local_authority_gateway_id,
+ room_state,
+ )
+
+ try:
+ local_gateway_id = local_authority_gateway_id()
+ try:
+ room = room_state(
+ default_db_path(),
+ room_id=params.get("room_id"),
+ include_disbanded=True,
+ )
+ except RoomHistoryExpiredError:
+ room = {
+ "authority_gateway_id": local_gateway_id,
+ "authority_epoch": 1,
+ }
+ if str(room["authority_gateway_id"]) != local_gateway_id:
+ raise AuthorityConflictError(
+ "This Group Chat is managed by another gateway."
+ )
+ tombstone = disband_room(
+ default_db_path(),
+ room_id=params.get("room_id"),
+ expected_gateway_id=local_gateway_id,
+ expected_epoch=int(room["authority_epoch"]),
+ )
+ return _ok(rid, {"tombstone": tombstone})
+ except HostedRoomError as exc:
+ reason = getattr(exc, "reason", None)
+ return _err(rid, 4113, str(exc), {"reason": reason} if reason else None)
+ except Exception as exc:
+ return _err(rid, 5114, str(exc))
+
+
+@method("groups.log")
+def _(rid, params: dict) -> dict:
+ """Return a monotonic room-log delta after ``since_seq``."""
+ from gateway.hosted_rooms import HostedRoomError, default_db_path, read_events
+
+ try:
+ delta = read_events(
+ default_db_path(),
+ room_id=params.get("room_id"),
+ since_seq=params.get("since_seq", 0),
+ limit=params.get("limit", 100),
+ include_disbanded=params.get("include_disbanded") is True,
+ )
+ return _ok(rid, delta)
+ except HostedRoomError as exc:
+ reason = getattr(exc, "reason", None)
+ return _err(rid, 4112, str(exc), {"reason": reason} if reason else None)
+ except Exception as exc:
+ return _err(rid, 5113, str(exc))
+
+
+def register(server) -> None:
+ _registry.install(server)