The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): fenced_update in hosted_rooms_common shared by rooms/driver/checkpoint CAS sites; trim section-header blank runs
Teknium9eb77d3542c6
diff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.pyindex f92eb087a33..19e4f428abf 100644--- a/gateway/hosted_room_driver.py+++ b/gateway/hosted_room_driver.py@@ -19,7 +19,8 @@ from functools import partialfrom typing import Any, Callable, Literal, get_argsfrom gateway.hosted_rooms_common import (- DbPath, bounded_int, canonical_json, compact_json, connect, identifier, table_columns, text, transaction)+ DbPath, bounded_int, canonical_json, compact_json, connect, fenced_update, identifier, table_columns, text,+ transaction)Clock = Callable[[], float]TaskStatus = Literal["queued", "running", "settled", "failed", "cancelled", "indeterminate", "deferred", "stopping"]@@ -473,8 +474,7 @@ def _transition(_require_active_lease(conn, lease, now=now)if guard is not None:guard(row)- if conn.execute(sql, params).rowcount != 1:- raise StaleTaskError(stale)+ fenced_update(conn, sql, params, StaleTaskError(stale))return _task_from_row(_load_task(conn, identity))@@ -539,16 +539,15 @@ def acquire_lease(return _lease_from_row({**dict(row), "expires_at": renewed_expiry})if same_authority and live:raise LeaseHeldError("room driver lease is held by another generation")- updated = conn.execute("""UPDATE hosted_room_driver_leases+ fenced_update(conn, """UPDATE hosted_room_driver_leasesSET gateway_id=?, authority_epoch=?, process_generation=?, lease_generation=lease_generation + 1,expires_at=?, acquired_at=?, updated_at=?, released_at=NULLWHERE 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))- if updated.rowcount != 1:- raise LeaseHeldError("room driver lease changed during acquisition")+ int(row["lease_generation"]), gateway_id, authority_epoch, now),+ LeaseHeldError("room driver lease changed during acquisition"))return _lease_from_row(conn.execute(_SELECT_LEASE, (room_id,)).fetchone(), reclaimed=True)@@ -558,12 +557,11 @@ def renew_lease(db_path: DbPath, lease: DriverLease, *, ttl_seconds: Any, clock: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=?+ fenced_update(conn, """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, *_run_fence(lease), now))- if updated.rowcount != 1:- raise StaleLeaseError("driver lease changed during renewal")+ (expires_at, now, lease.room_id, *_run_fence(lease), now),+ StaleLeaseError("driver lease changed during renewal"))return dataclasses.replace(lease, expires_at=expires_at, reclaimed=False)@@ -640,15 +638,13 @@ 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+ fenced_update(conn, """UPDATE hosted_room_driver_tasksSET 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=?""",(execution_generation, *_run_fence(lease), now, now, identity.room_id, identity.task_id,- expected_cancel_generation))- if updated.rowcount != 1:- raise StaleTaskError("task changed during start")+ expected_cancel_generation), StaleTaskError("task changed during start"))return TaskAttempt(identity=identity, lease=lease, execution_generation=execution_generation,cancel_generation=expected_cancel_generation)diff --git a/gateway/hosted_room_policy_checkpoint.py b/gateway/hosted_room_policy_checkpoint.pyindex 1dedf6d45ab..3b6bfcff83c 100644--- a/gateway/hosted_room_policy_checkpoint.py+++ b/gateway/hosted_room_policy_checkpoint.py@@ -14,7 +14,7 @@ from pathlib import Pathfrom typing import Any, Callable, Mappingfrom gateway import hosted_rooms-from gateway.hosted_rooms_common import DbPath, compact_json+from gateway.hosted_rooms_common import DbPath, compact_json, fenced_updateMAX_ACTIVE_POLICY_EVENTS = 64@@ -292,11 +292,10 @@ class HostedRoomPolicyCheckpoint:_require_room(conn, room_id)for event in rows:self._apply_event(conn, event)- updated = conn.execute(- "UPDATE hosted_room_policy_cursors SET through_seq=?, updated_at=? WHERE room_id=?",- (next_cursor, float(rows[-1].get("created_at") or 0), room_id))- if updated.rowcount != 1:- raise RuntimeError("room policy cursor disappeared during replay")+ fenced_update(+ conn, "UPDATE hosted_room_policy_cursors SET through_seq=?, updated_at=? WHERE room_id=?",+ (next_cursor, float(rows[-1].get("created_at") or 0), room_id),+ RuntimeError("room policy cursor disappeared during replay"))cursor = next_cursorreturn cursordiff --git a/gateway/hosted_rooms.py b/gateway/hosted_rooms.pyindex cd368aeb89d..0d55fe118a5 100644--- a/gateway/hosted_rooms.py+++ b/gateway/hosted_rooms.py@@ -18,8 +18,8 @@ from pathlib import Pathfrom typing import Any, Mappingfrom gateway.hosted_rooms_common import (- DbPath, bounded_int, canonical_json, clock as _now, compact_json, connect, identifier, open_sqlite, table_columns,- table_exists, transaction, utf8_len)+ DbPath, bounded_int, canonical_json, clock as _now, compact_json, connect, fenced_update as _fenced_update,+ identifier, open_sqlite, table_columns, table_exists, transaction, utf8_len)PROTOCOL_VERSION = 2MAX_ROOM_ID_CHARS = 128@@ -62,7 +62,6 @@ _OPTIONAL_ACTOR_FIELDS = (_ACTOR_FIELDS = frozenset({"kind", "id", *(field for field, _ in _OPTIONAL_ACTOR_FIELDS)})# --- 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")@@ -156,7 +155,6 @@ _REQUIRED_COLUMNS = tuple(_REMOTE_RUN_SCHEMA_COLUMNS = _REQUIRED_COLUMNS[4][1]# --- SQL fragments (statement text must stay byte-stable after whitespace normalisation) ----_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 (?, ?, ?, ?, ?, ?, ?, ?)")@@ -206,7 +204,6 @@ class AuthoritySupersededError(AuthorityConflictError):# --- validation ----------------------------------------------------------------_canonical_json = partial(canonical_json, error=HostedRoomError, ensure_ascii=False)_validate_identifier = partial(identifier, error=HostedRoomError)_room_id = partial(_validate_identifier, label="room_id", max_chars=MAX_ROOM_ID_CHARS)@@ -462,12 +459,6 @@ def _require_authority(room: sqlite3.Row, gateway_id: str, epoch: int, message:raise AuthorityConflictError(message)-def _fenced_update(conn: sqlite3.Connection, sql: str, params: tuple, error: Exception) -> None:- """Run a compare-and-swap UPDATE; anything but exactly one row means the fence was lost."""- if conn.execute(sql, params).rowcount != 1:- raise error--def _reload(conn: sqlite3.Connection, sql: str, params: tuple, missing: str) -> sqlite3.Row:"""Re-read a row this transaction just wrote; a miss is an invariant violation."""row = conn.execute(sql, params).fetchone()@@ -540,7 +531,6 @@ def _prepare_event(# --- retention --------------------------------------------------------------------# Deleted in this order when a disbanded room's payload is purged._DEPENDENT_TABLES = ("hosted_room_policy_transcript_state", "hosted_room_policy_transcript", "hosted_room_policy_publications",diff --git a/gateway/hosted_rooms_common.py b/gateway/hosted_rooms_common.pyindex 259190b4854..dde9b828aa3 100644--- a/gateway/hosted_rooms_common.py+++ b/gateway/hosted_rooms_common.py@@ -139,6 +139,12 @@ def connect(return conn+def fenced_update(conn: sqlite3.Connection, sql: str, params: tuple, error: Exception) -> None:+ """Run a compare-and-swap UPDATE; anything but exactly one row means the fence was lost."""+ if conn.execute(sql, params).rowcount != 1:+ raise error++def table_exists(conn: sqlite3.Connection, table: str) -> bool:row = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)).fetchone()return row is not None