The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: publish deferred room retries after discussion cleanup
Teknium80b3346eee35
diff --git a/gateway/hosted_room_policy_checkpoint.py b/gateway/hosted_room_policy_checkpoint.pyindex 97d538395ce..2d79bc98aad 100644--- a/gateway/hosted_room_policy_checkpoint.py+++ b/gateway/hosted_room_policy_checkpoint.py@@ -89,12 +89,16 @@ def _require_room(conn: sqlite3.Connection, room_id: str) -> None:def _settled_message(conn: sqlite3.Connection, room_id: str, discussion_event_id: str, message_event_id: Any) -> dict[str, Any] | None:- """Return the indexed member message a ``turn.settled`` event committed, if it is in the projection."""- rows = conn.execute(- "SELECT seq, event_json FROM hosted_room_policy_events WHERE room_id=? AND discussion_event_id=?",- (room_id, discussion_event_id)).fetchall()- return next(- (m for m in (json.loads(row["event_json"]) for row in rows) if m.get("event_id") == message_event_id), None)+ """Read the committed message even after its active discussion was compacted."""+ row = conn.execute(+ f"SELECT {_ROOM_EVENT_COLUMNS} FROM hosted_room_events WHERE room_id=? AND event_id=?",+ (room_id, message_event_id)).fetchone()+ if row is None:+ return None+ event = _event_from_room_row(row)+ if event["kind"] != "message.member" or _text(event["payload"], "discussion_event_id") != discussion_event_id:+ return None+ return eventclass HostedRoomPolicyCheckpoint:@@ -202,9 +206,10 @@ class HostedRoomPolicyCheckpoint:thread_id, discussion_event_id = _text(payload, "thread_id"), _text(payload, "discussion_event_id")if conn.execute("SELECT 1 FROM hosted_room_policy_events WHERE room_id=? AND discussion_event_id=? LIMIT 1",- (room_id, discussion_event_id)).fetchone() is None:- return- self._store_active_event(conn, event=event, thread_id=thread_id, discussion_event_id=discussion_event_id)+ (room_id, discussion_event_id)).fetchone() is not None:+ self._store_active_event(conn, event=event, thread_id=thread_id, discussion_event_id=discussion_event_id)+ # Late outcomes still need publication receipts and transcript commits,+ # but must not resurrect a completed discussion's active projection.if kind not in _TERMINAL_KINDS:returntask_id = _text(payload, "task_id")@@ -336,13 +341,21 @@ class HostedRoomPolicyCheckpoint:def events_for_task(self, *, room_id: str, source_event_seq: int) -> list[dict[str, Any]]:"""Load one bounded discussion projection for terminal reconstruction."""with self._connect() as conn:- source = conn.execute(- "SELECT discussion_event_id, thread_id FROM hosted_room_policy_events WHERE room_id=? AND seq=?",+ row = conn.execute(+ f"SELECT {_ROOM_EVENT_COLUMNS} FROM hosted_room_events WHERE room_id=? AND seq=?",(room_id, source_event_seq)).fetchone()- return [] if source is None else self._discussion_events(- conn, room_id=room_id, thread_id=str(source["thread_id"]),- discussion_event_id=str(source["discussion_event_id"]),+ if row is None or row["kind"] != "message.user":+ return []+ source = _event_from_room_row(row)+ events = self._discussion_events(+ conn, room_id=room_id, thread_id=_text(source["payload"], "thread_id"),+ discussion_event_id=str(source["event_id"]),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[source_event_seq] = source+ return [by_seq[seq] for seq in sorted(by_seq)]def compact_completed(self, *, room_id: str) -> None:"""Drop any completed projections left by an interrupted sync."""diff --git a/tests/tui_gateway/test_hosted_room_settled_retry.py b/tests/tui_gateway/test_hosted_room_settled_retry.pynew file mode 100644index 00000000000..de09fd44dfe--- /dev/null+++ b/tests/tui_gateway/test_hosted_room_settled_retry.py@@ -0,0 +1,73 @@+"""Deferred results survive discussion and bounded-transcript cleanup."""++import threading+import time+from types import SimpleNamespace++import pytest++from gateway import hosted_room_driver as driver, hosted_rooms+from tui_gateway.hosted_room_service import HostedRoomService++[email protected]("later_messages", [0, 25])+def test_settled_discussion_retry_publishes_once(tmp_path, monkeypatch, later_messages):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)+ (tmp_path / ".hermes" / "profiles" / "reviewer").mkdir(parents=True)+ server = SimpleNamespace(_methods={}, _sessions={}, _sessions_lock=threading.Lock())+ service = HostedRoomService(server, db_path=tmp_path / "state.db")+ service.create_room(room_id="room", name="Room", members=[+ {"member_id": "worker", "profile": "default", "handle": "worker"},+ {"member_id": "reviewer", "profile": "reviewer", "handle": "reviewer"},+ ])+ service.send(room_id="room", event_id="source", payload={"text": "Review", "thread_id": "thread"})+ binding = service.bindings()[0]+ task = driver.list_tasks(service.db_path, room_id="room", status="queued")[0]+ now = [time.time()]+ clock = lambda: now[0]+ service.runtime.clock = clock+ old = driver.acquire_lease(+ service.db_path, room_id="room", gateway_id=binding.gateway_id, authority_epoch=1,+ process_generation="old", ttl_seconds=1, clock=clock)+ driver.start_task(service.db_path, task["identity"], old, expected_cancel_generation=0, clock=clock)+ now[0] += 2+ lease = service.runtime._ensure_lease(binding)+ driver.recover_room(service.db_path, lease, clock=clock)+ driver.defer_indeterminate_task(+ service.db_path, task["identity"], lease, expected_execution_generation=1,+ expected_cancel_generation=0, reason="member_unavailable", clock=clock)+ service.prepare_room(binding)+ reviewer = driver.list_tasks(service.db_path, room_id="room", status="queued")[0]+ attempt = driver.start_task(+ service.db_path, reviewer["identity"], lease, expected_cancel_generation=0, clock=clock)+ driver.settle_task(service.db_path, attempt, settlement_id="pass", status="settled",+ result={"text": "PASS"}, clock=clock)+ service.prepare_room(binding)+ assert [e["kind"] for e in service._events("room")] == [+ "message.user", "turn.deferred", "turn.settled", "room.activity"]+ for index in range(later_messages):+ hosted_rooms.append_event(+ service.db_path, room_id="room", event_id=f"later-{index}", kind="message.user",+ actor={"kind": "user", "id": "test"},+ payload={"text": "Later", "thread_id": "thread"},+ authority_gateway_id=binding.gateway_id, authority_epoch=1)+ service._policy_snapshot(hosted_rooms.room_state(service.db_path, room_id="room"))+ assert service.retry_room_task("room", task_id=task["identity"].task_id)["status"] == "queued"+ attempt = driver.start_task(+ service.db_path, task["identity"], lease, expected_cancel_generation=0, clock=clock)+ driver.settle_task(service.db_path, attempt, settlement_id="retry", status="settled",+ result={"text": "Recovered answer"}, clock=clock)+ service.prepare_room(binding)+ restarted = HostedRoomService(server, db_path=service.db_path)+ for _ in range(2):+ restarted.prepare_room(binding)+ events = restarted._events("room")+ assert sum(e["kind"] == "message.member" and e["payload"].get("text") == "Recovered answer"+ for e in events) == 1+ assert restarted.policy_checkpoint.publication_exists(+ room_id="room", task_id=task["identity"].task_id, status="settled", execution_generation=2)+ for event_id in ("next", "after-stop"):+ assert restarted.send(room_id="room", event_id=event_id,+ payload={"text": "Continue", "thread_id": "thread"})["event_id"] == event_id+ restarted.stop_room("room", cancel_id=f"stop-{event_id}")