Skip to content

The agent that grows with you

fix(groups): preserve frozen admissions across history cache rebuilds

Teknium4afe99baf206
diff --git a/gateway/hosted_room_discussion.py b/gateway/hosted_room_discussion.py
index 559583991e6..03c46780a20 100644
--- a/gateway/hosted_room_discussion.py
+++ b/gateway/hosted_room_discussion.py
@@ -18,6 +18,7 @@ from typing import Any, Literal
from gateway import hosted_room_driver as driver
from gateway import hosted_rooms
from gateway import hosted_rooms_common as common
+from gateway.hosted_room_task_input import validate_task_input
from gateway.hosted_rooms_common import compact_json
@@ -539,19 +540,23 @@ 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:
+ round_index: int, seen_through_seq: int, prompt: str,
+ input_context: Mapping[str, Any] | None = None) -> DiscussionTaskPlan:
turn_id = f"d{discussion_event.seq}.r{round_index}.p{member_index}.s{seen_through_seq}.m{_member_digest(member)}"
seed = compact_json({
"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"],
+ **({"input_context": input_context} if input_context is not None else {})})
identity = driver.TaskIdentity(
room_id=room.room_id, task_id=f"dtask:{hashlib.sha256(seed.encode('utf-8')).hexdigest()[:48]}",
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}
+ if input_context is not None:
+ payload["input_context"] = dict(input_context)
return DiscussionTaskPlan(
identity, payload, discussion_event.event_id, member, member_index, round_index, seen_through_seq)
@@ -604,7 +609,8 @@ def _effective_watermarks(
def plan_next_task(
room_value: Any, events: Sequence[Mapping[str, Any]], *, local_profiles: Iterable[str],
- initial_watermarks: Mapping[tuple[str, str], int] | None = None) -> DiscussionDecision:
+ initial_watermarks: Mapping[tuple[str, str], int] | None = None,
+ freeze_input_context: bool = False) -> DiscussionDecision:
"""Replay the complete room log and return at most one next member task."""
room = validate_room(room_value, local_profiles=local_profiles)
validated = _validated_events(events, room=room)
@@ -642,7 +648,10 @@ def plan_next_task(
seen_through_seq=seen_through_seq)
return decide("task", "member_turn", 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))
+ round_index=round_index, seen_through_seq=seen_through_seq, prompt=prompt,
+ input_context=(validate_task_input({"watermark": watermark, "event_seqs": [
+ event.seq for event in thread_messages if watermark < event.seq <= seen_through_seq]})
+ if freeze_input_context else None)))
if not any(int(event.payload["round_index"]) == round_index for event in member_messages):
return decide("settled", "silent_round")
if round_index == MAX_DISCUSSION_ROUNDS - 1:
@@ -683,9 +692,23 @@ def reconstruct_task_plan(
raise DiscussionReconstructionError("task prompt is missing")
if len(prompt.encode("utf-8")) > driver.MAX_PROMPT_BYTES:
raise DiscussionReconstructionError("task prompt exceeds the driver limit")
+ input_context = None
+ if "input_context" in payload:
+ try:
+ input_context = validate_task_input(payload["input_context"])
+ except ValueError as exc:
+ raise DiscussionReconstructionError(str(exc)) from exc
+ if input_context["event_seqs"][-1] != int(match.group("seen")):
+ raise DiscussionReconstructionError("task input does not match turn_id")
+ message_seqs = {event.seq for event in validated
+ if event.kind in {"message.user", "message.member"}
+ and event.payload.get("thread_id") == identity.thread_id}
+ if any(seq not in message_seqs for seq in input_context["event_seqs"]):
+ raise DiscussionReconstructionError("task input message is missing")
reconstructed = _make_task_plan(
room=room, discussion_event=discussion, member=member, member_index=int(match.group("position")),
- round_index=int(match.group("round")), seen_through_seq=int(match.group("seen")), prompt=prompt)
+ round_index=int(match.group("round")), seen_through_seq=int(match.group("seen")), prompt=prompt,
+ input_context=input_context)
if reconstructed.identity != identity or dict(reconstructed.payload) != dict(payload):
raise DiscussionReconstructionError("driver task failed deterministic reconstruction")
return reconstructed
diff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.py
index 7cf44a075bc..755d03e6a14 100644
--- a/gateway/hosted_room_driver.py
+++ b/gateway/hosted_room_driver.py
@@ -35,7 +35,7 @@ TASK_STATUSES = frozenset(get_args(TaskStatus))
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"})
+_TASK_PAYLOAD_OPTIONAL_FIELDS = frozenset({"target_member_id", "input_context"})
_LEASE_COLUMNS = frozenset({
"room_id", "gateway_id", "authority_epoch", "process_generation", "lease_generation", "expires_at", "acquired_at",
"updated_at", "released_at"})
@@ -156,6 +156,13 @@ def _task_payload(value: Any) -> tuple[dict[str, Any], str, str]:
source_event_seq = _bounded_int(
value["source_event_seq"], message="source_event_seq must be a positive integer", low=1)
normalized = {"target_profile": target_profile, "prompt": prompt, "source_event_seq": source_event_seq}
+ if "input_context" in value:
+ from gateway.hosted_room_task_input import validate_task_input
+
+ try:
+ normalized["input_context"] = validate_task_input(value["input_context"])
+ except ValueError as exc:
+ raise DriverValidationError(str(exc)) from exc
if "target_member_id" in value:
normalized["target_member_id"] = _identifier(value["target_member_id"], label="target_member_id")
encoded = compact_json(normalized)
@@ -859,6 +866,23 @@ def prune_published_terminal_tasks(
return max(0, int(deleted.rowcount))
+
+def get_task_for_turn(
+ db_path: DbPath,
+ identity: TaskIdentity,
+) -> dict[str, Any] | None:
+ """Read the immutable admission for a turn, including older payload versions."""
+ conn = _connect(db_path)
+ try:
+ row = conn.execute(
+ """SELECT * FROM hosted_room_driver_tasks
+ WHERE room_id=? AND thread_id=? AND turn_id=?""",
+ (identity.room_id, identity.thread_id, identity.turn_id),
+ ).fetchone()
+ return _task_from_row(row) if row is not None else None
+ finally:
+ conn.close()
+
# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
# Names external plugins imported from this module before the Sep 2026 decomposition.
# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
diff --git a/gateway/hosted_room_policy_checkpoint.py b/gateway/hosted_room_policy_checkpoint.py
index 2d79bc98aad..7931fefa3bb 100644
--- a/gateway/hosted_room_policy_checkpoint.py
+++ b/gateway/hosted_room_policy_checkpoint.py
@@ -14,12 +14,14 @@ from pathlib import Path
from typing import Any, Callable, Mapping
from gateway import hosted_rooms
+from gateway.hosted_room_task_input import validate_task_input
from gateway.hosted_rooms_common import DbPath, compact_json, fenced_update
MAX_ACTIVE_POLICY_EVENTS = 64
MAX_THREAD_TRANSCRIPT_EVENTS = 24
-_TRANSCRIPT_SCHEMA_VERSION = 1
+_TRANSCRIPT_SCHEMA_VERSION = 4
+MAX_TRANSCRIPT_POLICY_EVENTS = MAX_THREAD_TRANSCRIPT_EVENTS * (MAX_ACTIVE_POLICY_EVENTS + 2)
_TERMINAL_KINDS = frozenset({"turn.settled", "turn.failed", "turn.cancelled", "turn.deferred"})
_SCHEMA_DDL = (
@@ -51,6 +53,9 @@ _SCHEMA_DDL = (
kind TEXT NOT NULL, settled_seq INTEGER, PRIMARY KEY(room_id, thread_id, seq))""",
"""CREATE TABLE IF NOT EXISTS hosted_room_policy_transcript_state (
room_id TEXT PRIMARY KEY, schema_version INTEGER NOT NULL)""",
+ """CREATE INDEX IF NOT EXISTS idx_hosted_room_user_thread
+ ON hosted_room_events(room_id, json_extract(payload_json, '$.thread_id'), seq)
+ WHERE kind='message.user'""",
)
_ROOM_EVENT_COLUMNS = hosted_rooms._EVENT_COLUMNS
@@ -63,7 +68,7 @@ _TRANSCRIPT_EVENTS_SQL = f"""WITH transcript_events(seq) AS (
SELECT {", ".join("events." + column for column in _ROOM_EVENT_COLUMNS.split(", "))}
FROM transcript_events
JOIN hosted_room_events AS events ON events.room_id=? AND events.seq=transcript_events.seq
- ORDER BY events.seq"""
+ ORDER BY events.seq LIMIT ?"""
@dataclass(frozen=True)
@@ -144,28 +149,6 @@ class HostedRoomPolicyCheckpoint:
"DELETE FROM hosted_room_policy_transcript WHERE room_id=? AND thread_id=? AND seq<?",
(event["room_id"], thread_id, int(cutoff["seq"])))
- def _backfill_transcript(self, conn: sqlite3.Connection, *, room_id: str, through_seq: int) -> None:
- """Migrate bounded committed thread history from the durable room log."""
- if through_seq <= 0:
- return
- settled_seq_by_message = {
- message_event_id: int(row["seq"])
- 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))
- if (message_event_id := _text(json.loads(row["payload_json"]), "message_event_id"))}
- for row in 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)):
- if row["kind"] == "message.member" and row["event_id"] not in settled_seq_by_message:
- continue
- event = _event_from_room_row(row)
- thread_id = _text(event["payload"], "thread_id")
- 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"]))
- )
-
def _discussion_events(
self, conn: sqlite3.Connection, *, room_id: str, thread_id: str, discussion_event_id: str, bound_error: str
) -> list[dict[str, Any]]:
@@ -175,7 +158,10 @@ class HostedRoomPolicyCheckpoint:
(room_id, discussion_event_id, MAX_ACTIVE_POLICY_EVENTS + 1)).fetchall()
if len(active_rows) > MAX_ACTIVE_POLICY_EVENTS:
raise RuntimeError(bound_error)
- rows = conn.execute(_TRANSCRIPT_EVENTS_SQL, (room_id, thread_id, room_id, thread_id, room_id)).fetchall()
+ rows = conn.execute(_TRANSCRIPT_EVENTS_SQL,
+ (room_id, thread_id, room_id, thread_id, room_id, MAX_TRANSCRIPT_POLICY_EVENTS + 1)).fetchall()
+ if len(rows) > MAX_TRANSCRIPT_POLICY_EVENTS:
+ raise RuntimeError("thread policy transcript exceeded its bound")
events_by_seq = {
int(event["seq"]): event
for event in (*map(_event_from_room_row, rows), *(json.loads(row["event_json"]) for row in active_rows))}
@@ -226,6 +212,9 @@ class HostedRoomPolicyCheckpoint:
if committed is not None:
seen_through_seq = max(seen_through_seq, int(committed["seq"]))
self._store_transcript_event(conn, event=committed, thread_id=thread_id, settled_seq=seq)
+ else:
+ # Non-visible receipts still supply historical reconstruction watermarks.
+ self._store_transcript_event(conn, event=event, thread_id=thread_id)
if member_id and seen_through_seq > 0:
conn.execute("""INSERT INTO hosted_room_policy_watermarks(
room_id, thread_id, member_id, seen_through_seq
@@ -258,7 +247,7 @@ class HostedRoomPolicyCheckpoint:
handler(self, conn, event, payload if isinstance(payload, Mapping) else {})
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."""
+ """Create the cursor and migrate derived policy caches by bounded replay."""
_require_room(conn, room_id)
conn.execute("""INSERT OR IGNORE INTO hosted_room_policy_cursors(
room_id, through_seq, stopped_through_seq, updated_at
@@ -269,7 +258,13 @@ class HostedRoomPolicyCheckpoint:
transcript_state = conn.execute(
"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)
+ # Rebuild derived history without rewriting admissions or the room log.
+ for table in ("hosted_room_policy_events", "hosted_room_policy_threads",
+ "hosted_room_policy_watermarks", "hosted_room_policy_transcript"):
+ conn.execute(f"DELETE FROM {table} WHERE room_id=?", (room_id,))
+ conn.execute("UPDATE hosted_room_policy_cursors SET through_seq=0, stopped_through_seq=0 WHERE room_id=?",
+ (room_id,))
+ cursor = 0
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""",
@@ -282,7 +277,12 @@ class HostedRoomPolicyCheckpoint:
conn.execute("BEGIN IMMEDIATE")
cursor = self._ensure_cursor_and_transcript(conn, room_id)
if cursor > latest_seq:
- raise RuntimeError("room policy cursor is ahead of the durable log")
+ with self._connect() as conn:
+ room = conn.execute("SELECT next_seq FROM hosted_rooms WHERE room_id=?", (room_id,)).fetchone()
+ if room is None:
+ raise hosted_rooms.RoomNotFoundError("hosted room not found")
+ if cursor >= int(room["next_seq"]):
+ raise RuntimeError("room policy cursor is ahead of the durable log")
while cursor < latest_seq:
page = hosted_rooms.read_events(
self.db_path, room_id=room_id, since_seq=cursor, limit=hosted_rooms.MAX_LOG_LIMIT)
@@ -293,6 +293,14 @@ class HostedRoomPolicyCheckpoint:
with self._connect() as conn:
conn.execute("BEGIN IMMEDIATE")
_require_room(conn, room_id)
+ current = conn.execute("SELECT through_seq FROM hosted_room_policy_cursors WHERE room_id=?",
+ (room_id,)).fetchone()
+ if current is None:
+ raise RuntimeError("room policy cursor disappeared during replay")
+ if int(current["through_seq"]) != cursor:
+ # Another worker applied the page: reload before any projection effects.
+ cursor = int(current["through_seq"])
+ continue
for event in rows:
self._apply_event(conn, event)
fenced_update(
@@ -304,10 +312,14 @@ class HostedRoomPolicyCheckpoint:
def snapshot(self, *, room_id: str, latest_seq: int) -> PolicySnapshot:
"""Return only the oldest active discussion and its watermark set."""
- through_seq = self.sync(room_id=room_id, latest_seq=latest_seq)
+ self.sync(room_id=room_id, latest_seq=latest_seq)
with self._connect() as conn:
+ conn.execute("BEGIN")
cursor = conn.execute(
- "SELECT stopped_through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,)).fetchone()
+ "SELECT through_seq, stopped_through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,)).fetchone()
+ if cursor is None:
+ raise hosted_rooms.RoomNotFoundError("hosted room checkpoint not found")
+ through_seq = int(cursor["through_seq"])
stopped_through_seq = int(cursor["stopped_through_seq"])
thread = conn.execute("""SELECT thread_id, discussion_event_id FROM hosted_room_policy_threads
WHERE room_id=? AND completed=0 AND latest_user_seq>?
@@ -338,14 +350,40 @@ class HostedRoomPolicyCheckpoint:
with self._connect() as conn:
return conn.execute(sql, params).fetchone() is not None
- def events_for_task(self, *, room_id: str, source_event_seq: int) -> list[dict[str, Any]]:
+ def events_for_task(self, *, room_id: str, source_event_seq: int,
+ input_context: Mapping[str, Any] | None = None,
+ task_id: str | None = None) -> list[dict[str, Any]]:
"""Load one bounded discussion projection for terminal reconstruction."""
with self._connect() as conn:
+ conn.execute("BEGIN")
+ published = self._published_task_events(conn, room_id=room_id, task_id=task_id)
+ if input_context is not None:
+ context = validate_task_input(input_context)
+ seqs = sorted({source_event_seq, *context["event_seqs"]})
+ placeholders = ",".join("?" for _ in seqs)
+ rows = conn.execute(f"SELECT * FROM hosted_room_events WHERE room_id=? AND seq IN ({placeholders}) ORDER BY seq",
+ (room_id, *seqs)).fetchall()
+ if len(rows) != len(seqs):
+ raise RuntimeError("admitted task input event is missing")
+ events = {int(row["seq"]): _event_from_room_row(row) for row in rows}
+ source_event = events[source_event_seq]
+ thread_id = _text(source_event["payload"], "thread_id")
+ if source_event["kind"] != "message.user" or not thread_id:
+ raise RuntimeError("admitted task source is not a user discussion")
+ # Supersession remains authoritative after the display projection compacts.
+ latest = conn.execute("""SELECT * FROM hosted_room_events
+ WHERE room_id=? AND kind='message.user' AND json_extract(payload_json, '$.thread_id')=?
+ ORDER BY seq DESC LIMIT 1""", (room_id, thread_id)).fetchone()
+ if latest is not None:
+ events[int(latest["seq"])] = _event_from_room_row(latest)
+ for event in published:
+ events[int(event["seq"])] = event
+ return [events[seq] for seq in sorted(events)]
row = conn.execute(
f"SELECT {_ROOM_EVENT_COLUMNS} FROM hosted_room_events WHERE room_id=? AND seq=?",
(room_id, source_event_seq)).fetchone()
if row is None or row["kind"] != "message.user":
- return []
+ return published
source = _event_from_room_row(row)
events = self._discussion_events(
conn, room_id=room_id, thread_id=_text(source["payload"], "thread_id"),
@@ -353,7 +391,7 @@ class HostedRoomPolicyCheckpoint:
bound_error="task policy projection exceeded its bound")
# The source can age out of BOTH bounded projections while a
# deferred task remains retryable. Its frozen prompt lives in the task.
- by_seq = {event["seq"]: event for event in events}
+ by_seq = {event["seq"]: event for event in (*events, *published)}
by_seq[source_event_seq] = source
return [by_seq[seq] for seq in sorted(by_seq)]
@@ -365,3 +403,24 @@ class HostedRoomPolicyCheckpoint:
).fetchall():
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,))
+
+
+ def _published_task_events(
+ self,
+ conn: sqlite3.Connection,
+ *,
+ room_id: str,
+ task_id: str | None,
+ ) -> list[dict[str, Any]]:
+ if not task_id:
+ return []
+ digest = task_id.removeprefix("dtask:")
+ rows = conn.execute(
+ """SELECT * FROM hosted_room_events
+ WHERE room_id=? AND event_id IN (?, ?) ORDER BY seq""",
+ (room_id, f"dmessage:{digest}", f"dterminal:{digest}"),
+ ).fetchall()
+ events = [_event_from_room_row(row) for row in rows]
+ if any(event["payload"].get("task_id") != task_id for event in events):
+ raise RuntimeError("published task receipt identity changed")
+ return events
\ No newline at end of file
diff --git a/gateway/hosted_room_task_input.py b/gateway/hosted_room_task_input.py
new file mode 100644
index 00000000000..477df26d76a
--- /dev/null
+++ b/gateway/hosted_room_task_input.py
@@ -0,0 +1,25 @@
+"""Bounded immutable input references carried by compacting policy callers."""
+
+from typing import Any
+
+
+MAX_TASK_INPUT_EVENTS = 128
+
+
+def validate_task_input(value: Any) -> dict[str, Any]:
+ if not isinstance(value, dict) or set(value) != {"watermark", "event_seqs"}:
+ raise ValueError("invalid task input context")
+ watermark = value["watermark"]
+ seqs = value["event_seqs"]
+ if type(watermark) is not int or watermark < 0:
+ raise ValueError("invalid task input watermark")
+ if not isinstance(seqs, list) or not 1 <= len(seqs) <= MAX_TASK_INPUT_EVENTS:
+ raise ValueError("task input context exceeded its bound")
+ previous = watermark
+ for seq in seqs:
+ if type(seq) is not int or not previous < seq <= 2**63 - 1:
+ raise ValueError(
+ "task input sequences must be increasing after the watermark"
+ )
+ previous = seq
+ return {"watermark": watermark, "event_seqs": list(seqs)}
\ No newline at end of file
diff --git a/tests/tui_gateway/test_hosted_room_frozen_publication.py b/tests/tui_gateway/test_hosted_room_frozen_publication.py
new file mode 100644
index 00000000000..ff5b114a2aa
--- /dev/null
+++ b/tests/tui_gateway/test_hosted_room_frozen_publication.py
@@ -0,0 +1,70 @@
+"""Frozen admissions reconstruct from canonical storage, not display caches."""
+
+import sqlite3
+import threading
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import hosted_room_driver as driver
+from gateway import hosted_rooms as rooms
+from tui_gateway.hosted_room_service import HostedRoomService
+
+
+def service(db):
+ instance = HostedRoomService(SimpleNamespace(_methods={}, _sessions={},
+ _sessions_lock=threading.Lock()), db_path=db)
+ instance.local_profiles = lambda: ("writer", "reviewer")
+ return instance
+
+
[email protected]("partial", [False, True])
+def test_terminal_reopen_uses_frozen_input_after_cache_loss(tmp_path, monkeypatch, partial):
+ monkeypatch.setattr(rooms, "local_authority_gateway_id", lambda: "home")
+ db = tmp_path / "room.db"
+ current = service(db)
+ current.create_room(room_id="room", name="Room", members=[
+ {"member_id": name, "profile": name, "handle": name}
+ for name in ("writer", "reviewer")])
+ current.send(room_id="room", event_id="input", payload={"text": "@writer original", "thread_id": "t"})
+ task, = driver.list_tasks(db, room_id="room", status="queued")
+ lease = driver.acquire_lease(db, room_id="room", gateway_id="home", authority_epoch=1,
+ process_generation="test", ttl_seconds=300, clock=time.time)
+ attempt = driver.start_task(db, task["identity"], lease, expected_cancel_generation=0, clock=time.time)
+ settled = driver.settle_task(db, attempt, settlement_id="result", status="settled",
+ result={"text": "original reply"}, clock=time.time)
+ if partial:
+ append = rooms.append_event
+ def interrupted(*args, **kwargs):
+ if kwargs.get("kind") == "turn.settled":
+ raise OSError("lost terminal append")
+ return append(*args, **kwargs)
+ with monkeypatch.context() as crash:
+ crash.setattr(rooms, "append_event", interrupted)
+ with pytest.raises(OSError, match="lost terminal"):
+ current._publish_terminal_tasks(current._room("room"))
+ # Advance and evict the display projection without admitting any further work.
+ for index in range(30):
+ rooms.append_event(db, room_id="room", event_id=f"later-{index}", kind="message.user",
+ actor={"kind": "user", "id": "home"}, authority_gateway_id="home", authority_epoch=1,
+ payload={"text": "@reviewer later", "thread_id": "t" if partial else "other"})
+ current.policy_checkpoint.snapshot(room_id="room", latest_seq=current._room("room")["latest_seq"])
+ with sqlite3.connect(db) as conn:
+ conn.execute("DELETE FROM hosted_room_policy_events WHERE room_id='room' AND seq=1")
+ conn.execute("DELETE FROM hosted_room_policy_transcript WHERE room_id='room' AND seq=1")
+ cold = service(db)
+ monkeypatch.setattr(driver, "admit_task", lambda *a, **kw: pytest.fail("publication readmitted work"))
+ assert cold._publish_terminal_tasks(cold._room("room"))
+ cold.policy_checkpoint.sync(room_id="room", latest_seq=cold._room("room")["latest_seq"])
+ own = [e for e in cold._events("room") if e["payload"].get("task_id") == task["identity"].task_id]
+ assert [e["kind"] for e in own] == ["message.member", "turn.settled"]
+ assert own[0]["payload"]["text"] == "original reply"
+ assert driver.get_task(db, task["identity"]) == settled
+ assert not cold._publish_terminal_tasks(cold._room("room"))
+ with sqlite3.connect(db) as conn:
+ assert conn.execute("SELECT COUNT(*) FROM hosted_room_driver_tasks").fetchone()[0] == 1
+ conn.execute("DELETE FROM hosted_room_events WHERE room_id='room' AND seq=1")
+ with pytest.raises(RuntimeError, match="input event is missing"):
+ cold.policy_checkpoint.events_for_task(room_id="room", source_event_seq=1,
+ input_context=task["payload"]["input_context"], task_id=task["identity"].task_id)
diff --git a/tests/tui_gateway/test_hosted_room_policy_upgrade.py b/tests/tui_gateway/test_hosted_room_policy_upgrade.py
new file mode 100644
index 00000000000..8e89daf8745
--- /dev/null
+++ b/tests/tui_gateway/test_hosted_room_policy_upgrade.py
@@ -0,0 +1,111 @@
+"""Late-receipt indexing upgrades derived caches, never accepted inputs or history."""
+
+import sqlite3
+import time
+from types import SimpleNamespace
+import threading
+
+import pytest
+
+from gateway import hosted_room_discussion as discussion
+from gateway import hosted_room_driver as driver
+from gateway import hosted_rooms as rooms
+from gateway.hosted_room_policy_checkpoint import HostedRoomPolicyCheckpoint
+from tui_gateway.hosted_room_service import HostedRoomService
+
+PROFILES = ("writer", "reviewer")
+
+
+def log(db):
+ return rooms.read_events(db, room_id="upgrade-room")["events"]
+
+
+def append(db, event_id, kind, payload, actor_kind="user"):
+ return rooms.append_event(db, room_id="upgrade-room", event_id=event_id, kind=kind,
+ actor={"kind": actor_kind, "id": "home"}, authority_gateway_id="home", authority_epoch=1, payload=payload)
+
+
+def legacy_cache(db, cache_version):
+ room = rooms.create_room(db, room_id="upgrade-room", name="Upgrade", authority_gateway_id="home",
+ members=[{"member_id": profile, "profile": profile, "handle": profile} for profile in PROFILES])
+ append(db, "source", "message.user", {"text": "@writer Prepare the plan.", "thread_id": "thread"})
+ original = discussion.plan_next_task(room, log(db), local_profiles=PROFILES, freeze_input_context=True).task
+ deferred = discussion.plan_publication(room, log(db), original, status="deferred", execution_generation=1,
+ result={"reason": "member_unavailable"}, local_profiles=PROFILES)
+ for event in deferred.events:
+ rooms.append_event(db, **event.append_kwargs("upgrade-room"))
+ append(db, "silent", "room.activity", {"status": "settled", "reason_code": "silent_round",
+ "thread_id": "thread", "discussion_event_id": "source"}, "gateway")
+ completed = discussion.plan_publication(room, log(db), original, status="settled",
+ result={"text": "The committed plan is ready."}, local_profiles=PROFILES)
+ rooms.append_event(db, **completed.events[0].append_kwargs("upgrade-room"))
+ append(db, "newer", "message.user", {"text": "@reviewer Use the earlier plan.", "thread_id": "thread"})
+ checkpoint = HostedRoomPolicyCheckpoint(db)
+ before = checkpoint.snapshot(room_id="upgrade-room", latest_seq=log(db)[-1]["seq"])
+ late = rooms.append_event(db, **completed.events[-1].append_kwargs("upgrade-room"))
+ # Versions 2/3 consumed a late receipt without indexing it once newer
+ # input prevented reopening the old discussion. Reproduce its persisted state.
+ with sqlite3.connect(db) as conn:
+ conn.execute("UPDATE hosted_room_policy_cursors SET through_seq=? WHERE room_id='upgrade-room'", (late["seq"],))
+ conn.execute("UPDATE hosted_room_policy_transcript_state SET schema_version=? WHERE room_id='upgrade-room'",
+ (cache_version,))
+ assert not checkpoint.publication_exists(room_id="upgrade-room", task_id=original.identity.task_id,
+ status="settled", execution_generation=2)
+ planned = discussion.plan_next_task(room, before.events, local_profiles=PROFILES,
+ initial_watermarks=before.watermarks, freeze_input_context=True).task
+ assert "The committed plan is ready." not in planned.payload["prompt"]
+ return room, original, planned
+
+
[email protected]("cache_version", [2, 3])
+def test_old_cache_rebuilds_late_receipts_and_context_without_changing_history(tmp_path, cache_version):
+ db = tmp_path / "state.db"
+ room, original, old_plan = legacy_cache(db, cache_version)
+ history = log(db)
+ checkpoint = HostedRoomPolicyCheckpoint(db)
+ updated = checkpoint.snapshot(room_id="upgrade-room", latest_seq=history[-1]["seq"])
+ assert checkpoint.publication_exists(room_id="upgrade-room", task_id=original.identity.task_id,
+ status="settled", execution_generation=2)
+ planned = discussion.plan_next_task(room, updated.events, local_profiles=PROFILES,
+ initial_watermarks=updated.watermarks, freeze_input_context=True).task
+ assert "The committed plan is ready." in planned.payload["prompt"]
+ assert planned.identity.task_id != old_plan.identity.task_id
+ assert log(db) == history
+ assert HostedRoomPolicyCheckpoint(db).snapshot(room_id="upgrade-room", latest_seq=history[-1]["seq"]) == updated
+
+
[email protected]("status", ["queued", "running", "indeterminate"])
[email protected]("cache_version", [2, 3])
+def test_upgrade_preserves_an_already_admitted_frozen_turn(tmp_path, monkeypatch, status, cache_version):
+ monkeypatch.setattr(rooms, "local_authority_gateway_id", lambda: "home")
+ db = tmp_path / "state.db"
+ _, _, old_plan = legacy_cache(db, cache_version)
+ clock = [time.time()]
+ admitted = driver.admit_task(db, old_plan.identity, payload=old_plan.payload, clock=lambda: clock[0])
+ if status != "queued":
+ lease = driver.acquire_lease(db, room_id="upgrade-room", gateway_id="home", authority_epoch=1,
+ process_generation="prior", ttl_seconds=1, clock=lambda: clock[0])
+ driver.start_task(db, old_plan.identity, lease, expected_cancel_generation=0, clock=lambda: clock[0])
+ if status == "indeterminate":
+ clock[0] += 2
+ current = driver.acquire_lease(db, room_id="upgrade-room", gateway_id="home", authority_epoch=1,
+ process_generation="current", ttl_seconds=60, clock=lambda: clock[0])
+ driver.recover_room(db, current, clock=lambda: clock[0])
+ history = log(db)
+ server = SimpleNamespace(_methods={}, _sessions={}, _sessions_lock=threading.Lock())
+ service = HostedRoomService(server, db_path=db)
+ service.local_profiles = lambda: PROFILES
+ service.runtime.clock = lambda: clock[0]
+ monkeypatch.setattr(driver, "admit_task", lambda *a, **kw: pytest.fail("cache rebuild readmitted work"))
+ service.prepare_room(service.bindings()[0])
+ # Reopening the service repeats only derived-cache preparation, not execution.
+ cold = HostedRoomService(server, db_path=db)
+ cold.local_profiles = lambda: PROFILES
+ cold.prepare_room(cold.bindings()[0])
+ existing = driver.get_task_for_turn(db, old_plan.identity)
+ assert existing["status"] == status
+ assert existing["identity"] == admitted["identity"]
+ assert existing["payload"] == admitted["payload"]
+ assert log(db) == history
+ with sqlite3.connect(db) as conn:
+ assert conn.execute("SELECT COUNT(*) FROM hosted_room_driver_tasks WHERE room_id='upgrade-room'").fetchone()[0] == 1
\ No newline at end of file
diff --git a/tui_gateway/hosted_room_service.py b/tui_gateway/hosted_room_service.py
index 63740b76821..cc5ace10cc9 100644
--- a/tui_gateway/hosted_room_service.py
+++ b/tui_gateway/hosted_room_service.py
@@ -374,9 +374,15 @@ class HostedRoomService:
execution_generation=execution_generation):
continue
task_events = self.policy_checkpoint.events_for_task(
- room_id=room_id, source_event_seq=int(task["payload"]["source_event_seq"]))
+ room_id=room_id, source_event_seq=int(task["payload"]["source_event_seq"]),
+ input_context=task["payload"].get("input_context"), task_id=task["identity"].task_id)
plan = discussion.reconstruct_task_plan(
room, task_events, task, local_profiles=local_profiles)
+ message_id = f"dmessage:{task['identity'].task_id.removeprefix('dtask:')}"
+ if any(event.get("event_id") == message_id and event["kind"] == "message.member" for event in task_events):
+ # Finish an already visible immutable reply even if a later request arrived.
+ task_events = [event for event in task_events if event["kind"] != "message.user"
+ or int(event["seq"]) <= int(task["payload"]["source_event_seq"])]
publication = discussion.plan_publication(
room, task_events, plan, status=status, result=task.get("result"),
execution_generation=execution_generation if status == "deferred" else None,
@@ -415,16 +421,31 @@ class HostedRoomService:
return
decision = discussion.plan_next_task(
room, list(snapshot.events), local_profiles=self.local_profiles(),
- initial_watermarks=snapshot.watermarks)
+ initial_watermarks=snapshot.watermarks, freeze_input_context=True)
if decision.status == "task" and decision.task is not None:
- driver.admit_task(
- self.db_path, decision.task.identity, payload=decision.task.payload,
- clock=time.time)
+ existing = driver.get_task_for_turn(self.db_path, decision.task.identity)
+ legacy_payload = dict(decision.task.payload)
+ legacy_payload.pop("input_context", None)
+ if existing is not None and "input_context" in existing["payload"]:
+ # A rebuilt cache may add older committed context. The slot
+ # already belongs to its original, frozen admission.
+ prior_events = self.policy_checkpoint.events_for_task(
+ room_id=binding.room_id, source_event_seq=existing["payload"]["source_event_seq"],
+ input_context=existing["payload"]["input_context"], task_id=existing["identity"].task_id)
+ discussion.reconstruct_task_plan(room, prior_events, existing, local_profiles=self.local_profiles())
+ admitted = existing
+ elif existing is not None and existing["payload"] == legacy_payload:
+ discussion.reconstruct_task_plan(room, list(snapshot.events), existing,
+ local_profiles=self.local_profiles())
+ admitted = existing
+ else:
+ admitted = driver.admit_task(
+ self.db_path, decision.task.identity, payload=decision.task.payload, clock=time.time)
# A stop can race the policy read from another process: re-read after admission
# and cancel a task whose source event is now behind the room stop fence.
fence = self._policy_snapshot(self._room(binding.room_id)).stopped_through_seq
if decision.source_event_seq is not None and decision.source_event_seq < fence:
- self.runtime.cancel(decision.task.identity, cancel_id=f"stop-fence:{fence}")
+ self.runtime.cancel(admitted["identity"], cancel_id=f"stop-fence:{fence}")
elif decision.status in {"settled", "bounded"}:
self._append_room_status(room, decision)