protocol
stringclasses
18 values
prompt
stringclasses
18 values
label
stringclasses
18 values
KVStoreSnapshotIsolation
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. --------------------------- MODULE KVStoreSnapshotIsolation --------------------------- (**************************************************************************) (* A simple key-value store exhibiting snapshot isolation. If two *) (* concurrent transactions write to the same key, the one merging later *) (* will be rejected. If they write different keys both will succeed. For *) (* a more-detailed specification of snapshot isolation, look at the *) (* specifications/SnapshotIsolation specs in the tlaplus/examples repo. *) (**************************************************************************) CONSTANTS Key, \* The set of all keys. Val, \* The set of all values. TxId \* The set of all transaction IDs. VARIABLES store, \* A data store mapping keys to values. tx, \* The set of open snapshot transactions. snapshotStore, \* Snapshots of the store for each transaction. written, \* A log of writes performed within each transaction. missed \* The set of writes invisible to each transaction. ---------------------------------------------------------------------------- NoVal == \* Choose something to represent the absence of a value. CHOOSE v : v \notin Val Store == \* The set of all key-value stores. [Key -> Val \cup {NoVal}] Init == \* The initial predicate. /\ store = [k \in Key |-> NoVal] \* All store values are initially NoVal. /\ tx = {} \* The set of open transactions is initially empty. /\ snapshotStore = \* All snapshotStore values are initially NoVal. [t \in TxId |-> [k \in Key |-> NoVal]] /\ written = [t \in TxId |-> {}] \* All write logs are initially empty. /\ missed = [t \in TxId |-> {}] \* All missed writes are initially empty. TypeInvariant == \* The type invariant. /\ store \in Store /\ tx \subseteq TxId /\ snapshotStore \in [TxId -> Store] /\ written \in [TxId -> SUBSET Key] /\ missed \in [TxId -> SUBSET Key] TxLifecycle == /\ \A t \in tx : \* If store != snapshot & we haven't written it, we must have missed a write. \A k \in Key : (store[k] /= snapshotStore[t][k] /\ k \notin written[t]) => k \in missed[t] /\ \A t \in TxId \ tx : \* Checks transactions are cleaned up after disposal. /\ \A k \in Key : snapshotStore[t][k] = NoVal /\ written[t] = {} /\ missed[t] = {} OpenTx(t) == \* Open a new transaction. /\ t \notin tx /\ tx' = tx \cup {t} /\ snapshotStore' = [snapshotStore EXCEPT ![t] = store] /\ UNCHANGED <<written, missed, store>> (* MASKED CODE *) Update(t, k, v) == \* Using transaction t, update the value associated with key k to v. /\ t \in tx /\ snapshotStore[t][k] \notin {NoVal, v} /\ snapshotStore' = [snapshotStore EXCEPT ![t][k] = v] /\ written' = [written EXCEPT ![t] = @ \cup {k}] /\ UNCHANGED <<tx, missed, store>> Remove(t, k) == \* Using transaction t, remove key k from the store. /\ t \in tx /\ snapshotStore[t][k] /= NoVal /\ snapshotStore' = [snapshotStore EXCEPT ![t][k] = NoVal] /\ written' = [written EXCEPT ![t] = @ \cup {k}] /\ UNCHANGED <<tx, missed, store>> RollbackTx(t) == \* Close the transaction without merging writes into store. /\ t \in tx /\ tx' = tx \ {t} /\ snapshotStore' = [snapshotStore EXCEPT ![t] = [k \in Key |-> NoVal]] /\ written' = [written EXCEPT ![t] = {}] /\ missed' = [missed EXCEPT ![t] = {}] /\ UNCHANGED store CloseTx(t) == \* Close transaction t, merging writes into store. /\ t \in tx /\ missed[t] \cap written[t] = {} \* Detection of write-write conflicts. /\ store' = \* Merge snapshotStore writes into store. [k \in Key |-> IF k \in written[t] THEN snapshotStore[t][k] ELSE store[k]] /\ tx' = tx \ {t} /\ missed' = \* Update the missed writes for other open transactions. [otherTx \in TxId |-> IF otherTx \in tx' THEN missed[otherTx] \cup written[t] ELSE {}] /\ snapshotStore' = [snapshotStore EXCEPT ![t] = [k \in Key |-> NoVal]] /\ written' = [written EXCEPT ![t] = {}] Next == \* The next-state relation. \/ \E t \in TxId : OpenTx(t) \/ \E t \in tx : \E k \in Key : \E v \in Val : Add(t, k, v) \/ \E t \in tx : \E k \in Key : \E v \in Val : Update(t, k, v) \/ \E t \in tx : \E k \in Key : Remove(t, k) \/ \E t \in tx : RollbackTx(t) \/ \E t \in tx : CloseTx(t) Spec == \* Initialize state with Init and transition with Next. Init /\ [][Next]_<<store, tx, snapshotStore, written, missed>> ---------------------------------------------------------------------------- THEOREM Spec => [](TypeInvariant /\ TxLifecycle) ============================================================================= ### Assistant:
Add(t, k, v) == \* Using transaction t, add value v to the store under key k. /\ t \in tx /\ snapshotStore[t][k] = NoVal /\ snapshotStore' = [snapshotStore EXCEPT ![t][k] = v] /\ written' = [written EXCEPT ![t] = @ \cup {k}] /\ UNCHANGED <<tx, missed, store>>
Echo
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. -------------------------------- MODULE Echo -------------------------------- (***************************************************************************) (* The Echo algorithm for constructing a spanning tree in an undirected *) (* graph starting from a single initiator, as a PlusCal algorithm. *) (***************************************************************************) EXTENDS Naturals, FiniteSets, Relation, TLC CONSTANTS Node, \* set of nodes (* MASKED CODE *) ASSUME /\ initiator \in Node /\ R \in [Node \X Node -> BOOLEAN] \* No edge from a node to itself (self-loops). /\ IsIrreflexive(R, Node) \* Undirected graph (there exists an edge from b \* to a if there exists an edge from a to b). /\ IsSymmetric(R, Node) \* There exists a spanning tree consisting of *all* nodes. \* (no forest of spanning trees). /\ IsConnected(R, Node) NoNode == CHOOSE x : x \notin Node neighbors(n) == { m \in Node : R[m,n] } (** --algorithm Echo { variable inbox = [n \in Node |-> {}]; \* model communication between nodes define { \* sending and receiving messages \* network obtained from net when p sends message of kind knd to q send(net, p, q, knd) == [net EXCEPT ![q] = @ \cup {[kind |-> knd, sndr |-> p]}] \* network obtained from net when p receives a message receive(net, p, msg) == [net EXCEPT ![p] = @ \ {msg}] \* network obtained from net when p send message of kind knd to all nodes in dest multicast(net, p, dest, knd) == [m \in Node |-> IF m \in dest THEN net[m] \cup {[kind |-> knd, sndr |-> p]} ELSE net[m]] } process (node \in Node) variables parent = NoNode, children = {}, rcvd = 0, nbrs = neighbors(self); { n0: if (self = initiator) { \* initiator sends first message to all its neighbors inbox := multicast(inbox, self, nbrs, "m") }; n1: while (rcvd < Cardinality(nbrs)) { \* receive some message from a neighbor with (msg \in inbox[self], net = receive(inbox, self, msg)) { rcvd := rcvd+1; if (self # initiator /\ rcvd = 1) { assert(msg.kind = "m"); \* the first received message is always of type "m" \* note the sender as the node's parent and send an "m" message to all remaining neighbors parent := msg.sndr; inbox := multicast(net, self, nbrs \ {msg.sndr}, "m") } else { \* subsequent messages are counted but don't give rise to another message inbox := net }; if (msg.kind = "c") { children := children \cup {msg.sndr} } } \* end with }; \* end while n2: if (self # initiator) { \* when non-initiator has received messages from all neighbors, acknowledge \* child relationship to the parent assert(parent \in nbrs); inbox := send(inbox, self, parent, "c") } } \* end process } **) \* BEGIN TRANSLATION VARIABLES inbox, pc (* define statement *) send(net, p, q, knd) == [net EXCEPT ![q] = @ \cup {[kind |-> knd, sndr |-> p]}] receive(net, p, msg) == [net EXCEPT ![p] = @ \ {msg}] multicast(net, p, dest, knd) == [m \in Node |-> IF m \in dest THEN net[m] \cup {[kind |-> knd, sndr |-> p]} ELSE net[m]] VARIABLES parent, children, rcvd, nbrs vars == << inbox, pc, parent, children, rcvd, nbrs >> ProcSet == (Node) Init == (* Global variables *) /\ inbox = [n \in Node |-> {}] (* Process node *) /\ parent = [self \in Node |-> NoNode] /\ children = [self \in Node |-> {}] /\ rcvd = [self \in Node |-> 0] /\ nbrs = [self \in Node |-> neighbors(self)] /\ pc = [self \in ProcSet |-> "n0"] n0(self) == /\ pc[self] = "n0" /\ IF self = initiator THEN /\ inbox' = multicast(inbox, self, nbrs[self], "m") ELSE /\ TRUE /\ inbox' = inbox /\ pc' = [pc EXCEPT ![self] = "n1"] /\ UNCHANGED << parent, children, rcvd, nbrs >> n1(self) == /\ pc[self] = "n1" /\ IF rcvd[self] < Cardinality(nbrs[self]) THEN /\ \E msg \in inbox[self]: LET net == receive(inbox, self, msg) IN /\ rcvd' = [rcvd EXCEPT ![self] = rcvd[self]+1] /\ IF self # initiator /\ rcvd'[self] = 1 THEN /\ Assert((msg.kind = "m"), "Failure of assertion at line 50, column 16.") /\ parent' = [parent EXCEPT ![self] = msg.sndr] /\ inbox' = multicast(net, self, nbrs[self] \ {msg.sndr}, "m") ELSE /\ inbox' = net /\ UNCHANGED parent /\ IF msg.kind = "c" THEN /\ children' = [children EXCEPT ![self] = children[self] \cup {msg.sndr}] ELSE /\ TRUE /\ UNCHANGED children /\ pc' = [pc EXCEPT ![self] = "n1"] ELSE /\ pc' = [pc EXCEPT ![self] = "n2"] /\ UNCHANGED << inbox, parent, children, rcvd >> /\ nbrs' = nbrs n2(self) == /\ pc[self] = "n2" /\ IF self # initiator THEN /\ Assert((parent[self] \in nbrs[self]), "Failure of assertion at line 65, column 10.") /\ inbox' = send(inbox, self, parent[self], "c") ELSE /\ TRUE /\ inbox' = inbox /\ pc' = [pc EXCEPT ![self] = "Done"] /\ UNCHANGED << parent, children, rcvd, nbrs >> node(self) == n0(self) \/ n1(self) \/ n2(self) (* Allow infinite stuttering to prevent deadlock on termination. *) Terminating == /\ \A self \in ProcSet: pc[self] = "Done" /\ UNCHANGED vars Next == (\E self \in Node: node(self)) \/ Terminating Spec == Init /\ [][Next]_vars Termination == <>(\A self \in ProcSet: pc[self] = "Done") \* END TRANSLATION (***************************************************************************) (* Correctness properties. *) (***************************************************************************) TypeOK == /\ parent \in [Node -> (Node \cup {NoNode})] /\ children \in [Node -> SUBSET Node] /\ rcvd \in [Node -> Nat] /\ nbrs \in [Node -> SUBSET Node] /\ \A n \in Node : nbrs[n] = neighbors(n) /\ rcvd[n] <= Cardinality(nbrs[n]) /\ inbox \in [Node -> SUBSET [kind : {"m","c"}, sndr : Node]] /\ \A n \in Node : \A msg \in inbox[n] : msg.sndr \in nbrs[n] (* The initiator never has a parent *) InitiatorNoParent == parent[initiator] = NoNode (* If a node has a parent, it is a neighbor node *) ParentIsNeighbor == \A n \in Node : parent[n] \in neighbors(n) \cup {NoNode} (* A node n is a child of node m only if m is the parent of n. At the end of the computation, this is "if and only if". *) ParentChild == \A m,n \in Node : /\ n \in children[m] => m = parent[n] /\ m = parent[n] /\ pc[m] = "Done" => n \in children[m] (* Compute the ancestor relation *) IsParent == [m,n \in Node |-> n = parent[m]] IsAncestor == TransitiveClosure(IsParent, Node) (* At the end of the computation, the initiator is an ancestor of every other node and the ancestor relation is acyclic. Beware: evaluating this property over any but tiny graphs is costly. *) AncestorProperties == (\A n \in Node : pc[n] = "Done") => LET anc == IsAncestor IN /\ \A n \in Node \ {initiator} : anc[n, initiator] /\ IsIrreflexive(anc, Node) ============================================================================= \* Modification History \* Last modified Wed Jun 17 09:23:17 PDT 2020 by markus \* Last modified Sun Jun 14 17:11:39 CEST 2020 by merz \* Created Tue Apr 26 09:42:23 CEST 2016 by merz ### Assistant:
initiator, \* single initiator, will be the root of the tree R \* neighborhood relation, represented as a Boolean function over nodes
CoffeeCan
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ---------------------------- MODULE CoffeeCan ------------------------------- (***************************************************************************) (* This is a spec for the Coffee Can problem, a math problem usually *) (* attributed to David Gries in his 1987 book The Science of Programming. *) (* However, on page 301 section 23.2 of the same book Gries attributes the *) (* problem to a 1979 letter by Edsger W. Dijkstra, who himself credits the *) (* problem to his colleague Carel S. Scholten. *) (* *) (* The problem as presented on page 165 of The Science of Programming: *) (* *) (* A coffee can contains some black beans and white beans. The following *) (* process is to be repeated as long as possible: *) (* *) (* Randomly select two beans from the can. If they are the same color, *) (* throw them out, but put another black bean in. (Enough extra black *) (* beans are available to do this.) If they are different colors, place *) (* the white one back into the can and throw the black one away. *) (* *) (* Execution of this process reduces the number of beans in the can by *) (* one. Repetition of this process must terminate with exactly one bean in *) (* the can, for then two beans cannot be selected. The question is: what, *) (* if anything, can be said about the color of the final bean based on the *) (* number of white beans and the number of black beans initially in the *) (* can? *) (* *) (* We model this problem in TLA⁺ with a focus on two things: *) (* 1. Validate a monotonic decrease in number of beans at each step *) (* 2. Identify a loop/inductive invariant *) (* 3. Form a hypothesis about the final bean and modelcheck it *) (* *) (* Finite modelchecking can only check our properties for a finite number *) (* of beans, while we want to show that it holds for all Natural numbers. *) (* TLA⁺'s built-in proof language can be used for this purpose, although *) (* such a proof is not currently included in this spec. *) (* *) (***************************************************************************) EXTENDS Naturals CONSTANT MaxBeanCount ASSUME MaxBeanCount \in Nat /\ MaxBeanCount >= 1 VARIABLES can \* The set of all possible cans Can == [black : 0..MaxBeanCount, white : 0..MaxBeanCount] \* Possible values the can variable can take on TypeInvariant == can \in Can \* Initialize can so it contains between 1 and MaxBeanCount beans Init == can \in {c \in Can : c.black + c.white \in 1..MaxBeanCount} \* Number of beans currently in the can BeanCount == can.black + can.white \* Pick two black beans; throw both away, put one black bean in PickSameColorBlack == /\ BeanCount > 1 /\ can.black >= 2 /\ can' = [can EXCEPT !.black = @ - 1] \* Pick two white beans; throw both away, put one black bean in PickSameColorWhite == /\ BeanCount > 1 /\ can.white >= 2 /\ can' = [can EXCEPT !.black = @ + 1, !.white = @ - 2] \* Pick one bean of each color; put white back, throw away black PickDifferentColor == /\ BeanCount > 1 /\ can.black >= 1 /\ can.white >= 1 /\ can' = [can EXCEPT !.black = @ - 1] \* Termination action to avoid triggering deadlock detection Termination == /\ BeanCount = 1 /\ UNCHANGED can \* Next-state relation: what actions can be taken? Next == \/ PickSameColorWhite \/ PickSameColorBlack \/ PickDifferentColor \/ Termination \* Action formula: every step decreases the number of beans in the can MonotonicDecrease == [][BeanCount' < BeanCount]_can \* Liveness property: we eventually end up with one bean left (* MASKED CODE *) \* Loop invariant: every step preserves white bean count mod 2 LoopInvariant == [][can.white % 2 = 0 <=> can'.white % 2 = 0]_can \* Hypothesis: If we start out with an even number of white beans, we end up \* with a single black bean. Otherwise, we end up with a single white bean. TerminationHypothesis == IF can.white % 2 = 0 THEN <>(can.black = 1 /\ can.white = 0) ELSE <>(can.black = 0 /\ can.white = 1) \* Start out in a state defined by the Init operator and every step is one \* defined by the Next operator. Assume weak fairness so the system can't \* stutter indefinitely: we eventually take some beans out of the can. Spec == /\ Init /\ [][Next]_can /\ WF_can(Next) \* What we want to show: that if our system follows the rules set out by the \* Spec operator, then all our properties and assumptions will be satisfied. THEOREM Spec => /\ TypeInvariant /\ MonotonicDecrease /\ EventuallyTerminates /\ LoopInvariant /\ TerminationHypothesis ============================================================================= ### Assistant:
EventuallyTerminates == <>(ENABLED Termination)
SimpleAllocator
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ------------------------ MODULE SimpleAllocator ------------------------- (***********************************************************************) (* Specification of an allocator managing a set of resources: *) (* - Clients can request sets of resources whenever all their previous *) (* requests have been satisfied. *) (* - Requests can be partly fulfilled, and resources can be returned *) (* even before the full request has been satisfied. However, clients *) (* only have an obligation to return resources after they have *) (* obtained all resources they requested. *) (***********************************************************************) EXTENDS FiniteSets, TLC CONSTANTS Clients, \* set of all clients Resources \* set of all resources ASSUME IsFiniteSet(Resources) VARIABLES unsat, \* set of all outstanding requests per process alloc \* set of resources allocated to given process TypeInvariant == /\ unsat \in [Clients -> SUBSET Resources] /\ alloc \in [Clients -> SUBSET Resources] ------------------------------------------------------------------------- (* Resources are available iff they have not been allocated. *) available == Resources \ (UNION {alloc[c] : c \in Clients}) (* Initially, no resources have been requested or allocated. *) Init == /\ unsat = [c \in Clients |-> {}] /\ alloc = [c \in Clients |-> {}] (* A client c may request a set of resources provided that all of its *) (* previous requests have been satisfied and that it doesn't hold any *) (* resources. *) Request(c,S) == /\ unsat[c] = {} /\ alloc[c] = {} /\ S # {} /\ unsat' = [unsat EXCEPT ![c] = S] /\ UNCHANGED alloc (* Allocation of a set of available resources to a client that *) (* requested them (the entire request does not have to be filled). *) Allocate(c,S) == /\ S # {} /\ S \subseteq available \cap unsat[c] /\ alloc' = [alloc EXCEPT ![c] = @ \cup S] /\ unsat' = [unsat EXCEPT ![c] = @ \ S] (* Client c returns a set of resources that it holds. It may do so *) (* even before its full request has been honored. *) Return(c,S) == /\ S # {} /\ S \subseteq alloc[c] /\ alloc' = [alloc EXCEPT ![c] = @ \ S] /\ UNCHANGED unsat (* The next-state relation. *) (* MASKED CODE *) vars == <<unsat,alloc>> ------------------------------------------------------------------------- (* The complete high-level specification. *) SimpleAllocator == /\ Init /\ [][Next]_vars /\ \A c \in Clients: WF_vars(Return(c, alloc[c])) /\ \A c \in Clients: SF_vars(\E S \in SUBSET Resources: Allocate(c,S)) ------------------------------------------------------------------------- ResourceMutex == \A c1,c2 \in Clients : c1 # c2 => alloc[c1] \cap alloc[c2] = {} ClientsWillReturn == \A c \in Clients : unsat[c]={} ~> alloc[c]={} ClientsWillObtain == \A c \in Clients, r \in Resources : r \in unsat[c] ~> r \in alloc[c] InfOftenSatisfied == \A c \in Clients : []<>(unsat[c] = {}) ------------------------------------------------------------------------- (* Used for symmetry reduction with TLC *) Symmetry == Permutations(Clients) \cup Permutations(Resources) ------------------------------------------------------------------------- (* The following version states a weaker fairness requirement for the *) (* clients: resources need be returned only if the entire request has *) (* been satisfied. *) SimpleAllocator2 == /\ Init /\ [][Next]_vars /\ \A c \in Clients: WF_vars(unsat[c] = {} /\ Return(c, alloc[c])) /\ \A c \in Clients: SF_vars(\E S \in SUBSET Resources: Allocate(c,S)) ------------------------------------------------------------------------- THEOREM SimpleAllocator => []TypeInvariant THEOREM SimpleAllocator => []ResourceMutex THEOREM SimpleAllocator => ClientsWillReturn THEOREM SimpleAllocator2 => ClientsWillReturn THEOREM SimpleAllocator => ClientsWillObtain THEOREM SimpleAllocator => InfOftenSatisfied (** The following do not hold: **) (** THEOREM SimpleAllocator2 => ClientsWillObtain **) (** THEOREM SimpleAllocator2 => InfOftenSatisfied **) ========================================================================= ### Assistant:
Next == \E c \in Clients, S \in SUBSET Resources : Request(c,S) \/ Allocate(c,S) \/ Return(c,S)
ReadersWriters
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. -------------------------- MODULE ReadersWriters -------------------------- (***************************************************************************) (* This solution to the readers-writers problem, cf. *) (* https://en.wikipedia.org/wiki/Readers–writers_problem, *) (* uses a queue in order to fairly serve all requests. *) (***************************************************************************) EXTENDS FiniteSets, Naturals, Sequences CONSTANT NumActors VARIABLES readers, \* set of processes currently reading writers, \* set of processes currently writing waiting \* queue of processes waiting to access the resource vars == <<readers, writers, waiting>> Actors == 1..NumActors ToSet(s) == { s[i] : i \in DOMAIN s } read(s) == s[1] = "read" write(s) == s[1] = "write" WaitingToRead == { p[2] : p \in ToSet(SelectSeq(waiting, read)) } WaitingToWrite == { p[2] : p \in ToSet(SelectSeq(waiting, write)) } --------------------------------------------------------------------------- (***********) (* Actions *) (***********) TryRead(actor) == /\ actor \notin WaitingToRead /\ waiting' = Append(waiting, <<"read", actor>>) /\ UNCHANGED <<readers, writers>> (* MASKED CODE *) Read(actor) == /\ readers' = readers \union {actor} /\ waiting' = Tail(waiting) /\ UNCHANGED writers Write(actor) == /\ readers = {} /\ writers' = writers \union {actor} /\ waiting' = Tail(waiting) /\ UNCHANGED readers ReadOrWrite == /\ waiting /= <<>> /\ writers = {} /\ LET pair == Head(waiting) actor == pair[2] IN CASE pair[1] = "read" -> Read(actor) [] pair[1] = "write" -> Write(actor) StopActivity(actor) == IF actor \in readers THEN /\ readers' = readers \ {actor} /\ UNCHANGED <<writers, waiting>> ELSE /\ writers' = writers \ {actor} /\ UNCHANGED <<readers, waiting>> Stop == \E actor \in readers \cup writers : StopActivity(actor) --------------------------------------------------------------------------- (*****************) (* Specification *) (*****************) Init == /\ readers = {} /\ writers = {} /\ waiting = <<>> Next == \/ \E actor \in Actors : TryRead(actor) \/ \E actor \in Actors : TryWrite(actor) \/ ReadOrWrite \/ Stop Fairness == /\ \A actor \in Actors : WF_vars(TryRead(actor)) /\ \A actor \in Actors : WF_vars(TryWrite(actor)) /\ WF_vars(ReadOrWrite) /\ WF_vars(Stop) Spec == Init /\ [][Next]_vars /\ Fairness --------------------------------------------------------------------------- (**************) (* Invariants *) (**************) TypeOK == /\ readers \subseteq Actors /\ writers \subseteq Actors /\ waiting \in Seq({"read", "write"} \times Actors) Safety == /\ ~(readers /= {} /\ writers /= {}) /\ Cardinality(writers) <= 1 (**************) (* Properties *) (**************) Liveness == /\ \A actor \in Actors : []<>(actor \in readers) /\ \A actor \in Actors : []<>(actor \in writers) /\ \A actor \in Actors : []<>(actor \notin readers) /\ \A actor \in Actors : []<>(actor \notin writers) ============================================================================ ### Assistant:
TryWrite(actor) == /\ actor \notin WaitingToWrite /\ waiting' = Append(waiting, <<"write", actor>>) /\ UNCHANGED <<readers, writers>>
Majority
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. -------------------------------- MODULE Majority ----------------------------- (****************************************************************************) (* TLA+ specification and proof of the majority vote algorithm due to Boyer *) (* and Moore. *) (* R.S. Boyer, J.S. Moore: MJRTY - A Fast Majority Vote Algorithm. *) (* In: R.S. Boyer (ed.): Automated Reasoning: Essays in Honor of Woody *) (* Bledsoe, pp. 105-117. Dordrecht, The Netherlands, 1991. *) (* Originally published in a technical report from 1981. *) (* The algorithm takes as input a sequence of values, makes one pass over *) (* the sequence, and reports an element cand such that no element other *) (* than cand may have an absolute majority in the sequence. *) (****************************************************************************) EXTENDS Integers, Sequences, FiniteSets CONSTANT Value ASSUME ConstAssump == Value # {} (****************************************************************************) (* Although seq is an input to the algorithm, we make it a variable so that *) (* we can use the model checker to verify the algorithm for all sequences *) (* up to some bounded size. *) (****************************************************************************) VARIABLES seq, \* input sequence of values, never changes i, \* next position of sequence to be checked cand, \* current candidate for having a majority cnt \* lower bound for the number of occurrences of the candidate so far (* MASKED CODE *) TypeOK == /\ seq \in Seq(Value) /\ i \in 1 .. Len(seq)+1 /\ cand \in Value /\ cnt \in Nat Init == /\ seq \in Seq(Value) /\ i = 1 /\ cand \in Value /\ cnt = 0 Next == /\ i <= Len(seq) /\ i' = i+1 /\ seq' = seq /\ \/ /\ cnt = 0 /\ cand' = seq[i] /\ cnt' = 1 \/ /\ cnt # 0 /\ cand = seq[i] /\ cand' = cand /\ cnt' = cnt + 1 \/ /\ cnt # 0 /\ cand # seq[i] /\ cand' = cand /\ cnt' = cnt - 1 Spec == Init /\ [][Next]_vars /\ WF_vars(Next) (****************************************************************************) (* Definitions used for stating correctness. *) (****************************************************************************) \* set of indexes in the prefix of the sequence strictly before j holding v PositionsBefore(v,j) == { k \in 1 .. (j-1) : seq[k] = v } \* number of times v occurs in that prefix OccurrencesBefore(v,j) == Cardinality(PositionsBefore(v,j)) \* number of times v occurs in all of the sequence Occurrences(x) == OccurrencesBefore(x, Len(seq)+1) \* main correctness property: cand can be the only value that has a majority Correct == i > Len(seq) => \A v \in Value : 2 * Occurrences(v) > Len(seq) => v = cand \* inductive invariant for proving correctness Inv == /\ cnt <= OccurrencesBefore(cand, i) /\ 2 * (OccurrencesBefore(cand, i) - cnt) <= i - 1 - cnt /\ \A v \in Value \ {cand} : 2 * OccurrencesBefore(v, i) <= i - 1 - cnt ============================================================================== ### Assistant:
vars == <<seq, i, cand, cnt>>
SlidingPuzzles
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. --------------------------- MODULE SlidingPuzzles --------------------------- EXTENDS Integers VARIABLE board W == 4 H == 5 Pos == (0 .. W - 1) \X (0 .. H - 1) Piece == SUBSET Pos Klotski == {{<<0, 0>>, <<0, 1>>}, {<<1, 0>>, <<2, 0>>, <<1, 1>>, <<2, 1>>}, {<<3, 0>>, <<3, 1>>},{<<0, 2>>, <<0, 3>>}, {<<1, 2>>, <<2, 2>>},{<<3, 2>>, <<3, 3>>}, {<<1, 3>>}, {<<2, 3>>}, {<<0, 4>>}, {<<3, 4>>}} KlotskiGoal == {<<1, 3>>, <<1, 4>>, <<2, 3>>, <<2, 4>>} \notin board ChooseOne(S, P(_)) == CHOOSE x \in S : P(x) /\ \A y \in S : P(y) => y = x TypeOK == board \in SUBSET Piece (***************************************************************************) (* Given a position and a set of empty positions return a set of *) (* appropriately filtered von Neumann neighborhood points *) (***************************************************************************) dir(p, es) == LET dir == {<<1, 0>>, <<0, 1>>, <<-1, 0>>, <<0, -1>>} IN {d \in dir : /\ <<p[1] + d[1], p[2] + d[2]>> \in Pos /\ <<p[1] + d[1], p[2] + d[2]>> \notin es} (***************************************************************************) (* Given a position and a unit translation vector return a pair of *) (* pieces, before and after translation in opposite this vector direction *) (***************************************************************************) move(p, d) == LET s == <<p[1] + d[1], p[2] + d[2]>> pc == ChooseOne(board, LAMBDA pc : s \in pc) IN <<pc, {<<q[1] - d[1], q[2] - d[2]>> : q \in pc}>> (***************************************************************************) (* Given specific free position and a set of all free positions return *) (* a set of boards updated by moving appropriate pieces to that *) (* free position *) (***************************************************************************) update(e, es) == LET dirs == dir(e, es) moved == {move(e, d) : d \in dirs} free == {<<pc, m>> \in moved : /\ m \cap (UNION (board \ {pc})) = {} /\ \A p \in m : p \in Pos} IN {(board \ {pc}) \cup {m} : <<pc, m>> \in free} Init == board = Klotski (* MASKED CODE *) ============================================================================= ### Assistant:
Next == LET empty == Pos \ UNION board IN \E e \in empty : board' \in update(e, empty)
SchedulingAllocator
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ------------------------ MODULE SchedulingAllocator --------------------- (***********************************************************************) (* Specification of an allocator managing a set of resources: *) (* - Clients can request sets of resources whenever all their previous *) (* requests have been satisfied. *) (* - Requests can be partly fulfilled, and resources can be returned *) (* even before the full request has been satisfied. However, clients *) (* only have an obligation to return resources after they have *) (* obtained all resources they requested. *) (* This allocator operates by repeatedly choosing a schedule according *) (* to which requests are satisfied. Resources can be allocated out of *) (* order as long as no client earlier in the schedule asks for them. *) (***********************************************************************) EXTENDS FiniteSets, Sequences, Naturals, TLC CONSTANTS Clients, \* set of all clients Resources \* set of all resources ASSUME IsFiniteSet(Resources) VARIABLES unsat, \* set of all outstanding requests per process alloc, \* set of resources allocated to given process sched \* schedule represented as a sequence of clients TypeInvariant == /\ unsat \in [Clients -> SUBSET Resources] /\ alloc \in [Clients -> SUBSET Resources] /\ sched \in Seq(Clients) ------------------------------------------------------------------------- (* The set of permutations of a finite set, represented as sequences. *) PermSeqs(S) == LET perms[ss \in SUBSET S] == IF ss = {} THEN { << >> } ELSE LET ps == [ x \in ss |-> { Append(sq,x) : sq \in perms[ss \ {x}] } ] IN UNION { ps[x] : x \in ss } IN perms[S] (* Remove element at index i from a sequence. *) (* Assumes that i \in 1..Len(seq) *) Drop(seq,i) == SubSeq(seq, 1, i-1) \circ SubSeq(seq, i+1, Len(seq)) (* Resources are available iff they have not been allocated. *) available == Resources \ (UNION {alloc[c] : c \in Clients}) (* Range of a function, e.g. elements of a sequence *) Range(f) == { f[x] : x \in DOMAIN f } (* Clients with pending requests that have not yet been scheduled *) toSchedule == { c \in Clients : unsat[c] # {} /\ c \notin Range(sched) } (* Initially, no resources have been requested or allocated. *) Init == /\ unsat = [c \in Clients |-> {}] /\ alloc = [c \in Clients |-> {}] /\ sched = << >> (* A client c may request a set of resources provided that all of its *) (* previous requests have been satisfied and that it doesn't hold any *) (* resources. The client is added to the pool of clients with *) (* outstanding requests. *) Request(c,S) == /\ unsat[c] = {} /\ alloc[c] = {} /\ S # {} /\ unsat' = [unsat EXCEPT ![c] = S] /\ UNCHANGED <<alloc,sched>> (* Allocation of a set of available resources to a client that has *) (* requested them (the entire request does not have to be filled). *) (* The process must appear in the schedule, and no process earlier in *) (* the schedule may have requested one of the resources. *) Allocate(c,S) == /\ S # {} /\ S \subseteq available \cap unsat[c] /\ \E i \in DOMAIN sched : /\ sched[i] = c /\ \A j \in 1..i-1 : unsat[sched[j]] \cap S = {} /\ sched' = IF S = unsat[c] THEN Drop(sched,i) ELSE sched /\ alloc' = [alloc EXCEPT ![c] = @ \cup S] /\ unsat' = [unsat EXCEPT ![c] = @ \ S] (* Client c returns a set of resources that it holds. It may do so *) (* even before its full request has been honored. *) Return(c,S) == /\ S # {} /\ S \subseteq alloc[c] /\ alloc' = [alloc EXCEPT ![c] = @ \ S] /\ UNCHANGED <<unsat,sched>> (* The allocator extends its schedule by adding the processes from *) (* the set of clients to be scheduled, in some unspecified order. *) Schedule == /\ toSchedule # {} /\ \E sq \in PermSeqs(toSchedule) : sched' = sched \circ sq /\ UNCHANGED <<unsat,alloc>> (* The next-state relation per client and set of resources. *) Next == \/ \E c \in Clients, S \in SUBSET Resources : Request(c,S) \/ Allocate(c,S) \/ Return(c,S) \/ Schedule vars == <<unsat,alloc,sched>> ------------------------------------------------------------------------- (***********************************************************************) (* Liveness assumptions: *) (* - Clients must return resources if their request has been satisfied.*) (* - The allocator must eventually allocate resources when possible. *) (* - The allocator must schedule the processes in the pool. *) (***********************************************************************) Liveness == /\ \A c \in Clients : WF_vars(unsat[c]={} /\ Return(c,alloc[c])) /\ \A c \in Clients : WF_vars(\E S \in SUBSET Resources : Allocate(c, S)) /\ WF_vars(Schedule) (* The specification of the scheduling allocator. *) Allocator == Init /\ [][Next]_vars /\ Liveness ------------------------------------------------------------------------- ResourceMutex == \** resources are allocated exclusively \A c1,c2 \in Clients : c1 # c2 => alloc[c1] \cap alloc[c2] = {} UnscheduledClients == \** clients that do not appear in the schedule Clients \ Range(sched) PrevResources(i) == \** resources that will be available when client i has to be satisfied available \cup (UNION {unsat[sched[j]] \cup alloc[sched[j]] : j \in 1..i-1}) \cup (UNION {alloc[c] : c \in UnscheduledClients}) AllocatorInvariant == \** a lower-level invariant /\ \** all clients in the schedule have outstanding requests \A i \in DOMAIN sched : unsat[sched[i]] # {} /\ \** all clients that need to be scheduled have outstanding requests \A c \in toSchedule : unsat[c] # {} /\ \** clients never hold a resource requested by a process earlier \** in the schedule \A i \in DOMAIN sched : \A j \in 1..i-1 : alloc[sched[i]] \cap unsat[sched[j]] = {} /\ \** the allocator can satisfy the requests of any scheduled client \** assuming that the clients scheduled earlier release their resources \A i \in DOMAIN sched : unsat[sched[i]] \subseteq PrevResources(i) ClientsWillReturn == \A c \in Clients: (unsat[c]={} ~> alloc[c]={}) ClientsWillObtain == \A c \in Clients, r \in Resources : r \in unsat[c] ~> r \in alloc[c] (* MASKED CODE *) (* Used for symmetry reduction with TLC. Note: because of the schedule sequence, the specification is no longer symmetric with respect to the processes! *) Symmetry == Permutations(Resources) ------------------------------------------------------------------------- THEOREM Allocator => []TypeInvariant THEOREM Allocator => []ResourceMutex THEOREM Allocator => []AllocatorInvariant THEOREM Allocator => ClientsWillReturn THEOREM Allocator => ClientsWillObtain THEOREM Allocator => InfOftenSatisfied ========================================================================= ### Assistant:
InfOftenSatisfied == \A c \in Clients : []<>(unsat[c] = {})
FastPaxos
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. --------------------------- MODULE FastPaxos ----------------------------- (* This is a simplified specification of Leslie Lamport's Fast Paxos protocol. The following papers, Fast Paxos by Leslie Lamport and Fast Paxos Made Easy: Theory and Implementation by Zhao Wenbing was referenced in writing this specification. This simplified specification was written by Lim Ngian Xin Terry & Gaurav Gandhi. The following assumptions are made in this simplified specification. 1. There is a unique coordinator in the system. Therefore, Phase 1a and 1b can be omitted. 2. All agents in the system can communicate with one another. 3. Agents must have some stable storage that survives failure and restarts. An agent restores its state from stable storage when it restarts, so the failure of an agent is indistinguishable from its simply pausing. There is thus no need to model failures explicitly. *) EXTENDS Paxos CONSTANTS FastQuorums, FastBallots VARIABLES cValue \* Value chosen by coordinator. ClassicBallots == Ballots \ FastBallots \* The set of ballots of classic rounds. FastAssume == /\ \A q \in FastQuorums : q \subseteq Replicas /\ \A q, r \in FastQuorums : q \intersect r # {} /\ \A q \in FastQuorums : (3 * Cardinality(Replicas)) \div 4 <= Cardinality(q) /\ \A q \in Quorums : \A r, s \in FastQuorums : q \intersect r \intersect s # {} ASSUME PaxosAssume /\ FastAssume IsMajorityValue(M, v) == Cardinality(M) \div 2 < Cardinality({m \in M : m.value = v}) (* Phase 2a (Fast): The coordinator starts a fast round by sending a P2a "Any" message, if no other values has been proposed before. *) FastAny == /\ UNCHANGED<<decision, maxBallot, maxVBallot, maxValue, cValue>> /\ \E f \in FastBallots : /\ SendMessage([type |-> "P2a", ballot |-> f, value |-> any]) (* Phase 2b (Fast): Acceptors can reply to a P2a "Any" message with a P2b message containing their proposed value. *) FastPropose == /\ UNCHANGED<<decision, cValue>> /\ \E a \in Replicas, m \in p2aMessages, v \in Values: /\ m.value = any /\ maxBallot[a] <= m.ballot /\ maxValue[a] = none \/ maxValue[a] = v /\ maxBallot' = [maxBallot EXCEPT ![a] = m.ballot] /\ maxVBallot' = [maxVBallot EXCEPT ![a] = m.ballot] /\ maxValue' = [maxValue EXCEPT ![a] = v] /\ \A n \in p2bMessages : ~(n.ballot = m.ballot /\ n.acceptor = a) /\ SendMessage([type |-> "P2b", ballot |-> m.ballot, acceptor |-> a, value |-> v]) (* A value is chosen if a fast quorum of acceptors proposed that value in a fast round. Because the quorum size of a fast round and classic round is different, we assume that the acceptor distinguishes a fast round and classic round based on the P2a message it receives. If the P2a message contains the special value "any", it is a fast round. Else it is a classic round. *) FastDecide == /\ UNCHANGED<<messages, maxBallot, maxVBallot, maxValue, cValue>> /\ \E b \in FastBallots, q \in FastQuorums : LET M == {m \in p2bMessages : m.ballot = b /\ m.acceptor \in q} V == {w \in Values : \E m \in M : w = m.value} IN /\ \A a \in q : \E m \in M : m.acceptor = a /\ 1 = Cardinality(V) /\ \E m \in M : decision' = m.value (* Phase 2a (Classic) If more than one value has been proposed, the collision is resolved using the following rules: 1. If the proposals contain different values, a value must be selected if the majority of acceptors in the fast quorum have casted a vote for that value. 2. Otherwise, the coordinator is free to select any value. *) ClassicAccept == /\ UNCHANGED<<decision, maxBallot, maxVBallot, maxValue>> /\ \E b \in ClassicBallots, f \in FastBallots, q \in FastQuorums, v \in Values : /\ f < b \* There was a fast round before this classic round. /\ cValue = none \/ cValue = v /\ cValue' = v /\ \A m \in p2aMessages : m.ballot # b /\ LET M == {m \in p2bMessages : m.ballot = f /\ m.acceptor \in q} V == {w \in Values : \E m \in M : w = m.value} IN /\ \A a \in q : \E m \in M : m.acceptor = a /\ 1 < Cardinality(V) \* Collision occurred. /\ IF \E w \in V : IsMajorityValue(M, w) THEN IsMajorityValue(M, v) \* Choose majority in quorum. ELSE v \in V \* Choose any. /\ SendMessage([type |-> "P2a", ballot |-> b, value |-> v]) (* Phase 2b (Classic) Same as in Paxos. *) (* MASKED CODE *) (* Consensus is achieved when a majority of acceptors accept the same ballot number. Functionally similar to PaxosDecide in Paxos.tla, but we also have to ensure that it can only occur in classic rounds and not fast rounds. *) ClassicDecide == /\ UNCHANGED<<messages, maxBallot, maxVBallot, maxValue, cValue>> /\ \E b \in ClassicBallots, q \in Quorums : LET M == {m \in p2bMessages : m.ballot = b /\ m.acceptor \in q} IN /\ \A a \in q : \E m \in M : m.acceptor = a /\ \E m \in M : decision' = m.value FastTypeOK == /\ PaxosTypeOK /\ cValue \in Values \union {none} FastInit == /\ PaxosInit /\ cValue = none FastNext == \/ FastAny \/ FastPropose \/ FastDecide \/ ClassicAccept \/ ClassicAccepted \/ ClassicDecide FastSpec == /\ FastInit /\ [][FastNext]_<<messages, decision, maxBallot, maxVBallot, maxValue, cValue>> /\ SF_<<messages, decision, maxBallot, maxVBallot, maxValue, cValue>>(FastDecide) /\ SF_<<messages, decision, maxBallot, maxVBallot, maxValue, cValue>>(ClassicDecide) \* Non-triviality safety property: Only proposed values can be learnt. FastNontriviality == \/ decision = none \/ \E m \in p2bMessages : m.value = decision /\ m.ballot \in FastBallots =============================================================== ### Assistant:
ClassicAccepted == /\ UNCHANGED<<cValue>> /\ PaxosAccepted
DiningPhilosophers
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ---- MODULE DiningPhilosophers ---- (* TLA+ / PlusCal implementation of the Dining Philosophers problem. Based on the exercise given in https://learntla.com/temporal-logic/operators/ This is an implementation of the Chandy-Misra solution. https://en.wikipedia.org/wiki/Dining_philosophers_problem#Chandy/Misra_solution In Dijkstra's original formulation of the problem, philosophers may not speak to each other and cannot hand forks to each other. In the Chandy-Misra formulation, philosophers may hand forks directly to each other. I ran this with alygin's TLA+ extension for VSCode: https://marketplace.visualstudio.com/items?itemName=alygin.vscode-tlaplus "> TLA+: Parse module" updates the translated TLA+ to match the PlusCal 'algorithm' above. "> TLA+: Check model with TLC" checks the model's correctness. You can also use TLA+ Toolbox. You may need to "create a model" and use the UI to add the invariants and properties at the bottom of this file. *) EXTENDS Integers, TLC CONSTANTS \* Number of philosophers NP ASSUME /\ NP \in Nat \ {0} (* --algorithm DiningPhilosophers variables forks = [ fork \in 1..NP |-> [ \* We start with each fork held by the lowest-number philosopher \* adjacent to the fork. holder |-> IF fork = 2 THEN 1 ELSE fork, \* Each fork starts out "dirty". Eating causes a fork to become \* dirty, after which the philosopher must clean the fork and hand \* it to their neighbor. clean |-> FALSE ] ] define LeftFork(p) == p RightFork(p) == IF p = NP THEN 1 ELSE p + 1 LeftPhilosopher(p) == IF p = 1 THEN NP ELSE p - 1 RightPhilosopher(p) == IF p = NP THEN 1 ELSE p + 1 IsHoldingBothForks(p) == forks[LeftFork(p)].holder = p /\ forks[RightFork(p)].holder = p BothForksAreClean(p) == forks[LeftFork(p)].clean /\ forks[RightFork(p)].clean CanEat(p) == IsHoldingBothForks(p) /\ BothForksAreClean(p) end define; \* This spawns 'NP' parallel Philosopher processes. \* \* A process looks kind of like an object oriented class, but '\in 1..NP' means \* it's really just an integer between 1 and NP. Use 'self' to access that \* integer. \* \* If you remove the 'fair' in 'fair process', each process can stop at any \* time and will never run again. Dining philosophers don't randomly die while \* clenching forks in the original problem, so let's keep the processes fair. fair process Philosopher \in 1..NP \* This acts like a member variable and you can access it like one. But we're \* actually creating an array with one element per process, and the "member \* variable" we access is just the corresponding bucket in that array. variables hungry = TRUE; begin Loop: while TRUE do \* Check if we're holding dirty forks that other philosophers might \* want. if /\ forks[LeftFork(self)].holder = self /\ ~forks[LeftFork(self)].clean then forks[LeftFork(self)] := [ holder |-> LeftPhilosopher(self), clean |-> TRUE ]; elsif /\ forks[RightFork(self)].holder = self /\ ~forks[RightFork(self)].clean then forks[RightFork(self)] := [ holder |-> RightPhilosopher(self), clean |-> TRUE ]; end if; if hungry then if CanEat(self) then Eat: hungry := FALSE; forks[LeftFork(self)].clean := FALSE || forks[RightFork(self)].clean := FALSE; end if; else Think: hungry := TRUE; end if; end while; end process; end algorithm; *) \* BEGIN TRANSLATION (chksum(pcal) = "8d8268d4" /\ chksum(tla) = "16352822") VARIABLES forks, pc (* define statement *) LeftFork(p) == p RightFork(p) == IF p = NP THEN 1 ELSE p + 1 LeftPhilosopher(p) == IF p = 1 THEN NP ELSE p - 1 RightPhilosopher(p) == IF p = NP THEN 1 ELSE p + 1 (* MASKED CODE *) CanEat(p) == IsHoldingBothForks(p) /\ BothForksAreClean(p) VARIABLE hungry vars == << forks, pc, hungry >> ProcSet == (1..NP) Init == (* Global variables *) /\ forks = [ fork \in 1..NP |-> [ holder |-> IF fork = 2 THEN 1 ELSE fork, clean |-> FALSE ] ] (* Process Philosopher *) /\ hungry = [self \in 1..NP |-> TRUE] /\ pc = [self \in ProcSet |-> "Loop"] Loop(self) == /\ pc[self] = "Loop" /\ IF /\ forks[LeftFork(self)].holder = self /\ ~forks[LeftFork(self)].clean THEN /\ forks' = [forks EXCEPT ![LeftFork(self)] = [ holder |-> LeftPhilosopher(self), clean |-> TRUE ]] ELSE /\ IF /\ forks[RightFork(self)].holder = self /\ ~forks[RightFork(self)].clean THEN /\ forks' = [forks EXCEPT ![RightFork(self)] = [ holder |-> RightPhilosopher(self), clean |-> TRUE ]] ELSE /\ TRUE /\ forks' = forks /\ IF hungry[self] THEN /\ IF CanEat(self) THEN /\ pc' = [pc EXCEPT ![self] = "Eat"] ELSE /\ pc' = [pc EXCEPT ![self] = "Loop"] ELSE /\ pc' = [pc EXCEPT ![self] = "Think"] /\ UNCHANGED hungry Think(self) == /\ pc[self] = "Think" /\ hungry' = [hungry EXCEPT ![self] = TRUE] /\ pc' = [pc EXCEPT ![self] = "Loop"] /\ forks' = forks Eat(self) == /\ pc[self] = "Eat" /\ hungry' = [hungry EXCEPT ![self] = FALSE] /\ forks' = [forks EXCEPT ![LeftFork(self)].clean = FALSE, ![RightFork(self)].clean = FALSE] /\ pc' = [pc EXCEPT ![self] = "Loop"] Philosopher(self) == Loop(self) \/ Think(self) \/ Eat(self) Next == (\E self \in 1..NP: Philosopher(self)) Spec == /\ Init /\ [][Next]_vars /\ \A self \in 1..NP : WF_vars(Philosopher(self)) \* END TRANSLATION ---- (* Invariant helpers *) ---- (* TRUE iff philosophers p and q share a fork between them. *) ShareFork(p, q) == {LeftFork(p), RightFork(p)} \cap {LeftFork(q), RightFork(q)} /= {} ---- (* Invariants *) ---- (* TLA+ and PlusCal are dynamically-typed, but we can roll our own typechecking with an invariant. *) TypeOK == /\ forks \in [1..NP -> [holder: 1..NP, clean: BOOLEAN]] /\ hungry \in [1..NP -> BOOLEAN] /\ pc \in [1..NP -> {"Loop", "Eat", "Think"}] (* If two philosophers share a fork, they cannot eat at the same time. *) ExclusiveAccess == \A p,q \in 1..NP: p /= q /\ ShareFork(p, q) => ~(pc[p] = "Eat" /\ pc[q] = "Eat") ---- (* Properties *) ---- (* Every philosopher will eventually get to eat again. *) NobodyStarves == \A p \in 1..NP: []<>(~hungry[p]) ==== ### Assistant:
IsHoldingBothForks(p) == forks[LeftFork(p)].holder = p /\ forks[RightFork(p)].holder = p BothForksAreClean(p) == forks[LeftFork(p)].clean /\ forks[RightFork(p)].clean
FindHighest
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ---------------------------- MODULE FindHighest ----------------------------- (***************************************************************************) (* Defines a very simple algorithm that finds the largest value in a *) (* sequence of Natural numbers. This was created as an exercise in finding *) (* & proving type invariants, inductive invariants, and correctness. *) (***************************************************************************) EXTENDS Sequences, Naturals, Integers, TLAPS (**************************************************************************** --algorithm Highest { variables f \in Seq(Nat); h = -1; i = 1; define { max(a, b) == IF a >= b THEN a ELSE b } { lb: while (i <= Len(f)) { h := max(h, f[i]); i := i + 1; } } } ****************************************************************************) \* BEGIN TRANSLATION (chksum(pcal) = "31f24270" /\ chksum(tla) = "819802c6") VARIABLES f, h, i, pc (* define statement *) max(a, b) == IF a >= b THEN a ELSE b vars == << f, h, i, pc >> Init == (* Global variables *) /\ f \in Seq(Nat) /\ h = -1 /\ i = 1 /\ pc = "lb" lb == /\ pc = "lb" /\ IF i <= Len(f) THEN /\ h' = max(h, f[i]) /\ i' = i + 1 /\ pc' = "lb" ELSE /\ pc' = "Done" /\ UNCHANGED << h, i >> /\ f' = f (* Allow infinite stuttering to prevent deadlock on termination. *) Terminating == pc = "Done" /\ UNCHANGED vars Next == lb \/ Terminating Spec == Init /\ [][Next]_vars (* MASKED CODE *) \* END TRANSLATION \* The type invariant; the proof system likes knowing variables are in Nat. \* It's a good idea to check these invariants with the model checker before \* trying to prove them. To quote Leslie Lamport, it's very difficult to \* prove something that isn't true! TypeOK == /\ f \in Seq(Nat) /\ i \in 1..(Len(f) + 1) /\ i \in Nat /\ h \in Nat \cup {-1} \* It's useful to prove the type invariant first, so it can be used as an \* assumption in further proofs to restrict variable values. THEOREM TypeInvariantHolds == Spec => []TypeOK \* To prove theorems like Spec => []Invariant, you have to: \* 1. Prove Invariant holds in the initial state (usually trivial) \* 2. Prove Invariant holds when variables are unchanged (usually trivial) \* 3. Prove that assuming Invariant is true, a Next step implies Invariant' \* The last one (inductive case) is usually quite difficult. It helps to \* never forget you have an extremely powerful assumption: that Invariant is \* true! PROOF \* The base case <1>a. Init => TypeOK BY DEFS Init, TypeOK \* The stuttering case <1>b. TypeOK /\ UNCHANGED vars => TypeOK' BY DEFS TypeOK, vars \* The inductive case; usually requires breaking down Next into disjuncts <1>c. TypeOK /\ Next => TypeOK' <2>a. TypeOK /\ lb => TypeOK' BY DEFS TypeOK, lb, max <2>b. TypeOK /\ Terminating => TypeOK' BY DEFS TypeOK, Terminating, vars <2> QED BY <2>a, <2>b DEF Next <1> QED BY PTL, <1>a, <1>b, <1>c DEF Spec \* The inductive invariant; writing these is an art. You want an invariant \* that can be shown to be true in every state, and if it's true in all \* states, it can be shown to imply algorithm correctness as a whole. InductiveInvariant == \A idx \in 1..(i - 1) : f[idx] <= h THEOREM InductiveInvariantHolds == Spec => []InductiveInvariant PROOF <1>a. Init => InductiveInvariant BY DEFS Init, InductiveInvariant <1>b. InductiveInvariant /\ UNCHANGED vars => InductiveInvariant' BY DEFS InductiveInvariant, vars <1>c. InductiveInvariant /\ TypeOK /\ TypeOK' /\ Next => InductiveInvariant' <2>a. InductiveInvariant /\ Terminating => InductiveInvariant' BY DEFS InductiveInvariant, Terminating, vars <2>b. InductiveInvariant /\ TypeOK /\ lb => InductiveInvariant' BY DEFS InductiveInvariant, TypeOK, lb, max <2> QED BY <2>a, <2>b DEF Next \* We need to note we made use of the type invariant theorem here <1> QED BY PTL, <1>a, <1>b, <1>c, TypeInvariantHolds DEF Spec \* A small sub-theorem that relates our inductive invariant to correctness DoneIndexValue == pc = "Done" => i = Len(f) + 1 THEOREM DoneIndexValueThm == Spec => []DoneIndexValue PROOF <1>a. Init => DoneIndexValue BY DEF Init, DoneIndexValue <1>b. DoneIndexValue /\ UNCHANGED vars => DoneIndexValue' BY DEFS DoneIndexValue, vars <1>c. DoneIndexValue /\ TypeOK /\ Next => DoneIndexValue' <2>a. DoneIndexValue /\ Terminating => DoneIndexValue' BY DEFS DoneIndexValue, Terminating, vars <2>b. DoneIndexValue /\ TypeOK /\ lb => DoneIndexValue' BY DEFS DoneIndexValue, TypeOK, lb <2> QED BY <2>a, <2>b DEF Next <1> QED BY PTL, <1>a, <1>b, <1>c, TypeInvariantHolds DEF Spec \* The main event! After the algorithm has terminated, the variable h must \* have value greater than or equal to any element of the sequence. Correctness == pc = "Done" => \A idx \in DOMAIN f : f[idx] <= h THEOREM IsCorrect == Spec => []Correctness PROOF <1>a. Init => Correctness BY DEF Init, Correctness <1>b. Correctness /\ UNCHANGED vars => Correctness' BY DEF Correctness, vars <1>c. /\ Correctness /\ InductiveInvariant' /\ DoneIndexValue' /\ Next => Correctness' <2>a. Correctness /\ Terminating => Correctness' BY DEF Correctness, Terminating, vars <2>b. /\ Correctness /\ InductiveInvariant' /\ DoneIndexValue' /\ lb => Correctness' BY DEFS Correctness, InductiveInvariant, DoneIndexValue, lb <2> QED BY <2>a, <2>b DEF Next <1> QED BY <1>a, <1>b, <1>c, InductiveInvariantHolds, DoneIndexValueThm, PTL DEF Spec ============================================================================= ### Assistant:
Termination == <>(pc = "Done")
Prisoners
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ------------------------------ MODULE Prisoners ----------------------------- (***************************************************************************) (* This module specifies the solution to the following puzzle, given on *) (* the Car Guys NPR radio show: *) (* *) (* The warden of a prison gives his prisoners the following problem. *) (* There is a room in the prison with two switches, labeled A and B. *) (* Each switch can be either up or down. Every so often, the warden *) (* will select a prisoner at random and take him into the room, where *) (* he must flip (change the position of) exactly one of the switches. *) (* The only guarantee he makes is that every prisoner will eventually *) (* be brought into the room multiple times. (More precisely, there *) (* will never be a time after which some prisoner is never again *) (* brought into the room.) *) (* *) (* At any time, any prisoner may declare that all the prisoners have *) (* been in the room at least once. If that prisoner is right, then *) (* all the prisoners go free. If he is wrong, all the prisoners are *) (* immediately executed. *) (* *) (* The prisoners are allowed to decide upon a strategy, after which *) (* they will not be allowed to communicate with one another. And, of *) (* course, they cannot see the room or who is being brought into it. *) (* What do they do? *) (* *) (* The solution presented by the Car Guys is specified below. *) (***************************************************************************) EXTENDS Naturals, FiniteSets CONSTANTS Prisoner, (***********************************************************************) (* The set of all prisoners. *) (***********************************************************************) Counter (***********************************************************************) (* This is an arbitrarily chosen prisoner, who will do the necessary *) (* counting. *) (***********************************************************************) ASSUME (*************************************************************************) (* We assume that the counter is a prisoner. We also assume that there *) (* is more than one prisoner. (The problem is trivial if there is a *) (* single prisoner.) *) (*************************************************************************) /\ Counter \in Prisoner /\ Cardinality(Prisoner) > 1 OtherPrisoner == Prisoner \ {Counter} (*************************************************************************) (* The set of all prisoners other than the counter. *) (*************************************************************************) VARIABLES switchAUp, switchBUp, (***********************************************************************) (* The states of the two switches, represented by boolean-valued *) (* variables. *) (***********************************************************************) timesSwitched, (***********************************************************************) (* For ever prisoner except the counter, timesSwitched[p] is the *) (* number of times prisoner p has moved switch A up. It is initially *) (* 0 and will equal at most 2. *) (***********************************************************************) count (***********************************************************************) (* The number of times the Counter has switched switch A down. *) (***********************************************************************) vars == <<switchAUp, switchBUp, timesSwitched, count>> (*************************************************************************) (* The tuple of all variables. *) (*************************************************************************) ----------------------------------------------------------------------------- (***************************************************************************) (* We first define three state predicates. *) (***************************************************************************) TypeOK == (*************************************************************************) (* The type-correctness invariant. This is not actually part of the *) (* specification. It is added to help the reader understand the *) (* specification and also because letting TLC (the model checker) check *) (* that it is an invariant is a good way to debug the specification. *) (* *) (* Note the bound on the value of count. *) (*************************************************************************) /\ switchAUp \in BOOLEAN /\ switchBUp \in BOOLEAN /\ timesSwitched \in [OtherPrisoner -> 0..2] /\ count \in 0 .. (2 * Cardinality(Prisoner) - 1) Init == (*************************************************************************) (* The initial predicate. *) (*************************************************************************) /\ switchAUp \in BOOLEAN /\ switchBUp \in BOOLEAN /\ timesSwitched = [i \in OtherPrisoner |-> 0] /\ count = 0 Done == (*************************************************************************) (* This is the condition that tells the counter that every other *) (* prisoner has been in the room at least once. (He will trivially know *) (* that he's already been in the room when this condition is true.) *) (*************************************************************************) count = 2 * (Cardinality(Prisoner) - 1) ----------------------------------------------------------------------------- (***************************************************************************) (* Next come the actions performed by each prisoner when he (or she) is *) (* brought into the room with the switches. *) (***************************************************************************) NonCounterStep(i) == (*************************************************************************) (* A prisoner other than the counter moves switch A up if it is down and *) (* if (s)he has not already moved it up two times. Otherwise, (s)he *) (* flips switch B. *) (*************************************************************************) /\ IF (~switchAUp) /\ (timesSwitched[i] < 2) THEN /\ switchAUp' = TRUE /\ timesSwitched' = [timesSwitched EXCEPT ![i] = @+1] /\ UNCHANGED switchBUp ELSE /\ switchBUp' = ~switchBUp /\ UNCHANGED <<switchAUp, timesSwitched>> /\ UNCHANGED count CounterStep == (*************************************************************************) (* If switch A is up, the counter moves it down and increments his (or *) (* her) count. Otherwise, (s)he flips switch B. *) (*************************************************************************) /\ IF switchAUp THEN /\ switchAUp' = FALSE /\ UNCHANGED switchBUp /\ count' = count + 1 ELSE /\ switchBUp' = ~switchBUp /\ UNCHANGED <<switchAUp, count>> /\ UNCHANGED timesSwitched Next == (*************************************************************************) (* The next-state relation *) (*************************************************************************) \/ CounterStep \/ \E i \in OtherPrisoner : NonCounterStep(i) Fairness == (*************************************************************************) (* This asserts that every prisoner is brought into the room infinitely *) (* often. *) (*************************************************************************) /\ WF_vars(CounterStep) /\ \A i \in OtherPrisoner : WF_vars(NonCounterStep(i)) (* MASKED CODE *) Liveness == <>Done (*************************************************************************) (* This asserts that Done is eventually true, so the prisoners are *) (* eventually released. *) (*************************************************************************) THEOREM Spec => Safety /\ Liveness (*************************************************************************) (* This theorem asserts that the specification satisfies properties *) (* Safety and Liveness. TLC verifies this in a few seconds for the case *) (* of a half dozen prisoners. It also quickly provides a counterexample *) (* if Done is changed to assert a smaller value of count. *) (*************************************************************************) CountInvariant == (*************************************************************************) (* This is an invariant of Spec. From its invariance, one can easily *) (* prove that Spec satisfies its safety property. *) (*************************************************************************) LET totalSwitched == (*******************************************************************) (* A recursive definition of the sum, over all p in OtherPrisoner, *) (* of timesSwitched[p]. *) (*******************************************************************) LET sum[S \in SUBSET OtherPrisoner] == IF S = {} THEN 0 ELSE LET p == CHOOSE pr \in S : TRUE IN timesSwitched[p] + sum[S \ {p}] IN sum[OtherPrisoner] oneIfUp == IF switchAUp THEN 1 ELSE 0 (*******************************************************************) (* Equals 1 if switch A is up, 0 otherwise. *) (*******************************************************************) IN count \in {totalSwitched - oneIfUp, totalSwitched - oneIfUp + 1} ============================================================================= ### Assistant:
Spec == Init /\ [][Next]_vars /\ Fairness ----------------------------------------------------------------------------- Safety == (*************************************************************************) (* This formula asserts that safety condition: that Done true implies *) (* that every prisoner other than the counter has flipped switch A at *) (* least once--and hence has been in the room at least once. Since the *) (* counter increments the count only when in the room, and Done implies *) (* count > 0, it also implies that the counter has been in the room. *) (*************************************************************************) [](Done => (\A i \in Prisoner \ {Counter} : timesSwitched[i] > 0))
RingLeader
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ---------------------------- MODULE ring_leader ---------------------------- (***************************************************************************) (* Algorithm by Chang and Roberts for electing a leader on a *) (* unidirectional ring. The algorithm originally appeared as *) (* E. Chang, R. Roberts: An improved algorithm for decentralized *) (* extrema-finding in circular configurations of processes, *) (* CACM 22(5): 281-283, 1979. *) (***************************************************************************) EXTENDS Naturals, Sequences (***************************************************************************) (* Constant parameters: *) (* - N is the number of nodes *) (* - Id is a sequence of natural numbers of length N such that *) (* Id[i] denotes the identity of node i. *) (* The algorithm can be initiated by several nodes, and the node with *) (* the smallest identity will be elected as the leader. *) (***************************************************************************) CONSTANTS N, Id ConstN == 6 ConstId == <<27, 4, 42, 15, 63, 9>> Node == 1 .. N ASSUME /\ N \in Nat \ {0} /\ Id \in Seq(Nat) /\ Len(Id) = N /\ \A m,n \in Node : m # n => Id[m] # Id[n] \* IDs are unique succ(n) == IF n=N THEN 1 ELSE n+1 \* successor along the ring (** Chang-Roberts algorithm written in PlusCal --algorithm ring_leader { (* msgs[n]: messages waiting to be received by node n *) variable msgs = [n \in Node |-> {}]; fair process (node \in Node) variables (* this node may be an initiator or not *) initiator \in BOOLEAN, state = IF initiator THEN "cand" ELSE "lost"; { \* initiators send their own ID to their neighbor n0: if (initiator) { msgs[succ(self)] := @ \cup {Id[self]} }; n1: while (TRUE) { \* handle some incoming message with (id \in msgs[self], _msgs = [msgs EXCEPT ![self] = @ \ {id}]) { if (state = "lost") { \* nodes that have already lost forward the message msgs := [_msgs EXCEPT ![succ(self)] = @ \cup {id}] } else if (id < Id[self]) { \* received smalled ID: record loss and forward the message state := "lost"; msgs := [_msgs EXCEPT ![succ(self)] = @ \cup {id}] } else { \* do not forward the message; if it's the own ID, declare win msgs := _msgs; if (id = Id[self]) { state := "won" } } } \* end with } \* end while } \* end process } \* end algorithm **) \* BEGIN TRANSLATION (chksum(pcal) = "65c8d352" /\ chksum(tla) = "33951c89") VARIABLES msgs, pc, initiator, state vars == << msgs, pc, initiator, state >> ProcSet == (Node) Init == (* Global variables *) /\ msgs = [n \in Node |-> {}] (* Process node *) /\ initiator \in [Node -> BOOLEAN] /\ state = [self \in Node |-> IF initiator[self] THEN "cand" ELSE "lost"] /\ pc = [self \in ProcSet |-> "n0"] n0(self) == /\ pc[self] = "n0" /\ IF initiator[self] THEN /\ msgs' = [msgs EXCEPT ![succ(self)] = @ \cup {Id[self]}] ELSE /\ TRUE /\ msgs' = msgs /\ pc' = [pc EXCEPT ![self] = "n1"] /\ UNCHANGED << initiator, state >> n1(self) == /\ pc[self] = "n1" /\ \E id \in msgs[self]: LET _msgs == [msgs EXCEPT ![self] = @ \ {id}] IN IF state[self] = "lost" THEN /\ msgs' = [_msgs EXCEPT ![succ(self)] = @ \cup {id}] /\ state' = state ELSE /\ IF id < Id[self] THEN /\ state' = [state EXCEPT ![self] = "lost"] /\ msgs' = [_msgs EXCEPT ![succ(self)] = @ \cup {id}] ELSE /\ msgs' = _msgs /\ IF id = Id[self] THEN /\ state' = [state EXCEPT ![self] = "won"] ELSE /\ TRUE /\ state' = state /\ pc' = [pc EXCEPT ![self] = "n1"] /\ UNCHANGED initiator node(self) == n0(self) \/ n1(self) (* Allow infinite stuttering to prevent deadlock on termination. *) Terminating == /\ \A self \in ProcSet: pc[self] = "Done" /\ UNCHANGED vars Next == (\E self \in Node: node(self)) \/ Terminating Spec == /\ Init /\ [][Next]_vars /\ \A self \in Node : WF_vars(node(self)) Termination == <>(\A self \in ProcSet: pc[self] = "Done") \* END TRANSLATION ----------------------------------------------------------------------------- (* type correctness *) TypeOK == /\ pc \in [Node -> {"n0", "n1", "Done"}] /\ msgs \in [Node -> SUBSET {Id[n] : n \in Node}] /\ initiator \in [Node -> BOOLEAN] /\ state \in [Node -> {"cand", "lost", "won"}] (***************************************************************************) (* Safety property: when node n wins the election, it is the initiator *) (* with the smallest ID, and all other nodes know that they lost. *) (***************************************************************************) (* MASKED CODE *) Liveness == (\E n \in Node : state[n] = "cand") => <>(\E n \in Node : state[n] = "won") ============================================================================= \* Modification History \* Last modified Tue Apr 27 20:05:58 PDT 2021 by markus \* Last modified Sat Mar 24 10:00:11 CET 2018 by merz \* Created Sat Apr 23 14:05:31 CEST 2016 by merz ### Assistant:
Correctness == \A n \in Node : state[n] = "won" => /\ initiator[n] /\ \A m \in Node \ {n} : /\ state[m] = "lost" /\ initiator[m] => Id[m] > Id[n]
SingleLaneBridge
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. -------------------------- MODULE SingleLaneBridge -------------------------- \* A bridge over a river is only wide enough to permit a single lane of traffic. \* Consequently, cars can only move concurrently if they are moving in the same \* direction. A safety violation occurs if two cars moving in different directions \* enter the bridge at the same time. \* To visualize the problem, refer to https://flylib.com/books/en/2.752.1.48/1/ EXTENDS Naturals, FiniteSets, Sequences CONSTANTS CarsRight, CarsLeft, Bridge, Positions VARIABLES Location, WaitingBeforeBridge vars == <<Location, WaitingBeforeBridge>> (* MASKED CODE *) StartBridge == CHOOSE min \in Bridge : \A e \in Bridge : min <= e EndBridge == CHOOSE max \in Bridge : \A e \in Bridge : max >= e ASSUME CarsRight \cap CarsLeft = {} ASSUME Cardinality(CarsRight \union CarsLeft ) # 0 ASSUME StartPos < StartBridge /\ EndPos > EndBridge /\ Cardinality(Bridge) < Cardinality(Positions) RECURSIVE SeqFromSet(_) SeqFromSet(S) == IF S = {} THEN << >> ELSE LET x == CHOOSE x \in S : TRUE IN << x >> \o SeqFromSet(S \ {x}) Cars == CarsRight \union CarsLeft CarsInBridge == { c \in Cars : Location[c] \in Bridge } CarsBeforeBridge == { car \in CarsRight : EndPos - EndBridge = 1 } \cup { car \in CarsLeft : StartBridge - StartPos = 1 } RMove(pos) == IF pos > StartPos THEN pos - 1 ELSE EndPos LMove(pos) == IF pos < EndPos THEN pos + 1 ELSE StartPos NextLocation(car) == IF car \in CarsRight THEN RMove(Location[car]) ELSE LMove(Location[car]) ChangeLocation(car) == /\ IF \/ car \in CarsRight /\ NextLocation(car) = EndBridge + 1 \/ car \in CarsLeft /\ NextLocation(car) = StartBridge - 1 THEN WaitingBeforeBridge' = Append(WaitingBeforeBridge, car) ELSE UNCHANGED WaitingBeforeBridge /\ Location' = [ Location EXCEPT ![car] = NextLocation(car) ] HaveSameDirection(car) == \/ car \in CarsRight /\ \A c \in CarsInBridge : c \in CarsRight \/ car \in CarsLeft /\ \A c \in CarsInBridge : c \in CarsLeft \* Actions MoveOutsideBridge(car) == /\ NextLocation(car) \notin Bridge /\ ChangeLocation(car) MoveInsideBridge(car) == /\ car \in CarsInBridge /\ \A c \in Cars : Location[c] # NextLocation(car) /\ ChangeLocation(car) EnterBridge == \/ /\ CarsInBridge = {} /\ Len(WaitingBeforeBridge) # 0 /\ Location' = [ Location EXCEPT ![Head(WaitingBeforeBridge)] = NextLocation(Head(WaitingBeforeBridge)) ] /\ WaitingBeforeBridge' = Tail(WaitingBeforeBridge) \/ /\ Len(WaitingBeforeBridge) # 0 /\ Head(WaitingBeforeBridge) \notin CarsInBridge /\ HaveSameDirection(Head(WaitingBeforeBridge)) /\ \A c \in Cars : Location[c] # NextLocation(Head(WaitingBeforeBridge)) /\ Location' = [ Location EXCEPT ![Head(WaitingBeforeBridge)] = NextLocation(Head(WaitingBeforeBridge)) ] /\ WaitingBeforeBridge' = Tail(WaitingBeforeBridge) Init == /\ Location = [ c \in Cars |-> IF c \in CarsRight THEN EndPos ELSE StartPos ] /\ WaitingBeforeBridge = SeqFromSet(CarsBeforeBridge) Next == \E car \in Cars : EnterBridge \/ MoveOutsideBridge(car) \/ MoveInsideBridge(car) Fairness == /\ \A car \in Cars : WF_vars(MoveOutsideBridge(car)) /\ \A car \in Cars : WF_vars(MoveInsideBridge(car)) /\ \A car \in Cars : WF_vars(EnterBridge) Spec == Init /\ [][Next]_vars /\ Fairness Invariants == \* Two cars or more cannot be in the same location in the Bridge at the same time /\ \A a,b \in Cars : /\ Location[a] \in Bridge /\ Location[a] = Location[b] => a = b \* The bridge capacity should be respected /\ Cardinality(CarsInBridge) < Cardinality(Bridge) + 1 \* Two cars of different directions can never be in the bridge /\ \A <<r,l>> \in CarsRight \X CarsLeft : ~ (Location[r] \in Bridge /\ Location[l] \in Bridge) TypeOK == /\ Location \in [ Cars -> Positions ] /\ Len(WaitingBeforeBridge) <= Cardinality(Cars) CarsInBridgeExitBridge == \* All cars eventually exit the Bridge \A car \in Cars : Location[car] \in Bridge ~> Location[car] \notin Bridge CarsEnterBridge == \* All cars eventually enter the bridge \A car \in Cars : Location[car] \notin Bridge ~> Location[car] \in Bridge THEOREM Spec => [] Invariants THEOREM Spec => [] TypeOK THEOREM Spec => CarsInBridgeExitBridge THEOREM Spec => CarsEnterBridge ============================================================================= \* Modification History \* Last modified Tue Oct 12 00:20:28 CEST 2021 by youne ### Assistant:
StartPos == CHOOSE min \in Positions : \A p \in Positions : min <= p EndPos == CHOOSE max \in Positions : \A p \in Positions : max >= p
Paxos
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. -------------------------------- MODULE Paxos ------------------------------- (***************************************************************************) (* This is a specification of the Paxos algorithm without explicit leaders *) (* or learners. It refines the spec in Voting *) (***************************************************************************) EXTENDS Integers ----------------------------------------------------------------------------- (***************************************************************************) (* The constant parameters and the set Ballots are the same as in Voting. *) (***************************************************************************) CONSTANT Value, Acceptor, Quorum ASSUME QuorumAssumption == /\ \A Q \in Quorum : Q \subseteq Acceptor /\ \A Q1, Q2 \in Quorum : Q1 \cap Q2 # {} Ballot == Nat None == CHOOSE v : v \notin Value (*************************************************************************) (* An unspecified value that is not a ballot number. *) (*************************************************************************) (***************************************************************************) (* This is a message-passing algorithm, so we begin by defining the set *) (* Message of all possible messages. The messages are explained below *) (* with the actions that send them. *) (***************************************************************************) Message == [type : {"1a"}, bal : Ballot] \cup [type : {"1b"}, acc : Acceptor, bal : Ballot, mbal : Ballot \cup {-1}, mval : Value \cup {None}] \cup [type : {"2a"}, bal : Ballot, val : Value] \cup [type : {"2b"}, acc : Acceptor, bal : Ballot, val : Value] ----------------------------------------------------------------------------- VARIABLE maxBal, maxVBal, \* <<maxVBal[a], maxVal[a]>> is the vote with the largest maxVal, \* ballot number cast by a; it equals <<-1, None>> if \* a has not cast any vote. msgs \* The set of all messages that have been sent. (***************************************************************************) (* NOTE: *) (* The algorithm is easier to understand in terms of the set msgs of all *) (* messages that have ever been sent. A more accurate model would use *) (* one or more variables to represent the messages actually in transit, *) (* and it would include actions representing message loss and duplication *) (* as well as message receipt. *) (* *) (* In the current spec, there is no need to model message loss because we *) (* are mainly concerned with the algorithm's safety property. The safety *) (* part of the spec says only what messages may be received and does not *) (* assert that any message actually is received. Thus, there is no *) (* difference between a lost message and one that is never received. The *) (* liveness property of the spec that we check makes it clear what *) (* messages must be received (and hence either not lost or successfully *) (* retransmitted if lost) to guarantee progress. *) (***************************************************************************) vars == <<maxBal, maxVBal, maxVal, msgs>> (*************************************************************************) (* It is convenient to define some identifier to be the tuple of all *) (* variables. I like to use the identifier `vars'. *) (*************************************************************************) (***************************************************************************) (* The type invariant and initial predicate. *) (***************************************************************************) TypeOK == /\ maxBal \in [Acceptor -> Ballot \cup {-1}] /\ maxVBal \in [Acceptor -> Ballot \cup {-1}] /\ maxVal \in [Acceptor -> Value \cup {None}] /\ msgs \subseteq Message Init == /\ maxBal = [a \in Acceptor |-> -1] /\ maxVBal = [a \in Acceptor |-> -1] /\ maxVal = [a \in Acceptor |-> None] /\ msgs = {} (***************************************************************************) (* The actions. We begin with the subaction (an action that will be used *) (* to define the actions that make up the next-state action. *) (***************************************************************************) Send(m) == msgs' = msgs \cup {m} (***************************************************************************) (* In an implementation, there will be a leader process that orchestrates *) (* a ballot. The ballot b leader performs actions Phase1a(b) and *) (* Phase2a(b). The Phase1a(b) action sends a phase 1a message (a message *) (* m with m.type = "1a") that begins ballot b. *) (***************************************************************************) Phase1a(b) == /\ Send([type |-> "1a", bal |-> b]) /\ UNCHANGED <<maxBal, maxVBal, maxVal>> (***************************************************************************) (* Upon receipt of a ballot b phase 1a message, acceptor a can perform a *) (* Phase1b(a) action only if b > maxBal[a]. The action sets maxBal[a] to *) (* b and sends a phase 1b message to the leader containing the values of *) (* maxVBal[a] and maxVal[a]. *) (***************************************************************************) Phase1b(a) == /\ \E m \in msgs : /\ m.type = "1a" /\ m.bal > maxBal[a] /\ maxBal' = [maxBal EXCEPT ![a] = m.bal] /\ Send([type |-> "1b", acc |-> a, bal |-> m.bal, mbal |-> maxVBal[a], mval |-> maxVal[a]]) /\ UNCHANGED <<maxVBal, maxVal>> (***************************************************************************) (* The Phase2a(b, v) action can be performed by the ballot b leader if two *) (* conditions are satisfied: (i) it has not already performed a phase 2a *) (* action for ballot b and (ii) it has received ballot b phase 1b messages *) (* from some quorum Q from which it can deduce that the value v is safe at *) (* ballot b. These enabling conditions are the first two conjuncts in the *) (* definition of Phase2a(b, v). This second conjunct, expressing *) (* condition (ii), is the heart of the algorithm. To understand it, *) (* observe that the existence of a phase 1b message m in msgs implies that *) (* m.mbal is the highest ballot number less than m.bal in which acceptor *) (* m.acc has or ever will cast a vote, and that m.mval is the value it *) (* voted for in that ballot if m.mbal # -1. It is not hard to deduce from *) (* this that the second conjunct implies that there exists a quorum Q such *) (* that ShowsSafeAt(Q, b, v) (where ShowsSafeAt is defined in module *) (* Voting). *) (* *) (* The action sends a phase 2a message that tells any acceptor a that it *) (* can vote for v in ballot b, unless it has already set maxBal[a] *) (* greater than b (thereby promising not to vote in ballot b). *) (***************************************************************************) Phase2a(b, v) == /\ ~ \E m \in msgs : m.type = "2a" /\ m.bal = b /\ \E Q \in Quorum : LET Q1b == {m \in msgs : /\ m.type = "1b" /\ m.acc \in Q /\ m.bal = b} Q1bv == {m \in Q1b : m.mbal \geq 0} IN /\ \A a \in Q : \E m \in Q1b : m.acc = a /\ \/ Q1bv = {} \/ \E m \in Q1bv : /\ m.mval = v /\ \A mm \in Q1bv : m.mbal \geq mm.mbal /\ Send([type |-> "2a", bal |-> b, val |-> v]) /\ UNCHANGED <<maxBal, maxVBal, maxVal>> (***************************************************************************) (* The Phase2b(a) action is performed by acceptor a upon receipt of a *) (* phase 2a message. Acceptor a can perform this action only if the *) (* message is for a ballot number greater than or equal to maxBal[a]. In *) (* that case, the acceptor votes as directed by the phase 2a message, *) (* setting maxVBal[a] and maxVal[a] to record that vote and sending a *) (* phase 2b message announcing its vote. It also sets maxBal[a] to the *) (* message's. ballot number *) (***************************************************************************) (* MASKED CODE *) (***************************************************************************) (* In an implementation, there will be learner processes that learn from *) (* the phase 2b messages if a value has been chosen. The learners are *) (* omitted from this abstract specification of the algorithm. *) (***************************************************************************) (***************************************************************************) (* Below are defined the next-state action and the complete spec. *) (***************************************************************************) Next == \/ \E b \in Ballot : \/ Phase1a(b) \/ \E v \in Value : Phase2a(b, v) \/ \E a \in Acceptor : Phase1b(a) \/ Phase2b(a) Spec == Init /\ [][Next]_vars ---------------------------------------------------------------------------- (***************************************************************************) (* We now define the refinement mapping under which this algorithm *) (* implements the specification in module Voting. *) (***************************************************************************) (***************************************************************************) (* As we observed, votes are registered by sending phase 2b messages. So *) (* the array `votes' describing the votes cast by the acceptors is defined *) (* as follows. *) (***************************************************************************) votes == [a \in Acceptor |-> {<<m.bal, m.val>> : m \in {mm \in msgs: /\ mm.type = "2b" /\ mm.acc = a }}] (***************************************************************************) (* We now instantiate module Voting, substituting the constants Value, *) (* Acceptor, and Quorum declared in this module for the corresponding *) (* constants of that module Voting, and substituting the variable maxBal *) (* and the defined state function `votes' for the correspondingly-named *) (* variables of module Voting. *) (***************************************************************************) V == INSTANCE Voting THEOREM Spec => V!Spec ----------------------------------------------------------------------------- (***************************************************************************) (* Here is a first attempt at an inductive invariant used to prove this *) (* theorem. *) (***************************************************************************) Inv == /\ TypeOK /\ \A a \in Acceptor : IF maxVBal[a] = -1 THEN maxVal[a] = None ELSE <<maxVBal[a], maxVal[a]>> \in votes[a] /\ \A m \in msgs : /\ (m.type = "1b") => /\ maxBal[m.acc] \geq m.bal /\ (m.mbal \geq 0) => <<m.mbal, m.mval>> \in votes[m.acc] /\ (m.type = "2a") => /\ \E Q \in Quorum : V!ShowsSafeAt(Q, m.bal, m.val) /\ \A mm \in msgs : /\ mm.type = "2a" /\ mm.bal = m.bal => mm.val = m.val /\ V!Inv ============================================================================ ### Assistant:
Phase2b(a) == \E m \in msgs : /\ m.type = "2a" /\ m.bal \geq maxBal[a] /\ maxBal' = [maxBal EXCEPT ![a] = m.bal] /\ maxVBal' = [maxVBal EXCEPT ![a] = m.bal] /\ maxVal' = [maxVal EXCEPT ![a] = m.val] /\ Send([type |-> "2b", acc |-> a, bal |-> m.bal, val |-> m.val])
CheckpointCoordination
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ----------------------- MODULE CheckpointCoordination ----------------------- EXTENDS Naturals, FiniteSets, Sequences CONSTANTS Node, \* The set of all nodes available for use in the cluster Majority \* The number of nodes constituting a majority VARIABLES IsNodeUp, \* Whether each node is up NetworkPath, \* Whether a network path exists between nodes Leader, \* Which node is currently elected leader ReplicatedLog, \* The replicated log of commands on each node ExecutionCounter, \* The index in the log each node will next execute LastVotePayload, \* Data field which piggybacks on vote responses CurrentLease, \* The current checkpoint lease recorded at each nodes CanTakeCheckpoint, \* Whether node believes it can take a checkpoint IsTakingCheckpoint, \* Whether node is currently taking a checkpoint TimeoutCounter, \* Counter of oldest lease which has not yet timed out LatestCheckpoint \* The latest recorded log checkpoint (***************************************************************************) (* Variables relating to the environment in which the cluster is running. *) (***************************************************************************) EnvironmentVars == << IsNodeUp, NetworkPath >> (***************************************************************************) (* Variables relating to the function of the Paxos (RSL) system itself. *) (***************************************************************************) PaxosVars == << Leader, ReplicatedLog, ExecutionCounter, LastVotePayload >> (***************************************************************************) (* Variables relating to the checkpoint coordination system logic. *) (***************************************************************************) CheckpointVars == << CurrentLease, CanTakeCheckpoint, IsTakingCheckpoint, TimeoutCounter, LatestCheckpoint >> (***************************************************************************) (* All variables. *) (***************************************************************************) AllVars == << IsNodeUp, NetworkPath, Leader, ReplicatedLog, ExecutionCounter, LastVotePayload, CurrentLease, CanTakeCheckpoint, IsTakingCheckpoint, TimeoutCounter, LatestCheckpoint >> (***************************************************************************) (* An arbitrary value not in the set of all nodes. *) (***************************************************************************) NoNode == CHOOSE n : n \notin Node (***************************************************************************) (* The set of all logs, the values of which are decided by Paxos. *) (***************************************************************************) Log == Seq(Node \cup {NoNode}) (***************************************************************************) (* The set of all log indices. *) (***************************************************************************) LogIndex == Nat \ {0} (***************************************************************************) (* The very first log index. *) (***************************************************************************) MinLogIndex == 1 (***************************************************************************) (* A blank log. *) (***************************************************************************) BlankLog == [i \in LogIndex |-> NoNode] (***************************************************************************) (* The set of all log checkpoints. *) (***************************************************************************) LogCheckpoint == [ log : Log, \* The saved log entries counter : LogIndex \* Highest log index in checkpoint, exclusive ] (***************************************************************************) (* The set of all log checkpoint leases. *) (***************************************************************************) (* MASKED CODE *) (***************************************************************************) (* Value indicating no checkpoint lease. *) (***************************************************************************) NoCheckpointLease == CHOOSE lease : lease \notin CheckpointLease (***************************************************************************) (* Reads the value from the index of the node's log. *) (***************************************************************************) ReadLog(node, index) == IF index \in DOMAIN ReplicatedLog[node] THEN ReplicatedLog[node][index] ELSE NoNode (***************************************************************************) (* Writes the value to the index of the node's log. *) (***************************************************************************) WriteLog(node, index, value) == [ [i \in LogIndex |-> ReadLog(node, i)] EXCEPT ![index] = value ] (***************************************************************************) (* Merges the logs of two replicas. Replica logs can differ if one was *) (* unable to receive messages from the leader. While replica logs can be *) (* missing values, they will never have conflicting values for any index. *) (***************************************************************************) MergeLogs(srcNode, dstNode) == [ i \in LogIndex |-> IF ReadLog(dstNode, i) /= NoNode THEN ReadLog(dstNode, i) ELSE ReadLog(srcNode, i) ] (***************************************************************************) (* The set of all unused log indices. *) (***************************************************************************) OpenIndices == { i \in LogIndex : \A n \in Node : ReadLog(n, i) = NoNode } (***************************************************************************) (* Finds the first unused replicated log index. *) (***************************************************************************) FirstOpenIndex == CHOOSE index \in OpenIndices : \A other \in OpenIndices : index <= other (***************************************************************************) (* The type invariant of all variables. *) (***************************************************************************) TypeInvariant == /\ IsNodeUp \in [Node -> BOOLEAN] /\ NetworkPath \in [Node \X Node -> BOOLEAN] /\ Leader \in Node \cup {NoNode} /\ ReplicatedLog \in [Node -> Log] /\ ExecutionCounter \in [Node -> LogIndex] /\ LastVotePayload \in [Node -> LogIndex] /\ CurrentLease \in [Node -> (CheckpointLease \cup {NoCheckpointLease})] /\ CanTakeCheckpoint \in [Node -> BOOLEAN] /\ IsTakingCheckpoint \in [Node -> BOOLEAN] /\ TimeoutCounter \in LogIndex /\ LatestCheckpoint \in LogCheckpoint (***************************************************************************) (* Safety checks which must hold in all states for the system to be *) (* considered functional. *) (***************************************************************************) SafetyInvariant == /\ Leader /= NoNode => \* The leader cannot take a checkpoint /\ ~CanTakeCheckpoint[Leader] /\ ~IsTakingCheckpoint[Leader] \* If the leader doesn't know about a lease, neither does any node /\ CurrentLease[Leader] = NoCheckpointLease => /\ \A n \in Node : /\ ~CanTakeCheckpoint[n] /\ ~IsTakingCheckpoint[n] \* If the leader knows about a lease, only that node can checkpoint /\ CurrentLease[Leader] /= NoCheckpointLease => /\ \A n \in Node : /\ (CanTakeCheckpoint[n] \/ IsTakingCheckpoint[n]) => /\ CurrentLease[Leader].node = n \* Two nodes can't take a checkpoint simultaneously /\ \A n1, n2 \in Node : /\ (CanTakeCheckpoint[n1] /\ CanTakeCheckpoint[n2]) => /\ n1 = n2 /\ (IsTakingCheckpoint[n1] /\ IsTakingCheckpoint[n2]) => /\ n1 = n2 \* Prerequisites for taking a checkpoint must be satisfied /\ \A n \in Node : /\ IsTakingCheckpoint[n] => CanTakeCheckpoint[n] /\ CanTakeCheckpoint[n] => (CurrentLease[n] /= NoCheckpointLease) /\ CanTakeCheckpoint[n] => CurrentLease[n].node = n /\ CanTakeCheckpoint[n] => CurrentLease[n].counter >= TimeoutCounter \* Replicated logs can never conflict /\ \A i \in LogIndex : /\ \A n1, n2 \in Node : \/ ReadLog(n1, i) = NoNode \/ ReadLog(n2, i) = NoNode \/ ReadLog(n1, i) = ReadLog(n2, i) (***************************************************************************) (* Expectations about system capabilities. *) (***************************************************************************) TemporalInvariant == \* Eventually, a checkpoint can be taken /\ <>(\E n \in Node : CanTakeCheckpoint[n]) \* If a node can take a checkpoint, eventually it will take a checkpoint /\ \A n \in Node : /\ CanTakeCheckpoint[n] ~> \/ IsTakingCheckpoint[n] \/ ~IsNodeUp[n] \/ CurrentLease[n].counter < TimeoutCounter \* If a node takes a checkpoint, eventually it will complete or timeout /\ \A n \in Node : /\ IsTakingCheckpoint[n] ~> \/ LastVotePayload[n] = ExecutionCounter[n] \/ ~IsNodeUp[n] \/ CurrentLease[n].counter < TimeoutCounter \* Eventually, a checkpoint will be completed /\ <>(LatestCheckpoint /= BlankLog) (***************************************************************************) (* Whether the dst node will receive a message from the src node. *) (***************************************************************************) ConnectedOneWay(src, dst) == /\ IsNodeUp[src] /\ IsNodeUp[dst] /\ NetworkPath[src, dst] (***************************************************************************) (* Whether the two nodes can talk to one another. *) (***************************************************************************) Connected(src, dst) == /\ ConnectedOneWay(src, dst) /\ ConnectedOneWay(dst, src) (***************************************************************************) (* Whether we have quorum from the given prospective leader node. *) (***************************************************************************) HaveQuorumFrom[leader \in Node] == LET available == {n \in Node : Connected(leader, n)} IN /\ IsNodeUp[leader] /\ Cardinality(available) >= Majority (***************************************************************************) (* Whether we have a leader and that leader has quorum. *) (***************************************************************************) HaveQuorum == /\ Leader /= NoNode /\ HaveQuorumFrom[Leader] (***************************************************************************) (* A node fails, losing all volatile local state. *) (***************************************************************************) NodeFailure(n) == /\ IsNodeUp' = [IsNodeUp EXCEPT ![n] = FALSE] /\ Leader' = IF n = Leader THEN NoNode ELSE Leader /\ ExecutionCounter' = [ExecutionCounter EXCEPT ![n] = MinLogIndex] /\ LastVotePayload' = [LastVotePayload EXCEPT ![n] = MinLogIndex] /\ CurrentLease' = [CurrentLease EXCEPT ![n] = NoCheckpointLease] /\ CanTakeCheckpoint' = [CanTakeCheckpoint EXCEPT ![n] = FALSE] /\ IsTakingCheckpoint' = [IsTakingCheckpoint EXCEPT ![n] = FALSE] /\ UNCHANGED <<NetworkPath>> /\ UNCHANGED <<ReplicatedLog>> /\ UNCHANGED <<TimeoutCounter, LatestCheckpoint>> (***************************************************************************) (* A node recovers. State is first rehydrated from the last checkpoint, *) (* with the node's locally-persisted log filling in any gaps after that. *) (***************************************************************************) NodeRecovery(n) == /\ ~IsNodeUp[n] /\ IsNodeUp' = [IsNodeUp EXCEPT ![n] = TRUE] /\ ReplicatedLog' = [ReplicatedLog EXCEPT ![n] = SubSeq(LatestCheckpoint.log, MinLogIndex, LatestCheckpoint.counter - 1) \o SubSeq(@, LatestCheckpoint.counter, Len(@))] /\ ExecutionCounter' = [ExecutionCounter EXCEPT ![n] = LatestCheckpoint.counter] /\ LastVotePayload' = [LastVotePayload EXCEPT ![n] = MinLogIndex] /\ CurrentLease' = [CurrentLease EXCEPT ![n] = NoCheckpointLease] /\ CanTakeCheckpoint' = [CanTakeCheckpoint EXCEPT ![n] = FALSE] /\ IsTakingCheckpoint' = [IsTakingCheckpoint EXCEPT ![n] = FALSE] /\ UNCHANGED <<NetworkPath>> /\ UNCHANGED <<Leader>> /\ UNCHANGED <<TimeoutCounter, LatestCheckpoint>> (***************************************************************************) (* A network link between two nodes fails in one direction. *) (***************************************************************************) NetworkFailure(src, dst) == /\ src /= dst /\ NetworkPath' = [NetworkPath EXCEPT ![src, dst] = FALSE] /\ UNCHANGED <<IsNodeUp>> /\ UNCHANGED PaxosVars /\ UNCHANGED CheckpointVars (***************************************************************************) (* A network link between two nodes recovers. *) (***************************************************************************) NetworkRecovery(src, dst) == /\ NetworkPath' = [NetworkPath EXCEPT ![src, dst] = TRUE] /\ UNCHANGED <<IsNodeUp>> /\ UNCHANGED PaxosVars /\ UNCHANGED CheckpointVars (***************************************************************************) (* Elects a new leader if one is not currently elected. *) (* We can safely assume nodes currently taking a backup are excluded from *) (* the leader election process, because their state is too far behind. *) (* The leader is required to be completely caught up, and thus cannot have *) (* any unprocessed replicated requests. *) (***************************************************************************) ElectLeader(n) == /\ Leader = NoNode /\ IsNodeUp[n] /\ ~IsTakingCheckpoint[n] /\ HaveQuorumFrom[n] /\ ExecutionCounter[n] = FirstOpenIndex /\ Leader' = n /\ CanTakeCheckpoint' = [CanTakeCheckpoint EXCEPT ![n] = FALSE] /\ UNCHANGED EnvironmentVars /\ UNCHANGED <<ReplicatedLog, ExecutionCounter, LastVotePayload>> /\ UNCHANGED <<CurrentLease, IsTakingCheckpoint, TimeoutCounter, LatestCheckpoint>> (***************************************************************************) (* Critical logic determining whether we should replace the current lease. *) (***************************************************************************) ShouldReplaceLease(currentLease) == \* Current lease has timed out \/ currentLease.counter < TimeoutCounter \* Snapshot has been completed & reported to leader by node \/ /\ Connected(Leader, currentLease.node) /\ currentLease.counter < LastVotePayload[currentLease.node] (***************************************************************************) (* The leader designates an arbitrary node to take a checkpoint. This is *) (* done by sending a replicated request to all nodes in the quorum. The *) (* request contains the node selected to perform a checkpoint. *) (***************************************************************************) SendReplicatedRequest(prospect) == LET currentLease == CurrentLease[Leader] IN LET index == FirstOpenIndex IN /\ HaveQuorum /\ Leader /= prospect /\ Connected(Leader, prospect) /\ currentLease /= NoCheckpointLease => ShouldReplaceLease(currentLease) /\ ReplicatedLog' = [n \in Node |-> IF ConnectedOneWay(Leader, n) THEN WriteLog(n, index, prospect) ELSE ReplicatedLog[n]] /\ CurrentLease' = [ CurrentLease EXCEPT ![Leader] = [ node |-> prospect, counter |-> index ] ] /\ UNCHANGED EnvironmentVars /\ UNCHANGED <<Leader, ExecutionCounter, LastVotePayload>> /\ UNCHANGED <<CanTakeCheckpoint, IsTakingCheckpoint, TimeoutCounter, LatestCheckpoint>> (***************************************************************************) (* Propagates chosen values to a node which might have missed them. *) (***************************************************************************) PropagateReplicatedRequest(src, dst) == /\ ConnectedOneWay(src, dst) /\ ReplicatedLog' = [ReplicatedLog EXCEPT ![dst] = MergeLogs(src, dst)] /\ UNCHANGED EnvironmentVars /\ UNCHANGED <<Leader, ExecutionCounter, LastVotePayload>> /\ UNCHANGED CheckpointVars (***************************************************************************) (* The node processes a replicated request. If the request specifies the *) (* node processing the request, and the node is not currently leader, then *) (* the node marks itself as able to take a checkpoint. *) (***************************************************************************) ProcessReplicatedRequest(n) == LET request == ReadLog(n, ExecutionCounter[n]) IN LET isTimedOut == ExecutionCounter[n] < TimeoutCounter IN /\ IsNodeUp[n] /\ ~IsTakingCheckpoint[n] /\ request /= NoNode /\ CanTakeCheckpoint' = [ CanTakeCheckpoint EXCEPT ![n] = /\ Leader /= n /\ n = request /\ ~isTimedOut ] /\ CurrentLease' = IF n = Leader THEN CurrentLease ELSE [ CurrentLease EXCEPT ![n] = IF isTimedOut THEN NoCheckpointLease ELSE [node |-> request, counter |-> ExecutionCounter[n]] ] /\ ExecutionCounter' = [ExecutionCounter EXCEPT ![n] = @ + 1] /\ UNCHANGED EnvironmentVars /\ UNCHANGED <<Leader, ReplicatedLog, LastVotePayload>> /\ UNCHANGED <<IsTakingCheckpoint, TimeoutCounter, LatestCheckpoint>> (***************************************************************************) (* A node begins a checkpoint if it believes it is able. *) (***************************************************************************) StartCheckpoint(n) == /\ CanTakeCheckpoint[n] /\ IsTakingCheckpoint' = [IsTakingCheckpoint EXCEPT ![n] = TRUE] /\ UNCHANGED EnvironmentVars /\ UNCHANGED PaxosVars /\ UNCHANGED <<CurrentLease, CanTakeCheckpoint, TimeoutCounter, LatestCheckpoint>> (***************************************************************************) (* Completes a checkpoint successfully. *) (***************************************************************************) FinishCheckpoint(n) == /\ IsTakingCheckpoint[n] /\ LastVotePayload' = [LastVotePayload EXCEPT ![n] = ExecutionCounter[n]] /\ CurrentLease' = [CurrentLease EXCEPT ![n] = NoCheckpointLease] /\ CanTakeCheckpoint' = [CanTakeCheckpoint EXCEPT ![n] = FALSE] /\ IsTakingCheckpoint' = [IsTakingCheckpoint EXCEPT ![n] = FALSE] /\ LatestCheckpoint' = [ log |-> SubSeq( ReplicatedLog[n], MinLogIndex, ExecutionCounter[n] - 1 ), counter |-> ExecutionCounter[n] ] /\ UNCHANGED EnvironmentVars /\ UNCHANGED <<Leader, ReplicatedLog, ExecutionCounter>> /\ UNCHANGED <<TimeoutCounter>> (***************************************************************************) (* Increments the timeout counter; while in a real-world system we can't *) (* expect every node to have its local time flow at the same rate, the *) (* specific system being modeled will drop a node from the replica set if *) (* its time dilation is beyond a small margin relative to the primary. *) (***************************************************************************) TriggerTimeout == /\ \E n \in Node : ReadLog(n, TimeoutCounter) /= NoNode /\ TimeoutCounter' = TimeoutCounter + 1 /\ CanTakeCheckpoint' = [ n \in Node |-> /\ CanTakeCheckpoint[n] /\ CurrentLease[n].counter > TimeoutCounter ] /\ IsTakingCheckpoint' = [ n \in Node |-> /\ IsTakingCheckpoint[n] /\ CurrentLease[n].counter > TimeoutCounter ] /\ UNCHANGED EnvironmentVars /\ UNCHANGED PaxosVars /\ UNCHANGED <<CurrentLease, LatestCheckpoint>> (***************************************************************************) (* The initial system state. All nodes healthy, log is blank. *) (***************************************************************************) Init == /\ IsNodeUp = [n \in Node |-> TRUE] /\ NetworkPath = [src, dst \in Node |-> TRUE] /\ Leader = NoNode /\ ReplicatedLog = [n \in Node |-> BlankLog] /\ ExecutionCounter = [n \in Node |-> MinLogIndex] /\ LastVotePayload = [n \in Node |-> MinLogIndex] /\ CurrentLease = [n \in Node |-> NoCheckpointLease] /\ CanTakeCheckpoint = [n \in Node |-> FALSE] /\ IsTakingCheckpoint = [n \in Node |-> FALSE] /\ TimeoutCounter = MinLogIndex /\ LatestCheckpoint = [log |-> BlankLog, counter |-> MinLogIndex] (***************************************************************************) (* The next-state relation. *) (***************************************************************************) Next == \/ \E n \in Node : NodeFailure(n) \/ \E n \in Node : NodeRecovery(n) \/ \E src, dst \in Node : NetworkFailure(src, dst) \/ \E src, dst \in Node : NetworkRecovery(src, dst) \/ \E n \in Node : ElectLeader(n) \/ \E n \in Node : SendReplicatedRequest(n) \/ \E src, dst \in Node : PropagateReplicatedRequest(src, dst) \/ \E n \in Node : ProcessReplicatedRequest(n) \/ \E n \in Node : StartCheckpoint(n) \/ \E n \in Node : FinishCheckpoint(n) \/ TriggerTimeout (***************************************************************************) (* Assumptions that good things eventually happen. *) (***************************************************************************) TemporalAssumptions == /\ \A n \in Node : WF_AllVars(NodeRecovery(n)) /\ \A src, dst \in Node : WF_AllVars(NetworkRecovery(src, dst)) /\ \A n \in Node : SF_AllVars(ElectLeader(n)) /\ \A n \in Node : SF_AllVars(SendReplicatedRequest(n)) /\ \A src, dst \in Node : SF_AllVars(PropagateReplicatedRequest(src, dst)) /\ \A n \in Node : SF_AllVars(ProcessReplicatedRequest(n)) /\ \A n \in Node : SF_AllVars(StartCheckpoint(n)) /\ \A n \in Node : SF_AllVars(FinishCheckpoint(n)) (***************************************************************************) (* The spec, defining the set of all system behaviours. *) (***************************************************************************) Spec == /\ Init /\ [][Next]_AllVars /\ TemporalAssumptions (***************************************************************************) (* Want to show: the set of all behaviours satisfies our requirements. *) (***************************************************************************) THEOREM Spec => /\ []TypeInvariant /\ []SafetyInvariant /\ []TemporalInvariant ============================================================================= ### Assistant:
CheckpointLease == [ node : Node, \* The node to which the checkpoint lease applies counter : LogIndex \* The log index at which the lease was issued ]
LeastCircularSubstring
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ---------------------- MODULE LeastCircularSubstring ------------------------ (***************************************************************************) (* An implementation of the lexicographically-least circular substring *) (* algorithm from the 1980 paper by Kellogg S. Booth. See: *) (* https://doi.org/10.1016/0020-0190(80)90149-0 *) (***************************************************************************) EXTENDS Integers, ZSequences CONSTANTS CharacterSet ASSUME CharacterSet \subseteq Nat (**************************************************************************** --algorithm LeastCircularSubstring variables b \in Corpus; n = ZLen(b); f = [index \in 0..2*n |-> nil]; i = nil; j = 1; k = 0; define Corpus == ZSeq(CharacterSet) nil == -1 end define; begin L3: while j < 2 * n do L5: i := f[j - k - 1]; L6: while b[j % n] /= b[(k + i + 1) % n] /\ i /= nil do L7: if b[j % n] < b[(k + i + 1) % n] then L8: k := j - i - 1; end if; L9: i := f[i]; end while; L10: if b[j % n] /= b[(k + i + 1) % n] /\ i = nil then L11: if b[j % n] < b[(k + i + 1) % n] then L12: k := j; end if; L13: f[j - k] := nil; else L14: f[j - k] := i + 1; end if; LVR: j := j + 1; end while; end algorithm; ****************************************************************************) \* BEGIN TRANSLATION (chksum(pcal) = "c2e05615" /\ chksum(tla) = "81694c33") VARIABLES b, n, f, i, j, k, pc (* define statement *) Corpus == ZSeq(CharacterSet) nil == -1 vars == << b, n, f, i, j, k, pc >> Init == (* Global variables *) /\ b \in Corpus /\ n = ZLen(b) /\ f = [index \in 0..2*n |-> nil] /\ i = nil /\ j = 1 /\ k = 0 /\ pc = "L3" L3 == /\ pc = "L3" /\ IF j < 2 * n THEN /\ pc' = "L5" ELSE /\ pc' = "Done" /\ UNCHANGED << b, n, f, i, j, k >> L5 == /\ pc = "L5" /\ i' = f[j - k - 1] /\ pc' = "L6" /\ UNCHANGED << b, n, f, j, k >> L6 == /\ pc = "L6" /\ IF b[j % n] /= b[(k + i + 1) % n] /\ i /= nil THEN /\ pc' = "L7" ELSE /\ pc' = "L10" /\ UNCHANGED << b, n, f, i, j, k >> L7 == /\ pc = "L7" /\ IF b[j % n] < b[(k + i + 1) % n] THEN /\ pc' = "L8" ELSE /\ pc' = "L9" /\ UNCHANGED << b, n, f, i, j, k >> L8 == /\ pc = "L8" /\ k' = j - i - 1 /\ pc' = "L9" /\ UNCHANGED << b, n, f, i, j >> (* MASKED CODE *) L10 == /\ pc = "L10" /\ IF b[j % n] /= b[(k + i + 1) % n] /\ i = nil THEN /\ pc' = "L11" ELSE /\ pc' = "L14" /\ UNCHANGED << b, n, f, i, j, k >> L11 == /\ pc = "L11" /\ IF b[j % n] < b[(k + i + 1) % n] THEN /\ pc' = "L12" ELSE /\ pc' = "L13" /\ UNCHANGED << b, n, f, i, j, k >> L12 == /\ pc = "L12" /\ k' = j /\ pc' = "L13" /\ UNCHANGED << b, n, f, i, j >> L13 == /\ pc = "L13" /\ f' = [f EXCEPT ![j - k] = nil] /\ pc' = "LVR" /\ UNCHANGED << b, n, i, j, k >> L14 == /\ pc = "L14" /\ f' = [f EXCEPT ![j - k] = i + 1] /\ pc' = "LVR" /\ UNCHANGED << b, n, i, j, k >> LVR == /\ pc = "LVR" /\ j' = j + 1 /\ pc' = "L3" /\ UNCHANGED << b, n, f, i, k >> (* Allow infinite stuttering to prevent deadlock on termination. *) Terminating == pc = "Done" /\ UNCHANGED vars Next == L3 \/ L5 \/ L6 \/ L7 \/ L8 \/ L9 \/ L10 \/ L11 \/ L12 \/ L13 \/ L14 \/ LVR \/ Terminating Spec == Init /\ [][Next]_vars Termination == <>(pc = "Done") \* END TRANSLATION TypeInvariant == /\ b \in Corpus /\ n = ZLen(b) /\ f \in [0..2*n -> 0..2*n \cup {nil}] /\ i \in 0..2*n \cup {nil} /\ j \in 0..2*n \cup {1} /\ k \in ZIndices(b) \cup {0} \* Is this shift the lexicographically-minimal rotation? IsLeastMinimalRotation(s, r) == LET rotation == Rotation(s, r) IN /\ \A other \in Rotations(s) : /\ rotation \preceq other.seq /\ rotation = other.seq => (r <= other.shift) Correctness == pc = "Done" => IsLeastMinimalRotation(b, k) ============================================================================= ### Assistant:
L9 == /\ pc = "L9" /\ i' = f[i] /\ pc' = "L6" /\ UNCHANGED << b, n, f, j, k >>
DieHard
### Human: generate the TLA+ code that is missing from the section labeled `(* MASKED CODE *)`. Do not include explanation; only TLA+ code. Provide only the code that should replace `(* MASKED CODE *)`, and no other code. ------------------------------ MODULE DieHard ------------------------------- (***************************************************************************) (* In the movie Die Hard 3, the heros must obtain exactly 4 gallons of *) (* water using a 5 gallon jug, a 3 gallon jug, and a water faucet. Our *) (* goal: to get TLC to solve the problem for us. *) (* *) (* First, we write a spec that describes all allowable behaviors of our *) (* heros. *) (***************************************************************************) EXTENDS Naturals (*************************************************************************) (* This statement imports the definitions of the ordinary operators on *) (* natural numbers, such as +. *) (*************************************************************************) (***************************************************************************) (* We next declare the specification's variables. *) (***************************************************************************) VARIABLES big, \* The number of gallons of water in the 5 gallon jug. small \* The number of gallons of water in the 3 gallon jug. (***************************************************************************) (* We now define TypeOK to be the type invariant, asserting that the value *) (* of each variable is an element of the appropriate set. A type *) (* invariant like this is not part of the specification, but it's *) (* generally a good idea to include it because it helps the reader *) (* understand the spec. Moreover, having TLC check that it is an *) (* invariant of the spec catches errors that, in a typed language, are *) (* caught by type checking. *) (* *) (* Note: TLA+ uses the convention that a list of formulas bulleted by /\ *) (* or \/ denotes the conjunction or disjunction of those formulas. *) (* Indentation of subitems is significant, allowing one to eliminate lots *) (* of parentheses. This makes a large formula much easier to read. *) (* However, it does mean that you have to be careful with your indentation.*) (***************************************************************************) TypeOK == /\ small \in 0..3 /\ big \in 0..5 (***************************************************************************) (* Now we define of the initial predicate, that specifies the initial *) (* values of the variables. I like to name this predicate Init, but the *) (* name doesn't matter. *) (***************************************************************************) Init == /\ big = 0 /\ small = 0 (***************************************************************************) (* Now we define the actions that our hero can perform. There are three *) (* things they can do: *) (* *) (* - Pour water from the faucet into a jug. *) (* *) (* - Pour water from a jug onto the ground. *) (* *) (* - Pour water from one jug into another *) (* *) (* We now consider the first two. Since the jugs are not calibrated, *) (* partially filling or partially emptying a jug accomplishes nothing. *) (* So, the first two possibilities yield the following four possible *) (* actions. *) (***************************************************************************) FillSmallJug == /\ small' = 3 /\ big' = big FillBigJug == /\ big' = 5 /\ small' = small EmptySmallJug == /\ small' = 0 /\ big' = big EmptyBigJug == /\ big' = 0 /\ small' = small (***************************************************************************) (* We now consider pouring water from one jug into another. Again, since *) (* the jugs are not callibrated, when pouring from jug A to jug B, it *) (* makes sense only to either fill B or empty A. And there's no point in *) (* emptying A if this will cause B to overflow, since that could be *) (* accomplished by the two actions of first filling B and then emptying A. *) (* So, pouring water from A to B leaves B with the lesser of (i) the water *) (* contained in both jugs and (ii) the volume of B. To express this *) (* mathematically, we first define Min(m,n) to equal the minimum of the *) (* numbers m and n. *) (***************************************************************************) Min(m,n) == IF m < n THEN m ELSE n (***************************************************************************) (* Now we define the last two pouring actions. From the observation *) (* above, these definitions should be clear. *) (***************************************************************************) SmallToBig == /\ big' = Min(big + small, 5) /\ small' = small - (big' - big) BigToSmall == /\ small' = Min(big + small, 3) /\ big' = big - (small' - small) (***************************************************************************) (* We define the next-state relation, which I like to call Next. A Next *) (* step is a step of one of the six actions defined above. Hence, Next is *) (* the disjunction of those actions. *) (***************************************************************************) Next == \/ FillSmallJug \/ FillBigJug \/ EmptySmallJug \/ EmptyBigJug \/ SmallToBig \/ BigToSmall (***************************************************************************) (* We define the formula Spec to be the complete specification, asserting *) (* of a behavior that it begins in a state satisfying Init, and that every *) (* step either satisfies Next or else leaves the pair <<big, small>> *) (* unchanged. *) (***************************************************************************) Spec == Init /\ [][Next]_<<big, small>> ----------------------------------------------------------------------------- (***************************************************************************) (* Remember that our heros must measure out 4 gallons of water. *) (* Obviously, those 4 gallons must be in the 5 gallon jug. So, they have *) (* solved their problem when they reach a state with big = 4. So, we *) (* define NotSolved to be the predicate asserting that big # 4. *) (***************************************************************************) (* MASKED CODE *) (***************************************************************************) (* We find a solution by having TLC check if NotSolved is an invariant, *) (* which will cause it to print out an "error trace" consisting of a *) (* behavior ending in a states where NotSolved is false. Such a *) (* behavior is the desired solution. (Because TLC uses a breadth-first *) (* search, it will find the shortest solution.) *) (***************************************************************************) ============================================================================= ### Assistant:
NotSolved == big # 4

Dataset Card for "tla_masked_code_eval"

More Information needed

Downloads last month
0
Edit dataset card