The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): unify hosted-room coercers/JSON/clock/connect into hosted_rooms_common; fold event insert + row helpers
Teknium92d60de4ae5e
diff --git a/gateway/hosted_room_discussion.py b/gateway/hosted_room_discussion.pyindex 3118e1c6ad1..07f0e5f2de2 100644--- a/gateway/hosted_room_discussion.py+++ b/gateway/hosted_room_discussion.py@@ -14,7 +14,6 @@ terminal driver rows into publication plans before asking for the next task.from __future__ import annotationsimport hashlib-import jsonimport refrom collections.abc import Iterable, Mapping, Sequencefrom dataclasses import dataclass@@ -24,6 +23,7 @@ from typing import Any, Literalfrom gateway import hosted_room_driver as driverfrom gateway import hosted_roomsfrom gateway import hosted_rooms_common as common+from gateway.hosted_rooms_common import compact_jsonMAX_DISCUSSION_MEMBERS = 6@@ -182,18 +182,18 @@ _identifier = partial(common.identifier, error=DiscussionValidationError, max_chars=driver.MAX_IDENTIFIER_CHARS)_exact_fields = partial(common.exact_fields, error=DiscussionValidationError)+_bounded_int = partial(common.bounded_int, error=DiscussionValidationError)def _positive_int(value: Any, *, label: str) -> int:- return common.positive_int(- value, error=DiscussionValidationError, message=f"{label} must be a positive integer"- )+ return _bounded_int(value, message=f"{label} must be a positive integer", low=1)def _zero_based_int(value: Any, *, label: str, maximum: int) -> int:- if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= maximum:- raise DiscussionValidationError(f"{label} must be an integer between 0 and {maximum}")- return value+ message = f"{label} must be an integer between 0 and {maximum}"+ return _bounded_int(value, message=message, high=maximum)++_text = partial(common.text, error=DiscussionValidationError)def _peer_target(member: DiscussionMember) -> Mapping[str, Any] | None:@@ -204,14 +204,7 @@ def _peer_target(member: DiscussionMember) -> Mapping[str, Any] | None:def validate_user_payload(value: Any) -> dict[str, Any]:"""Validate and normalize the exact ``message.user`` Discussion payload."""payload = _exact_fields(value, label="user payload", required=_USER_PAYLOAD_FIELDS)- text = payload["text"]- if not isinstance(text, str):- raise DiscussionValidationError("user payload text must be a string")- text = text.strip()- if not text:- raise DiscussionValidationError("user payload text must not be empty")- if len(text.encode("utf-8")) > MAX_USER_TEXT_BYTES:- raise DiscussionValidationError("user payload text is too large")+ text = _text(payload["text"], label="user payload text", max_bytes=MAX_USER_TEXT_BYTES)return {"text": text, "thread_id": _identifier(payload["thread_id"], label="thread_id")}@@ -298,7 +291,7 @@ def validate_roster(value: Any, *, local_profiles: Iterable[str]) -> tuple[Discuif len(display_name) > hosted_rooms.MAX_ACTOR_LABEL_CHARS:raise DiscussionValidationError(f"member {index} display_name is too long")- target_key = json.dumps(target, sort_keys=True, separators=(",", ":")).casefold()+ target_key = compact_json(target, ensure_ascii=False).casefold()target_message = ("member profiles must be unique" if target.get("kind") == "local"else "member targets must be unique"@@ -586,10 +579,7 @@ def _derive_member_watermarks(events: Sequence[_ValidatedEvent]) -> dict[tuple[sdef _member_digest(member: DiscussionMember) -> str:- target = json.dumps(- member.target or {"kind": "local", "profile": member.profile},- sort_keys=True, separators=(",", ":"),- )+ target = compact_json(member.target or {"kind": "local", "profile": member.profile}, ensure_ascii=False)seed = f"{member.member_id}\0{member.profile}\0{member.handle}\0{target}"return hashlib.sha256(seed.encode("utf-8")).hexdigest()[:24]@@ -680,20 +670,17 @@ def _make_task_plan(f"d{discussion_event.seq}.r{round_index}.p{member_index}."f"s{seen_through_seq}.m{_member_digest(member)}")- seed = json.dumps(- {- "discussion_event_id": discussion_event.event_id,- "member_id": member.member_id,- "member_index": member_index,- "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),- "room_id": room.room_id,- "round_index": round_index,- "seen_through_seq": seen_through_seq,- "source_event_seq": discussion_event.seq,- "thread_id": discussion_event.payload["thread_id"],- },- ensure_ascii=True, sort_keys=True, separators=(",", ":"),- )+ seed = compact_json({+ "discussion_event_id": discussion_event.event_id,+ "member_id": member.member_id,+ "member_index": member_index,+ "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),+ "room_id": room.room_id,+ "round_index": round_index,+ "seen_through_seq": seen_through_seq,+ "source_event_seq": discussion_event.seq,+ "thread_id": discussion_event.payload["thread_id"],+ })task_id = f"dtask:{hashlib.sha256(seed.encode('utf-8')).hexdigest()[:48]}"identity = driver.TaskIdentity(room_id=room.room_id, task_id=task_id,@@ -1020,7 +1007,7 @@ def plan_publication(raise DiscussionValidationError("invalid terminal publication status")if status == "deferred":message = "deferred publication requires an execution generation"- common.positive_int(execution_generation, error=DiscussionValidationError, message=message)+ _bounded_int(execution_generation, message=message, low=1)newer_same_thread = any(event.kind == "message.user"diff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.pyindex 47b822754cc..d2ef4e92060 100644--- a/gateway/hosted_room_driver.py+++ b/gateway/hosted_room_driver.py@@ -14,11 +14,12 @@ import jsonimport mathimport sqlite3from dataclasses import dataclass+from functools import partialfrom pathlib import Pathfrom typing import Any, Callable, Literal, get_argsfrom gateway.hosted_rooms_common import (- canonical_json, identifier, non_negative_int, positive_int, table_columns, transaction,+ bounded_int, canonical_json, compact_json, connect, identifier, table_columns, text, transaction,)Clock = Callable[[], float]@@ -149,8 +150,12 @@ class InvalidTaskTransitionError(DriverStateError):"""Raised when a requested task transition is not allowed."""-def _identifier(value: Any, *, label: str) -> str:- return identifier(value, label=label, error=DriverValidationError, max_chars=MAX_IDENTIFIER_CHARS)+_identifier = partial(identifier, error=DriverValidationError, max_chars=MAX_IDENTIFIER_CHARS)+_bounded_int = partial(bounded_int, error=DriverValidationError)+_canonical_json = partial(+ canonical_json, error=DriverValidationError, label="result", max_bytes=MAX_RESULT_JSON_BYTES,+ ensure_ascii=True,+)def _finite(compute: Callable[[], Any], message: str, *, positive: bool = False) -> float:@@ -180,12 +185,6 @@ def _expiry(now: float, ttl: float) -> float:return expires_at-def _canonical_json(value: Any) -> str:- return canonical_json(- value, error=DriverValidationError, label="result", max_bytes=MAX_RESULT_JSON_BYTES, ensure_ascii=True- )--def _task_payload(value: Any) -> tuple[dict[str, Any], str, str]:if not isinstance(value, dict):raise DriverValidationError("payload must be an object")@@ -196,21 +195,17 @@ def _task_payload(value: Any) -> tuple[dict[str, Any], str, str]:if missing:raise DriverValidationError(f"missing payload fields: {', '.join(sorted(missing))}")target_profile = _identifier(value["target_profile"], label="target_profile")- prompt = value["prompt"]- if not isinstance(prompt, str):- raise DriverValidationError("prompt must be a string")- if not prompt.strip():- raise DriverValidationError("prompt must not be empty")- if len(prompt.encode("utf-8")) > MAX_PROMPT_BYTES:- raise DriverValidationError("prompt is too large")- source_event_seq = positive_int(- value["source_event_seq"], error=DriverValidationError,- message="source_event_seq must be a positive integer",+ prompt = text(+ value["prompt"], error=DriverValidationError, label="prompt", max_bytes=MAX_PROMPT_BYTES,+ strip=False,+ )+ source_event_seq = _bounded_int(+ value["source_event_seq"], message="source_event_seq must be a positive integer", low=1)normalized = {"target_profile": target_profile, "prompt": prompt, "source_event_seq": source_event_seq}if "target_member_id" in value:normalized["target_member_id"] = _identifier(value["target_member_id"], label="target_member_id")- encoded = json.dumps(normalized, ensure_ascii=True, sort_keys=True, separators=(",", ":"))+ encoded = compact_json(normalized)return normalized, encoded, hashlib.sha256(encoded.encode("utf-8")).hexdigest()@@ -334,32 +329,27 @@ def _migrate_task_status_constraint(conn: sqlite3.Connection) -> None:def _connect(db_path: Path | str) -> sqlite3.Connection:- from hermes_state import apply_wal_with_fallback+ """Open the store; existing tables are validated (after the status-constraint migration when needed).- path = Path(db_path)- path.parent.mkdir(parents=True, exist_ok=True)- conn = sqlite3.connect(path, timeout=10)- conn.row_factory = sqlite3.Row- try:- apply_wal_with_fallback(conn, db_label="state.db (hosted_room_driver)")- conn.execute("PRAGMA foreign_keys=ON")- if _schema_objects_exist(conn):- if not _task_schema_supports_current_statuses(conn):- conn.execute("BEGIN IMMEDIATE")- _migrate_task_status_constraint(conn)- conn.commit()+ The driver schema never shipped, so an incompatible draft fails closed in+ ``_validate_schema`` instead of attempting a partial in-place migration.+ """+ existing: list[bool] = []++ def ready(conn: sqlite3.Connection) -> bool:+ existing.append(_schema_objects_exist(conn))+ return existing[0] and _task_schema_supports_current_statuses(conn)++ def initialize(conn: sqlite3.Connection) -> None:+ (_migrate_task_status_constraint if existing[0] else _initialize_schema)(conn)++ conn = connect(db_path, db_label="state.db (hosted_room_driver)", ready=ready, initialize=initialize)+ if existing[0]:+ try:_validate_schema(conn)- return conn- # Schema creation is one database-wide transaction. The driver schema- # has never shipped, so an incompatible draft schema fails closed- # instead of attempting a partial in-place migration.- conn.execute("BEGIN IMMEDIATE")- _initialize_schema(conn)- conn.commit()- except Exception:- conn.rollback()- conn.close()- raise+ except Exception:+ conn.close()+ raisereturn conn@@ -617,8 +607,8 @@ def acquire_lease("""Acquire an empty or expired room lease with a monotonic generation."""room_id = _identifier(room_id, label="room_id")gateway_id = _identifier(gateway_id, label="gateway_id")- authority_epoch = positive_int(- authority_epoch, error=DriverValidationError, message="authority_epoch must be a positive integer"+ authority_epoch = _bounded_int(+ authority_epoch, message="authority_epoch must be a positive integer", low=1)process_generation = _identifier(process_generation, label="process_generation")ttl_seconds = _ttl(ttl_seconds)@@ -1033,7 +1023,7 @@ def prune_published_terminal_tasks(now = _timestamp(clock)if retention_seconds <= 0:raise DriverValidationError("retention_seconds must be positive")- non_negative_int(retain, error=DriverValidationError, message="retain must be a non-negative integer")+ _bounded_int(retain, message="retain must be a non-negative integer")with _transaction(db_path) as conn:publications = conn.execute(diff --git a/gateway/hosted_room_links.py b/gateway/hosted_room_links.pyindex 44363cfda3e..8132c25cddb 100644--- a/gateway/hosted_room_links.py+++ b/gateway/hosted_room_links.py@@ -12,6 +12,7 @@ import jsonimport osimport timefrom dataclasses import dataclass, field+from functools import partialfrom pathlib import Pathfrom typing import Any, Mapping@@ -22,6 +23,7 @@ from gateway.hosted_room_peer import (TransportSecurity,validate_room_link_url,)+from gateway.hosted_rooms_common import compact_json, exact_fieldsMAX_LINKS = 512@@ -56,8 +58,7 @@ class StoredRoomLink:@classmethoddef from_mapping(cls, value: Mapping[str, Any]) -> "StoredRoomLink":- if set(value) - _LEGACY_FIELDS - _OPTIONAL_FIELDS or not _LEGACY_FIELDS.issubset(value):- raise HostedRoomPeerError("stored room link fields are invalid")+ _link_fields(value)room_id = _short_string(value["room_id"], "room_id")member_id = _short_string(value["member_id"], "member_id")target_profile = _short_string(value["target_profile"], "target_profile")@@ -101,10 +102,17 @@ class StoredRoomLink:def as_record(self) -> dict[str, Any]:record = {name: getattr(self, name) for name in _RECORD_FIELDS}- record["catalog_json"] = json.dumps(self.catalog_mapping(), sort_keys=True, separators=(",", ":"))+ record["catalog_json"] = compact_json(self.catalog_mapping(), ensure_ascii=False)return record+_link_fields = partial(+ exact_fields, label="stored room link", required=_LEGACY_FIELDS, optional=_OPTIONAL_FIELDS,+ error=HostedRoomPeerError, not_object="stored room link fields are invalid",+ missing_fmt="stored room link fields are invalid", unknown_fmt="stored room link fields are invalid",+)++def _short_string(value: Any, field: str) -> str:normalized = str(value or "").strip()if not normalized or len(normalized) > 256:diff --git a/gateway/hosted_room_peer.py b/gateway/hosted_room_peer.pyindex 31c302456fd..41675e74d5c 100644--- a/gateway/hosted_room_peer.py+++ b/gateway/hosted_room_peer.py@@ -16,7 +16,6 @@ import mathimport osimport reimport stat-import timeimport urllib.parsefrom dataclasses import asdict, dataclassfrom functools import lru_cache, partial@@ -24,7 +23,7 @@ from pathlib import Pathfrom typing import Any, Callable, Iterable, Literal, Mappingfrom gateway.hosted_room_execution_policy import RoomExecutionPolicy, execution_policy_mapping-from gateway.hosted_rooms_common import exact_fields, identifier, positive_int+from gateway.hosted_rooms_common import bounded_int, clock, compact_json, exact_fields, identifier, text# v2 adds authority/member lineage to scoped grants and is deliberately not@@ -137,7 +136,9 @@ def _identifier(value: Any, *, field: str) -> str:def _positive_int(value: Any, *, field: str) -> int:- return positive_int(value, error=HostedRoomPeerError, message=f"{field} must be a positive integer")+ return bounded_int(+ value, error=HostedRoomPeerError, message=f"{field} must be a positive integer", low=1+ )def _digest(value: Any, *, field: str) -> str:@@ -153,7 +154,7 @@ _exact_fields = partial(def _canonical_json(value: Mapping[str, Any]) -> bytes:- return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")+ return compact_json(value).encode("ascii")def _b64encode(value: bytes) -> str:@@ -445,8 +446,7 @@ class HostedMemberDispatch:prompt = value["prompt"]if not isinstance(prompt, str) or not prompt.strip():raise HostedRoomPeerError("prompt must be a non-empty string")- if len(prompt.encode("utf-8")) > MAX_PROMPT_BYTES:- raise HostedRoomPeerError("prompt is too large")+ text(prompt, error=HostedRoomPeerError, label="prompt", max_bytes=MAX_PROMPT_BYTES, strip=False)expected_prompt_digest = hashlib.sha256(prompt.encode("utf-8")).hexdigest()prompt_digest = _digest(value["prompt_digest"], field="prompt_digest")if not hmac.compare_digest(expected_prompt_digest, prompt_digest):@@ -483,7 +483,7 @@ def issue_room_grant("""Issue a target-verifiable bearer grant scoped to one room member."""if len(secret) < 32:raise HostedRoomGrantError("room grant secret must be at least 32 bytes")- now = time.time() if issued_at is None else float(issued_at)+ now = clock(issued_at)bounded_status_expiry = (now + float(ttl_seconds if status_ttl_seconds is None else status_ttl_seconds)if status_expires_at is None@@ -554,7 +554,7 @@ def decode_room_grant(raise HostedRoomGrantError("room grant payload is invalid") from excif not isinstance(payload, dict) or frozenset(payload) not in {_GRANT_FIELDS, _GRANT_REFRESH_FIELDS}:raise HostedRoomGrantError("room grant fields are invalid")- checked_now = time.time() if now is None else float(now)+ checked_now = clock(now)if not math.isfinite(checked_now):raise HostedRoomGrantError("room grant clock is invalid")try:@@ -586,7 +586,7 @@ def room_grant_needs_dispatch_refresh(try:payload = json.loads(_b64decode(_split_token(token)[0]).decode("ascii"))expires_at = float(payload["expires_at"])- checked_now = time.time() if now is None else float(now)+ checked_now = clock(now)return checked_now + max(0.0, float(leeway_seconds)) >= expires_atexcept Exception:return Truediff --git a/gateway/hosted_room_policy_checkpoint.py b/gateway/hosted_room_policy_checkpoint.pyindex bcb8d738b2b..c3d82d9251f 100644--- a/gateway/hosted_room_policy_checkpoint.py+++ b/gateway/hosted_room_policy_checkpoint.py@@ -79,13 +79,7 @@ class PolicySnapshot:watermarks: Mapping[tuple[str, str], int]-def _event_from_room_row(row: sqlite3.Row) -> dict[str, Any]:- return {- "room_id": str(row["room_id"]), "seq": int(row["seq"]), "event_id": str(row["event_id"]),- "kind": str(row["kind"]), "actor": json.loads(row["actor_json"]),- "authority_epoch": row["authority_epoch"], "payload": json.loads(row["payload_json"]),- "created_at": float(row["created_at"]), "idempotent": False,- }+_event_from_room_row = hosted_rooms._event_from_rowdef _require_room(conn: sqlite3.Connection, room_id: str) -> None:diff --git a/gateway/hosted_room_replicas.py b/gateway/hosted_room_replicas.pyindex 41815c8e5a3..08ffa915a33 100644--- a/gateway/hosted_room_replicas.py+++ b/gateway/hosted_room_replicas.py@@ -16,26 +16,26 @@ from __future__ import annotationsimport jsonimport sqlite3-import timefrom contextlib import contextmanager+from functools import partialfrom pathlib import Pathfrom typing import Any, Iteratorfrom gateway.hosted_rooms import (MAX_ACTOR_ID_CHARS,- MAX_EVENT_JSON_BYTES,- MAX_ROOM_ID_CHARS,HostedRoomError,RoomConflictError,- _canonical_json,+ _actor_json,_connect,+ _payload_json,+ _room_id,_transaction,_validate_identifier,_validate_members,_validate_room_name,local_authority_gateway_id,)-from gateway.hosted_rooms_common import positive_int, utf8_len+from gateway.hosted_rooms_common import bounded_int, clock, utf8_lenMAX_REPLICA_ROOMS = 256MAX_REPLICA_EVENT_BYTES = 256 * 1024 * 1024@@ -97,20 +97,12 @@ def _replica_transaction(db_path: Path | str) -> Iterator[sqlite3.Connection]:yield conn-def _room_id(value: Any) -> str:- return _validate_identifier(value, label="room_id", max_chars=MAX_ROOM_ID_CHARS)---def _positive_int(value: Any, message: str) -> int:- return positive_int(value, error=ReplicaError, message=message)+_positive_int = partial(bounded_int, error=ReplicaError, low=1)def _control_event_json(payload: dict[str, Any]) -> tuple[str, str]:"""Canonical (actor_json, payload_json) for a system authority-control event."""- return (- _canonical_json(_SYSTEM_ACTOR, label="actor", max_bytes=4 * 1024),- _canonical_json(payload, label="payload", max_bytes=MAX_EVENT_JSON_BYTES),- )+ return _actor_json(_SYSTEM_ACTOR), _payload_json(payload)def _event_bytes(event: dict[str, Any]) -> int:@@ -133,12 +125,12 @@ def _validate_page(page: Any) -> tuple[list[dict[str, Any]], dict[str, Any]]:gateway_id = _validate_identifier(authority.get("gateway_id"), label="page.authority.gateway_id", max_chars=MAX_ACTOR_ID_CHARS)- epoch = _positive_int(authority.get("epoch"), "page.authority.epoch must be a positive integer")+ epoch = _positive_int(authority.get("epoch"), message="page.authority.epoch must be a positive integer")previous_seq: int | None = Nonefor event in events:if not isinstance(event, dict):raise ReplicaError("page events must be objects")- seq = _positive_int(event.get("seq"), "event.seq must be a positive integer")+ seq = _positive_int(event.get("seq"), message="event.seq must be a positive integer")if previous_seq is not None and seq != previous_seq + 1:raise ReplicaGapError("page events must be contiguous")previous_seq = seq@@ -201,7 +193,7 @@ def ingest_page(room_name = _validate_room_name(room_name)_, members_json = _validate_members(members)events, authority = _validate_page(page)- now = time.time() if now is None else float(now)+ now = clock(now)with _replica_transaction(db_path) as conn:row, stored_epoch, last_seq, stored_bytes = _replica_row_state(conn, room_id)@@ -216,8 +208,8 @@ def ingest_page(size = _event_bytes(event)if stored_bytes + added_bytes + size > MAX_REPLICA_EVENT_BYTES:raise ReplicaError("replica event storage exhausted")- actor_json = _canonical_json(event["actor"], label="actor", max_bytes=4 * 1024)- payload_json = _canonical_json(event["payload"], label="payload", max_bytes=MAX_EVENT_JSON_BYTES)+ actor_json = _actor_json(event["actor"])+ payload_json = _payload_json(event["payload"])conn.execute(_INSERT_REPLICA_EVENT,(@@ -276,7 +268,7 @@ def promote_replica(room_id = _room_id(room_id)if not isinstance(reason, str) or not reason or len(reason) > 200:raise ReplicaError("reason must be a non-empty string of at most 200 chars")- now = time.time() if now is None else float(now)+ now = clock(now)local_gateway = local_authority_gateway_id()with _replica_transaction(db_path) as conn:@@ -354,8 +346,8 @@ def demote_room(observed_gateway_id = _validate_identifier(observed_gateway_id, label="observed_gateway_id", max_chars=MAX_ACTOR_ID_CHARS)- observed_epoch = _positive_int(observed_epoch, "observed_epoch must be a positive integer")- now = time.time() if now is None else float(now)+ observed_epoch = _positive_int(observed_epoch, message="observed_epoch must be a positive integer")+ now = clock(now)local_gateway = local_authority_gateway_id()with _transaction(db_path, immediate=True) as conn:diff --git a/gateway/hosted_rooms.py b/gateway/hosted_rooms.pyindex 2daf75d97b6..9c5c2c59712 100644--- a/gateway/hosted_rooms.py+++ b/gateway/hosted_rooms.py@@ -15,19 +15,13 @@ import hashlibimport jsonimport reimport sqlite3-import time+from functools import partialfrom pathlib import Pathfrom typing import Any, Mapping, NoReturnfrom gateway.hosted_rooms_common import (- canonical_json,- identifier,- non_negative_int,- open_sqlite,- positive_int,- table_columns,- table_exists,- transaction,+ bounded_int, canonical_json, clock as _now, compact_json, connect, identifier, open_sqlite,+ table_columns, table_exists, transaction,)PROTOCOL_VERSION = 2@@ -266,22 +260,12 @@ class AuthoritySupersededError(AuthorityConflictError):# --- validation ----------------------------------------------------------------def _canonical_json(value: Any, *, label: str, max_bytes: int) -> str:- return canonical_json(- value, error=HostedRoomError, label=label, max_bytes=max_bytes, ensure_ascii=False- )---def _validate_identifier(value: Any, *, label: str, max_chars: int) -> str:- return identifier(value, label=label, error=HostedRoomError, max_chars=max_chars)---def _room_id(value: Any) -> str:- return _validate_identifier(value, label="room_id", max_chars=MAX_ROOM_ID_CHARS)---def _event_id(value: Any, *, label: str = "event_id") -> str:- return _validate_identifier(value, label=label, max_chars=MAX_EVENT_ID_CHARS)+_canonical_json = partial(canonical_json, error=HostedRoomError, ensure_ascii=False)+_validate_identifier = partial(identifier, error=HostedRoomError)+_room_id = partial(_validate_identifier, label="room_id", max_chars=MAX_ROOM_ID_CHARS)+_event_id = partial(_validate_identifier, label="event_id", max_chars=MAX_EVENT_ID_CHARS)+_actor_json = partial(_canonical_json, label="actor", max_bytes=4 * 1024)+_payload_json = partial(_canonical_json, label="payload", max_bytes=MAX_EVENT_JSON_BYTES)def _actor_id(value: Any, label: str) -> str:@@ -289,31 +273,22 @@ def _actor_id(value: Any, label: str) -> str:def _require_positive_int(value: Any, label: str) -> int:- return positive_int(value, error=HostedRoomError, message=f"{label} must be a positive integer")+ return bounded_int(+ value, error=HostedRoomError, message=f"{label} must be a positive integer", low=1+ )def _bounded_limit(value: Any, maximum: int) -> int:- if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= maximum:- raise HostedRoomError(f"limit must be between 1 and {maximum}")- return value+ message = f"limit must be between 1 and {maximum}"+ return bounded_int(value, error=HostedRoomError, message=message, low=1, high=maximum)def _non_negative(value: Any, label: str) -> int:- return non_negative_int(- value, error=HostedRoomError, message=f"{label} must be a non-negative integer"- )---def _now(now: float | None) -> float:- return time.time() if now is None else float(now)+ return bounded_int(value, error=HostedRoomError, message=f"{label} must be a non-negative integer")def _system_actor_json(actor_id: str) -> str:- return _canonical_json({"kind": "system", "id": actor_id}, label="actor", max_bytes=4 * 1024)---def _payload_json(payload: Any) -> str:- return _canonical_json(payload, label="payload", max_bytes=MAX_EVENT_JSON_BYTES)+ return _actor_json({"kind": "system", "id": actor_id})def _claim_payload_json(previous_gateway_id: str, new_gateway_id: str, epoch: int) -> str:@@ -330,13 +305,10 @@ def user_event_id(client_event_id: Any) -> str:return f"user:{hashlib.sha256(normalized.encode('utf-8')).hexdigest()}"-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+_validate_room_name = partial(+ _validate_identifier, label="name", max_chars=MAX_ROOM_NAME_CHARS, pattern=None,+ invalid="invalid room name",+)def _validate_members(value: Any) -> tuple[list[dict[str, Any]], str]:@@ -373,11 +345,10 @@ def _legacy_members_match(existing_json: str, proposed: list[dict[str, Any]]) ->return True-def _validate_event_kind(value: Any) -> str:- return identifier(- value, label="kind", error=HostedRoomError, max_chars=MAX_EVENT_KIND_CHARS,- pattern=_EVENT_KIND_RE, invalid="invalid event kind",- )+_validate_event_kind = partial(+ _validate_identifier, label="kind", max_chars=MAX_EVENT_KIND_CHARS, pattern=_EVENT_KIND_RE,+ invalid="invalid event kind",+)def _optional_actor_field(actor: dict[str, Any], field: str, max_chars: int) -> str:@@ -412,7 +383,7 @@ def _validate_actor(value: Any, *, kind: str) -> tuple[dict[str, str], str]:field_value = _optional_actor_field(value, field, max_chars)if field_value:actor[field] = field_value- return actor, _canonical_json(actor, label="actor", max_bytes=4 * 1024)+ return actor, _actor_json(actor)# --- schema / connections -------------------------------------------------------@@ -563,39 +534,10 @@ def local_authority_gateway_id() -> str: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:- last = attempt + 1 == _JOURNAL_MODE_LOCK_RETRIES- if str(exc).lower() != "database is locked" or last:- 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+ return connect(+ db_path, db_label="state.db (hosted_rooms)", ready=_schema_is_current,+ initialize=lambda conn: _initialize_schema(conn), lock_retries=_JOURNAL_MODE_LOCK_RETRIES,+ )def _read_connection(db_path: Path | str) -> sqlite3.Connection:@@ -681,10 +623,27 @@ def _load_event(conn: sqlite3.Connection, room_id: str, event_id: str) -> sqlitereturn conn.execute(_SELECT_EVENT, (room_id, event_id)).fetchone()+def _event_content(row: sqlite3.Row) -> tuple[Any, Any, Any, Any]:+ """The immutable (kind, actor_json, authority_epoch, payload_json) an event id is bound to."""+ return row["kind"], row["actor_json"], row["authority_epoch"], row["payload_json"]++def _gateway_event_bytes(conn: sqlite3.Connection) -> int:return int(conn.execute(_SUM_EVENT_BYTES).fetchone()[0])+def _insert_event(+ conn: sqlite3.Connection, room: sqlite3.Row, room_id: str, seq: int, event_id: str, kind: str,+ actor_json: str, epoch: int, payload_json: str, now: float, *, allow_control: bool = False,+) -> int:+ """Capacity-check then INSERT one event at ``seq``; returns its accounted bytes."""+ event_bytes = _prepare_event(+ conn, room, event_id, kind, actor_json, payload_json, allow_control=allow_control+ )+ conn.execute(_INSERT_EVENT, (room_id, seq, event_id, kind, actor_json, epoch, payload_json, now))+ return event_bytes++def _prepare_event(conn: sqlite3.Connection, room: sqlite3.Row, event_id: str, kind: str, actor_json: str,payload_json: str, *, allow_control: bool = False,@@ -727,25 +686,27 @@ _DEPENDENT_TABLES = ()+def _room_ids(conn: sqlite3.Connection, sql: str, params: tuple[Any, ...]) -> list[str]:+ return [str(row["room_id"]) for row in conn.execute(sql, params).fetchall()]++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:- candidates.update(- str(row["room_id"]) for row in conn.execute(- """SELECT room_id FROM hosted_rooms+ candidates.update(_room_ids(+ conn,+ """SELECT room_id FROM hosted_roomsWHERE disbanded_at IS NOT NULL AND disbanded_at<=?""",- (now - DISBANDED_ROOM_RETENTION_SECONDS,),- ).fetchall()- )- candidates.update(- str(row["room_id"]) for row in conn.execute(- """SELECT room_id FROM hosted_rooms WHERE disbanded_at IS NOT NULL+ (now - DISBANDED_ROOM_RETENTION_SECONDS,),+ ))+ candidates.update(_room_ids(+ conn,+ """SELECT room_id FROM hosted_rooms WHERE disbanded_at IS NOT NULLORDER BY disbanded_at DESC, room_id ASC LIMIT -1 OFFSET ?""",- (MAX_DISBANDED_ROOM_TOMBSTONES,),- ).fetchall()- )+ (MAX_DISBANDED_ROOM_TOMBSTONES,),+ ))if max_gateway_event_bytes is not None:retained_bytes = _gateway_event_bytes(conn)if retained_bytes > max_gateway_event_bytes:@@ -864,9 +825,7 @@ def _room_grant_scope_key(claims: Mapping[str, Any]) -> str:}if not all(fields.values()):raise HostedRoomError("room grant scope is incomplete")- return hashlib.sha256(- json.dumps(fields, sort_keys=True, separators=(",", ":")).encode("utf-8")- ).hexdigest()+ return hashlib.sha256(compact_json(fields).encode("utf-8")).hexdigest()def revoke_room_grant_scope(@@ -1099,16 +1058,9 @@ def _adopt_legacy_room(seq = int(existing["next_seq"])actor_json = _system_actor_json("authority-control")payload_json = _claim_payload_json("legacy", authority_gateway_id, target_epoch)- claim_bytes = _prepare_event(- conn, existing, "system:authority-adopted", "authority.claimed", actor_json,- payload_json, allow_control=True,- )- conn.execute(- _INSERT_EVENT,- (- room_id, seq, "system:authority-adopted", "authority.claimed", actor_json,- target_epoch, payload_json, now,- ),+ claim_bytes = _insert_event(+ conn, existing, room_id, seq, "system:authority-adopted", "authority.claimed", actor_json,+ target_epoch, payload_json, now, allow_control=True,)adopted = conn.execute("""UPDATE hosted_rooms@@ -1287,12 +1239,7 @@ def append_event(with _transaction(db_path, immediate=True) as conn:existing = _load_event(conn, room_id, event_id)if existing is not None:- if (- existing["kind"] != kind- or existing["actor_json"] != actor_json- or existing["authority_epoch"] != authority_epoch- or existing["payload_json"] != payload_json- ):+ if _event_content(existing) != (kind, actor_json, authority_epoch, payload_json):raise EventConflictError("event_id already exists with different content")return _event_from_row(existing, idempotent=True)room = conn.execute(@@ -1308,14 +1255,10 @@ def append_event():raise AuthorityConflictError("stale hosted room authority")seq = int(room["next_seq"])- event_bytes = _prepare_event(- conn, room, event_id, kind, actor_json, payload_json,+ event_bytes = _insert_event(+ conn, room, room_id, seq, event_id, kind, actor_json, authority_epoch, payload_json, now,allow_control=kind in _CONTROL_EVENT_KINDS,)- conn.execute(- _INSERT_EVENT,- (room_id, seq, event_id, kind, actor_json, 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=?""",@@ -1374,11 +1317,8 @@ def probe_peer_room_reservation("""Check a peer reservation without creating or migrating shared state."""checked_room_id = _room_id(room_id)checked_profile = _actor_id(target_profile, "target_profile")- path = Path(db_path)- if not path.is_file():- return Falsereturn _probe(- path, "hosted_room_peer_reservations", _SELECT_LIVE_RESERVATION,+ Path(db_path), "hosted_room_peer_reservations", _SELECT_LIVE_RESERVATION,(checked_room_id, checked_profile, _now(now)),"peer room ownership is temporarily unavailable",)@@ -1403,7 +1343,6 @@ def room_state((room_id, int(row["authority_epoch"])),).fetchone()state = _room_from_row(row)- state["latest_seq"] = int(row["next_seq"]) - 1if claim_row is not None:state["authority_claim"] = _event_from_row(claim_row)return state@@ -1414,7 +1353,7 @@ def request_room_stop(expected_epoch: Any,) -> dict[str, Any]:"""Append an idempotent fence that supersedes earlier user turns."""- cancel_id = _event_id(cancel_id, label="cancel_id")+ cancel_id = _validate_identifier(cancel_id, label="cancel_id", max_chars=MAX_EVENT_ID_CHARS)digest = hashlib.sha256(cancel_id.encode()).hexdigest()[:32]return append_event(db_path, room_id=room_id, event_id=f"room-stop:{digest}", kind="room.stop_requested",@@ -1429,13 +1368,9 @@ def _append_authority_claim(actor_json: str, payload_json: str, now: float,) -> sqlite3.Row | None:"""Insert the claim event and CAS the room's authority; returns the stored claim event."""- seq = int(row["next_seq"])- claim_bytes = _prepare_event(- conn, row, event_id, "authority.claimed", actor_json, payload_json, allow_control=True- )- conn.execute(- _INSERT_EVENT,- (room_id, seq, event_id, "authority.claimed", actor_json, target_epoch, payload_json, now),+ claim_bytes = _insert_event(+ conn, row, room_id, int(row["next_seq"]), event_id, "authority.claimed", actor_json,+ target_epoch, payload_json, now, allow_control=True,)updated = conn.execute("""UPDATE hosted_rooms SET authority_gateway_id=?,@@ -1482,11 +1417,8 @@ def claim_authority(existing_event = _load_event(conn, room_id, event_id)idempotent = existing_event is not Noneif idempotent:- 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+ if _event_content(existing_event) != (+ "authority.claimed", claim_actor_json, target_epoch, claim_payload_json):raise EventConflictError("event_id already exists with different content")if current_gateway != new_gateway_id or current_epoch != target_epoch:@@ -1508,7 +1440,6 @@ def claim_authority("claimed room could not be reloaded",)state = _room_from_row(state_row, idempotent=idempotent)- state["latest_seq"] = int(state_row["next_seq"]) - 1if existing_event is None: # pragma: no cover - both claim paths set itraise RuntimeError("authority claim event could not be reloaded")state["claim_event"] = _event_from_row(existing_event, idempotent=idempotent)@@ -1563,19 +1494,10 @@ def disband_room(or int(room["authority_epoch"]) != expected_epoch):raise AuthorityConflictError("stale hosted room authority")- seq = int(room["next_seq"])- actor_json = _system_actor_json("room-control")- payload_json = _payload_json({"room_id": room_id})- disband_bytes = _prepare_event(- conn, room, "system:room-disbanded", "room.disbanded", actor_json, payload_json,- allow_control=True,- )- conn.execute(- _INSERT_EVENT,- (- room_id, seq, "system:room-disbanded", "room.disbanded", actor_json,- int(room["authority_epoch"]), payload_json, now,- ),+ disband_bytes = _insert_event(+ conn, room, room_id, int(room["next_seq"]), "system:room-disbanded", "room.disbanded",+ _system_actor_json("room-control"), int(room["authority_epoch"]),+ _payload_json({"room_id": room_id}), now, allow_control=True,)updated = conn.execute("""UPDATE hosted_roomsdiff --git a/gateway/hosted_rooms_common.py b/gateway/hosted_rooms_common.pyindex a08de5b43a4..7fbdee4aefe 100644--- a/gateway/hosted_rooms_common.py+++ b/gateway/hosted_rooms_common.py@@ -13,7 +13,9 @@ from __future__ import annotationsimport jsonimport reimport sqlite3+import timefrom contextlib import contextmanager+from functools import partialfrom pathlib import Pathfrom typing import Any, Callable, Iterator, Mapping@@ -26,29 +28,34 @@ def identifier(label: str,error: type[Exception],max_chars: int = 128,- pattern: re.Pattern[str] = IDENTIFIER_RE,+ pattern: re.Pattern[str] | None = IDENTIFIER_RE,invalid: str | None = None,) -> str:- """Strip and validate a bounded identifier; ``invalid`` overrides the fail message."""+ """Strip and validate a bounded string; ``pattern=None`` skips the shape check."""if not isinstance(value, str):raise error(f"{label} must be a string")value = value.strip()- if not value or len(value) > max_chars or not pattern.fullmatch(value):+ if not value or len(value) > max_chars or (pattern is not None and not pattern.fullmatch(value)):raise error(invalid or f"invalid {label}")return value-def positive_int(value: Any, *, error: type[Exception], message: str) -> int:- """Reject bools, non-ints and values below 1 (``message`` is the exact error text)."""- if isinstance(value, bool) or not isinstance(value, int) or value < 1:+def bounded_int(+ value: Any, *, error: type[Exception], message: str, low: int = 0, high: int | None = None+) -> int:+ """Reject bools, non-ints and values outside ``[low, high]`` (``message`` is the exact text)."""+ if (+ isinstance(value, bool)+ or not isinstance(value, int)+ or value < low+ or (high is not None and value > high)+ ):raise error(message)return value-def non_negative_int(value: Any, *, error: type[Exception], message: str) -> int:- if isinstance(value, bool) or not isinstance(value, int) or value < 0:- raise error(message)- return value+positive_int = partial(bounded_int, low=1)+non_negative_int = partial(bounded_int, low=0)def exact_fields(@@ -75,19 +82,30 @@ def exact_fields(return value+def text(value: Any, *, error: type[Exception], label: str, max_bytes: int, strip: bool = True) -> str:+ """Non-blank string bounded by ``max_bytes`` of UTF-8; ``strip=False`` keeps and measures the raw text."""+ if not isinstance(value, str):+ raise error(f"{label} must be a string")+ if not value.strip():+ raise error(f"{label} must not be empty")+ if strip:+ value = value.strip()+ if len(value.encode("utf-8")) > max_bytes:+ raise error(f"{label} is too large")+ return value+++def compact_json(value: Any, *, ensure_ascii: bool = True) -> str:+ """Sorted-key, separator-free JSON (the digest/storage canonical form)."""+ return json.dumps(value, ensure_ascii=ensure_ascii, sort_keys=True, separators=(",", ":"))++def canonical_json(- value: Any,- *,- error: type[Exception],- label: str,- max_bytes: int,- ensure_ascii: bool,+ value: Any, *, error: type[Exception], label: str, max_bytes: int, ensure_ascii: bool) -> str:- """Sorted, compact JSON bounded by ``max_bytes`` of UTF-8."""+ """``compact_json`` bounded by ``max_bytes`` of UTF-8; unserializable input raises ``error``."""try:- encoded = json.dumps(- value, ensure_ascii=ensure_ascii, sort_keys=True, separators=(",", ":")- )+ encoded = compact_json(value, ensure_ascii=ensure_ascii)except (TypeError, ValueError, RecursionError) as exc:raise error(f"{label} must be JSON-serializable") from excif len(encoded.encode("utf-8")) > max_bytes:@@ -99,6 +117,11 @@ def utf8_len(*parts: str) -> int:return len("".join(parts).encode("utf-8"))+def clock(now: float | None) -> float:+ """``now`` as a float, or the current wall clock when ``None``."""+ return time.time() if now is None else float(now)++def open_sqlite(path: Path | str, *, timeout: float = 10) -> sqlite3.Connection:"""Row-factory connection with foreign keys on; no journal or schema work."""conn = sqlite3.connect(path, timeout=timeout)@@ -107,6 +130,49 @@ def open_sqlite(path: Path | str, *, timeout: float = 10) -> sqlite3.Connection:return conn+def connect(+ db_path: Path | str,+ *,+ db_label: str,+ ready: Callable[[sqlite3.Connection], bool],+ initialize: Callable[[sqlite3.Connection], None],+ lock_retries: int = 1,+) -> sqlite3.Connection:+ """Open the shared root store: WAL, foreign keys, then ``initialize`` in one IMMEDIATE txn if not ``ready``.++ Multiple profile gateways share this database, so every draft-schema transition+ is serialized in SQLite itself: a crash rolls back the whole DDL/data migration and+ another process can safely retry it. Only the transient "database is locked" class+ from the journal-mode pragma is retried (it may ignore the busy timeout while another+ first opener initializes the DB, especially on Windows).+ """+ 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(lock_retries):+ try:+ apply_wal_with_fallback(conn, db_label=db_label)+ break+ except sqlite3.OperationalError as exc:+ if str(exc).lower() != "database is locked" or attempt + 1 == lock_retries:+ raise+ time.sleep(0.01 * (2**attempt))+ conn.execute("PRAGMA foreign_keys=ON")+ if not ready(conn):+ conn.execute("BEGIN IMMEDIATE")+ initialize(conn)+ conn.commit()+ except Exception:+ conn.rollback()+ conn.close()+ raise+ return conn++def table_exists(conn: sqlite3.Connection, table: str) -> bool:row = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)@@ -120,10 +186,7 @@ def table_columns(conn: sqlite3.Connection, table: str) -> frozenset[str]:@contextmanagerdef transaction(- connect: Callable[[Path | str], sqlite3.Connection],- db_path: Path | str,- *,- immediate: bool,+ connect: Callable[[Path | str], sqlite3.Connection], db_path: Path | str, *, immediate: bool) -> Iterator[sqlite3.Connection]:"""Open via ``connect``, optionally ``BEGIN IMMEDIATE``, commit on success, always close."""conn = connect(db_path)diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.pyindex e91567c6ecb..052eee868f1 100644--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@ -1874,8 +1874,7 @@ class TestHostedRoomRuns:for target in ("gateway.platforms.api_server.time.time",- "gateway.hosted_room_peer.time.time",- "gateway.hosted_rooms.time.time",+ "gateway.hosted_rooms_common.time.time",):monkeypatch.setattr(target, lambda: 200)claims = {