hosted_room_authority_history.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. """Bounded replay context for committed authority changes, never election proof.
  2. Reused from the recovery prerequisite; lineage mechanics build on Teknium's
  3. #99047, authored commit 6af548a1f73f26bca54dd2e23f0d278c37f3ba6c.
  4. The passive wire contract applies stricter bounds in hosted_room_passive_lineage.
  5. """
  6. from __future__ import annotations
  7. import json
  8. from dataclasses import dataclass
  9. from typing import Any
  10. from gateway.hosted_rooms_common import identifier
  11. MAX_AUTHORITY_SPANS = 1024
  12. #: Committed authority transfers, each the first event of its span. ``authority.claimed`` is the new
  13. #: owner's record; ``authority.lost`` is the record the outgoing owner commits when it is fenced to
  14. #: a proven newer epoch (``hosted_room_replicas.demote_room``; the standalone -> gateway handoff in
  15. #: ``hosted_rooms_gateway_import``). Both carry the same previous/next/epoch payload and are
  16. #: checked alike, so a store whose log holds its own fence followed by a later claim (a handed-off
  17. #: room, a returning gateway that reclaims) reads as one unbroken chain.
  18. TRANSFER_KINDS = ("authority.claimed", "authority.lost")
  19. class AuthorityHistoryError(ValueError):
  20. """The recorded authority sequence cannot explain the current room."""
  21. @dataclass(frozen=True)
  22. class AuthoritySpan:
  23. gateway_id: str
  24. epoch: int
  25. from_seq: int
  26. def as_mapping(self) -> dict[str, Any]:
  27. return {"gateway_id": self.gateway_id, "epoch": self.epoch, "from_seq": self.from_seq}
  28. def _gateway(value: Any) -> str:
  29. result = identifier(value, label="authority gateway", error=AuthorityHistoryError, max_chars=128)
  30. if result != value:
  31. raise AuthorityHistoryError("authority gateway must be canonical")
  32. return result
  33. def validate_history(value: Any, *, gateway_id: str, epoch: int) -> tuple[AuthoritySpan, ...]:
  34. """Validate contextual epochs; possession of this data grants no control rights."""
  35. if value is None:
  36. return (AuthoritySpan(gateway_id, epoch, 0),)
  37. if not isinstance(value, list) or not 1 <= len(value) <= MAX_AUTHORITY_SPANS:
  38. raise AuthorityHistoryError("authority history exceeds its bound or is absent")
  39. spans = []
  40. for item in value:
  41. if not isinstance(item, dict) or set(item) != {"gateway_id", "epoch", "from_seq"}:
  42. raise AuthorityHistoryError("authority history fields are invalid")
  43. source = _gateway(item["gateway_id"])
  44. generation, start = item["epoch"], item["from_seq"]
  45. if type(generation) is not int or not 1 <= generation < 2**63 or type(start) is not int or not 0 <= start < 2**63:
  46. raise AuthorityHistoryError("authority history coordinates are invalid")
  47. if not spans:
  48. if generation != 1 or start != 0:
  49. raise AuthorityHistoryError("authority history has no verified starting point")
  50. elif generation != spans[-1].epoch + 1 or start <= spans[-1].from_seq:
  51. raise AuthorityHistoryError("authority history has a gap or unordered boundary")
  52. spans.append(AuthoritySpan(source, generation, start))
  53. if (spans[-1].gateway_id, spans[-1].epoch) != (gateway_id, epoch):
  54. raise AuthorityHistoryError("authority history does not reach the current owner")
  55. return tuple(spans)
  56. def at_sequence(history: tuple[AuthoritySpan, ...], seq: int) -> AuthoritySpan:
  57. for span in reversed(history):
  58. if seq >= span.from_seq:
  59. return span
  60. raise AuthorityHistoryError("event precedes the known authority history")
  61. def origin_gateway_id(room: dict[str, Any]) -> str:
  62. """Keep the group/session namespace stable when its coordinator changes."""
  63. history = validate_history(room.get("authority_history"), gateway_id=room["authority_gateway_id"],
  64. epoch=room["authority_epoch"])
  65. return history[0].gateway_id
  66. def read_history_locked(conn, room_id: str, *, gateway_id: str, epoch: int) -> list[dict[str, Any]] | None:
  67. """Read committed authority transfers within the caller's room-state transaction.
  68. Legacy adoption is left on its existing path; it is not retroactively
  69. certified as a history of physical-host transfers.
  70. """
  71. rows = conn.execute(
  72. f"""SELECT seq,authority_epoch,actor_json,payload_json FROM hosted_room_events
  73. WHERE room_id=? AND kind IN {TRANSFER_KINDS} ORDER BY seq LIMIT ?""",
  74. (room_id, MAX_AUTHORITY_SPANS),
  75. ).fetchall()
  76. if len(rows) >= MAX_AUTHORITY_SPANS:
  77. raise AuthorityHistoryError("authority history exceeds its bound")
  78. if not rows:
  79. if epoch == 1:
  80. return None
  81. raise AuthorityHistoryError("current authority has no committed lineage")
  82. first = json.loads(rows[0]["payload_json"])
  83. if isinstance(first, dict) and first.get("previous_gateway_id") == "legacy":
  84. return None
  85. if not isinstance(first, dict) or "previous_gateway_id" not in first:
  86. raise AuthorityHistoryError("authority history has no previous owner")
  87. history = [AuthoritySpan(_gateway(first["previous_gateway_id"]), 1, 0)]
  88. for row in rows:
  89. actor, payload = json.loads(row["actor_json"]), json.loads(row["payload_json"])
  90. if actor != {"kind": "system", "id": "authority-control"} or not isinstance(payload, dict):
  91. raise AuthorityHistoryError("authority claim provenance is invalid")
  92. expected = history[-1].epoch + 1
  93. if (payload.get("previous_gateway_id") != history[-1].gateway_id
  94. or type(payload.get("authority_epoch")) is not int or payload["authority_epoch"] != expected
  95. or row["authority_epoch"] != expected):
  96. raise AuthorityHistoryError("authority claim does not extend its predecessor")
  97. history.append(AuthoritySpan(_gateway(payload.get("authority_gateway_id")), expected, int(row["seq"])))
  98. result = [span.as_mapping() for span in history]
  99. validate_history(result, gateway_id=gateway_id, epoch=epoch)
  100. return result