fix(webui): reconcile running turns on reconnect (#6715)
* fix(webui): reconcile running turns on reconnect * test(webui): verify only the current turn-sync policy
This commit is contained in:
1 parent
b453de9cf6
commit
094bac0dc3
25 files changed
+455
-226
No files matched your search
@@ -9,6 +9,7 @@ interface TurnRecord {
|
||||
// Only openOrder marks unsettled ownership; a timestamp alone does not.
|
||||
openOrder: number | null;
|
||||
startedAt: number | null;
|
||||
needsLiveCheck: boolean;
|
||||
}
|
||||
|
||||
interface ChatRecord {
|
||||
@@ -59,6 +60,7 @@ type Command =
|
||||
| { kind: "transport-lost" }
|
||||
| { kind: "local-stop" | "forget"; chatId: string }
|
||||
| { kind: "fence" | "settle-completed-lifecycle"; chatId: string; completedTurnIds: readonly string[] }
|
||||
| { kind: "reattach"; chatId: string; liveTurnIds: readonly string[] }
|
||||
| { kind: "restore-pending"; chatId: string; generation: number; turnId: string | null };
|
||||
|
||||
export type RunEffect =
|
||||
@@ -176,6 +178,7 @@ export class ClientRunLedger {
|
||||
case "transport-lost":
|
||||
for (const chat of this.chats.values()) {
|
||||
for (const turn of chat.turns.values()) {
|
||||
turn.needsLiveCheck = turn.openOrder !== null && (!turn.delivery || turn.delivery.phase === "accepted");
|
||||
if (turn.delivery?.phase === "sent") {
|
||||
turn.delivery = { phase: "unknown", role: turn.delivery.role };
|
||||
}
|
||||
@@ -207,6 +210,20 @@ export class ClientRunLedger {
|
||||
chat.anonymousActive = command.turnId === null;
|
||||
break;
|
||||
}
|
||||
case "reattach": {
|
||||
const chat = this.chats.get(command.chatId);
|
||||
if (!chat) break;
|
||||
const live = new Set(command.liveTurnIds);
|
||||
const retired: string[] = [];
|
||||
for (const [turnId, turn] of chat.turns) {
|
||||
if (turn.needsLiveCheck && !live.has(turnId)) retired.push(turnId);
|
||||
turn.needsLiveCheck = false;
|
||||
}
|
||||
// Absence only retires previously observed owners, not new/uncertain sends.
|
||||
// It does not report an outcome or claim that the transcript is complete.
|
||||
if (retired.length > 0) this.completeTurns(command.chatId, retired, "lifecycle", effects);
|
||||
break;
|
||||
}
|
||||
case "fence":
|
||||
case "settle-completed-lifecycle":
|
||||
this.completeTurns(command.chatId, command.completedTurnIds,
|
||||
@@ -391,7 +408,7 @@ export class ClientRunLedger {
|
||||
private ensureTurn(chat: ChatRecord, turnId: string): TurnRecord {
|
||||
let turn = chat.turns.get(turnId);
|
||||
if (!turn) {
|
||||
turn = { delivery: null, openOrder: null, startedAt: null };
|
||||
turn = { delivery: null, openOrder: null, startedAt: null, needsLiveCheck: false };
|
||||
chat.turns.set(turnId, turn);
|
||||
}
|
||||
return turn;
|
||||
|
||||
@@ -1069,6 +1069,10 @@ export class NanobotClient {
|
||||
} else {
|
||||
this.knownChats.add(parsed.chat_id);
|
||||
}
|
||||
const live = parsed.live_turn_ids;
|
||||
if (Array.isArray(live) && live.every((id) => typeof id === "string" && id.length > 0)) {
|
||||
this.applyRunEffects(this.runs.transition({ kind: "reattach", chatId: parsed.chat_id, liveTurnIds: live }));
|
||||
}
|
||||
this.dispatch(parsed.chat_id, parsed);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1565,6 +1565,7 @@ export type InboundEvent =
|
||||
chat_id: string;
|
||||
request_id?: string;
|
||||
temporary?: boolean;
|
||||
live_turn_ids?: string[];
|
||||
recovery_state?: RecoveryState;
|
||||
usage?: TurnUsage;
|
||||
}
|
||||
|
||||
@@ -307,6 +307,50 @@ describe("reconnect across chat selection and transport generations", () => {
|
||||
state: { active: false, unsettled: false }, unsettled: [] });
|
||||
});
|
||||
|
||||
it.each(["failed", "fragment"] as const)("clears a completed run after reconnect with a %s history read", async (read) => {
|
||||
const h = harness();
|
||||
h.client.attach("alpha");
|
||||
act(() => h.running("alpha", "turn-1", 100));
|
||||
expect(h.client.getRunState("alpha").active).toBe(true);
|
||||
await h.reopen();
|
||||
await act(async () => {
|
||||
const pending = h.reads.at(-1)!;
|
||||
if (read === "failed") pending.fail(503);
|
||||
else pending.resolve({ ...history("alpha", []), page: {
|
||||
history_generation: "real-use", before_cursor: null, has_more_before: true,
|
||||
record_range: { turn: 1, start: 1, end: 2 },
|
||||
} });
|
||||
});
|
||||
expect(h.client.getRunState("alpha").active).toBe(true);
|
||||
act(() => {
|
||||
h.socket().receive({ event: "attached", chat_id: "alpha", live_turn_ids: [] });
|
||||
h.running("alpha", "turn-1", 100); // An older running frame was still on the bus.
|
||||
});
|
||||
expect(h.client.getRunState("alpha").active).toBe(false);
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("preserves a still-live owner and a newly submitted turn on reattach", async () => {
|
||||
const h = harness();
|
||||
h.client.attach("alpha");
|
||||
act(() => {
|
||||
h.running("alpha", "finished", 100);
|
||||
h.running("alpha", "still-live", 200);
|
||||
});
|
||||
await h.reopen();
|
||||
act(() => {
|
||||
h.client.sendMessage("alpha", "new submission", undefined, { turnId: "new" });
|
||||
h.socket().receive({ event: "attached", chat_id: "alpha", live_turn_ids: ["still-live"] });
|
||||
});
|
||||
expect(h.client.getRunState("alpha").latestTurnId).toBe("new");
|
||||
expect(h.client.isRunCompleted("alpha", "new")).toBe(false);
|
||||
act(() => h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "new" }));
|
||||
expect(h.client.getRunState("alpha").active).toBe(true);
|
||||
act(() => h.socket().receive({ event: "turn_end", chat_id: "alpha", turn_id: "still-live" }));
|
||||
expect(h.client.getRunState("alpha").active).toBe(false);
|
||||
h.close();
|
||||
});
|
||||
|
||||
it("recovers six chats beyond the read-concurrency limit after a failed page and repeated drops", async () => {
|
||||
const h = harness();
|
||||
const chats = Array.from({ length: 6 }, (_, index) => `chat-${index}`);
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Attach reconciliation: bounded verification
|
||||
|
||||
A disconnect can drop the only named terminal observation. Even if the socket reconnects, paged history may fail or omit that ID. The attach reply therefore reports **all live named owners for the attached chat**. It is an absence check for previously confirmed, still-open owners marked by transport loss, not a new source of ownership, transcript coverage, or completion events. This is a separate finite model from the history/cache partitions; it is not a checked refinement of the Gateway or TypeScript.
|
||||
|
||||
## Source boundary and checked behavior
|
||||
|
||||
| Boundary | `AttachReconciliation.tla` |
|
||||
| --- | --- |
|
||||
| `nanobot/webui/inbound_commands.py` trusted `attach`, metadata in `session_projection.py`, WebSocket writer in `nanobot/channels/websocket/runtime.py` | `Subscribe` precedes the asynchronous metadata wait; `EnqueueAttached` samples `Live` and enqueues in one step on the same FIFO as pushes. `Hydrate` is separate ordinary running evidence. |
|
||||
| `nanobot/session/webui_turns.py` delivery owners and `nanobot/webui/outbound_delivery.py` terminal/idle delivery | The named owner stays live while terminal persistence is in flight. Retirement removes it from live status for either persistence outcome; an incomplete transcript can remain without being reported as running by attach, hydration, or the session list. Named idle also retires the owner. `DeliverTerminal` selects the subscribers at retirement, after persistence returns. |
|
||||
| `webui/src/lib/nanobot-client.ts` socket replacement and `client-run-ledger.ts` ownership | `LoseTransport` marks only confirmed open names, including neither queued local work nor anonymous recovery. `Observe` closes and tombstones marked absent IDs; presence alone adds no owner. Ordinary running hydration/push can create one. `ReceiveOld` ignores a previous socket's callback, and `ReplayBuffered` checks that a delayed start/delta cannot reopen a tombstoned lifecycle. |
|
||||
| Paged HTTP recovery (`useReconnectRuns.ts` and the history models) | HTTP supplies no completion evidence in this partition. A failed read and a page missing the ID are equivalent for this check. The separate history models cover pages that supply completion evidence. |
|
||||
|
||||
`TypeOK` and `LifecycleSafety` check that no live name is closed; the exact marked/open absent IDs are closed and tombstoned without adding owners, clearing a surviving clock, changing independent anonymous/queued work, fencing content, or generating synthetic completion. Server turn 1 starts at a reachable checkpoint (confirmed on the old connection, with a potentially lagging duplicate running event). Turn 2 can start while turn 1's terminal projection is awaiting persistence or after it retires. Consequently a sample may contain both names, preserve a still-running name, report a newer name not yet observed, or omit an old name while the newer one is already open. An independent queued candidate can be present at the loss or submitted after it. One or two drops may occur, including during handshake or before writer delivery.
|
||||
|
||||
`EventuallyRetiredOwnersSettle` checks each name independently: if the socket stays healthy after reconnect and that named owner is retired, eventually the client has no open ownership for that name and never reopens it. A newly queued send, anonymous recovery, or a different still-running server turn need not settle for this to hold. If none of those independent activities remain, settlement removes the stale busy indicator. The ordering argument is that a retirement **before** the sample yields absence; a retirement **after** the sample still addresses the already-subscribed socket. A later loss marks again and requires a later healthy attach.
|
||||
|
||||
## Scope and fairness
|
||||
|
||||
The model checks one chat, two unique named server IDs and one independent unacknowledged local candidate, one callback slot from a previous socket, and one late lifecycle replay probe. There is one complete, trusted snapshot per reconnect; retaining a mark for a live name after that snapshot is immaterial because the next loss recomputes marks. The queue models current-socket enqueue and receive order, not transcript or send-queue internals. Terminal recipient selection, retirement and enqueue are one model step after persistence; named idle is modeled without a persistence gap. Current-socket running hydration samples and enqueues in one step; the model does not cover an older server-side hydration task publishing a stale status onto a replacement socket. The wire does not independently discard addressed frames while healthy. Matching, writer serialization and lifetime/ownership hooks in the implementation require separate source review and regression tests.
|
||||
|
||||
Weak fairness is for reconnect, subscribe, completing the metadata wait and enqueuing `attached`, ordinary hydration and processing a nonempty healthy writer. It permits finite delay or another loss at any point. No fairness is assumed for turn admission or completion, local/anonymous work, HTTP, stale callbacks, or another disconnect. Permanent outage, a reconnect with no subsequent healthy synchronization, malformed or missing attach evidence, authentication/host changes, unbounded workloads, cross-chat interactions, and transcript/text projection are outside this liveness claim. There is no state constraint, symmetry reduction, or depth cutoff. Terminal states can stutter (`CHECK_DEADLOCK FALSE`).
|
||||
|
||||
## Reproduce and evidence
|
||||
|
||||
From the repository root, run `python3 -B webui/verification/turn-sync/run_tlc.py --jar /path/to/verified-tla2tools.jar --case attach-reconciliation`. This case also runs by default. It allows up to two losses, including schedules with a single loss.
|
||||
|
||||
The reference run with TLC 2.19 generated 654,943 states and exhausted all 154,552 distinct states with no counterexample and an empty state queue.
|
||||
@@ -0,0 +1,146 @@
|
||||
----------------------- MODULE AttachReconciliation -----------------------
|
||||
EXTENDS Naturals, FiniteSets, Sequences
|
||||
CONSTANT MaxLosses
|
||||
|
||||
Turns == {1, 2}
|
||||
Local == 3
|
||||
Idle == 0
|
||||
\* Phase: 0 not admitted, 1 running, 2 awaiting terminal persistence,
|
||||
\* 3 retired/durable, 4 retired/incomplete, 5 retired via named idle.
|
||||
VARIABLES phase, socket, connection, wire, oldCallback, client, probed, safe
|
||||
vars == <<phase, socket, connection, wire, oldCallback, client, probed, safe>>
|
||||
Live == {t \in Turns : phase[t] \in {1, 2}}
|
||||
Retired(t) == phase[t] >= 3
|
||||
Subscribed == connection \in {"metadata", "hydrate", "ready"}
|
||||
Frame(kind, id, ids) == [kind |-> kind, id |-> id, ids |-> ids]
|
||||
Running(t) == Frame("running", t, {})
|
||||
NoFrame == Frame("none", Idle, {})
|
||||
|
||||
Init ==
|
||||
/\ phase = [t \in Turns |-> IF t = 1 THEN 1 ELSE 0]
|
||||
/\ socket = 1 /\ connection = "ready"
|
||||
\* Turn 1 was confirmed over this socket. A duplicate running callback may lag.
|
||||
/\ wire = <<Running(1)>> /\ oldCallback = [socket |-> Idle, frame |-> NoFrame]
|
||||
/\ client = [open |-> {1}, marked |-> {}, closed |-> {}, clock |-> 1,
|
||||
anonymous |-> FALSE, fenced |-> {}, successes |-> {}]
|
||||
/\ probed = FALSE /\ safe = TRUE
|
||||
|
||||
LoseTransport ==
|
||||
/\ connection # "down" /\ socket <= MaxLosses
|
||||
/\ socket' = socket + 1 /\ connection' = "down" /\ wire' = <<>>
|
||||
/\ oldCallback' = IF wire = <<>> THEN oldCallback ELSE [socket |-> socket, frame |-> Head(wire)]
|
||||
\* 3 has a queued send but has not had a server observation.
|
||||
/\ client' = [client EXCEPT !.marked = client.open \cap Turns]
|
||||
/\ UNCHANGED <<phase, probed, safe>>
|
||||
Reconnect ==
|
||||
/\ connection = "down" /\ connection' = "open"
|
||||
/\ UNCHANGED <<phase, socket, wire, oldCallback, client, probed, safe>>
|
||||
Subscribe ==
|
||||
/\ connection = "open" /\ connection' = "metadata"
|
||||
/\ UNCHANGED <<phase, socket, wire, oldCallback, client, probed, safe>>
|
||||
EnqueueAttached ==
|
||||
/\ connection = "metadata" /\ connection' = "hydrate"
|
||||
\* Metadata await is before this atomic sample + enqueue on the same FIFO.
|
||||
/\ wire' = Append(wire, Frame("attached", Idle, Live))
|
||||
/\ UNCHANGED <<phase, socket, oldCallback, client, probed, safe>>
|
||||
Hydrate ==
|
||||
/\ connection = "hydrate" /\ connection' = "ready"
|
||||
\* Ordinary running hydration is a separate, ordered observation, not presence.
|
||||
/\ wire' = IF Live = {} THEN wire ELSE Append(wire, Running(IF 2 \in Live THEN 2 ELSE 1))
|
||||
/\ UNCHANGED <<phase, socket, oldCallback, client, probed, safe>>
|
||||
|
||||
StartNewer ==
|
||||
/\ phase[1] >= 2 /\ phase[2] = 0
|
||||
/\ phase' = [phase EXCEPT ![2] = 1]
|
||||
/\ wire' = IF Subscribed THEN Append(wire, Running(2)) ELSE wire
|
||||
/\ UNCHANGED <<socket, connection, oldCallback, client, probed, safe>>
|
||||
BeginPersistence(t) ==
|
||||
/\ phase[t] = 1 /\ phase' = [phase EXCEPT ![t] = 2]
|
||||
/\ UNCHANGED <<socket, connection, wire, oldCallback, client, probed, safe>>
|
||||
DeliverTerminal(t, outcome) ==
|
||||
/\ IF outcome = 5 THEN phase[t] = 1 ELSE phase[t] = 2
|
||||
/\ phase' = [phase EXCEPT ![t] = outcome]
|
||||
\* An incomplete transcript (4) does not keep the owner live. Named idle (5)
|
||||
\* needs no persistence. Both use the subscribers at retirement.
|
||||
/\ LET kind == IF outcome = 5 THEN "idle" ELSE "terminal"
|
||||
IN wire' = IF Subscribed THEN Append(wire, Frame(kind, t, {})) ELSE wire
|
||||
/\ UNCHANGED <<socket, connection, oldCallback, client, probed, safe>>
|
||||
|
||||
SubmitLocal ==
|
||||
/\ Local \notin client.open
|
||||
/\ client' = [client EXCEPT !.open = @ \cup {Local}]
|
||||
/\ UNCHANGED <<phase, socket, connection, wire, oldCallback, probed, safe>>
|
||||
BeginAnonymous ==
|
||||
/\ socket > 1 /\ ~client.anonymous
|
||||
/\ client' = [client EXCEPT !.anonymous = TRUE]
|
||||
/\ UNCHANGED <<phase, socket, connection, wire, oldCallback, probed, safe>>
|
||||
|
||||
Close(c, ids) == [c EXCEPT !.open = @ \ ids, !.marked = @ \ ids, !.closed = @ \cup ids,
|
||||
!.clock = IF c.clock \in ids THEN Idle ELSE @]
|
||||
Observe(c, msg) ==
|
||||
CASE msg.kind = "attached" -> Close(c, c.marked \ msg.ids)
|
||||
[] msg.kind \in {"running", "delta"} ->
|
||||
IF msg.id \in c.closed THEN c ELSE [c EXCEPT !.open = @ \cup {msg.id}, !.clock = msg.id]
|
||||
[] msg.kind = "terminal" -> Close([c EXCEPT !.successes = @ \cup {msg.id}], {msg.id})
|
||||
[] msg.kind = "idle" -> Close(c, {msg.id})
|
||||
[] OTHER -> c
|
||||
|
||||
AttachEffects(before, after, live) ==
|
||||
LET absent == {t \in before.open \cap Turns : t \in before.marked /\ t \notin live}
|
||||
IN /\ before.open \ after.open = absent
|
||||
/\ after.open \subseteq before.open
|
||||
/\ before.closed \subseteq after.closed
|
||||
/\ after.closed \ before.closed = absent
|
||||
/\ (before.clock \in after.open => after.clock = before.clock)
|
||||
/\ after.anonymous = before.anonymous
|
||||
/\ after.fenced = before.fenced
|
||||
/\ after.successes = before.successes
|
||||
Receive ==
|
||||
/\ Subscribed /\ wire # <<>>
|
||||
/\ LET msg == Head(wire)
|
||||
IN /\ client' = Observe(client, msg)
|
||||
/\ safe' = safe /\ (msg.kind = "attached" => AttachEffects(client, client', msg.ids))
|
||||
/\ wire' = Tail(wire)
|
||||
/\ UNCHANGED <<phase, socket, connection, oldCallback, probed>>
|
||||
ReceiveOld ==
|
||||
/\ connection # "down" /\ oldCallback.frame # NoFrame
|
||||
/\ client' = IF oldCallback.socket = socket THEN Observe(client, oldCallback.frame) ELSE client
|
||||
/\ safe' = safe /\ client' = client
|
||||
/\ oldCallback' = [socket |-> Idle, frame |-> NoFrame]
|
||||
/\ UNCHANGED <<phase, socket, connection, wire, probed>>
|
||||
ReplayBuffered(kind) ==
|
||||
/\ socket > 1 /\ Subscribed /\ ~probed /\ 1 \in client.closed
|
||||
\* One pre-closure buffered lifecycle-capable event; not a transcript probe.
|
||||
/\ client' = Observe(client, Frame(kind, 1, {}))
|
||||
/\ safe' = safe /\ client' = client
|
||||
/\ probed' = TRUE
|
||||
/\ UNCHANGED <<phase, socket, connection, wire, oldCallback>>
|
||||
|
||||
Next ==
|
||||
\/ LoseTransport \/ Reconnect \/ Subscribe \/ EnqueueAttached \/ Hydrate
|
||||
\/ StartNewer \/ (\E t \in Turns: BeginPersistence(t) \/ (\E outcome \in 3..5: DeliverTerminal(t, outcome)))
|
||||
\/ SubmitLocal \/ BeginAnonymous
|
||||
\/ Receive \/ ReceiveOld \/ (\E kind \in {"running", "delta"}: ReplayBuffered(kind))
|
||||
|
||||
\* Healthy transport eventually drains. Work, replay and further losses need
|
||||
\* not occur. HTTP provides no completion evidence in this partition.
|
||||
FairSpec == Init /\ [][Next]_vars /\ WF_vars(Reconnect) /\ WF_vars(Subscribe)
|
||||
/\ WF_vars(EnqueueAttached) /\ WF_vars(Hydrate) /\ WF_vars(Receive)
|
||||
TypeOK ==
|
||||
/\ phase \in [Turns -> 0..5]
|
||||
/\ socket \in 1..(MaxLosses+1)
|
||||
/\ connection \in {"down", "open", "metadata", "hydrate", "ready"}
|
||||
/\ client.open \subseteq Turns \cup {Local} /\ client.closed \subseteq Turns
|
||||
/\ client.marked \subseteq client.open \cap Turns /\ client.clock \in Turns \cup {Idle}
|
||||
/\ client.anonymous \in BOOLEAN /\ client.fenced = {} /\ client.successes \subseteq Turns
|
||||
LifecycleSafety ==
|
||||
/\ safe /\ client.closed \cap client.open = {}
|
||||
/\ (client.clock = Idle \/ client.clock \in client.open)
|
||||
/\ client.closed \cap Live = {}
|
||||
/\ \A t \in client.successes: phase[t] \in {3, 4}
|
||||
Healthy == socket > 1 /\ connection = "ready"
|
||||
\* On stable reconnect and actual retirement, both absence and later terminal
|
||||
\* are sufficient. Do not require that an executing turn or local send finishes.
|
||||
EventuallyRetiredOwnersSettle ==
|
||||
\A t \in Turns: (<>[] Healthy /\ <>[] Retired(t)) => <>[] (t \notin client.open)
|
||||
=============================================================================
|
||||
@@ -1,8 +1,8 @@
|
||||
# WebUI turn synchronization: bounded TLC models
|
||||
|
||||
These models check the missed-completion/stuck-busy ordering in [PR #6683](https://github.com/HKUDS/nanobot/pull/6683): a terminal frame is lost, a newer turn starts, and recovery history explicitly completes the older turn. Completing that turn must not stop the newer one or discard content that history has not covered.
|
||||
These models check recovery from a missed terminal frame. History can explicitly complete an older turn without stopping a newer one or discarding uncovered content. Independently, trusted attach can retire a previously confirmed owner absent from the Gateway's complete live-ID set, even if paged history supplies no completion ID.
|
||||
|
||||
**These are handwritten abstractions of selected current-implementation transitions, not mechanical verification of TypeScript or proof of all WebUI/Gateway behavior.** The default runner checks twelve positive configurations. Two current-policy missing-evidence cases run separately and retain temporal counterexamples; they are never counted as positive passes.
|
||||
**These are handwritten abstractions of selected transitions, not mechanical verification of implementation code or proof of all WebUI/Gateway behavior.** The runner checks thirteen configurations by default.
|
||||
|
||||
## Files and source mapping
|
||||
|
||||
@@ -14,8 +14,9 @@ These models check the missed-completion/stuck-busy ordering in [PR #6683](https
|
||||
| `CacheHandoff.tla` | Shared full-page publication, superseded own reads, one mounted whole-snapshot adopter and rejected stale callbacks. |
|
||||
| `SharedRequests.tla` | Per-key request sharing, consumer cancellation, invalidation/replacement, reconnect and stale/late delivery. |
|
||||
| `CompletionAuthority.tla` | Exact-ID ledger closure, coverage-dependent content fencing, anonymous recovery and another-chat isolation. |
|
||||
| `AttachReconciliation.tla` | Trusted attach snapshot and terminal fanout ordering; loss-marked ownership, stale socket callbacks and lifecycle-only absence reconciliation independent of paged history. |
|
||||
|
||||
The source owners are `client-run-ledger.ts`, `nanobot-client.ts`, `canonical-run-snapshot.ts`, `latest-thread-request.ts`, `thread-transcript.ts`, `webui-thread-cache.ts`, `useReconnectRuns.ts`, `useNanobotStream.ts` and `ThreadShell.tsx`. The runner can record their hashes; the mapping still requires human review. [`USAGE-LIFECYCLE.md`](USAGE-LIFECYCLE.md) details the dynamic full-page mapping.
|
||||
The runner can record the relevant client and Gateway source hashes; the mapping still requires human review. [`USAGE-LIFECYCLE.md`](USAGE-LIFECYCLE.md) details the dynamic full-page mapping. [`ATTACH-RECONCILIATION.md`](ATTACH-RECONCILIATION.md) describes the separate attach model, fairness assumptions, and reference runs.
|
||||
|
||||
The Gateway owns execution. The request registry owns cancellation and stale-response eligibility; `ThreadTranscript` owns content admission/coverage; `ClientRunLedger` alone owns the client's observed run state. Fresh full pages supply explicit completion facts even when mount/cache eligibility prevents content adoption. Eligible history is cached before completion notifications. The mounted transcript alone adopts whole snapshots; only an unmounted reader can perform background adoption, and only for an eligible idle page. Lifecycle-only closure preserves uncovered content and independent anonymous recovery. Initial cached seeds are not fresh evidence. Mounted fragments hand off completed IDs only when their gap/admission rules expose them.
|
||||
|
||||
@@ -26,8 +27,9 @@ The Gateway owns execution. The request registry owns cancellation and stale-res
|
||||
- `PartialCompletionPreservesRecovery` and `LifecycleOnlyPreservesContentAndRecovery`: named completion preserves independent anonymous recovery and uncovered content.
|
||||
- `MountedFragmentRequiresAcceptance`, `ActiveUnmountedSnapshotIsNotAdopted`, `CachePrecedesIdleNotification` and `SoleCanonicalActor`: content admission, notification ordering and single-owner boundaries.
|
||||
- `EventuallyIdle` and `EventuallyRequestsDrain`: conditional eventual quiescence under the stated finite workload and fairness assumptions.
|
||||
- `LifecycleSafety` and `EventuallyRetiredOwnersSettle`: after healthy reconnection, retired owners settle without completion evidence from history and without closing live owners.
|
||||
|
||||
## Scope and limits
|
||||
## History partition scope and limits
|
||||
|
||||
The fixed-mount submodel has one chat, two sequential server turns, at most one disconnect/reconnect and one logical latest-history read. `Mounted` is fixed for a run. Request, server capture and response processing are separate actions. Full pages contain all completed/observed IDs within the bounded turns. A real selected page can omit an ID, so this assumption matters. Mounted full-page facts are assumed to reach reconciliation; cache routing and dynamic selection are checked separately.
|
||||
|
||||
@@ -44,20 +46,15 @@ Requirements: Python 3.9+, Java and the official [`tla2tools.jar` from TLA+ v1.7
|
||||
From this directory in PowerShell:
|
||||
|
||||
```powershell
|
||||
# Twelve positive checks: every finite graph must exhaust without a counterexample.
|
||||
python -B .\run_tlc.py --jar 'C:\path\to\tla2tools.jar'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'TLC check failed' }
|
||||
|
||||
# Current-policy missing-evidence limits, separate from positive checks.
|
||||
python -B .\run_tlc.py --limits --jar 'C:\path\to\tla2tools.jar'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Missing-evidence classification changed' }
|
||||
```
|
||||
|
||||
Use `--case revised-unmounted-live` (repeatable) for individual cases. `--output-root` must name a new directory outside the checkout; otherwise a private temporary directory is allocated. `--implementation-root <repository-root>` records the relevant source hashes without asserting a checked refinement. Models/configs are copied into the external output directory before Java starts. Logs, state graphs and generated traces stay there. `manifest.json` records input/jar hashes, commands, exit statuses and graph counts. Defaults are two workers, a 1536 MiB heap and a 600-second per-case timeout; cases run sequentially.
|
||||
|
||||
A positive result requires exit 0, TLC's no-error completion message and an empty state queue. Timeouts, specification errors and other exits fail the runner. Limit cases instead require exit 13 and the temporal-violation signature, labeled `LIMITATION_COUNTEREXAMPLE`. A zero runner exit for `--limits` means the expected limitations were reproduced, not that liveness passed.
|
||||
A passing case requires exit 0, TLC's no-error completion message and an empty state queue. Counterexamples, timeouts and specification errors fail the runner.
|
||||
|
||||
## Reference positive results
|
||||
## Reference results
|
||||
|
||||
| Config | Checked scope | Distinct states |
|
||||
| --- | --- | ---: |
|
||||
@@ -74,4 +71,4 @@ A positive result requires exit 0, TLC's no-error completion message and an empt
|
||||
| `handoff-fullpage-active` | Pending newer turn; shared-page handoff and sole canonical actor | 80 |
|
||||
| `handoff-fullpage-idle` | Idle shared-page handoff and sole canonical actor | 80 |
|
||||
|
||||
`--case requests-two` and `--case lifecycle-fullpage-two-chats` expose larger current-policy products, not additional claimed positive results. The separate `--limits` cases retain two real evidence boundaries: a failed needed read without a later recovery read, and a fragment omitting the needed completed ID without a later bridge/read. Neither condition guarantees eventual idle.
|
||||
See [Attach reconciliation](ATTACH-RECONCILIATION.md#reproduce-and-evidence) for the `attach-reconciliation` config and its graph counts. The larger `requests-two` and `lifecycle-fullpage-two-chats` configurations are optional; they are not part of the reference run.
|
||||
@@ -28,7 +28,7 @@ Cache publication and its synchronous owner callback are one model action; navig
|
||||
| `handoff-fullpage-active` | `CacheHandoff.tla` | exit 0, no error, queue 0 | 80 |
|
||||
| `handoff-fullpage-idle` | `CacheHandoff.tla` | exit 0, no error, queue 0 | 80 |
|
||||
|
||||
The dynamic case has one chat, two sequential server turns, two outages and two selection changes, starting unselected. Selected and actually mounted owners are separate: a scheduled refresh may remain pending until selection away. Mounted-history H and reconnect R capture/processing are separate. The workload includes pending/active metadata, stale generations, transcript admission choices and independent anonymous activity. Full pages contain all bounded persisted completion IDs. Read failures and fragments are excluded from this positive workload, not hidden by fairness or state constraints.
|
||||
The dynamic case has one chat, two sequential server turns, two outages and two selection changes, starting unselected. Selected and actually mounted owners are separate: a scheduled refresh may remain pending until selection away. Mounted-history H and reconnect R capture/processing are separate. The workload includes pending/active metadata, stale generations, transcript admission choices and independent anonymous activity. This partition covers successful full pages that contain all bounded persisted completion IDs. [Attach reconciliation](ATTACH-RECONCILIATION.md) checks lifecycle convergence when history supplies no completion ID.
|
||||
|
||||
The config checks `TypeOK`, `NoOlderCompletionClearsNewer`, `PartialCompletionPreservesRecovery`, `LifecycleOnlyPreservesContentAndRecovery`, `ActiveUnmountedSnapshotIsNotAdopted`, `CachePrecedesIdleNotification`, `SoleCanonicalActor` and `ExplicitCompletionHandoffSettles`. It checks `RawExplicitCompletionsSettle` and `EventuallyIdle` in the same run. Raw learning includes every processed full-page ID even when cache admission fails: `learned ∩ open = {}`.
|
||||
|
||||
@@ -45,12 +45,6 @@ The handoff cases start at a source-reachable checkpoint: observed turn 1, lost
|
||||
|
||||
The maintained actual-hooks regression exercises the deferred-refresh boundary: a mounted reconnect full page completes 1 while 2 is still open; preflight rejects content adoption; selection away cancels the pending history refresh. Lifecycle observation closes only 1, preserving 2's owner/clock and uncovered content. Ending 2 can then leave idle without another refresh. This concrete regression and the model graph are separate forms of verification.
|
||||
|
||||
## Current-policy limits
|
||||
|
||||
`--limits` runs two cases separately from positive checks. Each must retain exit 13 and the temporal-property violation signature. Their runner status is `LIMITATION_COUNTEREXAMPLE`, not a passing liveness result; reached-state counts depend on concurrent search order.
|
||||
|
||||
- `lifecycle-failed-read-limit` allows needed reads to fail. A lost terminal plus failed recovery can leave an owner unresolved; fairness cannot manufacture a later retry.
|
||||
- `lifecycle-fragment-id-limit` allows fragments with omitted completion IDs and no switches. Without an owner/bridge/future read, completion evidence may never arrive. This is not an assertion about a particular native Gateway payload.
|
||||
- Larger current-policy two-chat products remain optional and are not claimed exhausted. Separate request/ledger/lifecycle graphs and other-chat sentinels are not a checked compositional liveness theorem.
|
||||
The larger two-chat configuration remains optional. The separate request, ledger and lifecycle models do not establish a compositional liveness theorem.
|
||||
|
||||
H/R captures overapproximate independent producers; concrete request sharing/abort is a separate `SharedRequests` partition. Transcript fragment joining, token/auth/client replacement, backend execution, eviction, multiple tabs/hosts, send queues and unbounded workloads are outside this model. Logs, states, source snapshots and the jar stay outside the checkout.
|
||||
@@ -7,13 +7,13 @@ EXTENDS Naturals, FiniteSets, Sequences, TLC
|
||||
\* Full pages contain all bounded persisted IDs; no fragment-gap bridging proof.
|
||||
\* Effect setup starts history (useNanobotStream:551) before transcript subscribe
|
||||
\* (:682 onward), so selected alone does not imply hasTranscript.
|
||||
CONSTANTS NChats, NTurns, MaxOutages, MaxSwitches, AllowFailures, Fragments
|
||||
CONSTANTS NChats, NTurns, MaxOutages, MaxSwitches
|
||||
Chats == 1..NChats
|
||||
Turns == 1..NTurns
|
||||
Readers == {"H", "R"}
|
||||
None == 0
|
||||
EmptyRead == [phase |-> 0, generation |-> 0, turn |-> 0,
|
||||
completed |-> {}, observed |-> {}, pending |-> FALSE, active |-> 0, fragment |-> FALSE]
|
||||
completed |-> {}, observed |-> {}, pending |-> FALSE, active |-> 0]
|
||||
EmptyLedger == [open |-> {}, closed |-> {}, fenced |-> {}, latest |-> 0,
|
||||
clock |-> 0, generation |-> 0, anonymous |-> FALSE,
|
||||
recoverySeen |-> FALSE, learned |-> {}]
|
||||
@@ -91,26 +91,22 @@ Receive(c) ==
|
||||
/\ reads' = IF ~ignored /\ m.kind = 2 THEN
|
||||
[reads EXCEPT ![c] = [r \in Readers |-> IF reads[c][r].phase # 0
|
||||
THEN [reads[c][r] EXCEPT !.phase = 1, !.completed = {},
|
||||
!.observed = {}, !.pending = FALSE, !.active = 0, !.fragment = FALSE]
|
||||
!.observed = {}, !.pending = FALSE, !.active = 0]
|
||||
ELSE reads[c][r]]]
|
||||
ELSE reads
|
||||
/\ wire' = [wire EXCEPT ![c] = Tail(@)]
|
||||
/\ UNCHANGED <<server, needHook, selected, mounted, switches, connected, outages, safe>>
|
||||
Capture(c,r,fragment,completions,pending) ==
|
||||
Capture(c,r,pending) ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ reads[c][r].phase = 1
|
||||
/\ fragment \in BOOLEAN /\ (fragment => Fragments)
|
||||
/\ IF fragment THEN completions \subseteq Done(c) ELSE completions = Done(c)
|
||||
/\ pending \in BOOLEAN /\ (pending => (Running(c) # {} \/ ledger[c].anonymous))
|
||||
/\ reads' = [reads EXCEPT ![c][r].phase = 2, ![c][r].completed = completions,
|
||||
/\ (pending => (Running(c) # {} \/ ledger[c].anonymous))
|
||||
/\ reads' = [reads EXCEPT ![c][r].phase = 2, ![c][r].completed = Done(c),
|
||||
![c][r].observed = Seen(c), ![c][r].pending = pending,
|
||||
![c][r].active = IF Running(c) = {} THEN 0 ELSE CHOOSE t \in Running(c) : TRUE,
|
||||
![c][r].fragment = fragment]
|
||||
![c][r].active = IF Running(c) = {} THEN 0 ELSE CHOOSE t \in Running(c) : TRUE]
|
||||
/\ UNCHANGED <<server, wire, ledger, needHook, selected, mounted, switches, connected, outages, safe>>
|
||||
Process(c,r,accepted,exposed) ==
|
||||
Process(c,r,accepted) ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ reads[c][r].phase = 2 /\ (r = "R" => connected) /\ (r = "H" => mounted = c)
|
||||
/\ accepted \in BOOLEAN /\ exposed \in BOOLEAN /\ (exposed => accepted)
|
||||
/\ LET q == reads[c][r]
|
||||
l == ledger[c]
|
||||
completed == q.completed
|
||||
@@ -118,32 +114,22 @@ Process(c,r,accepted,exposed) ==
|
||||
(l.generation = q.generation \/ l.latest \in (completed \cup l.fenced))
|
||||
explicit == q.turn # 0 /\ q.turn \in completed
|
||||
idle == ~q.pending /\ q.active = 0
|
||||
canCache == IF q.fragment THEN canApply ELSE
|
||||
(explicit \/ idle) /\ (q.turn = 0 \/ explicit \/ q.turn \in q.observed) /\ canApply
|
||||
canCache == (explicit \/ idle) /\ (q.turn = 0 \/ explicit \/ q.turn \in q.observed) /\ canApply
|
||||
hasOwner == mounted = c
|
||||
cacheInstall == r = "R" /\ canCache /\ hasOwner
|
||||
fragmentReady == q.fragment /\ ((r = "H" /\ exposed) \/
|
||||
(r = "R" /\ (~hasOwner \/ (cacheInstall /\ exposed))))
|
||||
\* Transcript acceptance controls adoption, not exact full-page closure.
|
||||
\* exposed is separate: a staged accepted fragment can expose no IDs.
|
||||
\* Non-seed full-page owner handoff; no pending fragment gap here.
|
||||
ownerWhole == ~q.fragment /\ (r = "H" \/ cacheInstall)
|
||||
backgroundWhole == ~q.fragment /\ r = "R" /\ canCache /\ idle /\ ~hasOwner
|
||||
ownerWhole == r = "H" \/ cacheInstall
|
||||
backgroundWhole == r = "R" /\ canCache /\ idle /\ ~hasOwner
|
||||
whole == ownerWhole \/ backgroundWhole
|
||||
\* Preflight/cache publication above still use the BEFORE-settlement ledger.
|
||||
\* A fresh, nonaborted full R page now supplies lifecycle evidence even
|
||||
\* with a mounted owner or canCache=FALSE. It grants no content coverage.
|
||||
lifecycle == fragmentReady \/ (r = "R" /\ ~q.fragment)
|
||||
doSettle == whole \/ lifecycle
|
||||
adopt == backgroundWhole \/ (ownerWhole /\ accepted /\ ~q.pending /\ canApply)
|
||||
nextOpen == IF doSettle THEN l.open \ completed ELSE l.open
|
||||
nextClock == IF adopt \/ (doSettle /\ l.latest \in completed) THEN 0 ELSE l.clock
|
||||
\* Fresh full pages settle explicit IDs independently of content adoption.
|
||||
nextOpen == l.open \ completed
|
||||
nextClock == IF adopt \/ l.latest \in completed THEN 0 ELSE l.clock
|
||||
nextAnon == IF adopt THEN FALSE ELSE l.anonymous
|
||||
nl == [l EXCEPT !.open = nextOpen,
|
||||
!.closed = IF doSettle THEN @ \cup completed ELSE @,
|
||||
!.closed = @ \cup completed,
|
||||
!.fenced = IF whole THEN @ \cup completed ELSE @,
|
||||
!.clock = nextClock, !.anonymous = nextAnon,
|
||||
!.learned = @ \cup (IF ~q.fragment \/ fragmentReady THEN completed ELSE {})]
|
||||
!.learned = @ \cup completed]
|
||||
IN /\ ledger' = [ledger EXCEPT ![c] = nl]
|
||||
/\ reads' = [reads EXCEPT ![c][r] = EmptyRead,
|
||||
![c]["H"] = IF cacheInstall \/ r = "H" THEN EmptyRead ELSE reads[c]["H"]]
|
||||
@@ -151,18 +137,12 @@ Process(c,r,accepted,exposed) ==
|
||||
!.collateral = @ /\ ((l.open \ completed) \subseteq nextOpen) /\
|
||||
(l.latest # 0 /\ l.latest \notin completed /\ l.clock = l.latest => nextClock = l.clock),
|
||||
!.partial = @ /\ (adopt \/ ~l.anonymous \/ nextAnon),
|
||||
!.lifecycle = @ /\ (~(lifecycle /\ ~whole) \/
|
||||
(nl.fenced = l.fenced /\ nextAnon = l.anonymous)),
|
||||
!.activeAdoption = @ /\ (~(r = "R" /\ ~hasOwner /\ ~q.fragment /\ ~idle) \/ ~adopt),
|
||||
!.lifecycle = @ /\ (whole \/ (nl.fenced = l.fenced /\ nextAnon = l.anonymous)),
|
||||
!.activeAdoption = @ /\ (~(r = "R" /\ ~hasOwner /\ ~idle) \/ ~adopt),
|
||||
!.cacheOrder = @ /\ (r # "R" \/ ~adopt \/ canCache),
|
||||
!.handoff = @ /\ (~doSettle \/ completed \cap nextOpen = {}),
|
||||
!.handoff = @ /\ (completed \cap nextOpen = {}),
|
||||
!.soleActor = @ /\ ~(ownerWhole /\ backgroundWhole)]
|
||||
/\ UNCHANGED <<server, wire, needHook, selected, mounted, switches, connected, outages>>
|
||||
Fail(c,r) ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ AllowFailures /\ reads[c][r].phase # 0
|
||||
/\ reads' = [reads EXCEPT ![c][r] = EmptyRead]
|
||||
/\ UNCHANGED <<server, wire, ledger, needHook, selected, mounted, switches, connected, outages, safe>>
|
||||
BeginRecovery(c) ==
|
||||
/\ UNCHANGED mounted
|
||||
/\ connected /\ Running(c) # {} /\ ~ledger[c].anonymous /\ ~ledger[c].recoverySeen
|
||||
@@ -175,14 +155,14 @@ EndRecovery(c) ==
|
||||
(IF ledger[c].latest = 0 THEN {} ELSE {ledger[c].latest}),
|
||||
![c].open = {}, ![c].clock = 0, ![c].latest = 0, ![c].anonymous = FALSE]
|
||||
/\ UNCHANGED <<server, wire, reads, needHook, selected, mounted, switches, connected, outages, safe>>
|
||||
CaptureAny(c,r) == \E f,p \in BOOLEAN, d \in SUBSET Turns : Capture(c,r,f,d,p)
|
||||
ProcessAny(c,r) == \E a,e \in BOOLEAN : Process(c,r,a,e)
|
||||
CaptureAny(c,r) == \E pending \in BOOLEAN : Capture(c,r,pending)
|
||||
ProcessAny(c,r) == \E accepted \in BOOLEAN : Process(c,r,accepted)
|
||||
Next ==
|
||||
\/ \E c \in Chats, t \in Turns : Start(c,t) \/ Finish(c,t)
|
||||
\/ Disconnect \/ Reconnect \/ HookEffect
|
||||
\/ \E c \in Chats \cup {0} : Switch(c)
|
||||
\/ \E c \in Chats : Receive(c) \/ BeginRecovery(c) \/ EndRecovery(c)
|
||||
\/ \E c \in Chats, r \in Readers : CaptureAny(c,r) \/ ProcessAny(c,r) \/ Fail(c,r)
|
||||
\/ \E c \in Chats, r \in Readers : CaptureAny(c,r) \/ ProcessAny(c,r)
|
||||
Spec == Init /\ [][Next]_vars
|
||||
FairSpec == Spec /\ WF_vars(Reconnect) /\ WF_vars(HookEffect) /\
|
||||
(\A c \in Chats : WF_vars(Receive(c))) /\
|
||||
@@ -196,8 +176,7 @@ TypeOK ==
|
||||
/\ ledger[c].fenced \subseteq Turns /\ ledger[c].latest \in Turns \cup {0}
|
||||
/\ ledger[c].clock \in Turns \cup {0}
|
||||
/\ ledger[c].generation \in 0..(NTurns+MaxOutages)
|
||||
\* Raw processed full-page IDs were already included in learned regardless of
|
||||
\* cache eligibility. Keep that definition, not just successful handoff IDs.
|
||||
\* Every processed full page contributes explicit IDs, even if cache admission fails.
|
||||
RawExplicitCompletionsSettle == \A c \in Chats : ledger[c].learned \cap ledger[c].open = {}
|
||||
ExplicitCompletionsSettle == RawExplicitCompletionsSettle
|
||||
NoOlderCompletionClearsNewer == safe.collateral
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
SPECIFICATION FairSpec
|
||||
CONSTANT MaxLosses = 2
|
||||
INVARIANTS TypeOK LifecycleSafety
|
||||
PROPERTY EventuallyRetiredOwnersSettle
|
||||
CHECK_DEADLOCK FALSE
|
||||
@@ -1,19 +0,0 @@
|
||||
CONSTANTS
|
||||
NChats = 1
|
||||
NTurns = 2
|
||||
MaxOutages = 2
|
||||
MaxSwitches = 2
|
||||
AllowFailures = TRUE
|
||||
Fragments = FALSE
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS
|
||||
TypeOK
|
||||
NoOlderCompletionClearsNewer
|
||||
PartialCompletionPreservesRecovery
|
||||
LifecycleOnlyPreservesContentAndRecovery
|
||||
ActiveUnmountedSnapshotIsNotAdopted
|
||||
CachePrecedesIdleNotification
|
||||
SoleCanonicalActor
|
||||
ExplicitCompletionHandoffSettles
|
||||
PROPERTY EventuallyIdle
|
||||
@@ -1,20 +0,0 @@
|
||||
CONSTANTS
|
||||
NChats = 1
|
||||
NTurns = 2
|
||||
MaxOutages = 2
|
||||
MaxSwitches = 0
|
||||
AllowFailures = FALSE
|
||||
Fragments = TRUE
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS
|
||||
TypeOK
|
||||
NoOlderCompletionClearsNewer
|
||||
PartialCompletionPreservesRecovery
|
||||
LifecycleOnlyPreservesContentAndRecovery
|
||||
ActiveUnmountedSnapshotIsNotAdopted
|
||||
CachePrecedesIdleNotification
|
||||
SoleCanonicalActor
|
||||
ExplicitCompletionHandoffSettles
|
||||
|
||||
PROPERTY EventuallyIdle
|
||||
@@ -3,8 +3,6 @@ CONSTANTS
|
||||
NTurns = 2
|
||||
MaxOutages = 2
|
||||
MaxSwitches = 2
|
||||
AllowFailures = FALSE
|
||||
Fragments = FALSE
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS
|
||||
|
||||
@@ -3,8 +3,6 @@ CONSTANTS
|
||||
NTurns = 2
|
||||
MaxOutages = 2
|
||||
MaxSwitches = 2
|
||||
AllowFailures = FALSE
|
||||
Fragments = FALSE
|
||||
SPECIFICATION FairSpec
|
||||
CHECK_DEADLOCK FALSE
|
||||
INVARIANTS
|
||||
|
||||
@@ -1,24 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check bounded current-policy models without writing generated files into the checkout."""
|
||||
"""Check bounded turn-sync models without writing generated files into the checkout."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
SOURCE = Path(__file__).resolve().parent
|
||||
EXPECTED_LIMITS = {
|
||||
"lifecycle-failed-read-limit": (13, "Temporal properties were violated"),
|
||||
"lifecycle-fragment-id-limit": (13, "Temporal properties were violated"),
|
||||
}
|
||||
ATTACH_CASE = "attach-reconciliation"
|
||||
REVISED_CASES = (
|
||||
"revised-mounted", "revised-unmounted",
|
||||
"revised-mounted-fragments", "revised-unmounted-fragments",
|
||||
@@ -30,16 +26,16 @@ USAGE_CASES = (
|
||||
)
|
||||
# Larger products are reproducible explicitly, not claimed exhausted by defaults.
|
||||
OPTIONAL_CASES = ("requests-two", "lifecycle-fullpage-two-chats")
|
||||
LIMIT_CASES = tuple(EXPECTED_LIMITS)
|
||||
CASES = REVISED_CASES + USAGE_CASES + OPTIONAL_CASES + LIMIT_CASES
|
||||
DEFAULT_CASES = REVISED_CASES + USAGE_CASES + (ATTACH_CASE,)
|
||||
CASES = DEFAULT_CASES + OPTIONAL_CASES
|
||||
MODULES = {
|
||||
**{case: "RevisedTurnSync.tla" for case in REVISED_CASES},
|
||||
**{case: "SharedRequests.tla" for case in ("requests-one", "requests-two-no-invalidations", "requests-two")},
|
||||
"authority": "CompletionAuthority.tla",
|
||||
**{case: "CacheHandoff.tla" for case in ("handoff-fullpage-active", "handoff-fullpage-idle")},
|
||||
**{case: "UsageLifecycle.tla" for case in (
|
||||
"lifecycle-fullpage-dynamic", "lifecycle-fullpage-two-chats", *LIMIT_CASES,
|
||||
)},
|
||||
"lifecycle-fullpage-dynamic": "UsageLifecycle.tla",
|
||||
"lifecycle-fullpage-two-chats": "UsageLifecycle.tla",
|
||||
ATTACH_CASE: "AttachReconciliation.tla",
|
||||
}
|
||||
COUNTS = re.compile(
|
||||
r"([\d,]+) states generated, ([\d,]+) distinct states found, ([\d,]+) states left on queue"
|
||||
@@ -49,7 +45,10 @@ IMPLEMENTATION_FILES = (
|
||||
"webui/src/lib/client-run-ledger.ts", "webui/src/lib/nanobot-client.ts",
|
||||
"webui/src/lib/canonical-run-snapshot.ts", "webui/src/lib/latest-thread-request.ts",
|
||||
"webui/src/lib/thread-transcript.ts", "webui/src/lib/webui-thread-cache.ts",
|
||||
"webui/src/components/thread/ThreadShell.tsx",
|
||||
"webui/src/components/thread/ThreadShell.tsx", "webui/src/lib/types.ts",
|
||||
"nanobot/session/webui_turns.py", "nanobot/webui/inbound_commands.py",
|
||||
"nanobot/webui/session_projection.py", "nanobot/webui/outbound_delivery.py",
|
||||
"nanobot/webui/ws_http.py", "nanobot/channels/websocket/runtime.py",
|
||||
)
|
||||
|
||||
|
||||
@@ -61,10 +60,8 @@ def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--jar", required=True, type=Path, help="External official tla2tools.jar; never copied")
|
||||
parser.add_argument("--output-root", type=Path, help="New task-owned directory outside this checkout")
|
||||
parser.add_argument("--implementation-root", type=Path, help="Optional read-only TypeScript provenance; not mechanical verification")
|
||||
selection = parser.add_mutually_exclusive_group()
|
||||
selection.add_argument("--case", action="append", choices=CASES, dest="cases", help="Repeat to select cases")
|
||||
selection.add_argument("--limits", action="store_true", help="Run ONLY current-policy missing-evidence counterexamples, not positive checks")
|
||||
parser.add_argument("--implementation-root", type=Path, help="Optional read-only implementation provenance; not mechanical verification")
|
||||
parser.add_argument("--case", action="append", choices=CASES, dest="cases", help="Repeat to select cases")
|
||||
parser.add_argument("--java", default="java")
|
||||
parser.add_argument("--workers", type=int, default=2)
|
||||
parser.add_argument("--heap-mb", type=int, default=1536)
|
||||
@@ -83,7 +80,7 @@ def main() -> int:
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
inputs = sorted((*SOURCE.glob("*.tla"), *SOURCE.glob("*.cfg")))
|
||||
manifest = {
|
||||
"scope": "finite fixed-mount, dynamic lifecycle, shared-request and completion partitions; not a checked TypeScript/compositional/all-system proof",
|
||||
"scope": "finite history, request, completion and attach partitions; not a checked implementation/compositional proof",
|
||||
"jar": {"path": str(jar), "sha256": sha256(jar)},
|
||||
"source_sha256": {path.name: sha256(path) for path in inputs},
|
||||
"results": [],
|
||||
@@ -93,11 +90,11 @@ def main() -> int:
|
||||
manifest["implementation_snapshot"] = {
|
||||
"root": str(implementation),
|
||||
"sha256": {name: sha256(implementation / name) for name in IMPLEMENTATION_FILES},
|
||||
"note": "Read-only provenance, not a checked refinement of TypeScript",
|
||||
"note": "Read-only provenance, not a checked refinement of implementation code",
|
||||
}
|
||||
print(f"Evidence: {output}", flush=True)
|
||||
unexpected = 0
|
||||
selected = args.cases or (LIMIT_CASES if args.limits else REVISED_CASES + USAGE_CASES)
|
||||
failed = 0
|
||||
selected = args.cases or DEFAULT_CASES
|
||||
for case in selected:
|
||||
case_dir = output / case
|
||||
case_dir.mkdir()
|
||||
@@ -113,7 +110,6 @@ def main() -> int:
|
||||
"tlc2.TLC", "-workers", str(args.workers), "-config", f"{case}.cfg",
|
||||
"-metadir", str(case_dir / "states"), module,
|
||||
]
|
||||
expected_exit, required_error = EXPECTED_LIMITS.get(case, (0, None))
|
||||
started = time.monotonic()
|
||||
timed_out = False
|
||||
try:
|
||||
@@ -133,19 +129,16 @@ def main() -> int:
|
||||
(case_dir / "tlc.log").write_text(text, encoding="utf-8")
|
||||
matches = list(COUNTS.finditer(text))
|
||||
counts = tuple(int(value.replace(",", "")) for value in matches[-1].groups()) if matches else None
|
||||
matched = not timed_out and actual_exit == expected_exit
|
||||
if required_error:
|
||||
matched = matched and required_error in text
|
||||
else:
|
||||
matched = (matched and "Model checking completed. No error has been found." in text
|
||||
and counts is not None and counts[2] == 0)
|
||||
status = ("LIMITATION_COUNTEREXAMPLE" if required_error else "EXHAUSTED_NO_COUNTEREXAMPLE") if matched else "UNEXPECTED_RESULT"
|
||||
unexpected += not matched
|
||||
exhausted = (
|
||||
actual_exit == 0 and "Model checking completed. No error has been found." in text
|
||||
and counts is not None and counts[2] == 0
|
||||
)
|
||||
status = "EXHAUSTED_NO_COUNTEREXAMPLE" if exhausted else "UNEXPECTED_RESULT"
|
||||
result = {
|
||||
"case": case, "status": status,
|
||||
"category": ("missing-evidence-limit" if case in LIMIT_CASES else
|
||||
"category": ("attach-model" if case == ATTACH_CASE else
|
||||
"expanded-usage-model" if case in USAGE_CASES + OPTIONAL_CASES else "fixed-mount-model"),
|
||||
"expected_exit": expected_exit, "actual_exit": actual_exit, "required_error": required_error,
|
||||
"actual_exit": actual_exit,
|
||||
"timed_out": timed_out, "seconds": round(time.monotonic() - started, 3),
|
||||
"generated": counts[0] if counts else None, "distinct": counts[1] if counts else None,
|
||||
"left_on_queue": counts[2] if counts else None,
|
||||
@@ -153,13 +146,12 @@ def main() -> int:
|
||||
}
|
||||
manifest["results"].append(result)
|
||||
(output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"{case}: {status}; exit={actual_exit}, expected={expected_exit}; distinct={result['distinct']}", flush=True)
|
||||
if not matched:
|
||||
print(f"{case}: {status}; exit={actual_exit}; distinct={result['distinct']}", flush=True)
|
||||
if not exhausted:
|
||||
failed += 1
|
||||
print(text[-5000:], flush=True)
|
||||
positive_count = sum(result["status"] == "EXHAUSTED_NO_COUNTEREXAMPLE" for result in manifest["results"])
|
||||
limit_count = sum(result["status"] == "LIMITATION_COUNTEREXAMPLE" for result in manifest["results"])
|
||||
print(f"Positive exhausted checks: {positive_count}; missing-evidence counterexamples: {limit_count}; unexpected: {unexpected}")
|
||||
return 1 if unexpected else 0
|
||||
print(f"Exhausted checks: {len(selected) - failed}; failed: {failed}")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in new issue
Block a user