fix(webui): settle completed turns across reconnect paths
Separate named completion facts from history adoption, preserve newer and anonymous activity, and keep one mounted whole-snapshot adopter. Unify explicit-ID lifecycle/content closure without discarding uncovered content. Cover the real client/hooks reconnect and selection races, await asynchronous browser fixture startup, and retain current-policy bounded TLC models and missing-evidence limits. Archive historical/candidate verification separately.
This commit is contained in:
1 parent
9e499ad539
commit
53a556585e
34 files changed
+1891
-46
No files matched your search
@@ -35,6 +35,8 @@ async function openThread(page: Page, events: ThreadProjectionEvent[] = [], loca
|
||||
});
|
||||
});
|
||||
await page.goto(`/browser/fixture.html?case=answer-order${reconnect ? "&reconnect=1" : ""}`);
|
||||
// The load event does not await the fixture module's asynchronous startup.
|
||||
await page.evaluate(async (entry) => { await import(entry); }, "/browser/fixture.tsx");
|
||||
await expect.poll(() => attached.has(chatId)).toBe(true);
|
||||
await expect(page.getByRole("status", { name: "Loading conversation…" })).toHaveCount(0);
|
||||
return {
|
||||
|
||||
@@ -544,7 +544,7 @@ export function useNanobotStream(
|
||||
}, [chatId, client]);
|
||||
const settleFragment = useCallback((owner: ThreadTranscript) => {
|
||||
if (!chatId || !owner.fragmentCompletedTurnIds.length) return;
|
||||
client.settleFragmentRunLifecycle(chatId, owner.fragmentCompletedTurnIds);
|
||||
client.settleCompletedRunLifecycle(chatId, owner.fragmentCompletedTurnIds);
|
||||
if (!client.getRunState(chatId)?.active) setRetryStatus(null);
|
||||
}, [chatId, client]);
|
||||
|
||||
@@ -575,7 +575,9 @@ export function useNanobotStream(
|
||||
if (chatId && canonical && (ownRead || !seed)) {
|
||||
if (body?.page?.record_range) {
|
||||
if (accepted) settleFragment(owner);
|
||||
} else if (ownRead && !owner.hasPendingFragmentGap) {
|
||||
} else if (!owner.hasPendingFragmentGap) {
|
||||
// A published reconnect page supersedes this owner's shared read.
|
||||
// The owner must reconcile its completion facts after that handoff too.
|
||||
reconcileCanonical(generation, canonical, accepted);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,26 +29,32 @@ export function useReconnectRuns(client: NanobotClient, getToken: () => string):
|
||||
const body = await fetchLatestWebuiThread(client, getToken(), key, signal);
|
||||
if (!body || signal.aborted) return;
|
||||
const { completedTurnIds, snapshot } = persistedCanonicalRunState(body);
|
||||
const mounted = client.hasTranscript(chatId);
|
||||
if (body.page?.record_range) {
|
||||
if (!Array.isArray(body.completed_turn_ids)) return;
|
||||
const mounted = client.hasTranscript(chatId);
|
||||
if (client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)) {
|
||||
webuiThreadCache.set(key, body);
|
||||
}
|
||||
// A mounted owner must accept (or stage) the fragment before settling.
|
||||
// Explicit completion is otherwise independent of a newer run, but the
|
||||
// fragment is not proof that its WS content is covered.
|
||||
if (!mounted) client.settleFragmentRunLifecycle(chatId, completedTurnIds);
|
||||
if (!mounted) client.settleCompletedRunLifecycle(chatId, completedTurnIds);
|
||||
return;
|
||||
}
|
||||
const explicitlyCompleted = turnId !== null && completedTurnIds.includes(turnId);
|
||||
if (!explicitlyCompleted && (snapshot.hasPendingToolCalls || snapshot.activeTurnId)) return;
|
||||
if (turnId && !explicitlyCompleted && !snapshot.observedTurnIds.includes(turnId)) return;
|
||||
if (!client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)) return;
|
||||
// Preserve the result before completion fences prune queued fragments.
|
||||
// Returning to an inactive chat can hydrate from this canonical page.
|
||||
webuiThreadCache.set(key, body);
|
||||
client.reconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot);
|
||||
const canCache = (explicitlyCompleted || (!snapshot.hasPendingToolCalls && !snapshot.activeTurnId))
|
||||
&& (!turnId || explicitlyCompleted || snapshot.observedTurnIds.includes(turnId))
|
||||
&& client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot);
|
||||
// Preserve adoptable history before notifying completion subscribers.
|
||||
if (canCache) webuiThreadCache.set(key, body);
|
||||
// Full-page completion facts belong to the ledger regardless of whether
|
||||
// a transcript can adopt this page. Retain content for its later owner.
|
||||
client.settleCompletedRunLifecycle(chatId, completedTurnIds);
|
||||
// Mounted owners alone adopt whole snapshots. Only an idle snapshot can
|
||||
// settle activity without a named identity.
|
||||
if (!mounted && canCache && !snapshot.hasPendingToolCalls && !snapshot.activeTurnId) {
|
||||
client.reconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot);
|
||||
}
|
||||
};
|
||||
let nextJob = 0;
|
||||
const worker = async () => {
|
||||
|
||||
@@ -58,7 +58,7 @@ type Command =
|
||||
| ({ kind: "written" | "reject" } & TurnRef)
|
||||
| { kind: "transport-lost" }
|
||||
| { kind: "local-stop" | "forget"; chatId: string }
|
||||
| { kind: "fence" | "settle-fragment-lifecycle"; chatId: string; completedTurnIds: readonly string[] }
|
||||
| { kind: "fence" | "settle-completed-lifecycle"; chatId: string; completedTurnIds: readonly string[] }
|
||||
| { kind: "restore-pending"; chatId: string; generation: number; turnId: string | null };
|
||||
|
||||
export type RunEffect =
|
||||
@@ -208,10 +208,9 @@ export class ClientRunLedger {
|
||||
break;
|
||||
}
|
||||
case "fence":
|
||||
this.fence(command.chatId, command.completedTurnIds, effects);
|
||||
break;
|
||||
case "settle-fragment-lifecycle":
|
||||
this.settleFragmentLifecycle(command.chatId, command.completedTurnIds, effects);
|
||||
case "settle-completed-lifecycle":
|
||||
this.completeTurns(command.chatId, command.completedTurnIds,
|
||||
command.kind === "fence" ? "content" : "lifecycle", effects);
|
||||
break;
|
||||
default: {
|
||||
const unhandled: never = command;
|
||||
@@ -348,7 +347,7 @@ export class ClientRunLedger {
|
||||
private applyCanonicalSnapshot(request: CanonicalRequest): { accepted: boolean; effects: readonly RunEffect[] } {
|
||||
const { chatId, snapshot } = request;
|
||||
const effects: RunEffect[] = [];
|
||||
this.fence(chatId, request.completedTurnIds, effects);
|
||||
this.completeTurns(chatId, request.completedTurnIds, "content", effects);
|
||||
if (!this.canApplyCanonical({ ...request, completedTurnIds: [] })) return { accepted: false, effects };
|
||||
|
||||
const chat = this.chats.get(chatId);
|
||||
@@ -466,34 +465,23 @@ export class ClientRunLedger {
|
||||
this.trimTerminalSet(chat.closed, chat.latestTurnId);
|
||||
}
|
||||
|
||||
private settleFragmentLifecycle(chatId: string, turnIds: readonly string[], effects: RunEffect[]): void {
|
||||
for (const turnId of turnIds) {
|
||||
if (!turnId) continue;
|
||||
const chat = this.ensureChat(chatId);
|
||||
this.rememberClosed(chat, turnId);
|
||||
this.settle(chatId, turnId, effects);
|
||||
if (chat.latestTurnId === turnId) {
|
||||
chat.anonymousActive = false;
|
||||
chat.effectiveStartedAt = null;
|
||||
}
|
||||
}
|
||||
effects.push({ kind: "prune-lifecycle-inbound", chatId, turnIds });
|
||||
}
|
||||
|
||||
private fence(chatId: string, turnIds: readonly string[], effects: RunEffect[]): void {
|
||||
private completeTurns(
|
||||
chatId: string, turnIds: readonly string[], coverage: "lifecycle" | "content", effects: RunEffect[],
|
||||
): void {
|
||||
let chat = this.chats.get(chatId);
|
||||
for (const turnId of turnIds) {
|
||||
if (!turnId) continue;
|
||||
chat ??= this.ensureChat(chatId);
|
||||
chat.fenced.add(turnId);
|
||||
// Explicit completion settles ownership even when the full page cannot be adopted.
|
||||
this.rememberClosed(chat, turnId);
|
||||
this.settle(chatId, turnId, effects);
|
||||
// Anonymous recovery activity is independent of this named turn.
|
||||
// Named completion never clears a different owner or anonymous recovery.
|
||||
if (chat.latestTurnId === turnId) chat.effectiveStartedAt = null;
|
||||
if (coverage === "content") chat.fenced.add(turnId);
|
||||
}
|
||||
if (chat) this.trimTerminalSet(chat.fenced);
|
||||
effects.push({ kind: "prune-inbound", chatId, turnIds: Array.from(chat?.fenced ?? []) });
|
||||
if (coverage === "content") {
|
||||
if (chat) this.trimTerminalSet(chat.fenced);
|
||||
effects.push({ kind: "prune-inbound", chatId, turnIds: Array.from(chat?.fenced ?? []) });
|
||||
} else effects.push({ kind: "prune-lifecycle-inbound", chatId, turnIds });
|
||||
}
|
||||
|
||||
private trimTerminalSet(turnIds: Set<string>, retainedTurnId?: string | null): void {
|
||||
|
||||
@@ -439,9 +439,9 @@ export class NanobotClient {
|
||||
this.applyRunEffects(this.runs.transition({ kind: "fence", chatId, completedTurnIds }));
|
||||
}
|
||||
|
||||
/** Settle explicit fragment completions without claiming coverage of live content. */
|
||||
settleFragmentRunLifecycle(chatId: string, completedTurnIds: readonly string[]): void {
|
||||
this.applyRunEffects(this.runs.transition({ kind: "settle-fragment-lifecycle", chatId, completedTurnIds }));
|
||||
/** Settle explicit completions without claiming coverage of live content. */
|
||||
settleCompletedRunLifecycle(chatId: string, completedTurnIds: readonly string[]): void {
|
||||
this.applyRunEffects(this.runs.transition({ kind: "settle-completed-lifecycle", chatId, completedTurnIds }));
|
||||
}
|
||||
|
||||
/** Whether a mounted transcript owns delivery for this chat. */
|
||||
|
||||
@@ -391,7 +391,7 @@ describe("NanobotClient", () => {
|
||||
socket.fakeOpen();
|
||||
socket.fakeMessage({ event: "recovery_state", chat_id: "chat", status: "resuming", recovery_id: "r1", attempts: 1 });
|
||||
socket.fakeMessage({ event: "goal_status", chat_id: "chat", turn_id: "recovery:r1", status: "running", started_at: 100 });
|
||||
client.settleFragmentRunLifecycle("chat", ["recovery:r1"]);
|
||||
client.settleCompletedRunLifecycle("chat", ["recovery:r1"]);
|
||||
socket.fakeMessage({ event: "attached", chat_id: "chat", recovery_state: {
|
||||
status: "awaiting_user", recovery_id: "r1", reason: "loop_guard", attempts: 1,
|
||||
} });
|
||||
@@ -2101,9 +2101,9 @@ describe("NanobotClient", () => {
|
||||
const oldContent = { event: "message", chat_id: "chat", turn_id: "history-0", text: "Unconsumed older content" };
|
||||
socket.fakeMessage(buffered);
|
||||
socket.fakeMessage(oldContent);
|
||||
client.settleFragmentRunLifecycle("chat", ["current"]);
|
||||
client.settleCompletedRunLifecycle("chat", ["current"]);
|
||||
const history = Array.from({ length: 300 }, (_, index) => `history-${index}`);
|
||||
client.settleFragmentRunLifecycle("chat", history);
|
||||
client.settleCompletedRunLifecycle("chat", history);
|
||||
|
||||
expect(history.filter((id) => client.isRunCompleted("chat", id))).toHaveLength(255);
|
||||
expect(client.isRunCompleted("chat", "history-0")).toBe(false);
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { useNanobotStream } from "@/hooks/useNanobotStream";
|
||||
import { useReconnectRuns } from "@/hooks/useReconnectRuns";
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||
import type { WebuiThreadPersistedPayload } from "@/lib/types";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
|
||||
class Socket {
|
||||
readyState = 0;
|
||||
onopen: (() => void) | null = null;
|
||||
onmessage: ((event: MessageEvent) => void) | null = null;
|
||||
onclose: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
send() {}
|
||||
open() { this.readyState = 1; this.onopen?.(); }
|
||||
close() { this.readyState = 3; this.onclose?.(); }
|
||||
receive(payload: unknown) { this.onmessage?.({ data: JSON.stringify(payload) } as MessageEvent); }
|
||||
}
|
||||
|
||||
interface Read {
|
||||
chat: string;
|
||||
signal: AbortSignal;
|
||||
resolve: (body: WebuiThreadPersistedPayload) => void;
|
||||
fail: (status: number) => void;
|
||||
}
|
||||
|
||||
function history(chat: string, completed: string[], active: string | null = null): WebuiThreadPersistedPayload {
|
||||
return {
|
||||
schemaVersion: 3, sessionKey: `websocket:${chat}`, projection: "events",
|
||||
completed_turn_ids: completed, has_pending_tool_calls: active !== null, active_turn_id: active,
|
||||
page: { history_generation: "real-use", before_cursor: null, has_more_before: false },
|
||||
events: [
|
||||
...completed.flatMap((turn) => [
|
||||
{ event: "user_message" as const, chat_id: chat, turn_id: turn, turn_seq: 1,
|
||||
projection_id: `${chat}-${turn}-question`, text: `${chat} question ${turn}`, starts_turn: true },
|
||||
{ event: "message" as const, chat_id: chat, turn_id: turn, turn_seq: 2,
|
||||
projection_id: `${chat}-${turn}-answer`, text: `${chat} answer ${turn}` },
|
||||
{ event: "turn_end" as const, chat_id: chat, turn_id: turn, turn_seq: 3,
|
||||
projection_id: `${chat}-${turn}-end` },
|
||||
]),
|
||||
...(active ? [{ event: "user_message" as const, chat_id: chat, turn_id: active, turn_seq: 1,
|
||||
projection_id: `${chat}-${active}-question`, text: `${chat} question ${active}`, starts_turn: true }] : []),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function harness() {
|
||||
const reads: Read[] = [];
|
||||
vi.stubGlobal("fetch", vi.fn((url: string, init: RequestInit) => {
|
||||
if (!String(url).includes("/webui-thread")) return Promise.resolve(new Response("{}", { status: 404 }));
|
||||
const key = decodeURIComponent(new URL(String(url), "http://test").pathname.split("/")[3]);
|
||||
return new Promise<Response>((resolve) => {
|
||||
reads.push({ chat: key.slice("websocket:".length), signal: init.signal as AbortSignal,
|
||||
// Deliberately allow delivery after cancellation: the consumer must reject it.
|
||||
resolve: (body) => resolve(new Response(JSON.stringify(body), { status: 200 })),
|
||||
fail: (status) => resolve(new Response("Synthetic failure", { status })) });
|
||||
});
|
||||
}));
|
||||
const sockets: Socket[] = [];
|
||||
const client = new NanobotClient({ url: "ws://test", reconnect: true, maxBackoffMs: 10,
|
||||
socketFactory: () => { const socket = new Socket(); sockets.push(socket); return socket as unknown as WebSocket; } });
|
||||
client.connect();
|
||||
sockets[0].open();
|
||||
const token = () => "synthetic-token";
|
||||
const recovery = renderHook(() => useReconnectRuns(client, token));
|
||||
const socket = () => sockets.at(-1)!;
|
||||
const running = (chat: string, turn: string, startedAt: number) => socket().receive({
|
||||
event: "goal_status", chat_id: chat, turn_id: turn, status: "running", started_at: startedAt,
|
||||
});
|
||||
const reopen = async () => {
|
||||
act(() => socket().close());
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10); });
|
||||
await act(async () => { socket().open(); });
|
||||
};
|
||||
const cache = new ThreadMessageCache(() => false);
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<ClientProvider client={client} token="synthetic-token">{children}</ClientProvider>
|
||||
);
|
||||
const mount = (initialChat: string) => renderHook(({ chat }) => {
|
||||
const stream = useNanobotStream(chat, [], false, undefined, undefined, [], { key: `websocket:${chat}`, cache });
|
||||
useEffect(() => {
|
||||
let refreshOnNextOpen = client.status !== "open";
|
||||
return client.onStatus((status) => {
|
||||
if (status !== "open") refreshOnNextOpen = true;
|
||||
else { if (refreshOnNextOpen) stream.refreshHistory(); refreshOnNextOpen = false; }
|
||||
});
|
||||
}, [stream.refreshHistory]);
|
||||
return stream;
|
||||
}, { wrapper, initialProps: { chat: initialChat } });
|
||||
return { client, reads, socket, running, reopen, mount,
|
||||
close: () => { recovery.unmount(); client.close(); } };
|
||||
}
|
||||
|
||||
beforeEach(() => { vi.useFakeTimers(); webuiThreadCache.clear(); });
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); webuiThreadCache.clear(); });
|
||||
|
||||
describe("reconnect across chat selection and transport generations", () => {
|
||||
it("gives a mounted owner sole responsibility for a shared completed page", async () => {
|
||||
const h = harness();
|
||||
act(() => h.running("alpha", "turn-1", 100));
|
||||
const selected = h.mount("alpha");
|
||||
await act(async () => { h.reads[0].resolve(history("alpha", [], "turn-1")); });
|
||||
const reconcile = vi.spyOn(h.client, "reconcileCanonicalCompletion");
|
||||
await h.reopen();
|
||||
await act(async () => { h.reads.at(-1)!.resolve(history("alpha", ["turn-1"])); });
|
||||
expect(reconcile).toHaveBeenCalledTimes(1);
|
||||
expect(selected.result.current.messages.map((message) => message.content)).toContain("alpha answer turn-1");
|
||||
expect(selected.result.current.isStreaming).toBe(false);
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
selected.unmount();
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("settles a mounted old turn when shared reconnect history precedes the newer running frame", async () => {
|
||||
const h = harness();
|
||||
act(() => h.running("alpha", "turn-1", 100));
|
||||
const selected = h.mount("alpha");
|
||||
await act(async () => { h.reads[0].resolve(history("alpha", [], "turn-1")); });
|
||||
await h.reopen();
|
||||
const read = h.reads.at(-1)!;
|
||||
expect(read.signal.aborted).toBe(false);
|
||||
await act(async () => { read.resolve(history("alpha", ["turn-1"], "turn-2")); });
|
||||
const completedFirst = h.client.isRunCompleted("alpha", "turn-1");
|
||||
act(() => {
|
||||
h.running("alpha", "turn-2", 200);
|
||||
h.socket().receive({ event: "message", chat_id: "alpha", turn_id: "turn-2", text: "alpha live answer" });
|
||||
h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "turn-2" });
|
||||
});
|
||||
const observed = { completedFirst, state: h.client.getRunState("alpha"),
|
||||
streaming: selected.result.current.isStreaming,
|
||||
contents: selected.result.current.messages.map((message) => message.content) };
|
||||
selected.unmount();
|
||||
h.close();
|
||||
expect(observed).toMatchObject({ completedFirst: true,
|
||||
state: { active: false, unsettled: false, latestTurnId: "turn-2" }, streaming: false,
|
||||
contents: expect.arrayContaining(["alpha answer turn-1", "alpha live answer"]) });
|
||||
});
|
||||
|
||||
it.each(["before", "after"] as const)("keeps two chats isolated when obsolete responses arrive %s current recovery across two outages", async (obsoleteTiming) => {
|
||||
const h = harness();
|
||||
// Turn IDs are deliberately reused across chats; ownership is a chat/turn pair.
|
||||
act(() => { h.running("alpha", "turn-1", 100); h.running("beta", "turn-1", 101); });
|
||||
const selected = h.mount("alpha");
|
||||
await act(async () => { h.reads[0].resolve(history("alpha", [], "turn-1")); });
|
||||
await h.reopen();
|
||||
const firstRecovery = h.reads.slice(1);
|
||||
expect(firstRecovery.map((read) => read.chat).sort()).toEqual(["alpha", "beta"]);
|
||||
selected.rerender({ chat: "beta" });
|
||||
expect(h.client.hasTranscript("alpha")).toBe(false);
|
||||
expect(h.client.hasTranscript("beta")).toBe(true);
|
||||
act(() => { h.running("alpha", "turn-2", 200); h.running("beta", "turn-2", 201); });
|
||||
// Cancel the whole first recovery batch before either old page returns.
|
||||
await h.reopen();
|
||||
expect(firstRecovery.every((read) => read.signal.aborted)).toBe(true);
|
||||
const secondRecovery = h.reads.slice(3);
|
||||
expect(secondRecovery.map((read) => read.chat).sort()).toEqual(["alpha", "beta"]);
|
||||
const beforeStale = [h.client.getRunState("alpha"), h.client.getRunState("beta")];
|
||||
const deliverObsolete = async () => {
|
||||
const states = [h.client.getRunState("alpha"), h.client.getRunState("beta")];
|
||||
const cached = [webuiThreadCache.get("websocket:alpha"), webuiThreadCache.get("websocket:beta")];
|
||||
await act(async () => { for (const read of firstRecovery) read.resolve(history(read.chat, ["turn-1"])); });
|
||||
expect([h.client.getRunState("alpha"), h.client.getRunState("beta")]).toEqual(states);
|
||||
expect([webuiThreadCache.get("websocket:alpha"), webuiThreadCache.get("websocket:beta")]).toEqual(cached);
|
||||
};
|
||||
if (obsoleteTiming === "before") await deliverObsolete();
|
||||
// Unmount beta while its shared current read survives in background recovery.
|
||||
selected.rerender({ chat: "alpha" });
|
||||
const secondAlpha = secondRecovery.find((read) => read.chat === "alpha")!;
|
||||
const secondBeta = secondRecovery.find((read) => read.chat === "beta")!;
|
||||
await act(async () => { secondBeta.resolve(history("beta", ["turn-1"], "turn-2")); });
|
||||
expect(h.client.isRunCompleted("beta", "turn-1")).toBe(true);
|
||||
expect(h.client.getRunState("alpha")).toEqual(beforeStale[0]);
|
||||
const betaBeforeAlpha = h.client.getRunState("beta");
|
||||
await act(async () => { secondAlpha.resolve(history("alpha", ["turn-1"], "turn-2")); });
|
||||
expect(h.client.isRunCompleted("alpha", "turn-1")).toBe(true);
|
||||
expect(h.client.getRunState("beta")).toEqual(betaBeforeAlpha);
|
||||
if (obsoleteTiming === "after") await deliverObsolete();
|
||||
for (const chat of ["alpha", "beta"]) expect(h.client.getRunState(chat)).toMatchObject({ active: true, latestTurnId: "turn-2" });
|
||||
act(() => {
|
||||
for (const chat of ["alpha", "beta"]) {
|
||||
h.socket().receive({ event: "message", chat_id: chat, turn_id: "turn-2", turn_seq: 2,
|
||||
projection_id: `${chat}-turn-2-answer`, text: `${chat} answer turn-2` });
|
||||
h.socket().receive({ event: "turn_end", chat_id: chat, turn_id: "turn-2", turn_seq: 3 });
|
||||
}
|
||||
});
|
||||
for (const chat of ["alpha", "beta"]) expect(h.client.getRunState(chat)).toMatchObject({ active: false, unsettled: false });
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
expect(selected.result.current.messages.map((message) => message.content)).toEqual(expect.arrayContaining([
|
||||
"alpha answer turn-1", "alpha answer turn-2",
|
||||
]));
|
||||
expect(selected.result.current.messages.every((message) => !message.content.includes("beta"))).toBe(true);
|
||||
// A third alpha turn starts while the user returns to the now-idle beta.
|
||||
act(() => h.running("alpha", "turn-3", 300));
|
||||
const alphaThird = h.client.getRunState("alpha");
|
||||
selected.rerender({ chat: "beta" });
|
||||
await act(async () => { h.reads.at(-1)!.resolve(history("beta", ["turn-1", "turn-2"])); });
|
||||
expect(h.client.getRunState("alpha")).toEqual(alphaThird);
|
||||
expect(selected.result.current.messages.map((message) => message.content)).toEqual(expect.arrayContaining([
|
||||
"beta answer turn-1", "beta answer turn-2",
|
||||
]));
|
||||
expect(selected.result.current.messages.every((message) => !message.content.includes("alpha"))).toBe(true);
|
||||
expect(selected.result.current.isStreaming).toBe(false);
|
||||
act(() => {
|
||||
h.socket().receive({ event: "message", chat_id: "alpha", turn_id: "turn-3", text: "alpha answer turn-3" });
|
||||
h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "turn-3" });
|
||||
});
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
expect(selected.result.current.messages.every((message) => !message.content.includes("alpha"))).toBe(true);
|
||||
selected.unmount();
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("preserves anonymous recovery through a mounted full-page cache handoff", async () => {
|
||||
const h = harness();
|
||||
act(() => h.running("alpha", "turn-1", 100));
|
||||
const selected = h.mount("alpha");
|
||||
await act(async () => { h.reads[0].resolve(history("alpha", [], "turn-1")); });
|
||||
act(() => h.socket().receive({ event: "recovery_state", chat_id: "alpha", status: "resuming",
|
||||
recovery_id: "independent", attempts: 1 }));
|
||||
await h.reopen();
|
||||
const body = { ...history("alpha", ["turn-1"]), has_pending_tool_calls: true };
|
||||
await act(async () => { h.reads.at(-1)!.resolve(body); });
|
||||
expect(h.client.isRunCompleted("alpha", "turn-1")).toBe(true);
|
||||
expect(h.client.getRunState("alpha")).toMatchObject({ active: true, unsettled: false, startedAt: null });
|
||||
expect(selected.result.current.isStreaming).toBe(true);
|
||||
act(() => h.socket().receive({ event: "recovery_state", chat_id: "alpha", status: "recovered",
|
||||
recovery_id: "independent", attempts: 1 }));
|
||||
expect(h.client.getRunState("alpha")).toMatchObject({ active: false, unsettled: false });
|
||||
expect(selected.result.current.isStreaming).toBe(false);
|
||||
selected.unmount();
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("rejects an abandoned chat's page after switching away and back without reconnecting", async () => {
|
||||
const h = harness();
|
||||
act(() => { h.running("alpha", "turn-1", 100); h.running("beta", "turn-1", 101); });
|
||||
const selected = h.mount("alpha");
|
||||
selected.rerender({ chat: "beta" });
|
||||
selected.rerender({ chat: "alpha" });
|
||||
const [abandonedAlpha, abandonedBeta, currentAlpha] = h.reads;
|
||||
expect(abandonedAlpha.signal.aborted).toBe(true);
|
||||
expect(abandonedBeta.signal.aborted).toBe(true);
|
||||
act(() => h.running("alpha", "turn-2", 200));
|
||||
await act(async () => { currentAlpha.resolve(history("alpha", ["turn-1"], "turn-2")); });
|
||||
const before = h.client.getRunState("alpha");
|
||||
await act(async () => {
|
||||
abandonedAlpha.resolve(history("alpha", [], "turn-1"));
|
||||
abandonedBeta.resolve(history("beta", ["turn-1"]));
|
||||
});
|
||||
expect(h.client.getRunState("alpha")).toEqual(before);
|
||||
expect(selected.result.current.messages.map((message) => message.content)).toContain("alpha answer turn-1");
|
||||
expect(selected.result.current.messages.every((message) => !message.content.includes("beta"))).toBe(true);
|
||||
expect(h.client.isRunCompleted("beta", "turn-1")).toBe(false);
|
||||
act(() => {
|
||||
for (const [chat, turn] of [["alpha", "turn-2"], ["beta", "turn-1"]]) {
|
||||
h.socket().receive({ event: "turn_end", chat_id: chat, turn_id: turn });
|
||||
}
|
||||
});
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
selected.unmount();
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("does not strand an older turn when selection changes before the scheduled mounted refresh", async () => {
|
||||
const h = harness();
|
||||
act(() => h.running("alpha", "turn-1", 100));
|
||||
const selected = h.mount("alpha");
|
||||
await h.reopen();
|
||||
const oldRead = h.reads.at(-1)!;
|
||||
act(() => h.socket().close());
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10); });
|
||||
const canReconcile = h.client.canReconcileCanonicalCompletion.bind(h.client);
|
||||
let pageProcessed!: () => void;
|
||||
const processed = new Promise<void>((resolve) => { pageProcessed = resolve; });
|
||||
const preflights: boolean[] = [];
|
||||
vi.spyOn(h.client, "canReconcileCanonicalCompletion").mockImplementation((...args) => {
|
||||
const accepted = canReconcile(...args);
|
||||
if (args[2].includes("turn-1") && args[3]?.activeTurnId === "turn-2") {
|
||||
preflights.push(accepted);
|
||||
pageProcessed();
|
||||
}
|
||||
return accepted;
|
||||
});
|
||||
let readsBeforeSwitch = 0;
|
||||
await act(async () => {
|
||||
h.socket().open();
|
||||
h.running("alpha", "turn-2", 200);
|
||||
h.reads.at(-1)!.resolve(history("alpha", ["turn-1"], "turn-2"));
|
||||
await processed;
|
||||
readsBeforeSwitch = h.reads.length;
|
||||
selected.rerender({ chat: "beta" });
|
||||
});
|
||||
act(() => {
|
||||
h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "turn-2" });
|
||||
h.socket().receive({ event: "session_updated", chat_id: "alpha", scope: "thread" });
|
||||
});
|
||||
const observed = { preflights, readsBeforeSwitch, oldReadAborted: oldRead.signal.aborted,
|
||||
state: h.client.getRunState("alpha"), unsettled: h.client.getUnsettledRunChatIds() };
|
||||
selected.unmount();
|
||||
h.close();
|
||||
expect(observed).toMatchObject({ preflights: [false], readsBeforeSwitch: 3, oldReadAborted: true,
|
||||
state: { active: false, unsettled: false }, unsettled: [] });
|
||||
});
|
||||
|
||||
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}`);
|
||||
act(() => { for (const chat of chats) h.running(chat, "turn-1", 100); });
|
||||
await h.reopen();
|
||||
const abandoned = [...h.reads];
|
||||
expect(abandoned).toHaveLength(4);
|
||||
await h.reopen();
|
||||
expect(abandoned.every((read) => read.signal.aborted)).toBe(true);
|
||||
const current = h.reads.slice(4);
|
||||
expect(current).toHaveLength(4);
|
||||
await act(async () => {
|
||||
current[0].fail(503);
|
||||
for (const read of current.slice(1)) read.resolve(history(read.chat, ["turn-1"]));
|
||||
});
|
||||
const remaining = h.reads.slice(8);
|
||||
expect(remaining.map((read) => read.chat).sort()).toEqual(["chat-4", "chat-5"]);
|
||||
await act(async () => { for (const read of remaining) read.resolve(history(read.chat, ["turn-1"])); });
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual(["chat-0"]);
|
||||
// A failed read is not success; the next real reconnect supplies its evidence.
|
||||
await h.reopen();
|
||||
expect(h.reads.slice(10).map((read) => read.chat)).toEqual(["chat-0"]);
|
||||
await act(async () => { h.reads[10].resolve(history("chat-0", ["turn-1"])); });
|
||||
await act(async () => { for (const read of abandoned) read.resolve(history(read.chat, [], "turn-1")); });
|
||||
expect(h.client.getUnsettledRunChatIds()).toEqual([]);
|
||||
for (const chat of chats) {
|
||||
expect(h.client.getRunState(chat)).toMatchObject({ active: false, unsettled: false });
|
||||
expect(webuiThreadCache.get(`websocket:${chat}`)?.completed_turn_ids).toEqual(["turn-1"]);
|
||||
}
|
||||
h.close();
|
||||
});
|
||||
});
|
||||
@@ -92,7 +92,7 @@ function makeClient() {
|
||||
getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle),
|
||||
canReconcileCanonicalCompletion,
|
||||
reconcileCanonicalCompletion,
|
||||
settleFragmentRunLifecycle: vi.fn(lifecycle.settleFragmentRunLifecycle.bind(lifecycle)),
|
||||
settleCompletedRunLifecycle: vi.fn(lifecycle.settleCompletedRunLifecycle.bind(lifecycle)),
|
||||
fenceCanonicalCompletedTurns: lifecycle.fenceCanonicalCompletedTurns.bind(lifecycle),
|
||||
getGoalState: lifecycle.getGoalState.bind(lifecycle),
|
||||
onTranscript: lifecycle.onTranscript.bind(lifecycle),
|
||||
@@ -266,9 +266,8 @@ function publishReconnectCompletion(
|
||||
const generation = client.getRunGeneration(chatId);
|
||||
const { completedTurnIds, snapshot } = persistedCanonicalRunState(body);
|
||||
expect(client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)).toBe(true);
|
||||
// useReconnectRuns publishes synchronously before settling/fencing the ledger.
|
||||
// A mounted transcript takes over reconciliation from the recovery reader.
|
||||
webuiThreadCache.set(`websocket:${chatId}`, body);
|
||||
expect(client.reconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)).toBe(true);
|
||||
}
|
||||
|
||||
function httpJson(body: unknown) {
|
||||
|
||||
@@ -116,6 +116,70 @@ describe("durable run recovery", () => {
|
||||
close();
|
||||
});
|
||||
|
||||
it.each(["before", "during"] as const)("settles an unmounted old completion when a newer turn starts %s the full-page read", async (timing) => {
|
||||
let finishRead!: (value: Response) => void;
|
||||
vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((resolve) => { finishRead = resolve; })));
|
||||
const { client, sockets, running, reopen, close } = setup();
|
||||
const early = { event: "delta", chat_id: "inactive", turn_id: "turn-old", stream_id: "old", text: "Buffered A" };
|
||||
const late = { ...early, text: "Late A" };
|
||||
const live = { event: "delta", chat_id: "inactive", turn_id: "turn-new", stream_id: "new", text: "Live B" };
|
||||
running();
|
||||
sockets[0].receive(early);
|
||||
if (timing === "before") running("inactive", "turn-new", 456);
|
||||
await reopen();
|
||||
if (timing === "during") act(() => running("inactive", "turn-new", 456));
|
||||
const newer = client.getRunState("inactive");
|
||||
const body: WebuiThreadPersistedPayload = {
|
||||
...completedThread(), schemaVersion: 3, completed_turn_ids: ["turn-old"],
|
||||
has_pending_tool_calls: true, active_turn_id: "turn-new",
|
||||
};
|
||||
body.events.push({ event: "user_message", chat_id: "inactive", turn_id: "turn-new", text: "Next task", starts_turn: true });
|
||||
await act(async () => { finishRead(response(body)); });
|
||||
expect(client.isRunCompleted("inactive", "turn-old")).toBe(true);
|
||||
expect(client.getRunState("inactive")).toEqual(newer);
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toBeUndefined();
|
||||
act(() => {
|
||||
sockets.at(-1)!.receive(late);
|
||||
sockets.at(-1)!.receive(live);
|
||||
running("inactive", "turn-old", 999);
|
||||
sockets.at(-1)!.receive({ event: "turn_end", chat_id: "inactive", turn_id: "turn-new" });
|
||||
});
|
||||
expect(client.getRunState("inactive")).toMatchObject({
|
||||
active: false, unsettled: false, latestTurnId: "turn-new", startedAt: null, generation: newer.generation,
|
||||
});
|
||||
expect(client.getUnsettledRunChatIds()).toEqual([]);
|
||||
const replay = vi.fn();
|
||||
client.onTranscript("inactive", replay);
|
||||
for (const content of [early, late, live]) expect(replay).toHaveBeenCalledWith(content);
|
||||
expect(replay).not.toHaveBeenCalledWith(expect.objectContaining({ event: "goal_status", turn_id: "turn-old" }));
|
||||
close();
|
||||
});
|
||||
|
||||
it.each(["full page", "fragment"] as const)("preserves independent anonymous recovery when a %s completes the old named turn", async (page) => {
|
||||
const body: WebuiThreadPersistedPayload = {
|
||||
...completedThread(), schemaVersion: 3, completed_turn_ids: ["turn-old"],
|
||||
has_pending_tool_calls: true, active_turn_id: null,
|
||||
...(page === "fragment" ? {
|
||||
page: { history_generation: "generation", record_range: { turn: 0, start: 5, end: 8 },
|
||||
before_cursor: "before-5", has_more_before: true, truncated_oversized_turn: true },
|
||||
} : {}),
|
||||
};
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body)));
|
||||
const { client, sockets, running, reopen, close } = setup();
|
||||
running();
|
||||
sockets[0].receive({ event: "recovery_state", chat_id: "inactive", status: "resuming", recovery_id: "new-recovery", attempts: 1 });
|
||||
const generation = client.getRunGeneration("inactive");
|
||||
await reopen();
|
||||
expect(client.isRunCompleted("inactive", "turn-old")).toBe(true);
|
||||
expect(client.getRunState("inactive")).toMatchObject({
|
||||
active: true, unsettled: false, latestTurnId: "turn-old", startedAt: null, generation,
|
||||
});
|
||||
expect(webuiThreadCache.get("websocket:inactive")).toEqual(body);
|
||||
act(() => sockets.at(-1)!.receive({ event: "recovery_state", chat_id: "inactive", status: "recovered", recovery_id: "new-recovery", attempts: 1 }));
|
||||
expect(client.getRunState("inactive")).toMatchObject({ active: false, unsettled: false });
|
||||
close();
|
||||
});
|
||||
|
||||
it("settles an unmounted run without losing buffered or late output absent from its completed latest fragment", async () => {
|
||||
const chatId = "inactive";
|
||||
const turnId = "turn-old";
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
------------------------- MODULE CacheHandoff -------------------------
|
||||
EXTENDS Naturals, FiniteSets
|
||||
CONSTANT ActiveTail
|
||||
Chats == {1,2}
|
||||
Turns == {1,2}
|
||||
VARIABLES ledger, selected, owner, switches, phase, response,
|
||||
admitted, cached, ownReadSuperseded, ownReadOwner,
|
||||
learned, lateRejected, otherOriginal, soleActor
|
||||
vars == <<ledger, selected, owner, switches, phase, response,
|
||||
admitted, cached, ownReadSuperseded, ownReadOwner,
|
||||
learned, lateRejected, otherOriginal, soleActor>>
|
||||
Complete(l,ids,coverage) == [l EXCEPT !.open = @ \ ids, !.closed = @ \cup ids,
|
||||
!.clock = IF l.latest \in ids THEN 0 ELSE @,
|
||||
!.fenced = IF coverage = "content" THEN @ \cup ids ELSE @]
|
||||
Init ==
|
||||
\* Reachable checkpoint: A is observed, initial active history already installed;
|
||||
\* disconnect lost A's terminal; reconnect R and H share one new request.
|
||||
\* Server has persisted turn 1 and is running turn 2, whose WS status is delayed.
|
||||
/\ ledger = [c \in Chats |-> [open |-> {1}, closed |-> {}, fenced |-> {},
|
||||
latest |-> 1, clock |-> 1, anonymous |-> FALSE, generation |-> 1]]
|
||||
/\ selected = 1 /\ owner = 0 /\ switches = 0 /\ phase = 0
|
||||
/\ response = [completed |-> {}, active |-> 0, pending |-> FALSE]
|
||||
/\ admitted = FALSE /\ cached = FALSE /\ ownReadSuperseded = FALSE /\ ownReadOwner = 0
|
||||
/\ soleActor = TRUE
|
||||
/\ learned = {} /\ lateRejected = FALSE /\ otherOriginal = ledger[2]
|
||||
Capture ==
|
||||
/\ phase = 0 /\ phase' = 1
|
||||
/\ response' = [completed |-> {1}, active |-> IF ActiveTail THEN 2 ELSE 0, pending |-> ActiveTail]
|
||||
/\ UNCHANGED <<ledger, selected, owner, switches, admitted, cached, ownReadSuperseded,
|
||||
ownReadOwner, learned, lateRejected, otherOriginal, soleActor>>
|
||||
Switch(c) ==
|
||||
/\ c \in Chats \cup {0} /\ c # selected /\ switches < 2
|
||||
/\ selected' = c /\ owner' = owner+1 /\ switches' = switches+1
|
||||
/\ UNCHANGED <<ledger, phase, response, admitted, cached, ownReadSuperseded,
|
||||
ownReadOwner, learned, lateRejected, otherOriginal, soleActor>>
|
||||
Process(accept) ==
|
||||
/\ phase = 1 /\ accept \in BOOLEAN
|
||||
/\ LET ids == response.completed
|
||||
hasOwner == selected = 1
|
||||
canApply == ledger[1].open \subseteq ids
|
||||
canCache == 1 \in ids /\ canApply
|
||||
idle == ~response.pending /\ response.active = 0
|
||||
publish == canCache
|
||||
ownerHandoff == publish /\ hasOwner
|
||||
\* R publishes an eligible cache BEFORE its unconditional lifecycle call.
|
||||
\* Owner content reconciliation remains the sole mounted canonical actor.
|
||||
ownerContent == ownerHandoff
|
||||
backgroundContent == publish /\ idle /\ ~hasOwner
|
||||
content == ownerContent \/ backgroundContent
|
||||
\* Admission permits adoption only, not explicit completion settlement.
|
||||
adopt == content /\ accept /\ ~response.pending /\ canApply
|
||||
next == Complete(ledger[1],ids,IF content THEN "content" ELSE "lifecycle")
|
||||
IN /\ ledger' = [ledger EXCEPT ![1] = IF adopt THEN [next EXCEPT !.anonymous = FALSE, !.clock = 0] ELSE next]
|
||||
/\ cached' = publish
|
||||
/\ ownReadSuperseded' = ownerHandoff
|
||||
/\ admitted' = (ownerHandoff /\ accept)
|
||||
/\ learned' = ids
|
||||
/\ soleActor' = (soleActor /\ ~(ownerContent /\ backgroundContent))
|
||||
/\ phase' = 2
|
||||
/\ UNCHANGED <<selected, owner, switches, response, ownReadOwner, lateRejected, otherOriginal>>
|
||||
ReceiveRunningTwo ==
|
||||
/\ phase = 2 /\ phase' = 3
|
||||
/\ ledger' = [ledger EXCEPT ![1].open = @ \cup {2}, ![1].latest = 2,
|
||||
![1].clock = 2, ![1].generation = @+1]
|
||||
/\ UNCHANGED <<selected, owner, switches, response, admitted, cached, ownReadSuperseded,
|
||||
ownReadOwner, learned, lateRejected, otherOriginal, soleActor>>
|
||||
ReceiveEndTwo ==
|
||||
/\ phase = 3 /\ phase' = 4
|
||||
/\ ledger' = [ledger EXCEPT ![1] = Complete(@,{2},"lifecycle")]
|
||||
/\ UNCHANGED <<selected, owner, switches, response, admitted, cached, ownReadSuperseded,
|
||||
ownReadOwner, learned, lateRejected, otherOriginal, soleActor>>
|
||||
LateOwnResponse ==
|
||||
/\ phase = 4 /\ phase' = 5
|
||||
/\ lateRejected' = (ownReadSuperseded \/ owner # ownReadOwner)
|
||||
/\ UNCHANGED <<ledger, selected, owner, switches, response, admitted, cached,
|
||||
ownReadSuperseded, ownReadOwner, learned, otherOriginal, soleActor>>
|
||||
Next == Capture \/ (\E c \in Chats \cup {0} : Switch(c)) \/
|
||||
(\E a \in BOOLEAN : Process(a)) \/ ReceiveRunningTwo \/ ReceiveEndTwo \/ LateOwnResponse
|
||||
Spec == Init /\ [][Next]_vars
|
||||
FairSpec == Spec /\ WF_vars(Capture) /\ WF_vars(\E a \in BOOLEAN : Process(a)) /\
|
||||
WF_vars(ReceiveRunningTwo) /\ WF_vars(ReceiveEndTwo) /\ WF_vars(LateOwnResponse)
|
||||
SoleCanonicalActor == soleActor
|
||||
RawExplicitCompletionsSettle == phase < 2 \/ learned \cap ledger[1].open = {}
|
||||
ExplicitCompletionsSettle == RawExplicitCompletionsSettle
|
||||
OtherChatUnchanged == ledger[2] = otherOriginal
|
||||
NoAnonymousClearedByNamedCompletion == ~ledger[1].anonymous
|
||||
StaleOwnReadCannotOverwrite == phase < 5 \/ lateRejected \/ (selected = 1 /\ ~ownReadSuperseded /\ owner = ownReadOwner)
|
||||
EventuallyIdle == <>[] (ledger[1].open = {} /\ ledger[1].clock = 0 /\ ~ledger[1].anonymous)
|
||||
=============================================================================
|
||||
@@ -0,0 +1,79 @@
|
||||
----------------------- MODULE CompletionAuthority -----------------------
|
||||
EXTENDS Naturals, FiniteSets
|
||||
\* Local algebra of ClientRunLedger.completeTurns, not a transcript controller.
|
||||
\* One arbitrary focus ledger; the other chat is a two-open-turn + anonymous
|
||||
\* sentinel. The transition's syntactic frame is restricted to focus.
|
||||
\* Completion fact and requested coverage are inputs; coverage admission is
|
||||
\* owned by the transcript, exercised separately in CacheHandoff.
|
||||
Chats == {1,2}
|
||||
Turns == {1,2}
|
||||
VARIABLES focus, ledger, original, buffer, originalBuffer, completed, coverage,
|
||||
phase, selected, switches, lateTurn, lateForwarded, safe
|
||||
vars == <<focus, ledger, original, buffer, originalBuffer, completed, coverage,
|
||||
phase, selected, switches, lateTurn, lateForwarded, safe>>
|
||||
Ledgers == {l \in [open : SUBSET Turns, closed : SUBSET Turns,
|
||||
fenced : SUBSET Turns, latest : Turns \cup {0},
|
||||
clock : Turns \cup {0}, anonymous : BOOLEAN] :
|
||||
l.fenced \subseteq l.closed /\
|
||||
(l.clock # 0 => l.clock = l.latest)}
|
||||
Init ==
|
||||
/\ focus \in Chats
|
||||
/\ \E l \in Ledgers : ledger = [c \in Chats |-> IF c = focus THEN l ELSE
|
||||
[open |-> Turns, closed |-> {}, fenced |-> {}, latest |-> 2, clock |-> 2, anonymous |-> TRUE]]
|
||||
/\ original = ledger
|
||||
/\ lateTurn \in Turns
|
||||
/\ buffer = [c \in Chats |-> IF c = focus THEN {lateTurn} ELSE Turns]
|
||||
/\ originalBuffer = buffer
|
||||
/\ completed \in SUBSET Turns /\ coverage \in {"lifecycle","content"}
|
||||
/\ phase = 0 /\ selected = 0 /\ switches = 0
|
||||
/\ lateForwarded = FALSE
|
||||
/\ safe = [explicit |-> TRUE, collateral |-> TRUE, anonymous |-> TRUE,
|
||||
isolation |-> TRUE, lifecycle |-> TRUE, closedStatus |-> TRUE]
|
||||
CompleteTurns ==
|
||||
/\ phase = 0
|
||||
/\ LET l == ledger[focus]
|
||||
nl == [l EXCEPT !.open = @ \ completed, !.closed = @ \cup completed,
|
||||
!.fenced = IF coverage = "content" THEN @ \cup completed ELSE @,
|
||||
!.clock = IF l.latest \in completed THEN 0 ELSE @]
|
||||
IN /\ ledger' = [ledger EXCEPT ![focus] = nl]
|
||||
/\ buffer' = IF coverage = "content" THEN [buffer EXCEPT ![focus] = @ \ nl.fenced] ELSE buffer
|
||||
/\ safe' = [safe EXCEPT
|
||||
!.explicit = (completed \cap nl.open = {}),
|
||||
!.collateral = ((l.open \ completed) = (nl.open \ completed)) /\
|
||||
(l.latest \notin completed => nl.clock = l.clock),
|
||||
!.anonymous = (nl.anonymous = l.anonymous),
|
||||
!.isolation = (\A c \in Chats \ {focus} : ledger'[c] = ledger[c] /\ buffer'[c] = buffer[c]),
|
||||
!.lifecycle = (coverage # "lifecycle" \/ (nl.fenced = l.fenced /\ buffer' = buffer))]
|
||||
/\ phase' = 1
|
||||
/\ UNCHANGED <<focus, original, originalBuffer, completed, coverage, selected, switches, lateTurn, lateForwarded>>
|
||||
LateContent ==
|
||||
/\ phase = 1
|
||||
/\ lateForwarded' = (lateTurn \notin ledger[focus].fenced)
|
||||
/\ phase' = 2
|
||||
/\ UNCHANGED <<focus, ledger, original, buffer, originalBuffer, completed, coverage,
|
||||
selected, switches, lateTurn, safe>>
|
||||
LateRunning ==
|
||||
/\ phase = 2
|
||||
/\ LET l == ledger[focus]
|
||||
drop == lateTurn \in (l.closed \cup l.fenced)
|
||||
nl == IF drop THEN l ELSE [l EXCEPT !.open = @ \cup {lateTurn}, !.latest = lateTurn, !.clock = lateTurn]
|
||||
IN /\ ledger' = [ledger EXCEPT ![focus] = nl]
|
||||
/\ safe' = [safe EXCEPT !.closedStatus = (lateTurn \in l.closed => nl = l)]
|
||||
/\ phase' = 3
|
||||
/\ UNCHANGED <<focus, original, buffer, originalBuffer, completed, coverage, selected, switches, lateTurn, lateForwarded>>
|
||||
Switch(c) ==
|
||||
/\ c \in Chats \cup {0} /\ c # selected /\ switches < 2
|
||||
/\ selected' = c /\ switches' = switches+1
|
||||
/\ UNCHANGED <<focus, ledger, original, buffer, originalBuffer, completed, coverage,
|
||||
phase, lateTurn, lateForwarded, safe>>
|
||||
Next == CompleteTurns \/ LateContent \/ LateRunning \/ (\E c \in Chats \cup {0} : Switch(c))
|
||||
Spec == Init /\ [][Next]_vars
|
||||
ExplicitCompletionsSettle == safe.explicit
|
||||
NoOlderCompletionClearsNewer == safe.collateral
|
||||
PartialCompletionPreservesRecovery == safe.anonymous
|
||||
OtherChatUnchanged == safe.isolation
|
||||
LifecycleOnlyPreservesContentAndRecovery == safe.lifecycle
|
||||
ClosedRunningCannotReopen == safe.closedStatus
|
||||
LateLifecycleContentSurvives == phase < 2 \/ coverage # "lifecycle" \/
|
||||
(lateTurn \notin original[focus].fenced => lateForwarded)
|
||||
=============================================================================
|
||||
@@ -0,0 +1,77 @@
|
||||
# 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 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.
|
||||
|
||||
## Files and source mapping
|
||||
|
||||
| Model | Current implementation boundary |
|
||||
| --- | --- |
|
||||
| `TurnSync.tla` | Shared server, wire, ledger state and live terminal transitions for the fixed-mount submodel; it has no standalone configuration or alternative completion policy. |
|
||||
| `RevisedTurnSync.tla` | Fixed mounted/unmounted full-page and fragment completion, content/lifecycle coverage, independent anonymous recovery and cache-before-notification ordering. |
|
||||
| `UsageLifecycle.tla` | Dynamic selection, actual mounted ownership, deferred hook effects and unconditional fresh full-page lifecycle observation. |
|
||||
| `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. |
|
||||
|
||||
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 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.
|
||||
|
||||
## Checked properties
|
||||
|
||||
- `ExplicitCompletionsSettle` / `RawExplicitCompletionsSettle`: learned explicit IDs retain no open lifecycle ownership. Raw full-page learning is independent of content eligibility.
|
||||
- `NoOlderCompletionClearsNewer`: completing one ID preserves other owners and their clocks.
|
||||
- `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.
|
||||
|
||||
## 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.
|
||||
|
||||
Pending metadata may omit an active ID. Independent anonymous recovery may begin during either executing turn, but no new recovery starts after both turns finish. Full-page liveness uses weak fairness for reconnection, queued lifecycle delivery, history capture and response processing. It assumes successful full responses and no future work; permanent disconnection, failed reads, omitted IDs and unbridgeable fragments do not satisfy that guarantee. Fragment cases check safety without inventing fragment-bridging fairness. Content is one arbitrary A-or-B probe identity with buffered/late tokens, not text reconstruction or eventual rendering.
|
||||
|
||||
The expanded dynamic workload has two sequential turns, two outages and two selection changes with selected/mounted state separated. The request partitions cover two keys without invalidation and one key with invalidation/replacement; each has two outages/switches. Local completion algebra considers either focus chat and another-chat sentinel, including overapproximated ledger inputs. These are separate finite graphs, not one combined graph or a checked compositional theorem. Larger two-chat products remain optional and are not claimed exhausted. There are no TLC state constraints or depth cutoffs.
|
||||
|
||||
The maintained `reconnect-real-use.test.tsx` tests exercise the real client/hooks independently of these models, including canceled responses, six-chat recovery and a failed page. Separate production-WebUI/real-Gateway acceptance covered two concurrent chats, six turns, two outages and three switches during outstanding reads. Those are concrete schedules, not an unbounded theorem. Backend execution, transcript joining/text projection, authentication replacement, eviction, multiple tabs/hosts and unbounded workloads remain outside the models.
|
||||
|
||||
## Reproduce
|
||||
|
||||
Requirements: Python 3.9+, Java and the official [`tla2tools.jar` from TLA+ v1.7.4](https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4). No jar is committed. The reference jar reports `TLC2 Version 2.19` and SHA-256 `936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`; this records observed provenance, not an independently verified release signature.
|
||||
|
||||
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.
|
||||
|
||||
## Reference positive results
|
||||
|
||||
| Config | Checked scope | Distinct states |
|
||||
| --- | --- | ---: |
|
||||
| `revised-mounted` | Fixed mounted full pages; safety | 10,299 |
|
||||
| `revised-unmounted` | Fixed unmounted full pages; safety | 16,844 |
|
||||
| `revised-mounted-fragments` | Mounted full pages/fragments; safety | 79,117 |
|
||||
| `revised-unmounted-fragments` | Unmounted full pages/fragments; safety | 105,114 |
|
||||
| `revised-mounted-live` | Mounted full pages; conditional liveness | 10,299 |
|
||||
| `revised-unmounted-live` | Unmounted full pages; conditional liveness | 16,844 |
|
||||
| `requests-two-no-invalidations` | Two keys, shared/canceled/late consumers; request-drain liveness | 473,117 |
|
||||
| `requests-one` | Per-key invalidation/replacement; request-drain liveness | 17,943 |
|
||||
| `authority` | Exact-ID closure, coverage, isolation and anonymous preservation | 276,480 |
|
||||
| `lifecycle-fullpage-dynamic` | Dynamic turns/outages/selection; raw completion safety and conditional liveness | 114,597 |
|
||||
| `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.
|
||||
@@ -0,0 +1,231 @@
|
||||
------------------------- MODULE RevisedTurnSync -------------------------
|
||||
EXTENDS TurnSync
|
||||
|
||||
\* Current fixed-mount completion and content-coverage transitions.
|
||||
\* TurnSync supplies only the shared server, wire and ledger state.
|
||||
CONSTANT IncludeFragments
|
||||
|
||||
VARIABLES snapshotIsFragment, probeTurn, bufferedProbe, lateProbe,
|
||||
probeProtected, contentLost, lifecycleOnlyPreserved,
|
||||
mountedFragmentPreserved, activeSnapshotNotAdopted,
|
||||
cacheBeforeNotification, cached, effectsOrder
|
||||
|
||||
extraVars == <<snapshotIsFragment, probeTurn, bufferedProbe, lateProbe,
|
||||
probeProtected, contentLost, lifecycleOnlyPreserved,
|
||||
mountedFragmentPreserved, activeSnapshotNotAdopted,
|
||||
cacheBeforeNotification, cached, effectsOrder>>
|
||||
revisedVars == <<vars, extraVars>>
|
||||
|
||||
RevisedInit ==
|
||||
/\ Init
|
||||
/\ snapshotIsFragment = FALSE
|
||||
\* One arbitrary content identity is sufficient to test either A or B.
|
||||
/\ probeTurn \in Turns
|
||||
/\ bufferedProbe = "absent"
|
||||
/\ lateProbe = "none"
|
||||
/\ probeProtected = FALSE
|
||||
/\ contentLost = FALSE
|
||||
/\ lifecycleOnlyPreserved = TRUE
|
||||
/\ mountedFragmentPreserved = TRUE
|
||||
/\ activeSnapshotNotAdopted = TRUE
|
||||
/\ cacheBeforeNotification = TRUE
|
||||
/\ cached = FALSE
|
||||
/\ effectsOrder = <<>>
|
||||
|
||||
RevisedCaptureWith(fragment, pending, activeId, completions, observed) ==
|
||||
/\ readPhase = "requested" /\ connected
|
||||
/\ fragment \in BOOLEAN /\ (fragment => IncludeFragments)
|
||||
/\ pending \in BOOLEAN
|
||||
/\ pending => (anonymous \/ (\E t \in Turns : server[t] = "running"))
|
||||
/\ LET done == {t \in Turns : server[t] = "done"}
|
||||
seen == {t \in Turns : server[t] # "new"}
|
||||
exactActive == IF server[B] = "running" THEN B
|
||||
ELSE IF server[A] = "running" THEN A ELSE None
|
||||
IN /\ activeId \in {None, exactActive}
|
||||
/\ IF fragment
|
||||
THEN /\ completions \subseteq done
|
||||
/\ observed \subseteq seen
|
||||
ELSE /\ completions = done
|
||||
/\ observed = seen
|
||||
/\ snapshotIsFragment' = fragment
|
||||
/\ snapshotPending' = pending
|
||||
/\ snapshotCompleted' = completions
|
||||
/\ snapshotObserved' = observed
|
||||
/\ snapshotActive' = activeId
|
||||
/\ readPhase' = "ready"
|
||||
/\ lastAction' = "capture-revised-history"
|
||||
/\ UNCHANGED <<server, connected, disconnected, wire, open, closed, fenced,
|
||||
latest, clock, generation, anonymous, recoverySeen, requestTurn,
|
||||
requestGeneration, learned, collateral, partialRecoveryPreserved>>
|
||||
/\ UNCHANGED <<probeTurn, bufferedProbe, lateProbe, probeProtected,
|
||||
contentLost, lifecycleOnlyPreserved, mountedFragmentPreserved,
|
||||
activeSnapshotNotAdopted, cacheBeforeNotification, cached, effectsOrder>>
|
||||
|
||||
RevisedCapture ==
|
||||
\E fragment, pending \in BOOLEAN, activeId \in Turns \cup {None},
|
||||
completions, observed \in SUBSET Turns :
|
||||
RevisedCaptureWith(fragment, pending, activeId, completions, observed)
|
||||
|
||||
\* Recovery may begin during either executing turn with either observed owner.
|
||||
\* New recovery after both server turns finish is excluded by the
|
||||
\* no-future-work liveness scope.
|
||||
RevisedStartAnonymousRecovery ==
|
||||
/\ connected /\ latest \in Turns
|
||||
/\ (\E t \in Turns : server[t] = "running")
|
||||
/\ ~anonymous /\ ~recoverySeen
|
||||
/\ anonymous' = TRUE
|
||||
/\ recoverySeen' = TRUE
|
||||
/\ lastAction' = "receive-revised-anonymous-recovery"
|
||||
/\ UNCHANGED <<server, connected, disconnected, wire, open, closed, fenced,
|
||||
latest, clock, generation, readPhase, requestTurn,
|
||||
requestGeneration, snapshotCompleted, snapshotActive,
|
||||
snapshotObserved, snapshotPending, learned, collateral, partialRecoveryPreserved>>
|
||||
/\ UNCHANGED extraVars
|
||||
|
||||
\* A buffered content token represents a pending delta/message/stream_end,
|
||||
\* not a lifecycle status. It has already reached the client before this read.
|
||||
BufferProbe ==
|
||||
/\ ~Mounted /\ connected /\ probeTurn \in open
|
||||
/\ bufferedProbe = "absent" /\ probeTurn \notin fenced
|
||||
/\ bufferedProbe' = "queued"
|
||||
/\ lastAction' = "buffer-content-probe"
|
||||
/\ UNCHANGED <<server, connected, disconnected, wire, open, closed, fenced,
|
||||
latest, clock, generation, anonymous, recoverySeen, readPhase,
|
||||
requestTurn, requestGeneration, snapshotCompleted, snapshotActive,
|
||||
snapshotObserved, snapshotPending, learned, collateral,
|
||||
partialRecoveryPreserved>>
|
||||
/\ UNCHANGED <<snapshotIsFragment, probeTurn, lateProbe, probeProtected,
|
||||
contentLost, lifecycleOnlyPreserved, mountedFragmentPreserved,
|
||||
activeSnapshotNotAdopted, cacheBeforeNotification, cached, effectsOrder>>
|
||||
|
||||
\* ClientRunLedger.applyObservation: closed activity/progress is forwarded;
|
||||
\* fenced activity is dropped. Neither branch can reopen lifecycle ownership.
|
||||
ReceiveLateProbe ==
|
||||
/\ connected /\ probeTurn \in closed /\ lateProbe = "none"
|
||||
/\ lateProbe' = IF probeTurn \in fenced THEN "dropped" ELSE "forwarded"
|
||||
/\ contentLost' = (contentLost \/ (probeProtected /\ probeTurn \in fenced))
|
||||
/\ lastAction' = "receive-late-content-probe"
|
||||
/\ UNCHANGED <<server, connected, disconnected, wire, open, closed, fenced,
|
||||
latest, clock, generation, anonymous, recoverySeen, readPhase,
|
||||
requestTurn, requestGeneration, snapshotCompleted, snapshotActive,
|
||||
snapshotObserved, snapshotPending, learned, collateral,
|
||||
partialRecoveryPreserved>>
|
||||
/\ UNCHANGED <<snapshotIsFragment, probeTurn, bufferedProbe, probeProtected,
|
||||
lifecycleOnlyPreserved, mountedFragmentPreserved,
|
||||
activeSnapshotNotAdopted, cacheBeforeNotification, cached, effectsOrder>>
|
||||
|
||||
\* For full pages, accepted abstracts owner.accept(). For fragments it means
|
||||
\* the owner has admitted/joined the fragment AND exposed its completed IDs.
|
||||
\* A staged fragment may return true from owner.accept() with no such handoff;
|
||||
\* that case takes accepted=FALSE here. No fragment-bridging liveness is assumed.
|
||||
RevisedProcessWithAcceptance(accepted) ==
|
||||
/\ readPhase = "ready" /\ connected
|
||||
/\ accepted \in BOOLEAN
|
||||
/\ LET completed == snapshotCompleted
|
||||
represented == latest # None /\ latest \in completed
|
||||
\* Completion IDs are supplied; observed IDs alone cannot settle an
|
||||
\* open candidate owner. Preflight is evaluated BEFORE settlement.
|
||||
canApply == open \subseteq completed /\
|
||||
(generation = requestGeneration \/ represented)
|
||||
explicit == requestTurn # None /\ requestTurn \in completed
|
||||
idleSnapshot == ~snapshotPending /\ snapshotActive = None
|
||||
canCache == (explicit \/ idleSnapshot) /\
|
||||
(requestTurn = None \/ explicit \/ requestTurn \in snapshotObserved) /\
|
||||
canApply
|
||||
fragmentReady == snapshotIsFragment /\ (~Mounted \/ accepted)
|
||||
\* Mounted full-page reconciliation is intentionally unchanged:
|
||||
\* rejection/partial adoption still calls fenceCanonicalCompletedTurns.
|
||||
fullAccept == ~snapshotIsFragment /\
|
||||
(IF Mounted THEN accepted /\ ~snapshotPending /\ canApply
|
||||
ELSE canCache /\ idleSnapshot)
|
||||
lifecyclePath == fragmentReady \/ (~snapshotIsFragment /\ ~Mounted)
|
||||
wholeFence == ~snapshotIsFragment /\ (Mounted \/ fullAccept)
|
||||
settleIds == lifecyclePath \/ wholeFence
|
||||
nextOpen == IF settleIds THEN open \ completed ELSE open
|
||||
nextClosed == IF settleIds THEN closed \cup completed ELSE closed
|
||||
nextFenced == IF wholeFence THEN fenced \cup completed ELSE fenced
|
||||
nextClock == IF fullAccept \/ (settleIds /\ latest \in completed)
|
||||
THEN None ELSE clock
|
||||
nextAnonymous == IF fullAccept THEN FALSE ELSE anonymous
|
||||
nextBuffered == IF wholeFence /\ probeTurn \in completed /\ bufferedProbe = "queued"
|
||||
THEN "pruned" ELSE bufferedProbe
|
||||
lifecycleOnly == lifecyclePath /\ ~wholeFence
|
||||
didCache == IF snapshotIsFragment THEN canApply ELSE ~Mounted /\ canCache
|
||||
\* Order models synchronous cache publication preceding run-status
|
||||
\* callbacks; it is not a second asynchronous HTTP/WS transition.
|
||||
order == (IF didCache THEN <<"cache">> ELSE <<>>) \o
|
||||
(IF lifecyclePath THEN <<"lifecycle">> ELSE <<>>) \o
|
||||
(IF wholeFence THEN <<"fence">> ELSE <<>>) \o
|
||||
(IF fullAccept THEN <<"adopt">> ELSE <<>>)
|
||||
willNotifyIdle == Active /\ nextOpen = {} /\ nextClock = None /\ ~nextAnonymous
|
||||
IN /\ open' = nextOpen
|
||||
/\ closed' = nextClosed
|
||||
/\ fenced' = nextFenced
|
||||
/\ clock' = nextClock
|
||||
/\ anonymous' = nextAnonymous
|
||||
\* A mounted rejected/staged fragment has not yet handed completion
|
||||
\* identities to the ledger. Full pages retain the original invariant.
|
||||
/\ learned' = learned \cup (IF ~snapshotIsFragment \/ fragmentReady THEN completed ELSE {})
|
||||
/\ collateral' = ((open \ completed) \ nextOpen) \cup
|
||||
(IF latest # None /\ latest \notin completed /\ clock = latest /\ nextClock # clock
|
||||
THEN {latest} ELSE {})
|
||||
/\ partialRecoveryPreserved' = (fullAccept \/ ~anonymous \/ nextAnonymous)
|
||||
/\ bufferedProbe' = nextBuffered
|
||||
/\ contentLost' = (contentLost \/
|
||||
(lifecycleOnly /\ bufferedProbe = "queued" /\ nextBuffered # "queued"))
|
||||
/\ probeProtected' = IF wholeFence /\ probeTurn \in completed THEN FALSE
|
||||
ELSE probeProtected \/ (lifecycleOnly /\ probeTurn \in completed)
|
||||
/\ lifecycleOnlyPreserved' = (~lifecycleOnly \/
|
||||
(nextFenced = fenced /\ nextBuffered = bufferedProbe /\ nextAnonymous = anonymous))
|
||||
/\ mountedFragmentPreserved' = (~(Mounted /\ snapshotIsFragment /\ ~accepted) \/
|
||||
(nextOpen = open /\ nextClosed = closed /\ nextFenced = fenced /\
|
||||
nextClock = clock /\ nextAnonymous = anonymous))
|
||||
/\ activeSnapshotNotAdopted' = (Mounted \/ snapshotIsFragment \/ idleSnapshot \/ ~fullAccept)
|
||||
/\ cached' = (cached \/ didCache)
|
||||
/\ effectsOrder' = order
|
||||
/\ cacheBeforeNotification' = (~(~Mounted /\ didCache /\ willNotifyIdle) \/
|
||||
(Len(order) > 0 /\ Head(order) = "cache"))
|
||||
/\ readPhase' = "handled"
|
||||
/\ lastAction' = "process-revised-history"
|
||||
/\ UNCHANGED <<server, connected, disconnected, wire, latest, generation,
|
||||
recoverySeen, requestTurn, requestGeneration, snapshotCompleted,
|
||||
snapshotActive, snapshotObserved, snapshotPending,
|
||||
snapshotIsFragment, probeTurn, lateProbe>>
|
||||
|
||||
RevisedProcess == \E accepted \in BOOLEAN : RevisedProcessWithAcceptance(accepted)
|
||||
|
||||
RevisedNext ==
|
||||
\/ ((\/ \E t \in Turns : Start(t)
|
||||
\/ \E t \in Turns : Finish(t)
|
||||
\/ Disconnect \/ Reconnect \/ Receive
|
||||
\/ EndAnonymousRecovery)
|
||||
/\ UNCHANGED extraVars)
|
||||
\/ RevisedStartAnonymousRecovery
|
||||
\/ RevisedCapture
|
||||
\/ RevisedProcess
|
||||
\/ BufferProbe
|
||||
\/ ReceiveLateProbe
|
||||
|
||||
RevisedSpec == RevisedInit /\ [][RevisedNext]_revisedVars
|
||||
RevisedFairSpec == RevisedSpec /\ WF_revisedVars(Reconnect /\ UNCHANGED extraVars) /\
|
||||
WF_revisedVars(Receive /\ UNCHANGED extraVars) /\
|
||||
WF_revisedVars(RevisedCapture) /\ WF_revisedVars(RevisedProcess)
|
||||
|
||||
RevisedTypeOK ==
|
||||
/\ TypeOK
|
||||
/\ IncludeFragments \in BOOLEAN /\ snapshotIsFragment \in BOOLEAN
|
||||
/\ probeTurn \in Turns
|
||||
/\ bufferedProbe \in {"absent", "queued", "pruned"}
|
||||
/\ lateProbe \in {"none", "forwarded", "dropped"}
|
||||
/\ probeProtected \in BOOLEAN /\ contentLost \in BOOLEAN
|
||||
/\ lifecycleOnlyPreserved \in BOOLEAN /\ mountedFragmentPreserved \in BOOLEAN
|
||||
/\ activeSnapshotNotAdopted \in BOOLEAN /\ cacheBeforeNotification \in BOOLEAN
|
||||
/\ cached \in BOOLEAN
|
||||
/\ effectsOrder \in Seq({"cache", "lifecycle", "fence", "adopt"})
|
||||
|
||||
LifecycleOnlyPreservesContentAndRecovery == lifecycleOnlyPreserved /\ ~contentLost
|
||||
MountedFragmentRequiresAcceptance == mountedFragmentPreserved
|
||||
ActiveUnmountedSnapshotIsNotAdopted == activeSnapshotNotAdopted
|
||||
CachePrecedesIdleNotification == cacheBeforeNotification
|
||||
|
||||
=============================================================================
|
||||
@@ -0,0 +1,165 @@
|
||||
------------------------- MODULE SharedRequests -------------------------
|
||||
EXTENDS Naturals, FiniteSets
|
||||
CONSTANTS NChats, MaxOutages, MaxSwitches, MaxInvalidations
|
||||
Chats == 1..NChats
|
||||
Readers == {"H", "R"}
|
||||
\* At most H and R actively await one key; each attaches to at most one network
|
||||
\* object. Thus two live slots are sufficient, not an arbitrary request cutoff.
|
||||
\* Released/aborted network identities with no consumers are observationally
|
||||
\* merged into late[key]; they may deliver but cannot regain an active wrapper.
|
||||
\* Same authenticated client/token, two distinct websocket:<chat> keys.
|
||||
Slots == {1,2}
|
||||
EmptyNet == [phase |-> 0, shareable |-> FALSE, baseline |-> 0, body |-> 0]
|
||||
EmptyConsumer == [phase |-> 0, slot |-> 0, owner |-> 0, epoch |-> 0, body |-> 0]
|
||||
VARIABLES net, current, consumers, selected, owner, connected, outages,
|
||||
switches, hookNeed, jobs, version, cache, invalidations, late,
|
||||
published, delivered, safe
|
||||
vars == <<net, current, consumers, selected, owner, connected, outages,
|
||||
switches, hookNeed, jobs, version, cache, invalidations, late,
|
||||
published, delivered, safe>>
|
||||
Attached(cs,i) == {r \in Readers : cs[r].phase = 1 /\ cs[r].slot = i}
|
||||
Clean(ns,cs) == [i \in Slots |-> IF Attached(cs,i) = {} THEN EmptyNet ELSE ns[i]]
|
||||
Pointer(p,ns) == IF p = 0 THEN 0 ELSE IF ns[p].phase = 0 THEN 0 ELSE p
|
||||
Abandoned(ns,cs) == \E i \in Slots : ns[i].phase # 0 /\ Attached(cs,i) = {}
|
||||
Init ==
|
||||
/\ net = [c \in Chats |-> [i \in Slots |-> EmptyNet]]
|
||||
/\ current = [c \in Chats |-> 0]
|
||||
/\ consumers = [c \in Chats |-> [r \in Readers |-> EmptyConsumer]]
|
||||
/\ selected = 1 /\ owner = 0 /\ connected = TRUE /\ outages = 0 /\ switches = 0
|
||||
/\ hookNeed = TRUE /\ jobs = Chats
|
||||
/\ version = [c \in Chats |-> 0] /\ cache = [c \in Chats |-> 0]
|
||||
/\ invalidations = [c \in Chats |-> 0] /\ late = {}
|
||||
/\ published = [c \in Chats |-> 0] /\ delivered = [c \in Chats |-> 0]
|
||||
/\ safe = [keyIsolation |-> TRUE, consumerEligibility |-> TRUE,
|
||||
lateNoEffect |-> TRUE, sharedIdentity |-> TRUE]
|
||||
Start(c,r) ==
|
||||
/\ IF r = "H" THEN c = selected /\ hookNeed ELSE c \in jobs \/ consumers[c][r].phase = 3
|
||||
/\ LET cs == [consumers[c] EXCEPT ![r] = EmptyConsumer]
|
||||
ns == Clean(net[c],cs)
|
||||
ptr == Pointer(current[c],ns)
|
||||
join == IF ptr = 0 THEN FALSE ELSE ns[ptr].shareable /\ ns[ptr].baseline = cache[c]
|
||||
free == {i \in Slots : ns[i].phase = 0}
|
||||
id == IF join THEN ptr ELSE CHOOSE i \in free : \A j \in free : i <= j
|
||||
nc == [cs EXCEPT ![r] = [phase |-> 1, slot |-> id, owner |-> owner,
|
||||
epoch |-> outages, body |-> 0]]
|
||||
nn == IF join THEN ns ELSE [ns EXCEPT ![id] =
|
||||
[phase |-> 1, shareable |-> connected, baseline |-> cache[c], body |-> 0]]
|
||||
IN /\ free # {} \/ join
|
||||
/\ consumers' = [consumers EXCEPT ![c] = nc]
|
||||
/\ net' = [net EXCEPT ![c] = nn]
|
||||
/\ current' = [current EXCEPT ![c] = id]
|
||||
/\ late' = IF Abandoned(net[c],cs) THEN late \cup {c} ELSE late
|
||||
/\ safe' = [safe EXCEPT !.sharedIdentity = @ /\ (~join \/ id = ptr)]
|
||||
/\ hookNeed' = IF r = "H" THEN FALSE ELSE hookNeed
|
||||
/\ jobs' = IF r = "R" THEN jobs \ {c} ELSE jobs
|
||||
/\ UNCHANGED <<selected, owner, connected, outages, switches, version, cache,
|
||||
invalidations, published, delivered>>
|
||||
Switch(c) ==
|
||||
/\ c \in Chats \cup {0} /\ c # selected /\ switches < MaxSwitches
|
||||
/\ selected' = c /\ owner' = owner+1 /\ switches' = switches+1
|
||||
/\ hookNeed' = (c # 0)
|
||||
/\ LET cs == [k \in Chats |-> [consumers[k] EXCEPT !["H"] = EmptyConsumer]]
|
||||
ns == [k \in Chats |-> Clean(net[k],cs[k])]
|
||||
IN /\ consumers' = cs /\ net' = ns
|
||||
/\ current' = [k \in Chats |-> Pointer(current[k],ns[k])]
|
||||
/\ late' = late \cup {k \in Chats : Abandoned(net[k],cs[k]) \/ consumers[k]["H"].phase = 2}
|
||||
/\ UNCHANGED <<connected, outages, jobs, version, cache, invalidations, published, delivered, safe>>
|
||||
Disconnect ==
|
||||
/\ connected /\ outages < MaxOutages
|
||||
/\ connected' = FALSE /\ outages' = outages+1 /\ jobs' = {}
|
||||
/\ LET cs == [c \in Chats |-> [consumers[c] EXCEPT !["R"] = EmptyConsumer]]
|
||||
ns == [c \in Chats |-> Clean([i \in Slots |-> [net[c][i] EXCEPT !.shareable = FALSE]],cs[c])]
|
||||
IN /\ consumers' = cs /\ net' = ns
|
||||
/\ current' = [c \in Chats |-> Pointer(current[c],ns[c])]
|
||||
/\ late' = late \cup {c \in Chats : Abandoned(net[c],cs[c]) \/ consumers[c]["R"].phase = 2}
|
||||
/\ UNCHANGED <<selected, owner, switches, hookNeed, version, cache, invalidations, published, delivered, safe>>
|
||||
Reconnect ==
|
||||
/\ ~connected /\ connected' = TRUE /\ jobs' = Chats
|
||||
/\ hookNeed' = (selected # 0)
|
||||
/\ UNCHANGED <<net, current, consumers, selected, owner, outages, switches,
|
||||
version, cache, invalidations, late, published, delivered, safe>>
|
||||
Invalidate(c) ==
|
||||
/\ invalidations[c] < MaxInvalidations
|
||||
/\ invalidations' = [invalidations EXCEPT ![c] = @+1]
|
||||
/\ version' = [version EXCEPT ![c] = @+1]
|
||||
/\ consumers' = [consumers EXCEPT ![c] = [r \in Readers |->
|
||||
IF consumers[c][r].phase = 1 THEN [consumers[c][r] EXCEPT !.phase = 3, !.slot = 0]
|
||||
ELSE consumers[c][r]]]
|
||||
/\ net' = [net EXCEPT ![c] = [i \in Slots |-> EmptyNet]]
|
||||
/\ current' = [current EXCEPT ![c] = 0]
|
||||
/\ late' = IF \E i \in Slots : net[c][i].phase # 0 THEN late \cup {c} ELSE late
|
||||
/\ UNCHANGED <<selected, owner, connected, outages, switches, hookNeed, jobs,
|
||||
cache, published, delivered, safe>>
|
||||
RetryHook(c) ==
|
||||
/\ c = selected /\ consumers[c]["H"].phase = 3 /\ ~hookNeed
|
||||
/\ hookNeed' = TRUE
|
||||
/\ UNCHANGED <<net, current, consumers, selected, owner, connected, outages,
|
||||
switches, jobs, version, cache, invalidations, late, published, delivered, safe>>
|
||||
Capture(c,i) ==
|
||||
/\ net[c][i].phase = 1
|
||||
/\ net' = [net EXCEPT ![c][i].phase = 2, ![c][i].body = version[c]]
|
||||
/\ UNCHANGED <<current, consumers, selected, owner, connected, outages, switches,
|
||||
hookNeed, jobs, version, cache, invalidations, late, published, delivered, safe>>
|
||||
Resolve(c,i) ==
|
||||
/\ net[c][i].phase = 2
|
||||
/\ consumers' = [consumers EXCEPT ![c] = [r \in Readers |->
|
||||
IF consumers[c][r].phase = 1 /\ consumers[c][r].slot = i THEN
|
||||
[consumers[c][r] EXCEPT !.phase = 2, !.slot = 0, !.body = net[c][i].body]
|
||||
ELSE consumers[c][r]]]
|
||||
/\ net' = [net EXCEPT ![c][i] = EmptyNet]
|
||||
/\ current' = [current EXCEPT ![c] = IF @ = i THEN 0 ELSE @]
|
||||
/\ UNCHANGED <<selected, owner, connected, outages, switches, hookNeed, jobs,
|
||||
version, cache, invalidations, late, published, delivered, safe>>
|
||||
Consume(c,r,publish) ==
|
||||
/\ consumers[c][r].phase = 2 /\ publish \in BOOLEAN
|
||||
/\ LET q == consumers[c][r]
|
||||
eligible == IF r = "H" THEN c = selected /\ q.owner = owner ELSE connected /\ q.epoch = outages
|
||||
didPublish == eligible /\ (r = "H" \/ publish)
|
||||
handoff == didPublish /\ c = selected
|
||||
cs == [consumers[c] EXCEPT ![r] = EmptyConsumer,
|
||||
!["H"] = IF handoff \/ r = "H" THEN EmptyConsumer ELSE consumers[c]["H"]]
|
||||
ns == Clean(net[c],cs)
|
||||
IN /\ consumers' = [consumers EXCEPT ![c] = cs]
|
||||
/\ net' = [net EXCEPT ![c] = ns]
|
||||
/\ current' = [current EXCEPT ![c] = Pointer(@,ns)]
|
||||
/\ cache' = IF didPublish THEN [cache EXCEPT ![c] = @+1] ELSE cache
|
||||
/\ published' = IF didPublish THEN [published EXCEPT ![c] = q.body] ELSE published
|
||||
/\ delivered' = IF handoff THEN [delivered EXCEPT ![c] = q.body] ELSE delivered
|
||||
/\ late' = IF Abandoned(net[c],cs) \/ (handoff /\ consumers[c]["H"].phase = 2 /\ r # "H")
|
||||
THEN late \cup {c} ELSE late
|
||||
/\ safe' = [safe EXCEPT
|
||||
!.keyIsolation = @ /\ (\A k \in Chats \ {c} : published'[k] = published[k] /\ delivered'[k] = delivered[k]),
|
||||
!.consumerEligibility = @ /\ (didPublish => eligible) /\ (handoff => c = selected)]
|
||||
/\ UNCHANGED <<selected, owner, connected, outages, switches, hookNeed, jobs,
|
||||
version, invalidations>>
|
||||
LateDelivery(c) ==
|
||||
/\ c \in late /\ late' = late \ {c}
|
||||
/\ UNCHANGED <<net, current, consumers, selected, owner, connected, outages, switches,
|
||||
hookNeed, jobs, version, cache, invalidations, published, delivered, safe>>
|
||||
StartAny == \E c \in Chats, r \in Readers : Start(c,r)
|
||||
CaptureAny == \E c \in Chats, i \in Slots : Capture(c,i)
|
||||
ResolveAny == \E c \in Chats, i \in Slots : Resolve(c,i)
|
||||
ConsumeAny == \E c \in Chats, r \in Readers, p \in BOOLEAN : Consume(c,r,p)
|
||||
RetryAny == \E c \in Chats : RetryHook(c)
|
||||
Next == StartAny \/ CaptureAny \/ ResolveAny \/ ConsumeAny \/ RetryAny \/ Disconnect \/ Reconnect \/
|
||||
(\E c \in Chats \cup {0} : Switch(c)) \/ (\E c \in Chats : Invalidate(c) \/ LateDelivery(c))
|
||||
Spec == Init /\ [][Next]_vars
|
||||
FairSpec == Spec /\ WF_vars(StartAny) /\ WF_vars(CaptureAny) /\ WF_vars(ResolveAny) /\
|
||||
WF_vars(ConsumeAny) /\ WF_vars(RetryAny) /\ WF_vars(Reconnect)
|
||||
TypeOK ==
|
||||
/\ selected \in Chats \cup {0} /\ switches \in 0..MaxSwitches /\ outages \in 0..MaxOutages
|
||||
/\ connected \in BOOLEAN /\ jobs \subseteq Chats /\ late \subseteq Chats
|
||||
/\ \A c \in Chats : /\ current[c] \in Slots \cup {0}
|
||||
/\ invalidations[c] \in 0..MaxInvalidations
|
||||
/\ \A r \in Readers : consumers[c][r].phase \in 0..3
|
||||
/\ \A i \in Slots : net[c][i].phase \in 0..2
|
||||
NoWrongKeyDelivery == safe.keyIsolation
|
||||
NoIneligibleConsumerDelivery == safe.consumerEligibility
|
||||
NoOrphanedNetwork == \A c \in Chats, i \in Slots :
|
||||
(net[c][i].phase # 0) => Attached(consumers[c],i) # {}
|
||||
PointerHasRequest == \A c \in Chats : IF current[c] = 0 THEN TRUE ELSE net[c][current[c]].phase # 0
|
||||
SharingUsesCurrentIdentity == safe.sharedIdentity
|
||||
Quiescent == connected /\ ~hookNeed /\ jobs = {} /\
|
||||
(\A c \in Chats, r \in Readers : consumers[c][r].phase = 0)
|
||||
EventuallyRequestsDrain == <>[] Quiescent
|
||||
=============================================================================
|
||||
@@ -0,0 +1,166 @@
|
||||
----------------------------- MODULE TurnSync -----------------------------
|
||||
EXTENDS Naturals, FiniteSets, Sequences
|
||||
|
||||
\* Shared server, wire and ledger state for the fixed-mount model.
|
||||
CONSTANTS A, B, Mounted
|
||||
|
||||
Turns == {A, B}
|
||||
None == "none"
|
||||
Frames == [kind : {"running", "end"}, turn : Turns]
|
||||
|
||||
VARIABLES server, connected, disconnected, wire,
|
||||
open, closed, fenced, latest, clock, generation,
|
||||
anonymous, recoverySeen,
|
||||
readPhase, requestTurn, requestGeneration,
|
||||
snapshotCompleted, snapshotActive, snapshotObserved, snapshotPending,
|
||||
learned, collateral, partialRecoveryPreserved, lastAction
|
||||
|
||||
vars == <<server, connected, disconnected, wire,
|
||||
open, closed, fenced, latest, clock, generation,
|
||||
anonymous, recoverySeen,
|
||||
readPhase, requestTurn, requestGeneration,
|
||||
snapshotCompleted, snapshotActive, snapshotObserved, snapshotPending,
|
||||
learned, collateral, partialRecoveryPreserved, lastAction>>
|
||||
|
||||
Active == open # {} \/ clock # None \/ anonymous
|
||||
|
||||
Init ==
|
||||
/\ server = [t \in Turns |-> "new"]
|
||||
/\ connected = TRUE
|
||||
/\ disconnected = FALSE
|
||||
/\ wire = <<>>
|
||||
/\ open = {}
|
||||
/\ closed = {}
|
||||
/\ fenced = {}
|
||||
/\ latest = None
|
||||
/\ clock = None
|
||||
/\ generation = 0
|
||||
/\ anonymous = FALSE
|
||||
/\ recoverySeen = FALSE
|
||||
/\ readPhase = "none"
|
||||
/\ requestTurn = None
|
||||
/\ requestGeneration = 0
|
||||
/\ snapshotCompleted = {}
|
||||
/\ snapshotActive = None
|
||||
/\ snapshotObserved = {}
|
||||
/\ snapshotPending = FALSE
|
||||
/\ learned = {}
|
||||
/\ collateral = {}
|
||||
/\ partialRecoveryPreserved = TRUE
|
||||
/\ lastAction = "init"
|
||||
|
||||
Enqueue(kind, t) ==
|
||||
IF connected THEN Append(wire, [kind |-> kind, turn |-> t]) ELSE wire
|
||||
|
||||
Start(t) ==
|
||||
/\ server[t] = "new"
|
||||
/\ t = A \/ server[A] = "done"
|
||||
/\ server' = [server EXCEPT ![t] = "running"]
|
||||
/\ wire' = Enqueue("running", t)
|
||||
/\ lastAction' = IF t = A THEN "server-start-A" ELSE "server-start-B"
|
||||
/\ UNCHANGED <<connected, disconnected, open, closed, fenced, latest, clock,
|
||||
generation, anonymous, recoverySeen, readPhase, requestTurn,
|
||||
requestGeneration, snapshotCompleted, snapshotActive,
|
||||
snapshotObserved, snapshotPending, learned, collateral, partialRecoveryPreserved>>
|
||||
|
||||
Finish(t) ==
|
||||
/\ server[t] = "running"
|
||||
/\ server' = [server EXCEPT ![t] = "done"]
|
||||
/\ wire' = Enqueue("end", t)
|
||||
/\ lastAction' = IF t = A THEN "server-finish-A" ELSE "server-finish-B"
|
||||
/\ UNCHANGED <<connected, disconnected, open, closed, fenced, latest, clock,
|
||||
generation, anonymous, recoverySeen, readPhase, requestTurn,
|
||||
requestGeneration, snapshotCompleted, snapshotActive,
|
||||
snapshotObserved, snapshotPending, learned, collateral, partialRecoveryPreserved>>
|
||||
|
||||
Disconnect ==
|
||||
/\ connected /\ ~disconnected
|
||||
/\ connected' = FALSE
|
||||
/\ disconnected' = TRUE
|
||||
/\ wire' = <<>>
|
||||
/\ lastAction' = "disconnect"
|
||||
/\ UNCHANGED <<server, open, closed, fenced, latest, clock, generation,
|
||||
anonymous, recoverySeen, readPhase, requestTurn, requestGeneration,
|
||||
snapshotCompleted, snapshotActive, snapshotObserved, snapshotPending, learned,
|
||||
collateral, partialRecoveryPreserved>>
|
||||
|
||||
Reconnect ==
|
||||
/\ ~connected /\ disconnected
|
||||
/\ connected' = TRUE
|
||||
/\ wire' = IF server[B] = "running" THEN <<[kind |-> "running", turn |-> B]>>
|
||||
ELSE IF server[A] = "running" THEN <<[kind |-> "running", turn |-> A]>>
|
||||
ELSE <<>>
|
||||
/\ readPhase' = IF Active THEN "requested" ELSE "none"
|
||||
/\ requestTurn' = latest
|
||||
/\ requestGeneration' = generation
|
||||
/\ lastAction' = "reconnect-and-request"
|
||||
/\ UNCHANGED <<server, disconnected, open, closed, fenced, latest, clock,
|
||||
generation, anonymous, recoverySeen, snapshotCompleted,
|
||||
snapshotActive, snapshotObserved, snapshotPending, learned, collateral,
|
||||
partialRecoveryPreserved>>
|
||||
|
||||
Receive ==
|
||||
/\ connected /\ Len(wire) > 0
|
||||
/\ LET m == Head(wire)
|
||||
ignored == m.turn \in fenced \/ (m.kind = "running" /\ m.turn \in closed)
|
||||
IN /\ wire' = Tail(wire)
|
||||
/\ IF ignored
|
||||
THEN UNCHANGED <<open, closed, latest, clock, generation, anonymous>>
|
||||
ELSE IF m.kind = "running"
|
||||
THEN /\ open' = open \cup {m.turn}
|
||||
/\ latest' = m.turn
|
||||
/\ clock' = m.turn
|
||||
/\ generation' = generation + 1
|
||||
/\ anonymous' = FALSE
|
||||
/\ UNCHANGED closed
|
||||
ELSE /\ open' = open \ {m.turn}
|
||||
/\ closed' = closed \cup {m.turn}
|
||||
/\ clock' = IF latest = None \/ latest = m.turn THEN None ELSE clock
|
||||
/\ anonymous' = IF latest = None \/ latest = m.turn THEN FALSE ELSE anonymous
|
||||
/\ UNCHANGED <<latest, generation>>
|
||||
/\ readPhase' = IF ~ignored /\ m.kind = "end" /\ readPhase \in {"requested", "ready"}
|
||||
THEN "requested" ELSE readPhase
|
||||
/\ lastAction' = IF m.kind = "running"
|
||||
THEN IF m.turn = A THEN "receive-running-A" ELSE "receive-running-B"
|
||||
ELSE IF m.turn = A THEN "receive-end-A" ELSE "receive-end-B"
|
||||
/\ UNCHANGED <<server, connected, disconnected, fenced, recoverySeen,
|
||||
requestTurn, requestGeneration, snapshotCompleted,
|
||||
snapshotActive, snapshotObserved, snapshotPending, learned, collateral,
|
||||
partialRecoveryPreserved>>
|
||||
|
||||
EndAnonymousRecovery ==
|
||||
/\ connected /\ anonymous /\ server[B] = "done"
|
||||
/\ closed' = closed \cup open \cup (IF latest = None THEN {} ELSE {latest})
|
||||
/\ open' = {}
|
||||
/\ latest' = None
|
||||
/\ clock' = None
|
||||
/\ anonymous' = FALSE
|
||||
/\ lastAction' = "end-anonymous-recovery"
|
||||
/\ UNCHANGED <<server, connected, disconnected, wire, fenced, generation,
|
||||
recoverySeen, readPhase, requestTurn, requestGeneration,
|
||||
snapshotCompleted, snapshotActive, snapshotObserved, snapshotPending,
|
||||
learned, collateral, partialRecoveryPreserved>>
|
||||
|
||||
TypeOK ==
|
||||
/\ server \in [Turns -> {"new", "running", "done"}]
|
||||
/\ connected \in BOOLEAN /\ disconnected \in BOOLEAN
|
||||
/\ \A i \in 1..Len(wire) : wire[i] \in Frames
|
||||
/\ open \subseteq Turns /\ closed \subseteq Turns /\ fenced \subseteq Turns
|
||||
/\ latest \in Turns \cup {None} /\ clock \in Turns \cup {None}
|
||||
/\ generation \in 0..4 /\ requestGeneration \in 0..4
|
||||
/\ anonymous \in BOOLEAN /\ recoverySeen \in BOOLEAN
|
||||
/\ readPhase \in {"none", "requested", "ready", "handled"}
|
||||
/\ requestTurn \in Turns \cup {None}
|
||||
/\ snapshotCompleted \subseteq Turns /\ snapshotObserved \subseteq Turns
|
||||
/\ snapshotActive \in Turns \cup {None} /\ snapshotPending \in BOOLEAN
|
||||
/\ learned \subseteq Turns /\ collateral \subseteq Turns
|
||||
/\ partialRecoveryPreserved \in BOOLEAN
|
||||
|
||||
ExplicitCompletionsSettle == learned \cap open = {}
|
||||
NoOlderCompletionClearsNewer == collateral = {}
|
||||
PartialCompletionPreservesRecovery == partialRecoveryPreserved
|
||||
|
||||
Quiescent == server[A] = "done" /\ server[B] = "done" /\ connected /\ ~anonymous
|
||||
EventuallyIdle == [] (Quiescent => <>[] ~Active)
|
||||
|
||||
=============================================================================
|
||||
@@ -0,0 +1,56 @@
|
||||
# Full-page lifecycle observation: bounded verification
|
||||
|
||||
These are handwritten, source-aligned finite abstractions, **not checked TypeScript refinements or an all-system/compositional liveness theorem**. Run `run_tlc.py --implementation-root <repository-root>` to record the actual source snapshot. Review models and source mapping together when implementation changes.
|
||||
|
||||
## Current source mapping
|
||||
|
||||
`useReconnectRuns` computes pure cache eligibility, publishes an eligible cache, then unconditionally calls `settleCompletedRunLifecycle` for a fresh, nonaborted full page. Explicit IDs do not authorize whole-snapshot adoption, content fencing or anonymous-recovery clearing. Only an unmounted, eligible, idle response gets background canonical adoption. Mounted transcripts remain the sole mounted whole-snapshot actor. Fragment handoff is separate.
|
||||
|
||||
| Source anchor | Abstraction |
|
||||
| --- | --- |
|
||||
| `useReconnectRuns`: unsettled-chat jobs, captured generation/turn, post-await abort | `UsageLifecycle.Reconnect`, `NewRead`, disconnected R cancellation and `Process` eligibility |
|
||||
| Pure preflight before cache publication | `Process.canApply/canCache/cacheInstall` use the pre-transition ledger, before completion settlement |
|
||||
| Fresh full-page explicit lifecycle settlement | `Process.lifecycle` applies even with an owner and rejected cache admission |
|
||||
| Idle-only unmounted whole-snapshot adoption | `ownerWhole` versus `backgroundWhole`; never both |
|
||||
| `useNanobotStream`: own-read/non-seed cache handoff versus exposed fragment IDs | `ownerWhole`, separate `accepted` and `exposed`; no fragment-gap bridging proof |
|
||||
| Owner/disposal/supersession guards and synchronous cache install | `mounted` separate from `selected`, canceled H after publication, `CacheHandoff.ownReadSuperseded/owner` |
|
||||
| `ClientRunLedger.completeTurns` | Exact named `open/closed/clock` settlement; content coverage alone extends `fenced`; lifecycle coverage preserves anonymous recovery |
|
||||
|
||||
`ClientRunLedger` owns observed client run state. `completeTurns` unifies explicit canonical completed-ID closure, not every supported completion transition. Live terminal observations and legacy observed-turn settlement retain their own supported transitions; `UsageLifecycle.Receive` is separate. The Gateway remains execution authority.
|
||||
|
||||
Cache publication and its synchronous owner callback are one model action; navigation cannot interleave within it. The resulting ledger combines authorized owner content closure with idempotent reconnect lifecycle closure. This is not an instruction-by-instruction proof of callback reentrancy or notification ordering.
|
||||
|
||||
## Dynamic lifecycle and handoff cases
|
||||
|
||||
| Config | Module | Expected result | Reference distinct states |
|
||||
| --- | --- | --- | ---: |
|
||||
| `lifecycle-fullpage-dynamic` | `UsageLifecycle.tla` | exit 0, no error, queue 0 | 114,597 |
|
||||
| `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 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 = {}`.
|
||||
|
||||
The conditional temporal property is:
|
||||
|
||||
```tla
|
||||
Quiescent == connected /\ (\A c \in Chats : Done(c) = Turns /\ ~ledger[c].anonymous)
|
||||
EventuallyIdle == [] (Quiescent => <>[] (\A c \in Chats : ~Active(c)))
|
||||
```
|
||||
|
||||
Weak fairness covers reconnect, an already-scheduled hook effect, existing wire delivery and capture/processing of an already-started read. There is no fairness for starting/finishing future server turns, ending anonymous recovery, retries, fragment bridging or creation of later session-update reads. There is no state/action constraint, symmetry reduction or depth cutoff.
|
||||
|
||||
The handoff cases start at a source-reachable checkpoint: observed turn 1, lost terminal, fresh shared R/H read completing 1 and either active/pending 2 or an idle tail. They cover both transcript admission outcomes, two switches, canceled/superseded own callbacks, raw settlement, liveness, sole canonical actor and an unsettled other-chat sentinel. They check eligible handoff ownership, not the entire dynamic graph or transcript text projection.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,212 @@
|
||||
------------------------- MODULE UsageLifecycle -------------------------
|
||||
EXTENDS Naturals, FiniteSets, Sequences, TLC
|
||||
\* Per-chat server/ledger composition, plus dynamic selected vs actually mounted
|
||||
\* transcript and separate reconnect/own-read continuations. H/R captures are an
|
||||
\* independent-producer OVERAPPROXIMATION: concrete sharing/abort is partitioned
|
||||
\* into SharedRequests, not asserted equivalent. A counterexample needs mapping.
|
||||
\* 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
|
||||
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]
|
||||
EmptyLedger == [open |-> {}, closed |-> {}, fenced |-> {}, latest |-> 0,
|
||||
clock |-> 0, generation |-> 0, anonymous |-> FALSE,
|
||||
recoverySeen |-> FALSE, learned |-> {}]
|
||||
VARIABLES server, wire, ledger, reads, needHook, selected, mounted, switches,
|
||||
connected, outages, safe
|
||||
vars == <<server, wire, ledger, reads, needHook, selected, mounted, switches,
|
||||
connected, outages, safe>>
|
||||
Active(c) == ledger[c].open # {} \/ ledger[c].clock # 0 \/ ledger[c].anonymous
|
||||
Done(c) == {t \in Turns : server[c][t] = 2}
|
||||
Running(c) == {t \in Turns : server[c][t] = 1}
|
||||
Seen(c) == {t \in Turns : server[c][t] # 0}
|
||||
NewRead(c) == [EmptyRead EXCEPT !.phase = 1,
|
||||
!.generation = ledger[c].generation, !.turn = ledger[c].latest]
|
||||
Init ==
|
||||
/\ server = [c \in Chats |-> [t \in Turns |-> 0]]
|
||||
/\ wire = [c \in Chats |-> <<>>]
|
||||
/\ ledger = [c \in Chats |-> EmptyLedger]
|
||||
/\ reads = [c \in Chats |-> [r \in Readers |-> EmptyRead]]
|
||||
/\ needHook = {}
|
||||
/\ selected = 0 /\ mounted = 0 /\ switches = 0 /\ connected = TRUE /\ outages = 0
|
||||
/\ safe = [collateral |-> TRUE, partial |-> TRUE, lifecycle |-> TRUE,
|
||||
activeAdoption |-> TRUE, cacheOrder |-> TRUE, handoff |-> TRUE, soleActor |-> TRUE]
|
||||
Start(c,t) ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ server[c][t] = 0 /\ (IF t = 1 THEN TRUE ELSE server[c][t-1] = 2)
|
||||
/\ server' = [server EXCEPT ![c][t] = 1]
|
||||
/\ wire' = IF connected THEN [wire EXCEPT ![c] = Append(@, [kind |-> 1, turn |-> t])] ELSE wire
|
||||
/\ UNCHANGED <<ledger, reads, needHook, selected, mounted, switches, connected, outages, safe>>
|
||||
Finish(c,t) ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ server[c][t] = 1
|
||||
/\ server' = [server EXCEPT ![c][t] = 2]
|
||||
/\ wire' = IF connected THEN [wire EXCEPT ![c] = Append(@, [kind |-> 2, turn |-> t])] ELSE wire
|
||||
/\ UNCHANGED <<ledger, reads, needHook, selected, mounted, switches, connected, outages, safe>>
|
||||
Disconnect ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ connected /\ outages < MaxOutages
|
||||
/\ connected' = FALSE /\ outages' = outages+1
|
||||
/\ wire' = [c \in Chats |-> <<>>]
|
||||
/\ reads' = [c \in Chats |-> [reads[c] EXCEPT !["R"] = EmptyRead]]
|
||||
/\ UNCHANGED <<server, ledger, needHook, selected, mounted, switches, safe>>
|
||||
Reconnect ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ ~connected /\ connected' = TRUE
|
||||
/\ wire' = [c \in Chats |-> IF Running(c) = {} THEN <<>> ELSE
|
||||
<<[kind |-> 1, turn |-> CHOOSE t \in Running(c) : TRUE]>>]
|
||||
/\ reads' = [c \in Chats |-> [reads[c] EXCEPT !["R"] = IF Active(c) THEN NewRead(c) ELSE EmptyRead]]
|
||||
/\ needHook' = IF selected # 0 THEN needHook \cup {selected} ELSE needHook
|
||||
/\ UNCHANGED <<server, ledger, selected, switches, outages, safe>>
|
||||
Switch(c) ==
|
||||
/\ c \in Chats \cup {0} /\ c # selected /\ switches < MaxSwitches
|
||||
/\ selected' = c /\ mounted' = 0 /\ switches' = switches+1
|
||||
/\ reads' = IF selected = 0 THEN reads ELSE [reads EXCEPT ![selected]["H"] = EmptyRead]
|
||||
/\ needHook' = IF c = 0 THEN {} ELSE {c}
|
||||
/\ UNCHANGED <<server, wire, ledger, connected, outages, safe>>
|
||||
HookEffect ==
|
||||
/\ selected # 0 /\ selected \in needHook
|
||||
/\ reads' = [reads EXCEPT ![selected]["H"] = NewRead(selected)]
|
||||
/\ mounted' = selected
|
||||
/\ needHook' = needHook \ {selected}
|
||||
/\ UNCHANGED <<server, wire, ledger, selected, switches, connected, outages, safe>>
|
||||
Receive(c) ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ connected /\ Len(wire[c]) > 0
|
||||
/\ LET m == Head(wire[c])
|
||||
l == ledger[c]
|
||||
ignored == m.turn \in l.fenced \/ (m.kind = 1 /\ m.turn \in l.closed)
|
||||
nl == IF ignored THEN l ELSE IF m.kind = 1 THEN
|
||||
[l EXCEPT !.open = @ \cup {m.turn}, !.latest = m.turn, !.clock = m.turn,
|
||||
!.generation = @+1, !.anonymous = FALSE]
|
||||
ELSE [l EXCEPT !.open = @ \ {m.turn}, !.closed = @ \cup {m.turn},
|
||||
!.clock = IF l.latest = 0 \/ l.latest = m.turn THEN 0 ELSE @,
|
||||
!.anonymous = IF l.latest = 0 \/ l.latest = m.turn THEN FALSE ELSE @]
|
||||
IN /\ ledger' = [ledger EXCEPT ![c] = nl]
|
||||
/\ 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]
|
||||
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) ==
|
||||
/\ 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,
|
||||
![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]
|
||||
/\ UNCHANGED <<server, wire, ledger, needHook, selected, mounted, switches, connected, outages, safe>>
|
||||
Process(c,r,accepted,exposed) ==
|
||||
/\ 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
|
||||
canApply == l.open \subseteq (completed \cup l.fenced) /\
|
||||
(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
|
||||
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
|
||||
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
|
||||
nextAnon == IF adopt THEN FALSE ELSE l.anonymous
|
||||
nl == [l EXCEPT !.open = nextOpen,
|
||||
!.closed = IF doSettle THEN @ \cup completed ELSE @,
|
||||
!.fenced = IF whole THEN @ \cup completed ELSE @,
|
||||
!.clock = nextClock, !.anonymous = nextAnon,
|
||||
!.learned = @ \cup (IF ~q.fragment \/ fragmentReady THEN completed ELSE {})]
|
||||
IN /\ ledger' = [ledger EXCEPT ![c] = nl]
|
||||
/\ reads' = [reads EXCEPT ![c][r] = EmptyRead,
|
||||
![c]["H"] = IF cacheInstall \/ r = "H" THEN EmptyRead ELSE reads[c]["H"]]
|
||||
/\ safe' = [safe EXCEPT
|
||||
!.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),
|
||||
!.cacheOrder = @ /\ (r # "R" \/ ~adopt \/ canCache),
|
||||
!.handoff = @ /\ (~doSettle \/ 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
|
||||
/\ ledger' = [ledger EXCEPT ![c].anonymous = TRUE, ![c].recoverySeen = TRUE]
|
||||
/\ UNCHANGED <<server, wire, reads, needHook, selected, mounted, switches, connected, outages, safe>>
|
||||
EndRecovery(c) ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ connected /\ ledger[c].anonymous /\ Done(c) = Turns
|
||||
/\ ledger' = [ledger EXCEPT ![c].closed = @ \cup ledger[c].open \cup
|
||||
(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)
|
||||
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)
|
||||
Spec == Init /\ [][Next]_vars
|
||||
FairSpec == Spec /\ WF_vars(Reconnect) /\ WF_vars(HookEffect) /\
|
||||
(\A c \in Chats : WF_vars(Receive(c))) /\
|
||||
(\A c \in Chats, r \in Readers : WF_vars(CaptureAny(c,r)) /\ WF_vars(ProcessAny(c,r)))
|
||||
TypeOK ==
|
||||
/\ server \in [Chats -> [Turns -> 0..2]] /\ selected \in Chats \cup {0}
|
||||
/\ mounted \in Chats \cup {0} /\ (mounted # 0 => mounted = selected)
|
||||
/\ switches \in 0..MaxSwitches /\ outages \in 0..MaxOutages /\ connected \in BOOLEAN
|
||||
/\ needHook \subseteq Chats
|
||||
/\ \A c \in Chats : /\ ledger[c].open \subseteq Turns /\ ledger[c].closed \subseteq Turns
|
||||
/\ 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.
|
||||
RawExplicitCompletionsSettle == \A c \in Chats : ledger[c].learned \cap ledger[c].open = {}
|
||||
ExplicitCompletionsSettle == RawExplicitCompletionsSettle
|
||||
NoOlderCompletionClearsNewer == safe.collateral
|
||||
PartialCompletionPreservesRecovery == safe.partial
|
||||
LifecycleOnlyPreservesContentAndRecovery == safe.lifecycle
|
||||
ActiveUnmountedSnapshotIsNotAdopted == safe.activeAdoption
|
||||
CachePrecedesIdleNotification == safe.cacheOrder
|
||||
ExplicitCompletionHandoffSettles == safe.handoff
|
||||
SoleCanonicalActor == safe.soleActor
|
||||
Quiescent == connected /\ (\A c \in Chats : Done(c) = Turns /\ ~ledger[c].anonymous)
|
||||
EventuallyIdle == [] (Quiescent => <>[] (\A c \in Chats : ~Active(c)))
|
||||
=============================================================================
|
||||
@@ -0,0 +1,3 @@
|
||||
SPECIFICATION Spec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS ExplicitCompletionsSettle NoOlderCompletionClearsNewer PartialCompletionPreservesRecovery OtherChatUnchanged LifecycleOnlyPreservesContentAndRecovery ClosedRunningCannotReopen LateLifecycleContentSurvives
|
||||
@@ -0,0 +1,7 @@
|
||||
CONSTANT ActiveTail = TRUE
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS OtherChatUnchanged StaleOwnReadCannotOverwrite
|
||||
INVARIANTS ExplicitCompletionsSettle SoleCanonicalActor
|
||||
PROPERTY EventuallyIdle
|
||||
INVARIANT RawExplicitCompletionsSettle
|
||||
@@ -0,0 +1,7 @@
|
||||
CONSTANT ActiveTail = FALSE
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS OtherChatUnchanged StaleOwnReadCannotOverwrite
|
||||
INVARIANTS ExplicitCompletionsSettle SoleCanonicalActor
|
||||
PROPERTY EventuallyIdle
|
||||
INVARIANT RawExplicitCompletionsSettle
|
||||
@@ -0,0 +1,19 @@
|
||||
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
|
||||
@@ -0,0 +1,20 @@
|
||||
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
|
||||
@@ -0,0 +1,20 @@
|
||||
CONSTANTS
|
||||
NChats = 1
|
||||
NTurns = 2
|
||||
MaxOutages = 2
|
||||
MaxSwitches = 2
|
||||
AllowFailures = FALSE
|
||||
Fragments = FALSE
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS
|
||||
TypeOK
|
||||
NoOlderCompletionClearsNewer
|
||||
PartialCompletionPreservesRecovery
|
||||
LifecycleOnlyPreservesContentAndRecovery
|
||||
ActiveUnmountedSnapshotIsNotAdopted
|
||||
CachePrecedesIdleNotification
|
||||
SoleCanonicalActor
|
||||
ExplicitCompletionHandoffSettles
|
||||
PROPERTY EventuallyIdle
|
||||
INVARIANT RawExplicitCompletionsSettle
|
||||
@@ -0,0 +1,20 @@
|
||||
CONSTANTS
|
||||
NChats = 2
|
||||
NTurns = 2
|
||||
MaxOutages = 2
|
||||
MaxSwitches = 2
|
||||
AllowFailures = FALSE
|
||||
Fragments = FALSE
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS
|
||||
TypeOK
|
||||
NoOlderCompletionClearsNewer
|
||||
PartialCompletionPreservesRecovery
|
||||
LifecycleOnlyPreservesContentAndRecovery
|
||||
ActiveUnmountedSnapshotIsNotAdopted
|
||||
CachePrecedesIdleNotification
|
||||
SoleCanonicalActor
|
||||
ExplicitCompletionHandoffSettles
|
||||
PROPERTY EventuallyIdle
|
||||
INVARIANT RawExplicitCompletionsSettle
|
||||
@@ -0,0 +1,8 @@
|
||||
CONSTANTS NChats = 1
|
||||
MaxOutages = 2
|
||||
MaxSwitches = 2
|
||||
MaxInvalidations = 1
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS TypeOK NoWrongKeyDelivery NoIneligibleConsumerDelivery NoOrphanedNetwork PointerHasRequest SharingUsesCurrentIdentity
|
||||
PROPERTY EventuallyRequestsDrain
|
||||
@@ -0,0 +1,8 @@
|
||||
CONSTANTS NChats = 2
|
||||
MaxOutages = 2
|
||||
MaxSwitches = 2
|
||||
MaxInvalidations = 0
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS TypeOK NoWrongKeyDelivery NoIneligibleConsumerDelivery NoOrphanedNetwork PointerHasRequest SharingUsesCurrentIdentity
|
||||
PROPERTY EventuallyRequestsDrain
|
||||
@@ -0,0 +1,8 @@
|
||||
CONSTANTS NChats = 2
|
||||
MaxOutages = 2
|
||||
MaxSwitches = 2
|
||||
MaxInvalidations = 1
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS TypeOK NoWrongKeyDelivery NoIneligibleConsumerDelivery NoOrphanedNetwork PointerHasRequest SharingUsesCurrentIdentity
|
||||
PROPERTY EventuallyRequestsDrain
|
||||
@@ -0,0 +1,16 @@
|
||||
SPECIFICATION RevisedSpec
|
||||
CONSTANTS
|
||||
A = A
|
||||
B = B
|
||||
Mounted = TRUE
|
||||
IncludeFragments = TRUE
|
||||
INVARIANTS
|
||||
RevisedTypeOK
|
||||
ExplicitCompletionsSettle
|
||||
NoOlderCompletionClearsNewer
|
||||
PartialCompletionPreservesRecovery
|
||||
LifecycleOnlyPreservesContentAndRecovery
|
||||
MountedFragmentRequiresAcceptance
|
||||
ActiveUnmountedSnapshotIsNotAdopted
|
||||
CachePrecedesIdleNotification
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,9 @@
|
||||
SPECIFICATION RevisedFairSpec
|
||||
CONSTANTS
|
||||
A = A
|
||||
B = B
|
||||
Mounted = TRUE
|
||||
IncludeFragments = FALSE
|
||||
INVARIANT RevisedTypeOK
|
||||
PROPERTY EventuallyIdle
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,16 @@
|
||||
SPECIFICATION RevisedSpec
|
||||
CONSTANTS
|
||||
A = A
|
||||
B = B
|
||||
Mounted = TRUE
|
||||
IncludeFragments = FALSE
|
||||
INVARIANTS
|
||||
RevisedTypeOK
|
||||
ExplicitCompletionsSettle
|
||||
NoOlderCompletionClearsNewer
|
||||
PartialCompletionPreservesRecovery
|
||||
LifecycleOnlyPreservesContentAndRecovery
|
||||
MountedFragmentRequiresAcceptance
|
||||
ActiveUnmountedSnapshotIsNotAdopted
|
||||
CachePrecedesIdleNotification
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,16 @@
|
||||
SPECIFICATION RevisedSpec
|
||||
CONSTANTS
|
||||
A = A
|
||||
B = B
|
||||
Mounted = FALSE
|
||||
IncludeFragments = TRUE
|
||||
INVARIANTS
|
||||
RevisedTypeOK
|
||||
ExplicitCompletionsSettle
|
||||
NoOlderCompletionClearsNewer
|
||||
PartialCompletionPreservesRecovery
|
||||
LifecycleOnlyPreservesContentAndRecovery
|
||||
MountedFragmentRequiresAcceptance
|
||||
ActiveUnmountedSnapshotIsNotAdopted
|
||||
CachePrecedesIdleNotification
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,9 @@
|
||||
SPECIFICATION RevisedFairSpec
|
||||
CONSTANTS
|
||||
A = A
|
||||
B = B
|
||||
Mounted = FALSE
|
||||
IncludeFragments = FALSE
|
||||
INVARIANT RevisedTypeOK
|
||||
PROPERTY EventuallyIdle
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,16 @@
|
||||
SPECIFICATION RevisedSpec
|
||||
CONSTANTS
|
||||
A = A
|
||||
B = B
|
||||
Mounted = FALSE
|
||||
IncludeFragments = FALSE
|
||||
INVARIANTS
|
||||
RevisedTypeOK
|
||||
ExplicitCompletionsSettle
|
||||
NoOlderCompletionClearsNewer
|
||||
PartialCompletionPreservesRecovery
|
||||
LifecycleOnlyPreservesContentAndRecovery
|
||||
MountedFragmentRequiresAcceptance
|
||||
ActiveUnmountedSnapshotIsNotAdopted
|
||||
CachePrecedesIdleNotification
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check bounded current-policy 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
|
||||
|
||||
|
||||
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"),
|
||||
}
|
||||
REVISED_CASES = (
|
||||
"revised-mounted", "revised-unmounted",
|
||||
"revised-mounted-fragments", "revised-unmounted-fragments",
|
||||
"revised-mounted-live", "revised-unmounted-live",
|
||||
)
|
||||
USAGE_CASES = (
|
||||
"requests-two-no-invalidations", "requests-one", "authority",
|
||||
"lifecycle-fullpage-dynamic", "handoff-fullpage-active", "handoff-fullpage-idle",
|
||||
)
|
||||
# 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
|
||||
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,
|
||||
)},
|
||||
}
|
||||
COUNTS = re.compile(
|
||||
r"([\d,]+) states generated, ([\d,]+) distinct states found, ([\d,]+) states left on queue"
|
||||
)
|
||||
IMPLEMENTATION_FILES = (
|
||||
"webui/src/hooks/useReconnectRuns.ts", "webui/src/hooks/useNanobotStream.ts",
|
||||
"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",
|
||||
)
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
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("--java", default="java")
|
||||
parser.add_argument("--workers", type=int, default=2)
|
||||
parser.add_argument("--heap-mb", type=int, default=1536)
|
||||
parser.add_argument("--timeout-seconds", type=int, default=600, help="Per-case hard timeout")
|
||||
args = parser.parse_args()
|
||||
jar = args.jar.resolve(strict=True)
|
||||
if args.workers < 1 or args.heap_mb < 64 or args.timeout_seconds < 1:
|
||||
parser.error("workers/timeout must be positive and heap must be at least 64 MiB")
|
||||
checkout = next((path for path in SOURCE.parents if (path / ".git").exists()), SOURCE)
|
||||
if args.output_root is None:
|
||||
output = Path(tempfile.mkdtemp(prefix="nanobot-turn-sync-tlc-"))
|
||||
else:
|
||||
output = args.output_root.resolve()
|
||||
if output == checkout or checkout in output.parents:
|
||||
parser.error("output-root must be outside the checkout")
|
||||
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",
|
||||
"jar": {"path": str(jar), "sha256": sha256(jar)},
|
||||
"source_sha256": {path.name: sha256(path) for path in inputs},
|
||||
"results": [],
|
||||
}
|
||||
if args.implementation_root:
|
||||
implementation = args.implementation_root.resolve(strict=True)
|
||||
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",
|
||||
}
|
||||
print(f"Evidence: {output}", flush=True)
|
||||
unexpected = 0
|
||||
selected = args.cases or (LIMIT_CASES if args.limits else REVISED_CASES + USAGE_CASES)
|
||||
for case in selected:
|
||||
case_dir = output / case
|
||||
case_dir.mkdir()
|
||||
# TLC can create trace modules on failure. Run an immutable input copy
|
||||
# outside the checkout so even unexpected outputs stay task-owned.
|
||||
for path in inputs:
|
||||
shutil.copyfile(path, case_dir / path.name)
|
||||
module = MODULES[case]
|
||||
temp = case_dir / "temp"
|
||||
temp.mkdir()
|
||||
command = [
|
||||
args.java, f"-Xmx{args.heap_mb}m", "-XX:+UseParallelGC", f"-Djava.io.tmpdir={temp}", "-cp", str(jar),
|
||||
"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:
|
||||
run = subprocess.run(
|
||||
command, cwd=case_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
encoding="utf-8", errors="replace", timeout=args.timeout_seconds, check=False,
|
||||
)
|
||||
actual_exit, text = run.returncode, run.stdout
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
timed_out = True
|
||||
actual_exit = None
|
||||
text = exc.stdout or b""
|
||||
if isinstance(text, bytes):
|
||||
text = text.decode("utf-8", errors="replace")
|
||||
except OSError as exc:
|
||||
actual_exit, text = None, str(exc)
|
||||
(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
|
||||
result = {
|
||||
"case": case, "status": status,
|
||||
"category": ("missing-evidence-limit" if case in LIMIT_CASES 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,
|
||||
"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,
|
||||
"command": command, "cwd": str(case_dir), "log": str(case_dir / "tlc.log"),
|
||||
}
|
||||
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(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
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user