Skip to content

The agent that grows with you

feat: retain hosted room work evidence across authority changes

Teknium0af2c714542d
diff --git a/gateway/hosted_room_authority_history.py b/gateway/hosted_room_authority_history.py
new file mode 100644
index 00000000000..3f53d8f19ae
--- /dev/null
+++ b/gateway/hosted_room_authority_history.py
@@ -0,0 +1,114 @@
+"""Bounded replay context for committed authority changes, never election proof.
+
+Reused from the recovery prerequisite; lineage mechanics build on Teknium's
+#99047, authored commit 6af548a1f73f26bca54dd2e23f0d278c37f3ba6c.
+The passive wire contract applies stricter bounds in hosted_room_passive_lineage.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from typing import Any
+
+from gateway.hosted_rooms_common import identifier
+
+MAX_AUTHORITY_SPANS = 1024
+
+
+class AuthorityHistoryError(ValueError):
+ """The recorded authority sequence cannot explain the current room."""
+
+
+@dataclass(frozen=True)
+class AuthoritySpan:
+ gateway_id: str
+ epoch: int
+ from_seq: int
+
+ def as_mapping(self) -> dict[str, Any]:
+ return {"gateway_id": self.gateway_id, "epoch": self.epoch, "from_seq": self.from_seq}
+
+
+def _gateway(value: Any) -> str:
+ result = identifier(value, label="authority gateway", error=AuthorityHistoryError, max_chars=128)
+ if result != value:
+ raise AuthorityHistoryError("authority gateway must be canonical")
+ return result
+
+
+def validate_history(value: Any, *, gateway_id: str, epoch: int) -> tuple[AuthoritySpan, ...]:
+ """Validate contextual epochs; possession of this data grants no control rights."""
+ if value is None:
+ return (AuthoritySpan(gateway_id, epoch, 0),)
+ if not isinstance(value, list) or not 1 <= len(value) <= MAX_AUTHORITY_SPANS:
+ raise AuthorityHistoryError("authority history exceeds its bound or is absent")
+ spans = []
+ for item in value:
+ if not isinstance(item, dict) or set(item) != {"gateway_id", "epoch", "from_seq"}:
+ raise AuthorityHistoryError("authority history fields are invalid")
+ source = _gateway(item["gateway_id"])
+ generation, start = item["epoch"], item["from_seq"]
+ if type(generation) is not int or not 1 <= generation < 2**63 or type(start) is not int or not 0 <= start < 2**63:
+ raise AuthorityHistoryError("authority history coordinates are invalid")
+ if not spans:
+ if generation != 1 or start != 0:
+ raise AuthorityHistoryError("authority history has no verified starting point")
+ elif generation != spans[-1].epoch + 1 or start <= spans[-1].from_seq:
+ raise AuthorityHistoryError("authority history has a gap or unordered boundary")
+ spans.append(AuthoritySpan(source, generation, start))
+ if (spans[-1].gateway_id, spans[-1].epoch) != (gateway_id, epoch):
+ raise AuthorityHistoryError("authority history does not reach the current owner")
+ return tuple(spans)
+
+
+def at_sequence(history: tuple[AuthoritySpan, ...], seq: int) -> AuthoritySpan:
+ for span in reversed(history):
+ if seq >= span.from_seq:
+ return span
+ raise AuthorityHistoryError("event precedes the known authority history")
+
+
+def origin_gateway_id(room: dict[str, Any]) -> str:
+ """Keep the group/session namespace stable when its coordinator changes."""
+ history = validate_history(room.get("authority_history"), gateway_id=room["authority_gateway_id"],
+ epoch=room["authority_epoch"])
+ return history[0].gateway_id
+
+
+def read_history_locked(conn, room_id: str, *, gateway_id: str, epoch: int) -> list[dict[str, Any]] | None:
+ """Read committed claims within the caller's room-state transaction.
+
+ Legacy adoption is left on its existing path; it is not retroactively
+ certified as a history of physical-host transfers.
+ """
+ rows = conn.execute(
+ """SELECT seq,authority_epoch,actor_json,payload_json FROM hosted_room_events
+ WHERE room_id=? AND kind='authority.claimed' ORDER BY seq LIMIT ?""",
+ (room_id, MAX_AUTHORITY_SPANS),
+ ).fetchall()
+ if len(rows) >= MAX_AUTHORITY_SPANS:
+ raise AuthorityHistoryError("authority history exceeds its bound")
+ if not rows:
+ if epoch == 1:
+ return None
+ raise AuthorityHistoryError("current authority has no committed lineage")
+ first = json.loads(rows[0]["payload_json"])
+ if isinstance(first, dict) and first.get("previous_gateway_id") == "legacy":
+ return None
+ if not isinstance(first, dict) or "previous_gateway_id" not in first:
+ raise AuthorityHistoryError("authority history has no previous owner")
+ history = [AuthoritySpan(_gateway(first["previous_gateway_id"]), 1, 0)]
+ for row in rows:
+ actor, payload = json.loads(row["actor_json"]), json.loads(row["payload_json"])
+ if actor != {"kind": "system", "id": "authority-control"} or not isinstance(payload, dict):
+ raise AuthorityHistoryError("authority claim provenance is invalid")
+ expected = history[-1].epoch + 1
+ if (payload.get("previous_gateway_id") != history[-1].gateway_id
+ or type(payload.get("authority_epoch")) is not int or payload["authority_epoch"] != expected
+ or row["authority_epoch"] != expected):
+ raise AuthorityHistoryError("authority claim does not extend its predecessor")
+ history.append(AuthoritySpan(_gateway(payload.get("authority_gateway_id")), expected, int(row["seq"])))
+ result = [span.as_mapping() for span in history]
+ validate_history(result, gateway_id=gateway_id, epoch=epoch)
+ return result
diff --git a/gateway/hosted_room_work_lineage.py b/gateway/hosted_room_work_lineage.py
new file mode 100644
index 00000000000..02ff3678067
--- /dev/null
+++ b/gateway/hosted_room_work_lineage.py
@@ -0,0 +1,41 @@
+"""Validate passive evidence against committed authority spans, never elect an owner."""
+from gateway.hosted_room_authority_history import at_sequence, read_history_locked, validate_history
+
+
+def source_prefix_locked(conn, room_id, authority, seq):
+ from gateway.hosted_room_work_records import WorkRecordPrefixError, digest
+ history = read_history_locked(conn, room_id, gateway_id=authority["gateway_id"], epoch=authority["epoch"])
+ if history is None:
+ raise WorkRecordPrefixError("successor work evidence has no verified lineage")
+ spans = validate_history(history, gateway_id=authority["gateway_id"], epoch=authority["epoch"])
+ count = 0
+ import json
+ for event in conn.execute("SELECT seq,authority_epoch,actor_json,kind FROM hosted_room_events WHERE room_id=? AND seq<=? ORDER BY seq", (room_id, seq)):
+ count += 1
+ span = at_sequence(spans, count)
+ actor = json.loads(event["actor_json"])
+ boundary = span.epoch > 1 and count == span.from_seq
+ if (event["seq"] != count or event["authority_epoch"] != span.epoch
+ or (actor.get("kind") == "gateway" and actor.get("id") != span.gateway_id)
+ or (event["kind"] == "authority.claimed") != boundary):
+ raise WorkRecordPrefixError("work record history prefix is not verified")
+ if count != seq:
+ raise WorkRecordPrefixError("work record history prefix is unavailable")
+ return spans, digest(history)
+
+
+def validate_provenance(record, spans):
+ from gateway.hosted_room_work_records import WorkRecordError
+ # Execution generation remains an independent per-task counter.
+ for task in record["tasks"]:
+ at_sequence(spans, task["source_event_seq"])
+ for receipt in record["receipts"]:
+ if not any(s.gateway_id == receipt["home_install_id"] == receipt["authority_gateway_id"]
+ and s.epoch == receipt["authority_epoch"] for s in spans):
+ raise WorkRecordError("work record receipt has no original authority span")
+
+
+def task_origins(record, spans):
+ return {task["task_id"]: {"gateway_id": origin.gateway_id, "epoch": origin.epoch}
+ for task in record["tasks"] for origin in [at_sequence(spans, task["source_event_seq"])]}
+
diff --git a/gateway/hosted_room_work_records.py b/gateway/hosted_room_work_records.py
new file mode 100644
index 00000000000..a2f99ddc90e
--- /dev/null
+++ b/gateway/hosted_room_work_records.py
@@ -0,0 +1,374 @@
+"""Bounded room-scoped evidence, never executable driver state or authority."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+import sqlite3
+
+from gateway import hosted_rooms as rooms
+from gateway import hosted_room_work_storage as storage
+from gateway.hosted_rooms_common import identifier, table_exists
+
+VERSION = 1
+PERMISSION = "work_records"
+MAX_TASKS = 128
+MAX_RECEIPTS = 256
+MAX_BYTES = 128 * 1024
+MAX_STORE_BYTES = 4 * 1024 * 1024
+MAX_STORE_ROWS = 512
+SOURCE_TABLE = "hosted_room_work_records_source"
+TARGET_TABLE = "hosted_room_work_records_target"
+PENDING_TABLE = "hosted_room_work_records_pending"
+BLOCKED_DELIVERY_STATUSES = {"rejected", "needs_reauthorization", "invalid_ack", "unsupported_lineage", "invalid_work_evidence"}
+LIMITATIONS = ["process_local_approvals_not_captured", "field_journals_not_captured",
+ "external_effects_not_captured", "absent_record_is_not_non_admission", "not_execution_checkpoint"]
+_PHASES = {"queued", "running", "indeterminate", "stopping", "deferred", "settled", "failed", "cancelled"}
+_TASK_FIELDS = {
+ "task_id", "thread_id", "turn_id", "source_event_seq", "payload_sha256", "member_id", "profile",
+ "execution_generation", "cancel_generation", "phase", "settlement_id", "cancel_id"}
+_RECEIPT_FIELDS = {
+ "room_id", "home_install_id", "authority_gateway_id", "authority_epoch", "member_id", "target_install_id",
+ "target_profile", "task_id", "execution_generation", "run_id", "session_id"}
+_FIELDS = {"version", "room_id", "home_install_id", "authority", "roster_sha256", "history", "revision", "digest",
+ "availability", "reason", "tasks", "receipts", "stop", "limitations"}
+
+
+class WorkRecordError(ValueError):
+ """Controlled invalid or unavailable work evidence."""
+
+
+class InvalidStoredWorkRecord(WorkRecordError):
+ """Retained bytes cannot be reused; commit their invalid disposition."""
+
+
+class WorkRecordCapacityError(WorkRecordError):
+ """The bounded evidence store is full."""
+
+
+class WorkRecordPrefixError(WorkRecordError):
+ """The matching canonical history prefix is not retained."""
+
+
+def encode(value) -> str:
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
+
+
+def digest(value) -> str:
+ return hashlib.sha256(encode(value).encode("utf-8")).hexdigest()
+
+
+def _fields(value, fields):
+ if not isinstance(value, dict) or set(value) != fields:
+ raise WorkRecordError("work record fields are invalid")
+
+
+def _integer(value, *, minimum=0):
+ if type(value) is not int or not minimum <= value < 2**63:
+ raise WorkRecordError("work record integer is invalid")
+
+
+def _id(value):
+ if identifier(value, label="record identity", error=WorkRecordError, max_chars=256) != value:
+ raise WorkRecordError("work record identity is not canonical")
+
+
+def _sha(value):
+ if not isinstance(value, str) or re.fullmatch(r"[0-9a-f]{64}", value) is None:
+ raise WorkRecordError("work record digest is invalid")
+
+
+def validate(record: dict) -> dict:
+ v2 = isinstance(record, dict) and type(record.get("version")) is int and record["version"] == 2
+ _fields(record, _FIELDS | {"lineage_sha256", "incompleteness"} if v2 else _FIELDS)
+ if type(record["version"]) is not int or record["version"] not in {1, 2}:
+ raise WorkRecordError("work record version is unsupported")
+ _id(record["room_id"])
+ _id(record["home_install_id"])
+ _fields(record["authority"], {"gateway_id", "epoch"})
+ _integer(record["authority"]["epoch"], minimum=1)
+ if record["authority"]["gateway_id"] != record["home_install_id"] or (not v2 and record["authority"]["epoch"] != 1):
+ raise WorkRecordError("work record authority is unsupported")
+ if v2:
+ _sha(record["lineage_sha256"])
+ if record["incompleteness"] != ["prior_authority_work_unknown"]:
+ raise WorkRecordError("work record incompleteness is required")
+ _sha(record["roster_sha256"])
+ _integer(record["revision"], minimum=1)
+ _fields(record["history"], {"seq", "event_sha256"})
+ _integer(record["history"]["seq"])
+ _sha(record["history"]["event_sha256"])
+ if record["limitations"] != LIMITATIONS:
+ raise WorkRecordError("work record limitations are required")
+ if record["availability"] not in {"available", "unavailable"} or record["reason"] not in {
+ None, "task_store_missing", "unsupported_task", "bounds_exceeded"}:
+ raise WorkRecordError("work record availability is invalid")
+ if (record["availability"] == "available") != (record["reason"] is None):
+ raise WorkRecordError("work record availability conflicts")
+ tasks, receipts = record["tasks"], record["receipts"]
+ if not isinstance(tasks, list) or len(tasks) > MAX_TASKS or not isinstance(receipts, list) or len(receipts) > MAX_RECEIPTS:
+ raise WorkRecordError("work record list exceeds its bound")
+ if record["availability"] == "unavailable" and (tasks or receipts):
+ raise WorkRecordError("unavailable work record must not appear complete")
+ task_ids, receipt_ids = set(), set()
+ for task in tasks:
+ _fields(task, _TASK_FIELDS)
+ for name in ("task_id", "thread_id", "turn_id", "member_id", "profile"):
+ _id(task[name])
+ for name in ("settlement_id", "cancel_id"):
+ if task[name] is not None:
+ _id(task[name])
+ for name in ("execution_generation", "cancel_generation"):
+ _integer(task[name])
+ _integer(task["source_event_seq"], minimum=1)
+ _sha(task["payload_sha256"])
+ if task["source_event_seq"] > record["history"]["seq"] or task["phase"] not in _PHASES or task["task_id"] in task_ids:
+ raise WorkRecordError("work record task conflicts")
+ task_ids.add(task["task_id"])
+ for receipt in receipts:
+ _fields(receipt, _RECEIPT_FIELDS)
+ for name in _RECEIPT_FIELDS - {"authority_epoch", "execution_generation"}:
+ _id(receipt[name])
+ _integer(receipt["execution_generation"], minimum=1)
+ _integer(receipt["authority_epoch"], minimum=1)
+ if (receipt["room_id"] != record["room_id"]
+ or receipt["authority_gateway_id"] != receipt["home_install_id"]
+ or (not v2 and (receipt["home_install_id"] != record["home_install_id"] or receipt["authority_epoch"] != 1))):
+ raise WorkRecordError("work record receipt lineage conflicts")
+ key = tuple(receipt[k] for k in sorted(_RECEIPT_FIELDS - {"run_id", "session_id"}))
+ if key in receipt_ids:
+ raise WorkRecordError("work record receipt is duplicated")
+ receipt_ids.add(key)
+ _fields(record["stop"], {"closing", "revocation_complete", "seq", "cancel_id"})
+ for key in ("closing", "revocation_complete"):
+ if type(record["stop"][key]) is not bool:
+ raise WorkRecordError("work record closing fact is invalid")
+ _integer(record["stop"]["seq"])
+ if record["stop"]["seq"] > record["history"]["seq"]:
+ raise WorkRecordError("work record stop is beyond its prefix")
+ if record["stop"]["cancel_id"] is not None:
+ _id(record["stop"]["cancel_id"])
+ _sha(record["digest"])
+ if record["digest"] != digest({k: v for k, v in record.items() if k not in {"revision", "digest"}}):
+ raise WorkRecordError("work record content digest conflicts")
+ if len(encode(record).encode("utf-8")) > MAX_BYTES:
+ raise WorkRecordError("work record exceeds its byte bound")
+ return record
+
+
+def initialize(conn: sqlite3.Connection) -> None:
+ storage.initialize(conn)
+
+
+def _budget(conn, table, proposed):
+ total_sql, count_sql = storage.usage_sql((SOURCE_TABLE, PENDING_TABLE, storage.INVALID_TABLE))
+ total, count = conn.execute(f"SELECT {total_sql}, {count_sql}").fetchone()
+ keys = ["room_id", "producer_gateway_id", "producer_epoch"]
+ if table == PENDING_TABLE:
+ keys.append("target_install_id")
+ where = " AND ".join(f"{k}=?" for k in keys)
+ old = conn.execute(f"SELECT {storage.row_size_sql(table)} FROM {table} WHERE {where}",
+ [proposed[k] for k in keys]).fetchone()
+ size = conn.execute(f"SELECT {storage.row_size_sql(table)} FROM (SELECT "
+ + ",".join(f"? AS {k}" for k in proposed) + ")", tuple(proposed.values())).fetchone()[0]
+ if total - (old[0] if old else 0) + size > MAX_STORE_BYTES or count - bool(old) + 1 > MAX_STORE_ROWS:
+ raise WorkRecordCapacityError("work record storage is full")
+
+
+def history_anchor(conn, table: str, room_id: str, seq: int) -> str:
+ if seq == 0:
+ return digest([])
+ row = conn.execute(f"""SELECT seq,event_id,kind,actor_json,authority_epoch,payload_json,created_at
+ FROM {table} WHERE room_id=? AND seq=?""", (room_id, seq)).fetchone()
+ if row is None:
+ raise WorkRecordPrefixError("work record history prefix is unavailable")
+ return digest([row["seq"], row["event_id"], row["kind"], json.loads(row["actor_json"]),
+ row["authority_epoch"], json.loads(row["payload_json"]), float(row["created_at"])])
+
+
+def _capture_tasks(conn, room_id):
+ from gateway import hosted_room_driver as driver
+ if not table_exists(conn, "hosted_room_driver_tasks"):
+ return [], [], "task_store_missing"
+ # Published terminal records already travel in canonical history. Keep
+ # outstanding tasks and unacknowledged publications within this small slice.
+ published = ""
+ if table_exists(conn, "hosted_room_policy_publications"):
+ published = """NOT EXISTS (SELECT 1 FROM hosted_room_policy_publications AS p
+ WHERE p.room_id=t.room_id AND p.task_id=t.task_id AND p.kind IN ('turn.settled','turn.failed','turn.cancelled'))"""
+ task_filter = f" AND (status NOT IN ('settled','failed','cancelled') OR {published})" if published else ""
+ rows = conn.execute("""SELECT task_id,thread_id,turn_id,source_event_seq,payload_json,payload_digest,
+ status,execution_generation,cancel_generation,settlement_id,cancel_id
+ FROM hosted_room_driver_tasks AS t WHERE room_id=?""" + task_filter + " ORDER BY task_id LIMIT ?",
+ (room_id, MAX_TASKS + 1)).fetchall()
+ receipts = [dict(row) for row in conn.execute(
+ f"SELECT {','.join(sorted(_RECEIPT_FIELDS))} FROM hosted_room_remote_runs AS t WHERE room_id=?"
+ + (f" AND {published}" if published else "") + " ORDER BY task_id,execution_generation,member_id LIMIT ?",
+ (room_id, MAX_RECEIPTS + 1))]
+ if len(rows) > MAX_TASKS or len(receipts) > MAX_RECEIPTS:
+ return [], [], "bounds_exceeded"
+ tasks = []
+ for row in rows:
+ try:
+ payload, encoded, payload_digest = driver._task_payload(json.loads(row["payload_json"]))
+ except (ValueError, driver.DriverStateError):
+ return [], [], "unsupported_task"
+ if payload_digest != row["payload_digest"] or encoded != row["payload_json"] or payload["source_event_seq"] != row["source_event_seq"]:
+ return [], [], "unsupported_task"
+ tasks.append({**{key: row[key] for key in _TASK_FIELDS - {"payload_sha256", "phase", "member_id", "profile"}},
+ "payload_sha256": payload_digest, "phase": row["status"], "profile": payload["target_profile"],
+ "member_id": payload.get("target_member_id", payload["target_profile"])})
+ return tasks, receipts, None
+
+
+def capture(db_path, *, room_id: str, local_gateway_id: str, through_seq: int | None = None) -> dict:
+ """Commit a new revision only when one consistent source view changes."""
+ with rooms._transaction(db_path, immediate=True) as conn:
+ try:
+ return capture_locked(conn, room_id=room_id, local_gateway_id=local_gateway_id, through_seq=through_seq)
+ except InvalidStoredWorkRecord:
+ pass # Commit this capture's invalid disposition, not new evidence.
+ raise InvalidStoredWorkRecord("stored work evidence is invalid")
+
+
+def capture_locked(conn, *, room_id, local_gateway_id, through_seq=None):
+ initialize(conn)
+ room = conn.execute("SELECT * FROM hosted_rooms WHERE room_id=?", (room_id,)).fetchone()
+ if (room is None or room["authority_gateway_id"] != local_gateway_id or room["disbanded_at"] is not None):
+ raise WorkRecordError("work record source is unavailable")
+ seq = room["next_seq"] - 1
+ if through_seq is not None and seq > through_seq:
+ raise WorkRecordPrefixError("history delivery must precede work records")
+ tasks, receipts, reason = _capture_tasks(conn, room_id)
+ fence = None # This runtime has no durable peer revocation completion proof.
+ stop = conn.execute("""SELECT seq,payload_json FROM hosted_room_events
+ WHERE room_id=? AND kind='room.stop_requested' ORDER BY seq DESC LIMIT 1""", (room_id,)).fetchone()
+ content = {
+ "version": 1 if room["authority_epoch"] == 1 else 2, "room_id": room_id, "home_install_id": local_gateway_id,
+ "authority": {"gateway_id": local_gateway_id, "epoch": room["authority_epoch"]},
+ "roster_sha256": roster_digest(json.loads(room["members_json"])),
+ "history": {"seq": seq, "event_sha256": history_anchor(conn, "hosted_room_events", room_id, seq)},
+ "availability": "unavailable" if reason else "available", "reason": reason,
+ "tasks": tasks, "receipts": receipts, "limitations": LIMITATIONS,
+ "stop": {"closing": fence is not None, "revocation_complete": fence is not None and fence[0] is not None,
+ "seq": stop["seq"] if stop else 0, "cancel_id": json.loads(stop["payload_json"]).get("cancel_id") if stop else None},
+ }
+ spans = None
+ if content["version"] == 2:
+ from gateway import hosted_room_work_lineage as lineage
+ spans, content["lineage_sha256"] = lineage.source_prefix_locked(conn, room_id, content["authority"], seq)
+ content["incompleteness"] = ["prior_authority_work_unknown"]
+ previous = conn.execute(f"SELECT * FROM {SOURCE_TABLE} WHERE room_id=? AND producer_gateway_id=? AND producer_epoch=?",
+ storage.scope(content)).fetchone()
+ previous_record = storage.validate_stored_locked(conn, SOURCE_TABLE, previous) if previous is not None else None
+ revision = previous_record["revision"] + 1 if previous_record else 1
+ record = {**content, "revision": revision, "digest": digest(content)}
+ if len(encode(record).encode("utf-8")) > MAX_BYTES:
+ content.update(tasks=[], receipts=[], availability="unavailable", reason="bounds_exceeded")
+ record = {**content, "revision": revision, "digest": digest(content)}
+ try:
+ validate(record)
+ _validate_roster(record, json.loads(room["members_json"]))
+ if spans is not None:
+ lineage.validate_provenance(record, spans)
+ except WorkRecordError:
+ if reason is not None:
+ raise
+ content.update(tasks=[], receipts=[], availability="unavailable", reason="unsupported_task")
+ record = validate({**content, "revision": revision, "digest": digest(content)})
+ if previous_record is not None and previous_record["digest"] == record["digest"]:
+ return previous_record
+ storage.save_locked(conn, SOURCE_TABLE, record)
+ return record
+
+
+def _validate_roster(record, members):
+ if roster_digest(members) != record["roster_sha256"]:
+ raise WorkRecordError("work record roster conflicts")
+ roster = {m.get("member_id", m.get("profile")): m for m in members}
+ for task in record["tasks"]:
+ if roster.get(task["member_id"], {}).get("profile") != task["profile"]:
+ raise WorkRecordError("work record task target conflicts")
+ for receipt in record["receipts"]:
+ target = roster.get(receipt["member_id"], {}).get("target", {})
+ if (target.get("kind") != "peer" or target.get("installation_id") != receipt["target_install_id"]
+ or target.get("profile") != receipt["target_profile"]):
+ raise WorkRecordError("work record receipt target conflicts")
+
+
+def prepare_delivery_locked(conn, *, room_id, target_install_id, route_generation, local_gateway_id, through_seq):
+ """Freeze a source view now; expose it only after its history is acknowledged."""
+ initialize(conn)
+ current = conn.execute("SELECT authority_gateway_id,authority_epoch FROM hosted_rooms WHERE room_id=?", (room_id,)).fetchone()
+ if current is None or current["authority_gateway_id"] != local_gateway_id:
+ raise WorkRecordError("work record source is unavailable")
+ key = (room_id, current["authority_gateway_id"], current["authority_epoch"], target_install_id)
+ old = conn.execute(f"SELECT * FROM {PENDING_TABLE} WHERE room_id=? AND producer_gateway_id=? AND producer_epoch=? AND target_install_id=?", key).fetchone()
+ old_record = storage.validate_stored_locked(conn, PENDING_TABLE, old) if old is not None else None
+ if old is not None and old["disposition"] != "current":
+ raise WorkRecordError("pending work record is not current")
+ if old is not None and old["status"] != "acked":
+ if old["route_generation"] == route_generation and old["status"] in BLOCKED_DELIVERY_STATUSES:
+ return None
+ record = old_record
+ current = conn.execute("SELECT authority_gateway_id,authority_epoch,members_json FROM hosted_rooms WHERE room_id=?", (room_id,)).fetchone()
+ if (current is None or record["home_install_id"] != local_gateway_id
+ or record["authority"] != {"gateway_id": current["authority_gateway_id"], "epoch": current["authority_epoch"]}
+ or record["roster_sha256"] != roster_digest(json.loads(current["members_json"]))):
+ raise WorkRecordError("pending work record source changed")
+ else:
+ record = capture_locked(conn, room_id=room_id, local_gateway_id=local_gateway_id)
+ if old is not None and (old["revision"], old["digest"]) == (record["revision"], record["digest"]):
+ return None
+ if old is not None and old["status"] != "acked":
+ # A legitimate migrated JSON spelling is still immutable pending bytes.
+ conn.execute(f"""UPDATE {PENDING_TABLE} SET route_generation=?,status='pending'
+ WHERE room_id=? AND producer_gateway_id=? AND producer_epoch=? AND target_install_id=?
+ AND disposition='current'""", (route_generation, *key))
+ else:
+ storage.save_locked(conn, PENDING_TABLE, record, target_install_id=target_install_id, route_generation=route_generation)
+ # Persist the anchor even while history is behind. Recapturing the moving
+ # source tip on each attempt can otherwise starve a busy group indefinitely.
+ return record if record["history"]["seq"] <= through_seq else None
+
+
+def delivery_status_locked(conn, *, room_id, target_install_id, route_generation, record, status):
+ initialize(conn)
+ row = conn.execute(f"SELECT * FROM {PENDING_TABLE} WHERE room_id=? AND target_install_id=? "
+ "AND producer_gateway_id=? AND producer_epoch=? AND disposition='current'",
+ (room_id, target_install_id, record["authority"]["gateway_id"], record["authority"]["epoch"])).fetchone()
+ if row is None:
+ return False
+ try:
+ if storage.validate_stored_locked(conn, PENDING_TABLE, row) != record:
+ return False
+ except InvalidStoredWorkRecord:
+ return False
+ return conn.execute(f"""UPDATE {PENDING_TABLE} SET status=? WHERE room_id=? AND target_install_id=?
+ AND route_generation=? AND revision=? AND digest=? AND producer_gateway_id=? AND producer_epoch=?
+ AND disposition='current'""",
+ (status, room_id, target_install_id, route_generation, record["revision"], record["digest"],
+ record["authority"]["gateway_id"], record["authority"]["epoch"])).rowcount == 1
+
+
+
+def roster_digest(members):
+ _, encoded = rooms._validate_members(members)
+ return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
+
+
+def acknowledgement(record):
+ """Exact passive ACK shape; never an admission or execution receipt."""
+ ack = {"room_id": record["room_id"], "revision": record["revision"],
+ "digest": record["digest"], "passive": True}
+ if record["version"] == 2:
+ ack.update(version=2, authority=record["authority"], lineage_sha256=record["lineage_sha256"])
+ return ack
+
+
+def acknowledge_locked(conn, *, room_id, target_install_id, route_generation, record, ack):
+ if encode(ack) != encode(acknowledgement(record)):
+ return False
+ return delivery_status_locked(conn, room_id=room_id, target_install_id=target_install_id,
+ route_generation=route_generation, record=record, status="acked")
diff --git a/gateway/hosted_room_work_storage.py b/gateway/hosted_room_work_storage.py
new file mode 100644
index 00000000000..1aad0f906ee
--- /dev/null
+++ b/gateway/hosted_room_work_storage.py
@@ -0,0 +1,247 @@
+"""Producer-scoped passive evidence storage and durable older-writer guards."""
+
+import json
+
+from gateway.hosted_rooms_common import table_exists
+
+
+INVALID_TABLE = "hosted_room_work_records_invalid"
+
+
+def initialize(conn):
+ if not conn.in_transaction:
+ # Reserve the writer before schema reads. A deferred SAVEPOINT can lose
+ # its write upgrade to another publisher without honoring busy_timeout.
+ conn.execute("BEGIN IMMEDIATE")
+ with conn:
+ _initialize_locked(conn)
+ return
+ # Nested initialization must never commit or roll back caller-owned work.
+ conn.execute("SAVEPOINT work_record_initialize")
+ try:
+ _initialize_locked(conn)
+ except BaseException:
+ conn.execute("ROLLBACK TO work_record_initialize")
+ conn.execute("RELEASE work_record_initialize")
+ raise
+ conn.execute("RELEASE work_record_initialize")
+
+
+def _initialize_locked(conn):
+ from gateway import hosted_room_work_records as work
+ tables = (work.SOURCE_TABLE, work.PENDING_TABLE)
+ # Orphans are opaque evidence, not snapshots. No FK or producer can honestly
+ # be supplied for them. Preserve every original column and forbid mutation.
+ conn.execute(f"""CREATE TABLE IF NOT EXISTS {INVALID_TABLE} (
+ evidence_id INTEGER PRIMARY KEY, source_table TEXT NOT NULL,
+ room_id TEXT NOT NULL, revision INTEGER NOT NULL, digest TEXT NOT NULL, record_json TEXT NOT NULL,
+ target_install_id TEXT, route_generation TEXT, status TEXT,
+ disposition TEXT NOT NULL CHECK(disposition='invalid'))""")
+ for table in tables:
+ pending = table == work.PENDING_TABLE
+ parent = "hosted_room_replicas" if table == work.TARGET_TABLE else "hosted_rooms"
+ columns = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})")}
+ legacy = bool(columns) and "producer_gateway_id" not in columns
+ # Preserve surrounding cleanup triggers by recreating the same table name
+ # inside this transaction, rather than renaming its referents.
+ rows = conn.execute(f"SELECT * FROM {table}").fetchall() if legacy else []
+ triggers = conn.execute("SELECT sql FROM sqlite_master WHERE type='trigger' AND tbl_name=?", (table,)).fetchall() if legacy else []
+ if legacy:
+ conn.execute(f"DROP TABLE {table}")
+ extra = "target_install_id TEXT NOT NULL, route_generation TEXT NOT NULL, status TEXT NOT NULL," if pending else ""
+ key = ",target_install_id" if pending else ""
+ conn.execute(f"""CREATE TABLE IF NOT EXISTS {table} (
+ room_id TEXT NOT NULL, revision INTEGER NOT NULL, digest TEXT NOT NULL, record_json TEXT NOT NULL,
+ producer_gateway_id TEXT NOT NULL, producer_epoch INTEGER NOT NULL,
+ disposition TEXT NOT NULL CHECK(disposition IN ('current','superseded_authority','historical','invalid')),
+ {extra} PRIMARY KEY(room_id,producer_gateway_id,producer_epoch{key}),
+ FOREIGN KEY(room_id) REFERENCES {parent}(room_id) ON DELETE CASCADE)""")
+ for row in rows:
+ if not conn.execute(f"SELECT 1 FROM {parent} WHERE room_id=?", (row["room_id"],)).fetchone():
+ fields = ["source_table", "room_id", "revision", "digest", "record_json", "disposition"]
+ values = [table, row["room_id"], row["revision"], row["digest"], row["record_json"], "invalid"]
+ if pending:
+ fields += ["target_install_id", "route_generation", "status"]
+ values += [row[k] for k in fields[-3:]]
+ conn.execute(f"INSERT INTO {INVALID_TABLE} ({','.join(fields)}) VALUES ({','.join('?' for _ in fields)})", values)
+ continue
+ producer, epoch, disposition = "", 0, "invalid"
+ try:
+ record = work.validate(json.loads(row["record_json"]))
+ if (record["version"] != 1 or record["room_id"] != row["room_id"]
+ or record["revision"] != row["revision"] or record["digest"] != row["digest"]):
+ raise work.WorkRecordError("legacy work scope conflicts")
+ producer, epoch, disposition = record["home_install_id"], 1, "current"
+ except (ValueError, TypeError, KeyError):
+ pass # Explicitly invalid, with original bytes and no invented producer.
+ fields = ["room_id", "revision", "digest", "record_json", "producer_gateway_id", "producer_epoch", "disposition"]
+ values = [row[k] for k in fields[:4]] + [producer, epoch, disposition]
+ if pending:
+ fields += ["target_install_id", "route_generation", "status"]
+ values += [row[k] for k in fields[-3:]]
+ values[6] = scope_disposition(conn, table, dict(zip(fields, values)))
+ conn.execute(f"INSERT INTO {table} ({','.join(fields)}) VALUES ({','.join('?' for _ in fields)})", values)
+ for trigger in triggers:
+ conn.execute(trigger[0])
+ _guards(conn, work, tables)
+ _invalid_guards(conn)
+ # Ordinary initialization owns schema/guards only. Each consuming operation
+ # validates its own row; authority/enrollment triggers freeze exact-room old
+ # scopes. Legacy dispositions were resolved at insertion above.
+
+
+def scope_disposition(conn, table, row):
+ """Read-only authority projection, also used when inserting migrated rows."""
+ from gateway import hosted_room_work_records as work
+ if row["disposition"] != "current":
+ return row["disposition"]
+ current = None
+ current = conn.execute("SELECT authority_gateway_id,authority_epoch FROM hosted_rooms WHERE room_id=?",
+ (row["room_id"],)).fetchone()
+ if current is None or tuple(current) == (row["producer_gateway_id"], row["producer_epoch"]):
+ return "current"
+ return "superseded_authority" if table == work.PENDING_TABLE and row["status"] != "acked" else "historical"
+
+
+def _guards(conn, work, tables):
+ total, count = usage_sql((*tables, INVALID_TABLE))
+ for table in tables:
+ for operation in ("INSERT", "UPDATE"):
+ key = "room_id=NEW.room_id AND producer_gateway_id=NEW.producer_gateway_id AND producer_epoch=NEW.producer_epoch"
+ if table == work.PENDING_TABLE:
+ key += " AND target_install_id=NEW.target_install_id"
+ old_size = (f"COALESCE((SELECT {row_size_sql(table)} FROM {table} WHERE {key}),0)"
+ if operation == "INSERT" else row_size_sql(table, "OLD."))
+ new_size = row_size_sql(table, "NEW.")
+ old_count = f"(SELECT COUNT(*) FROM {table} WHERE {key})" if operation == "INSERT" else "1"
+ conn.execute(f"DROP TRIGGER IF EXISTS trg_{table}_budget_v2_{operation.lower()}")
+ conn.execute(f"DROP TRIGGER IF EXISTS trg_{table}_budget_v3_{operation.lower()}")
+ conn.execute(f"DROP TRIGGER IF EXISTS trg_{table}_budget_v4_{operation.lower()}")
+ conn.execute(f"""CREATE TRIGGER trg_{table}_budget_v4_{operation.lower()}
+ BEFORE {operation} ON {table} WHEN (
+ (({new_size})>({old_size}) AND ({total})-({old_size})+({new_size})>{work.MAX_STORE_BYTES})
+ OR ({old_count}=0 AND ({total}>{work.MAX_STORE_BYTES} OR {count}+1>{work.MAX_STORE_ROWS})))
+ BEGIN SELECT RAISE(ABORT, 'work record storage is full'); END""")
+ conn.execute(f"""CREATE TRIGGER IF NOT EXISTS trg_{table}_immutable_v2
+ BEFORE UPDATE ON {table} WHEN
+ NEW.room_id!=OLD.room_id OR NEW.producer_gateway_id!=OLD.producer_gateway_id
+ OR NEW.producer_epoch!=OLD.producer_epoch
+ OR (OLD.disposition!='current' AND (NEW.record_json!=OLD.record_json OR NEW.revision!=OLD.revision
+ OR NEW.digest!=OLD.digest OR NEW.disposition!=OLD.disposition))
+ BEGIN SELECT RAISE(ABORT, 'historical work record is immutable'); END""")
+ conn.execute(f"""CREATE TRIGGER IF NOT EXISTS trg_{table}_delete_v2 BEFORE DELETE ON {table}
+ WHEN OLD.disposition!='current' AND EXISTS (SELECT 1 FROM hosted_rooms
+ WHERE room_id=OLD.room_id AND disbanded_at IS NULL)
+ BEGIN SELECT RAISE(ABORT, 'historical work record is immutable'); END""")
+ # INSERT OR REPLACE performs a delete internally. Refuse it before the
+ # uniqueness conflict can remove an immutable snapshot.
+ extra = " AND p.target_install_id=NEW.target_install_id" if table == work.PENDING_TABLE else ""
+ conn.execute(f"""CREATE TRIGGER IF NOT EXISTS trg_{table}_replace_v2
+ BEFORE INSERT ON {table} WHEN EXISTS (SELECT 1 FROM {table} p WHERE p.room_id=NEW.room_id
+ AND p.producer_gateway_id=NEW.producer_gateway_id AND p.producer_epoch=NEW.producer_epoch
+ {extra} AND p.disposition!='current')
+ BEGIN SELECT RAISE(ABORT, 'historical work record is immutable'); END""")
+ conn.execute(f"""CREATE TRIGGER IF NOT EXISTS trg_work_pending_outcome_v2 BEFORE UPDATE ON {work.PENDING_TABLE}
+ WHEN OLD.disposition!='current' AND (NEW.status!=OLD.status OR NEW.route_generation!=OLD.route_generation
+ OR NEW.target_install_id!=OLD.target_install_id)
+ BEGIN SELECT RAISE(ABORT, 'historical delivery outcome is immutable'); END""")
+ # A raw authority update by an older owner must also freeze old evidence.
+ conn.execute(f"""CREATE TRIGGER IF NOT EXISTS trg_work_authority_transition_v2
+ AFTER UPDATE OF authority_gateway_id,authority_epoch ON hosted_rooms BEGIN
+ UPDATE {work.SOURCE_TABLE} SET disposition='historical' WHERE room_id=NEW.room_id AND disposition='current'
+ AND (producer_gateway_id!=NEW.authority_gateway_id OR producer_epoch!=NEW.authority_epoch);
+ UPDATE {work.PENDING_TABLE} SET disposition=CASE WHEN status='acked' THEN 'historical' ELSE 'superseded_authority' END
+ WHERE room_id=NEW.room_id AND disposition='current'
+ AND (producer_gateway_id!=NEW.authority_gateway_id OR producer_epoch!=NEW.authority_epoch);
+ END""")
+
+
+def retained_fields(table):
+ from gateway import hosted_room_work_records as work
+ fields = ["room_id", "revision", "digest", "record_json"]
+ fields += ["source_table"] if table == INVALID_TABLE else ["producer_gateway_id", "producer_epoch"]
+ if table in (work.PENDING_TABLE, INVALID_TABLE):
+ fields += ["target_install_id", "route_generation", "status"]
+ return fields
+
+
+def row_size_sql(table, prefix=""):
+ # Reserve the longest bounded disposition up front so freezing/cleanup can
+ # still run at capacity. Every original variable column is charged as bytes.
+ return "20+" + "+".join(f"COALESCE(length(CAST({prefix}{k} AS BLOB)),0)" for k in retained_fields(table))
+
+
+def usage_sql(tables):
+ return (" + ".join(f"(SELECT COALESCE(SUM({row_size_sql(t)}),0) FROM {t})" for t in tables),
+ " + ".join(f"(SELECT COUNT(*) FROM {t})" for t in tables))
+
+
+def validate_stored(row):
+ from gateway import hosted_room_work_records as work
+ try:
+ record = work.validate(json.loads(row["record_json"]))
+ if (row["disposition"] == "invalid"
+ or scope(record) != (row["room_id"], row["producer_gateway_id"], row["producer_epoch"])
+ or record["revision"] != row["revision"] or record["digest"] != row["digest"]):
+ raise work.WorkRecordError("stored work metadata conflicts with record scope")
+ except (ValueError, TypeError, KeyError, RecursionError) as exc:
+ raise work.InvalidStoredWorkRecord("stored work evidence is invalid") from exc
+ return record
+
+
+def validate_stored_locked(conn, table, row):
+ """Validate the consumed row; invalidate only its unchanged current version.
+
+ The savepoint owns a standalone classification or joins the caller's write
+ transaction. A caller catching InvalidStoredWorkRecord must commit that
+ transaction before reporting controlled failure. Historical rows are never
+ rewritten, and read-only projections use validate_stored instead.
+ """
+ from gateway import hosted_room_work_records as work
+ try:
+ return validate_stored(row)
+ except work.InvalidStoredWorkRecord:
+ if row["disposition"] == "current":
+ # Match all examined values, not merely a key that may since have
+ # been replaced. IS preserves NULL/BLOB distinctions in old stores.
+ fields = list(row.keys())
+ where = " AND ".join(f'"{k}" IS ?' for k in fields)
+ conn.execute("SAVEPOINT work_record_invalidate")
+ try:
+ conn.execute(f"UPDATE {table} SET disposition='invalid' WHERE {where}", [row[k] for k in fields])
+ except BaseException:
+ conn.execute("ROLLBACK TO work_record_invalidate")
+ conn.execute("RELEASE work_record_invalidate")
+ raise
+ conn.execute("RELEASE work_record_invalidate")
+ raise
+
+
+def scope(record):
+ return record["room_id"], record["authority"]["gateway_id"], record["authority"]["epoch"]
+
+
+def save_locked(conn, table, record, *, target_install_id=None, route_generation=None):
+ from gateway import hosted_room_work_records as work
+ data = work.encode(record)
+ fields = ["room_id", "producer_gateway_id", "producer_epoch", "revision", "digest", "record_json", "disposition"]
+ values = [*scope(record), record["revision"], record["digest"], data, "current"]
+ keys = fields[:3]
+ if target_install_id is not None:
+ fields += ["target_install_id", "route_generation", "status"]
+ values += [target_install_id, route_generation, "pending"]
+ keys += ["target_install_id"]
+ work._budget(conn, table, dict(zip(fields, values)))
+ updates = ','.join(f'{k}=excluded.{k}' for k in fields if k not in keys)
+ conn.execute(f"INSERT INTO {table} ({','.join(fields)}) VALUES ({','.join('?' for _ in fields)}) "
+ f"ON CONFLICT({','.join(keys)}) DO UPDATE SET {updates}", values)
+
+
+
+def _invalid_guards(conn):
+ # There is no reviewed retirement grant in this runtime. Opaque evidence
+ # cannot acquire a first-writer owner or be reclaimed by an ordinary writer.
+ for operation in ("INSERT", "UPDATE", "DELETE"):
+ conn.execute(f"""CREATE TRIGGER IF NOT EXISTS trg_work_invalid_{operation.lower()}
+ BEFORE {operation} ON {INVALID_TABLE}
+ BEGIN SELECT RAISE(ABORT, 'invalid work evidence is immutable'); END""")
diff --git a/tests/gateway/test_room_work_evidence.py b/tests/gateway/test_room_work_evidence.py
new file mode 100644
index 00000000000..38ef60f48d8
--- /dev/null
+++ b/tests/gateway/test_room_work_evidence.py
@@ -0,0 +1,119 @@
+"""Passive receipts survive owner changes without granting replay rights."""
+import copy
+import json
+import sqlite3
+from contextlib import closing
+
+import pytest
+
+from gateway import hosted_rooms as rooms
+
+
+def connect(path):
+ conn = sqlite3.connect(path)
+ conn.row_factory = sqlite3.Row
+ return conn
+
+
+def create(path, room="room"):
+ rooms.create_room(path, room_id=room, name="Evidence", members=[{"profile": "ops", "handle": "ops"}],
+ authority_gateway_id="owner-a", now=10)
+
+
+def test_pending_ack_survives_restart_and_fences_authority(tmp_path):
+ from gateway import hosted_room_work_records as work
+ path = tmp_path / "state.db"
+ create(path)
+ rooms.append_event(path, room_id="room", event_id="input", kind="message.user",
+ actor={"kind": "user", "id": "alice"}, payload={"text": "hello"},
+ authority_gateway_id="owner-a", authority_epoch=1)
+ from gateway import hosted_room_driver as driver
+ identity = driver.TaskIdentity("room", "task", "thread", "turn")
+ driver.admit_task(path, identity, payload={"target_profile": "ops", "prompt": "private prompt",
+ "source_event_seq": 1}, clock=lambda: 10)
+ first = work.capture(path, room_id="room", local_gateway_id="owner-a")
+ assert first["tasks"][0]["task_id"] == "task"
+ assert "private prompt" not in work.encode(first)
+ assert first["version"] == 1
+ with closing(connect(path)) as conn, conn:
+ pending = work.prepare_delivery_locked(conn, room_id="room", local_gateway_id="owner-a",
+ target_install_id="peer", route_generation="route-1", through_seq=100)
+ raw = conn.execute(f"SELECT record_json FROM {work.PENDING_TABLE}").fetchone()[0]
+ with closing(connect(path)) as conn, conn:
+ for key, value in (("revision", first["revision"] + 1), ("digest", "0" * 64),
+ ("authority", {"gateway_id": "owner-b", "epoch": 2})):
+ ack = work.acknowledgement(pending)
+ ack[key] = value
+ assert not work.acknowledge_locked(conn, room_id="room", target_install_id="peer",
+ route_generation="route-1", record=pending, ack=ack)
+ assert not work.acknowledge_locked(conn, room_id="room", target_install_id="peer",
+ route_generation="route-2", record=pending, ack=work.acknowledgement(pending))
+ conn.execute("UPDATE hosted_rooms SET authority_gateway_id='owner-b',authority_epoch=2 WHERE room_id='room'")
+ conn.execute("INSERT INTO hosted_room_events VALUES ('room',2,'claim','authority.claimed',?,2,?,11)",
+ (json.dumps({"kind": "system", "id": "authority-control"}), json.dumps({
+ "previous_gateway_id": "owner-a", "authority_gateway_id": "owner-b", "authority_epoch": 2})))
+ conn.execute("UPDATE hosted_rooms SET next_seq=3 WHERE room_id='room'")
+ successor = work.capture(path, room_id="room", local_gateway_id="owner-b")
+ assert successor["version"] == 2
+ assert successor["incompleteness"] == ["prior_authority_work_unknown"]
+ with closing(connect(path)) as conn, conn:
+ assert not work.acknowledge_locked(conn, room_id="room", target_install_id="peer",
+ route_generation="route-1", record=pending, ack=work.acknowledgement(pending))
+ old = conn.execute(f"SELECT * FROM {work.PENDING_TABLE}").fetchone()
+ assert old["record_json"] == raw and old["status"] == "pending"
+ assert old["disposition"] == "superseded_authority"
+ current = work.prepare_delivery_locked(conn, room_id="room", local_gateway_id="owner-b",
+ target_install_id="peer", route_generation="route-3", through_seq=100)
+ ack = work.acknowledgement(current)
+ wrong = copy.deepcopy(ack)
+ wrong["lineage_sha256"] = "0" * 64
+ assert not work.acknowledge_locked(conn, room_id="room", target_install_id="peer",
+ route_generation="route-3", record=current, ack=wrong)
+ assert work.acknowledge_locked(conn, room_id="room", target_install_id="peer",
+ route_generation="route-3", record=current, ack=ack)
+ with pytest.raises(sqlite3.IntegrityError):
+ conn.execute(f"UPDATE {work.PENDING_TABLE} SET room_id='other' WHERE producer_epoch=1")
+ with pytest.raises(work.WorkRecordError):
+ work.capture(path, room_id="room", local_gateway_id="owner-a")
+
+
+def test_migration_preserves_bytes_invalid_rows_and_caller_transaction(tmp_path, monkeypatch):
+ from gateway import hosted_room_work_records as work
+ from gateway import hosted_room_work_storage as storage
+ path = tmp_path / "state.db"
+ create(path)
+ create(path, "healthy")
+ record = work.capture(path, room_id="room", local_gateway_id="owner-a")
+ raw = json.dumps(record, indent=3)
+ with closing(connect(path)) as conn, conn:
+ conn.execute(f"DROP TABLE {work.SOURCE_TABLE}")
+ conn.execute("DROP TRIGGER IF EXISTS trg_work_invalid_insert")
+ conn.execute(f"CREATE TABLE {work.SOURCE_TABLE} (room_id TEXT PRIMARY KEY, revision INTEGER, digest TEXT, record_json TEXT)")
+ conn.execute(f"INSERT INTO {work.SOURCE_TABLE} VALUES (?,?,?,?)", ("room", record["revision"], record["digest"], raw))
+ conn.execute(f"INSERT INTO {work.SOURCE_TABLE} VALUES ('orphan',4,'broken','not-json')")
+ with closing(connect(path)) as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ work.initialize(conn)
+ assert conn.in_transaction
+ conn.rollback()
+ assert "producer_epoch" not in {r[1] for r in conn.execute(f"PRAGMA table_info({work.SOURCE_TABLE})")}
+ work.initialize(conn)
+ assert conn.execute(f"SELECT record_json FROM {work.SOURCE_TABLE} WHERE room_id='room'").fetchone()[0] == raw
+ assert conn.execute(f"SELECT record_json FROM {storage.INVALID_TABLE}").fetchone()[0] == "not-json"
+ conn.execute(f"UPDATE {work.SOURCE_TABLE} SET record_json='bad' WHERE room_id='room'")
+ conn.commit()
+ # Ordinary init/capture must never scan and mutate unrelated damaged evidence.
+ work.capture(path, room_id="healthy", local_gateway_id="owner-a")
+ with closing(connect(path)) as conn:
+ assert conn.execute(f"SELECT disposition FROM {work.SOURCE_TABLE} WHERE room_id='room'").fetchone()[0] == "current"
+ with pytest.raises(work.InvalidStoredWorkRecord):
+ work.capture(path, room_id="room", local_gateway_id="owner-a")
+ with closing(connect(path)) as conn:
+ assert conn.execute(f"SELECT disposition,record_json FROM {work.SOURCE_TABLE} WHERE room_id='room'").fetchone()[:] == ("invalid", "bad")
+ with pytest.raises(sqlite3.IntegrityError):
+ conn.execute(f"DELETE FROM {storage.INVALID_TABLE}")
+ monkeypatch.setattr(work, "MAX_STORE_BYTES", 1)
+ work.initialize(conn)
+ with pytest.raises(work.WorkRecordCapacityError):
+ work.prepare_delivery_locked(conn, room_id="healthy", local_gateway_id="owner-a",
+ target_install_id="peer", route_generation="route", through_seq=100)