-
Notifications
You must be signed in to change notification settings - Fork 7.2k
/
ZkV3_7_0.tla
2050 lines (1905 loc) · 111 KB
/
ZkV3_7_0.tla
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
------------------------------ MODULE ZkV3_7_0 ------------------------------
(* This is the system specification for Zab in apache/zookeeper with version 3.7.0 *)
(* Reference:
FLE: FastLeaderElection.java, Vote.java, QuorumPeer.java, e.g. in
https://github.com/apache/zookeeper.
ZAB: QuorumPeer.java, Learner.java, Follower.java, LearnerHandler.java,
Leader.java, e.g. in https://github.com/apache/zookeeper.
https://cwiki.apache.org/confluence/display/ZOOKEEPER/Zab1.0.
*)
EXTENDS FastLeaderElection
-----------------------------------------------------------------------------
\* The set of requests that can go into history
\* CONSTANT Value \* Replaced by recorder.nClientRequest
Value == Nat
\* Zab states
CONSTANTS ELECTION, DISCOVERY, SYNCHRONIZATION, BROADCAST
\* Sync modes & message types
CONSTANTS DIFF, TRUNC, SNAP
\* Message types
CONSTANTS FOLLOWERINFO, LEADERINFO, ACKEPOCH, NEWLEADER, ACKLD,
UPTODATE, PROPOSAL, ACK, COMMIT
(* NOTE: In production, there is no message type ACKLD. Server judges if counter
of ACK is 0 to distinguish one ACK represents ACKLD or not. Here we
divide ACK into ACKLD and ACK, to enhance readability of spec.*)
\* Node status
CONSTANTS ONLINE, OFFLINE
\* [MaxTimeoutFailures, MaxTransactionNum, MaxEpoch, MaxCrashes, MaxPartitions]
CONSTANT Parameters
MAXEPOCH == 10
-----------------------------------------------------------------------------
\* Variables in annotations mean variables defined in FastLeaderElection.
\* Variables that all servers use.
VARIABLES zabState, \* Current phase of server, in
\* {ELECTION, DISCOVERY, SYNCHRONIZATION, BROADCAST}.
acceptedEpoch, \* Epoch of the last LEADERINFO packet accepted,
\* namely f.p in paper.
lastCommitted, \* Maximum index and zxid known to be committed,
\* namely 'lastCommitted' in Leader. Starts from 0,
\* and increases monotonically before restarting.
lastSnapshot, \* Index and zxid corresponding to latest snapshot
\* from data tree.
initialHistory \* history that server initially has before election.
\* state, \* State of server, in {LOOKING, FOLLOWING, LEADING}.
\* currentEpoch, \* Epoch of the last NEWLEADER packet accepted,
\* namely f.a in paper.
\* lastProcessed,\* Index and zxid of the last processed txn.
\* history \* History of servers: sequence of transactions,
\* containing: zxid, value, ackSid, epoch.
\* leader : [committedRequests + toBeApplied] [outstandingProposals]
\* follower: [committedRequests] [pendingTxns]
\* Variables only used for leader.
VARIABLES learners, \* Set of servers leader connects,
\* namely 'learners' in Leader.
connecting, \* Set of learners leader has received
\* FOLLOWERINFO from, namely
\* 'connectingFollowers' in Leader.
\* Set of record [sid, connected].
electing, \* Set of learners leader has received
\* ACKEPOCH from, namely 'electingFollowers'
\* in Leader. Set of record
\* [sid, peerLastZxid, inQuorum].
\* And peerLastZxid = <<-1,-1>> means has done
\* syncFollower with this sid.
\* inQuorum = TRUE means in code it is one
\* element in 'electingFollowers'.
ackldRecv, \* Set of learners leader has received
\* ACK of NEWLEADER from, namely
\* 'newLeaderProposal' in Leader.
\* Set of record [sid, connected].
forwarding, \* Set of learners that are synced with
\* leader, namely 'forwardingFollowers'
\* in Leader.
tempMaxEpoch \* ({Maximum epoch in FOLLOWEINFO} + 1) that
\* leader has received from learners,
\* namely 'epoch' in Leader.
\* leadingVoteSet \* Set of voters that follow leader.
\* Variables only used for follower.
VARIABLES connectInfo, \* Record [sid, syncMode, nlRcv].
\* sid: Leader id that follower has connected with.
\* syncMode: Sync mode according to reveiced Sync Message.
\* nlRcv: If follower has received NEWLEADER.
packetsSync \* packets of PROPOSAL and COMMIT from leader,
\* namely 'packetsNotCommitted' and
\* 'packetsCommitted' in SyncWithLeader
\* in Learner.
\* Variables about network channel.
VARIABLE msgs \* Simulates network channel.
\* msgs[i][j] means the input buffer of server j
\* from server i.
\* electionMsgs \* Network channel in FLE module.
\* Variables about status of cluster network and node presence.
VARIABLES status, \* Whether the server is online or offline.
partition \* network partion.
\* Variables only used in verifying properties.
VARIABLES epochLeader, \* Set of leaders in every epoch.
proposalMsgsLog, \* Set of all broadcast messages.
violatedInvariants \* Check whether there are conditions
\* contrary to the facts.
\* Variables only used for looking.
\*VARIABLE currentVote, \* Info of current vote, namely 'currentVote'
\* \* in QuorumPeer.
\* logicalClock, \* Election instance, namely 'logicalClock'
\* \* in FastLeaderElection.
\* receiveVotes, \* Votes from current FLE round, namely
\* \* 'recvset' in FastLeaderElection.
\* outOfElection, \* Votes from previous and current FLE round,
\* \* namely 'outofelection' in FastLeaderElection.
\* recvQueue, \* Queue of received notifications or timeout
\* \* signals.
\* waitNotmsg \* Whether waiting for new not.See line 1050
\* \* in FastLeaderElection for details.
\*VARIABLE idTable \* For mapping Server to Integers,
\* to compare ids between servers.
\* Update: we have transformed idTable from variable to function.
\*VARIABLE clientReuqest \* Start from 0, and increases monotonically
\* when LeaderProcessRequest performed. To
\* avoid existing two requests with same value.
\* Update: Remove it to recorder.nClientRequest.
\* Variable used for recording critical data,
\* to constrain state space or update values.
VARIABLE recorder \* Consists: members of Parameters and pc, values.
\* Form is record:
\* [pc, nTransaction, maxEpoch, nTimeout, nClientRequest,
\* nPartition, nCrash]
serverVars == <<state, currentEpoch, lastProcessed, zabState, acceptedEpoch,
history, lastCommitted, lastSnapshot, initialHistory>>
electionVars == electionVarsL
leaderVars == <<leadingVoteSet, learners, connecting, electing,
ackldRecv, forwarding, tempMaxEpoch>>
followerVars == <<connectInfo, packetsSync>>
verifyVars == <<proposalMsgsLog, epochLeader, violatedInvariants>>
msgVars == <<msgs, electionMsgs>>
envVars == <<status, partition>>
vars == <<serverVars, electionVars, leaderVars, followerVars,
verifyVars, msgVars, envVars, recorder>>
-----------------------------------------------------------------------------
ServersIncNullPoint == Server \union {NullPoint}
Zxid ==
Seq(Nat \union {-1})
HistoryItem ==
[ zxid: Zxid,
value: Value,
ackSid: SUBSET Server,
epoch: Nat ]
Proposal ==
[ source: Server,
epoch: Nat,
zxid: Zxid,
data: Value ]
LastItem ==
[ index: Nat, zxid: Zxid ]
SyncPackets ==
[ notCommitted: Seq(HistoryItem),
committed: Seq(Zxid) ]
Message ==
[ mtype: {FOLLOWERINFO}, mzxid: Zxid ] \union
[ mtype: {LEADERINFO}, mzxid: Zxid ] \union
[ mtype: {ACKEPOCH}, mzxid: Zxid, mepoch: Nat \union {-1} ] \union
[ mtype: {DIFF}, mzxid: Zxid ] \union
[ mtype: {TRUNC}, mtruncZxid: Zxid ] \union
[ mtype: {SNAP}, msnapZxid: Zxid, msnapshot: Seq(HistoryItem)] \union
[ mtype: {PROPOSAL}, mzxid: Zxid, mdata: Value ] \union
[ mtype: {COMMIT}, mzxid: Zxid ] \union
[ mtype: {NEWLEADER}, mzxid: Zxid ] \union
[ mtype: {ACKLD}, mzxid: Zxid ] \union
[ mtype: {ACK}, mzxid: Zxid ] \union
[ mtype: {UPTODATE}, mzxid: Zxid ]
ElectionState == {LOOKING, FOLLOWING, LEADING}
ZabState == {ELECTION, DISCOVERY, SYNCHRONIZATION, BROADCAST}
ViolationSet == {"stateInconsistent", "proposalInconsistent",
"commitInconsistent", "ackInconsistent",
"messageIllegal" }
SyncMode == {DIFF, TRUNC, SNAP, NONE}
Connecting == [ sid : Server,
connected: BOOLEAN ]
AckldRecv == Connecting
Electing == [ sid: Server,
peerLastZxid: Zxid,
inQuorum: BOOLEAN ]
ConnectInfo == [ sid : ServersIncNullPoint,
syncMode: SyncMode,
nlRcv: BOOLEAN ]
Vote ==
[proposedLeader: ServersIncNullPoint,
proposedZxid: Zxid,
proposedEpoch: Nat ]
ElectionVote ==
[vote: Vote, round: Nat, state: ElectionState, version: Nat]
ElectionMsg ==
[ mtype: {NOTIFICATION},
msource: Server,
mstate: ElectionState,
mround: Nat,
mvote: Vote ] \union
[ mtype: {NONE} ]
TypeOK ==
/\ zabState \in [Server -> ZabState]
/\ acceptedEpoch \in [Server -> Nat]
/\ lastCommitted \in [Server -> LastItem]
/\ lastSnapshot \in [Server -> LastItem]
/\ learners \in [Server -> SUBSET Server]
/\ connecting \in [Server -> SUBSET Connecting]
/\ electing \in [Server -> SUBSET Electing]
/\ ackldRecv \in [Server -> SUBSET AckldRecv]
/\ forwarding \in [Server -> SUBSET Server]
/\ initialHistory \in [Server -> Seq(HistoryItem)]
/\ tempMaxEpoch \in [Server -> Nat]
/\ connectInfo \in [Server -> ConnectInfo]
/\ packetsSync \in [Server -> SyncPackets]
/\ status \in [Server -> {ONLINE, OFFLINE}]
/\ partition \in [Server -> [Server -> BOOLEAN ]]
/\ proposalMsgsLog \in SUBSET Proposal
/\ epochLeader \in [1..MAXEPOCH -> SUBSET Server]
/\ violatedInvariants \in [ViolationSet -> BOOLEAN]
/\ msgs \in [Server -> [Server -> Seq(Message)]]
\* Fast Leader Election
/\ electionMsgs \in [Server -> [Server -> Seq(ElectionMsg)]]
/\ recvQueue \in [Server -> Seq(ElectionMsg)]
/\ leadingVoteSet \in [Server -> SUBSET Server]
/\ receiveVotes \in [Server -> [Server -> ElectionVote]]
/\ currentVote \in [Server -> Vote]
/\ outOfElection \in [Server -> [Server -> ElectionVote]]
/\ lastProcessed \in [Server -> LastItem]
/\ history \in [Server -> Seq(HistoryItem)]
/\ state \in [Server -> ElectionState]
/\ waitNotmsg \in [Server -> BOOLEAN]
/\ currentEpoch \in [Server -> Nat]
/\ logicalClock \in [Server -> Nat]
-----------------------------------------------------------------------------
\* Return the maximum value from the set S
Maximum(S) == IF S = {} THEN -1
ELSE CHOOSE n \in S: \A m \in S: n >= m
\* Return the minimum value from the set S
Minimum(S) == IF S = {} THEN -1
ELSE CHOOSE n \in S: \A m \in S: n <= m
\* Check server state
IsON(s) == status[s] = ONLINE
IsOFF(s) == status[s] = OFFLINE
IsLeader(s) == state[s] = LEADING
IsFollower(s) == state[s] = FOLLOWING
IsLooking(s) == state[s] = LOOKING
IsMyLearner(i, j) == j \in learners[i]
IsMyLeader(i, j) == connectInfo[i].sid = j
HasNoLeader(i) == connectInfo[i].sid = NullPoint
HasLeader(i) == connectInfo[i].sid /= NullPoint
MyVote(i) == currentVote[i].proposedLeader
\* Check if s is a quorum
IsQuorum(s) == s \in Quorums
HasPartitioned(i, j) == /\ partition[i][j] = TRUE
/\ partition[j][i] = TRUE
-----------------------------------------------------------------------------
\* Check zxid state
ToZxid(z) == [epoch |-> z[1], counter |-> z[2]]
TxnZxidEqual(txn, z) == txn.zxid[1] = z[1] /\ txn.zxid[2] = z[2]
TxnEqual(txn1, txn2) == /\ ZxidEqual(txn1.zxid, txn2.zxid)
/\ txn1.value = txn2.value
EpochPrecedeInTxn(txn1, txn2) == txn1.zxid[1] < txn2.zxid[1]
-----------------------------------------------------------------------------
\* Actions about recorder
GetParameter(p) == IF p \in DOMAIN Parameters THEN Parameters[p] ELSE 0
GetRecorder(p) == IF p \in DOMAIN recorder THEN recorder[p] ELSE 0
RecorderGetHelper(m) == (m :> recorder[m])
RecorderIncHelper(m) == (m :> recorder[m] + 1)
RecorderIncTimeout == RecorderIncHelper("nTimeout")
RecorderGetTimeout == RecorderGetHelper("nTimeout")
RecorderIncCrash == RecorderIncHelper("nCrash")
RecorderGetCrash == RecorderGetHelper("nCrash")
RecorderSetTransactionNum(pc) == ("nTransaction" :>
IF pc[1] = "LeaderProcessRequest" THEN
LET s == CHOOSE i \in Server:
\A j \in Server: Len(history'[i]) >= Len(history'[j])
IN Len(history'[s])
ELSE recorder["nTransaction"])
RecorderSetMaxEpoch(pc) == ("maxEpoch" :>
IF pc[1] = "LeaderProcessFOLLOWERINFO" THEN
LET s == CHOOSE i \in Server:
\A j \in Server: acceptedEpoch'[i] >= acceptedEpoch'[j]
IN acceptedEpoch'[s]
ELSE recorder["maxEpoch"])
RecorderSetRequests(pc) == ("nClientRequest" :>
IF pc[1] = "LeaderProcessRequest" THEN
recorder["nClientRequest"] + 1
ELSE recorder["nClientRequest"] )
RecorderSetPartition(pc) == ("nPartition" :>
IF pc[1] = "PartitionStart" THEN recorder["nPartition"] + 1
ELSE recorder["nPartition"] )
RecorderSetPc(pc) == ("pc" :> pc)
RecorderSetFailure(pc) == CASE pc[1] = "Timeout" -> RecorderIncTimeout @@ RecorderGetCrash
[] pc[1] = "LeaderTimeout" -> RecorderIncTimeout @@ RecorderGetCrash
[] pc[1] = "FollowerTimeout" -> RecorderIncTimeout @@ RecorderGetCrash
[] pc[1] = "PartitionStart" -> IF IsLooking(pc[2])
THEN RecorderGetTimeout @@ RecorderGetCrash
ELSE RecorderIncTimeout @@ RecorderGetCrash
[] pc[1] = "NodeCrash" -> IF IsLooking(pc[2])
THEN RecorderGetTimeout @@ RecorderIncCrash
ELSE RecorderIncTimeout @@ RecorderIncCrash
[] OTHER -> RecorderGetTimeout @@ RecorderGetCrash
UpdateRecorder(pc) == recorder' = RecorderSetPartition(pc)
@@ RecorderSetFailure(pc) @@ RecorderSetTransactionNum(pc)
@@ RecorderSetMaxEpoch(pc) @@ RecorderSetPc(pc)
@@ RecorderSetRequests(pc) @@ recorder
UnchangeRecorder == UNCHANGED recorder
CheckParameterHelper(n, p, Comp(_,_)) == IF p \in DOMAIN Parameters
THEN Comp(n, Parameters[p])
ELSE TRUE
CheckParameterLimit(n, p) == CheckParameterHelper(n, p, LAMBDA i, j: i < j)
CheckTimeout == CheckParameterLimit(recorder.nTimeout, "MaxTimeoutFailures")
CheckTransactionNum == CheckParameterLimit(recorder.nTransaction, "MaxTransactionNum")
CheckEpoch == CheckParameterLimit(recorder.maxEpoch, "MaxEpoch")
CheckPartition == /\ CheckTimeout
/\ CheckParameterLimit(recorder.nPartition, "MaxPartitions")
CheckCrash(i) == /\ \/ IsLooking(i)
\/ /\ ~IsLooking(i)
/\ CheckTimeout
/\ CheckParameterLimit(recorder.nCrash, "MaxCrashes")
CheckStateConstraints == CheckTimeout /\ CheckTransactionNum /\ CheckEpoch
-----------------------------------------------------------------------------
\* Actions about network
PendingFOLLOWERINFO(i, j) == /\ msgs[j][i] /= << >>
/\ msgs[j][i][1].mtype = FOLLOWERINFO
PendingLEADERINFO(i, j) == /\ msgs[j][i] /= << >>
/\ msgs[j][i][1].mtype = LEADERINFO
PendingACKEPOCH(i, j) == /\ msgs[j][i] /= << >>
/\ msgs[j][i][1].mtype = ACKEPOCH
PendingNEWLEADER(i, j) == /\ msgs[j][i] /= << >>
/\ msgs[j][i][1].mtype = NEWLEADER
PendingACKLD(i, j) == /\ msgs[j][i] /= << >>
/\ msgs[j][i][1].mtype = ACKLD
PendingUPTODATE(i, j) == /\ msgs[j][i] /= << >>
/\ msgs[j][i][1].mtype = UPTODATE
PendingPROPOSAL(i, j) == /\ msgs[j][i] /= << >>
/\ msgs[j][i][1].mtype = PROPOSAL
PendingACK(i, j) == /\ msgs[j][i] /= << >>
/\ msgs[j][i][1].mtype = ACK
PendingCOMMIT(i, j) == /\ msgs[j][i] /= << >>
/\ msgs[j][i][1].mtype = COMMIT
\* Add a message to msgs - add a message m to msgs.
Send(i, j, m) == msgs' = [msgs EXCEPT ![i][j] = Append(msgs[i][j], m)]
SendPackets(i, j, ms) == msgs' = [msgs EXCEPT ![i][j] = msgs[i][j] \o ms ]
DiscardAndSendPackets(i, j, ms) == msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]),
![i][j] = msgs[i][j] \o ms ]
\* Remove a message from msgs - discard head of msgs.
Discard(i, j) == msgs' = IF msgs[i][j] /= << >> THEN [msgs EXCEPT ![i][j] = Tail(msgs[i][j])]
ELSE msgs
\* Leader broadcasts a message(PROPOSAL/COMMIT) to all other servers in forwardingFollowers.
Broadcast(i, m) == msgs' = [msgs EXCEPT ![i] = [v \in Server |-> IF /\ v \in forwarding[i]
/\ v /= i
THEN Append(msgs[i][v], m)
ELSE msgs[i][v]]]
DiscardAndBroadcast(i, j, m) ==
msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]),
![i] = [v \in Server |-> IF /\ v \in forwarding[i]
/\ v /= i
THEN Append(msgs[i][v], m)
ELSE msgs[i][v]]]
\* Leader broadcasts LEADERINFO to all other servers in connectingFollowers.
DiscardAndBroadcastLEADERINFO(i, j, m) ==
LET new_connecting_quorum == {c \in connecting'[i]: c.connected = TRUE }
new_sid_connecting == {c.sid: c \in new_connecting_quorum }
IN
msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]),
![i] = [v \in Server |-> IF /\ v \in new_sid_connecting
/\ v \in learners[i]
/\ v /= i
THEN Append(msgs[i][v], m)
ELSE msgs[i][v] ] ]
\* Leader broadcasts UPTODATE to all other servers in newLeaderProposal.
DiscardAndBroadcastUPTODATE(i, j, m) ==
LET new_ackldRecv_quorum == {a \in ackldRecv'[i]: a.connected = TRUE }
new_sid_ackldRecv == {a.sid: a \in new_ackldRecv_quorum}
IN
msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]),
![i] = [v \in Server |-> IF /\ v \in new_sid_ackldRecv
/\ v \in learners[i]
/\ v /= i
THEN Append(msgs[i][v], m)
ELSE msgs[i][v] ] ]
\* Combination of Send and Discard - discard head of msgs[j][i] and add m into msgs.
Reply(i, j, m) == msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]),
![i][j] = Append(msgs[i][j], m)]
\* Shuffle input buffer.
Clean(i, j) == msgs' = [msgs EXCEPT ![j][i] = << >>, ![i][j] = << >>]
CleanInputBuffer(i) == msgs' = [s \in Server |-> [v \in Server |-> IF v = i THEN << >>
ELSE msgs[s][v]]]
CleanInputBufferInCluster(S) == msgs' = [s \in Server |->
[v \in Server |-> IF v \in S THEN << >>
ELSE msgs[s][v] ] ]
-----------------------------------------------------------------------------
\* Define initial values for all variables
InitServerVars == /\ InitServerVarsL
/\ zabState = [s \in Server |-> ELECTION]
/\ acceptedEpoch = [s \in Server |-> 0]
/\ lastCommitted = [s \in Server |-> [ index |-> 0,
zxid |-> <<0, 0>> ] ]
/\ lastSnapshot = [s \in Server |-> [ index |-> 0,
zxid |-> <<0, 0>> ] ]
/\ initialHistory = [s \in Server |-> << >>]
InitLeaderVars == /\ InitLeaderVarsL
/\ learners = [s \in Server |-> {}]
/\ connecting = [s \in Server |-> {}]
/\ electing = [s \in Server |-> {}]
/\ ackldRecv = [s \in Server |-> {}]
/\ forwarding = [s \in Server |-> {}]
/\ tempMaxEpoch = [s \in Server |-> 0]
InitElectionVars == InitElectionVarsL
InitFollowerVars == /\ connectInfo = [s \in Server |-> [sid |-> NullPoint,
syncMode |-> NONE,
nlRcv |-> FALSE ] ]
/\ packetsSync = [s \in Server |->
[ notCommitted |-> << >>,
committed |-> << >> ] ]
InitVerifyVars == /\ proposalMsgsLog = {}
/\ epochLeader = [e \in 1..MAXEPOCH |-> {} ]
/\ violatedInvariants = [stateInconsistent |-> FALSE,
proposalInconsistent |-> FALSE,
commitInconsistent |-> FALSE,
ackInconsistent |-> FALSE,
messageIllegal |-> FALSE ]
InitMsgVars == /\ msgs = [s \in Server |-> [v \in Server |-> << >>] ]
/\ electionMsgs = [s \in Server |-> [v \in Server |-> << >>] ]
InitEnvVars == /\ status = [s \in Server |-> ONLINE ]
/\ partition = [s \in Server |-> [v \in Server |-> FALSE] ]
InitRecorder == recorder = [nTimeout |-> 0,
nTransaction |-> 0,
nPartition |-> 0,
maxEpoch |-> 0,
nCrash |-> 0,
pc |-> <<"Init">>,
nClientRequest |-> 0]
Init == /\ InitServerVars
/\ InitLeaderVars
/\ InitElectionVars
/\ InitFollowerVars
/\ InitVerifyVars
/\ InitMsgVars
/\ InitEnvVars
/\ InitRecorder
-----------------------------------------------------------------------------
ZabTurnToLeading(i) ==
/\ zabState' = [zabState EXCEPT ![i] = DISCOVERY]
/\ learners' = [learners EXCEPT ![i] = {i}]
/\ connecting' = [connecting EXCEPT ![i] = { [ sid |-> i,
connected |-> TRUE ] }]
/\ electing' = [electing EXCEPT ![i] = { [ sid |-> i,
peerLastZxid |-> <<-1,-1>>,
inQuorum |-> TRUE ] }]
/\ ackldRecv' = [ackldRecv EXCEPT ![i] = { [ sid |-> i,
connected |-> TRUE ] }]
/\ forwarding' = [forwarding EXCEPT ![i] = {}]
/\ initialHistory' = [initialHistory EXCEPT ![i] = history'[i]]
/\ tempMaxEpoch' = [tempMaxEpoch EXCEPT ![i] = acceptedEpoch[i] + 1]
ZabTurnToFollowing(i) ==
/\ zabState' = [zabState EXCEPT ![i] = DISCOVERY]
/\ initialHistory' = [initialHistory EXCEPT ![i] = history'[i]]
/\ packetsSync' = [packetsSync EXCEPT ![i].notCommitted = << >>,
![i].committed = << >> ]
(* Fast Leader Election *)
FLEReceiveNotmsg(i, j) ==
/\ IsON(i)
/\ ReceiveNotmsg(i, j)
/\ UNCHANGED <<zabState, acceptedEpoch, lastCommitted, learners, connecting,
initialHistory, electing, ackldRecv, forwarding, tempMaxEpoch,
lastSnapshot, followerVars, verifyVars, envVars, msgs>>
/\ UpdateRecorder(<<"FLEReceiveNotmsg", i, j>>)
FLENotmsgTimeout(i) ==
/\ IsON(i)
/\ NotmsgTimeout(i)
/\ UNCHANGED <<zabState, acceptedEpoch, lastCommitted, learners, connecting,
initialHistory, electing, ackldRecv, forwarding, tempMaxEpoch,
lastSnapshot, followerVars, verifyVars, envVars, msgs>>
/\ UpdateRecorder(<<"FLENotmsgTimeout", i>>)
FLEHandleNotmsg(i) ==
/\ IsON(i)
/\ HandleNotmsg(i)
/\ LET newState == state'[i]
IN
\/ /\ newState = LEADING
/\ ZabTurnToLeading(i)
/\ UNCHANGED packetsSync
\/ /\ newState = FOLLOWING
/\ ZabTurnToFollowing(i)
/\ UNCHANGED <<learners, connecting, electing, ackldRecv,
forwarding, tempMaxEpoch>>
\/ /\ newState = LOOKING
/\ UNCHANGED <<zabState, learners, connecting, electing, ackldRecv,
forwarding, tempMaxEpoch, packetsSync, initialHistory>>
/\ UNCHANGED <<lastCommitted, lastSnapshot, acceptedEpoch,
connectInfo, verifyVars, envVars, msgs>>
/\ UpdateRecorder(<<"FLEHandleNotmsg", i>>)
\* On the premise that ReceiveVotes.HasQuorums = TRUE,
\* corresponding to logic in FastLeaderElection.
FLEWaitNewNotmsg(i) ==
/\ IsON(i)
/\ WaitNewNotmsg(i)
/\ LET newState == state'[i]
IN
\/ /\ newState = LEADING
/\ ZabTurnToLeading(i)
/\ UNCHANGED packetsSync
\/ /\ newState = FOLLOWING
/\ ZabTurnToFollowing(i)
/\ UNCHANGED <<learners, connecting, electing, ackldRecv, forwarding,
tempMaxEpoch>>
\/ /\ newState = LOOKING
/\ PrintT("Note: New state is LOOKING in FLEWaitNewNotmsgEnd," \o
" which should not happen.")
/\ UNCHANGED <<zabState, learners, connecting, electing, ackldRecv,
forwarding, tempMaxEpoch, initialHistory, packetsSync>>
/\ UNCHANGED <<lastCommitted, lastSnapshot, acceptedEpoch,
connectInfo, verifyVars, envVars, msgs>>
/\ UpdateRecorder(<<"FLEWaitNewNotmsg", i>>)
-----------------------------------------------------------------------------
InitialVotes == [ vote |-> InitialVote,
round |-> 0,
state |-> LOOKING,
version |-> 0 ]
InitialConnectInfo == [sid |-> NullPoint,
syncMode |-> NONE,
nlRcv |-> FALSE ]
\* Equals to for every server in S, performing action ZabTimeout.
ZabTimeoutInCluster(S) ==
/\ state' = [s \in Server |-> IF s \in S THEN LOOKING ELSE state[s] ]
/\ lastProcessed' = [s \in Server |-> IF s \in S THEN InitLastProcessed(s)
ELSE lastProcessed[s] ]
/\ logicalClock' = [s \in Server |-> IF s \in S THEN logicalClock[s] + 1
ELSE logicalClock[s] ]
/\ currentVote' = [s \in Server |-> IF s \in S THEN
[proposedLeader |-> s,
proposedZxid |-> lastProcessed'[s].zxid,
proposedEpoch |-> currentEpoch[s] ]
ELSE currentVote[s] ]
/\ receiveVotes' = [s \in Server |-> IF s \in S THEN [v \in Server |-> InitialVotes]
ELSE receiveVotes[s] ]
/\ outOfElection' = [s \in Server |-> IF s \in S THEN [v \in Server |-> InitialVotes]
ELSE outOfElection[s] ]
/\ recvQueue' = [s \in Server |-> IF s \in S THEN << [mtype |-> NONE] >>
ELSE recvQueue[s] ]
/\ waitNotmsg' = [s \in Server |-> IF s \in S THEN FALSE ELSE waitNotmsg[s] ]
/\ leadingVoteSet' = [s \in Server |-> IF s \in S THEN {} ELSE leadingVoteSet[s] ]
/\ UNCHANGED <<electionMsgs, currentEpoch, history>>
/\ zabState' = [s \in Server |-> IF s \in S THEN ELECTION ELSE zabState[s] ]
/\ connectInfo' = [s \in Server |-> IF s \in S THEN InitialConnectInfo
ELSE connectInfo[s] ]
/\ CleanInputBufferInCluster(S)
(* Describe how a server transitions from LEADING/FOLLOWING to LOOKING.*)
FollowerShutdown(i) ==
/\ ZabTimeout(i)
/\ zabState' = [zabState EXCEPT ![i] = ELECTION]
/\ connectInfo' = [connectInfo EXCEPT ![i] = InitialConnectInfo]
LeaderShutdown(i) ==
/\ LET cluster == {i} \union learners[i]
IN ZabTimeoutInCluster(cluster)
/\ learners' = [learners EXCEPT ![i] = {}]
/\ forwarding' = [forwarding EXCEPT ![i] = {}]
RemoveElecting(set, sid) ==
LET sid_electing == {s.sid: s \in set }
IN IF sid \notin sid_electing THEN set
ELSE LET info == CHOOSE s \in set: s.sid = sid
new_info == [ sid |-> sid,
peerLastZxid |-> <<-1, -1>>,
inQuorum |-> info.inQuorum ]
IN (set \ {info}) \union {new_info}
RemoveConnectingOrAckldRecv(set, sid) ==
LET sid_set == {s.sid: s \in set}
IN IF sid \notin sid_set THEN set
ELSE LET info == CHOOSE s \in set: s.sid = sid
new_info == [ sid |-> sid,
connected |-> FALSE ]
IN (set \ {info}) \union {new_info}
\* See removeLearnerHandler for details.
RemoveLearner(i, j) ==
/\ learners' = [learners EXCEPT ![i] = @ \ {j}]
/\ forwarding' = [forwarding EXCEPT ![i] = IF j \in forwarding[i]
THEN @ \ {j} ELSE @ ]
/\ electing' = [electing EXCEPT ![i] = RemoveElecting(@, j) ]
/\ connecting' = [connecting EXCEPT ![i] = RemoveConnectingOrAckldRecv(@, j) ]
/\ ackldRecv' = [ackldRecv EXCEPT ![i] = RemoveConnectingOrAckldRecv(@, j) ]
-----------------------------------------------------------------------------
\* Actions of situation error.
PartitionStart(i, j) ==
/\ CheckPartition \* test restrictions of partition
/\ i /= j
/\ IsON(i)
/\ IsON(j)
/\ \lnot HasPartitioned(i, j)
/\ \/ /\ IsLeader(i) /\ IsMyLearner(i, j)
/\ IsFollower(j) /\ IsMyLeader(j, i)
/\ LET newLearners == learners[i] \ {j}
IN \/ /\ IsQuorum(newLearners) \* just remove this learner
/\ RemoveLearner(i, j)
/\ FollowerShutdown(j)
/\ Clean(i ,j)
\/ /\ ~IsQuorum(newLearners) \* leader switches to looking
/\ LeaderShutdown(i)
/\ UNCHANGED <<connecting, electing, ackldRecv>>
\/ /\ IsLooking(i)
/\ IsLooking(j)
/\ IdCompare(i, j)
/\ UNCHANGED <<varsL, zabState, connectInfo, msgs, learners,
forwarding, connecting, electing, ackldRecv>>
/\ partition' = [partition EXCEPT ![i][j] = TRUE, ![j][i] = TRUE ]
/\ UNCHANGED <<acceptedEpoch, lastCommitted, lastSnapshot, tempMaxEpoch,
initialHistory, verifyVars, packetsSync, status>>
/\ UpdateRecorder(<<"PartitionStart", i, j>>)
PartitionRecover(i, j) ==
/\ IsON(i)
/\ IsON(j)
/\ IdCompare(i, j)
/\ HasPartitioned(i, j)
/\ partition' = [partition EXCEPT ![i][j] = FALSE, ![j][i] = FALSE ]
/\ UNCHANGED <<serverVars, leaderVars, electionVars, followerVars,
verifyVars, msgVars, status>>
/\ UpdateRecorder(<<"PartitionRecover", i, j>>)
NodeCrash(i) ==
/\ CheckCrash(i)
/\ IsON(i)
/\ status' = [status EXCEPT ![i] = OFFLINE ]
/\ \/ /\ IsLooking(i)
/\ UNCHANGED <<varsL, zabState, connectInfo, msgs, learners,
forwarding, connecting, electing, ackldRecv>>
\/ /\ IsFollower(i)
/\ LET connectedWithLeader == HasLeader(i)
IN \/ /\ connectedWithLeader
/\ LET leader == connectInfo[i].sid
newCluster == learners[leader] \ {i}
IN
\/ /\ IsQuorum(newCluster)
/\ RemoveLearner(leader, i)
/\ FollowerShutdown(i)
/\ Clean(leader, i)
\/ /\ ~IsQuorum(newCluster)
/\ LeaderShutdown(leader)
/\ UNCHANGED <<electing, connecting, ackldRecv>>
\/ /\ ~connectedWithLeader
/\ FollowerShutdown(i)
/\ CleanInputBuffer({i})
/\ UNCHANGED <<learners, forwarding, connecting, electing, ackldRecv>>
\/ /\ IsLeader(i)
/\ LeaderShutdown(i)
/\ UNCHANGED <<electing, connecting, ackldRecv>>
/\ UNCHANGED <<acceptedEpoch, lastCommitted, lastSnapshot, tempMaxEpoch,
initialHistory, verifyVars, packetsSync, partition>>
/\ UpdateRecorder(<<"NodeCrash", i>>)
NodeStart(i) ==
/\ IsOFF(i)
/\ status' = [status EXCEPT ![i] = ONLINE ]
/\ lastProcessed' = [lastProcessed EXCEPT ![i] = InitLastProcessed(i)]
/\ lastCommitted' = [lastCommitted EXCEPT ![i] = lastSnapshot[i]]
/\ UNCHANGED <<state, currentEpoch, zabState, acceptedEpoch, history,
lastSnapshot, initialHistory, leaderVars, electionVars,
followerVars, verifyVars, msgVars, partition>>
/\ UpdateRecorder(<<"NodeStart", i>>)
-----------------------------------------------------------------------------
(* Establish connection between leader and follower, containing actions like
addLearnerHandler, findLeader, connectToLeader.*)
ConnectAndFollowerSendFOLLOWERINFO(i, j) ==
/\ IsON(i) /\ IsON(j)
/\ IsLeader(i) /\ \lnot IsMyLearner(i, j)
/\ IsFollower(j) /\ HasNoLeader(j) /\ MyVote(j) = i
/\ learners' = [learners EXCEPT ![i] = learners[i] \union {j}]
/\ connectInfo' = [connectInfo EXCEPT ![j].sid = i]
/\ Send(j, i, [ mtype |-> FOLLOWERINFO,
mzxid |-> <<acceptedEpoch[j], 0>> ])
/\ UNCHANGED <<serverVars, electionVars, leadingVoteSet, connecting,
electing, ackldRecv, forwarding, tempMaxEpoch,
verifyVars, envVars, electionMsgs, packetsSync>>
/\ UpdateRecorder(<<"ConnectAndFollowerSendFOLLOWERINFO", i, j>>)
\* waitingForNewEpoch in Leader
WaitingForNewEpoch(i, set) == (i \in set /\ IsQuorum(set)) = FALSE
WaitingForNewEpochTurnToFalse(i, set) == /\ i \in set
/\ IsQuorum(set)
\* There may exists some follower in connecting but shuts down and
\* connects again. So when leader broadcasts LEADERINFO, the
\* follower will receive LEADERINFO, and receive it again after
\* sending FOLLOWERINFO. So connected makes sure each follower
\* will only receive LEADERINFO at most once before timeout.
UpdateConnectingOrAckldRecv(oldSet, sid) ==
LET sid_set == {s.sid: s \in oldSet}
IN IF sid \in sid_set
THEN LET old_info == CHOOSE info \in oldSet: info.sid = sid
follower_info == [ sid |-> sid,
connected |-> TRUE ]
IN (oldSet \ {old_info} ) \union {follower_info}
ELSE LET follower_info == [ sid |-> sid,
connected |-> TRUE ]
IN oldSet \union {follower_info}
(* Leader waits for receiving FOLLOWERINFO from a quorum including itself,
and chooses a new epoch e' as its own epoch and broadcasts LEADERINFO.
See getEpochToPropose in Leader for details. *)
LeaderProcessFOLLOWERINFO(i, j) ==
/\ CheckEpoch \* test restrictions of max epoch
/\ IsON(i)
/\ IsLeader(i)
/\ PendingFOLLOWERINFO(i, j)
/\ LET msg == msgs[j][i][1]
infoOk == IsMyLearner(i, j)
lastAcceptedEpoch == msg.mzxid[1]
sid_connecting == {c.sid: c \in connecting[i]}
IN
/\ infoOk
/\ \/ \* 1. has not broadcast LEADERINFO
/\ WaitingForNewEpoch(i, sid_connecting)
/\ \/ /\ zabState[i] = DISCOVERY
/\ UNCHANGED violatedInvariants
\/ /\ zabState[i] /= DISCOVERY
/\ PrintT("Exception: waitingFotNewEpoch true," \o
" while zabState not DISCOVERY.")
/\ violatedInvariants' = [violatedInvariants EXCEPT !.stateInconsistent = TRUE]
/\ tempMaxEpoch' = [tempMaxEpoch EXCEPT ![i] = IF lastAcceptedEpoch >= tempMaxEpoch[i]
THEN lastAcceptedEpoch + 1
ELSE @]
/\ connecting' = [connecting EXCEPT ![i] = UpdateConnectingOrAckldRecv(@, j) ]
/\ LET new_sid_connecting == {c.sid: c \in connecting'[i]}
IN
\/ /\ WaitingForNewEpochTurnToFalse(i, new_sid_connecting)
/\ acceptedEpoch' = [acceptedEpoch EXCEPT ![i] = tempMaxEpoch'[i]]
/\ LET newLeaderZxid == <<acceptedEpoch'[i], 0>>
m == [ mtype |-> LEADERINFO,
mzxid |-> newLeaderZxid ]
IN DiscardAndBroadcastLEADERINFO(i, j, m)
\/ /\ ~WaitingForNewEpochTurnToFalse(i, new_sid_connecting)
/\ Discard(j, i)
/\ UNCHANGED acceptedEpoch
\/ \* 2. has broadcast LEADERINFO
/\ ~WaitingForNewEpoch(i, sid_connecting)
/\ Reply(i, j, [ mtype |-> LEADERINFO,
mzxid |-> <<acceptedEpoch[i], 0>> ] )
/\ UNCHANGED <<tempMaxEpoch, connecting, acceptedEpoch, violatedInvariants>>
/\ UNCHANGED <<state, currentEpoch, lastProcessed, zabState, history, lastCommitted,
followerVars, electionVars, initialHistory, leadingVoteSet, learners,
electing, ackldRecv, forwarding, proposalMsgsLog, epochLeader,
lastSnapshot, electionMsgs, envVars>>
/\ UpdateRecorder(<<"LeaderProcessFOLLOWERINFO", i, j>>)
(* Follower receives LEADERINFO. If newEpoch >= acceptedEpoch, then follower
updates acceptedEpoch and sends ACKEPOCH back, containing currentEpoch and
lastProcessedZxid. After this, zabState turns to SYNC.
See registerWithLeader in Learner for details.*)
FollowerProcessLEADERINFO(i, j) ==
/\ IsON(i)
/\ IsFollower(i)
/\ PendingLEADERINFO(i, j)
/\ LET msg == msgs[j][i][1]
newEpoch == msg.mzxid[1]
infoOk == IsMyLeader(i, j)
epochOk == newEpoch >= acceptedEpoch[i]
stateOk == zabState[i] = DISCOVERY
IN /\ infoOk
/\ \/ \* 1. Normal case
/\ epochOk
/\ \/ /\ stateOk
/\ \/ /\ newEpoch > acceptedEpoch[i]
/\ acceptedEpoch' = [acceptedEpoch EXCEPT ![i] = newEpoch]
/\ LET epochBytes == currentEpoch[i]
m == [ mtype |-> ACKEPOCH,
mzxid |-> lastProcessed[i].zxid,
mepoch |-> epochBytes ]
IN Reply(i, j, m)
\/ /\ newEpoch = acceptedEpoch[i]
/\ LET m == [ mtype |-> ACKEPOCH,
mzxid |-> lastProcessed[i].zxid,
mepoch |-> -1 ]
IN Reply(i, j, m)
/\ UNCHANGED acceptedEpoch
/\ zabState' = [zabState EXCEPT ![i] = SYNCHRONIZATION]
/\ UNCHANGED violatedInvariants
\/ /\ ~stateOk
/\ PrintT("Exception: Follower receives LEADERINFO," \o
" whileZabState not DISCOVERY.")
/\ violatedInvariants' = [violatedInvariants EXCEPT !.stateInconsistent = TRUE]
/\ Discard(j, i)
/\ UNCHANGED <<acceptedEpoch, zabState>>
/\ UNCHANGED <<varsL, connectInfo, learners, forwarding, electing,
connecting, ackldRecv>>
\/ \* 2. Abnormal case - go back to election
/\ ~epochOk
/\ FollowerShutdown(i)
/\ Clean(i, connectInfo[i].sid)
/\ RemoveLearner(connectInfo[i].sid, i)
/\ UNCHANGED <<acceptedEpoch, violatedInvariants>>
/\ UNCHANGED <<history, lastCommitted, tempMaxEpoch, initialHistory, lastSnapshot,
proposalMsgsLog, epochLeader, packetsSync, envVars>>
/\ UpdateRecorder(<<"FollowerProcessLEADERINFO", i, j>>)
-----------------------------------------------------------------------------
RECURSIVE UpdateAckSidHelper(_,_,_,_)
UpdateAckSidHelper(his, cur, end, target) ==
IF cur > end THEN his
ELSE LET curTxn == [ zxid |-> his[1].zxid,
value |-> his[1].value,
ackSid |-> IF target \in his[1].ackSid THEN his[1].ackSid
ELSE his[1].ackSid \union {target},
epoch |-> his[1].epoch ]
IN <<curTxn>> \o UpdateAckSidHelper(Tail(his), cur + 1, end, target)
\* There originally existed one bug in LeaderProcessACK when
\* monotonicallyInc = FALSE, and it is we did not add ackSid of
\* history in SYNC. So we update ackSid in syncFollower.
UpdateAckSid(his, lastSeenIndex, target) ==
IF Len(his) = 0 \/ lastSeenIndex = 0 THEN his
ELSE UpdateAckSidHelper(his, 1, Minimum( { Len(his), lastSeenIndex} ), target)
\* return -1: this zxid appears at least twice; Len(his) + 1: does not exist;
\* 1 ~ Len(his): exists and appears just once.
RECURSIVE ZxidToIndexHepler(_,_,_,_)
ZxidToIndexHepler(his, zxid, cur, appeared) ==
IF cur > Len(his) THEN cur
ELSE IF TxnZxidEqual(his[cur], zxid)
THEN CASE appeared = TRUE -> -1
[] OTHER -> Minimum( { cur,
ZxidToIndexHepler(his, zxid, cur + 1, TRUE) } )
ELSE ZxidToIndexHepler(his, zxid, cur + 1, appeared)
ZxidToIndex(his, zxid) == IF ZxidEqual( zxid, <<0, 0>> ) THEN 0
ELSE IF Len(his) = 0 THEN 1
ELSE LET len == Len(his) IN
IF \E idx \in 1..len: TxnZxidEqual(his[idx], zxid)
THEN ZxidToIndexHepler(his, zxid, 1, FALSE)
ELSE len + 1
\* Find index idx which meets:
\* history[idx].zxid <= zxid < history[idx + 1].zxid
RECURSIVE IndexOfZxidHelper(_,_,_,_)
IndexOfZxidHelper(his, zxid, cur, end) ==
IF cur > end THEN end
ELSE IF ZxidCompare(his[cur].zxid, zxid) THEN cur - 1
ELSE IndexOfZxidHelper(his, zxid, cur + 1, end)
IndexOfZxid(his, zxid) == IF Len(his) = 0 THEN 0
ELSE LET idx == ZxidToIndex(his, zxid)
len == Len(his)
IN
IF idx <= len THEN idx
ELSE IndexOfZxidHelper(his, zxid, 1, len)
RECURSIVE queuePackets(_,_,_,_,_)
queuePackets(queue, his, cur, committed, end) ==
IF cur > end THEN queue
ELSE CASE cur > committed ->
LET m_proposal == [ mtype |-> PROPOSAL,
mzxid |-> his[cur].zxid,
mdata |-> his[cur].value ]
IN queuePackets(Append(queue, m_proposal), his, cur + 1, committed, end)
[] cur <= committed ->
LET m_proposal == [ mtype |-> PROPOSAL,
mzxid |-> his[cur].zxid,
mdata |-> his[cur].value ]
m_commit == [ mtype |-> COMMIT,
mzxid |-> his[cur].zxid ]
newQueue == queue \o <<m_proposal, m_commit>>
IN queuePackets(newQueue, his, cur + 1, committed, end)
RECURSIVE setPacketsForChecking(_,_,_,_,_,_)
setPacketsForChecking(set, src, ep, his, cur, end) ==
IF cur > end THEN set
ELSE LET m_proposal == [ source |-> src,
epoch |-> ep,
zxid |-> his[cur].zxid,
data |-> his[cur].value ]
IN setPacketsForChecking((set \union {m_proposal}), src, ep, his, cur + 1, end)
\* Func lead() calls zk.loadData(), which will call takeSnapshot().
LastSnapshot(i) == IF zabState[i] = BROADCAST THEN lastSnapshot[i]
ELSE CASE IsLeader(i) ->
LET lastIndex == Len(history[i])
IN IF lastIndex = 0 THEN [ index |-> 0,
zxid |-> <<0, 0>> ]
ELSE [ index |-> lastIndex,
zxid |-> history[i][lastIndex].zxid ]
[] OTHER -> lastSnapshot[i]
\* To compress state space,
\* 1. we merge sending SNAP and outputing snapshot buffer into sending SNAP, and
\* 2. substitute sub sequence of history for snapshot of data tree.
SerializeSnapshot(i, idx) == IF idx <= 0 THEN << >>
ELSE SubSeq(history[i], 1, idx)
(* See queueCommittedProposals in LearnerHandler and startForwarding in Leader
for details. For proposals in committedLog and toBeApplied, send <PROPOSAL,
COMMIT>. For proposals in outstandingProposals, send PROPOSAL only. *)
SendSyncMsgs(i, j, lastSeenZxid, lastSeenIndex, mode, needRemoveHead) ==
/\ LET lastCommittedIndex == IF zabState[i] = BROADCAST
THEN lastCommitted[i].index
ELSE Len(history[i])
lastProposedIndex == Len(history[i])
queue_origin == IF lastSeenIndex >= lastProposedIndex
THEN << >>
ELSE queuePackets(<< >>, history[i],
lastSeenIndex + 1, lastCommittedIndex,
lastProposedIndex)
set_forChecking == IF lastSeenIndex >= lastProposedIndex
THEN {}
ELSE setPacketsForChecking( { }, i,
acceptedEpoch[i], history[i],
lastSeenIndex + 1, lastProposedIndex)
m_trunc == [ mtype |-> TRUNC, mtruncZxid |-> lastSeenZxid ]
m_diff == [ mtype |-> DIFF, mzxid |-> lastSeenZxid ]
m_snap == [ mtype |-> SNAP, msnapZxid |-> lastSeenZxid,
msnapshot |-> SerializeSnapshot(i, lastSeenIndex) ]
newLeaderZxid == <<acceptedEpoch[i], 0>>
m_newleader == [ mtype |-> NEWLEADER,
mzxid |-> newLeaderZxid ]
queue_toSend == CASE mode = TRUNC -> (<<m_trunc>> \o queue_origin) \o <<m_newleader>>
[] mode = DIFF -> (<<m_diff>> \o queue_origin) \o <<m_newleader>>
[] mode = SNAP -> (<<m_snap>> \o queue_origin) \o <<m_newleader>>
IN /\ \/ /\ needRemoveHead
/\ DiscardAndSendPackets(i, j, queue_toSend)