Repository navigation
Description
Parked idea. Nobody is working on this now. The notes below record a
short pilot so that whoever picks it up can start from it instead of
from scratch.
The idea
Use a model checker to look for bugs that come from the order in which
things happen: clicks, network responses, timers, and remounts. These
bugs are hard to reach with ordinary tests, because a test has to guess
the exact order that breaks things.
The approach, which an AI agent can mostly carry out:
- Write a small model of the code in TLA+.
The model lists the variables that matter and every step that can
change them, such as "the user sends a call", "a response arrives",
or "a timer fires". - Write down the rules that must always hold, for example "the page
never goes back to an older State token" (the signed token the server
sends with each component's State). - Run TLC, the TLA+ model checker. It tries every order of steps up to
a small limit (here, 3 calls and 1 remount) and prints the exact
sequence of steps that breaks a rule. - Turn each printed sequence into a unit test against the real code.
The model is someone's reading of the code and can be wrong, so a
sequence counts as a bug only when the test fails too.
TLC proves nothing beyond the limits it was given, and a clean run shows
only that the model keeps the rules, not that the code does. It is good
at finding bugs that need several steps in an unusual order, quickly.
Pilot: the Vue Events bridge
The pilot modeled createVueEventsBridge in
packages/js/citry-client/src/citry-events-vue.ts (at 05db9ce6b) for
one spot on the page where a component is mounted (one stableId). The
model covers:
- the queue that sends one call at a time;
acceptedEpoch, which the bridge raises each time it accepts a
response, and the checks that drop work started under an older count;- delayed actions, both blocking and
wait: false; - a render that replaces the calling component with a new instance,
including the case where the call's own render did it
(acceptedRemount); latestCallWins, which cancels earlier calls to the same handler.
A click, a timer or a network response can only run while the bridge
waits on a timer, the network, or the render. Between those waits the
bridge only chains promises, which nothing outside can interrupt. So the
model treats the code between two such waits as one step.
Rules that held
At 3 calls and 2 component generations, so one remount (about 9,300
states, about one second):
- the page never goes back to an older State token;
- a promise, once settled, stays settled;
- every call's promise eventually settles.
Two bugs found
TLC printed two step sequences that break a rule, and a unit test
against the real bridge confirmed each one:
- With
latest_wins, a superseded call still runs its delayed actions and holds up the newer call #306: with@event(latest_wins=True), a call that was rejected as
supersededstill runs its delayed actions, and the newer call waits
for them. - After a Render replaces the caller, its delayed
wait=Falseactions run even after a newer result #307: after a Render replaces the calling component, an older
delayedwait=Falseaction still runs after the new component's
result was accepted, which the Events spec says should not happen.
Each issue holds its step sequence and the failing test.
What the model leaves out
- The render's two awaits (
prepareRender,commitRender) are one step,
so clicks during a slow render are not explored. applyActionscalled from page code (applyActionsExternally) is not
modeled. It raisesacceptedEpochwhile a queued call is in flight,
so it is the next thing to add.retireanddisposehappen only through a remounting render, not on
their own.- Page code that the bridge calls in the middle of a step:
dispatchEventlisteners,$onEventhandlers,citry:events:*
lifecycle listeners, and Vue watchers that run after a State refresh.
Any of these can callsend()or remove a component, which the model
rules out while a response is being applied. - Only one component spot, one handler with
latestCallWinsand one
without, and server actions that always target the caller. - Errors, timeouts, and attachments are not modeled.
Where else this could help
Ranked by how much ordering matters:
- The rest of the events protocol: the server side of State tokens and
sendSequence, and the HTML-fragment client in
src/citry-fragments.ts. - Render caches and their invalidation, where two renders can overlap.
- For the parser, compiler, formatter, and
python_safe_eval, which do
not depend on ordering, property-based tests, fuzzing, or Kani
(which proves small Rust functions cannot panic) would find more for
the effort than TLA+.
To resume
- Get TLC: a JDK 17 or newer, plus
tla2tools.jarfrom the
TLA+ releases. Run
java -cp tla2tools.jar tlc2.TLC -workers auto -config <rule>.cfg EventsBridge.tla. - Add the page-code listeners above to the model, then
applyActionsExternally. - Before adding TLC to CI, state its cost and what it protects, as
CLAUDE.mdasks for any new verification step. Running it by hand
when the bridge changes may be enough.
The model (EventsBridge.tla) and one config
Each rule was checked in its own run, with a config like this one:
CONSTANTS MaxJobs = 3
MaxGen = 2
SPECIFICATION Spec
CHECK_DEADLOCK FALSE
INVARIANT NoEffectAfterCancel
Use PROPERTY instead of INVARIANT for NoRollback, SettledStays,
and EverySettles.
---------------------------- MODULE EventsBridge ----------------------------
(***************************************************************************)
(* A model of the Vue Events bridge in *)
(* packages/js/citry-client/src/citry-events-vue.ts, for one component *)
(* place (one stableId). *)
(* *)
(* JavaScript runs one piece of code at a time, and switches only at an *)
(* `await`. So each step below is the code between two awaits: the fetch, *)
(* a delay timer, or the render commit. *)
(* *)
(* Action codes in a server response: *)
(* "S" state, no delay (applied before the others, "hoisted") *)
(* "SD" state, delay, wait:false (runs detached on a timer) *)
(* "SDW" state, delay, blocking *)
(* "ED" event, delay, wait:false *)
(* "EDW" event, delay, blocking *)
(* "RM" render that replaces (remounts) the calling component *)
(* "D" data *)
(***************************************************************************)
EXTENDS Naturals, Sequences, FiniteSets
CONSTANTS MaxJobs, MaxGen
\* The responses the server may send. A real server always ends with data.
Lists == { <<"S", "D">>, <<"SD", "D">>, <<"SDW", "D">>, <<"ED", "D">>,
<<"EDW", "D">>, <<"RM", "ED", "D">>, <<"RM", "SDW", "D">>,
<<"RM", "D">> }
VARIABLES
gen, \* generation of the instance mounted at the place now
live, \* generations whose owner record still exists (not retired)
epoch, \* epoch[g]: that owner's acceptedEpoch
queue, \* job ids waiting to be sent, in order
active, \* the job runQueue is working on, or 0
nJobs,
jobs, \* jobs[id]: one send() call
timers, \* detached delayed actions waiting on their timer
accepted, \* responses accepted so far; also each response's number
pageVersion, \* number of the response whose State token the page holds
cancelledEffect, \* ghost: a cancelled call changed the page
staleEffect \* ghost: an action ran after a newer result was applied
vars == <<gen, live, epoch, queue, active, nJobs, jobs, timers, accepted,
pageVersion, cancelledEffect, staleEffect>>
Range(s) == { s[i] : i \in 1..Len(s) }
(* Between accepting a response and its first real await (a delay timer *)
(* or the render), the bridge only chains microtasks, so no click, timer *)
(* or network event can run. "applying" marks that stretch. *)
Quiet == IF active = 0 THEN TRUE ELSE jobs[active].phase /= "applying"
NoJob == [g |-> 0, latest |-> FALSE, phase |-> "none", settled |-> FALSE,
cancelled |-> FALSE, remounted |-> FALSE, ep |-> 0, resp |-> 0,
todo |-> <<>>, pending |-> "none"]
Init ==
/\ gen = 1
/\ live = {1}
/\ epoch = [g \in 1..MaxGen |-> 0]
/\ queue = <<>>
/\ active = 0
/\ nJobs = 0
/\ jobs = [k \in 1..MaxJobs |-> NoJob]
/\ timers = {}
/\ accepted = 0
/\ pageVersion = 0
/\ cancelledEffect = FALSE
/\ staleEffect = FALSE
(* continuationCurrent(): the owner still has the epoch this response was *)
(* accepted under, and unless the call's own render remounted the caller, *)
(* the caller is still the mounted instance. *)
ContinuationOK(j) ==
/\ epoch[jobs[j].g] = jobs[j].ep
/\ jobs[j].remounted \/ (jobs[j].g \in live /\ jobs[j].g = gen)
\* Record the ghost flags for a visible change made on behalf of job j.
Flag(j) ==
/\ cancelledEffect' = (cancelledEffect \/ jobs[j].cancelled)
/\ staleEffect' = (staleEffect \/ accepted > jobs[j].resp)
NoFlag == UNCHANGED <<cancelledEffect, staleEffect>>
\* host.commitState matches by render ID. The automatic target is the
\* caller's render ID, which exists only while generation g is mounted.
CommitState(j) ==
IF gen = jobs[j].g
THEN /\ pageVersion' = jobs[j].resp
/\ Flag(j)
ELSE UNCHANGED pageVersion /\ NoFlag
\* Visible effect of running delayed action a for job j (checks passed).
RunEffect(j, a) ==
IF a \in {"SD", "SDW"} THEN CommitState(j)
ELSE /\ UNCHANGED pageVersion \* event: dispatchEvent always fires here
/\ Flag(j)
\* Settle job j with a rejection or resolution and leave the queue.
Finish(j) ==
jobs' = [jobs EXCEPT ![j].settled = TRUE, ![j].phase = "done"]
-----------------------------------------------------------------------------
(* send(): the user triggers a call from the mounted instance. With *)
(* latestCallWins, earlier calls to the same handler are cancelled. *)
Send(lat) ==
/\ Quiet
/\ nJobs < MaxJobs
/\ LET id == nJobs + 1
victim(k) == /\ jobs[k].latest /\ lat
/\ jobs[k].g = gen
/\ ~jobs[k].settled
/\ (k \in Range(queue) \/ k = active)
victims == { k \in 1..nJobs : victim(k) }
IN /\ nJobs' = id
/\ queue' = Append(SelectSeq(queue, LAMBDA k : k \notin victims), id)
/\ jobs' = [k \in 1..MaxJobs |->
IF k = id
THEN [NoJob EXCEPT !.g = gen, !.latest = lat,
!.phase = "queued"]
ELSE IF k \in victims
THEN [jobs[k] EXCEPT !.settled = TRUE,
!.cancelled = TRUE,
!.phase = IF k = active
THEN jobs[k].phase
ELSE "done"]
ELSE jobs[k]]
/\ UNCHANGED <<gen, live, epoch, active, timers, accepted, pageVersion,
cancelledEffect, staleEffect>>
(* runQueue takes the next job. A job whose instance is gone was already *)
(* removed by retire(), so a settled one is just skipped. *)
Dequeue ==
/\ active = 0
/\ queue /= <<>>
/\ LET j == Head(queue) IN
/\ queue' = Tail(queue)
/\ IF jobs[j].settled
THEN UNCHANGED <<active, jobs>>
ELSE /\ active' = j
/\ jobs' = [jobs EXCEPT ![j].phase = "inflight"]
/\ UNCHANGED <<gen, live, epoch, nJobs, timers, accepted, pageVersion,
cancelledEffect, staleEffect>>
\* A cancelled call loses its race against job.cancelled while in flight.
AbortInflight ==
/\ active /= 0
/\ jobs[active].phase = "inflight"
/\ jobs[active].cancelled
/\ Finish(active)
/\ active' = 0
/\ UNCHANGED <<gen, live, epoch, queue, nJobs, timers, accepted,
pageVersion, cancelledEffect, staleEffect>>
(* The response arrives and is accepted: acceptedEpoch goes up, and an *)
(* undelayed state action is applied at once. *)
Respond(L) ==
/\ active /= 0
/\ jobs[active].phase = "inflight"
/\ ~jobs[active].cancelled
/\ ("RM" \in Range(L)) => gen < MaxGen
/\ LET j == active
g == jobs[j].g
n == accepted + 1
IN /\ g \in live /\ g = gen
/\ accepted' = n
/\ epoch' = [epoch EXCEPT ![g] = @ + 1]
/\ jobs' = [jobs EXCEPT ![j].phase = "applying",
![j].ep = epoch[g] + 1,
![j].resp = n,
![j].todo = SelectSeq(L, LAMBDA a : a /= "S")]
/\ IF "S" \in Range(L)
THEN /\ pageVersion' = n
/\ cancelledEffect' = (cancelledEffect \/ jobs[j].cancelled)
/\ UNCHANGED staleEffect
ELSE UNCHANGED pageVersion /\ NoFlag
/\ UNCHANGED <<gen, live, queue, active, nJobs, timers>>
(* retire(old, acceptedTransaction) as called during the render commit: *)
(* queued work of the old instance is cancelled, the old owner's timers *)
(* are rejected, and the active call is marked acceptedRemount. *)
Remount(j) ==
LET old == gen
oldQueued == { k \in Range(queue) : jobs[k].g = old }
IN /\ gen' = old + 1
/\ live' = (live \ {old}) \cup {old + 1}
/\ queue' = SelectSeq(queue, LAMBDA k : k \notin oldQueued)
/\ timers' = { t \in timers : ~(jobs[t.j].g = old /\ ~t.remountBucket) }
/\ jobs' = [k \in 1..MaxJobs |->
IF k = j
THEN [jobs[k] EXCEPT !.remounted = TRUE,
!.todo = Tail(jobs[k].todo)]
ELSE IF k \in oldQueued
THEN [jobs[k] EXCEPT !.settled = TRUE,
!.cancelled = TRUE,
!.phase = "done"]
ELSE jobs[k]]
\* The render carries the new instance's fresh token.
/\ pageVersion' = jobs[j].resp
/\ Flag(j)
(* The active call runs its next action. *)
StepApply ==
/\ active /= 0
/\ jobs[active].phase = "applying"
/\ LET j == active
t == jobs[j].todo
g == jobs[j].g
ownerRetired == g \notin live
IN
IF t = <<>>
THEN \* all actions applied: resolve (a no-op if already settled)
/\ Finish(j) /\ active' = 0
/\ UNCHANGED <<gen, live, epoch, queue, nJobs, timers, accepted,
pageVersion, cancelledEffect, staleEffect>>
ELSE LET a == Head(t) IN
CASE a \in {"SD", "ED"} ->
\* delay() rejects at once for a retired owner, unless remounted;
\* the detached .catch only reports it.
/\ timers' = IF ownerRetired /\ ~jobs[j].remounted
THEN timers
ELSE timers \cup {[j |-> j, a |-> a,
remountBucket |-> jobs[j].remounted]}
/\ jobs' = [jobs EXCEPT ![j].todo = Tail(t)]
/\ UNCHANGED <<gen, live, epoch, queue, active, nJobs, accepted,
pageVersion, cancelledEffect, staleEffect>>
[] a \in {"SDW", "EDW"} ->
IF ownerRetired /\ ~jobs[j].remounted
THEN /\ Finish(j) /\ active' = 0
/\ UNCHANGED <<gen, live, epoch, queue, nJobs, timers,
accepted, pageVersion, cancelledEffect,
staleEffect>>
ELSE /\ jobs' = [jobs EXCEPT ![j].phase = "delaying",
![j].pending = a,
![j].todo = Tail(t)]
/\ UNCHANGED <<gen, live, epoch, queue, active, nJobs, timers,
accepted, pageVersion, cancelledEffect,
staleEffect>>
[] a = "RM" ->
\* The render races prepareRender/commitRender against
\* job.cancelled, and checks stillCurrent with the epoch.
IF jobs[j].cancelled \/ ~(g \in live /\ g = gen /\ epoch[g] = jobs[j].ep)
THEN /\ Finish(j) /\ active' = 0
/\ UNCHANGED <<gen, live, epoch, queue, nJobs, timers,
accepted, pageVersion, cancelledEffect,
staleEffect>>
ELSE /\ Remount(j)
/\ UNCHANGED <<epoch, active, nJobs, accepted>>
[] a = "D" ->
IF ContinuationOK(j)
THEN /\ jobs' = [jobs EXCEPT ![j].todo = Tail(t)]
/\ UNCHANGED <<gen, live, epoch, queue, active, nJobs, timers,
accepted, pageVersion, cancelledEffect,
staleEffect>>
ELSE /\ Finish(j) /\ active' = 0
/\ UNCHANGED <<gen, live, epoch, queue, nJobs, timers,
accepted, pageVersion, cancelledEffect,
staleEffect>>
(* The timer of a blocking delayed action fires. delay() is not raced *)
(* against job.cancelled, so a cancelled call reaches this step too. *)
FireBlocking ==
/\ active /= 0
/\ jobs[active].phase = "delaying"
/\ LET j == active IN
IF ContinuationOK(j)
THEN /\ RunEffect(j, jobs[j].pending)
/\ jobs' = [jobs EXCEPT ![j].phase = "applying", ![j].pending = "none"]
/\ UNCHANGED <<gen, live, epoch, queue, active, nJobs, timers, accepted>>
ELSE /\ Finish(j) /\ active' = 0
/\ UNCHANGED <<gen, live, epoch, queue, nJobs, timers, accepted,
pageVersion, cancelledEffect, staleEffect>>
(* The timer of a detached delayed action fires. On a failed check the *)
(* bridge fires citry:events:stale and drops the action. *)
FireDetached ==
/\ Quiet
/\ \E t \in timers :
/\ timers' = timers \ {t}
/\ IF ContinuationOK(t.j)
THEN RunEffect(t.j, t.a)
ELSE UNCHANGED pageVersion /\ NoFlag
/\ UNCHANGED <<gen, live, epoch, queue, active, nJobs, jobs, accepted>>
Next ==
\/ \E lat \in BOOLEAN : Send(lat)
\/ Dequeue
\/ AbortInflight
\/ \E L \in Lists : Respond(L)
\/ StepApply
\/ FireBlocking
\/ FireDetached
\* Everything except the user's clicks keeps making progress.
Fairness ==
/\ WF_vars(Dequeue)
/\ WF_vars(AbortInflight)
/\ WF_vars(\E L \in Lists : Respond(L))
/\ WF_vars(StepApply)
/\ WF_vars(FireBlocking)
/\ WF_vars(FireDetached)
Spec == Init /\ [][Next]_vars /\ Fairness
-----------------------------------------------------------------------------
(* What must hold *)
\* The page never goes back to an older State token.
NoRollback == [][pageVersion' >= pageVersion]_pageVersion
\* Once a call is rejected as cancelled (superseded or retired), it changes
\* nothing on the page.
NoEffectAfterCancel == ~cancelledEffect
\* spec.md "Order and timing": a delayed action runs only if no newer
\* result for the calling component has been applied.
NoStaleDelayedAction == ~staleEffect
\* Every call's promise eventually settles.
EverySettles == \A k \in 1..MaxJobs :
(jobs[k].phase = "queued") ~> jobs[k].settled
\* A settled job never becomes unsettled (exactly-once settlement).
SettledStays == [][\A k \in 1..MaxJobs : jobs[k].settled => jobs'[k].settled]_jobs
=============================================================================
Activity