fix(webui): reconcile running turns on reconnect (#6715)

* fix(webui): reconcile running turns on reconnect

* test(webui): verify only the current turn-sync policy
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-19 16:08:20 +08:00
1 parent b453de9cf6
commit 094bac0dc3
25 files changed
+455 -226

No files matched your search

+2
View File
@@ -242,6 +242,8 @@ WebUI sends a `request_id` with every `new_chat`, `new_temporary_chat`, and `for
Clients must correlate tagged responses by ID, not by arrival order or the temporary-chat flag. Ordinary `attach` replies cannot complete a creation request. IDs provide correlation, not deduplication: a sent request that times out has an unknown outcome and must not be automatically replayed. Expired unsent requests must be removed before reconnecting.
For authenticated WebUI `attach` requests, `attached.live_turn_ids` lists all named owners in the session that are still queued or running when the gateway acknowledges the subscription. An empty list explicitly reports no named owners. It can retire previously observed owners after reconnect, but does not confirm a new submission, report a turn outcome, or say that the paginated transcript is complete.
A timeout ends the client's pending request, allowing a new user-initiated request with a different ID. A late response cannot complete that newer request. Late temporary-chat creations are discarded rather than selected.
Support and testing cover same-version WebUI/gateway combinations. Cross-version combinations may work, but a passing protocol check does not guarantee all features work; align versions first when troubleshooting. See [Versions and updating the right machine](guides/remote-instances.md#versions-and-updating-the-right-machine).
@@ -461,6 +461,59 @@ async def test_attach_exposes_the_session_canonical_model_preset(bus, tmp_path)
}
@pytest.mark.parametrize("persisted", [True, False])
async def test_reattach_during_terminal_write_observes_the_end(
history, bus, start_listener, monkeypatch, persisted: bool,
) -> None:
channel = _ch(bus, session_manager=history.sessions)
port, _ = await start_listener(channel)
chat_id = "reconnect-during-terminal"
turn_id = "turn-1"
metadata = {"webui": True, WEBUI_TURN_METADATA_KEY: turn_id, WEBSOCKET_TURN_OWNER_METADATA_KEY: "owner"}
await wth.publish_turn_run_status(
MessageBus(), InboundMessage(channel="websocket", sender_id="test", chat_id=chat_id,
content="question", metadata=metadata),
"running",
)
writing, release = asyncio.Event(), asyncio.Event()
async def persist_terminal(*args, **kwargs):
writing.set()
await release.wait()
return persisted
monkeypatch.setattr(channel._outbound._transcripts, "prepare_and_append", persist_terminal)
terminal = asyncio.create_task(channel.send(OutboundMessage(
channel="websocket", chat_id=chat_id, content="", metadata=metadata, event=TurnEndEvent(),
)))
token = channel.gateway.tokens.issue_token(300, audience="webui")
attach = json.dumps({"type": "attach", "chat_id": chat_id})
try:
await asyncio.wait_for(writing.wait(), timeout=2)
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?token={token}") as client:
await client.send(attach)
attached = await _recv_ws_event(client, "attached")
release.set()
await terminal
async with asyncio.timeout(2):
events = []
while True:
event = json.loads(await client.recv())
if event["event"] == "session_updated":
break
events.append(event)
assert [event["turn_id"] for event in events if event["event"] == "turn_end"] == [turn_id]
assert attached["live_turn_ids"] == [turn_id]
await client.send(attach)
assert (await _recv_ws_event(client, "attached"))["live_turn_ids"] == []
# Keeping an incomplete history marker must not assert liveness.
assert wth.websocket_turn_id(chat_id) == (None if persisted else turn_id)
finally:
release.set()
await terminal
wth.clear_websocket_turns(chat_id)
@pytest.mark.asyncio
async def test_temporary_chat_is_transient_and_discarded(history, bus, tmp_path) -> None:
sessions = history.sessions
@@ -5953,7 +6006,8 @@ def test_parse_envelope_rejects_legacy_and_garbage() -> None:
assert _parse_envelope('{"type":123}') is None
def test_sessions_list_includes_active_run_started_at(monkeypatch) -> None:
@pytest.mark.parametrize("retired", [False, True])
def test_sessions_list_reports_only_live_runs(monkeypatch, retired: bool) -> None:
from websockets.datastructures import Headers
from websockets.http11 import Request
@@ -6000,7 +6054,10 @@ def test_sessions_list_includes_active_run_started_at(monkeypatch) -> None:
wth.clear_websocket_turns("chat-1")
try:
asyncio.run(_register_running_turn("chat-1", 1_700_000_000.0))
asyncio.run(_register_running_turn("chat-1", 1_700_000_000.0, owner="owner-1"))
if retired:
assert wth.mark_websocket_turn_transcript_persistence_failed("chat-1", "owner-1")
wth.clear_websocket_turn_if_current("chat-1", "owner-1", preserve_persistence_failure=True)
req = Request("/api/sessions", Headers([("Authorization", "Bearer tok")]))
resp = asyncio.run(channel.gateway.http._handle_sessions_list(req))
finally:
@@ -6019,7 +6076,7 @@ def test_sessions_list_includes_active_run_started_at(monkeypatch) -> None:
"title": "Running",
"preview": "work",
"model_preset": "fast",
"run_started_at": 1_700_000_000.0,
**({} if retired else {"run_started_at": 1_700_000_000.0}),
"project_locked": True,
"handle": handle.public_payload(),
}
@@ -1,12 +1,17 @@
import json
from typing import Any
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock
import pytest
from websockets.asyncio.server import ServerConnection
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.session.webui_turns import (
clear_websocket_turns,
register_queued_websocket_turn_if_idle,
websocket_turn_wall_started_at,
)
from nanobot.webui.gateway_services import build_gateway_services
from nanobot.webui.outbound_delivery import WebUIOutboundDelivery
@@ -52,8 +57,7 @@ def _delivery(history, tmp_path) -> tuple[WebUIOutboundDelivery, _RecordingTrans
async def test_subscribe_hydration_is_quiet_when_no_turn_active(history, tmp_path):
outbound, transport = _delivery(history, tmp_path)
with patch("nanobot.webui.session_projection.websocket_turn_wall_started_at", return_value=None):
await outbound.hydrate("test-chat")
await outbound.hydrate("hydrate-idle-chat")
assert transport.frames == []
@@ -62,22 +66,19 @@ async def test_subscribe_hydration_is_quiet_when_no_turn_active(history, tmp_pat
async def test_subscribe_hydration_pushes_running_when_turn_active(history, tmp_path):
outbound, transport = _delivery(history, tmp_path)
with (
patch(
"nanobot.webui.session_projection.websocket_turn_wall_started_at",
return_value=1234567890.0,
),
patch(
"nanobot.webui.session_projection.websocket_turn_id",
return_value="turn-active",
),
):
await outbound.hydrate("test-chat")
chat_id = "hydrate-running-chat"
assert register_queued_websocket_turn_if_idle(chat_id, "turn-active") is not None
try:
started_at = websocket_turn_wall_started_at(chat_id)
assert started_at is not None
await outbound.hydrate(chat_id)
finally:
clear_websocket_turns(chat_id)
assert transport.frames == [{
"event": "goal_status",
"chat_id": "test-chat",
"chat_id": chat_id,
"status": "running",
"started_at": 1234567890.0,
"started_at": started_at,
"turn_id": "turn-active",
}]
+24 -7
View File
@@ -79,10 +79,11 @@ class _WebsocketTurn:
started_at: float
turn_id: str | None
transcript_persistence_failed: bool = False
ended: bool = False
# All in-flight lifecycle owners per chat, in admission order. The three maps
# above remain the latest-owner projection consumed by the HTTP API.
# In-flight owners and any retained transcript-recovery markers, in admission
# order. The three maps above remain the latest-owner projection for the HTTP API.
_WEBSOCKET_ACTIVE_TURNS: dict[str, dict[str, _WebsocketTurn]] = {}
@@ -251,21 +252,36 @@ async def maybe_generate_webui_title(
def websocket_turn_wall_started_at(chat_id: str) -> float | None:
"""Return ``time.time()`` when the active user turn began, if still running."""
"""Return the start time for the latest transcript owner, even if retired."""
return _WEBSOCKET_TURN_WALL_STARTED_AT.get(chat_id)
def websocket_turn_id(chat_id: str) -> str | None:
"""Return the WebUI identity of the active turn, when one was provided."""
"""Return the latest transcript owner's WebUI identity, even if retired."""
return _WEBSOCKET_TURN_IDS.get(chat_id)
def live_websocket_turns(chat_id: str) -> tuple[tuple[float, str | None], ...]:
"""Return queued/running owners, excluding retired transcript-recovery markers."""
turns = _WEBSOCKET_ACTIVE_TURNS.get(chat_id)
if turns is None:
return ()
# HTTP session lists also sample from a reader thread.
return tuple((turn.started_at, turn.turn_id) for turn in turns.copy().values() if not turn.ended)
def latest_live_websocket_turn(chat_id: str) -> tuple[float, str | None] | None:
"""Return the latest queued or running turn for status and admission."""
turns = live_websocket_turns(chat_id)
return turns[-1] if turns else None
def register_queued_websocket_turn_if_idle(
chat_id: str,
turn_id: str | None,
) -> str | None:
"""Track an accepted WebUI turn while it waits for AgentLoop admission."""
if websocket_turn_wall_started_at(chat_id) is not None:
if latest_live_websocket_turn(chat_id) is not None:
return None
owner = uuid4().hex
_WEBSOCKET_ACTIVE_TURNS.setdefault(chat_id, {})[owner] = _WebsocketTurn(
@@ -303,7 +319,7 @@ def mark_websocket_turn_transcript_persistence_failed(
chat_id: str,
owner: str | None,
) -> bool:
"""Keep a turn active when any canonical display event could not be written."""
"""Remember that this owner's canonical transcript may be incomplete."""
if not owner:
return False
turns = _WEBSOCKET_ACTIVE_TURNS.get(chat_id)
@@ -319,13 +335,14 @@ def clear_websocket_turn_if_current(
*,
preserve_persistence_failure: bool = False,
) -> bool:
"""Clear one lifecycle owner without disturbing concurrent turns for the chat."""
"""Retire one owner, optionally keeping its transcript-recovery marker."""
if not owner:
return False
turns = _WEBSOCKET_ACTIVE_TURNS.get(chat_id)
if turns is None or owner not in turns:
return False
if preserve_persistence_failure and turns[owner].transcript_persistence_failed:
turns[owner] = replace(turns[owner], ended=True)
return False
turns.pop(owner)
_sync_websocket_turn_projection(chat_id)
+16 -19
View File
@@ -38,9 +38,9 @@ from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.webui_turns import (
clear_websocket_turn_if_current,
clear_websocket_turns,
latest_live_websocket_turn,
live_websocket_turns,
register_queued_websocket_turn_if_idle,
websocket_turn_id,
websocket_turn_wall_started_at,
)
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import safe_filename
@@ -273,12 +273,9 @@ class WebUICommandRouter:
body["mcp_presets"] = mcp_presets
if session_mentions:
body["session_mentions"] = session_mentions
active_turn_id = websocket_turn_id(chat_id)
if active_turn_id is not None:
body["active_turn_id"] = active_turn_id
started_at = websocket_turn_wall_started_at(chat_id)
if active_turn_id is not None and started_at is not None:
body["started_at"] = started_at
live_turn = latest_live_websocket_turn(chat_id)
if live_turn is not None and live_turn[1] is not None:
body["started_at"], body["active_turn_id"] = live_turn
raw = json.dumps(body, ensure_ascii=False)
for connection in self._transport.webui_subscribers(chat_id):
if connection is not origin:
@@ -448,12 +445,13 @@ class WebUICommandRouter:
)
return
self._transport.webui_attach(connection, chat_id)
await self._transport.webui_send_event(
connection,
"attached",
chat_id=chat_id,
**(await self._session_projection.attach_fields(webui_session_key(chat_id))),
)
fields = await self._session_projection.attach_fields(webui_session_key(chat_id))
if connection in self._webui_connections:
# Sample after the metadata read and enqueue without another yield.
fields["live_turn_ids"] = [
turn_id for _, turn_id in live_websocket_turns(chat_id) if turn_id is not None
]
await self._transport.webui_send_event(connection, "attached", chat_id=chat_id, **fields)
await self._outbound.hydrate(chat_id)
return
if command_type == "set_sidebar_state":
@@ -503,7 +501,7 @@ class WebUICommandRouter:
lambda: self._workspaces.scope_for_set_request(
envelope,
chat_id=chat_id,
chat_running=websocket_turn_wall_started_at(chat_id) is not None,
chat_running=latest_live_websocket_turn(chat_id) is not None,
can_change_project=self.workspace_project_selection_available(connection),
),
chat_id=chat_id,
@@ -692,7 +690,7 @@ class WebUICommandRouter:
lambda: self._workspaces.scope_for_message(
envelope,
chat_id=chat_id,
chat_running=websocket_turn_wall_started_at(chat_id) is not None,
chat_running=latest_live_websocket_turn(chat_id) is not None,
can_change_project=self.workspace_project_selection_available(connection),
),
chat_id=chat_id,
@@ -921,8 +919,7 @@ class WebUICommandRouter:
session_mentions=session_mentions,
)
if is_webui and turn_id:
active_turn_id = websocket_turn_id(chat_id)
started_at = websocket_turn_wall_started_at(chat_id)
started_at, active_turn_id = latest_live_websocket_turn(chat_id) or (None, None)
await self._transport.webui_send_event(
connection,
"message_accepted",
@@ -1007,7 +1004,7 @@ class WebUICommandRouter:
scope = policy.workspace_scope if policy is not None else (
await self._workspaces.scope_for_message(
payload, chat_id=chat_id,
chat_running=websocket_turn_wall_started_at(chat_id) is not None,
chat_running=latest_live_websocket_turn(chat_id) is not None,
can_change_project=self.workspace_project_selection_available(connection),
)
)
+13 -15
View File
@@ -333,17 +333,13 @@ class WebUIOutboundDelivery:
turn_id = msg.metadata.get(WEBUI_TURN_METADATA_KEY)
turn_owner = msg.metadata.get(WEBSOCKET_TURN_OWNER_METADATA_KEY)
owner = turn_owner if isinstance(turn_owner, str) else None
try:
if recipients and event.status in ("running", "idle"):
await self._send_goal_status(
msg.chat_id, event.status, started_at=event.started_at,
turn_id=turn_id if isinstance(turn_id, str) else None,
)
finally:
if event.status == "idle":
clear_websocket_turn_if_current(
msg.chat_id, owner, preserve_persistence_failure=True,
)
if event.status == "idle":
clear_websocket_turn_if_current(msg.chat_id, owner, preserve_persistence_failure=True)
if recipients and event.status in ("running", "idle"):
await self._send_goal_status(
msg.chat_id, event.status, started_at=event.started_at,
turn_id=turn_id if isinstance(turn_id, str) else None,
)
return
if isinstance(event, TurnEndEvent):
turn_id = msg.metadata.get(WEBUI_TURN_METADATA_KEY)
@@ -591,7 +587,8 @@ class WebUIOutboundDelivery:
turn_owner: str | None = None,
context_graph_parts: ContextGraphParts | None = None,
) -> None:
recipients = self._transport.webui_recipients(ChatAudience(chat_id))
audience = ChatAudience(chat_id)
recipients = () if persistence == "turn_complete" else self._transport.webui_recipients(audience)
body: dict[str, Any] = dict(payload)
if persistence == "turn_activity":
await self._persist_turn_transcript_event(
@@ -607,10 +604,11 @@ class WebUIOutboundDelivery:
chat_id, body, metadata=metadata, phase="complete",
transcript_overrides={WEBUI_TRANSCRIPT_INCOMPLETE_KEY: True} if prior_failure else None,
)
if persisted:
# A durable incomplete marker allows HTTP recovery after restart.
clear_websocket_turn_if_current(chat_id, turn_owner)
clear_websocket_turn_if_current(chat_id, turn_owner, preserve_persistence_failure=not persisted)
self.discard(chat_id, complete=True)
# Include connections that may have seen this owner as live while
# the terminal write was pending.
recipients = self._transport.webui_recipients(audience)
await self._fanout(recipients, body, label=f" {body['event']} ")
async def _send_goal_state(self, chat_id: str, blob: dict[str, Any]) -> None:
+2 -5
View File
@@ -9,7 +9,7 @@ from nanobot.providers.base import LLMUsage
from nanobot.session.model_selection import SessionModelPreset
from nanobot.session.recovery import recovery_state_from_metadata
from nanobot.session.state import SessionState
from nanobot.session.webui_turns import websocket_turn_id, websocket_turn_wall_started_at
from nanobot.session.webui_turns import latest_live_websocket_turn
from nanobot.webui.goal_state import goal_state_ws_blob
if TYPE_CHECKING:
@@ -114,7 +114,4 @@ class WebUISessionProjection:
@staticmethod
def active_turn_status(chat_id: str) -> tuple[float, str | None] | None:
"""Return same-process running-turn state for reconnect hydration."""
started_at = websocket_turn_wall_started_at(chat_id)
if started_at is None:
return None
return started_at, websocket_turn_id(chat_id)
return latest_live_websocket_turn(chat_id)
+2 -2
View File
@@ -24,7 +24,7 @@ from nanobot.security.workspace_access import (
default_workspace_scope,
validate_workspace_scope_payload,
)
from nanobot.session.webui_turns import websocket_turn_wall_started_at
from nanobot.session.webui_turns import latest_live_websocket_turn
from nanobot.webui.session_identity import webui_session_key
if TYPE_CHECKING:
@@ -532,7 +532,7 @@ class WebUIWorkspaceController:
async def stage_scope(self, chat_id: str, scope: WorkspaceScope) -> WorkspaceScope:
"""Keep a new chat's scope transient until its first accepted message."""
async with self._scope_lock(chat_id):
if websocket_turn_wall_started_at(chat_id) is not None:
if latest_live_websocket_turn(chat_id) is not None:
raise WorkspaceScopeError("chat_running", status=409)
session_key = webui_session_key(chat_id)
if (
+4 -4
View File
@@ -1085,7 +1085,7 @@ class GatewayHTTPHandler:
stored_sessions: list[dict[str, Any]],
) -> dict[str, Any]:
assert self.session_manager is not None
from nanobot.session.webui_turns import websocket_turn_wall_started_at
from nanobot.session.webui_turns import latest_live_websocket_turn
sessions = list_webui_sessions(self.session_manager, stored_sessions)
cleaned: list[dict[str, Any]] = []
@@ -1105,9 +1105,9 @@ class GatewayHTTPHandler:
if row.get("recovery_state") is None:
row.pop("recovery_state", None)
chat_id = key.split(":", 1)[1]
started_at = websocket_turn_wall_started_at(chat_id)
if started_at is not None:
row["run_started_at"] = started_at
turn = latest_live_websocket_turn(chat_id)
if turn is not None:
row["run_started_at"] = turn[0]
if default_scope is None:
default_scope = self.workspaces.default_scope()
scope_present, raw_scope = indexed_workspace_scope(s)
+5 -9
View File
@@ -71,12 +71,8 @@ async def test_hydration_events_restore_goal_and_running_turn(
}
}
monkeypatch.setattr(
"nanobot.webui.session_projection.websocket_turn_wall_started_at",
lambda _chat_id: 42.5,
)
monkeypatch.setattr(
"nanobot.webui.session_projection.websocket_turn_id",
lambda _chat_id: "turn-1",
"nanobot.webui.session_projection.latest_live_websocket_turn",
lambda _chat_id: (42.5, "turn-1"),
)
events = await WebUISessionProjection(sessions).hydration_events(
@@ -112,7 +108,7 @@ async def test_hydration_clears_stale_goal_without_an_active_goal(
sessions.state.read_metadata = AsyncMock(side_effect=lambda key: sessions.read_session_metadata(key))
sessions.read_session_metadata.return_value = {"metadata": {}}
monkeypatch.setattr(
"nanobot.webui.session_projection.websocket_turn_wall_started_at",
"nanobot.webui.session_projection.latest_live_websocket_turn",
lambda _chat_id: None,
)
@@ -142,11 +138,11 @@ async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loop
def active_turn(_chat_id):
assert threading.get_ident() == loop_thread
return 42.5
return (42.5, None)
monkeypatch.setattr(sessions._store, "read_metadata", read_metadata)
monkeypatch.setattr(
"nanobot.webui.session_projection.websocket_turn_wall_started_at", active_turn,
"nanobot.webui.session_projection.latest_live_websocket_turn", active_turn,
)
projection = WebUISessionProjection(sessions)
task = asyncio.create_task(projection.hydration_events("websocket:chat-io", "chat-io"))
+18 -1
View File
@@ -9,6 +9,7 @@ interface TurnRecord {
// Only openOrder marks unsettled ownership; a timestamp alone does not.
openOrder: number | null;
startedAt: number | null;
needsLiveCheck: boolean;
}
interface ChatRecord {
@@ -59,6 +60,7 @@ type Command =
| { kind: "transport-lost" }
| { kind: "local-stop" | "forget"; chatId: string }
| { kind: "fence" | "settle-completed-lifecycle"; chatId: string; completedTurnIds: readonly string[] }
| { kind: "reattach"; chatId: string; liveTurnIds: readonly string[] }
| { kind: "restore-pending"; chatId: string; generation: number; turnId: string | null };
export type RunEffect =
@@ -176,6 +178,7 @@ export class ClientRunLedger {
case "transport-lost":
for (const chat of this.chats.values()) {
for (const turn of chat.turns.values()) {
turn.needsLiveCheck = turn.openOrder !== null && (!turn.delivery || turn.delivery.phase === "accepted");
if (turn.delivery?.phase === "sent") {
turn.delivery = { phase: "unknown", role: turn.delivery.role };
}
@@ -207,6 +210,20 @@ export class ClientRunLedger {
chat.anonymousActive = command.turnId === null;
break;
}
case "reattach": {
const chat = this.chats.get(command.chatId);
if (!chat) break;
const live = new Set(command.liveTurnIds);
const retired: string[] = [];
for (const [turnId, turn] of chat.turns) {
if (turn.needsLiveCheck && !live.has(turnId)) retired.push(turnId);
turn.needsLiveCheck = false;
}
// Absence only retires previously observed owners, not new/uncertain sends.
// It does not report an outcome or claim that the transcript is complete.
if (retired.length > 0) this.completeTurns(command.chatId, retired, "lifecycle", effects);
break;
}
case "fence":
case "settle-completed-lifecycle":
this.completeTurns(command.chatId, command.completedTurnIds,
@@ -391,7 +408,7 @@ export class ClientRunLedger {
private ensureTurn(chat: ChatRecord, turnId: string): TurnRecord {
let turn = chat.turns.get(turnId);
if (!turn) {
turn = { delivery: null, openOrder: null, startedAt: null };
turn = { delivery: null, openOrder: null, startedAt: null, needsLiveCheck: false };
chat.turns.set(turnId, turn);
}
return turn;
+4
View File
@@ -1069,6 +1069,10 @@ export class NanobotClient {
} else {
this.knownChats.add(parsed.chat_id);
}
const live = parsed.live_turn_ids;
if (Array.isArray(live) && live.every((id) => typeof id === "string" && id.length > 0)) {
this.applyRunEffects(this.runs.transition({ kind: "reattach", chatId: parsed.chat_id, liveTurnIds: live }));
}
this.dispatch(parsed.chat_id, parsed);
return;
}
+1
View File
@@ -1565,6 +1565,7 @@ export type InboundEvent =
chat_id: string;
request_id?: string;
temporary?: boolean;
live_turn_ids?: string[];
recovery_state?: RecoveryState;
usage?: TurnUsage;
}
@@ -307,6 +307,50 @@ describe("reconnect across chat selection and transport generations", () => {
state: { active: false, unsettled: false }, unsettled: [] });
});
it.each(["failed", "fragment"] as const)("clears a completed run after reconnect with a %s history read", async (read) => {
const h = harness();
h.client.attach("alpha");
act(() => h.running("alpha", "turn-1", 100));
expect(h.client.getRunState("alpha").active).toBe(true);
await h.reopen();
await act(async () => {
const pending = h.reads.at(-1)!;
if (read === "failed") pending.fail(503);
else pending.resolve({ ...history("alpha", []), page: {
history_generation: "real-use", before_cursor: null, has_more_before: true,
record_range: { turn: 1, start: 1, end: 2 },
} });
});
expect(h.client.getRunState("alpha").active).toBe(true);
act(() => {
h.socket().receive({ event: "attached", chat_id: "alpha", live_turn_ids: [] });
h.running("alpha", "turn-1", 100); // An older running frame was still on the bus.
});
expect(h.client.getRunState("alpha").active).toBe(false);
h.close();
});
it("preserves a still-live owner and a newly submitted turn on reattach", async () => {
const h = harness();
h.client.attach("alpha");
act(() => {
h.running("alpha", "finished", 100);
h.running("alpha", "still-live", 200);
});
await h.reopen();
act(() => {
h.client.sendMessage("alpha", "new submission", undefined, { turnId: "new" });
h.socket().receive({ event: "attached", chat_id: "alpha", live_turn_ids: ["still-live"] });
});
expect(h.client.getRunState("alpha").latestTurnId).toBe("new");
expect(h.client.isRunCompleted("alpha", "new")).toBe(false);
act(() => h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "new" }));
expect(h.client.getRunState("alpha").active).toBe(true);
act(() => h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "still-live" }));
expect(h.client.getRunState("alpha").active).toBe(false);
h.close();
});
it("recovers six chats beyond the read-concurrency limit after a failed page and repeated drops", async () => {
const h = harness();
const chats = Array.from({ length: 6 }, (_, index) => `chat-${index}`);
@@ -0,0 +1,28 @@
# Attach reconciliation: bounded verification
A disconnect can drop the only named terminal observation. Even if the socket reconnects, paged history may fail or omit that ID. The attach reply therefore reports **all live named owners for the attached chat**. It is an absence check for previously confirmed, still-open owners marked by transport loss, not a new source of ownership, transcript coverage, or completion events. This is a separate finite model from the history/cache partitions; it is not a checked refinement of the Gateway or TypeScript.
## Source boundary and checked behavior
| Boundary | `AttachReconciliation.tla` |
| --- | --- |
| `nanobot/webui/inbound_commands.py` trusted `attach`, metadata in `session_projection.py`, WebSocket writer in `nanobot/channels/websocket/runtime.py` | `Subscribe` precedes the asynchronous metadata wait; `EnqueueAttached` samples `Live` and enqueues in one step on the same FIFO as pushes. `Hydrate` is separate ordinary running evidence. |
| `nanobot/session/webui_turns.py` delivery owners and `nanobot/webui/outbound_delivery.py` terminal/idle delivery | The named owner stays live while terminal persistence is in flight. Retirement removes it from live status for either persistence outcome; an incomplete transcript can remain without being reported as running by attach, hydration, or the session list. Named idle also retires the owner. `DeliverTerminal` selects the subscribers at retirement, after persistence returns. |
| `webui/src/lib/nanobot-client.ts` socket replacement and `client-run-ledger.ts` ownership | `LoseTransport` marks only confirmed open names, including neither queued local work nor anonymous recovery. `Observe` closes and tombstones marked absent IDs; presence alone adds no owner. Ordinary running hydration/push can create one. `ReceiveOld` ignores a previous socket's callback, and `ReplayBuffered` checks that a delayed start/delta cannot reopen a tombstoned lifecycle. |
| Paged HTTP recovery (`useReconnectRuns.ts` and the history models) | HTTP supplies no completion evidence in this partition. A failed read and a page missing the ID are equivalent for this check. The separate history models cover pages that supply completion evidence. |
`TypeOK` and `LifecycleSafety` check that no live name is closed; the exact marked/open absent IDs are closed and tombstoned without adding owners, clearing a surviving clock, changing independent anonymous/queued work, fencing content, or generating synthetic completion. Server turn 1 starts at a reachable checkpoint (confirmed on the old connection, with a potentially lagging duplicate running event). Turn 2 can start while turn 1's terminal projection is awaiting persistence or after it retires. Consequently a sample may contain both names, preserve a still-running name, report a newer name not yet observed, or omit an old name while the newer one is already open. An independent queued candidate can be present at the loss or submitted after it. One or two drops may occur, including during handshake or before writer delivery.
`EventuallyRetiredOwnersSettle` checks each name independently: if the socket stays healthy after reconnect and that named owner is retired, eventually the client has no open ownership for that name and never reopens it. A newly queued send, anonymous recovery, or a different still-running server turn need not settle for this to hold. If none of those independent activities remain, settlement removes the stale busy indicator. The ordering argument is that a retirement **before** the sample yields absence; a retirement **after** the sample still addresses the already-subscribed socket. A later loss marks again and requires a later healthy attach.
## Scope and fairness
The model checks one chat, two unique named server IDs and one independent unacknowledged local candidate, one callback slot from a previous socket, and one late lifecycle replay probe. There is one complete, trusted snapshot per reconnect; retaining a mark for a live name after that snapshot is immaterial because the next loss recomputes marks. The queue models current-socket enqueue and receive order, not transcript or send-queue internals. Terminal recipient selection, retirement and enqueue are one model step after persistence; named idle is modeled without a persistence gap. Current-socket running hydration samples and enqueues in one step; the model does not cover an older server-side hydration task publishing a stale status onto a replacement socket. The wire does not independently discard addressed frames while healthy. Matching, writer serialization and lifetime/ownership hooks in the implementation require separate source review and regression tests.
Weak fairness is for reconnect, subscribe, completing the metadata wait and enqueuing `attached`, ordinary hydration and processing a nonempty healthy writer. It permits finite delay or another loss at any point. No fairness is assumed for turn admission or completion, local/anonymous work, HTTP, stale callbacks, or another disconnect. Permanent outage, a reconnect with no subsequent healthy synchronization, malformed or missing attach evidence, authentication/host changes, unbounded workloads, cross-chat interactions, and transcript/text projection are outside this liveness claim. There is no state constraint, symmetry reduction, or depth cutoff. Terminal states can stutter (`CHECK_DEADLOCK FALSE`).
## Reproduce and evidence
From the repository root, run `python3 -B webui/verification/turn-sync/run_tlc.py --jar /path/to/verified-tla2tools.jar --case attach-reconciliation`. This case also runs by default. It allows up to two losses, including schedules with a single loss.
The reference run with TLC 2.19 generated 654,943 states and exhausted all 154,552 distinct states with no counterexample and an empty state queue.
@@ -0,0 +1,146 @@
----------------------- MODULE AttachReconciliation -----------------------
EXTENDS Naturals, FiniteSets, Sequences
CONSTANT MaxLosses
Turns == {1, 2}
Local == 3
Idle == 0
\* Phase: 0 not admitted, 1 running, 2 awaiting terminal persistence,
\* 3 retired/durable, 4 retired/incomplete, 5 retired via named idle.
VARIABLES phase, socket, connection, wire, oldCallback, client, probed, safe
vars == <<phase, socket, connection, wire, oldCallback, client, probed, safe>>
Live == {t \in Turns : phase[t] \in {1, 2}}
Retired(t) == phase[t] >= 3
Subscribed == connection \in {"metadata", "hydrate", "ready"}
Frame(kind, id, ids) == [kind |-> kind, id |-> id, ids |-> ids]
Running(t) == Frame("running", t, {})
NoFrame == Frame("none", Idle, {})
Init ==
/\ phase = [t \in Turns |-> IF t = 1 THEN 1 ELSE 0]
/\ socket = 1 /\ connection = "ready"
\* Turn 1 was confirmed over this socket. A duplicate running callback may lag.
/\ wire = <<Running(1)>> /\ oldCallback = [socket |-> Idle, frame |-> NoFrame]
/\ client = [open |-> {1}, marked |-> {}, closed |-> {}, clock |-> 1,
anonymous |-> FALSE, fenced |-> {}, successes |-> {}]
/\ probed = FALSE /\ safe = TRUE
LoseTransport ==
/\ connection # "down" /\ socket <= MaxLosses
/\ socket' = socket + 1 /\ connection' = "down" /\ wire' = <<>>
/\ oldCallback' = IF wire = <<>> THEN oldCallback ELSE [socket |-> socket, frame |-> Head(wire)]
\* 3 has a queued send but has not had a server observation.
/\ client' = [client EXCEPT !.marked = client.open \cap Turns]
/\ UNCHANGED <<phase, probed, safe>>
Reconnect ==
/\ connection = "down" /\ connection' = "open"
/\ UNCHANGED <<phase, socket, wire, oldCallback, client, probed, safe>>
Subscribe ==
/\ connection = "open" /\ connection' = "metadata"
/\ UNCHANGED <<phase, socket, wire, oldCallback, client, probed, safe>>
EnqueueAttached ==
/\ connection = "metadata" /\ connection' = "hydrate"
\* Metadata await is before this atomic sample + enqueue on the same FIFO.
/\ wire' = Append(wire, Frame("attached", Idle, Live))
/\ UNCHANGED <<phase, socket, oldCallback, client, probed, safe>>
Hydrate ==
/\ connection = "hydrate" /\ connection' = "ready"
\* Ordinary running hydration is a separate, ordered observation, not presence.
/\ wire' = IF Live = {} THEN wire ELSE Append(wire, Running(IF 2 \in Live THEN 2 ELSE 1))
/\ UNCHANGED <<phase, socket, oldCallback, client, probed, safe>>
StartNewer ==
/\ phase[1] >= 2 /\ phase[2] = 0
/\ phase' = [phase EXCEPT ![2] = 1]
/\ wire' = IF Subscribed THEN Append(wire, Running(2)) ELSE wire
/\ UNCHANGED <<socket, connection, oldCallback, client, probed, safe>>
BeginPersistence(t) ==
/\ phase[t] = 1 /\ phase' = [phase EXCEPT ![t] = 2]
/\ UNCHANGED <<socket, connection, wire, oldCallback, client, probed, safe>>
DeliverTerminal(t, outcome) ==
/\ IF outcome = 5 THEN phase[t] = 1 ELSE phase[t] = 2
/\ phase' = [phase EXCEPT ![t] = outcome]
\* An incomplete transcript (4) does not keep the owner live. Named idle (5)
\* needs no persistence. Both use the subscribers at retirement.
/\ LET kind == IF outcome = 5 THEN "idle" ELSE "terminal"
IN wire' = IF Subscribed THEN Append(wire, Frame(kind, t, {})) ELSE wire
/\ UNCHANGED <<socket, connection, oldCallback, client, probed, safe>>
SubmitLocal ==
/\ Local \notin client.open
/\ client' = [client EXCEPT !.open = @ \cup {Local}]
/\ UNCHANGED <<phase, socket, connection, wire, oldCallback, probed, safe>>
BeginAnonymous ==
/\ socket > 1 /\ ~client.anonymous
/\ client' = [client EXCEPT !.anonymous = TRUE]
/\ UNCHANGED <<phase, socket, connection, wire, oldCallback, probed, safe>>
Close(c, ids) == [c EXCEPT !.open = @ \ ids, !.marked = @ \ ids, !.closed = @ \cup ids,
!.clock = IF c.clock \in ids THEN Idle ELSE @]
Observe(c, msg) ==
CASE msg.kind = "attached" -> Close(c, c.marked \ msg.ids)
[] msg.kind \in {"running", "delta"} ->
IF msg.id \in c.closed THEN c ELSE [c EXCEPT !.open = @ \cup {msg.id}, !.clock = msg.id]
[] msg.kind = "terminal" -> Close([c EXCEPT !.successes = @ \cup {msg.id}], {msg.id})
[] msg.kind = "idle" -> Close(c, {msg.id})
[] OTHER -> c
AttachEffects(before, after, live) ==
LET absent == {t \in before.open \cap Turns : t \in before.marked /\ t \notin live}
IN /\ before.open \ after.open = absent
/\ after.open \subseteq before.open
/\ before.closed \subseteq after.closed
/\ after.closed \ before.closed = absent
/\ (before.clock \in after.open => after.clock = before.clock)
/\ after.anonymous = before.anonymous
/\ after.fenced = before.fenced
/\ after.successes = before.successes
Receive ==
/\ Subscribed /\ wire # <<>>
/\ LET msg == Head(wire)
IN /\ client' = Observe(client, msg)
/\ safe' = safe /\ (msg.kind = "attached" => AttachEffects(client, client', msg.ids))
/\ wire' = Tail(wire)
/\ UNCHANGED <<phase, socket, connection, oldCallback, probed>>
ReceiveOld ==
/\ connection # "down" /\ oldCallback.frame # NoFrame
/\ client' = IF oldCallback.socket = socket THEN Observe(client, oldCallback.frame) ELSE client
/\ safe' = safe /\ client' = client
/\ oldCallback' = [socket |-> Idle, frame |-> NoFrame]
/\ UNCHANGED <<phase, socket, connection, wire, probed>>
ReplayBuffered(kind) ==
/\ socket > 1 /\ Subscribed /\ ~probed /\ 1 \in client.closed
\* One pre-closure buffered lifecycle-capable event; not a transcript probe.
/\ client' = Observe(client, Frame(kind, 1, {}))
/\ safe' = safe /\ client' = client
/\ probed' = TRUE
/\ UNCHANGED <<phase, socket, connection, wire, oldCallback>>
Next ==
\/ LoseTransport \/ Reconnect \/ Subscribe \/ EnqueueAttached \/ Hydrate
\/ StartNewer \/ (\E t \in Turns: BeginPersistence(t) \/ (\E outcome \in 3..5: DeliverTerminal(t, outcome)))
\/ SubmitLocal \/ BeginAnonymous
\/ Receive \/ ReceiveOld \/ (\E kind \in {"running", "delta"}: ReplayBuffered(kind))
\* Healthy transport eventually drains. Work, replay and further losses need
\* not occur. HTTP provides no completion evidence in this partition.
FairSpec == Init /\ [][Next]_vars /\ WF_vars(Reconnect) /\ WF_vars(Subscribe)
/\ WF_vars(EnqueueAttached) /\ WF_vars(Hydrate) /\ WF_vars(Receive)
TypeOK ==
/\ phase \in [Turns -> 0..5]
/\ socket \in 1..(MaxLosses+1)
/\ connection \in {"down", "open", "metadata", "hydrate", "ready"}
/\ client.open \subseteq Turns \cup {Local} /\ client.closed \subseteq Turns
/\ client.marked \subseteq client.open \cap Turns /\ client.clock \in Turns \cup {Idle}
/\ client.anonymous \in BOOLEAN /\ client.fenced = {} /\ client.successes \subseteq Turns
LifecycleSafety ==
/\ safe /\ client.closed \cap client.open = {}
/\ (client.clock = Idle \/ client.clock \in client.open)
/\ client.closed \cap Live = {}
/\ \A t \in client.successes: phase[t] \in {3, 4}
Healthy == socket > 1 /\ connection = "ready"
\* On stable reconnect and actual retirement, both absence and later terminal
\* are sufficient. Do not require that an executing turn or local send finishes.
EventuallyRetiredOwnersSettle ==
\A t \in Turns: (<>[] Healthy /\ <>[] Retired(t)) => <>[] (t \notin client.open)
=============================================================================
+9 -12
View File
@@ -1,8 +1,8 @@
# WebUI turn synchronization: bounded TLC models
These models check the missed-completion/stuck-busy ordering in [PR #6683](https://github.com/HKUDS/nanobot/pull/6683): a terminal frame is lost, a newer turn starts, and recovery history explicitly completes the older turn. Completing that turn must not stop the newer one or discard content that history has not covered.
These models check recovery from a missed terminal frame. History can explicitly complete an older turn without stopping a newer one or discarding uncovered content. Independently, trusted attach can retire a previously confirmed owner absent from the Gateway's complete live-ID set, even if paged history supplies no completion ID.
**These are handwritten abstractions of selected current-implementation transitions, not mechanical verification of TypeScript or proof of all WebUI/Gateway behavior.** The default runner checks twelve positive configurations. Two current-policy missing-evidence cases run separately and retain temporal counterexamples; they are never counted as positive passes.
**These are handwritten abstractions of selected transitions, not mechanical verification of implementation code or proof of all WebUI/Gateway behavior.** The runner checks thirteen configurations by default.
## Files and source mapping
@@ -14,8 +14,9 @@ These models check the missed-completion/stuck-busy ordering in [PR #6683](https
| `CacheHandoff.tla` | Shared full-page publication, superseded own reads, one mounted whole-snapshot adopter and rejected stale callbacks. |
| `SharedRequests.tla` | Per-key request sharing, consumer cancellation, invalidation/replacement, reconnect and stale/late delivery. |
| `CompletionAuthority.tla` | Exact-ID ledger closure, coverage-dependent content fencing, anonymous recovery and another-chat isolation. |
| `AttachReconciliation.tla` | Trusted attach snapshot and terminal fanout ordering; loss-marked ownership, stale socket callbacks and lifecycle-only absence reconciliation independent of paged history. |
The source owners are `client-run-ledger.ts`, `nanobot-client.ts`, `canonical-run-snapshot.ts`, `latest-thread-request.ts`, `thread-transcript.ts`, `webui-thread-cache.ts`, `useReconnectRuns.ts`, `useNanobotStream.ts` and `ThreadShell.tsx`. The runner can record their hashes; the mapping still requires human review. [`USAGE-LIFECYCLE.md`](USAGE-LIFECYCLE.md) details the dynamic full-page mapping.
The runner can record the relevant client and Gateway source hashes; the mapping still requires human review. [`USAGE-LIFECYCLE.md`](USAGE-LIFECYCLE.md) details the dynamic full-page mapping. [`ATTACH-RECONCILIATION.md`](ATTACH-RECONCILIATION.md) describes the separate attach model, fairness assumptions, and reference runs.
The Gateway owns execution. The request registry owns cancellation and stale-response eligibility; `ThreadTranscript` owns content admission/coverage; `ClientRunLedger` alone owns the client's observed run state. Fresh full pages supply explicit completion facts even when mount/cache eligibility prevents content adoption. Eligible history is cached before completion notifications. The mounted transcript alone adopts whole snapshots; only an unmounted reader can perform background adoption, and only for an eligible idle page. Lifecycle-only closure preserves uncovered content and independent anonymous recovery. Initial cached seeds are not fresh evidence. Mounted fragments hand off completed IDs only when their gap/admission rules expose them.
@@ -26,8 +27,9 @@ The Gateway owns execution. The request registry owns cancellation and stale-res
- `PartialCompletionPreservesRecovery` and `LifecycleOnlyPreservesContentAndRecovery`: named completion preserves independent anonymous recovery and uncovered content.
- `MountedFragmentRequiresAcceptance`, `ActiveUnmountedSnapshotIsNotAdopted`, `CachePrecedesIdleNotification` and `SoleCanonicalActor`: content admission, notification ordering and single-owner boundaries.
- `EventuallyIdle` and `EventuallyRequestsDrain`: conditional eventual quiescence under the stated finite workload and fairness assumptions.
- `LifecycleSafety` and `EventuallyRetiredOwnersSettle`: after healthy reconnection, retired owners settle without completion evidence from history and without closing live owners.
## Scope and limits
## History partition scope and limits
The fixed-mount submodel has one chat, two sequential server turns, at most one disconnect/reconnect and one logical latest-history read. `Mounted` is fixed for a run. Request, server capture and response processing are separate actions. Full pages contain all completed/observed IDs within the bounded turns. A real selected page can omit an ID, so this assumption matters. Mounted full-page facts are assumed to reach reconciliation; cache routing and dynamic selection are checked separately.
@@ -44,20 +46,15 @@ Requirements: Python 3.9+, Java and the official [`tla2tools.jar` from TLA+ v1.7
From this directory in PowerShell:
```powershell
# Twelve positive checks: every finite graph must exhaust without a counterexample.
python -B .\run_tlc.py --jar 'C:\path\to\tla2tools.jar'
if ($LASTEXITCODE -ne 0) { throw 'TLC check failed' }
# Current-policy missing-evidence limits, separate from positive checks.
python -B .\run_tlc.py --limits --jar 'C:\path\to\tla2tools.jar'
if ($LASTEXITCODE -ne 0) { throw 'Missing-evidence classification changed' }
```
Use `--case revised-unmounted-live` (repeatable) for individual cases. `--output-root` must name a new directory outside the checkout; otherwise a private temporary directory is allocated. `--implementation-root <repository-root>` records the relevant source hashes without asserting a checked refinement. Models/configs are copied into the external output directory before Java starts. Logs, state graphs and generated traces stay there. `manifest.json` records input/jar hashes, commands, exit statuses and graph counts. Defaults are two workers, a 1536 MiB heap and a 600-second per-case timeout; cases run sequentially.
A positive result requires exit 0, TLC's no-error completion message and an empty state queue. Timeouts, specification errors and other exits fail the runner. Limit cases instead require exit 13 and the temporal-violation signature, labeled `LIMITATION_COUNTEREXAMPLE`. A zero runner exit for `--limits` means the expected limitations were reproduced, not that liveness passed.
A passing case requires exit 0, TLC's no-error completion message and an empty state queue. Counterexamples, timeouts and specification errors fail the runner.
## Reference positive results
## Reference results
| Config | Checked scope | Distinct states |
| --- | --- | ---: |
@@ -74,4 +71,4 @@ A positive result requires exit 0, TLC's no-error completion message and an empt
| `handoff-fullpage-active` | Pending newer turn; shared-page handoff and sole canonical actor | 80 |
| `handoff-fullpage-idle` | Idle shared-page handoff and sole canonical actor | 80 |
`--case requests-two` and `--case lifecycle-fullpage-two-chats` expose larger current-policy products, not additional claimed positive results. The separate `--limits` cases retain two real evidence boundaries: a failed needed read without a later recovery read, and a fragment omitting the needed completed ID without a later bridge/read. Neither condition guarantees eventual idle.
See [Attach reconciliation](ATTACH-RECONCILIATION.md#reproduce-and-evidence) for the `attach-reconciliation` config and its graph counts. The larger `requests-two` and `lifecycle-fullpage-two-chats` configurations are optional; they are not part of the reference run.
@@ -28,7 +28,7 @@ Cache publication and its synchronous owner callback are one model action; navig
| `handoff-fullpage-active` | `CacheHandoff.tla` | exit 0, no error, queue 0 | 80 |
| `handoff-fullpage-idle` | `CacheHandoff.tla` | exit 0, no error, queue 0 | 80 |
The dynamic case has one chat, two sequential server turns, two outages and two selection changes, starting unselected. Selected and actually mounted owners are separate: a scheduled refresh may remain pending until selection away. Mounted-history H and reconnect R capture/processing are separate. The workload includes pending/active metadata, stale generations, transcript admission choices and independent anonymous activity. Full pages contain all bounded persisted completion IDs. Read failures and fragments are excluded from this positive workload, not hidden by fairness or state constraints.
The dynamic case has one chat, two sequential server turns, two outages and two selection changes, starting unselected. Selected and actually mounted owners are separate: a scheduled refresh may remain pending until selection away. Mounted-history H and reconnect R capture/processing are separate. The workload includes pending/active metadata, stale generations, transcript admission choices and independent anonymous activity. This partition covers successful full pages that contain all bounded persisted completion IDs. [Attach reconciliation](ATTACH-RECONCILIATION.md) checks lifecycle convergence when history supplies no completion ID.
The config checks `TypeOK`, `NoOlderCompletionClearsNewer`, `PartialCompletionPreservesRecovery`, `LifecycleOnlyPreservesContentAndRecovery`, `ActiveUnmountedSnapshotIsNotAdopted`, `CachePrecedesIdleNotification`, `SoleCanonicalActor` and `ExplicitCompletionHandoffSettles`. It checks `RawExplicitCompletionsSettle` and `EventuallyIdle` in the same run. Raw learning includes every processed full-page ID even when cache admission fails: `learned ∩ open = {}`.
@@ -45,12 +45,6 @@ The handoff cases start at a source-reachable checkpoint: observed turn 1, lost
The maintained actual-hooks regression exercises the deferred-refresh boundary: a mounted reconnect full page completes 1 while 2 is still open; preflight rejects content adoption; selection away cancels the pending history refresh. Lifecycle observation closes only 1, preserving 2's owner/clock and uncovered content. Ending 2 can then leave idle without another refresh. This concrete regression and the model graph are separate forms of verification.
## Current-policy limits
`--limits` runs two cases separately from positive checks. Each must retain exit 13 and the temporal-property violation signature. Their runner status is `LIMITATION_COUNTEREXAMPLE`, not a passing liveness result; reached-state counts depend on concurrent search order.
- `lifecycle-failed-read-limit` allows needed reads to fail. A lost terminal plus failed recovery can leave an owner unresolved; fairness cannot manufacture a later retry.
- `lifecycle-fragment-id-limit` allows fragments with omitted completion IDs and no switches. Without an owner/bridge/future read, completion evidence may never arrive. This is not an assertion about a particular native Gateway payload.
- Larger current-policy two-chat products remain optional and are not claimed exhausted. Separate request/ledger/lifecycle graphs and other-chat sentinels are not a checked compositional liveness theorem.
The larger two-chat configuration remains optional. The separate request, ledger and lifecycle models do not establish a compositional liveness theorem.
H/R captures overapproximate independent producers; concrete request sharing/abort is a separate `SharedRequests` partition. Transcript fragment joining, token/auth/client replacement, backend execution, eviction, multiple tabs/hosts, send queues and unbounded workloads are outside this model. Logs, states, source snapshots and the jar stay outside the checkout.
+23 -44
View File
@@ -7,13 +7,13 @@ EXTENDS Naturals, FiniteSets, Sequences, TLC
\* Full pages contain all bounded persisted IDs; no fragment-gap bridging proof.
\* Effect setup starts history (useNanobotStream:551) before transcript subscribe
\* (:682 onward), so selected alone does not imply hasTranscript.
CONSTANTS NChats, NTurns, MaxOutages, MaxSwitches, AllowFailures, Fragments
CONSTANTS NChats, NTurns, MaxOutages, MaxSwitches
Chats == 1..NChats
Turns == 1..NTurns
Readers == {"H", "R"}
None == 0
EmptyRead == [phase |-> 0, generation |-> 0, turn |-> 0,
completed |-> {}, observed |-> {}, pending |-> FALSE, active |-> 0, fragment |-> FALSE]
completed |-> {}, observed |-> {}, pending |-> FALSE, active |-> 0]
EmptyLedger == [open |-> {}, closed |-> {}, fenced |-> {}, latest |-> 0,
clock |-> 0, generation |-> 0, anonymous |-> FALSE,
recoverySeen |-> FALSE, learned |-> {}]
@@ -91,26 +91,22 @@ Receive(c) ==
/\ reads' = IF ~ignored /\ m.kind = 2 THEN
[reads EXCEPT ![c] = [r \in Readers |-> IF reads[c][r].phase # 0
THEN [reads[c][r] EXCEPT !.phase = 1, !.completed = {},
!.observed = {}, !.pending = FALSE, !.active = 0, !.fragment = FALSE]
!.observed = {}, !.pending = FALSE, !.active = 0]
ELSE reads[c][r]]]
ELSE reads
/\ wire' = [wire EXCEPT ![c] = Tail(@)]
/\ UNCHANGED <<server, needHook, selected, mounted, switches, connected, outages, safe>>
Capture(c,r,fragment,completions,pending) ==
Capture(c,r,pending) ==
/\ UNCHANGED mounted
/\ reads[c][r].phase = 1
/\ fragment \in BOOLEAN /\ (fragment => Fragments)
/\ IF fragment THEN completions \subseteq Done(c) ELSE completions = Done(c)
/\ pending \in BOOLEAN /\ (pending => (Running(c) # {} \/ ledger[c].anonymous))
/\ reads' = [reads EXCEPT ![c][r].phase = 2, ![c][r].completed = completions,
/\ (pending => (Running(c) # {} \/ ledger[c].anonymous))
/\ reads' = [reads EXCEPT ![c][r].phase = 2, ![c][r].completed = Done(c),
![c][r].observed = Seen(c), ![c][r].pending = pending,
![c][r].active = IF Running(c) = {} THEN 0 ELSE CHOOSE t \in Running(c) : TRUE,
![c][r].fragment = fragment]
![c][r].active = IF Running(c) = {} THEN 0 ELSE CHOOSE t \in Running(c) : TRUE]
/\ UNCHANGED <<server, wire, ledger, needHook, selected, mounted, switches, connected, outages, safe>>
Process(c,r,accepted,exposed) ==
Process(c,r,accepted) ==
/\ UNCHANGED mounted
/\ reads[c][r].phase = 2 /\ (r = "R" => connected) /\ (r = "H" => mounted = c)
/\ accepted \in BOOLEAN /\ exposed \in BOOLEAN /\ (exposed => accepted)
/\ LET q == reads[c][r]
l == ledger[c]
completed == q.completed
@@ -118,32 +114,22 @@ Process(c,r,accepted,exposed) ==
(l.generation = q.generation \/ l.latest \in (completed \cup l.fenced))
explicit == q.turn # 0 /\ q.turn \in completed
idle == ~q.pending /\ q.active = 0
canCache == IF q.fragment THEN canApply ELSE
(explicit \/ idle) /\ (q.turn = 0 \/ explicit \/ q.turn \in q.observed) /\ canApply
canCache == (explicit \/ idle) /\ (q.turn = 0 \/ explicit \/ q.turn \in q.observed) /\ canApply
hasOwner == mounted = c
cacheInstall == r = "R" /\ canCache /\ hasOwner
fragmentReady == q.fragment /\ ((r = "H" /\ exposed) \/
(r = "R" /\ (~hasOwner \/ (cacheInstall /\ exposed))))
\* Transcript acceptance controls adoption, not exact full-page closure.
\* exposed is separate: a staged accepted fragment can expose no IDs.
\* Non-seed full-page owner handoff; no pending fragment gap here.
ownerWhole == ~q.fragment /\ (r = "H" \/ cacheInstall)
backgroundWhole == ~q.fragment /\ r = "R" /\ canCache /\ idle /\ ~hasOwner
ownerWhole == r = "H" \/ cacheInstall
backgroundWhole == r = "R" /\ canCache /\ idle /\ ~hasOwner
whole == ownerWhole \/ backgroundWhole
\* Preflight/cache publication above still use the BEFORE-settlement ledger.
\* A fresh, nonaborted full R page now supplies lifecycle evidence even
\* with a mounted owner or canCache=FALSE. It grants no content coverage.
lifecycle == fragmentReady \/ (r = "R" /\ ~q.fragment)
doSettle == whole \/ lifecycle
adopt == backgroundWhole \/ (ownerWhole /\ accepted /\ ~q.pending /\ canApply)
nextOpen == IF doSettle THEN l.open \ completed ELSE l.open
nextClock == IF adopt \/ (doSettle /\ l.latest \in completed) THEN 0 ELSE l.clock
\* Fresh full pages settle explicit IDs independently of content adoption.
nextOpen == l.open \ completed
nextClock == IF adopt \/ l.latest \in completed THEN 0 ELSE l.clock
nextAnon == IF adopt THEN FALSE ELSE l.anonymous
nl == [l EXCEPT !.open = nextOpen,
!.closed = IF doSettle THEN @ \cup completed ELSE @,
!.closed = @ \cup completed,
!.fenced = IF whole THEN @ \cup completed ELSE @,
!.clock = nextClock, !.anonymous = nextAnon,
!.learned = @ \cup (IF ~q.fragment \/ fragmentReady THEN completed ELSE {})]
!.learned = @ \cup completed]
IN /\ ledger' = [ledger EXCEPT ![c] = nl]
/\ reads' = [reads EXCEPT ![c][r] = EmptyRead,
![c]["H"] = IF cacheInstall \/ r = "H" THEN EmptyRead ELSE reads[c]["H"]]
@@ -151,18 +137,12 @@ Process(c,r,accepted,exposed) ==
!.collateral = @ /\ ((l.open \ completed) \subseteq nextOpen) /\
(l.latest # 0 /\ l.latest \notin completed /\ l.clock = l.latest => nextClock = l.clock),
!.partial = @ /\ (adopt \/ ~l.anonymous \/ nextAnon),
!.lifecycle = @ /\ (~(lifecycle /\ ~whole) \/
(nl.fenced = l.fenced /\ nextAnon = l.anonymous)),
!.activeAdoption = @ /\ (~(r = "R" /\ ~hasOwner /\ ~q.fragment /\ ~idle) \/ ~adopt),
!.lifecycle = @ /\ (whole \/ (nl.fenced = l.fenced /\ nextAnon = l.anonymous)),
!.activeAdoption = @ /\ (~(r = "R" /\ ~hasOwner /\ ~idle) \/ ~adopt),
!.cacheOrder = @ /\ (r # "R" \/ ~adopt \/ canCache),
!.handoff = @ /\ (~doSettle \/ completed \cap nextOpen = {}),
!.handoff = @ /\ (completed \cap nextOpen = {}),
!.soleActor = @ /\ ~(ownerWhole /\ backgroundWhole)]
/\ UNCHANGED <<server, wire, needHook, selected, mounted, switches, connected, outages>>
Fail(c,r) ==
/\ UNCHANGED mounted
/\ AllowFailures /\ reads[c][r].phase # 0
/\ reads' = [reads EXCEPT ![c][r] = EmptyRead]
/\ UNCHANGED <<server, wire, ledger, needHook, selected, mounted, switches, connected, outages, safe>>
BeginRecovery(c) ==
/\ UNCHANGED mounted
/\ connected /\ Running(c) # {} /\ ~ledger[c].anonymous /\ ~ledger[c].recoverySeen
@@ -175,14 +155,14 @@ EndRecovery(c) ==
(IF ledger[c].latest = 0 THEN {} ELSE {ledger[c].latest}),
![c].open = {}, ![c].clock = 0, ![c].latest = 0, ![c].anonymous = FALSE]
/\ UNCHANGED <<server, wire, reads, needHook, selected, mounted, switches, connected, outages, safe>>
CaptureAny(c,r) == \E f,p \in BOOLEAN, d \in SUBSET Turns : Capture(c,r,f,d,p)
ProcessAny(c,r) == \E a,e \in BOOLEAN : Process(c,r,a,e)
CaptureAny(c,r) == \E pending \in BOOLEAN : Capture(c,r,pending)
ProcessAny(c,r) == \E accepted \in BOOLEAN : Process(c,r,accepted)
Next ==
\/ \E c \in Chats, t \in Turns : Start(c,t) \/ Finish(c,t)
\/ Disconnect \/ Reconnect \/ HookEffect
\/ \E c \in Chats \cup {0} : Switch(c)
\/ \E c \in Chats : Receive(c) \/ BeginRecovery(c) \/ EndRecovery(c)
\/ \E c \in Chats, r \in Readers : CaptureAny(c,r) \/ ProcessAny(c,r) \/ Fail(c,r)
\/ \E c \in Chats, r \in Readers : CaptureAny(c,r) \/ ProcessAny(c,r)
Spec == Init /\ [][Next]_vars
FairSpec == Spec /\ WF_vars(Reconnect) /\ WF_vars(HookEffect) /\
(\A c \in Chats : WF_vars(Receive(c))) /\
@@ -196,8 +176,7 @@ TypeOK ==
/\ ledger[c].fenced \subseteq Turns /\ ledger[c].latest \in Turns \cup {0}
/\ ledger[c].clock \in Turns \cup {0}
/\ ledger[c].generation \in 0..(NTurns+MaxOutages)
\* Raw processed full-page IDs were already included in learned regardless of
\* cache eligibility. Keep that definition, not just successful handoff IDs.
\* Every processed full page contributes explicit IDs, even if cache admission fails.
RawExplicitCompletionsSettle == \A c \in Chats : ledger[c].learned \cap ledger[c].open = {}
ExplicitCompletionsSettle == RawExplicitCompletionsSettle
NoOlderCompletionClearsNewer == safe.collateral
@@ -0,0 +1,5 @@
SPECIFICATION FairSpec
CONSTANT MaxLosses = 2
INVARIANTS TypeOK LifecycleSafety
PROPERTY EventuallyRetiredOwnersSettle
CHECK_DEADLOCK FALSE
@@ -1,19 +0,0 @@
CONSTANTS
NChats = 1
NTurns = 2
MaxOutages = 2
MaxSwitches = 2
AllowFailures = TRUE
Fragments = FALSE
SPECIFICATION FairSpec
CHECK_DEADLOCK FALSE
INVARIANTS
TypeOK
NoOlderCompletionClearsNewer
PartialCompletionPreservesRecovery
LifecycleOnlyPreservesContentAndRecovery
ActiveUnmountedSnapshotIsNotAdopted
CachePrecedesIdleNotification
SoleCanonicalActor
ExplicitCompletionHandoffSettles
PROPERTY EventuallyIdle
@@ -1,20 +0,0 @@
CONSTANTS
NChats = 1
NTurns = 2
MaxOutages = 2
MaxSwitches = 0
AllowFailures = FALSE
Fragments = TRUE
SPECIFICATION FairSpec
CHECK_DEADLOCK FALSE
INVARIANTS
TypeOK
NoOlderCompletionClearsNewer
PartialCompletionPreservesRecovery
LifecycleOnlyPreservesContentAndRecovery
ActiveUnmountedSnapshotIsNotAdopted
CachePrecedesIdleNotification
SoleCanonicalActor
ExplicitCompletionHandoffSettles
PROPERTY EventuallyIdle
@@ -3,8 +3,6 @@ CONSTANTS
NTurns = 2
MaxOutages = 2
MaxSwitches = 2
AllowFailures = FALSE
Fragments = FALSE
SPECIFICATION FairSpec
CHECK_DEADLOCK FALSE
INVARIANTS
@@ -3,8 +3,6 @@ CONSTANTS
NTurns = 2
MaxOutages = 2
MaxSwitches = 2
AllowFailures = FALSE
Fragments = FALSE
SPECIFICATION FairSpec
CHECK_DEADLOCK FALSE
INVARIANTS
+30 -38
View File
@@ -1,24 +1,20 @@
#!/usr/bin/env python3
"""Check bounded current-policy models without writing generated files into the checkout."""
"""Check bounded turn-sync models without writing generated files into the checkout."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import time
from pathlib import Path
SOURCE = Path(__file__).resolve().parent
EXPECTED_LIMITS = {
"lifecycle-failed-read-limit": (13, "Temporal properties were violated"),
"lifecycle-fragment-id-limit": (13, "Temporal properties were violated"),
}
ATTACH_CASE = "attach-reconciliation"
REVISED_CASES = (
"revised-mounted", "revised-unmounted",
"revised-mounted-fragments", "revised-unmounted-fragments",
@@ -30,16 +26,16 @@ USAGE_CASES = (
)
# Larger products are reproducible explicitly, not claimed exhausted by defaults.
OPTIONAL_CASES = ("requests-two", "lifecycle-fullpage-two-chats")
LIMIT_CASES = tuple(EXPECTED_LIMITS)
CASES = REVISED_CASES + USAGE_CASES + OPTIONAL_CASES + LIMIT_CASES
DEFAULT_CASES = REVISED_CASES + USAGE_CASES + (ATTACH_CASE,)
CASES = DEFAULT_CASES + OPTIONAL_CASES
MODULES = {
**{case: "RevisedTurnSync.tla" for case in REVISED_CASES},
**{case: "SharedRequests.tla" for case in ("requests-one", "requests-two-no-invalidations", "requests-two")},
"authority": "CompletionAuthority.tla",
**{case: "CacheHandoff.tla" for case in ("handoff-fullpage-active", "handoff-fullpage-idle")},
**{case: "UsageLifecycle.tla" for case in (
"lifecycle-fullpage-dynamic", "lifecycle-fullpage-two-chats", *LIMIT_CASES,
)},
"lifecycle-fullpage-dynamic": "UsageLifecycle.tla",
"lifecycle-fullpage-two-chats": "UsageLifecycle.tla",
ATTACH_CASE: "AttachReconciliation.tla",
}
COUNTS = re.compile(
r"([\d,]+) states generated, ([\d,]+) distinct states found, ([\d,]+) states left on queue"
@@ -49,7 +45,10 @@ IMPLEMENTATION_FILES = (
"webui/src/lib/client-run-ledger.ts", "webui/src/lib/nanobot-client.ts",
"webui/src/lib/canonical-run-snapshot.ts", "webui/src/lib/latest-thread-request.ts",
"webui/src/lib/thread-transcript.ts", "webui/src/lib/webui-thread-cache.ts",
"webui/src/components/thread/ThreadShell.tsx",
"webui/src/components/thread/ThreadShell.tsx", "webui/src/lib/types.ts",
"nanobot/session/webui_turns.py", "nanobot/webui/inbound_commands.py",
"nanobot/webui/session_projection.py", "nanobot/webui/outbound_delivery.py",
"nanobot/webui/ws_http.py", "nanobot/channels/websocket/runtime.py",
)
@@ -61,10 +60,8 @@ def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--jar", required=True, type=Path, help="External official tla2tools.jar; never copied")
parser.add_argument("--output-root", type=Path, help="New task-owned directory outside this checkout")
parser.add_argument("--implementation-root", type=Path, help="Optional read-only TypeScript provenance; not mechanical verification")
selection = parser.add_mutually_exclusive_group()
selection.add_argument("--case", action="append", choices=CASES, dest="cases", help="Repeat to select cases")
selection.add_argument("--limits", action="store_true", help="Run ONLY current-policy missing-evidence counterexamples, not positive checks")
parser.add_argument("--implementation-root", type=Path, help="Optional read-only implementation provenance; not mechanical verification")
parser.add_argument("--case", action="append", choices=CASES, dest="cases", help="Repeat to select cases")
parser.add_argument("--java", default="java")
parser.add_argument("--workers", type=int, default=2)
parser.add_argument("--heap-mb", type=int, default=1536)
@@ -83,7 +80,7 @@ def main() -> int:
output.mkdir(parents=True, exist_ok=False)
inputs = sorted((*SOURCE.glob("*.tla"), *SOURCE.glob("*.cfg")))
manifest = {
"scope": "finite fixed-mount, dynamic lifecycle, shared-request and completion partitions; not a checked TypeScript/compositional/all-system proof",
"scope": "finite history, request, completion and attach partitions; not a checked implementation/compositional proof",
"jar": {"path": str(jar), "sha256": sha256(jar)},
"source_sha256": {path.name: sha256(path) for path in inputs},
"results": [],
@@ -93,11 +90,11 @@ def main() -> int:
manifest["implementation_snapshot"] = {
"root": str(implementation),
"sha256": {name: sha256(implementation / name) for name in IMPLEMENTATION_FILES},
"note": "Read-only provenance, not a checked refinement of TypeScript",
"note": "Read-only provenance, not a checked refinement of implementation code",
}
print(f"Evidence: {output}", flush=True)
unexpected = 0
selected = args.cases or (LIMIT_CASES if args.limits else REVISED_CASES + USAGE_CASES)
failed = 0
selected = args.cases or DEFAULT_CASES
for case in selected:
case_dir = output / case
case_dir.mkdir()
@@ -113,7 +110,6 @@ def main() -> int:
"tlc2.TLC", "-workers", str(args.workers), "-config", f"{case}.cfg",
"-metadir", str(case_dir / "states"), module,
]
expected_exit, required_error = EXPECTED_LIMITS.get(case, (0, None))
started = time.monotonic()
timed_out = False
try:
@@ -133,19 +129,16 @@ def main() -> int:
(case_dir / "tlc.log").write_text(text, encoding="utf-8")
matches = list(COUNTS.finditer(text))
counts = tuple(int(value.replace(",", "")) for value in matches[-1].groups()) if matches else None
matched = not timed_out and actual_exit == expected_exit
if required_error:
matched = matched and required_error in text
else:
matched = (matched and "Model checking completed. No error has been found." in text
and counts is not None and counts[2] == 0)
status = ("LIMITATION_COUNTEREXAMPLE" if required_error else "EXHAUSTED_NO_COUNTEREXAMPLE") if matched else "UNEXPECTED_RESULT"
unexpected += not matched
exhausted = (
actual_exit == 0 and "Model checking completed. No error has been found." in text
and counts is not None and counts[2] == 0
)
status = "EXHAUSTED_NO_COUNTEREXAMPLE" if exhausted else "UNEXPECTED_RESULT"
result = {
"case": case, "status": status,
"category": ("missing-evidence-limit" if case in LIMIT_CASES else
"category": ("attach-model" if case == ATTACH_CASE else
"expanded-usage-model" if case in USAGE_CASES + OPTIONAL_CASES else "fixed-mount-model"),
"expected_exit": expected_exit, "actual_exit": actual_exit, "required_error": required_error,
"actual_exit": actual_exit,
"timed_out": timed_out, "seconds": round(time.monotonic() - started, 3),
"generated": counts[0] if counts else None, "distinct": counts[1] if counts else None,
"left_on_queue": counts[2] if counts else None,
@@ -153,13 +146,12 @@ def main() -> int:
}
manifest["results"].append(result)
(output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
print(f"{case}: {status}; exit={actual_exit}, expected={expected_exit}; distinct={result['distinct']}", flush=True)
if not matched:
print(f"{case}: {status}; exit={actual_exit}; distinct={result['distinct']}", flush=True)
if not exhausted:
failed += 1
print(text[-5000:], flush=True)
positive_count = sum(result["status"] == "EXHAUSTED_NO_COUNTEREXAMPLE" for result in manifest["results"])
limit_count = sum(result["status"] == "LIMITATION_COUNTEREXAMPLE" for result in manifest["results"])
print(f"Positive exhausted checks: {positive_count}; missing-evidence counterexamples: {limit_count}; unexpected: {unexpected}")
return 1 if unexpected else 0
print(f"Exhausted checks: {len(selected) - failed}; failed: {failed}")
return 1 if failed else 0
if __name__ == "__main__":