Skip to content

The agent that grows with you

refactor(gateway): hug SQL literal openers and repack hosted-room layouts to <=120 cols (AST-neutral); reuse common identifier/compact_json in execution_policy and links

Teknium75d39ba43068
diff --git a/gateway/hosted_room_discussion.py b/gateway/hosted_room_discussion.py
index 9273ca7ff65..c47b75936dd 100644
--- a/gateway/hosted_room_discussion.py
+++ b/gateway/hosted_room_discussion.py
@@ -44,8 +44,7 @@ _LOCAL_TARGET_FIELDS = frozenset({"kind", "profile"})
_PEER_TARGET_FIELDS = frozenset({"kind", "peer_id", "installation_id", "profile", "capability_digest"})
_REMOTE_MEMBER_FIELDS = frozenset({
"connectionId", "connectionKind", "connectionLabel", "connection_id", "connection_kind", "connection_label",
- "remoteSource", "route", "sourceMissing", "sourceReachable", "sourceScoped", "targetProfile", "target_profile",
-})
+ "remoteSource", "route", "sourceMissing", "sourceReachable", "sourceScoped", "targetProfile", "target_profile"})
_USER_PAYLOAD_FIELDS = frozenset({"text", "thread_id"})
_TURN_COORDINATE_FIELDS = frozenset(
{"discussion_event_id", "member_id", "member_index", "round_index", "task_id", "thread_id", "turn_id", })
@@ -53,8 +52,7 @@ _MEMBER_MESSAGE_FIELDS = _TURN_COORDINATE_FIELDS | {"text"}
_TERMINAL_COMMON_FIELDS = _TURN_COORDINATE_FIELDS | {"seen_through_seq"}
_TERMINAL_EXTRA_FIELDS = {
"turn.settled": frozenset({"message_event_id", "passed"}), "turn.failed": frozenset({"error"}),
- "turn.cancelled": frozenset({"reason"}), "turn.deferred": frozenset({"execution_generation", "reason"}),
-}
+ "turn.cancelled": frozenset({"reason"}), "turn.deferred": frozenset({"execution_generation", "reason"})}
_TERMINAL_OPTIONAL_FIELDS = {"turn.failed": frozenset({"reason_code"})}
_TERMINAL_EVENT_KINDS = frozenset(_TERMINAL_EXTRA_FIELDS)
# Gateway-authored control events: kind -> (exact payload fields, identifier fields).
@@ -138,9 +136,8 @@ class EventPlan:
def append_kwargs(self, room_id: str) -> dict[str, Any]:
"""Return keyword arguments accepted by ``append_event``."""
return {
- "room_id": room_id, "event_id": self.event_id, "kind": self.kind,
- "actor": dict(self.actor), "payload": dict(self.payload),
- "authority_gateway_id": self.authority_gateway_id,
+ "room_id": room_id, "event_id": self.event_id, "kind": self.kind, "actor": dict(self.actor),
+ "payload": dict(self.payload), "authority_gateway_id": self.authority_gateway_id,
"authority_epoch": self.authority_epoch}
@@ -194,8 +191,7 @@ def validate_user_payload(value: Any) -> dict[str, Any]:
def _validate_member_target(value: Any, *, profile: str, known_profiles: set[str], index: int) -> dict[str, Any]:
if value is None:
if profile not in known_profiles:
- raise DiscussionValidationError(
- f"member {index} profile '{profile}' is not local to this gateway")
+ raise DiscussionValidationError(f"member {index} profile '{profile}' is not local to this gateway")
return {"kind": "local", "profile": profile}
if not isinstance(value, Mapping):
raise DiscussionValidationError(f"member {index} target must be an object")
@@ -208,21 +204,17 @@ def _validate_member_target(value: Any, *, profile: str, known_profiles: set[str
target_profile = _identifier(target["profile"], label=f"member {index} target profile")
if kind == "local":
if target_profile != profile or profile not in known_profiles:
- raise DiscussionValidationError(
- f"member {index} local target does not match a local profile")
+ raise DiscussionValidationError(f"member {index} local target does not match a local profile")
return {"kind": "local", "profile": profile}
if target_profile != profile:
- raise DiscussionValidationError(
- f"member {index} peer target profile does not match member profile")
+ raise DiscussionValidationError(f"member {index} peer target profile does not match member profile")
capability_digest = target["capability_digest"]
if not isinstance(capability_digest, str) or not re.fullmatch(r"[0-9a-f]{64}", capability_digest):
raise DiscussionValidationError(f"member {index} capability_digest must be a sha256 digest")
return {
- "kind": "peer",
- "peer_id": _identifier(target["peer_id"], label=f"member {index} peer_id"),
+ "kind": "peer", "peer_id": _identifier(target["peer_id"], label=f"member {index} peer_id"),
"installation_id": _identifier(target["installation_id"], label=f"member {index} installation_id"),
- "profile": target_profile,
- "capability_digest": capability_digest}
+ "profile": target_profile, "capability_digest": capability_digest}
def validate_roster(value: Any, *, local_profiles: Iterable[str]) -> tuple[DiscussionMember, ...]:
@@ -248,8 +240,7 @@ def validate_roster(value: Any, *, local_profiles: Iterable[str]) -> tuple[Discu
raise DiscussionValidationError(
f"member {index} contains cross-gateway fields: {', '.join(sorted(remote_fields))}")
member = _exact_fields(
- raw, label=f"member {index}",
- required=frozenset({"member_id", "profile", "handle"}),
+ raw, label=f"member {index}", required=frozenset({"member_id", "profile", "handle"}),
optional=frozenset({"display_name", "target"}))
member_id = _identifier(member["member_id"], label=f"member {index} id")
profile = _identifier(member["profile"], label=f"member {index} profile")
@@ -275,8 +266,7 @@ def validate_roster(value: Any, *, local_profiles: Iterable[str]) -> tuple[Discu
raise DiscussionValidationError(message)
seen.add(key)
members.append(DiscussionMember(
- member_id=member_id, profile=profile, handle=handle,
- display_name=display_name, target=target))
+ member_id=member_id, profile=profile, handle=handle, display_name=display_name, target=target))
return tuple(members)
@@ -389,8 +379,7 @@ def _validate_member_message(
peer = _peer_target(member)
expected = {
"kind": "member", "id": member.member_id, "profile": member.profile,
- "connection_id": peer.get("peer_id") if peer else None,
- }
+ "connection_id": peer.get("peer_id") if peer else None}
if any(actor.get(key) != value for key, value in expected.items()):
raise DiscussionValidationError("message.member actor does not match roster")
return payload
@@ -399,8 +388,7 @@ def _validate_member_message(
def _validate_terminal_event(
kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any], room: DiscussionRoom) -> Mapping[str, Any]:
_exact_fields(
- payload, label=f"{kind} payload",
- required=_TERMINAL_COMMON_FIELDS | _TERMINAL_EXTRA_FIELDS[kind],
+ payload, label=f"{kind} payload", required=_TERMINAL_COMMON_FIELDS | _TERMINAL_EXTRA_FIELDS[kind],
optional=_TERMINAL_OPTIONAL_FIELDS.get(kind, frozenset()))
_validate_turn_coordinates(payload, room)
_positive_int(payload.get("seen_through_seq"), label="seen_through_seq")
@@ -442,8 +430,7 @@ def _validate_gateway_event(
_EVENT_VALIDATORS = {
- "message.user": _validate_user_event,
- "message.member": _validate_member_message,
+ "message.user": _validate_user_event, "message.member": _validate_member_message,
**dict.fromkeys(_TERMINAL_EVENT_KINDS, _validate_terminal_event),
**dict.fromkeys(_GATEWAY_EVENT_FIELDS, _validate_gateway_event)}
@@ -459,8 +446,7 @@ def _validate_event(raw: Any, *, room: DiscussionRoom, previous_seq: int) -> _Va
event_id = _identifier(raw.get("event_id"), label="event_id")
kind, actor, payload = raw.get("kind"), raw.get("actor"), raw.get("payload")
for value, expected, message in (
- (kind, str, "event kind must be a string"),
- (actor, Mapping, "event actor must be an object"),
+ (kind, str, "event kind must be a string"), (actor, Mapping, "event actor must be an object"),
(payload, Mapping, "event payload must be an object")):
if not isinstance(value, expected):
raise DiscussionValidationError(message)
@@ -505,13 +491,10 @@ def _derive_member_watermarks(events: Sequence[_ValidatedEvent]) -> dict[tuple[s
previous = terminal_by_task.get(task_id)
if previous is not None:
if previous.kind != "turn.deferred":
- raise DiscussionValidationError(
- f"task '{task_id}' has more than one terminal room event")
+ raise DiscussionValidationError(f"task '{task_id}' has more than one terminal room event")
if event.kind == "turn.deferred" and int(
- event.payload["execution_generation"]
- ) <= int(previous.payload["execution_generation"]):
- raise DiscussionValidationError(
- f"task '{task_id}' deferral generation did not advance")
+ event.payload["execution_generation"]) <= int(previous.payload["execution_generation"]):
+ raise DiscussionValidationError(f"task '{task_id}' deferral generation did not advance")
terminal_by_task[task_id] = event
key = (str(event.payload["thread_id"]), str(event.payload["member_id"]))
watermark = int(event.payload["seen_through_seq"])
@@ -563,19 +546,16 @@ def _truncate_utf8_text(value: Any, *, max_bytes: int, suffix: str = "") -> str:
def _build_prompt(
- *, room: DiscussionRoom, member: DiscussionMember, messages: Sequence[_ValidatedEvent],
- watermark: int, seen_through_seq: int) -> str:
+ *, room: DiscussionRoom, member: DiscussionMember, messages: Sequence[_ValidatedEvent], watermark: int,
+ seen_through_seq: int) -> str:
delta = [event for event in messages if watermark < event.seq <= seen_through_seq][- MAX_DISCUSSION_DELTA_LINES:]
- peers = ", ".join(
- f"@{candidate.handle}" for candidate in room.members if candidate.member_id != member.member_id)
+ peers = ", ".join(f"@{candidate.handle}" for candidate in room.members if candidate.member_id != member.member_id)
opening = [
f'[Discussion: "{room.name}"] You are @{member.handle}, one participant '
- f"with {peers or 'no other members'} and the user.",
- "",
+ f"with {peers or 'no other members'} and the user.", "",
"New messages in this thread since your last turn (oldest first):"]
rules = [
- "",
- "Rules for this Discussion:",
+ "", "Rules for this Discussion:",
"- Reply with one conversational message only when you have something new worth adding.",
'- If you have nothing new to add, reply with exactly "(pass)".',
"- Mention a teammate by handle to pull them into the next round; do not repeat points already made.",
@@ -605,8 +585,8 @@ def _build_prompt(
def _make_task_plan(
- *, room: DiscussionRoom, discussion_event: _ValidatedEvent, member: DiscussionMember,
- member_index: int, round_index: int, seen_through_seq: int, prompt: str) -> DiscussionTaskPlan:
+ *, room: DiscussionRoom, discussion_event: _ValidatedEvent, member: DiscussionMember, member_index: int,
+ round_index: int, seen_through_seq: int, prompt: str) -> DiscussionTaskPlan:
turn_id = (
f"d{discussion_event.seq}.r{round_index}.p{member_index}."
f"s{seen_through_seq}.m{_member_digest(member)}")
@@ -614,16 +594,13 @@ def _make_task_plan(
"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"],
- })
+ "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,
- thread_id=str(discussion_event.payload["thread_id"]), turn_id=turn_id)
+ room_id=room.room_id, task_id=task_id, thread_id=str(discussion_event.payload["thread_id"]), turn_id=turn_id)
payload = {
"target_member_id": member.member_id, "target_profile": member.profile, "prompt": prompt,
- "source_event_seq": discussion_event.seq,
- }
+ "source_event_seq": discussion_event.seq}
return DiscussionTaskPlan(
identity=identity, payload=payload, discussion_event_id=discussion_event.event_id, member=member,
member_index=member_index, round_index=round_index, seen_through_seq=seen_through_seq)
@@ -680,7 +657,8 @@ def _effective_watermarks(
) -> dict[tuple[str, str], int]:
watermarks = {
(str(thread_id), str(member_id)): int(value)
- for (thread_id, member_id), value in (initial_watermarks or {}).items()
+ for (thread_id, member_id),
+ value in (initial_watermarks or {}).items()
if int(value) >= 0}
for key, value in _derive_member_watermarks(validated).items():
watermarks[key] = max(watermarks.get(key, 0), value)
@@ -698,8 +676,8 @@ def plan_next_task(
return DiscussionDecision(status="idle", reason="no_pending_user_event")
thread_id = str(discussion.payload["thread_id"])
decide = partial(
- DiscussionDecision, discussion_event_id=discussion.event_id,
- source_event_seq=discussion.seq, thread_id=thread_id)
+ DiscussionDecision, discussion_event_id=discussion.event_id, source_event_seq=discussion.seq,
+ thread_id=thread_id)
thread_messages, discussion_messages, member_messages = _thread_messages(validated, discussion)
if len(member_messages) >= MAX_DISCUSSION_MESSAGES:
@@ -730,8 +708,8 @@ def plan_next_task(
if not any(watermark < event.seq <= seen_through_seq for event in thread_messages):
continue
prompt = _build_prompt(
- room=room, member=member, messages=thread_messages,
- watermark=watermark, seen_through_seq=seen_through_seq)
+ room=room, member=member, messages=thread_messages, watermark=watermark,
+ seen_through_seq=seen_through_seq)
task = _make_task_plan(
room=room, discussion_event=discussion, member=member, member_index=member_index,
round_index=round_index, seen_through_seq=seen_through_seq, prompt=prompt)
@@ -746,8 +724,8 @@ def plan_next_task(
def reconstruct_task_plan(
- room_value: Any, events: Sequence[Mapping[str, Any]], task: Mapping[str, Any],
- *, local_profiles: Iterable[str]) -> DiscussionTaskPlan:
+ room_value: Any, events: Sequence[Mapping[str, Any]], task: Mapping[str, Any], *, local_profiles: Iterable[str]
+) -> DiscussionTaskPlan:
"""Reconstruct and verify one persisted driver task after a restart."""
room = validate_room(room_value, local_profiles=local_profiles)
validated = _validated_events(events, room=room)
@@ -775,8 +753,7 @@ def reconstruct_task_plan(
(
candidate for candidate in room.members
if candidate.profile == profile
- and (target_member_id is None or candidate.member_id == target_member_id)),
- None)
+ and (target_member_id is None or candidate.member_id == target_member_id)), None)
if member is None or _member_digest(member) != match.group("member"):
raise DiscussionReconstructionError("task target member does not match turn_id")
prompt = payload.get("prompt")
@@ -797,8 +774,7 @@ def _turn_coordinates(task: DiscussionTaskPlan) -> dict[str, Any]:
return {
"discussion_event_id": task.discussion_event_id, "member_id": task.member.member_id,
"member_index": task.member_index, "round_index": task.round_index, "task_id": task.identity.task_id,
- "thread_id": task.identity.thread_id, "turn_id": task.identity.turn_id,
- }
+ "thread_id": task.identity.thread_id, "turn_id": task.identity.turn_id}
def _terminal_text(result: Any, *, field: str, fallback: str) -> str:
@@ -820,8 +796,8 @@ def _settled_effects(
result: Any, *, task: DiscussionTaskPlan, room: DiscussionRoom, message_event_id: str, **_: Any
) -> tuple[dict[str, Any], list[EventPlan]]:
text = _truncate_utf8_text(
- _terminal_text(result, field="text", fallback=""),
- max_bytes=MAX_MEMBER_TEXT_BYTES, suffix=_TRUNCATED_REPLY_NOTICE)
+ _terminal_text(result, field="text", fallback=""), max_bytes=MAX_MEMBER_TEXT_BYTES,
+ suffix=_TRUNCATED_REPLY_NOTICE)
passed = is_pass_text(text)
effects: list[EventPlan] = []
if not passed:
@@ -833,8 +809,8 @@ def _settled_effects(
member_actor["display_name"] = task.member.display_name
effects.append(EventPlan(
event_id=message_event_id, kind="message.member", actor=member_actor,
- payload={**_turn_coordinates(task), "text": text},
- authority_gateway_id=room.gateway_id, authority_epoch=room.authority_epoch))
+ payload={**_turn_coordinates(task), "text": text}, authority_gateway_id=room.gateway_id,
+ authority_epoch=room.authority_epoch))
return {"message_event_id": None if passed else message_event_id, "passed": passed}, effects
@@ -860,14 +836,12 @@ def _deferred_effects(
result: Any, *, execution_generation: int | None, **_: Any) -> tuple[dict[str, Any], list[EventPlan]]:
return {
"execution_generation": execution_generation,
- "reason": _terminal_text(result, field="reason", fallback="member_unavailable"),
- }, []
+ "reason": _terminal_text(result, field="reason", fallback="member_unavailable")}, []
_TERMINAL_EFFECTS = {
"settled": _settled_effects, "failed": _failed_effects, "cancelled": _cancelled_effects,
- "deferred": _deferred_effects,
-}
+ "deferred": _deferred_effects}
def plan_publication(
@@ -903,12 +877,11 @@ def plan_publication(
if effective_status == "deferred" else f"dterminal:{digest}")
common_payload = {**_turn_coordinates(task), "seen_through_seq": task.seen_through_seq}
extra, effects = _TERMINAL_EFFECTS[effective_status](
- result, task=task, room=room, message_event_id=f"dmessage:{digest}",
- newer_same_thread=newer_same_thread, execution_generation=execution_generation)
+ result, task=task, room=room, message_event_id=f"dmessage:{digest}", newer_same_thread=newer_same_thread,
+ execution_generation=execution_generation)
terminal_kind = f"turn.{effective_status}"
effects.append(EventPlan(
- event_id=terminal_event_id, kind=terminal_kind,
- actor={"kind": "gateway", "id": room.gateway_id},
- payload={**common_payload, **extra},
- authority_gateway_id=room.gateway_id, authority_epoch=room.authority_epoch))
+ event_id=terminal_event_id, kind=terminal_kind, actor={"kind": "gateway", "id": room.gateway_id},
+ payload={**common_payload, **extra}, authority_gateway_id=room.gateway_id, authority_epoch=room.authority_epoch
+ ))
return PublicationPlan(task_id=task.identity.task_id, terminal_kind=terminal_kind, events=tuple(effects))
diff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.py
index 89533d2ae50..48d0097337a 100644
--- a/gateway/hosted_room_driver.py
+++ b/gateway/hosted_room_driver.py
@@ -37,13 +37,13 @@ TERMINAL_STATUSES = frozenset({"settled", "failed", "cancelled"})
_TASK_PAYLOAD_REQUIRED_FIELDS = frozenset({"target_profile", "prompt", "source_event_seq"})
_TASK_PAYLOAD_OPTIONAL_FIELDS = frozenset({"target_member_id"})
_LEASE_COLUMNS = frozenset({
- "room_id", "gateway_id", "authority_epoch", "process_generation",
- "lease_generation", "expires_at", "acquired_at", "updated_at", "released_at"})
+ "room_id", "gateway_id", "authority_epoch", "process_generation", "lease_generation", "expires_at", "acquired_at",
+ "updated_at", "released_at"})
_TASK_COLUMN_ORDER = (
- "room_id", "task_id", "thread_id", "turn_id", "source_event_seq", "payload_json", "payload_digest",
- "status", "execution_generation", "cancel_generation", "run_gateway_id", "run_process_generation",
- "run_lease_generation", "cancel_id", "settlement_id", "settlement_status", "result_json", "created_at",
- "updated_at", "started_at", "terminal_at", "indeterminate_at")
+ "room_id", "task_id", "thread_id", "turn_id", "source_event_seq", "payload_json", "payload_digest", "status",
+ "execution_generation", "cancel_generation", "run_gateway_id", "run_process_generation", "run_lease_generation",
+ "cancel_id", "settlement_id", "settlement_status", "result_json", "created_at", "updated_at", "started_at",
+ "terminal_at", "indeterminate_at")
_TASK_COLUMNS = frozenset(_TASK_COLUMN_ORDER)
_TASK_ORDER = "ORDER BY source_event_seq, created_at, task_id"
_SELECT_LEASE = "SELECT * FROM hosted_room_driver_leases WHERE room_id=?"
@@ -73,15 +73,13 @@ def _generation_update(set_clause: str, status: str) -> str:
_SETTLE_RUNNING_SQL = _generation_update(_SETTLE_SET, "running") + f" AND {_RUN_FENCE}"
_SETTLE_STOPPING_SQL = _generation_update(_SETTLE_SET, "stopping")
_REQUEUE_RUNNING_SQL = _task_update(
- f"{_REQUEUE_SET}, started_at=NULL, updated_at=?",
- f"status='running' AND {_GENERATION_FENCE} AND {_RUN_FENCE}")
+ f"{_REQUEUE_SET}, started_at=NULL, updated_at=?", f"status='running' AND {_GENERATION_FENCE} AND {_RUN_FENCE}")
_CANCEL_QUEUED_SQL = _task_update(_CANCEL_SET, "status IN ('queued', 'deferred') AND cancel_generation=?")
_BEGIN_STOP_SQL = _task_update(
"status='stopping', cancel_generation=?, cancel_id=?, updated_at=?",
"status IN ('running', 'indeterminate') AND cancel_generation=?")
_COMPLETE_STOP_SQL = _task_update(
- "status='cancelled', terminal_at=?, updated_at=?",
- "status='stopping' AND cancel_id=? AND cancel_generation=?")
+ "status='cancelled', terminal_at=?, updated_at=?", "status='stopping' AND cancel_id=? AND cancel_generation=?")
# Lease-first recovery transitions: name -> (fenced status, SET clause, generation-guard stale message,
# row stale message); the UPDATE is _generation_update(set_clause, status).
@@ -92,11 +90,11 @@ _GENERATION_TRANSITIONS = {
"indeterminate", _CANCEL_SET, "indeterminate cancellation proof is stale",
"indeterminate cancellation proof lost its fence"),
"requeue": (
- "indeterminate", f"{_REQUEUE_SET}, started_at=NULL, indeterminate_at=NULL, updated_at=?",
- _INDETERMINATE_STALE, "indeterminate task changed during requeue"),
+ "indeterminate", f"{_REQUEUE_SET}, started_at=NULL, indeterminate_at=NULL, updated_at=?", _INDETERMINATE_STALE,
+ "indeterminate task changed during requeue"),
"defer": (
- "indeterminate", "status='deferred', result_json=?, terminal_at=?, updated_at=?",
- _INDETERMINATE_STALE, "indeterminate task changed during deferral"),
+ "indeterminate", "status='deferred', result_json=?, terminal_at=?, updated_at=?", _INDETERMINATE_STALE,
+ "indeterminate task changed during deferral"),
"requeue_deferred": (
"deferred",
f"{_REQUEUE_SET}, result_json=NULL, started_at=NULL, terminal_at=NULL, indeterminate_at=NULL, updated_at=?",
@@ -130,8 +128,7 @@ class InvalidTaskTransitionError(DriverStateError): """Raised when a requested t
_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)
+ 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:
@@ -238,8 +235,7 @@ def _create_task_table(conn: sqlite3.Connection, table: str = "hosted_room_drive
def _initialize_schema(conn: sqlite3.Connection) -> None:
- conn.execute(
- """CREATE TABLE IF NOT EXISTS hosted_room_driver_leases (
+ conn.execute("""CREATE TABLE IF NOT EXISTS hosted_room_driver_leases (
room_id TEXT PRIMARY KEY, gateway_id TEXT NOT NULL,
authority_epoch INTEGER NOT NULL CHECK (authority_epoch >= 1), process_generation TEXT NOT NULL,
lease_generation INTEGER NOT NULL CHECK (lease_generation >= 1),
@@ -265,8 +261,7 @@ def _validate_schema(conn: sqlite3.Connection) -> None:
def _schema_objects_exist(conn: sqlite3.Connection) -> bool:
- rows = conn.execute(
- """SELECT name FROM sqlite_master WHERE type='table'
+ rows = conn.execute("""SELECT name FROM sqlite_master WHERE type='table'
AND name IN ('hosted_room_driver_leases', 'hosted_room_driver_tasks')"""
).fetchall()
if {row[0] for row in rows} != {"hosted_room_driver_leases", "hosted_room_driver_tasks"}:
@@ -343,9 +338,8 @@ def _optional(cast: Callable[[Any], Any]) -> Callable[[Any], Any]:
# result_json is exposed as "result"). Columns not listed are passed through untouched.
_TASK_VIEW_CASTS: dict[str, Callable[[Any], Any]] = {
"execution_generation": int, "cancel_generation": int, "run_lease_generation": _optional(int),
- "result_json": _optional(json.loads), "created_at": float, "updated_at": float,
- "started_at": _optional(float), "terminal_at": _optional(float), "indeterminate_at": _optional(float),
-}
+ "result_json": _optional(json.loads), "created_at": float, "updated_at": float, "started_at": _optional(float),
+ "terminal_at": _optional(float), "indeterminate_at": _optional(float)}
def _task_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str, Any]:
@@ -478,8 +472,8 @@ def _require_cancel_generation(row: sqlite3.Row, expected_cancel_generation: int
def _transition(
db_path: Path | str, identity: TaskIdentity, *, sql: str, set_params: tuple[Any, ...],
- fence_params: tuple[Any, ...], stale: str, now: float, lease: DriverLease | None = None,
- lease_first: bool = True, replay: Callable[[sqlite3.Row], dict[str, Any] | None] | None = None,
+ fence_params: tuple[Any, ...], stale: str, now: float, lease: DriverLease | None = None, lease_first: bool = True,
+ replay: Callable[[sqlite3.Row], dict[str, Any] | None] | None = None,
guard: Callable[[sqlite3.Row], None] | None = None) -> dict[str, Any]:
"""Run one fenced task transition: load -> idempotent replay -> lease/fence guard -> UPDATE.
@@ -517,14 +511,13 @@ def _generation_transition(
raise StaleTaskError(generation_stale)
return _transition(
- db_path, identity, lease=lease, now=now, replay=replay, guard=guard,
- sql=_generation_update(set_clause, status), set_params=set_params,
- fence_params=(execution_generation, cancel_generation), stale=stale)
+ db_path, identity, lease=lease, now=now, replay=replay, guard=guard, sql=_generation_update(set_clause, status),
+ set_params=set_params, fence_params=(execution_generation, cancel_generation), stale=stale)
def _run_fence_transition(
- db_path: Path | str, attempt: TaskAttempt, *, guard_stale: str,
- lease_generation: Callable[[Any], int] = int, **transition: Any) -> dict[str, Any]:
+ db_path: Path | str, attempt: TaskAttempt, *, guard_stale: str, lease_generation: Callable[[Any], int] = int,
+ **transition: Any) -> dict[str, Any]:
"""Transition fenced on this attempt's running generation under its exact lease (row guard + SQL fence).
``lease_generation`` casts the stored run_lease_generation: ``int`` raises on NULL, ``int(v or 0)`` reads 0.
@@ -542,9 +535,8 @@ def _run_fence_transition(
return _transition(
db_path, attempt.identity, lease=lease, guard=guard,
fence_params=(
- attempt.execution_generation, attempt.cancel_generation,
- lease.gateway_id, lease.process_generation, lease.lease_generation),
- **transition)
+ attempt.execution_generation, attempt.cancel_generation, lease.gateway_id, lease.process_generation,
+ lease.lease_generation), **transition)
def acquire_lease(
@@ -563,8 +555,7 @@ def acquire_lease(
_require_room_authority(conn, room_id=room_id, gateway_id=gateway_id, authority_epoch=authority_epoch)
row = conn.execute(_SELECT_LEASE, (room_id,)).fetchone()
if row is None:
- conn.execute(
- """INSERT INTO hosted_room_driver_leases (
+ conn.execute("""INSERT INTO hosted_room_driver_leases (
room_id, gateway_id, authority_epoch, process_generation, lease_generation,
expires_at, acquired_at, updated_at, released_at
) VALUES (?, ?, ?, ?, 1, ?, ?, ?, NULL)""",
@@ -582,15 +573,14 @@ def acquire_lease(
if same_authority and live:
raise LeaseHeldError("room driver lease is held by another generation")
- updated = conn.execute(
- """UPDATE hosted_room_driver_leases
+ updated = conn.execute("""UPDATE hosted_room_driver_leases
SET gateway_id=?, authority_epoch=?, process_generation=?, lease_generation=lease_generation + 1,
expires_at=?, acquired_at=?, updated_at=?, released_at=NULL
WHERE room_id=? AND lease_generation=? AND (
gateway_id != ? OR authority_epoch != ? OR released_at IS NOT NULL OR expires_at <= ?)""",
(
- gateway_id, authority_epoch, process_generation, expires_at, now, now,
- room_id, int(row["lease_generation"]), gateway_id, authority_epoch, now))
+ gateway_id, authority_epoch, process_generation, expires_at, now, now, room_id,
+ int(row["lease_generation"]), gateway_id, authority_epoch, now))
if updated.rowcount != 1:
raise LeaseHeldError("room driver lease changed during acquisition")
return _lease_from_row(conn.execute(_SELECT_LEASE, (room_id,)).fetchone(), reclaimed=True)
@@ -604,8 +594,7 @@ def renew_lease(db_path: Path | str, lease: DriverLease, *, ttl_seconds: Any, cl
with _transaction(db_path) as conn:
current = _require_active_lease(conn, lease, now=now)
expires_at = max(float(current["expires_at"]), requested_expiry)
- updated = conn.execute(
- """UPDATE hosted_room_driver_leases SET expires_at=?, updated_at=?
+ updated = conn.execute("""UPDATE hosted_room_driver_leases SET expires_at=?, updated_at=?
WHERE room_id=? AND gateway_id=? AND process_generation=?
AND lease_generation=? AND released_at IS NULL AND expires_at > ?""",
(expires_at, now, lease.room_id, lease.gateway_id, lease.process_generation, lease.lease_generation, now))
@@ -631,8 +620,7 @@ def release_lease(db_path: Path | str, lease: DriverLease, *, clock: Clock) -> d
).fetchone()
if running is not None:
raise InvalidTaskTransitionError("cannot release a room lease while tasks are running")
- conn.execute(
- """UPDATE hosted_room_driver_leases SET expires_at=?, updated_at=?, released_at=?
+ conn.execute("""UPDATE hosted_room_driver_leases SET expires_at=?, updated_at=?, released_at=?
WHERE room_id=? AND lease_generation=?""",
(now, now, now, lease.room_id, lease.lease_generation))
current = {**dict(row), "expires_at": now, "updated_at": now, "released_at": now}
@@ -657,8 +645,7 @@ def admit_task(db_path: Path | str, identity: TaskIdentity, *, payload: Any, clo
(identity.room_id, identity.thread_id, identity.turn_id)).fetchone()
if turn is not None:
raise TaskConflictError("thread_id and turn_id are already bound to a task")
- conn.execute(
- """INSERT INTO hosted_room_driver_tasks (
+ conn.execute("""INSERT INTO hosted_room_driver_tasks (
room_id, task_id, thread_id, turn_id, source_event_seq, payload_json, payload_digest,
status, execution_generation, cancel_generation, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', 0, 0, ?, ?)""",
@@ -693,8 +680,7 @@ def start_task(
if next_queued is None or next_queued["task_id"] != identity.task_id:
raise InvalidTaskTransitionError("task is not next in the hosted room event order")
execution_generation = int(row["execution_generation"]) + 1
- updated = conn.execute(
- """UPDATE hosted_room_driver_tasks
+ updated = conn.execute("""UPDATE hosted_room_driver_tasks
SET status='running', execution_generation=?, run_gateway_id=?, run_process_generation=?,
run_lease_generation=?, started_at=?, updated_at=?
WHERE room_id=? AND task_id=? AND status='queued' AND cancel_generation=?""",
@@ -704,8 +690,8 @@ def start_task(
if updated.rowcount != 1:
raise StaleTaskError("task changed during start")
return TaskAttempt(
- identity=identity, lease=lease,
- execution_generation=execution_generation, cancel_generation=expected_cancel_generation)
+ identity=identity, lease=lease, execution_generation=execution_generation,
+ cancel_generation=expected_cancel_generation)
def settle_task(
@@ -717,14 +703,13 @@ def settle_task(
now = _timestamp(clock)
return _run_fence_transition(
db_path, attempt, guard_stale="task attempt is stale or cancelled", lease_first=False, now=now,
- replay=_settlement_replay(settlement_id, status, result_json),
- sql=_SETTLE_RUNNING_SQL, set_params=(status, settlement_id, status, result_json, now, now),
- stale="task changed during settlement")
+ replay=_settlement_replay(settlement_id, status, result_json), sql=_SETTLE_RUNNING_SQL,
+ set_params=(status, settlement_id, status, result_json, now, now), stale="task changed during settlement")
def settle_stopping_task(
db_path: Path | str, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,
- expected_cancel_generation: int, settlement_id: Any, status: TerminalStatus, result: Any, clock: Clock,
+ expected_cancel_generation: int, settlement_id: Any, status: TerminalStatus, result: Any, clock: Clock
) -> dict[str, Any]:
"""Commit a completion that won the race with an unacknowledged Stop."""
settlement_id = _terminal_settlement_id(settlement_id, status)
@@ -734,15 +719,15 @@ def settle_stopping_task(
now = _timestamp(clock)
return _transition(
db_path, identity, lease=lease, lease_first=False, now=now,
- replay=_settlement_replay(settlement_id, status, result_json),
- sql=_SETTLE_STOPPING_SQL, set_params=(status, settlement_id, status, result_json, now, now),
+ replay=_settlement_replay(settlement_id, status, result_json), sql=_SETTLE_STOPPING_SQL,
+ set_params=(status, settlement_id, status, result_json, now, now),
fence_params=(expected_execution_generation, expected_cancel_generation),
stale="task completion lost the stop race")
def resolve_indeterminate_task(
db_path: Path | str, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,
- expected_cancel_generation: int, settlement_id: Any, status: TerminalStatus, result: Any, clock: Clock,
+ expected_cancel_generation: int, settlement_id: Any, status: TerminalStatus, result: Any, clock: Clock
) -> dict[str, Any]:
"""Commit a verified historical receipt under the current room lease."""
_expected_generations(lease, identity, expected_execution_generation, expected_cancel_generation)
@@ -763,8 +748,8 @@ def resolve_indeterminate_cancellation(
cancel_id = _identifier(cancel_id, label="cancel_id")
now = _timestamp(clock)
return _generation_transition(
- db_path, identity, lease, "resolve_cancel", expected_execution_generation, expected_cancel_generation,
- now=now, replay=_cancel_replay(cancel_id), set_params=(expected_cancel_generation + 1, cancel_id, now, now))
+ db_path, identity, lease, "resolve_cancel", expected_execution_generation, expected_cancel_generation, now=now,
+ replay=_cancel_replay(cancel_id), set_params=(expected_cancel_generation + 1, cancel_id, now, now))
def requeue_indeterminate_task(
@@ -822,8 +807,8 @@ def requeue_not_admitted_task(db_path: Path | str, attempt: TaskAttempt, *, cloc
return _run_fence_transition(
db_path, attempt, guard_stale="not-admitted task attempt lost its fence",
- lease_generation=lambda value: int(value or 0), now=now, replay=replay,
- sql=_REQUEUE_RUNNING_SQL, set_params=(now,), stale="not-admitted task changed during requeue")
+ lease_generation=lambda value: int(value or 0), now=now, replay=replay, sql=_REQUEUE_RUNNING_SQL,
+ set_params=(now,), stale="not-admitted task changed during requeue")
def cancel_task(
@@ -896,8 +881,7 @@ def recover_room(db_path: Path | str, lease: DriverLease, *, clock: Clock) -> di
if stale_rows:
conn.execute(
f"""UPDATE hosted_room_driver_tasks SET status='indeterminate', indeterminate_at=?, updated_at=?
- WHERE {foreign_running}""",
- (now, now, *fence))
+ WHERE {foreign_running}""", (now, now, *fence))
return {
status: [_task_identity_from_row(row) for row in _tasks_in_order(conn, lease.room_id, status)]
for status in ("queued", "indeterminate")}
@@ -925,8 +909,8 @@ def list_tasks(db_path: Path | str, *, room_id: Any, status: TaskStatus | None =
def prune_published_terminal_tasks(
- db_path: Path | str, *, room_id: Any, clock: Clock,
- retention_seconds: float = TERMINAL_TASK_RETENTION_SECONDS, retain: int = MAX_RETAINED_TERMINAL_TASKS) -> int:
+ db_path: Path | str, *, room_id: Any, clock: Clock, retention_seconds: float = TERMINAL_TASK_RETENTION_SECONDS,
+ retain: int = MAX_RETAINED_TERMINAL_TASKS) -> int:
"""Bound execution rows after outcomes are durable in the room log."""
room_id = _identifier(room_id, label="room_id")
now = _timestamp(clock)
@@ -939,8 +923,7 @@ def prune_published_terminal_tasks(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='hosted_room_policy_publications'").fetchone()
if publications is None:
return 0
- rows = conn.execute(
- """SELECT t.task_id, t.terminal_at FROM hosted_room_driver_tasks t
+ rows = conn.execute("""SELECT t.task_id, t.terminal_at FROM hosted_room_driver_tasks t
WHERE t.room_id=? AND t.status IN ('settled', 'failed', 'cancelled')
AND EXISTS (SELECT 1 FROM hosted_room_policy_publications p
WHERE p.room_id=t.room_id AND p.task_id=t.task_id
@@ -949,7 +932,8 @@ def prune_published_terminal_tasks(
cutoff = now - float(retention_seconds)
candidates = [
str(row["task_id"])
- for index, row in enumerate(rows)
+ for index,
+ row in enumerate(rows)
if index >= retain or (row["terminal_at"] is not None and float(row["terminal_at"]) <= cutoff)
][:MAX_TASK_PRUNE_BATCH]
if not candidates:
diff --git a/gateway/hosted_room_execution_policy.py b/gateway/hosted_room_execution_policy.py
index 6bc87f6a86e..6766aff866c 100644
--- a/gateway/hosted_room_execution_policy.py
+++ b/gateway/hosted_room_execution_policy.py
@@ -3,17 +3,15 @@
from __future__ import annotations
import hashlib
-import json
-import re
from contextvars import ContextVar, Token
from dataclasses import asdict, dataclass
from typing import Any, Mapping
+from gateway.hosted_rooms_common import compact_json, identifier
POLICY_VERSION = 1
MAX_POLICY_TOOLSETS = 128
MAX_POLICY_ITERATIONS = (1 << 53) - 1
-_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]*$")
_POLICY_FIELDS = {"version", "target_profile", "enabled_toolsets", "approval_mode", "max_iterations", "policy_digest"}
@@ -21,16 +19,12 @@ class RoomExecutionPolicyError(ValueError): """A RoomLink execution policy is ma
def _policy_digest(unsigned: Mapping[str, Any]) -> str:
- encoded = json.dumps(unsigned, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode("ascii")
- return hashlib.sha256(encoded).hexdigest()
+ return hashlib.sha256(compact_json(unsigned).encode("ascii")).hexdigest()
def _identifier(value: Any, *, field: str) -> str:
# Stringifies first (``None`` -> ""), so non-strings also fail as "is invalid".
- normalized = str(value or "").strip()
- if not normalized or len(normalized) > 128 or _IDENTIFIER_RE.fullmatch(normalized) is None:
- raise RoomExecutionPolicyError(f"{field} is invalid")
- return normalized
+ return identifier(str(value or ""), label=field, error=RoomExecutionPolicyError, invalid=f"{field} is invalid")
@dataclass(frozen=True)
@@ -68,8 +62,7 @@ class RoomExecutionPolicy:
raise RoomExecutionPolicyError("max_iterations is invalid")
unsigned = {
"version": POLICY_VERSION, "target_profile": target_profile, "enabled_toolsets": list(toolsets),
- "approval_mode": approval_mode, "max_iterations": max_iterations,
- }
+ "approval_mode": approval_mode, "max_iterations": max_iterations}
supplied = str(value["policy_digest"] or "").strip().lower()
if supplied != _policy_digest(unsigned):
raise RoomExecutionPolicyError("policy_digest does not match the execution policy")
@@ -99,8 +92,7 @@ def execution_policy_mapping(*, target_profile: str, config: Mapping[str, Any] |
"version": POLICY_VERSION, "target_profile": _identifier(target_profile, field="target_profile"),
"enabled_toolsets": toolsets,
"approval_mode": ("off" if _YOLO_MODE_FROZEN else _normalize_approval_mode(approvals.get("mode", "manual"))),
- "max_iterations": min(resolve_turn_limit(agent.get("max_turns")), MAX_POLICY_ITERATIONS),
- }
+ "max_iterations": min(resolve_turn_limit(agent.get("max_turns")), MAX_POLICY_ITERATIONS)}
value = {**unsigned, "policy_digest": _policy_digest(unsigned)}
return RoomExecutionPolicy.from_mapping(value).as_mapping()
@@ -123,5 +115,4 @@ def current_room_execution_policy() -> RoomExecutionPolicy | None:
__all__ = [
"MAX_POLICY_ITERATIONS", "POLICY_VERSION", "RoomExecutionPolicy", "RoomExecutionPolicyError",
"bind_room_execution_policy", "current_room_execution_policy", "execution_policy_mapping",
- "reset_room_execution_policy",
-]
+ "reset_room_execution_policy"]
diff --git a/gateway/hosted_room_links.py b/gateway/hosted_room_links.py
index 7658b6be9c4..10efc6254d7 100644
--- a/gateway/hosted_room_links.py
+++ b/gateway/hosted_room_links.py
@@ -18,24 +18,21 @@ from typing import Any, Mapping
from gateway import hosted_rooms
from gateway.hosted_room_peer import (
- GatewayRoomCatalog,
- HostedRoomPeerError,
- TransportSecurity,
- validate_room_link_url)
-from gateway.hosted_rooms_common import compact_json, exact_fields
+ GatewayRoomCatalog, HostedRoomPeerError, TransportSecurity, validate_room_link_url)
+from gateway.hosted_rooms_common import compact_json, exact_fields, identifier
MAX_LINKS = 512
MAX_GRANT_CHARS = 16 * 1024
_LEGACY_FIELDS = {
- "room_id", "member_id", "target_url", "target_profile", "grant", "catalog",
- "cancellation_scope_id", "trace_id", "updated_at"}
+ "room_id", "member_id", "target_url", "target_profile", "grant", "catalog", "cancellation_scope_id", "trace_id",
+ "updated_at"}
_OPTIONAL_FIELDS = {"transport_security", "status"}
# SQLite record columns that map 1:1 onto mapping fields, in record order
# (``catalog_json`` is the serialized ``catalog``).
_RECORD_FIELDS = (
- "room_id", "member_id", "target_url", "target_profile", "grant", "cancellation_scope_id",
- "trace_id", "transport_security", "status", "updated_at")
+ "room_id", "member_id", "target_url", "target_profile", "grant", "cancellation_scope_id", "trace_id",
+ "transport_security", "status", "updated_at")
_STATUSES = {"ready", "unavailable", "needs_reauthorization"}
@@ -109,10 +106,9 @@ _link_fields = partial(
def _short_string(value: Any, field: str) -> str:
- normalized = str(value or "").strip()
- if not normalized or len(normalized) > 256:
- raise HostedRoomPeerError(f"{field} is invalid")
- return normalized
+ return identifier(
+ str(value or ""), label=field, error=HostedRoomPeerError, max_chars=256, pattern=None,
+ invalid=f"{field} is invalid")
def _link_rows(db_path: Path | str) -> list[dict[str, Any]]:
@@ -156,11 +152,10 @@ def mark_room_link_status(db_path: Path | str, *, room_id: str, member_id: str,
def make_stored_link(
- *, room_id: str, member_id: str, target_url: str, target_profile: str, grant: str,
- catalog: GatewayRoomCatalog, cancellation_scope_id: str, trace_id: str) -> StoredRoomLink:
+ *, room_id: str, member_id: str, target_url: str, target_profile: str, grant: str, catalog: GatewayRoomCatalog,
+ cancellation_scope_id: str, trace_id: str) -> StoredRoomLink:
target_url, transport_security = validate_room_link_url(target_url)
return StoredRoomLink.from_mapping({
"room_id": room_id, "member_id": member_id, "target_url": target_url, "target_profile": target_profile,
"grant": grant, "catalog": catalog.as_mapping(), "cancellation_scope_id": cancellation_scope_id,
- "trace_id": trace_id, "transport_security": transport_security, "status": "ready", "updated_at": time.time(),
- })
+ "trace_id": trace_id, "transport_security": transport_security, "status": "ready", "updated_at": time.time()})
diff --git a/gateway/hosted_room_peer.py b/gateway/hosted_room_peer.py
index bcb22f7d2b4..ce26c77c570 100644
--- a/gateway/hosted_room_peer.py
+++ b/gateway/hosted_room_peer.py
@@ -131,8 +131,7 @@ def _identifier(value: Any, *, field: str) -> str:
def _positive_int(value: Any, *, field: str) -> int:
- return bounded_int(
- value, error=HostedRoomPeerError, message=f"{field} must be a positive integer", low=1)
+ return bounded_int(value, error=HostedRoomPeerError, message=f"{field} must be a positive integer", low=1)
def _digest(value: Any, *, field: str) -> str:
@@ -191,8 +190,8 @@ def _parse_endpoint(endpoint: Any) -> tuple[str | None, str | None, TransportSec
_CATALOG_FIELDS = {
- "installation_id", "protocol_versions", "link_modes", "persistent_process", "text",
- "attachments", "execution_policy", "catalog_digest"}
+ "installation_id", "protocol_versions", "link_modes", "persistent_process", "text", "attachments",
+ "execution_policy", "catalog_digest"}
@dataclass(frozen=True)
@@ -229,9 +228,8 @@ class GatewayRoomCatalog:
endpoint_url, endpoint_reason, transport_security = _parse_endpoint(value["endpoint"])
catalog = cls(
installation_id=installation_id, protocol_versions=versions, link_modes=links,
- persistent_process=value["persistent_process"], text=value["text"],
- attachments=value["attachments"], execution_policy=policy,
- catalog_digest=_digest(value["catalog_digest"], field="catalog_digest"),
+ persistent_process=value["persistent_process"], text=value["text"], attachments=value["attachments"],
+ execution_policy=policy, catalog_digest=_digest(value["catalog_digest"], field="catalog_digest"),
endpoint_url=endpoint_url, endpoint_reason=endpoint_reason, transport_security=transport_security)
unsigned = catalog.as_mapping()
del unsigned["catalog_digest"]
@@ -244,9 +242,9 @@ class GatewayRoomCatalog:
"""Canonical catalog mapping; ``endpoint`` appears only when advertised."""
value = {
"installation_id": self.installation_id, "protocol_versions": list(self.protocol_versions),
- "link_modes": list(self.link_modes), "persistent_process": self.persistent_process,
- "text": self.text, "attachments": self.attachments,
- "execution_policy": self.execution_policy.as_mapping(), "catalog_digest": self.catalog_digest}
+ "link_modes": list(self.link_modes), "persistent_process": self.persistent_process, "text": self.text,
+ "attachments": self.attachments, "execution_policy": self.execution_policy.as_mapping(),
+ "catalog_digest": self.catalog_digest}
if self.endpoint_url is not None or self.endpoint_reason is not None:
value["endpoint"] = self.endpoint_mapping()
return value
@@ -380,12 +378,10 @@ def validate_room_link_url(value: Any) -> tuple[str, TransportSecurity]:
# Validator per dispatch field, in validation order. ``prompt`` and
# ``prompt_digest`` are checked together against each other in from_mapping.
_DISPATCH_FIELDS: dict[str, Callable[..., Any]] = dict(
- protocol_version=_positive_int, room_id=_identifier, home_install_id=_identifier,
- authority_gateway_id=_identifier, authority_epoch=_positive_int, member_id=_identifier,
- target_install_id=_identifier, target_profile=_identifier, task_id=_identifier,
- execution_generation=_positive_int, source_event_seq=_positive_int, cancellation_scope_id=_identifier,
- capability_digest=_digest, execution_policy_digest=_digest, trace_id=_identifier,
-)
+ protocol_version=_positive_int, room_id=_identifier, home_install_id=_identifier, authority_gateway_id=_identifier,
+ authority_epoch=_positive_int, member_id=_identifier, target_install_id=_identifier, target_profile=_identifier,
+ task_id=_identifier, execution_generation=_positive_int, source_event_seq=_positive_int,
+ cancellation_scope_id=_identifier, capability_digest=_digest, execution_policy_digest=_digest, trace_id=_identifier)
@dataclass(frozen=True)
@@ -433,8 +429,8 @@ class HostedMemberDispatch:
# Grant scope fields, in issue-time validation order; each is validated with
# the same checker as the matching dispatch field (``grant_id`` is an identifier).
_GRANT_SCOPE = (
- "grant_id", "room_id", "home_install_id", "authority_gateway_id", "authority_epoch",
- "member_id", "target_install_id", "target_profile")
+ "grant_id", "room_id", "home_install_id", "authority_gateway_id", "authority_epoch", "member_id",
+ "target_install_id", "target_profile")
_GRANT_FIELDS = frozenset({
"version", *_GRANT_SCOPE, "execution_policy_digest", "permissions", "issued_at", "expires_at"})
_GRANT_REFRESH_FIELDS = _GRANT_FIELDS | {"status_expires_at"}
@@ -446,9 +442,9 @@ MAX_STATUS_GRANT_TTL_SECONDS = 30 * 24 * 60 * 60
def issue_room_grant(
secret: bytes, *, grant_id: str, room_id: str, home_install_id: str, authority_gateway_id: str,
authority_epoch: int, member_id: str, target_install_id: str, target_profile: str,
- execution_policy_digest: str | None = None,
- permissions: Iterable[str] = ("approve", "dispatch", "status", "stop"), issued_at: float | None = None,
- ttl_seconds: float = 3600, status_ttl_seconds: float | None = None, status_expires_at: float | None = None) -> str:
+ execution_policy_digest: str | None = None, permissions: Iterable[str] = ("approve", "dispatch", "status", "stop"),
+ issued_at: float | None = None, ttl_seconds: float = 3600, status_ttl_seconds: float | None = None,
+ status_expires_at: float | None = None) -> str:
"""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")
@@ -467,16 +463,15 @@ def issue_room_grant(
raise HostedRoomGrantError("room grant permissions are invalid")
scope = {
"grant_id": grant_id, "room_id": room_id, "home_install_id": home_install_id,
- "authority_gateway_id": authority_gateway_id, "authority_epoch": authority_epoch,
- "member_id": member_id, "target_install_id": target_install_id, "target_profile": target_profile}
+ "authority_gateway_id": authority_gateway_id, "authority_epoch": authority_epoch, "member_id": member_id,
+ "target_install_id": target_install_id, "target_profile": target_profile}
payload = {
"version": PROTOCOL_VERSION,
**{name: _DISPATCH_FIELDS.get(name, _identifier)(scope[name], field=name) for name in _GRANT_SCOPE},
"execution_policy_digest": _digest(
execution_policy_digest
- or execution_policy_mapping(target_profile=target_profile)["policy_digest"],
- field="execution_policy_digest"),
- "permissions": list(allowed), "issued_at": now, "expires_at": now + float(ttl_seconds),
+ or execution_policy_mapping(target_profile=target_profile)["policy_digest"], field="execution_policy_digest"
+ ), "permissions": list(allowed), "issued_at": now, "expires_at": now + float(ttl_seconds),
"status_expires_at": bounded_status_expiry}
encoded = _canonical_json(payload)
signature = hmac.new(secret, encoded, hashlib.sha256).digest()
@@ -487,8 +482,8 @@ def issue_room_grant(
def verify_room_grant(
- secret: bytes, token: str, dispatch: HostedMemberDispatch, *, permission: str = "dispatch",
- now: float | None = None) -> dict[str, Any]:
+ secret: bytes, token: str, dispatch: HostedMemberDispatch, *, permission: str = "dispatch", now: float | None = None
+) -> dict[str, Any]:
"""Verify one room grant against exact recipient dispatch coordinates."""
payload = decode_room_grant(secret, token, permission=permission, now=now)
if payload["version"] != dispatch.protocol_version:
diff --git a/gateway/hosted_room_policy_checkpoint.py b/gateway/hosted_room_policy_checkpoint.py
index da17a03a162..fa88bed592c 100644
--- a/gateway/hosted_room_policy_checkpoint.py
+++ b/gateway/hosted_room_policy_checkpoint.py
@@ -91,8 +91,7 @@ def _settled_message(
"SELECT seq, event_json FROM hosted_room_policy_events WHERE room_id=? AND discussion_event_id=?",
(room_id, discussion_event_id)).fetchall()
return next(
- (m for m in (json.loads(row["event_json"]) for row in rows) if m.get("event_id") == message_event_id),
- None)
+ (m for m in (json.loads(row["event_json"]) for row in rows) if m.get("event_id") == message_event_id), None)
class HostedRoomPolicyCheckpoint:
@@ -116,8 +115,7 @@ class HostedRoomPolicyCheckpoint:
@staticmethod
def _store_active_event(
conn: sqlite3.Connection, *, event: Mapping[str, Any], thread_id: str, discussion_event_id: str) -> None:
- conn.execute(
- """INSERT OR IGNORE INTO hosted_room_policy_events(
+ conn.execute("""INSERT OR IGNORE INTO hosted_room_policy_events(
room_id, thread_id, discussion_event_id, seq, event_json
) VALUES (?, ?, ?, ?, ?)""",
(event["room_id"], thread_id, discussion_event_id, int(event["seq"]), compact_json(dict(event))))
@@ -125,16 +123,14 @@ class HostedRoomPolicyCheckpoint:
@staticmethod
def _store_transcript_event(
conn: sqlite3.Connection, *, event: Mapping[str, Any], thread_id: str, settled_seq: int | None = None) -> None:
- conn.execute(
- """INSERT INTO hosted_room_policy_transcript(
+ conn.execute("""INSERT INTO hosted_room_policy_transcript(
room_id, thread_id, seq, kind, settled_seq
) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(room_id, thread_id, seq) DO UPDATE SET
settled_seq=COALESCE(excluded.settled_seq, hosted_room_policy_transcript.settled_seq)""",
(event["room_id"], thread_id, int(event["seq"]), str(event["kind"]), settled_seq))
if event["kind"] in {"message.user", "message.member"}:
- cutoff = conn.execute(
- """SELECT seq FROM hosted_room_policy_transcript
+ cutoff = conn.execute("""SELECT seq FROM hosted_room_policy_transcript
WHERE room_id=? AND thread_id=? AND kind IN ('message.user', 'message.member')
ORDER BY seq DESC LIMIT 1 OFFSET ?""",
(event["room_id"], thread_id, MAX_THREAD_TRANSCRIPT_EVENTS - 1)).fetchone()
@@ -148,8 +144,7 @@ class HostedRoomPolicyCheckpoint:
if through_seq <= 0:
return
settled_seq_by_message: dict[str, int] = {}
- for row in conn.execute(
- """SELECT seq, payload_json FROM hosted_room_events
+ for row in conn.execute("""SELECT seq, payload_json FROM hosted_room_events
WHERE room_id=? AND seq<=? AND kind='turn.settled' ORDER BY seq""", (room_id, through_seq)):
message_event_id = str(json.loads(row["payload_json"]).get("message_event_id") or "")
if message_event_id:
@@ -157,8 +152,7 @@ class HostedRoomPolicyCheckpoint:
rows = conn.execute(
f"""SELECT {_ROOM_EVENT_COLUMNS} FROM hosted_room_events
WHERE room_id=? AND seq<=? AND kind IN ('message.user', 'message.member')
- ORDER BY seq""",
- (room_id, through_seq))
+ ORDER BY seq""", (room_id, through_seq))
for row in rows:
if row["kind"] == "message.member" and row["event_id"] not in settled_seq_by_message:
continue
@@ -166,15 +160,14 @@ class HostedRoomPolicyCheckpoint:
thread_id = str(event["payload"].get("thread_id") or "")
if thread_id:
self._store_transcript_event(
- conn, event=event, thread_id=thread_id,
- settled_seq=settled_seq_by_message.get(str(row["event_id"])))
+ conn, event=event, thread_id=thread_id, settled_seq=settled_seq_by_message.get(str(row["event_id"]))
+ )
def _discussion_events(
- self, conn: sqlite3.Connection, *, room_id: str, thread_id: str, discussion_event_id: str,
- bound_error: str) -> list[dict[str, Any]]:
+ self, conn: sqlite3.Connection, *, room_id: str, thread_id: str, discussion_event_id: str, bound_error: str
+ ) -> list[dict[str, Any]]:
"""Merge the thread transcript with the active projection, ordered by seq."""
- active_rows = conn.execute(
- """SELECT event_json FROM hosted_room_policy_events
+ active_rows = conn.execute("""SELECT event_json FROM hosted_room_policy_events
WHERE room_id=? AND discussion_event_id=? ORDER BY seq LIMIT ?""",
(room_id, discussion_event_id, MAX_ACTIVE_POLICY_EVENTS + 1)).fetchall()
if len(active_rows) > MAX_ACTIVE_POLICY_EVENTS:
@@ -183,8 +176,7 @@ class HostedRoomPolicyCheckpoint:
events_by_seq = {
int(event["seq"]): event
for event in (
- *(_event_from_room_row(row) for row in rows),
- *(json.loads(row["event_json"]) for row in active_rows))}
+ *(_event_from_room_row(row) for row in rows), *(json.loads(row["event_json"]) for row in active_rows))}
return [events_by_seq[seq] for seq in sorted(events_by_seq)]
# -- per-kind projection handlers (dispatched by _apply_event) -----------
@@ -196,8 +188,7 @@ class HostedRoomPolicyCheckpoint:
event_id = str(event.get("event_id") or "")
if not thread_id or not event_id:
return
- conn.execute(
- """INSERT INTO hosted_room_policy_threads(
+ conn.execute("""INSERT INTO hosted_room_policy_threads(
room_id, thread_id, discussion_event_id, latest_user_seq, completed
) VALUES (?, ?, ?, ?, 0)
ON CONFLICT(room_id, thread_id) DO UPDATE SET
@@ -226,8 +217,7 @@ class HostedRoomPolicyCheckpoint:
task_id = str(payload.get("task_id") or "")
execution_generation = (int(payload.get("execution_generation") or 0) if kind == "turn.deferred" else 0)
if task_id:
- conn.execute(
- """INSERT OR IGNORE INTO hosted_room_policy_publications(
+ conn.execute("""INSERT OR IGNORE INTO hosted_room_policy_publications(
room_id, task_id, kind, execution_generation, seq
) VALUES (?, ?, ?, ?, ?)""",
(room_id, task_id, kind, execution_generation, seq))
@@ -239,8 +229,7 @@ class HostedRoomPolicyCheckpoint:
seen_through_seq = max(seen_through_seq, int(committed["seq"]))
self._store_transcript_event(conn, event=committed, thread_id=thread_id, settled_seq=seq)
if member_id and seen_through_seq > 0:
- conn.execute(
- """INSERT INTO hosted_room_policy_watermarks(
+ conn.execute("""INSERT INTO hosted_room_policy_watermarks(
room_id, thread_id, member_id, seen_through_seq
) VALUES (?, ?, ?, ?)
ON CONFLICT(room_id, thread_id, member_id) DO UPDATE SET
@@ -257,16 +246,14 @@ class HostedRoomPolicyCheckpoint:
def _apply_stop_requested(
self, conn: sqlite3.Connection, event: Mapping[str, Any], payload: Mapping[str, Any]) -> None:
- conn.execute(
- """UPDATE hosted_room_policy_cursors
+ conn.execute("""UPDATE hosted_room_policy_cursors
SET stopped_through_seq=MAX(stopped_through_seq, ?) WHERE room_id=?""",
(int(event["seq"]), str(event["room_id"])))
_APPLY_BY_KIND: dict[str, Callable[..., None]] = {
"message.user": _apply_user_message, "message.member": _apply_discussion_event,
**dict.fromkeys(_TERMINAL_KINDS, _apply_discussion_event), "room.activity": _apply_room_activity,
- "room.stop_requested": _apply_stop_requested,
- }
+ "room.stop_requested": _apply_stop_requested}
def _apply_event(self, conn: sqlite3.Connection, event: Mapping[str, Any]) -> None:
handler = self._APPLY_BY_KIND.get(str(event.get("kind") or ""))
@@ -278,8 +265,7 @@ class HostedRoomPolicyCheckpoint:
def _ensure_cursor_and_transcript(self, conn: sqlite3.Connection, room_id: str) -> int:
"""Create the room cursor if absent, backfill the transcript once, return through_seq."""
_require_room(conn, room_id)
- conn.execute(
- """INSERT OR IGNORE INTO hosted_room_policy_cursors(
+ conn.execute("""INSERT OR IGNORE INTO hosted_room_policy_cursors(
room_id, through_seq, stopped_through_seq, updated_at
) VALUES (?, 0, 0, 0)""", (room_id,))
row = conn.execute("SELECT through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,)).fetchone()
@@ -288,8 +274,7 @@ class HostedRoomPolicyCheckpoint:
"SELECT schema_version FROM hosted_room_policy_transcript_state WHERE room_id=?", (room_id,)).fetchone()
if transcript_state is None or int(transcript_state["schema_version"]) < _TRANSCRIPT_SCHEMA_VERSION:
self._backfill_transcript(conn, room_id=room_id, through_seq=cursor)
- conn.execute(
- """INSERT INTO hosted_room_policy_transcript_state(room_id, schema_version)
+ conn.execute("""INSERT INTO hosted_room_policy_transcript_state(room_id, schema_version)
VALUES (?, ?)
ON CONFLICT(room_id) DO UPDATE SET schema_version=excluded.schema_version""",
(room_id, _TRANSCRIPT_SCHEMA_VERSION))
@@ -330,21 +315,17 @@ class HostedRoomPolicyCheckpoint:
cursor = conn.execute(
"SELECT stopped_through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,)).fetchone()
stopped_through_seq = int(cursor["stopped_through_seq"])
- thread = conn.execute(
- """SELECT thread_id, discussion_event_id FROM hosted_room_policy_threads
+ thread = conn.execute("""SELECT thread_id, discussion_event_id FROM hosted_room_policy_threads
WHERE room_id=? AND completed=0 AND latest_user_seq>?
ORDER BY latest_user_seq, thread_id LIMIT 1""", (room_id, stopped_through_seq)).fetchone()
if thread is None:
return PolicySnapshot(
- through_seq=through_seq, stopped_through_seq=stopped_through_seq,
- events=(), watermarks={})
+ through_seq=through_seq, stopped_through_seq=stopped_through_seq, events=(), watermarks={})
thread_id = str(thread["thread_id"])
events = self._discussion_events(
- conn, room_id=room_id, thread_id=thread_id,
- discussion_event_id=str(thread["discussion_event_id"]),
+ conn, room_id=room_id, thread_id=thread_id, discussion_event_id=str(thread["discussion_event_id"]),
bound_error="active room policy projection exceeded its bound")
- watermark_rows = conn.execute(
- """SELECT member_id, seen_through_seq FROM hosted_room_policy_watermarks
+ watermark_rows = conn.execute("""SELECT member_id, seen_through_seq FROM hosted_room_policy_watermarks
WHERE room_id=? AND thread_id=?""", (room_id, thread_id)).fetchall()
return PolicySnapshot(
through_seq=through_seq, stopped_through_seq=stopped_through_seq, events=tuple(events),
@@ -380,8 +361,8 @@ class HostedRoomPolicyCheckpoint:
"""Drop any completed projections left by an interrupted sync."""
with self._connect() as conn:
completed = conn.execute(
- "SELECT discussion_event_id FROM hosted_room_policy_threads WHERE room_id=? AND completed=1",
- (room_id,)).fetchall()
+ "SELECT discussion_event_id FROM hosted_room_policy_threads WHERE room_id=? AND completed=1", (room_id,)
+ ).fetchall()
for row in completed:
conn.execute(_DELETE_ACTIVE_EVENTS_SQL, (room_id, str(row["discussion_event_id"])))
conn.execute("DELETE FROM hosted_room_policy_threads WHERE room_id=? AND completed=1", (room_id,))
diff --git a/gateway/hosted_room_replicas.py b/gateway/hosted_room_replicas.py
index 2ab23d22a8c..5b41ff23cc5 100644
--- a/gateway/hosted_room_replicas.py
+++ b/gateway/hosted_room_replicas.py
@@ -17,18 +17,8 @@ from pathlib import Path
from typing import Any, Iterator
from gateway.hosted_rooms import (
- MAX_ACTOR_ID_CHARS,
- HostedRoomError,
- RoomConflictError,
- _actor_json,
- _connect,
- _payload_json,
- _room_id,
- _transaction,
- _validate_identifier,
- _validate_members,
- _validate_room_name,
- local_authority_gateway_id)
+ MAX_ACTOR_ID_CHARS, HostedRoomError, RoomConflictError, _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 bounded_int, clock, utf8_len
MAX_REPLICA_ROOMS = 256
@@ -50,8 +40,7 @@ class ReplicaEpochRegressionError(ReplicaError): """A page or demotion carries a
def _initialize_replica_schema(conn: sqlite3.Connection) -> None:
- conn.execute(
- """CREATE TABLE IF NOT EXISTS hosted_room_replicas (
+ conn.execute("""CREATE TABLE IF NOT EXISTS hosted_room_replicas (
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 CHECK (authority_epoch >= 1),
@@ -60,8 +49,7 @@ def _initialize_replica_schema(conn: sqlite3.Connection) -> None:
created_at REAL NOT NULL, updated_at REAL NOT NULL
)"""
)
- conn.execute(
- """CREATE TABLE IF NOT EXISTS hosted_room_replica_events (
+ conn.execute("""CREATE TABLE IF NOT EXISTS hosted_room_replica_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,
payload_json TEXT NOT NULL, created_at REAL NOT NULL,
@@ -134,8 +122,7 @@ def _validate_page(page: Any) -> tuple[list[dict[str, Any]], dict[str, Any]]:
def _replica_row_state(conn: sqlite3.Connection, room_id: str) -> tuple[sqlite3.Row | None, int, int, int]:
"""Return (row, stored_epoch, last_seq, stored_bytes); a new room is admitted only under the room cap."""
- row = conn.execute(
- """SELECT authority_gateway_id, authority_epoch, last_seq, latest_seq, event_bytes
+ row = conn.execute("""SELECT authority_gateway_id, authority_epoch, last_seq, latest_seq, event_bytes
FROM hosted_room_replicas WHERE room_id=?""", (room_id,)).fetchone()
if row is None:
count = conn.execute("SELECT COUNT(*) FROM hosted_room_replicas").fetchone()[0]
@@ -151,14 +138,12 @@ def _store_replica(
"""INSERT the replica row for a new room, else UPDATE it (event_bytes accumulates)."""
values = (room_name, members_json, authority["gateway_id"], authority["epoch"], new_last, max(latest_seq, new_last))
if is_new:
- conn.execute(
- """INSERT INTO hosted_room_replicas (room_id, name, members_json,
+ conn.execute("""INSERT INTO hosted_room_replicas (room_id, name, members_json,
authority_gateway_id, authority_epoch, last_seq, latest_seq, event_bytes,
created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(room_id, *values, added_bytes, now, now))
else:
- conn.execute(
- """UPDATE hosted_room_replicas SET name=?, members_json=?, authority_gateway_id=?,
+ conn.execute("""UPDATE hosted_room_replicas SET name=?, members_json=?, authority_gateway_id=?,
authority_epoch=?, last_seq=?, latest_seq=?, event_bytes=event_bytes+?,
updated_at=? WHERE room_id=?""", (*values, added_bytes, now, room_id))
@@ -203,8 +188,7 @@ def ingest_page(
authority=authority, new_last=new_last, latest_seq=latest_seq, added_bytes=added_bytes, now=now)
return {
"room_id": room_id, "stored_seq": new_last, "ingested": len(new_events), "authority": authority,
- "caught_up": new_last >= max(latest_seq, new_last),
- }
+ "caught_up": new_last >= max(latest_seq, new_last)}
def replica_state(db_path: Path | str, *, room_id: Any) -> dict[str, Any]:
@@ -218,8 +202,7 @@ def replica_state(db_path: Path | str, *, room_id: Any) -> dict[str, Any]:
"room_id": row["room_id"], "name": row["name"], "members": json.loads(row["members_json"]),
"authority": {"gateway_id": row["authority_gateway_id"], "epoch": int(row["authority_epoch"])},
"last_seq": int(row["last_seq"]), "latest_seq": int(row["latest_seq"]), "event_bytes": int(row["event_bytes"]),
- "created_at": float(row["created_at"]), "updated_at": float(row["updated_at"]),
- }
+ "created_at": float(row["created_at"]), "updated_at": float(row["updated_at"])}
def promote_replica(
@@ -255,35 +238,31 @@ def promote_replica(
claim_event_id = f"system:authority-claimed:{target_epoch}"
claim_actor_json, claim_payload_json = _control_event_json({
"previous_gateway_id": previous_gateway, "authority_gateway_id": local_gateway,
- "authority_epoch": target_epoch, "promoted_from_replica": True, "reason": reason,
- })
+ "authority_epoch": target_epoch, "promoted_from_replica": True, "reason": reason})
claim_bytes = utf8_len(claim_event_id, "authority.claimed", claim_actor_json, claim_payload_json)
- conn.execute(
- """INSERT INTO hosted_rooms
+ 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, ?, ?, NULL)""",
(
- room_id, replica["name"], replica["members_json"], local_gateway, target_epoch,
- claim_seq + 1, int(replica["event_bytes"]) + claim_bytes, now, now))
+ room_id, replica["name"], replica["members_json"], local_gateway, target_epoch, claim_seq + 1,
+ int(replica["event_bytes"]) + claim_bytes, now, now))
conn.execute(
f"""INSERT INTO hosted_room_events {_EVENT_COLUMNS}
SELECT room_id, seq, event_id, kind, actor_json, authority_epoch, payload_json, created_at
- FROM hosted_room_replica_events WHERE room_id=?""",
- (room_id,))
+ FROM hosted_room_replica_events WHERE room_id=?""", (room_id,))
conn.execute(
_INSERT_ROOM_EVENT,
(
- room_id, claim_seq, claim_event_id, "authority.claimed",
- claim_actor_json, target_epoch, claim_payload_json, now))
+ room_id, claim_seq, claim_event_id, "authority.claimed", claim_actor_json, target_epoch,
+ claim_payload_json, now))
conn.execute("DELETE FROM hosted_room_replica_events WHERE room_id=?", (room_id,))
conn.execute("DELETE FROM hosted_room_replicas WHERE room_id=?", (room_id,))
return {
"room_id": room_id, "authority_gateway_id": local_gateway, "authority_epoch": target_epoch,
"previous_gateway_id": previous_gateway, "previous_epoch": previous_epoch, "claim_seq": claim_seq,
- "latest_seq": claim_seq,
- }
+ "latest_seq": claim_seq}
def demote_room(
@@ -303,8 +282,7 @@ def demote_room(
local_gateway = local_authority_gateway_id()
with _transaction(db_path, immediate=True) as conn:
- row = conn.execute(
- """SELECT authority_gateway_id, authority_epoch, next_seq
+ row = conn.execute("""SELECT authority_gateway_id, authority_epoch, next_seq
FROM hosted_rooms WHERE room_id=? AND disbanded_at IS NULL""", (room_id,)).fetchone()
if row is None:
raise ReplicaError("room not found in the local authoritative store")
@@ -313,27 +291,23 @@ def demote_room(
if current_gateway == observed_gateway_id and current_epoch == observed_epoch:
return {
"room_id": room_id, "authority_gateway_id": current_gateway, "authority_epoch": current_epoch,
- "idempotent": True,
- }
+ "idempotent": True}
if observed_epoch <= current_epoch:
raise ReplicaEpochRegressionError("observed epoch does not supersede the stored authority")
if current_gateway != local_gateway:
raise ReplicaError("room is not locally authoritative; nothing to demote")
lost_actor_json, lost_payload_json = _control_event_json({
- "previous_gateway_id": current_gateway,
- "authority_gateway_id": observed_gateway_id,
+ "previous_gateway_id": current_gateway, "authority_gateway_id": observed_gateway_id,
"authority_epoch": observed_epoch})
conn.execute(
_INSERT_ROOM_EVENT,
(
- room_id, int(row["next_seq"]), f"system:authority-lost:{observed_epoch}",
- "authority.lost", lost_actor_json, observed_epoch, lost_payload_json, now))
- conn.execute(
- """UPDATE hosted_rooms
+ room_id, int(row["next_seq"]), f"system:authority-lost:{observed_epoch}", "authority.lost",
+ lost_actor_json, observed_epoch, lost_payload_json, now))
+ conn.execute("""UPDATE hosted_rooms
SET authority_gateway_id=?, authority_epoch=?, next_seq=next_seq+1, revision=revision+1, updated_at=?
WHERE room_id=?""",
(observed_gateway_id, observed_epoch, now, room_id))
return {
"room_id": room_id, "authority_gateway_id": observed_gateway_id, "authority_epoch": observed_epoch,
- "idempotent": False,
- }
+ "idempotent": False}
diff --git a/gateway/hosted_rooms.py b/gateway/hosted_rooms.py
index 7ae15b9039c..a311a22af3e 100644
--- a/gateway/hosted_rooms.py
+++ b/gateway/hosted_rooms.py
@@ -17,8 +17,8 @@ from pathlib import Path
from typing import Any, Mapping, NoReturn
from gateway.hosted_rooms_common import (
- bounded_int, canonical_json, clock as _now, compact_json, connect, identifier, open_sqlite,
- 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
MAX_ROOM_ID_CHARS = 128
@@ -49,14 +49,13 @@ _JOURNAL_MODE_LOCK_RETRIES = 8
_EVENT_KIND_RE = re.compile(r"^[a-z][a-z0-9_.-]*$")
_CONTROL_EVENT_KINDS = frozenset({"authority.claimed", "authority.lost", "room.disbanded", "room.stop_requested"})
_EVENT_KINDS_BY_ACTOR = {
- "user": frozenset({"message.user"}),
- "member": frozenset({"message.member"}),
+ "user": frozenset({"message.user"}), "member": frozenset({"message.member"}),
"gateway": frozenset({
- "member.unavailable", "room.activity", "room.stop_requested", "turn.deferred",
- "turn.reassigned", "turn.cancelled", "turn.failed", "turn.settled", "turn.started"}),
+ "member.unavailable", "room.activity", "room.stop_requested", "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"})}
+ "authority.claimed", "authority.lost", "room.created", "room.disbanded", "room.members_changed", "room.renamed"
+ })}
_OPTIONAL_ACTOR_FIELDS = (
("display_name", MAX_ACTOR_LABEL_CHARS), ("profile", MAX_ACTOR_ID_CHARS), ("connection_id", MAX_ACTOR_ID_CHARS))
_ACTOR_FIELDS = frozenset({"kind", "id", *(field for field, _ in _OPTIONAL_ACTOR_FIELDS)})
@@ -64,8 +63,8 @@ _ACTOR_FIELDS = frozenset({"kind", "id", *(field for field, _ in _OPTIONAL_ACTOR
# --- schema -----------------------------------------------------------------
_REMOTE_RUN_IDENTITY_COLUMNS = (
- "room_id", "home_install_id", "authority_gateway_id", "authority_epoch", "member_id",
- "target_install_id", "target_profile", "task_id", "execution_generation")
+ "room_id", "home_install_id", "authority_gateway_id", "authority_epoch", "member_id", "target_install_id",
+ "target_profile", "task_id", "execution_generation")
_REMOTE_RUNS_BODY = """
room_id TEXT NOT NULL,
home_install_id TEXT NOT NULL,
@@ -131,8 +130,7 @@ _SCHEMA_DDL = (
status TEXT NOT NULL DEFAULT 'ready',
updated_at REAL NOT NULL,
PRIMARY KEY (room_id, member_id)
- )""",
- f"CREATE TABLE IF NOT EXISTS hosted_room_remote_runs ({_REMOTE_RUNS_BODY})",
+ )""", f"CREATE TABLE IF NOT EXISTS hosted_room_remote_runs ({_REMOTE_RUNS_BODY})",
"""CREATE TABLE IF NOT EXISTS hosted_room_revoked_grants (
scope_key TEXT PRIMARY KEY,
expires_at REAL NOT NULL,
@@ -149,8 +147,7 @@ _SCHEMA_DDL = (
created_at REAL NOT NULL,
updated_at REAL NOT NULL,
PRIMARY KEY (room_id, member_id, target_profile)
- )""",
-)
+ )""")
# (table, required columns) parsed from the DDL, in the order _schema_is_current probes them.
_REQUIRED_COLUMNS = tuple(
(
@@ -163,8 +160,7 @@ _REMOTE_RUN_SCHEMA_COLUMNS = _REQUIRED_COLUMNS[4][1]
_EVENT_COLUMNS = ("room_id, seq, event_id, kind, actor_json, authority_epoch, payload_json, created_at")
_SELECT_EVENT = f"SELECT {_EVENT_COLUMNS} FROM hosted_room_events WHERE room_id=? AND event_id=?"
-_INSERT_EVENT = (
- f"INSERT INTO hosted_room_events ({_EVENT_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
+_INSERT_EVENT = (f"INSERT INTO hosted_room_events ({_EVENT_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
_ROOM_COLUMNS = (
"room_id, name, members_json, authority_gateway_id, authority_epoch, next_seq, revision,"
" created_at, updated_at, disbanded_at")
@@ -179,13 +175,12 @@ _RETIRE_FROM_ROOMS = (
"INSERT OR IGNORE INTO hosted_room_retired_ids (room_id, retired_at)"
" SELECT room_id, disbanded_at FROM hosted_rooms WHERE {where}")
_LINK_COLUMNS = (
- "room_id", "member_id", "target_url", "target_profile", "grant", "catalog_json",
- "cancellation_scope_id", "trace_id", "transport_security", "status", "updated_at")
+ "room_id", "member_id", "target_url", "target_profile", "grant", "catalog_json", "cancellation_scope_id",
+ "trace_id", "transport_security", "status", "updated_at")
_REMOTE_RUN_WHERE = " AND ".join(f"{column}=?" for column in _REMOTE_RUN_IDENTITY_COLUMNS)
_SELECT_REMOTE_RUN = f"SELECT * FROM hosted_room_remote_runs WHERE {_REMOTE_RUN_WHERE}"
_LIVE_RESERVATION_WHERE = ("WHERE room_id=? AND target_profile=? AND expires_at>? AND revoked_at IS NULL")
-_SELECT_LIVE_RESERVATION = (
- f"SELECT 1 FROM hosted_room_peer_reservations {_LIVE_RESERVATION_WHERE} LIMIT 1")
+_SELECT_LIVE_RESERVATION = (f"SELECT 1 FROM hosted_room_peer_reservations {_LIVE_RESERVATION_WHERE} LIMIT 1")
class HostedRoomError(ValueError): """Base class for invalid or conflicting hosted-room operations."""
@@ -265,8 +260,7 @@ def user_event_id(client_event_id: Any) -> str:
_validate_room_name = partial(
- _validate_identifier, label="name", max_chars=MAX_ROOM_NAME_CHARS, pattern=None,
- invalid="invalid room name")
+ _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]:
@@ -401,8 +395,7 @@ def _migrate_legacy_columns(conn: sqlite3.Connection) -> None:
if column not in columns[table]:
conn.execute(ddl)
if "event_bytes" not in columns["hosted_rooms"]:
- conn.execute(
- """UPDATE hosted_rooms
+ conn.execute("""UPDATE hosted_rooms
SET event_bytes=COALESCE((
SELECT SUM(
length(CAST(event_id AS BLOB)) +
@@ -528,8 +521,7 @@ def _room_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str, A
"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,
- }
+ "updated_at": float(row["updated_at"]), "idempotent": idempotent}
# sqlite3.Row: ``x in row`` scans values, so ``.keys()`` is load-bearing.
if "disbanded_at" in row.keys() and row["disbanded_at"] is not None: # noqa: SIM118
room["disbanded_at"] = float(row["disbanded_at"])
@@ -543,8 +535,7 @@ def _event_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str,
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(epoch) if epoch is not None else None,
- "payload": json.loads(row["payload_json"]), "created_at": float(row["created_at"]), "idempotent": idempotent,
- }
+ "payload": json.loads(row["payload_json"]), "created_at": float(row["created_at"]), "idempotent": idempotent}
def _load_event(conn: sqlite3.Connection, room_id: str, event_id: str) -> sqlite3.Row | None:
@@ -561,8 +552,8 @@ def _gateway_event_bytes(conn: sqlite3.Connection) -> int:
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:
+ 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))
@@ -570,8 +561,8 @@ def _insert_event(
def _prepare_event(
- conn: sqlite3.Connection, room: sqlite3.Row, event_id: str, kind: str, actor_json: str,
- payload_json: str, *, allow_control: bool = False) -> int:
+ conn: sqlite3.Connection, room: sqlite3.Row, event_id: str, kind: str, actor_json: str, payload_json: str, *,
+ allow_control: bool = False) -> int:
"""Size one pending event and enforce per-room and gateway capacity; returns its bytes."""
additional_bytes = len((event_id + kind + actor_json + payload_json).encode("utf-8"))
count_reserve = CONTROL_EVENT_COUNT_RESERVE if allow_control else 0
@@ -597,8 +588,8 @@ def _prepare_event(
_DEPENDENT_TABLES = (
"hosted_room_policy_transcript_state", "hosted_room_policy_transcript", "hosted_room_policy_publications",
"hosted_room_policy_watermarks", "hosted_room_policy_events", "hosted_room_policy_threads",
- "hosted_room_policy_cursors", "hosted_room_driver_tasks", "hosted_room_driver_leases",
- "hosted_room_remote_runs", "hosted_room_links", "hosted_room_peer_reservations", "hosted_room_events")
+ "hosted_room_policy_cursors", "hosted_room_driver_tasks", "hosted_room_driver_leases", "hosted_room_remote_runs",
+ "hosted_room_links", "hosted_room_peer_reservations", "hosted_room_events")
def _room_ids(conn: sqlite3.Connection, sql: str, params: tuple[Any, ...]) -> list[str]:
@@ -620,8 +611,7 @@ def _prune_disbanded_rooms_locked(
if max_gateway_event_bytes is not None:
retained_bytes = _gateway_event_bytes(conn)
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
+ 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():
candidates.add(str(row["room_id"]))
@@ -632,10 +622,7 @@ def _prune_disbanded_rooms_locked(
return 0
placeholders = ",".join("?" for _ in candidates)
room_ids = tuple(sorted(candidates))
- conn.execute(
- _RETIRE_FROM_ROOMS.format(
- where=f"room_id IN ({placeholders}) AND disbanded_at IS NOT NULL"),
- room_ids)
+ conn.execute(_RETIRE_FROM_ROOMS.format(where=f"room_id IN ({placeholders}) AND disbanded_at IS NOT NULL"), room_ids)
for table in _DEPENDENT_TABLES:
if table_exists(conn, table):
conn.execute(f"DELETE FROM {table} WHERE room_id IN ({placeholders})", room_ids)
@@ -656,8 +643,7 @@ def prune_disbanded_rooms(db_path: Path | str, *, now: float | None = None) -> i
def list_room_link_records(db_path: Path | str) -> list[dict[str, Any]]:
"""Return private RoomLink records without logging or formatting grants."""
with _transaction(db_path) as conn:
- rows = conn.execute(
- """SELECT room_id, member_id, target_url, target_profile, grant,
+ rows = conn.execute("""SELECT room_id, member_id, target_url, target_profile, grant,
catalog_json, cancellation_scope_id, trace_id,
transport_security, status, updated_at
FROM hosted_room_links
@@ -670,14 +656,13 @@ def upsert_room_link_record(db_path: Path | str, *, record: Mapping[str, Any], m
"""Atomically insert or replace one private RoomLink record."""
with _transaction(db_path, immediate=True) as conn:
existing = conn.execute(
- "SELECT 1 FROM hosted_room_links WHERE room_id=? AND member_id=?",
- (record["room_id"], record["member_id"])).fetchone()
+ "SELECT 1 FROM hosted_room_links WHERE room_id=? AND member_id=?", (record["room_id"], record["member_id"])
+ ).fetchone()
if existing is None:
count = int(conn.execute("SELECT COUNT(*) FROM hosted_room_links").fetchone()[0])
if count >= max_links:
raise HostedRoomError("too many stored room links")
- conn.execute(
- """INSERT INTO hosted_room_links(
+ conn.execute("""INSERT INTO hosted_room_links(
room_id, member_id, target_url, target_profile, grant,
catalog_json, cancellation_scope_id, trace_id,
transport_security, status, updated_at
@@ -716,8 +701,8 @@ def _room_grant_scope_key(claims: Mapping[str, Any]) -> str:
fields = {
key: str(claims.get(key) or "")
for key in (
- "room_id", "home_install_id", "authority_gateway_id", "authority_epoch",
- "member_id", "target_install_id", "target_profile")}
+ "room_id", "home_install_id", "authority_gateway_id", "authority_epoch", "member_id", "target_install_id",
+ "target_profile")}
if not all(fields.values()):
raise HostedRoomError("room grant scope is incomplete")
return hashlib.sha256(compact_json(fields).encode("utf-8")).hexdigest()
@@ -733,8 +718,7 @@ def revoke_room_grant_scope(
return
with _transaction(db_path, immediate=True) as conn:
conn.execute("DELETE FROM hosted_room_revoked_grants WHERE expires_at<=?", (timestamp,))
- conn.execute(
- """INSERT INTO hosted_room_revoked_grants(
+ conn.execute("""INSERT INTO hosted_room_revoked_grants(
scope_key, expires_at, revoked_before
) VALUES (?, ?, ?)
ON CONFLICT(scope_key) DO UPDATE SET
@@ -742,15 +726,13 @@ def revoke_room_grant_scope(
excluded.expires_at),
revoked_before=MAX(hosted_room_revoked_grants.revoked_before,
excluded.revoked_before)""", (scope_key, expiry, timestamp))
- conn.execute(
- """UPDATE hosted_room_peer_reservations SET revoked_at=?, updated_at=? WHERE room_id=?
+ conn.execute("""UPDATE hosted_room_peer_reservations SET revoked_at=?, updated_at=? WHERE room_id=?
AND member_id=? AND target_profile=? AND authority_gateway_id=?
AND authority_epoch=?""",
(
timestamp, timestamp, str(claims.get("room_id") or ""), str(claims.get("member_id") or ""),
str(claims.get("target_profile") or ""), str(claims.get("authority_gateway_id") or ""),
- int(claims.get("authority_epoch") or 0),
- ))
+ int(claims.get("authority_epoch") or 0)))
def _reservation_claims(claims: Mapping[str, Any]) -> tuple[str, str, str, str, int]:
@@ -783,21 +765,18 @@ def reserve_peer_room(
conn.execute("DELETE FROM hosted_room_peer_reservations WHERE expires_at<=?", (timestamp,))
authority_rows = conn.execute(
f"""SELECT authority_gateway_id, authority_epoch
- FROM hosted_room_peer_reservations {_LIVE_RESERVATION_WHERE}""",
- (room_id, target_profile, timestamp)).fetchall()
+ FROM hosted_room_peer_reservations {_LIVE_RESERVATION_WHERE}""", (room_id, target_profile, timestamp)
+ ).fetchall()
if any(_reservation_superseded(row, gateway_id, epoch) for row in authority_rows):
raise AuthorityConflictError("peer room reservation authority changed")
- conn.execute(
- """UPDATE hosted_room_peer_reservations SET revoked_at=?, updated_at=? WHERE room_id=?
+ conn.execute("""UPDATE hosted_room_peer_reservations SET revoked_at=?, updated_at=? WHERE room_id=?
AND target_profile=? AND authority_epoch<? AND revoked_at IS NULL""",
(timestamp, timestamp, room_id, target_profile, epoch))
- existing = conn.execute(
- """SELECT authority_gateway_id, authority_epoch FROM hosted_room_peer_reservations
+ existing = conn.execute("""SELECT authority_gateway_id, authority_epoch FROM hosted_room_peer_reservations
WHERE room_id=? AND member_id=? AND target_profile=?""", values[:3]).fetchone()
if existing is not None and _reservation_superseded(existing, gateway_id, epoch):
raise AuthorityConflictError("peer room reservation authority changed")
- conn.execute(
- """INSERT INTO hosted_room_peer_reservations(
+ conn.execute("""INSERT INTO hosted_room_peer_reservations(
room_id, member_id, target_profile, authority_gateway_id,
authority_epoch, expires_at, revoked_at, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?)
@@ -861,11 +840,9 @@ def upsert_remote_run_receipt(db_path: Path | str, *, record: Mapping[str, Any],
if (*_remote_run_identity(existing), existing["run_id"], existing["session_id"]) != immutable:
raise HostedRoomError("remote run receipt conflicts with its logical task")
conn.execute(
- f"UPDATE hosted_room_remote_runs SET updated_at=? WHERE {_REMOTE_RUN_WHERE}",
- (timestamp, *identity))
+ f"UPDATE hosted_room_remote_runs SET updated_at=? WHERE {_REMOTE_RUN_WHERE}", (timestamp, *identity))
return
- conn.execute(
- """INSERT INTO hosted_room_remote_runs(
+ conn.execute("""INSERT INTO hosted_room_remote_runs(
room_id, home_install_id, authority_gateway_id,
authority_epoch, member_id, target_install_id,
target_profile, task_id, execution_generation, run_id,
@@ -874,19 +851,19 @@ def upsert_remote_run_receipt(db_path: Path | str, *, record: Mapping[str, Any],
def list_remote_run_receipts(
- db_path: Path | str, *, room_id: str | None = None, target_profile: str | None = None,
- session_id: str | None = None) -> list[dict[str, Any]]:
+ db_path: Path | str, *, room_id: str | None = None, target_profile: str | None = None, session_id: str | None = None
+) -> list[dict[str, Any]]:
"""Return remote run handles in durable task order."""
filters = [
(column, value)
- for column, value in (("room_id", room_id), ("target_profile", target_profile), ("session_id", session_id))
+ for column,
+ value in (("room_id", room_id), ("target_profile", target_profile), ("session_id", session_id))
if value is not None]
where = f" WHERE {' AND '.join(f'{column}=?' for column, _ in filters)}" if filters else ""
with _transaction(db_path) as conn:
rows = conn.execute(
"SELECT * FROM hosted_room_remote_runs" + where
- + " ORDER BY created_at, task_id, execution_generation",
- [value for _, value in filters]).fetchall()
+ + " ORDER BY created_at, task_id, execution_generation", [value for _, value in filters]).fetchall()
return [dict(row) for row in rows]
@@ -900,18 +877,17 @@ def remote_run_receipt(db_path: Path | str, *, record: Mapping[str, Any]) -> dic
def _adopt_legacy_room(
- conn: sqlite3.Connection, existing: sqlite3.Row, *, room_id: str, members_json: str,
- authority_gateway_id: str, now: float) -> dict[str, Any]:
+ conn: sqlite3.Connection, existing: sqlite3.Row, *, room_id: str, members_json: str, authority_gateway_id: str,
+ now: float) -> dict[str, Any]:
"""Claim a 'legacy'-authority room for a real gateway with a fenced claim event."""
target_epoch = int(existing["authority_epoch"]) + 1
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 = _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
+ 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
SET members_json=?, 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=?
@@ -925,15 +901,14 @@ def _adopt_legacy_room(
result = _room_from_row(existing, idempotent=True)
result["adopted"] = True
claim_event = _reload(
- conn, _SELECT_EVENT, (room_id, "system:authority-adopted"),
- "legacy adoption event could not be reloaded")
+ conn, _SELECT_EVENT, (room_id, "system:authority-adopted"), "legacy adoption event could not be reloaded")
result["claim_event"] = _event_from_row(claim_event)
return result
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]:
+ 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 = _room_id(room_id)
name = _validate_room_name(name)
@@ -980,7 +955,7 @@ def create_room(
def list_rooms(
- db_path: Path | str, *, include_disbanded: bool = False, limit: int = MAX_ROOM_LIST_LIMIT, offset: int = 0,
+ db_path: Path | str, *, include_disbanded: bool = False, limit: int = MAX_ROOM_LIST_LIMIT, offset: int = 0
) -> list[dict[str, Any]]:
"""Return one bounded read-only page ordered by most recent change."""
limit = _bounded_limit(limit, MAX_ROOM_LIST_LIMIT)
@@ -989,8 +964,8 @@ def list_rooms(
try:
rows = conn.execute(
f"""SELECT {_ROOM_COLUMNS} 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()
+ ORDER BY updated_at DESC, room_id ASC LIMIT ? OFFSET ?""", (int(include_disbanded), limit, offset)
+ ).fetchall()
finally:
conn.close()
return [_room_from_row(row) for row in rows]
@@ -1020,8 +995,7 @@ def rename_room(
epoch = int(room["authority_epoch"])
event_bytes = _prepare_event(conn, room, event_id, "room.renamed", actor_json, payload_json)
# Rename updates the room row before inserting its event (order is load-bearing).
- conn.execute(
- """UPDATE hosted_rooms
+ conn.execute("""UPDATE hosted_rooms
SET name=?, next_seq=?, event_bytes=event_bytes+?, revision=revision+1, updated_at=?
WHERE room_id=?""", (name, seq + 1, event_bytes, now, room_id))
conn.execute(_INSERT_EVENT, (room_id, seq, event_id, "room.renamed", actor_json, epoch, payload_json, now))
@@ -1068,15 +1042,12 @@ def append_event(
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)
- advanced = conn.execute(
- """UPDATE hosted_rooms SET next_seq=?, event_bytes=event_bytes+?, updated_at=?
+ 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 = _reload(
- conn,
- f"SELECT {_EVENT_COLUMNS} FROM hosted_room_events WHERE room_id=? AND seq=?",
- (room_id, seq),
+ conn, f"SELECT {_EVENT_COLUMNS} FROM hosted_room_events WHERE room_id=? AND seq=?", (room_id, seq),
"appended event could not be reloaded")
result = _event_from_row(row)
result["actor"] = normalized_actor
@@ -1107,8 +1078,7 @@ def probe_hosted_room(db_path: Path | str, *, room_id: Any) -> bool:
"""
checked_room_id = _room_id(room_id)
return _probe(
- Path(db_path), "hosted_rooms",
- "SELECT 1 FROM hosted_rooms WHERE room_id=? AND disbanded_at IS NULL LIMIT 1",
+ Path(db_path), "hosted_rooms", "SELECT 1 FROM hosted_rooms WHERE room_id=? AND disbanded_at IS NULL LIMIT 1",
(checked_room_id,), "hosted room ownership is temporarily unavailable")
@@ -1129,8 +1099,7 @@ def room_state(db_path: Path | str, *, room_id: Any, include_disbanded: bool = F
row = _room_row(
conn,
f"""SELECT {_ROOM_COLUMNS} FROM hosted_rooms WHERE room_id=? AND (disbanded_at IS NULL
- OR ?)""",
- (room_id, int(include_disbanded)), room_id)
+ OR ?)""", (room_id, int(include_disbanded)), room_id)
claim_row = conn.execute(
f"""SELECT {_EVENT_COLUMNS} FROM hosted_room_events WHERE room_id=?
AND kind='authority.claimed' AND authority_epoch=? ORDER BY seq DESC LIMIT 1""",
@@ -1142,7 +1111,7 @@ def room_state(db_path: Path | str, *, room_id: Any, include_disbanded: bool = F
def request_room_stop(
- db_path: Path | str, *, room_id: Any, cancel_id: Any, expected_gateway_id: Any, expected_epoch: Any,
+ db_path: Path | str, *, room_id: Any, cancel_id: Any, expected_gateway_id: Any, expected_epoch: Any
) -> dict[str, Any]:
"""Append an idempotent fence that supersedes earlier user turns."""
cancel_id = _validate_identifier(cancel_id, label="cancel_id", max_chars=MAX_EVENT_ID_CHARS)
@@ -1154,15 +1123,14 @@ def request_room_stop(
def _append_authority_claim(
- conn: sqlite3.Connection, row: sqlite3.Row, *, room_id: str, event_id: str,
- expected_gateway_id: str, expected_epoch: int, new_gateway_id: str, target_epoch: int,
- actor_json: str, payload_json: str, now: float) -> sqlite3.Row | None:
+ conn: sqlite3.Connection, row: sqlite3.Row, *, room_id: str, event_id: str, expected_gateway_id: str,
+ expected_epoch: int, new_gateway_id: str, target_epoch: int, 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."""
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=?,
+ 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=?,
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=?""",
@@ -1173,8 +1141,8 @@ def _append_authority_claim(
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]:
+ 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.
Does not decide *when* takeover is safe: a replicated driver calls it only after its
@@ -1230,8 +1198,8 @@ def _disband_replay(conn: sqlite3.Connection, room_id: str, room: sqlite3.Row |
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}
+ "room_id": room_id, "disbanded_at": float(retired["retired_at"]), "idempotent": True,
+ "history_expired": True}
if room["disbanded_at"] is None:
return None
conn.execute(_INSERT_RETIRED, (room_id, float(room["disbanded_at"])))
@@ -1243,8 +1211,8 @@ def _disband_replay(conn: sqlite3.Connection, room_id: str, room: sqlite3.Row |
def disband_room(
- db_path: Path | str, *, room_id: Any, expected_gateway_id: Any, expected_epoch: Any,
- now: float | None = None) -> dict[str, Any]:
+ 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 = _room_id(room_id)
expected_gateway_id = _actor_id(expected_gateway_id, "expected_gateway_id")
@@ -1252,8 +1220,7 @@ def disband_room(
now = _now(now)
with _transaction(db_path, immediate=True) as conn:
- room = conn.execute(
- """SELECT authority_gateway_id, authority_epoch, next_seq, event_bytes, disbanded_at
+ room = conn.execute("""SELECT authority_gateway_id, authority_epoch, next_seq, event_bytes, disbanded_at
FROM hosted_rooms WHERE room_id=?""", (room_id,)).fetchone()
replay = _disband_replay(conn, room_id, room)
if replay is not None:
@@ -1261,10 +1228,9 @@ def disband_room(
_require_authority(room, expected_gateway_id, expected_epoch, "stale hosted room authority")
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_rooms
+ _system_actor_json("room-control"), int(room["authority_epoch"]), _payload_json({"room_id": room_id}), now,
+ allow_control=True)
+ 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=?
@@ -1274,14 +1240,13 @@ def disband_room(
raise RoomConflictError("hosted room disband lost its fence")
conn.execute(_INSERT_RETIRED, (room_id, now))
event = _reload(
- conn, _SELECT_EVENT, (room_id, "system:room-disbanded"),
- "room disband event could not be reloaded")
+ conn, _SELECT_EVENT, (room_id, "system:room-disbanded"), "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,
+ 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 = _room_id(room_id)
@@ -1313,15 +1278,14 @@ def read_events(
SELECT {_EVENT_COLUMNS}
FROM candidates
WHERE cumulative_bytes<=?
- ORDER BY seq ASC""",
- (room_id, since_seq, limit, MAX_LOG_PAGE_BYTES)).fetchall()
+ 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, "authority": authority}
+ "events": page_events, "cursor": cursor, "latest_seq": latest_seq, "has_more": cursor < latest_seq,
+ "authority": authority}
def page_bytes(page: dict[str, Any]) -> int:
return len(json.dumps(page, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
diff --git a/gateway/hosted_rooms_common.py b/gateway/hosted_rooms_common.py
index 923d72d558d..496089de927 100644
--- a/gateway/hosted_rooms_common.py
+++ b/gateway/hosted_rooms_common.py
@@ -44,9 +44,8 @@ non_negative_int = partial(bounded_int, low=0)
def exact_fields(
- value: Any, *, label: str, required: frozenset[str] | set[str],
- optional: frozenset[str] | set[str] = frozenset(), error: type[Exception], not_object: str | None = None,
- missing_fmt: str = "{label} is missing fields: {fields}",
+ value: Any, *, label: str, required: frozenset[str] | set[str], optional: frozenset[str] | set[str] = frozenset(),
+ error: type[Exception], not_object: str | None = None, missing_fmt: str = "{label} is missing fields: {fields}",
unknown_fmt: str = "{label} has unknown fields: {fields}") -> Mapping[str, Any]:
"""Require exactly ``required`` (+ any ``optional``) keys; formats name the offenders sorted."""
if not isinstance(value, Mapping):