Skip to content

The agent that grows with you

fix(gateway): import pre-isolation hosted_room* rows into shared-state.db (#109775)

finn7635e9fe101614e
diff --git a/gateway/hosted_rooms.py b/gateway/hosted_rooms.py
index 7874243db29..9de2dd13068 100644
--- a/gateway/hosted_rooms.py
+++ b/gateway/hosted_rooms.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import hashlib
import json
+import logging
import re
import sqlite3
from contextlib import closing
@@ -45,6 +46,8 @@ CONTROL_EVENT_COUNT_RESERVE = 64
CONTROL_EVENT_BYTE_RESERVE = 1024 * 1024
_JOURNAL_MODE_LOCK_RETRIES = 8
+logger = logging.getLogger(__name__)
+
_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 = {
@@ -422,9 +425,112 @@ def local_authority_gateway_id() -> str:
return _actor_id(f"install:{install_id}", "authority_gateway_id")
-_connect = partial(
- connect, db_label="shared-state.db (hosted_rooms)", ready=_schema_is_current,
- initialize=lambda conn: _initialize_schema(conn), lock_retries=_JOURNAL_MODE_LOCK_RETRIES)
+# --- pre-isolation import -------------------------------------------------------
+# ``0e422e0ece`` repointed the room store from the root ``state.db`` to ``shared-state.db`` without
+# moving the rows it already held, so an install that had rooms started with an empty coordination
+# set and every pre-existing room resolved to "hosted room not found" (#109775). The first open
+# after the upgrade copies the rows across once; the marker row keeps that a one-shot step, because
+# a purge in THIS store must never be undone by re-importing rows the legacy store still holds.
+_LEGACY_SOURCE_NAME = "state.db"
+_LEGACY_MARKER_TABLE = "hosted_room_legacy_imports"
+# Liveness state, never copied: a lease is a ~15s heartbeat plus a process generation, so a copied
+# lease names a process that is gone. The driver claims a fresh one instead.
+_LEGACY_IMPORT_SKIP = frozenset({"hosted_room_driver_leases"})
+
+
+def _legacy_source_path(db_path: Path) -> Path | None:
+ """The pre-isolation store for ``db_path``, or ``None`` when this database has no predecessor.
+
+ Only the shared coordination database has one: callers that pass any other path (older
+ layouts, tests) own that file directly.
+ """
+ return db_path.with_name(_LEGACY_SOURCE_NAME) if db_path.name == "shared-state.db" else None
+
+
+def _legacy_import_settled(conn: sqlite3.Connection, db_path: Path) -> bool:
+ """True once the pre-isolation import for this database has been recorded (or never applies)."""
+ if _legacy_source_path(db_path) is None:
+ return True
+ return table_exists(conn, _LEGACY_MARKER_TABLE) and conn.execute(
+ f"SELECT 1 FROM {_LEGACY_MARKER_TABLE} WHERE source=?", (_LEGACY_SOURCE_NAME,)).fetchone() is not None
+
+
+def _copy_legacy_rows(target: sqlite3.Connection, source: Path) -> int:
+ """Copy the ``hosted_room*`` rows ``target`` is missing from ``source``; returns rooms copied.
+
+ ``INSERT OR IGNORE`` means rows this store already has always win. A table this store has not
+ created yet (the driver, policy and replica schemas are initialized by their own modules) is
+ created from the source's own DDL so its rows survive the upgrade too.
+ """
+ copied = 0
+ with closing(sqlite3.connect(f"file:{source}?mode=ro", uri=True, timeout=10)) as legacy:
+ names = [str(row[0]) for row in legacy.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name GLOB 'hosted_room*'")]
+ # Parents first: hosted_room_events carries a foreign key into hosted_rooms.
+ for name in sorted(names, key=lambda name: (name != "hosted_rooms", name)):
+ if name in _LEGACY_IMPORT_SKIP or name == _LEGACY_MARKER_TABLE or name.endswith(("_next", "_migrating")):
+ continue
+ if not table_exists(target, name):
+ target.execute(str(legacy.execute(
+ "SELECT sql FROM sqlite_master WHERE type='table' AND name=?", (name,)).fetchone()[0]))
+ target_columns = table_columns(target, name)
+ # Source PRAGMA order (a frozenset would not be deterministic); columns this store
+ # lacks are dropped, ones it added take their DDL default.
+ columns = [str(row[1]) for row in legacy.execute(f"PRAGMA table_info({name})")
+ if str(row[1]) in target_columns]
+ if not columns:
+ continue
+ cursor = target.executemany(
+ f"INSERT OR IGNORE INTO {name} ({', '.join(columns)}) VALUES ({', '.join('?' * len(columns))})",
+ legacy.execute(f"SELECT {', '.join(columns)} FROM {name}"))
+ if name == "hosted_rooms":
+ copied = max(0, cursor.rowcount)
+ return copied
+
+
+def _import_legacy_rooms(conn: sqlite3.Connection, db_path: Path) -> None:
+ """Copy the pre-isolation rows in once, then record the marker; never fails the open.
+
+ The copy runs inside the caller's schema transaction, so a crash leaves either both the
+ copied rows and the marker or neither.
+ """
+ if _legacy_import_settled(conn, db_path):
+ return
+ source = _legacy_source_path(db_path)
+ try:
+ copied = _copy_legacy_rows(conn, source) if source.is_file() else 0
+ except (OSError, sqlite3.Error) as exc:
+ # A locked or unreadable legacy store must not take hosted rooms down with it: skip this
+ # open, leave the marker unset, retry on the next one.
+ logger.warning("hosted rooms: could not import the pre-isolation %s (%s); will retry", source, exc)
+ return
+ conn.execute(
+ f"CREATE TABLE IF NOT EXISTS {_LEGACY_MARKER_TABLE} ("
+ "source TEXT PRIMARY KEY, imported_at REAL NOT NULL, rooms INTEGER NOT NULL)")
+ conn.execute(
+ f"INSERT OR IGNORE INTO {_LEGACY_MARKER_TABLE} (source, imported_at, rooms) VALUES (?, ?, ?)",
+ (_LEGACY_SOURCE_NAME, _now(None), copied))
+ if copied:
+ logger.info("hosted rooms: imported %d pre-isolation Group Chat(s) from %s", copied, source)
+
+
+def _store_ready(conn: sqlite3.Connection, db_path: Path) -> bool:
+ """The store can serve rooms once its schema is current and the pre-isolation import has run."""
+ return _schema_is_current(conn) and _legacy_import_settled(conn, db_path)
+
+
+def _initialize_store(conn: sqlite3.Connection, db_path: Path) -> None:
+ """Create or migrate the schema, then copy the pre-isolation rows in."""
+ _initialize_schema(conn)
+ _import_legacy_rooms(conn, db_path)
+
+
+def _connect(db_path: DbPath) -> sqlite3.Connection:
+ """Open the shared room store; ``initialize`` carries the path so the one-shot import can find it."""
+ path = Path(db_path)
+ return connect(
+ path, db_label="shared-state.db (hosted_rooms)", ready=partial(_store_ready, db_path=path),
+ initialize=partial(_initialize_store, db_path=path), lock_retries=_JOURNAL_MODE_LOCK_RETRIES)
def _read_connection(db_path: DbPath) -> sqlite3.Connection:
@@ -433,7 +539,7 @@ def _read_connection(db_path: DbPath) -> sqlite3.Connection:
if not path.is_file():
_connect(path).close()
conn = open_sqlite(path)
- if not _schema_is_current(conn):
+ if not _store_ready(conn, path):
conn.close()
_connect(path).close()
conn = open_sqlite(path)
diff --git a/tests/gateway/test_hosted_rooms.py b/tests/gateway/test_hosted_rooms.py
index 64a1cc57732..3946f8fc807 100644
--- a/tests/gateway/test_hosted_rooms.py
+++ b/tests/gateway/test_hosted_rooms.py
@@ -1362,3 +1362,76 @@ def test_default_db_path_never_names_the_master_session_store(tmp_path, monkeypa
assert from_profile == from_root, "one coordination file per install"
assert from_root.parent == root
assert from_root.name != "state.db"
+
+
+def test_upgrade_keeps_rooms_from_before_the_shared_state_db_split(tmp_path):
+ """Rooms an install already had stay reachable after the move to ``shared-state.db``.
+
+ ``0e422e0ece`` repointed the store at ``shared-state.db`` but left the hosted_room* rows in
+ the root ``state.db``, so every pre-existing room resolved to "hosted room not found" (#109775).
+ This is that upgrade: rooms and their events already in ``state.db``, nothing in the new file.
+ """
+ legacy = tmp_path / "state.db"
+ _create(legacy)
+ _append(
+ legacy,
+ room_id="room-1",
+ event_id="event-1",
+ kind="message.user",
+ actor=USER,
+ payload={"text": "before the upgrade"},
+ now=11,
+ )
+
+ store = tmp_path / "shared-state.db"
+
+ assert [room["room_id"] for room in rooms.list_rooms(store)] == ["room-1"]
+ assert rooms.room_state(store, room_id="room-1")["latest_seq"] == 1
+ assert [
+ event["event_id"] for event in rooms.read_events(store, room_id="room-1")["events"]
+ ] == ["event-1"]
+
+
+def test_legacy_import_is_a_one_shot_and_skips_driver_liveness_state(tmp_path):
+ """The copy runs once, never overwrites, and leaves the driver's lease behind (#109775)."""
+ legacy = tmp_path / "state.db"
+ _create(legacy)
+
+ def now() -> float:
+ return 100.0
+
+ driver.admit_task(
+ legacy,
+ driver.TaskIdentity(room_id="room-1", task_id="task-1", thread_id="thread-1", turn_id="turn-1"),
+ payload={"target_profile": "ops", "prompt": "ping", "source_event_seq": 1},
+ clock=now,
+ )
+ driver.acquire_lease(
+ legacy,
+ room_id="room-1",
+ gateway_id="gateway-a",
+ authority_epoch=1,
+ process_generation="process-a",
+ ttl_seconds=30,
+ clock=now,
+ )
+
+ store = tmp_path / "shared-state.db"
+ assert [room["room_id"] for room in rooms.list_rooms(store)] == ["room-1"]
+ with sqlite3.connect(store) as conn:
+ # Durable work follows the room across; the lease is liveness state and stays behind.
+ assert conn.execute("SELECT COUNT(*) FROM hosted_room_driver_tasks").fetchone()[0] == 1
+ assert conn.execute(
+ "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='hosted_room_driver_leases'"
+ ).fetchone()[0] == 0
+
+ # Forcing a second import (marker cleared) must not replace what this store already owns.
+ rooms.rename_room(store, room_id="room-1", event_id="rename-1", name="Renamed", now=12)
+ with sqlite3.connect(store) as conn:
+ conn.execute("DELETE FROM hosted_room_legacy_imports")
+ assert rooms.room_state(store, room_id="room-1")["name"] == "Renamed"
+
+ # And the record of the import is what keeps a purge from being undone by a later open.
+ with sqlite3.connect(store) as conn:
+ conn.execute("DELETE FROM hosted_rooms")
+ assert rooms.list_rooms(store) == []