Debian Codegraph @

server/raft_test.go

raw
1 // Copyright 2021-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bytes"
18 "encoding/binary"
19 "errors"
20 "fmt"
21 "math"
22 "math/rand"
23 "net/url"
24 "os"
25 "path"
26 "path/filepath"
27 "reflect"
28 "slices"
29 "strings"
30 "sync"
31 "sync/atomic"
32 "testing"
33 "time"
34
35 "github.com/nats-io/nats.go"
36 )
37
38 func TestNRGSimple(t *testing.T) {
39 c := createJetStreamClusterExplicit(t, "R3S", 3)
40 defer c.shutdown()
41
42 rg := c.createRaftGroup("TEST", 3, newStateAdder)
43 rg.waitOnLeader()
44 // Do several state transitions.
45 rg.randomMember().(*stateAdder).proposeDelta(22)
46 rg.randomMember().(*stateAdder).proposeDelta(-11)
47 rg.randomMember().(*stateAdder).proposeDelta(-10)
48 // Wait for all members to have the correct state.
49 rg.waitOnTotal(t, 1)
50 }
51
52 func TestNRGSnapshotAndRestart(t *testing.T) {
53 c := createJetStreamClusterExplicit(t, "R3S", 3)
54 defer c.shutdown()
55
56 rg := c.createRaftGroup("TEST", 3, newStateAdder)
57 lsm := rg.waitOnLeader()
58 require_NotNil(t, lsm)
59 leader := lsm.(*stateAdder)
60
61 var expectedTotal int64
62
63 sm := rg.nonLeader().(*stateAdder)
64
65 for i := 0; i < 1000; i++ {
66 delta := rand.Int63n(222)
67 expectedTotal += delta
68 leader.proposeDelta(delta)
69
70 if i == 250 {
71 // Let some things catchup.
72 time.Sleep(50 * time.Millisecond)
73 // Snapshot leader and stop and snapshot a member.
74 leader.snapshot(t)
75 sm.snapshot(t)
76 sm.stop()
77 }
78 }
79 // Restart.
80 sm.restart()
81 // Wait for all members to have the correct state.
82 rg.waitOnTotal(t, expectedTotal)
83 }
84
85 func TestNRGAppendEntryEncode(t *testing.T) {
86 ae := &appendEntry{
87 term: 1,
88 pindex: 0,
89 }
90
91 // Test leader should be _EMPTY_ or exactly idLen long
92 ae.leader = "foo_bar_baz"
93 _, err := ae.encode(nil)
94 require_Error(t, err, errLeaderLen)
95
96 // Empty ok (noLeader)
97 ae.leader = noLeader // _EMPTY_
98 _, err = ae.encode(nil)
99 require_NoError(t, err)
100
101 ae.leader = "DEREK123"
102 _, err = ae.encode(nil)
103 require_NoError(t, err)
104
105 // Buffer reuse
106 var rawSmall [32]byte
107 var rawBigger [64]byte
108
109 b := rawSmall[:]
110 ae.encode(b)
111 if b[0] != 0 {
112 t.Fatalf("Expected arg buffer to not be used")
113 }
114 b = rawBigger[:]
115 ae.encode(b)
116 if b[0] == 0 {
117 t.Fatalf("Expected arg buffer to be used")
118 }
119
120 // Test max number of entries.
121 for i := 0; i < math.MaxUint16+1; i++ {
122 ae.entries = append(ae.entries, &Entry{EntryNormal, nil})
123 }
124 _, err = ae.encode(b)
125 require_Error(t, err, errTooManyEntries)
126 }
127
128 func TestNRGAppendEntryDecode(t *testing.T) {
129 ae := &appendEntry{
130 leader: "12345678",
131 term: 1,
132 pindex: 0,
133 }
134 for i := 0; i < math.MaxUint16; i++ {
135 ae.entries = append(ae.entries, &Entry{EntryNormal, nil})
136 }
137 buf, err := ae.encode(nil)
138 require_NoError(t, err)
139
140 // Truncate buffer first.
141 short := buf[0 : len(buf)-1025]
142 _, err = decodeAppendEntry(short, nil, _EMPTY_)
143 require_Error(t, err, errBadAppendEntry)
144
145 for i := 0; i < 100; i++ {
146 b := copyBytes(buf)
147 // modifying the header (idx < 42) will not result in an error by decodeAppendEntry
148 bi := 42 + rand.Intn(len(b)-42)
149 if b[bi] != 0 && bi != 40 {
150 b[bi] = 0
151 _, err = decodeAppendEntry(b, nil, _EMPTY_)
152 require_Error(t, err, errBadAppendEntry)
153 }
154 }
155 }
156
157 func TestNRGAppendEntryDecodeTruncatedEntryLength(t *testing.T) {
158 ae := &appendEntry{
159 leader: "12345678",
160 term: 1,
161 entries: []*Entry{newEntry(EntryNormal, nil)},
162 }
163
164 buf, err := ae.encode(nil)
165 require_NoError(t, err)
166
167 // Truncate the 4 byte length field of the first entry.
168 // The decoder wants to read 4 bytes, finds only 2 bytes left.
169 truncated := buf[:appendEntryBaseLen+2]
170 _, err = decodeAppendEntry(truncated, nil, _EMPTY_)
171 require_Error(t, err, errBadAppendEntry)
172 }
173
174 func TestNRGPeerStateDecodeTruncated(t *testing.T) {
175 ps := &peerState{knownPeers: []string{"12345678", "abcdefgh"}, clusterSize: 2}
176 buf := encodePeerState(ps)
177
178 // Sanity check the round trip.
179 dps, err := decodePeerState(buf)
180 require_NoError(t, err)
181 require_Equal(t, len(dps.knownPeers), 2)
182 require_Equal(t, dps.clusterSize, 2)
183
184 // Header claims one peer but only a partial id (idLen-5 bytes) follows.
185 // len == cap so the partial id can not be read past the slice.
186 truncated := make([]byte, 8+idLen-5)
187 le := binary.LittleEndian
188 le.PutUint32(truncated[0:], 1)
189 le.PutUint32(truncated[4:], 1)
190 _, err = decodePeerState(truncated)
191 require_Error(t, err, errCorruptPeers)
192 }
193
194 func TestNRGRecoverFromFollowingNoLeader(t *testing.T) {
195 c := createJetStreamClusterExplicit(t, "R3S", 3)
196 defer c.shutdown()
197
198 rg := c.createRaftGroup("TEST", 3, newStateAdder)
199 rg.waitOnLeader()
200
201 // Find out what term we are on.
202 term := rg.leader().node().Term()
203
204 // Start by pausing all of the nodes. This will stop them from
205 // processing new entries.
206 for _, n := range rg {
207 n.node().PauseApply()
208 }
209
210 // Now drain all of the ApplyQ entries from them, which will stop
211 // them from automatically trying to follow a previous leader if
212 // they happened to have received an apply entry from one. Then
213 // we're going to force them into a state where they are all
214 // followers but they don't have a leader.
215 for _, n := range rg {
216 rn := n.node().(*raft)
217 rn.ApplyQ().drain()
218 rn.switchToFollower(noLeader)
219 }
220
221 // Resume the nodes.
222 for _, n := range rg {
223 n.node().ResumeApply()
224 }
225
226 // Wait a while. The nodes should notice that they haven't heard
227 // from a leader lately and will switch to voting. After an
228 // election we should find a new leader and be on a new term.
229 rg.waitOnLeader()
230 require_True(t, rg.leader() != nil)
231 require_NotEqual(t, rg.leader().node().Term(), term)
232 }
233
234 func TestNRGInlineStepdown(t *testing.T) {
235 c := createJetStreamClusterExplicit(t, "R3S", 3)
236 defer c.shutdown()
237
238 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
239 rg.waitOnLeader()
240
241 // When StepDown() completes, we should not be the leader. Before,
242 // this would not be guaranteed as the stepdown could be processed
243 // some time later.
244 n := rg.leader().node().(*raft)
245 require_NoError(t, n.StepDown())
246 require_NotEqual(t, n.State(), Leader)
247 }
248
249 func TestNRGMalformedAppendEntryResponse(t *testing.T) {
250 c := createJetStreamClusterExplicit(t, "R3S", 3)
251 defer c.shutdown()
252
253 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
254 rg.waitOnLeader()
255
256 n := rg.leader().node().(*raft)
257
258 // A message whose length does not match appendEntryResponseLen decodes to
259 // nil. This must not cause a nil pointer dereference/panic.
260 n.handleAppendEntryResponse(nil, nil, nil, "subject", "reply", []byte{})
261 n.handleAppendEntryResponse(nil, nil, nil, "subject", "reply", []byte{1, 2, 3})
262 }
263
264 func TestNRGObserverMode(t *testing.T) {
265 c := createJetStreamClusterExplicit(t, "R3S", 3)
266 defer c.shutdown()
267
268 rg := c.createRaftGroup("TEST", 3, newStateAdder)
269 rg.waitOnLeader()
270
271 // Put all of the followers into observer mode. In this state
272 // they will not participate in an election but they will continue
273 // to apply incoming commits.
274 for _, n := range rg {
275 if n.node().Leader() {
276 continue
277 }
278 n.node().SetObserver(true)
279 }
280
281 // Propose a change from the leader.
282 adder := rg.leader().(*stateAdder)
283 adder.proposeDelta(1)
284 adder.proposeDelta(2)
285 adder.proposeDelta(3)
286
287 // Wait for the followers to apply it.
288 rg.waitOnTotal(t, 6)
289
290 // Confirm the followers are still just observers and weren't
291 // reset out of that state for some reason.
292 for _, n := range rg {
293 if n.node().Leader() {
294 continue
295 }
296 require_True(t, n.node().IsObserver())
297 }
298 }
299
300 func TestNRGAEFromOldLeader(t *testing.T) {
301 c := createJetStreamClusterExplicit(t, "R3S", 3)
302 defer c.shutdown()
303
304 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
305 defer nc.Close()
306
307 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
308 rg.waitOnLeader()
309
310 // Listen out for catchup requests.
311 ch := make(chan *nats.Msg, 16)
312 _, err := nc.ChanSubscribe(fmt.Sprintf(raftCatchupReply, ">"), ch)
313 require_NoError(t, err)
314
315 // Start next term so that we can reuse term 1 in the next step.
316 leader := rg.leader().node().(*raft)
317 leader.StepDown()
318 time.Sleep(time.Millisecond * 100)
319 rg.waitOnLeader()
320 require_Equal(t, leader.Term(), 2)
321 leader = rg.leader().node().(*raft)
322
323 // Send an append entry with an outdated term. Beforehand, doing
324 // so would have caused a WAL reset and then would have triggered
325 // a Raft-level catchup.
326 ae := &appendEntry{
327 term: 1,
328 pindex: 0,
329 leader: leader.id,
330 reply: nc.NewRespInbox(),
331 }
332 payload, err := ae.encode(nil)
333 require_NoError(t, err)
334 resp, err := nc.Request(leader.asubj, payload, time.Second)
335 require_NoError(t, err)
336
337 // Wait for the response, the server should have rejected it.
338 ar := decodeAppendEntryResponse(resp.Data)
339 require_NotNil(t, ar)
340 require_Equal(t, ar.success, false)
341
342 // No catchup should happen at this point because no reset should
343 // have happened.
344 require_NoChanRead(t, ch, time.Second*2)
345 }
346
347 // TestNRGSimpleElection tests that a simple election succeeds. It is
348 // simple because the group hasn't processed any entries and hasn't
349 // suffered any interruptions of any kind, therefore there should be
350 // no way that the conditions for granting the votes can fail.
351 func TestNRGSimpleElection(t *testing.T) {
352 c := createJetStreamClusterExplicit(t, "R3S", 9)
353 defer c.shutdown()
354 c.waitOnLeader()
355
356 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
357 defer nc.Close()
358
359 rg := c.createRaftGroup("TEST", 9, newStateAdder)
360 rg.waitOnLeader()
361
362 voteReqs := make(chan *nats.Msg, 1)
363 voteResps := make(chan *nats.Msg, len(rg)-1)
364
365 // Keep a record of the term when we started.
366 leader := rg.leader().node().(*raft)
367 startTerm := leader.term
368
369 // Subscribe to the vote request subject, this should be the
370 // same across all nodes in the group.
371 _, err := nc.ChanSubscribe(leader.vsubj, voteReqs)
372 require_NoError(t, err)
373
374 // Subscribe to all of the vote response inboxes for all nodes
375 // in the Raft group, as they can differ.
376 for _, n := range rg {
377 rn := n.node().(*raft)
378 _, err = nc.ChanSubscribe(rn.vreply, voteResps)
379 require_NoError(t, err)
380 }
381
382 // Step down, this will start a new voting session.
383 require_NoError(t, rg.leader().node().StepDown())
384
385 // Wait for a vote request to come in.
386 msg := require_ChanRead(t, voteReqs, time.Second)
387 vr := decodeVoteRequest(msg.Data, msg.Reply)
388 require_True(t, vr != nil)
389 require_NotEqual(t, vr.candidate, _EMPTY_)
390
391 // The leader should have bumped their term in order to start
392 // an election.
393 require_Equal(t, vr.term, startTerm+1)
394 require_Equal(t, vr.lastTerm, startTerm)
395
396 // Wait for all of the vote responses to come in. There should
397 // be as many vote responses as there are followers.
398 for i := 0; i < len(rg)-1; i++ {
399 msg := require_ChanRead(t, voteResps, time.Second)
400 re := decodeVoteResponse(msg.Data)
401 require_True(t, re != nil)
402
403 // Ignore old vote responses that could be in-flight.
404 if re.term < vr.term {
405 i--
406 continue
407 }
408
409 // The vote should have been granted.
410 require_Equal(t, re.granted, true)
411
412 // The node granted the vote, therefore the term in the vote
413 // response should have advanced as well.
414 require_Equal(t, re.term, vr.term)
415 require_Equal(t, re.term, startTerm+1)
416 }
417
418 // Everyone in the group should have voted for our candidate
419 // and arrived at the term from the vote request.
420 rg.lockAll()
421 defer rg.unlockAll()
422 for _, n := range rg {
423 rn := n.node().(*raft)
424 require_Equal(t, rn.term, vr.term)
425 require_Equal(t, rn.term, startTerm+1)
426 require_Equal(t, rn.vote, vr.candidate)
427 }
428 }
429
430 // TestNRGLeaderTransfer verifies that a Raft group correctly transfers
431 // leadership to a chosen preferred node when the current leader steps down.
432 func TestNRGLeaderTransfer(t *testing.T) {
433 c := createJetStreamClusterExplicit(t, "R3S", 3)
434 defer c.shutdown()
435
436 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
437 defer nc.Close()
438
439 rg := c.createMemRaftGroup("Test", 3, newStateAdder)
440 rg.waitOnLeader()
441
442 leader := rg.leader()
443 sub, err := nc.SubscribeSync(leader.node().(*raft).asubj)
444 require_NoError(t, err)
445 defer sub.Drain()
446 require_NoError(t, nc.Flush())
447
448 preferredID := rg.nonLeader().node().ID()
449 leader.node().StepDown(preferredID)
450 newLeader := rg.waitOnLeader()
451
452 require_Equal(t, newLeader.node().ID(), preferredID)
453
454 // Expect to see a EntryLeader message
455 checkFor(t, time.Second, 0, func() (err error) {
456 msg, err := sub.NextMsg(time.Second)
457 if err != nil {
458 return err
459 }
460
461 ae, err := decodeAppendEntry(msg.Data, nil, msg.Reply)
462 if err != nil {
463 return err
464 }
465
466 if len(ae.entries) == 1 {
467 e := ae.entries[0]
468 if e.Type == EntryLeaderTransfer && string(e.Data) == preferredID {
469 return nil
470 }
471 }
472
473 return fmt.Errorf("Expect EntryLeaderTransfer")
474 })
475 }
476
477 func TestNRGSwitchStateClearsQueues(t *testing.T) {
478 c := createJetStreamClusterExplicit(t, "R3S", 3)
479 defer c.shutdown()
480 s := c.servers[0] // RunBasicJetStreamServer not available
481
482 n := &raft{
483 prop: newIPQueue[*proposedEntry](s, "prop"),
484 resp: newIPQueue[*appendEntryResponse](s, "resp"),
485 leadc: make(chan leadChange, 1), // for switchState
486 sd: t.TempDir(),
487 dios: defaultDiskIOSemaphore(),
488 }
489 n.state.Store(int32(Leader))
490 require_Equal(t, n.prop.len(), 0)
491 require_Equal(t, n.resp.len(), 0)
492
493 n.prop.push(&proposedEntry{&Entry{}, _EMPTY_})
494 n.resp.push(&appendEntryResponse{})
495 require_Equal(t, n.prop.len(), 1)
496 require_Equal(t, n.resp.len(), 1)
497
498 n.switchState(Follower)
499 require_Equal(t, n.prop.len(), 0)
500 require_Equal(t, n.resp.len(), 0)
501 }
502
503 func TestNRGStepDownOnSameTermDoesntClearVote(t *testing.T) {
504 c := createJetStreamClusterExplicit(t, "R3S", 3)
505 defer c.shutdown()
506 c.waitOnLeader()
507
508 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
509 defer nc.Close()
510
511 rg := c.createRaftGroup("TEST", 3, newStateAdder)
512 rg.waitOnLeader()
513
514 lsm := rg.leader().(*stateAdder)
515 leader := lsm.node().(*raft)
516 follower := rg.nonLeader().node().(*raft)
517
518 // Make sure we handle the leader change notification from above.
519 require_ChanRead(t, lsm.lch, time.Second)
520
521 // Subscribe to the append entry subject.
522 sub, err := nc.SubscribeSync(leader.asubj)
523 require_NoError(t, err)
524
525 // Get the first append entry that we receive.
526 msg, err := sub.NextMsg(time.Second)
527 require_NoError(t, err)
528 require_NoError(t, sub.Unsubscribe())
529
530 // We're going to modify the append entry that we received so that
531 // we can send it again with modifications.
532 ae, err := decodeAppendEntry(msg.Data, nil, msg.Reply)
533 require_NoError(t, err)
534
535 // First of all we're going to try sending an append entry that
536 // has an old term and a fake leader.
537 msg.Reply = follower.areply
538 ae.leader = follower.id
539 ae.term = leader.term - 1
540 msg.Data, err = ae.encode(msg.Data[:0])
541 require_NoError(t, err)
542 require_NoError(t, nc.PublishMsg(msg))
543
544 // Because the term was old, the fake leader shouldn't matter as
545 // the current leader should ignore it.
546 require_NoChanRead(t, lsm.lch, time.Second)
547
548 // Now we're going to send it on the same term that the current leader
549 // is on. What we expect to happen is that the leader will step down
550 // but it *shouldn't* clear the vote.
551 ae.term = leader.term
552 msg.Data, err = ae.encode(msg.Data[:0])
553 require_NoError(t, err)
554 require_NoError(t, nc.PublishMsg(msg))
555
556 // Wait for the leader transition and ensure that the vote wasn't
557 // cleared.
558 require_ChanRead(t, lsm.lch, time.Second)
559 require_NotEqual(t, leader.vote, noVote)
560 }
561
562 func TestNRGUnsuccessfulVoteRequestDoesntResetElectionTimer(t *testing.T) {
563 // This test relies on nodes not hitting their election timer too often,
564 // otherwise the step later where we capture the election time before and
565 // after the failed vote request will flake.
566 origMinTimeout, origMaxTimeout, origHBInterval := minElectionTimeout, maxElectionTimeout, hbInterval
567 minElectionTimeout, maxElectionTimeout, hbInterval = time.Second*5, time.Second*10, time.Second*10
568 defer func() {
569 minElectionTimeout, maxElectionTimeout, hbInterval = origMinTimeout, origMaxTimeout, origHBInterval
570 }()
571
572 c := createJetStreamClusterExplicit(t, "R3S", 3)
573 defer c.shutdown()
574 c.waitOnLeader()
575
576 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
577 defer nc.Close()
578
579 rg := c.createRaftGroup("TEST", 3, newStateAdder)
580
581 // Because the election timer is quite high, we want to kick a node into
582 // campaigning before it naturally needs to, otherwise the test takes a
583 // long time just to pick a leader.
584 for _, n := range rg {
585 n.node().Campaign()
586 break
587 }
588 rg.waitOnLeader()
589 rgLeader := rg.leader()
590 leader := rgLeader.node().(*raft)
591 follower := rg.nonLeader().node().(*raft)
592
593 // Send one message to ensure heartbeats are not sent during the remainder of this test.
594 rgLeader.(*stateAdder).proposeDelta(1)
595 rg.waitOnTotal(t, 1)
596
597 // Set up a new inbox for the vote responses to go to.
598 vsubj, vreply := leader.vsubj, nc.NewInbox()
599 ch := make(chan *nats.Msg, 3)
600 _, err := nc.ChanSubscribe(vreply, ch)
601 require_NoError(t, err)
602
603 // Keep a track of the last time the election timer was reset before this.
604 // Also build up a vote request that's obviously behind so that the other
605 // nodes should not do anything with it. All locks are taken at the same
606 // time so that it guarantees that both the leader and the follower aren't
607 // operating at the time we take the etlr snapshots.
608 rg.lockAll()
609 leader.resetElect(maxElectionTimeout)
610 follower.resetElect(maxElectionTimeout)
611 leaderOriginal := leader.etlr
612 followerOriginal := follower.etlr
613 vr := &voteRequest{
614 term: follower.term - 1,
615 lastTerm: follower.term - 1,
616 lastIndex: 0,
617 candidate: follower.id,
618 }
619 rg.unlockAll()
620
621 // Now send a vote request that's obviously behind.
622 require_NoError(t, nc.PublishMsg(&nats.Msg{
623 Subject: vsubj,
624 Reply: vreply,
625 Data: vr.encode(),
626 }))
627
628 // Wait for everyone to respond.
629 require_ChanRead(t, ch, time.Second)
630 require_ChanRead(t, ch, time.Second)
631 require_ChanRead(t, ch, time.Second)
632
633 // Neither the leader nor our chosen follower should have updated their
634 // election timer as a result of this.
635 rg.lockAll()
636 leaderEqual := leaderOriginal.Equal(leader.etlr)
637 followerEqual := followerOriginal.Equal(follower.etlr)
638 rg.unlockAll()
639 require_True(t, leaderEqual)
640 require_True(t, followerEqual)
641 }
642
643 func TestNRGUnsuccessfulVoteRequestCampaignEarly(t *testing.T) {
644 n, cleanup := initSingleMemRaftNode(t)
645 defer cleanup()
646
647 nats0 := "S1Nunr6R" // "nats-0"
648 n.etlr = time.Time{}
649
650 // Simple case: we are follower and vote for a candidate.
651 require_NoError(t, n.processVoteRequest(&voteRequest{term: 1, lastTerm: 0, lastIndex: 0, candidate: nats0}))
652 require_Equal(t, n.term, 1)
653 require_Equal(t, n.vote, nats0)
654 require_NotEqual(t, n.etlr, time.Time{}) // Resets election timer as it voted.
655 n.etlr = time.Time{}
656
657 // We are follower and deny vote for outdated candidate.
658 n.pterm, n.pindex = 1, 100
659 require_NoError(t, n.processVoteRequest(&voteRequest{term: 2, lastTerm: 1, lastIndex: 2, candidate: nats0}))
660 require_Equal(t, n.term, 2)
661 require_Equal(t, n.vote, noVote)
662 require_NotEqual(t, n.etlr, time.Time{}) // Resets election timer as it starts campaigning.
663 n.etlr = time.Time{}
664
665 // Switch to candidate.
666 n.pterm, n.pindex = 2, 200
667 n.switchToCandidate()
668 require_Equal(t, n.term, 3)
669 require_Equal(t, n.State(), Candidate)
670 require_NotEqual(t, n.etlr, time.Time{}) // Resets election timer as part of switching state.
671 n.etlr = time.Time{}
672
673 // We are candidate and deny vote for outdated candidate. But they were on a more recent term, restart campaign.
674 require_NoError(t, n.processVoteRequest(&voteRequest{term: 4, lastTerm: 1, lastIndex: 2, candidate: nats0}))
675 require_Equal(t, n.term, 4)
676 require_Equal(t, n.vote, noVote)
677 require_NotEqual(t, n.etlr, time.Time{}) // Resets election timer as it restarts campaigning.
678 n.etlr = time.Time{}
679
680 // Switch to candidate.
681 n.pterm, n.pindex = 4, 400
682 n.switchToCandidate()
683 require_Equal(t, n.term, 5)
684 require_Equal(t, n.State(), Candidate)
685 require_NotEqual(t, n.etlr, time.Time{}) // Resets election timer as part of switching state.
686 n.etlr = time.Time{}
687
688 // We are candidate and deny vote for outdated candidate. Don't start campaigning early.
689 require_NoError(t, n.processVoteRequest(&voteRequest{term: 5, lastTerm: 1, lastIndex: 2, candidate: nats0}))
690 require_Equal(t, n.term, 5)
691 require_Equal(t, n.vote, noVote)
692 // Election timer must NOT be updated as that would mean another candidate that we don't vote
693 // for can short-circuit us by making us restart elections, denying us the ability to become leader.
694 require_Equal(t, n.etlr, time.Time{})
695 }
696
697 func TestNRGInvalidTAVDoesntPanic(t *testing.T) {
698 c := createJetStreamClusterExplicit(t, "R3S", 3)
699 defer c.shutdown()
700 c.waitOnLeader()
701
702 rg := c.createRaftGroup("TEST", 3, newStateAdder)
703 leader := rg.waitOnLeader()
704 require_NotNil(t, leader)
705
706 // Mangle the TAV file to a short length (less than uint64).
707 tav := filepath.Join(leader.node().(*raft).sd, termVoteFile)
708 require_NoError(t, os.WriteFile(tav, []byte{1, 2, 3, 4}, 0644))
709
710 // Restart the node.
711 leader.stop()
712 leader.restart()
713
714 // Before the fix, a crash would have happened before this point.
715 c.waitOnAllCurrent()
716 }
717
718 func TestNRGAssumeHighTermAfterCandidateIsolation(t *testing.T) {
719 c := createJetStreamClusterExplicit(t, "R3S", 3)
720 defer c.shutdown()
721 c.waitOnLeader()
722
723 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
724 defer nc.Close()
725
726 rg := c.createRaftGroup("TEST", 3, newStateAdder)
727 rg.waitOnLeader()
728
729 // Bump the term up on one of the follower nodes by a considerable
730 // amount and force it into the candidate state. This is what happens
731 // after a period of time in isolation.
732 follower := rg.nonLeader().node().(*raft)
733 follower.Lock()
734 follower.term += 100
735 follower.switchState(Candidate)
736 follower.Unlock()
737
738 follower.requestVote()
739 time.Sleep(time.Millisecond * 100)
740
741 // The candidate will shortly send a vote request. When that happens,
742 // the rest of the nodes in the cluster should move up to that term,
743 // even though they will not grant the vote.
744 nterm := follower.Term()
745 for _, n := range rg {
746 require_Equal(t, n.node().Term(), nterm)
747 }
748
749 // Have the leader send out a proposal, which will force the candidate
750 // back into follower state.
751 rg.waitOnLeader()
752 rg.leader().(*stateAdder).proposeDelta(1)
753 rg.waitOnTotal(t, 1)
754
755 // The candidate should have switched to a follower on a term equal to
756 // or newer than the candidate had.
757 for _, n := range rg {
758 require_NotEqual(t, n.node().State(), Candidate)
759 require_True(t, n.node().Term() >= nterm)
760 }
761 }
762
763 // Test to make sure this does not cause us to truncate our wal or enter catchup state.
764 func TestNRGHeartbeatOnLeaderChange(t *testing.T) {
765 c := createJetStreamClusterExplicit(t, "R3S", 3)
766 defer c.shutdown()
767
768 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
769 rg.waitOnLeader()
770
771 for i := 0; i < 10; i++ {
772 // Restart the leader.
773 leader := rg.leader().(*stateAdder)
774 leader.proposeDelta(22)
775 leader.proposeDelta(-11)
776 leader.proposeDelta(-10)
777 // Must observe forward progress, so each iteration will check +1 total.
778 rg.waitOnTotal(t, int64(i+1))
779 leader.stop()
780 leader.restart()
781 rg.waitOnLeader()
782 }
783 }
784
785 func TestNRGElectionTimerAfterObserver(t *testing.T) {
786 c := createJetStreamClusterExplicit(t, "R3S", 3)
787 defer c.shutdown()
788
789 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
790 rg.waitOnLeader()
791
792 for _, n := range rg {
793 n.node().SetObserver(true)
794 }
795
796 time.Sleep(maxElectionTimeout)
797 before := time.Now()
798
799 for _, n := range rg {
800 n.node().SetObserver(false)
801 }
802
803 time.Sleep(maxCampaignTimeout)
804
805 for _, n := range rg {
806 rn := n.node().(*raft)
807 rn.RLock()
808 etlr := rn.etlr
809 rn.RUnlock()
810 require_True(t, etlr.After(before))
811 }
812 }
813
814 func TestNRGSystemClientCleanupFromAccount(t *testing.T) {
815 c := createJetStreamClusterExplicit(t, "R3S", 3)
816 defer c.shutdown()
817
818 s := c.randomServer()
819 sacc := s.SystemAccount()
820
821 numClients := func() int {
822 sacc.mu.RLock()
823 defer sacc.mu.RUnlock()
824 return len(sacc.clients)
825 }
826
827 start := numClients()
828
829 var all []smGroup
830 for i := 0; i < 5; i++ {
831 rgName := fmt.Sprintf("TEST-%d", i)
832 rg := c.createRaftGroup(rgName, 3, newStateAdder)
833 all = append(all, rg)
834 rg.waitOnLeader()
835 }
836 for _, rg := range all {
837 for _, sm := range rg {
838 sm.node().Stop()
839 }
840 for _, sm := range rg {
841 sm.node().WaitForStop()
842 }
843 }
844 finish := numClients()
845 require_Equal(t, start, finish)
846 }
847
848 func TestNRGCandidateDoesntRevertTermAfterOldAE(t *testing.T) {
849 c := createJetStreamClusterExplicit(t, "R3S", 3)
850 defer c.shutdown()
851
852 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
853 rg.waitOnLeader()
854
855 // Bump the term up a few times.
856 for i := 0; i < 3; i++ {
857 rg.leader().node().StepDown()
858 time.Sleep(time.Millisecond * 50) // Needed because stepdowns not synchronous
859 rg.waitOnLeader()
860 }
861
862 leader := rg.leader().node().(*raft)
863 follower := rg.nonLeader().node().(*raft)
864
865 // Sanity check that we are where we expect to be.
866 require_Equal(t, leader.term, 4)
867 require_Equal(t, follower.term, 4)
868
869 // At this point the active term is 4 and pterm is 4, force the
870 // term up to 9. This won't bump the pterm.
871 rg.lockAll()
872 for _, n := range rg {
873 n.node().(*raft).term += 5
874 }
875 rg.unlockAll()
876
877 // Build an AE that has a term newer than the pterm but older than
878 // the term. Give it to the follower in candidate state.
879 ae := newAppendEntry(leader.id, 6, leader.commit, leader.pterm, leader.pindex, nil)
880 follower.switchToCandidate()
881 follower.processAppendEntry(ae, nil)
882
883 // The candidate must not have reverted back to term 6.
884 require_NotEqual(t, follower.term, 6)
885 }
886
887 func TestNRGTermDoesntRollBackToPtermOnCatchup(t *testing.T) {
888 c := createJetStreamClusterExplicit(t, "R3S", 3)
889 defer c.shutdown()
890
891 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
892 defer nc.Close()
893
894 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
895 rg.waitOnLeader()
896
897 // Propose some entries so that we have entries in the log that have pterm 1.
898 lsm := rg.leader().(*stateAdder)
899 for i := 0; i < 5; i++ {
900 lsm.proposeDelta(1)
901 rg.waitOnTotal(t, int64(i)+1)
902 }
903
904 // Check that everyone is where they are supposed to be.
905 rg.lockAll()
906 for _, n := range rg {
907 rn := n.node().(*raft)
908 require_Equal(t, rn.term, 1)
909 require_Equal(t, rn.pterm, 1)
910 require_Equal(t, rn.pindex, 6)
911 }
912 rg.unlockAll()
913
914 // Force a stepdown so that we move up to term 2.
915 rg.leader().node().(*raft).switchToFollower(noLeader)
916 rg.waitOnLeader()
917 leader := rg.leader().node().(*raft)
918
919 // Now make sure everyone has moved up to term 2. Additionally we're
920 // going to prune back the follower logs to term 1 as this is what will
921 // create the right conditions for the catchup.
922 rg.lockAll()
923 for _, n := range rg {
924 rn := n.node().(*raft)
925 require_Equal(t, rn.term, 2)
926
927 if !rn.Leader() {
928 rn.truncateWAL(1, 6)
929 require_Equal(t, rn.term, 2) // rn.term must stay the same
930 require_Equal(t, rn.pterm, 1)
931 require_Equal(t, rn.pindex, 6)
932 }
933 }
934 // This will make followers run a catchup.
935 ae := newAppendEntry(leader.id, leader.term, leader.commit, leader.pterm, leader.pindex, nil)
936 rg.unlockAll()
937
938 arInbox := nc.NewRespInbox()
939 arCh := make(chan *nats.Msg, 2)
940 _, err := nc.ChanSubscribe(arInbox, arCh)
941 require_NoError(t, err)
942
943 // Ensure the subscription is known by the server we're connected to,
944 // but also by the other servers in the cluster.
945 require_NoError(t, nc.Flush())
946 time.Sleep(100 * time.Millisecond)
947
948 // In order to trip this condition, we need to send an append entry that
949 // will trick the followers into running a catchup. In the process they
950 // were setting the term back to pterm which is incorrect.
951 b, err := ae.encode(nil)
952 require_NoError(t, err)
953 require_NoError(t, nc.PublishMsg(&nats.Msg{
954 Subject: fmt.Sprintf(raftAppendSubj, "TEST"),
955 Reply: arInbox,
956 Data: b,
957 }))
958
959 // Wait for both followers to respond to the append entry and then verify
960 // that none of the nodes should have reverted back to term 1.
961 require_ChanRead(t, arCh, time.Second*5) // First follower
962 require_ChanRead(t, arCh, time.Second*5) // Second follower
963 for _, n := range rg {
964 require_NotEqual(t, n.node().Term(), 1)
965 }
966 }
967
968 func TestNRGNoResetOnAppendEntryResponse(t *testing.T) {
969 c := createJetStreamClusterExplicit(t, "R3S", 3)
970 defer c.shutdown()
971
972 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
973 defer nc.Close()
974
975 rg := c.createRaftGroup("TEST", 3, newStateAdder)
976 rg.waitOnLeader()
977 c.waitOnAllCurrent()
978
979 leader := rg.leader().node().(*raft)
980 follower := rg.nonLeader().node().(*raft)
981 lsm := rg.leader().(*stateAdder)
982 isLeader := require_ChanRead(t, lsm.lch, 5*time.Second)
983 require_True(t, isLeader)
984
985 // Subscribe for append entries that aren't heartbeats and respond to
986 // each of them as though it's a non-success and with a higher term.
987 // The higher term in this case is what would cause the leader previously
988 // to reset the entire log which it shouldn't do.
989 _, err := nc.Subscribe(fmt.Sprintf(raftAppendSubj, "TEST"), func(msg *nats.Msg) {
990 if ae, err := decodeAppendEntry(msg.Data, nil, msg.Reply); err == nil && len(ae.entries) > 0 {
991 ar := newAppendEntryResponse(ae.term+1, ae.commit, follower.id, false)
992 require_NoError(t, msg.Respond(ar.encode(nil)))
993 }
994 })
995 require_NoError(t, err)
996
997 c.waitOnAllCurrent()
998
999 // Temporarily prevent followers to respond
1000 locked := rg.lockFollowers()
1001
1002 // Generate an append entry that the subscriber above can respond to.
1003 lsm.proposeDelta(5)
1004
1005 // Expect the leader to step down
1006 checkFor(t, 10*time.Second, 0, func() error {
1007 isLeader = require_ChanRead(t, lsm.lch, 5*time.Second)
1008 if isLeader {
1009 return fmt.Errorf("Node is still leader!")
1010 }
1011 return nil
1012 })
1013
1014 // Unlock the followers
1015 for _, l := range locked {
1016 l.node().(*raft).Unlock()
1017 }
1018
1019 // The was-leader should now have stepped down, make sure that it
1020 // didn't blow away its log in the process.
1021 rg.lockAll()
1022 defer rg.unlockAll()
1023 require_Equal(t, leader.State(), Follower)
1024 require_NotEqual(t, leader.pterm, 0)
1025 require_NotEqual(t, leader.pindex, 0)
1026 }
1027
1028 func TestNRGCandidateDontStepdownDueToLeaderOfPreviousTerm(t *testing.T) {
1029 // This test relies on nodes not hitting their election timer too often.
1030 origMinTimeout, origMaxTimeout, origHBInterval := minElectionTimeout, maxElectionTimeout, hbInterval
1031 minElectionTimeout, maxElectionTimeout, hbInterval = time.Second*5, time.Second*10, time.Second
1032 defer func() {
1033 minElectionTimeout, maxElectionTimeout, hbInterval = origMinTimeout, origMaxTimeout, origHBInterval
1034 }()
1035
1036 c := createJetStreamClusterExplicit(t, "R3S", 3)
1037 defer c.shutdown()
1038 c.waitOnLeader()
1039
1040 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
1041 defer nc.Close()
1042
1043 rg := c.createRaftGroup("TEST", 3, newStateAdder)
1044 rg.waitOnLeader()
1045
1046 var (
1047 candidatePterm uint64 = 50
1048 candidatePindex uint64 = 70
1049 candidateTerm uint64 = 100
1050 )
1051
1052 // Create a candidate that has received entries while they were a follower in a previous term
1053 candidate := rg.nonLeader().node().(*raft)
1054 candidate.Lock()
1055 candidate.switchState(Candidate)
1056 candidate.pterm = candidatePterm
1057 candidate.pindex = candidatePindex
1058 candidate.term = candidateTerm
1059 candidate.Unlock()
1060
1061 // Leader term is behind candidate
1062 leader := rg.leader().node().(*raft)
1063 leader.Lock()
1064 leader.term = candidatePterm
1065 leader.pterm = candidatePterm
1066 leader.pindex = candidatePindex
1067 leader.Unlock()
1068
1069 // Subscribe to the append entry subject.
1070 sub, err := nc.SubscribeSync(leader.asubj)
1071 require_NoError(t, err)
1072
1073 // Get the first append entry that we receive, should be heartbeat from leader of prev term
1074 msg, err := sub.NextMsg(5 * time.Second)
1075 require_NoError(t, err)
1076
1077 // Stop nodes from progressing so we can check state
1078 rg.lockAll()
1079 defer rg.unlockAll()
1080
1081 // Decode the append entry
1082 ae, err := decodeAppendEntry(msg.Data, nil, msg.Reply)
1083 require_NoError(t, err)
1084
1085 // Check that the append entry is from the leader
1086 require_Equal(t, ae.leader, leader.id)
1087 // Check that it came from the leader before it updated its term with the response from the candidate
1088 require_Equal(t, ae.term, candidatePterm)
1089
1090 // Check that the candidate hasn't stepped down
1091 require_Equal(t, candidate.State(), Candidate)
1092 // Check that the candidate's term is still ahead of the leader's term
1093 require_True(t, candidate.term > ae.term)
1094 }
1095
1096 func TestNRGRemoveLeaderPeerDeadlockBug(t *testing.T) {
1097 c := createJetStreamClusterExplicit(t, "R3S", 3)
1098 defer c.shutdown()
1099
1100 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
1101 rg.waitOnLeader()
1102
1103 n := rg.leader().node().(*raft)
1104 leader := n.ID()
1105
1106 // Propose to remove the leader as a peer. Will lead to a deadlock with bug.
1107 require_NoError(t, n.ProposeRemovePeer(leader))
1108 rg.waitOnLeader()
1109
1110 checkFor(t, 10*time.Second, 200*time.Millisecond, func() error {
1111 nl := n.GroupLeader()
1112 if nl != leader {
1113 return nil
1114 }
1115 return errors.New("Leader has not moved")
1116 })
1117 }
1118
1119 func TestNRGWALEntryWithoutQuorumMustTruncate(t *testing.T) {
1120 tests := []struct {
1121 title string
1122 modify func(rg smGroup)
1123 }{
1124 {
1125 // state equals, only need to remove the entry
1126 title: "equal",
1127 modify: func(rg smGroup) {},
1128 },
1129 {
1130 // state diverged, need to replace the entry
1131 title: "diverged",
1132 modify: func(rg smGroup) {
1133 rg.leader().(*stateAdder).proposeDelta(11)
1134 },
1135 },
1136 }
1137
1138 for _, test := range tests {
1139 t.Run(test.title, func(t *testing.T) {
1140 c := createJetStreamClusterExplicit(t, "R3S", 3)
1141 defer c.shutdown()
1142
1143 rg := c.createRaftGroup("TEST", 3, newStateAdder)
1144 rg.waitOnLeader()
1145
1146 var err error
1147 var scratch [1024]byte
1148
1149 // Simulate leader storing an AppendEntry in WAL but being hard killed before it can propose to its peers.
1150 n := rg.leader().node().(*raft)
1151 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1152 entries := []*Entry{newEntry(EntryNormal, esm)}
1153 n.Lock()
1154 ae := n.buildAppendEntry(entries)
1155 ae.buf, err = ae.encode(scratch[:])
1156 require_NoError(t, err)
1157 err = n.storeToWAL(ae)
1158 n.Unlock()
1159 require_NoError(t, err)
1160
1161 // Stop the leader so it moves to another one.
1162 n.shutdown()
1163
1164 // Wait for another leader to be picked
1165 rg.waitOnLeader()
1166
1167 // Make a modification, specific to this test.
1168 test.modify(rg)
1169
1170 // Restart the previous leader that contains the stored AppendEntry without quorum.
1171 for _, a := range rg {
1172 if a.node().ID() == n.ID() {
1173 sa := a.(*stateAdder)
1174 sa.restart()
1175 break
1176 }
1177 }
1178
1179 // The previous leader's WAL should truncate to remove the AppendEntry only it has.
1180 // Eventually all WALs for all peers must match.
1181 checkFor(t, 5*time.Second, 200*time.Millisecond, func() error {
1182 var expected []*appendEntry
1183 for _, a := range rg {
1184 an := a.node().(*raft)
1185 var state StreamState
1186 an.wal.FastState(&state)
1187 if len(expected) > 0 && int(state.LastSeq-state.FirstSeq+1) != len(expected) {
1188 return fmt.Errorf("WAL is different: too many entries")
1189 }
1190 // Loop over all entries in the WAL, checking if the contents for all RAFT nodes are equal.
1191 for index := state.FirstSeq; index <= state.LastSeq; index++ {
1192 ae, err := an.loadEntry(index)
1193 if err != nil {
1194 return err
1195 }
1196 ae.buf = nil // ... as we'll deeply check everything else in the AE.
1197 ae.lterm = 0 // ... as lterm can differ if one node caught up another.
1198 seq := int(index)
1199 if len(expected) < seq {
1200 expected = append(expected, ae)
1201 } else if !reflect.DeepEqual(expected[seq-1], ae) {
1202 return fmt.Errorf("WAL is different: stored AEs differ")
1203 }
1204 }
1205 }
1206 return nil
1207 })
1208 })
1209 }
1210 }
1211
1212 func TestNRGTermNoDecreaseAfterWALReset(t *testing.T) {
1213 c := createJetStreamClusterExplicit(t, "R3S", 3)
1214 defer c.shutdown()
1215
1216 rg := c.createRaftGroup("TEST", 3, newStateAdder)
1217 rg.waitOnLeader()
1218
1219 l := rg.leader().node().(*raft)
1220 l.Lock()
1221 l.term = 20
1222 l.Unlock()
1223
1224 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1225 entries := []*Entry{newEntry(EntryNormal, esm)}
1226 l.Lock()
1227 ae := l.buildAppendEntry(entries)
1228 l.Unlock()
1229
1230 for _, f := range rg {
1231 if f.node().ID() != l.ID() {
1232 fn := f.node().(*raft)
1233 fn.processAppendEntry(ae, fn.aesub)
1234 require_Equal(t, fn.term, 20) // Follower's term gets upped as expected.
1235 }
1236 }
1237
1238 // Lower the term, simulating the followers receiving a message from an old term/leader.
1239 ae.term = 3
1240 for _, f := range rg {
1241 if f.node().ID() != l.ID() {
1242 fn := f.node().(*raft)
1243 fn.processAppendEntry(ae, fn.aesub)
1244 require_Equal(t, fn.term, 20) // Follower should reject and the term stays the same.
1245
1246 fn.Lock()
1247 fn.resetWAL()
1248 fn.Unlock()
1249 fn.processAppendEntry(ae, fn.aesub)
1250 require_Equal(t, fn.term, 20) // Follower should reject again, even after reset, term stays the same.
1251 }
1252 }
1253 }
1254
1255 func TestNRGPendingAppendEntryCacheInvalidation(t *testing.T) {
1256 for _, test := range []struct {
1257 title string
1258 entries int
1259 }{
1260 {title: "empty", entries: 1},
1261 {title: "at limit", entries: paeDropThreshold},
1262 {title: "full", entries: paeDropThreshold + 1},
1263 } {
1264 t.Run(test.title, func(t *testing.T) {
1265 c := createJetStreamClusterExplicit(t, "R3S", 3)
1266 defer c.shutdown()
1267
1268 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
1269 rg.waitOnLeader()
1270 l := rg.leader()
1271
1272 l.(*stateAdder).proposeDelta(1)
1273 rg.waitOnTotal(t, 1)
1274
1275 // Fill up the cache with N entries.
1276 // The contents don't matter as they should never be applied.
1277 rg.lockAll()
1278 for _, s := range rg {
1279 n := s.node().(*raft)
1280 for i := 0; i < test.entries; i++ {
1281 n.pae[n.pindex+uint64(1+i)] = newAppendEntry("", 0, 0, 0, 0, nil)
1282 }
1283 }
1284 rg.unlockAll()
1285
1286 l.(*stateAdder).proposeDelta(1)
1287 rg.waitOnTotal(t, 2)
1288 })
1289 }
1290 }
1291
1292 func TestNRGTruncateWALClearsPendingAppendEntryCache(t *testing.T) {
1293 n, cleanup := initSingleMemRaftNode(t)
1294 defer cleanup()
1295
1296 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1297 entries := []*Entry{newEntry(EntryNormal, esm)}
1298
1299 nats0 := "S1Nunr6R" // "nats-0"
1300
1301 // Store three entries through the normal path so both the WAL and n.pae
1302 // are populated by cachePendingEntry.
1303 ae1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
1304 ae2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
1305 ae3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 2, entries: entries})
1306
1307 n.processAppendEntry(ae1, n.aesub)
1308 n.processAppendEntry(ae2, n.aesub)
1309 n.processAppendEntry(ae3, n.aesub)
1310
1311 n.Lock()
1312 defer n.Unlock()
1313
1314 // Sanity check: WAL and cache both have all three entries.
1315 require_Equal(t, n.pindex, 3)
1316 require_Equal(t, n.wal.State().Msgs, 3)
1317 require_NotNil(t, n.pae[1])
1318 require_NotNil(t, n.pae[2])
1319 require_NotNil(t, n.pae[3])
1320
1321 // Truncate WAL back to index 1, dropping entries 2 and 3 from the log.
1322 n.truncateWAL(1, 1)
1323 require_Equal(t, n.pindex, 1)
1324 require_Equal(t, n.wal.State().Msgs, 1)
1325
1326 // The cache must not retain entries for indices the WAL no longer holds,
1327 // otherwise applyCommit could later apply stale entries straight from
1328 // the cache (bypassing the WAL load path).
1329 require_Len(t, len(n.pae), 1)
1330 require_NotNil(t, n.pae[1])
1331 }
1332
1333 func TestNRGTruncateWALRevertsUncommittedAddPeer(t *testing.T) {
1334 const (
1335 KindLeader = iota
1336 KindFollower
1337 KindRestart
1338 )
1339 test := func(kind int) {
1340 n, cleanup := initSingleMemRaftNode(t)
1341 defer cleanup()
1342
1343 nats0 := "S1Nunr6R" // "nats-0"
1344 newPeer := "yrzKKRBu" // "nats-1"
1345 n.addPeer(nats0)
1346 require_Len(t, len(n.peers), 2)
1347
1348 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1349 normal := []*Entry{newEntry(EntryNormal, esm)}
1350 addPeer := newEntry(EntryAddPeer, []byte(newPeer))
1351
1352 if kind == KindLeader {
1353 n.switchToLeader()
1354 n.sendMembershipChange(addPeer)
1355 } else {
1356 // Store a normal entry, then an uncommitted AddPeer entry.
1357 ae1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: normal})
1358 ae2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: []*Entry{addPeer}})
1359 aesub := n.aesub
1360 if kind == KindRestart {
1361 aesub = nil
1362 }
1363 n.processAppendEntry(ae1, aesub)
1364 n.processAppendEntry(ae2, aesub)
1365 }
1366
1367 // The peer is tracked speculatively, and a membership change is now inflight.
1368 require_Equal(t, n.pindex, 2)
1369 _, ok := n.peers[newPeer]
1370 require_True(t, ok)
1371 require_Equal(t, n.csz, 3)
1372 require_Equal(t, n.qn, 2)
1373 require_NotNil(t, n.membChange)
1374 require_Equal(t, n.membChange.index, 2)
1375 require_Equal(t, n.membChange.peer, newPeer)
1376 require_True(t, n.membChange.prev == nil)
1377
1378 // Raftz should report the new peer as not known/committed yet.
1379 rz := n.s.Raftz(&RaftzOptions{AccountFilter: globalAccountName})
1380 require_NotNil(t, rz)
1381 gz := (*rz)[globalAccountName]["TEST"]
1382 require_NotNil(t, gz)
1383 require_Len(t, len(gz.Peers), 2)
1384 require_True(t, gz.Peers[nats0].Known)
1385 require_False(t, gz.Peers[newPeer].Known)
1386
1387 // Truncate the uncommitted AddPeer entry. Its speculative effects must be reverted.
1388 n.Lock()
1389 n.truncateWAL(1, 1)
1390 n.Unlock()
1391 require_Equal(t, n.pindex, 1)
1392 _, ok = n.peers[newPeer]
1393 require_False(t, ok)
1394 require_Equal(t, n.csz, 2)
1395 require_Equal(t, n.qn, 2)
1396 require_True(t, n.membChange == nil)
1397
1398 // Raftz should also be reverted.
1399 rz = n.s.Raftz(&RaftzOptions{AccountFilter: globalAccountName})
1400 require_NotNil(t, rz)
1401 gz = (*rz)[globalAccountName]["TEST"]
1402 require_NotNil(t, gz)
1403 require_Len(t, len(gz.Peers), 1)
1404 require_True(t, gz.Peers[nats0].Known)
1405 }
1406
1407 t.Run("Leader", func(t *testing.T) { test(KindLeader) })
1408 t.Run("Follower", func(t *testing.T) { test(KindFollower) })
1409 t.Run("Restart", func(t *testing.T) { test(KindRestart) })
1410 }
1411
1412 func TestNRGTruncateWALRevertsUncommittedRemovePeer(t *testing.T) {
1413 const (
1414 KindLeader = iota
1415 KindFollower
1416 KindRestart
1417 )
1418 test := func(kind int) {
1419 n, cleanup := initSingleMemRaftNode(t)
1420 defer cleanup()
1421
1422 nats0 := "S1Nunr6R" // "nats-0"
1423 oldPeer := "yrzKKRBu" // "nats-1"
1424 n.addPeer(nats0)
1425 n.addPeer(oldPeer)
1426 require_Len(t, len(n.peers), 3)
1427
1428 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1429 normal := []*Entry{newEntry(EntryNormal, esm)}
1430 removePeer := newEntry(EntryRemovePeer, []byte(oldPeer))
1431
1432 if kind == KindLeader {
1433 n.switchToLeader()
1434 n.sendMembershipChange(removePeer)
1435 } else {
1436 // Store a normal entry, then an uncommitted AddPeer entry.
1437 ae1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: normal})
1438 ae2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: []*Entry{removePeer}})
1439 aesub := n.aesub
1440 if kind == KindRestart {
1441 aesub = nil
1442 }
1443 n.processAppendEntry(ae1, aesub)
1444 n.processAppendEntry(ae2, aesub)
1445 }
1446
1447 // The peer is gone and quorum shrank.
1448 _, ok := n.peers[oldPeer]
1449 require_False(t, ok)
1450 require_Equal(t, n.csz, 2)
1451 require_Equal(t, n.qn, 2)
1452 _, ok = n.removed[oldPeer]
1453 require_False(t, ok)
1454 require_NotNil(t, n.membChange)
1455 require_Equal(t, n.membChange.index, 2)
1456 require_Equal(t, n.membChange.peer, oldPeer)
1457 require_NotNil(t, n.membChange.prev)
1458
1459 // Raftz shouldn't report the to-be-removed peer anymore.
1460 rz := n.s.Raftz(&RaftzOptions{AccountFilter: globalAccountName})
1461 require_NotNil(t, rz)
1462 gz := (*rz)[globalAccountName]["TEST"]
1463 require_NotNil(t, gz)
1464 require_Len(t, len(gz.Peers), 1)
1465 require_True(t, gz.Peers[nats0].Known)
1466
1467 // Truncate the uncommitted RemovePeer entry. Its speculative effects must be reverted.
1468 n.Lock()
1469 n.truncateWAL(1, 1)
1470 n.Unlock()
1471 _, ok = n.peers[oldPeer]
1472 require_True(t, ok)
1473 require_Equal(t, n.csz, 3)
1474 require_Equal(t, n.qn, 2)
1475 _, ok = n.removed[oldPeer]
1476 require_False(t, ok)
1477 require_True(t, n.membChange == nil)
1478
1479 // Raftz should also be reverted.
1480 rz = n.s.Raftz(&RaftzOptions{AccountFilter: globalAccountName})
1481 require_NotNil(t, rz)
1482 gz = (*rz)[globalAccountName]["TEST"]
1483 require_NotNil(t, gz)
1484 require_Len(t, len(gz.Peers), 2)
1485 require_True(t, gz.Peers[nats0].Known)
1486 require_True(t, gz.Peers[oldPeer].Known)
1487 }
1488
1489 t.Run("Leader", func(t *testing.T) { test(KindLeader) })
1490 t.Run("Follower", func(t *testing.T) { test(KindFollower) })
1491 t.Run("Restart", func(t *testing.T) { test(KindRestart) })
1492 }
1493
1494 func TestNRGResetWALClearsPendingAppendEntryCache(t *testing.T) {
1495 n, cleanup := initSingleMemRaftNode(t)
1496 defer cleanup()
1497
1498 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1499 entries := []*Entry{newEntry(EntryNormal, esm)}
1500
1501 nats0 := "S1Nunr6R" // "nats-0"
1502
1503 ae1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
1504 ae2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
1505 ae3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 2, entries: entries})
1506
1507 n.processAppendEntry(ae1, n.aesub)
1508 n.processAppendEntry(ae2, n.aesub)
1509 n.processAppendEntry(ae3, n.aesub)
1510
1511 n.Lock()
1512 defer n.Unlock()
1513
1514 require_Equal(t, n.pindex, 3)
1515 require_Equal(t, len(n.pae), 3)
1516
1517 n.resetWAL()
1518 require_Equal(t, n.pindex, 0)
1519 require_Equal(t, n.wal.State().Msgs, 0)
1520
1521 // All cached pending append entries should be gone after a full reset.
1522 require_Equal(t, len(n.pae), 0)
1523 }
1524
1525 func TestNRGInstallSnapshotClearsPendingAppendEntryCache(t *testing.T) {
1526 n, cleanup := initSingleMemRaftNode(t)
1527 defer cleanup()
1528
1529 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1530 entries := []*Entry{newEntry(EntryNormal, esm)}
1531
1532 nats0 := "S1Nunr6R" // "nats-0"
1533
1534 // Three appendEntries arrive with commit lagging at 0, so applyCommit
1535 // never runs and all three remain cached in n.pae.
1536 ae1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
1537 ae2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
1538 ae3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 2, entries: entries})
1539
1540 n.processAppendEntry(ae1, n.aesub)
1541 n.processAppendEntry(ae2, n.aesub)
1542 n.processAppendEntry(ae3, n.aesub)
1543
1544 n.Lock()
1545 defer n.Unlock()
1546
1547 require_Equal(t, n.pindex, 3)
1548 require_Equal(t, n.commit, 0)
1549 require_Equal(t, len(n.pae), 3)
1550
1551 // Install a snapshot covering the entire log. The WAL gets compacted
1552 // past index 3, but cached entries 1-3 would otherwise stay in n.pae
1553 // since applyCommit never ran for them and cachePendingEntry only
1554 // overwrites at the current n.pindex (which won't revisit 1-3).
1555 snap := &snapshot{
1556 lastTerm: 1,
1557 lastIndex: 3,
1558 peerstate: encodePeerState(&peerState{n.peerNames(), n.csz, n.extSt}),
1559 }
1560 require_NoError(t, n.installSnapshot(snap))
1561
1562 require_Equal(t, n.wal.State().Msgs, 0)
1563 require_Equal(t, len(n.pae), 0)
1564 }
1565
1566 func TestNRGCatchupFromSnapshotClearsPendingAppendEntryCache(t *testing.T) {
1567 n, cleanup := initSingleMemRaftNode(t)
1568 defer cleanup()
1569
1570 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1571 entries := []*Entry{newEntry(EntryNormal, esm)}
1572 snapshotEntries := []*Entry{
1573 newEntry(EntrySnapshot, nil),
1574 newEntry(EntryPeerState, encodePeerState(&peerState{n.peerNames(), n.csz, n.extSt})),
1575 }
1576
1577 nats0 := "S1Nunr6R" // "nats-0"
1578
1579 // Receive two appendEntries normally; commit lags so both stay cached.
1580 ae1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
1581 ae2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
1582 n.processAppendEntry(ae1, n.aesub)
1583 n.processAppendEntry(ae2, n.aesub)
1584 require_Equal(t, n.pindex, 2)
1585 require_Equal(t, len(n.pae), 2)
1586
1587 // Leader is way ahead; this triggers catchup.
1588 aeTriggerCatchup := encode(t, &appendEntry{leader: nats0, term: 1, commit: 100, pterm: 1, pindex: 100, entries: nil})
1589 n.processAppendEntry(aeTriggerCatchup, n.aesub)
1590 require_True(t, n.catchup != nil)
1591
1592 // Leader sends a snapshot at the catchup point. n.pindex/n.commit jump
1593 // to 100 without applyCommit running for indices 1-2, so the cached
1594 // entries from before catchup would otherwise leak.
1595 aeCatchupSnapshot := encode(t, &appendEntry{leader: nats0, term: 1, commit: 100, pterm: 1, pindex: 100, entries: snapshotEntries})
1596 n.processAppendEntry(aeCatchupSnapshot, n.catchup.sub)
1597
1598 n.Lock()
1599 defer n.Unlock()
1600 require_Equal(t, n.pindex, 100)
1601 require_Equal(t, n.commit, 100)
1602 require_Equal(t, len(n.pae), 0)
1603 }
1604
1605 func TestNRGCatchupDoesNotTruncateUncommittedEntriesWithQuorum(t *testing.T) {
1606 n, cleanup := initSingleMemRaftNode(t)
1607 defer cleanup()
1608
1609 // Create a sample entry, the content doesn't matter, just that it's stored.
1610 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1611 entries := []*Entry{newEntry(EntryNormal, esm)}
1612
1613 nats0 := "S1Nunr6R" // "nats-0"
1614 nats1 := "yrzKKRBu" // "nats-1"
1615
1616 // Timeline, for first leader
1617 aeInitial := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
1618 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
1619 aeUncommitted := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
1620 aeNoQuorum := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 2, entries: entries})
1621
1622 // Timeline, after leader change
1623 aeMissed := encode(t, &appendEntry{leader: nats1, term: 2, commit: 1, pterm: 1, pindex: 2, entries: entries})
1624 aeCatchupTrigger := encode(t, &appendEntry{leader: nats1, term: 2, commit: 1, pterm: 2, pindex: 3, entries: entries})
1625 aeHeartbeat2 := encode(t, &appendEntry{leader: nats1, term: 2, commit: 2, pterm: 2, pindex: 4, entries: nil})
1626 aeHeartbeat3 := encode(t, &appendEntry{leader: nats1, term: 2, commit: 4, pterm: 2, pindex: 4, entries: nil})
1627
1628 // Initial case is simple, just store the entry.
1629 n.processAppendEntry(aeInitial, n.aesub)
1630 require_Equal(t, n.wal.State().Msgs, 1)
1631 entry, err := n.loadEntry(1)
1632 require_NoError(t, err)
1633 require_Equal(t, entry.leader, nats0)
1634
1635 // Heartbeat, makes sure commit moves up.
1636 n.processAppendEntry(aeHeartbeat, n.aesub)
1637 require_Equal(t, n.commit, 1)
1638
1639 // We get one entry that has quorum (but we don't know that yet), so it stays uncommitted for a bit.
1640 n.processAppendEntry(aeUncommitted, n.aesub)
1641 require_Equal(t, n.wal.State().Msgs, 2)
1642 entry, err = n.loadEntry(2)
1643 require_NoError(t, err)
1644 require_Equal(t, entry.leader, nats0)
1645
1646 // We get one entry that has NO quorum (but we don't know that yet).
1647 n.processAppendEntry(aeNoQuorum, n.aesub)
1648 require_Equal(t, n.wal.State().Msgs, 3)
1649 entry, err = n.loadEntry(3)
1650 require_NoError(t, err)
1651 require_Equal(t, entry.leader, nats0)
1652
1653 // We've just had a leader election, and we missed one message from the previous leader.
1654 // We should truncate the last message.
1655 n.processAppendEntry(aeCatchupTrigger, n.aesub)
1656 require_Equal(t, n.wal.State().Msgs, 2)
1657 require_True(t, n.catchup == nil)
1658
1659 // We get a heartbeat that prompts us to catchup.
1660 n.processAppendEntry(aeHeartbeat2, n.aesub)
1661 require_Equal(t, n.wal.State().Msgs, 2)
1662 require_Equal(t, n.commit, 1) // Commit should not change, as we missed an item.
1663 require_True(t, n.catchup != nil)
1664 require_Equal(t, n.catchup.pterm, 1) // n.pterm
1665 require_Equal(t, n.catchup.pindex, 2) // n.pindex
1666
1667 // We now notice the leader indicated a different entry at the (no quorum) index, should save that.
1668 n.processAppendEntry(aeMissed, n.catchup.sub)
1669 require_Equal(t, n.wal.State().Msgs, 3)
1670 require_True(t, n.catchup != nil)
1671
1672 // We now get the entry that initially triggered us to catchup, it should be added.
1673 n.processAppendEntry(aeCatchupTrigger, n.catchup.sub)
1674 require_Equal(t, n.wal.State().Msgs, 4)
1675 require_True(t, n.catchup != nil)
1676 entry, err = n.loadEntry(4)
1677 require_NoError(t, err)
1678 require_Equal(t, entry.leader, nats1)
1679
1680 // Heartbeat, makes sure we commit (and reset catchup, as we're now up-to-date).
1681 n.processAppendEntry(aeHeartbeat3, n.aesub)
1682 require_Equal(t, n.commit, 4)
1683 require_True(t, n.catchup == nil)
1684 }
1685
1686 func TestNRGCatchupCanTruncateMultipleEntriesWithoutQuorum(t *testing.T) {
1687 n, cleanup := initSingleMemRaftNode(t)
1688 defer cleanup()
1689
1690 // Create a sample entry, the content doesn't matter, just that it's stored.
1691 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1692 entries := []*Entry{newEntry(EntryNormal, esm)}
1693
1694 nats0 := "S1Nunr6R" // "nats-0"
1695 nats1 := "yrzKKRBu" // "nats-1"
1696
1697 // Timeline, for first leader
1698 aeInitial := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
1699 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
1700 aeNoQuorum1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
1701 aeNoQuorum2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 2, entries: entries})
1702
1703 // Timeline, after leader change
1704 aeMissed1 := encode(t, &appendEntry{leader: nats1, term: 2, commit: 1, pterm: 1, pindex: 1, entries: entries})
1705 aeMissed2 := encode(t, &appendEntry{leader: nats1, term: 2, commit: 1, pterm: 2, pindex: 2, entries: entries})
1706 aeCatchupTrigger := encode(t, &appendEntry{leader: nats1, term: 2, commit: 1, pterm: 2, pindex: 3, entries: entries})
1707 aeHeartbeat2 := encode(t, &appendEntry{leader: nats1, term: 2, commit: 2, pterm: 2, pindex: 4, entries: nil})
1708 aeHeartbeat3 := encode(t, &appendEntry{leader: nats1, term: 2, commit: 4, pterm: 2, pindex: 4, entries: nil})
1709
1710 // Initial case is simple, just store the entry.
1711 n.processAppendEntry(aeInitial, n.aesub)
1712 require_Equal(t, n.wal.State().Msgs, 1)
1713 entry, err := n.loadEntry(1)
1714 require_NoError(t, err)
1715 require_Equal(t, entry.leader, nats0)
1716
1717 // Heartbeat, makes sure commit moves up.
1718 n.processAppendEntry(aeHeartbeat, n.aesub)
1719 require_Equal(t, n.commit, 1)
1720
1721 // We get one entry that has NO quorum (but we don't know that yet).
1722 n.processAppendEntry(aeNoQuorum1, n.aesub)
1723 require_Equal(t, n.wal.State().Msgs, 2)
1724 entry, err = n.loadEntry(2)
1725 require_NoError(t, err)
1726 require_Equal(t, entry.leader, nats0)
1727
1728 // We get another entry that has NO quorum (but we don't know that yet).
1729 n.processAppendEntry(aeNoQuorum2, n.aesub)
1730 require_Equal(t, n.wal.State().Msgs, 3)
1731 entry, err = n.loadEntry(3)
1732 require_NoError(t, err)
1733 require_Equal(t, entry.leader, nats0)
1734
1735 // We've just had a leader election, and we missed messages from the previous leader.
1736 // We should truncate the last message.
1737 n.processAppendEntry(aeCatchupTrigger, n.aesub)
1738 require_Equal(t, n.wal.State().Msgs, 2)
1739 require_True(t, n.catchup == nil)
1740
1741 // We get a heartbeat that prompts us to catchup.
1742 n.processAppendEntry(aeHeartbeat2, n.aesub)
1743 require_Equal(t, n.wal.State().Msgs, 2)
1744 require_Equal(t, n.commit, 1) // Commit should not change, as we missed an item.
1745 require_True(t, n.catchup != nil)
1746 require_Equal(t, n.catchup.pterm, 1) // n.pterm
1747 require_Equal(t, n.catchup.pindex, 2) // n.pindex
1748
1749 // We now notice the leader indicated a different entry at the (no quorum) index. We should truncate again.
1750 n.processAppendEntry(aeMissed2, n.catchup.sub)
1751 require_Equal(t, n.wal.State().Msgs, 1)
1752 require_True(t, n.catchup == nil)
1753
1754 // We get a heartbeat that prompts us to catchup.
1755 n.processAppendEntry(aeHeartbeat2, n.aesub)
1756 require_Equal(t, n.wal.State().Msgs, 1)
1757 require_Equal(t, n.commit, 1) // Commit should not change, as we missed an item.
1758 require_True(t, n.catchup != nil)
1759 require_Equal(t, n.catchup.pterm, 1) // n.pterm
1760 require_Equal(t, n.catchup.pindex, 1) // n.pindex
1761
1762 // We now get caught up with the missed messages.
1763 n.processAppendEntry(aeMissed1, n.catchup.sub)
1764 require_Equal(t, n.wal.State().Msgs, 2)
1765 require_True(t, n.catchup != nil)
1766
1767 n.processAppendEntry(aeMissed2, n.catchup.sub)
1768 require_Equal(t, n.wal.State().Msgs, 3)
1769 require_True(t, n.catchup != nil)
1770
1771 // We now get the entry that initially triggered us to catchup, it should be added.
1772 n.processAppendEntry(aeCatchupTrigger, n.catchup.sub)
1773 require_Equal(t, n.wal.State().Msgs, 4)
1774 require_True(t, n.catchup != nil)
1775 entry, err = n.loadEntry(4)
1776 require_NoError(t, err)
1777 require_Equal(t, entry.leader, nats1)
1778
1779 // Heartbeat, makes sure we commit (and reset catchup, as we're now up-to-date).
1780 n.processAppendEntry(aeHeartbeat3, n.aesub)
1781 require_Equal(t, n.commit, 4)
1782 require_True(t, n.catchup == nil)
1783 }
1784
1785 func TestNRGCatchupDoesNotTruncateCommittedEntriesDuringRedelivery(t *testing.T) {
1786 n, cleanup := initSingleMemRaftNode(t)
1787 defer cleanup()
1788
1789 // Create a sample entry, the content doesn't matter, just that it's stored.
1790 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1791 entries := []*Entry{newEntry(EntryNormal, esm)}
1792
1793 nats0 := "S1Nunr6R" // "nats-0"
1794
1795 // Timeline.
1796 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
1797 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
1798 aeHeartbeat1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: nil})
1799 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 2, entries: entries})
1800 aeHeartbeat2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 3, pterm: 1, pindex: 3, entries: nil})
1801
1802 // Initial case is simple, just store the entry.
1803 n.processAppendEntry(aeMsg1, n.aesub)
1804 require_Equal(t, n.wal.State().Msgs, 1)
1805 entry, err := n.loadEntry(1)
1806 require_NoError(t, err)
1807 require_Equal(t, entry.leader, nats0)
1808
1809 // Deliver a message.
1810 n.processAppendEntry(aeMsg2, n.aesub)
1811 require_Equal(t, n.wal.State().Msgs, 2)
1812 entry, err = n.loadEntry(2)
1813 require_NoError(t, err)
1814 require_Equal(t, entry.leader, nats0)
1815
1816 // Heartbeat, makes sure commit moves up.
1817 n.processAppendEntry(aeHeartbeat1, n.aesub)
1818 require_Equal(t, n.commit, 2)
1819
1820 // Deliver another message.
1821 n.processAppendEntry(aeMsg3, n.aesub)
1822 require_Equal(t, n.wal.State().Msgs, 3)
1823 entry, err = n.loadEntry(3)
1824 require_NoError(t, err)
1825 require_Equal(t, entry.leader, nats0)
1826
1827 // Simulate receiving an old entry as a redelivery. We should not truncate as that lowers our commit.
1828 n.processAppendEntry(aeMsg1, n.aesub)
1829 require_Equal(t, n.commit, 2)
1830
1831 // Heartbeat, makes sure we commit.
1832 n.processAppendEntry(aeHeartbeat2, n.aesub)
1833 require_Equal(t, n.commit, 3)
1834 }
1835
1836 func TestNRGCatchupFromNewLeaderWithIncorrectPterm(t *testing.T) {
1837 n, cleanup := initSingleMemRaftNode(t)
1838 defer cleanup()
1839
1840 // Create a sample entry, the content doesn't matter, just that it's stored.
1841 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1842 entries := []*Entry{newEntry(EntryNormal, esm)}
1843
1844 nats0 := "S1Nunr6R" // "nats-0"
1845
1846 // Timeline.
1847 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 0, entries: entries})
1848 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
1849
1850 // Heartbeat, triggers catchup.
1851 n.processAppendEntry(aeHeartbeat, n.aesub)
1852 require_Equal(t, n.commit, 0) // Commit should not change, as we missed an item.
1853 require_True(t, n.catchup != nil)
1854 require_Equal(t, n.catchup.pterm, 0) // n.pterm
1855 require_Equal(t, n.catchup.pindex, 0) // n.pindex
1856
1857 // First catchup message has the incorrect pterm, stop catchup and re-trigger later with the correct pterm.
1858 n.processAppendEntry(aeMsg, n.catchup.sub)
1859 require_True(t, n.catchup == nil)
1860 require_Equal(t, n.pterm, 1)
1861 require_Equal(t, n.pindex, 0)
1862
1863 // Heartbeat, triggers catchup.
1864 n.processAppendEntry(aeHeartbeat, n.aesub)
1865 require_Equal(t, n.commit, 0) // Commit should not change, as we missed an item.
1866 require_True(t, n.catchup != nil)
1867 require_Equal(t, n.catchup.pterm, 1) // n.pterm
1868 require_Equal(t, n.catchup.pindex, 0) // n.pindex
1869
1870 // Now we get the message again and can continue to store it.
1871 n.processAppendEntry(aeMsg, n.catchup.sub)
1872 require_Equal(t, n.wal.State().Msgs, 1)
1873 entry, err := n.loadEntry(1)
1874 require_NoError(t, err)
1875 require_Equal(t, entry.leader, nats0)
1876
1877 // Now heartbeat is able to commit the entry.
1878 n.processAppendEntry(aeHeartbeat, n.aesub)
1879 require_Equal(t, n.commit, 1)
1880 }
1881
1882 func TestNRGDontRemoveSnapshotIfTruncateToApplied(t *testing.T) {
1883 n, cleanup := initSingleMemRaftNode(t)
1884 defer cleanup()
1885
1886 // Create a sample entry, the content doesn't matter, just that it's stored.
1887 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1888 entries := []*Entry{newEntry(EntryNormal, esm)}
1889
1890 nats0 := "S1Nunr6R" // "nats-0"
1891
1892 // Timeline.
1893 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
1894 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
1895
1896 // Initial case is simple, just store the entry.
1897 n.processAppendEntry(aeMsg, n.aesub)
1898 require_Equal(t, n.wal.State().Msgs, 1)
1899 entry, err := n.loadEntry(1)
1900 require_NoError(t, err)
1901 require_Equal(t, entry.leader, nats0)
1902
1903 // Heartbeat, makes sure commit moves up.
1904 n.processAppendEntry(aeHeartbeat, n.aesub)
1905 require_Equal(t, n.commit, 1)
1906 require_Equal(t, n.pterm, 1)
1907
1908 // Simulate upper layer calling down to apply.
1909 n.Applied(1)
1910
1911 // Install snapshot and check it exists.
1912 err = n.InstallSnapshot(nil, false)
1913 require_NoError(t, err)
1914
1915 snapshots := path.Join(n.sd, snapshotsDir)
1916 files, err := os.ReadDir(snapshots)
1917 require_NoError(t, err)
1918 require_Equal(t, len(files), 1)
1919
1920 // Truncate and check snapshot is kept.
1921 n.truncateWAL(n.pterm, n.applied)
1922
1923 files, err = os.ReadDir(snapshots)
1924 require_NoError(t, err)
1925 require_Equal(t, len(files), 1)
1926 }
1927
1928 func TestNRGSnapshotAndTruncateToApplied(t *testing.T) {
1929 n, cleanup := initSingleMemRaftNode(t)
1930 defer cleanup()
1931
1932 // Create a sample entry, the content doesn't matter, just that it's stored.
1933 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
1934 entries := []*Entry{newEntry(EntryNormal, esm)}
1935
1936 nats1 := "yrzKKRBu" // "nats-1"
1937 nats0 := "S1Nunr6R" // "nats-0"
1938
1939 n.Lock()
1940 n.addPeer(nats1)
1941 n.Unlock()
1942
1943 // Timeline, other leader
1944 aeMsg1 := encode(t, &appendEntry{leader: nats1, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
1945 aeMsg2 := encode(t, &appendEntry{leader: nats1, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
1946
1947 // Timeline, we temporarily became leader
1948 aeHeartbeat1 := encode(t, &appendEntry{leader: nats0, term: 2, commit: 3, pterm: 1, pindex: 3, entries: nil})
1949 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 2, commit: 3, pterm: 1, pindex: 3, entries: entries})
1950
1951 // Timeline, old leader is back.
1952 aeHeartbeat2 := encode(t, &appendEntry{leader: nats1, term: 3, commit: 3, pterm: 1, pindex: 3, entries: nil})
1953
1954 // Simply receive first message.
1955 n.processAppendEntry(aeMsg1, n.aesub)
1956 require_Equal(t, n.commit, 0)
1957 require_Equal(t, n.wal.State().Msgs, 1)
1958 entry, err := n.loadEntry(1)
1959 require_NoError(t, err)
1960 require_Equal(t, entry.leader, nats1)
1961
1962 // Receive second message, which commits the first message.
1963 n.processAppendEntry(aeMsg2, n.aesub)
1964 require_Equal(t, n.commit, 1)
1965 require_Equal(t, n.wal.State().Msgs, 2)
1966 entry, err = n.loadEntry(2)
1967 require_NoError(t, err)
1968 require_Equal(t, entry.leader, nats1)
1969
1970 // Simulate upper layer calling down to apply.
1971 n.Applied(1)
1972
1973 // Send heartbeat, which commits the second message.
1974 n.switchToLeader()
1975 n.term = aeHeartbeat1.term
1976 n.processAppendEntryResponse(&appendEntryResponse{
1977 term: aeHeartbeat1.term,
1978 index: aeHeartbeat1.pindex,
1979 peer: nats1,
1980 reply: _EMPTY_,
1981 success: true,
1982 })
1983 require_Equal(t, n.commit, 3)
1984
1985 // Simulate upper layer calling down to apply.
1986 n.Applied(3)
1987
1988 // Install snapshot and check it exists.
1989 err = n.InstallSnapshot(nil, false)
1990 require_NoError(t, err)
1991
1992 snapshots := path.Join(n.sd, snapshotsDir)
1993 files, err := os.ReadDir(snapshots)
1994 require_NoError(t, err)
1995 require_Equal(t, len(files), 1)
1996 require_Equal(t, n.wal.State().Msgs, 0)
1997
1998 // Store a third message, it stays uncommitted.
1999 require_NoError(t, n.storeToWAL(aeMsg3))
2000 require_Equal(t, n.commit, 3)
2001 require_Equal(t, n.wal.State().Msgs, 1)
2002 entry, err = n.loadEntry(4)
2003 require_NoError(t, err)
2004 require_Equal(t, entry.leader, nats0)
2005
2006 // Receive heartbeat from new leader, should not lose commits.
2007 n.stepdown(noLeader)
2008 n.processAppendEntry(aeHeartbeat2, n.aesub)
2009 require_Equal(t, n.wal.State().Msgs, 0)
2010 require_Equal(t, n.commit, 3)
2011 require_Equal(t, n.applied, 3)
2012 }
2013
2014 func TestNRGIgnoreDoubleSnapshot(t *testing.T) {
2015 n, cleanup := initSingleMemRaftNode(t)
2016 defer cleanup()
2017
2018 // Create a sample entry, the content doesn't matter, just that it's stored.
2019 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2020 entries := []*Entry{newEntry(EntryNormal, esm)}
2021
2022 nats0 := "S1Nunr6R" // "nats-0"
2023
2024 // Timeline
2025 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2026 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
2027 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 2, commit: 1, pterm: 1, pindex: 1, entries: entries})
2028
2029 // Simply receive first message.
2030 n.processAppendEntry(aeMsg1, n.aesub)
2031 require_Equal(t, n.pindex, 1)
2032 require_Equal(t, n.commit, 0)
2033
2034 // Heartbeat moves commit up.
2035 n.processAppendEntry(aeHeartbeat, n.aesub)
2036 require_Equal(t, n.commit, 1)
2037
2038 // Manually call back down to applied.
2039 n.Applied(1)
2040
2041 // Second message just for upping the pterm.
2042 n.processAppendEntry(aeMsg2, n.aesub)
2043 require_Equal(t, n.pindex, 2)
2044 require_Equal(t, n.commit, 1)
2045 require_Equal(t, n.pterm, 2)
2046 require_Equal(t, n.term, 2)
2047
2048 // Snapshot, and confirm state.
2049 err := n.InstallSnapshot(nil, false)
2050 require_NoError(t, err)
2051 snap, err := n.loadLastSnapshot()
2052 require_NoError(t, err)
2053 require_Equal(t, snap.lastTerm, 1)
2054 require_Equal(t, snap.lastIndex, 1)
2055
2056 // Snapshot again, should not overwrite previous snapshot.
2057 err = n.InstallSnapshot(nil, false)
2058 require_Error(t, err, errNoSnapAvailable)
2059 snap, err = n.loadLastSnapshot()
2060 require_NoError(t, err)
2061 require_Equal(t, snap.lastTerm, 1)
2062 require_Equal(t, snap.lastIndex, 1)
2063 }
2064
2065 func TestNRGDontSwitchToCandidateWithInflightSnapshot(t *testing.T) {
2066 n, cleanup := initSingleMemRaftNode(t)
2067 defer cleanup()
2068
2069 // Create a sample snapshot entry, the content doesn't matter.
2070 snapshotEntries := []*Entry{
2071 newEntry(EntrySnapshot, nil),
2072 newEntry(EntryPeerState, encodePeerState(&peerState{n.peerNames(), n.csz, n.extSt})),
2073 }
2074
2075 nats0 := "S1Nunr6R" // "nats-0"
2076
2077 // Timeline.
2078 aeTriggerCatchup := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
2079 aeCatchupSnapshot := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: snapshotEntries})
2080
2081 // Switch follower into catchup.
2082 n.processAppendEntry(aeTriggerCatchup, n.aesub)
2083 require_True(t, n.catchup != nil)
2084 require_Equal(t, n.catchup.pterm, 0) // n.pterm
2085 require_Equal(t, n.catchup.pindex, 0) // n.pindex
2086
2087 // Follower receives a snapshot, marking a snapshot as inflight as the apply queue is async.
2088 n.processAppendEntry(aeCatchupSnapshot, n.catchup.sub)
2089 require_Equal(t, n.pindex, 1)
2090 require_Equal(t, n.commit, 1)
2091
2092 // Try to switch to candidate, it should be blocked since the snapshot is not processed yet.
2093 n.switchToCandidate()
2094 require_Equal(t, n.State(), Follower)
2095
2096 // Simulate snapshot being processed by the upper layer.
2097 n.Applied(1)
2098
2099 // Retry becoming candidate, snapshot is processed so can now do so.
2100 n.switchToCandidate()
2101 require_Equal(t, n.State(), Candidate)
2102 }
2103
2104 func TestNRGDontSwitchToCandidateWithMultipleInflightSnapshots(t *testing.T) {
2105 n, cleanup := initSingleMemRaftNode(t)
2106 defer cleanup()
2107
2108 // Create a sample snapshot entry, the content doesn't matter.
2109 snapshotEntries := []*Entry{
2110 newEntry(EntrySnapshot, nil),
2111 newEntry(EntryPeerState, encodePeerState(&peerState{n.peerNames(), n.csz, n.extSt})),
2112 }
2113
2114 nats0 := "S1Nunr6R" // "nats-0"
2115
2116 // Timeline.
2117 aeSnapshot1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: snapshotEntries})
2118 aeSnapshot2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: snapshotEntries})
2119 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: nil})
2120
2121 // Simulate snapshots being sent to us.
2122 n.processAppendEntry(aeSnapshot1, n.aesub)
2123 require_Equal(t, n.pindex, 1)
2124 require_Equal(t, n.commit, 0)
2125 require_Equal(t, n.applied, 0)
2126
2127 n.processAppendEntry(aeSnapshot2, n.aesub)
2128 require_Equal(t, n.pindex, 2)
2129 require_Equal(t, n.commit, 1)
2130 require_Equal(t, n.applied, 0)
2131
2132 n.processAppendEntry(aeHeartbeat, n.aesub)
2133 require_Equal(t, n.pindex, 2)
2134 require_Equal(t, n.commit, 2)
2135 require_Equal(t, n.applied, 0)
2136
2137 for i := uint64(1); i <= 2; i++ {
2138 // Try to switch to candidate, it should be blocked since the snapshot is not processed yet.
2139 n.switchToCandidate()
2140 require_Equal(t, n.State(), Follower)
2141
2142 // Simulate snapshot being processed by the upper layer.
2143 n.Applied(i)
2144 }
2145
2146 // Retry becoming candidate, all snapshots processed so can now do so.
2147 n.switchToCandidate()
2148 require_Equal(t, n.State(), Candidate)
2149 }
2150
2151 func TestNRGRecoverPindexPtermOnlyIfLogNotEmpty(t *testing.T) {
2152 c := createJetStreamClusterExplicit(t, "R3S", 3)
2153 defer c.shutdown()
2154
2155 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
2156 defer nc.Close()
2157
2158 rg := c.createRaftGroup("TEST", 3, newStateAdder)
2159 rg.waitOnLeader()
2160
2161 gn := rg[0].(*stateAdder)
2162 rn := rg[0].node().(*raft)
2163
2164 // Delete the msgs and snapshots, leaving the only remaining trace
2165 // of the term in the TAV file.
2166 store := filepath.Join(gn.cfg.Store)
2167 require_NoError(t, rn.wal.Truncate(0))
2168 require_NoError(t, os.RemoveAll(filepath.Join(store, "msgs")))
2169 require_NoError(t, os.RemoveAll(filepath.Join(store, "snapshots")))
2170
2171 for _, gn := range rg {
2172 gn.stop()
2173 }
2174 rg[0].restart()
2175 rn = rg[0].node().(*raft)
2176
2177 // Both should be zero as, without any snapshots or log entries,
2178 // the log is considered empty and therefore we account as such.
2179 require_Equal(t, rn.pterm, 0)
2180 require_Equal(t, rn.pindex, 0)
2181 }
2182
2183 func TestNRGCancelCatchupWhenDetectingHigherTermDuringVoteRequest(t *testing.T) {
2184 n, cleanup := initSingleMemRaftNode(t)
2185 defer cleanup()
2186
2187 // Create a sample entry, the content doesn't matter, just that it's stored.
2188 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2189 entries := []*Entry{newEntry(EntryNormal, esm)}
2190
2191 nats0 := "S1Nunr6R" // "nats-0"
2192
2193 // Timeline.
2194 aeCatchupTrigger := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
2195 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2196
2197 // Truncate to simulate we missed one message and need to catchup.
2198 n.processAppendEntry(aeCatchupTrigger, n.aesub)
2199 require_True(t, n.catchup != nil)
2200 require_Equal(t, n.catchup.pterm, 0) // n.pterm
2201 require_Equal(t, n.catchup.pindex, 0) // n.pindex
2202
2203 // Process first message as part of the catchup.
2204 catchupSub := n.catchup.sub
2205 n.processAppendEntry(aeMsg1, catchupSub)
2206 require_True(t, n.catchup != nil)
2207
2208 // Receiving a vote request should cancel our catchup.
2209 // Otherwise, we could receive catchup messages after this that provides the previous leader with quorum.
2210 // If the new leader doesn't have these entries, the previous leader would desync since it would commit them.
2211 err := n.processVoteRequest(&voteRequest{2, 1, 1, nats0, "reply"})
2212 require_NoError(t, err)
2213 require_True(t, n.catchup == nil)
2214 }
2215
2216 func TestNRGMultipleStopsDontPanic(t *testing.T) {
2217 n, cleanup := initSingleMemRaftNode(t)
2218 defer cleanup()
2219
2220 defer func() {
2221 p := recover()
2222 require_True(t, p == nil)
2223 }()
2224
2225 for i := 0; i < 10; i++ {
2226 n.Stop()
2227 }
2228 }
2229
2230 func TestNRGTruncateDownToCommitted(t *testing.T) {
2231 n, cleanup := initSingleMemRaftNode(t)
2232 defer cleanup()
2233
2234 // Create a sample entry, the content doesn't matter, just that it's stored.
2235 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2236 entries := []*Entry{newEntry(EntryNormal, esm)}
2237
2238 nats0 := "S1Nunr6R" // "nats-0"
2239 nats1 := "yrzKKRBu" // "nats-1"
2240
2241 // Timeline, we are leader
2242 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2243 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
2244
2245 // Timeline, after leader change
2246 aeMsg3 := encode(t, &appendEntry{leader: nats1, term: 2, commit: 1, pterm: 1, pindex: 1, entries: entries})
2247 aeHeartbeat := encode(t, &appendEntry{leader: nats1, term: 2, commit: 2, pterm: 2, pindex: 2, entries: nil})
2248
2249 // Simply receive first message.
2250 n.processAppendEntry(aeMsg1, n.aesub)
2251 require_Equal(t, n.commit, 0)
2252 require_Equal(t, n.wal.State().Msgs, 1)
2253 entry, err := n.loadEntry(1)
2254 require_NoError(t, err)
2255 require_Equal(t, entry.leader, nats0)
2256
2257 // Receive second message, which commits the first message.
2258 n.processAppendEntry(aeMsg2, n.aesub)
2259 require_Equal(t, n.commit, 1)
2260 require_Equal(t, n.wal.State().Msgs, 2)
2261 entry, err = n.loadEntry(2)
2262 require_NoError(t, err)
2263 require_Equal(t, entry.leader, nats0)
2264
2265 // We receive an entry from another leader, should truncate down to commit / remove the second message.
2266 // After doing so, we should also be able to immediately store the message after.
2267 n.processAppendEntry(aeMsg3, n.aesub)
2268 require_Equal(t, n.commit, 1)
2269 require_Equal(t, n.wal.State().Msgs, 2)
2270 entry, err = n.loadEntry(2)
2271 require_NoError(t, err)
2272 require_Equal(t, entry.leader, nats1)
2273
2274 // Heartbeat moves commit up.
2275 n.processAppendEntry(aeHeartbeat, n.aesub)
2276 require_Equal(t, n.commit, 2)
2277 }
2278
2279 type mockWALTruncateAlwaysFails struct {
2280 WAL
2281 }
2282
2283 func (m mockWALTruncateAlwaysFails) Truncate(seq uint64) error {
2284 return errors.New("test: truncate always fails")
2285 }
2286
2287 func TestNRGTruncateDownToCommittedWhenTruncateFails(t *testing.T) {
2288 n, cleanup := initSingleMemRaftNode(t)
2289 defer cleanup()
2290
2291 n.Lock()
2292 n.wal = mockWALTruncateAlwaysFails{n.wal}
2293 n.Unlock()
2294
2295 // Create a sample entry, the content doesn't matter, just that it's stored.
2296 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2297 entries := []*Entry{newEntry(EntryNormal, esm)}
2298
2299 nats0 := "S1Nunr6R" // "nats-0"
2300 nats1 := "yrzKKRBu" // "nats-1"
2301
2302 // Timeline, we are leader
2303 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2304 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
2305
2306 // Timeline, after leader change
2307 aeMsg3 := encode(t, &appendEntry{leader: nats1, term: 2, commit: 1, pterm: 1, pindex: 1, entries: entries})
2308
2309 // Simply receive first message.
2310 n.processAppendEntry(aeMsg1, n.aesub)
2311 require_Equal(t, n.commit, 0)
2312 require_Equal(t, n.wal.State().Msgs, 1)
2313 entry, err := n.loadEntry(1)
2314 require_NoError(t, err)
2315 require_Equal(t, entry.leader, nats0)
2316
2317 // Receive second message, which commits the first message.
2318 n.processAppendEntry(aeMsg2, n.aesub)
2319 require_Equal(t, n.commit, 1)
2320 require_Equal(t, n.wal.State().Msgs, 2)
2321 entry, err = n.loadEntry(2)
2322 require_NoError(t, err)
2323 require_Equal(t, entry.leader, nats0)
2324
2325 // We receive an entry from another leader, should truncate down to commit / remove the second message.
2326 // But, truncation fails so should register that and not change pindex/pterm.
2327 bindex, bterm := n.pindex, n.pterm
2328 n.processAppendEntry(aeMsg3, n.aesub)
2329 require_Error(t, n.werr, errors.New("test: truncate always fails"))
2330 require_Equal(t, bindex, n.pindex)
2331 require_Equal(t, bterm, n.pterm)
2332 }
2333
2334 func TestNRGForwardProposalResponse(t *testing.T) {
2335 c := createJetStreamClusterExplicit(t, "R3S", 3)
2336 defer c.shutdown()
2337
2338 nc, _ := jsClientConnect(t, c.leader(), nats.UserInfo("admin", "s3cr3t!"))
2339 defer nc.Close()
2340
2341 rg := c.createRaftGroup("TEST", 3, newStateAdder)
2342 rg.waitOnLeader()
2343
2344 n := rg.nonLeader().node().(*raft)
2345 psubj := n.psubj
2346
2347 data := make([]byte, binary.MaxVarintLen64)
2348 dn := binary.PutVarint(data, int64(123))
2349
2350 _, err := nc.Request(psubj, data[:dn], time.Second*5)
2351 require_NoError(t, err)
2352
2353 rg.waitOnTotal(t, 123)
2354 }
2355
2356 func TestNRGMemoryWALEmptiesSnapshotsDir(t *testing.T) {
2357 n, c := initSingleMemRaftNodeWithCluster(t)
2358 defer c.shutdown()
2359
2360 // Create a sample entry, the content doesn't matter, just that it's stored.
2361 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2362 entries := []*Entry{newEntry(EntryNormal, esm)}
2363
2364 nats0 := "S1Nunr6R" // "nats-0"
2365
2366 // Timeline
2367 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2368 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
2369
2370 // Simply receive first message.
2371 n.processAppendEntry(aeMsg, n.aesub)
2372 require_Equal(t, n.pindex, 1)
2373 require_Equal(t, n.commit, 0)
2374
2375 // Heartbeat moves commit up.
2376 n.processAppendEntry(aeHeartbeat, n.aesub)
2377 require_Equal(t, n.commit, 1)
2378
2379 // Manually call back down to applied, and then snapshot.
2380 n.Applied(1)
2381 err := n.InstallSnapshot(nil, false)
2382 require_NoError(t, err)
2383
2384 // Stop current node and restart it.
2385 n.Stop()
2386 n.WaitForStop()
2387
2388 s := c.servers[0]
2389 ms, err := newMemStore(&StreamConfig{Name: "TEST", Storage: MemoryStorage})
2390 require_NoError(t, err)
2391 cfg := &RaftConfig{Name: "TEST", Store: n.sd, Log: ms}
2392 n, err = s.initRaftNode(globalAccountName, cfg, pprofLabels{})
2393 require_NoError(t, err)
2394
2395 // Since the WAL is in-memory, the snapshots dir should've been emptied upon restart.
2396 files, err := os.ReadDir(filepath.Join(n.sd, snapshotsDir))
2397 require_NoError(t, err)
2398 require_Len(t, len(files), 0)
2399 }
2400
2401 func TestNRGHealthCheckWaitForCatchup(t *testing.T) {
2402 n, cleanup := initSingleMemRaftNode(t)
2403 defer cleanup()
2404
2405 // Create a sample entry, the content doesn't matter, just that it's stored.
2406 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2407 entries := []*Entry{newEntry(EntryNormal, esm)}
2408
2409 nats0 := "S1Nunr6R" // "nats-0"
2410
2411 n.Lock()
2412 n.addPeer(nats0)
2413 n.Unlock()
2414
2415 // Timeline
2416 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2417 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
2418 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: entries})
2419 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 3, pterm: 1, pindex: 3, entries: nil})
2420
2421 // Switch follower into catchup.
2422 n.processAppendEntry(aeHeartbeat, n.aesub)
2423 require_True(t, n.catchup != nil)
2424 require_Equal(t, n.catchup.pterm, 0) // n.pterm
2425 require_Equal(t, n.catchup.pindex, 0) // n.pindex
2426 require_Equal(t, n.catchup.cterm, aeHeartbeat.term)
2427 require_Equal(t, n.catchup.cindex, aeHeartbeat.pindex)
2428
2429 // Catchup first message.
2430 n.processAppendEntry(aeMsg1, n.catchup.sub)
2431 require_Equal(t, n.pindex, 1)
2432 require_False(t, n.Healthy())
2433
2434 // Catchup second message.
2435 n.processAppendEntry(aeMsg2, n.catchup.sub)
2436 require_Equal(t, n.pindex, 2)
2437 require_Equal(t, n.commit, 1)
2438 require_False(t, n.Healthy())
2439
2440 // If we apply the entry sooner than we receive the next catchup message,
2441 // should not mark as healthy since we're still in catchup.
2442 n.Applied(1)
2443 require_False(t, n.Healthy())
2444
2445 // Catchup third message.
2446 n.processAppendEntry(aeMsg3, n.catchup.sub)
2447 require_Equal(t, n.pindex, 3)
2448 require_Equal(t, n.commit, 2)
2449 n.Applied(2)
2450 require_False(t, n.Healthy())
2451
2452 // Heartbeat stops catchup.
2453 n.processAppendEntry(aeHeartbeat, n.aesub)
2454 require_True(t, n.catchup == nil)
2455 require_Equal(t, n.pindex, 3)
2456 require_Equal(t, n.commit, 3)
2457 require_False(t, n.Healthy())
2458
2459 // Still need to wait for the last entry to be applied.
2460 n.Applied(3)
2461 require_True(t, n.Healthy())
2462 }
2463
2464 func TestNRGHealthCheckWaitForDoubleCatchup(t *testing.T) {
2465 n, cleanup := initSingleMemRaftNode(t)
2466 defer cleanup()
2467
2468 // Create a sample entry, the content doesn't matter, just that it's stored.
2469 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2470 entries := []*Entry{newEntry(EntryNormal, esm)}
2471
2472 nats0 := "S1Nunr6R" // "nats-0"
2473
2474 n.Lock()
2475 n.addPeer(nats0)
2476 n.Unlock()
2477
2478 // Timeline
2479 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2480 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
2481 aeHeartbeat1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: nil})
2482 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: entries})
2483 aeHeartbeat2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 3, pterm: 1, pindex: 3, entries: nil})
2484
2485 // Switch follower into catchup.
2486 n.processAppendEntry(aeHeartbeat1, n.aesub)
2487 require_True(t, n.catchup != nil)
2488 require_Equal(t, n.catchup.pterm, 0) // n.pterm
2489 require_Equal(t, n.catchup.pindex, 0) // n.pindex
2490 require_Equal(t, n.catchup.cterm, aeHeartbeat1.term)
2491 require_Equal(t, n.catchup.cindex, aeHeartbeat1.pindex)
2492
2493 // Catchup first message.
2494 n.processAppendEntry(aeMsg1, n.catchup.sub)
2495 require_Equal(t, n.pindex, 1)
2496 require_False(t, n.Healthy())
2497
2498 // We miss this message, since we're catching up.
2499 n.processAppendEntry(aeMsg3, n.aesub)
2500 require_True(t, n.catchup != nil)
2501 require_Equal(t, n.pindex, 1)
2502 require_False(t, n.Healthy())
2503
2504 // We also miss the heartbeat, since we're catching up.
2505 n.processAppendEntry(aeHeartbeat2, n.aesub)
2506 require_True(t, n.catchup != nil)
2507 require_Equal(t, n.pindex, 1)
2508 require_False(t, n.Healthy())
2509
2510 // Catchup second message, this will stop catchup.
2511 n.processAppendEntry(aeMsg2, n.catchup.sub)
2512 require_Equal(t, n.pindex, 2)
2513 require_Equal(t, n.commit, 1)
2514 n.Applied(1)
2515 require_False(t, n.Healthy())
2516
2517 // We expect to still be in catchup, waiting for a heartbeat or new append entry to reset.
2518 require_True(t, n.catchup != nil)
2519 require_Equal(t, n.catchup.cterm, aeHeartbeat1.term)
2520 require_Equal(t, n.catchup.cindex, aeHeartbeat1.pindex)
2521
2522 // We now get a 'future' heartbeat, should restart catchup.
2523 n.processAppendEntry(aeHeartbeat2, n.aesub)
2524 require_True(t, n.catchup != nil)
2525 require_Equal(t, n.catchup.pterm, 1) // n.pterm
2526 require_Equal(t, n.catchup.pindex, 2) // n.pindex
2527 require_Equal(t, n.catchup.cterm, aeHeartbeat2.term)
2528 require_Equal(t, n.catchup.cindex, aeHeartbeat2.pindex)
2529 require_False(t, n.Healthy())
2530
2531 // Catchup third message.
2532 n.processAppendEntry(aeMsg3, n.catchup.sub)
2533 require_Equal(t, n.pindex, 3)
2534 require_Equal(t, n.commit, 2)
2535 n.Applied(2)
2536 require_False(t, n.Healthy())
2537
2538 // Heartbeat stops catchup.
2539 n.processAppendEntry(aeHeartbeat2, n.aesub)
2540 require_True(t, n.catchup == nil)
2541 require_Equal(t, n.pindex, 3)
2542 require_Equal(t, n.commit, 3)
2543 require_False(t, n.Healthy())
2544
2545 // Still need to wait for the last entry to be applied.
2546 n.Applied(3)
2547 require_True(t, n.Healthy())
2548 }
2549
2550 func TestNRGHealthCheckWaitForPendingCommitsWhenPaused(t *testing.T) {
2551 n, cleanup := initSingleMemRaftNode(t)
2552 defer cleanup()
2553
2554 // Create a sample entry, the content doesn't matter, just that it's stored.
2555 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2556 entries := []*Entry{newEntry(EntryNormal, esm)}
2557
2558 nats0 := "S1Nunr6R" // "nats-0"
2559
2560 n.Lock()
2561 n.addPeer(nats0)
2562 n.Unlock()
2563
2564 // Timeline
2565 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2566 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
2567 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: nil})
2568
2569 // Process first message.
2570 n.processAppendEntry(aeMsg1, n.aesub)
2571 require_Equal(t, n.pindex, 1)
2572 require_False(t, n.Healthy())
2573
2574 // Process second message, moves commit up.
2575 n.processAppendEntry(aeMsg2, n.aesub)
2576 require_Equal(t, n.pindex, 2)
2577 require_False(t, n.Healthy())
2578
2579 // We're healthy once we've applied the first message.
2580 n.Applied(1)
2581 require_True(t, n.Healthy())
2582
2583 // If we're paused we still are healthy if there are no pending commits.
2584 err := n.PauseApply()
2585 require_NoError(t, err)
2586 require_True(t, n.Healthy())
2587
2588 // Heartbeat marks second message to be committed.
2589 n.processAppendEntry(aeHeartbeat, n.aesub)
2590 require_Equal(t, n.pindex, 2)
2591 require_False(t, n.Healthy())
2592
2593 // Resuming apply commits the message.
2594 n.ResumeApply()
2595 require_NoError(t, err)
2596 require_False(t, n.Healthy())
2597
2598 // But still waiting for it to be applied before marking healthy.
2599 n.Applied(2)
2600 require_True(t, n.Healthy())
2601 }
2602
2603 func TestNRGAppendEntryCanEstablishQuorumAfterLeaderChange(t *testing.T) {
2604 n, cleanup := initSingleMemRaftNode(t)
2605 defer cleanup()
2606
2607 // Create a sample entry, the content doesn't matter, just that it's stored.
2608 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2609 entries := []*Entry{newEntry(EntryNormal, esm)}
2610
2611 nats0 := "S1Nunr6R" // "nats-0"
2612
2613 n.Lock()
2614 n.addPeer(nats0)
2615 n.Unlock()
2616
2617 // Timeline
2618 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2619 aeHeartbeatResponse := &appendEntryResponse{term: 1, index: 2, peer: nats0, success: true}
2620
2621 // Process first message.
2622 n.processAppendEntry(aeMsg, n.aesub)
2623 require_Equal(t, n.pindex, 1)
2624 require_Equal(t, n.aflr, 0)
2625
2626 // Simulate becoming leader, and not knowing if the stored entry has quorum and can be committed.
2627 // Switching to leader should send a heartbeat.
2628 n.switchToLeader()
2629 require_Equal(t, n.aflr, 2)
2630 require_Equal(t, n.commit, 0)
2631
2632 // We simulate receiving the successful heartbeat response here. It should move the commit up.
2633 n.processAppendEntryResponse(aeHeartbeatResponse)
2634 require_Equal(t, n.commit, 2)
2635 require_Equal(t, n.aflr, 2)
2636
2637 // Once the entry is applied, it should reset the applied floor.
2638 n.Applied(2)
2639 require_Equal(t, n.aflr, 0)
2640 }
2641
2642 func TestNRGQuorumAccounting(t *testing.T) {
2643 n, cleanup := initSingleMemRaftNode(t)
2644 defer cleanup()
2645
2646 nats1 := "yrzKKRBu" // "nats-1"
2647 nats2 := "cnrtt3eg" // "nats-2"
2648
2649 n.Lock()
2650 n.addPeer(nats1)
2651 n.addPeer(nats2)
2652 n.Unlock()
2653
2654 // Timeline
2655 aeHeartbeat1Response := &appendEntryResponse{term: 1, index: 1, peer: nats1, success: true}
2656 aeHeartbeat2Response := &appendEntryResponse{term: 1, index: 1, peer: nats2, success: true}
2657
2658 // Adjust cluster size, so we need at least 2 responses from other servers to establish quorum.
2659 require_NoError(t, n.AdjustBootClusterSize(5))
2660 require_Equal(t, n.csz, 5)
2661 require_Equal(t, n.qn, 3)
2662
2663 // Switch this node to leader which sends an entry.
2664 n.switchToLeader()
2665 n.term = 1
2666 require_Equal(t, n.pindex, 1)
2667
2668 // The first response MUST NOT indicate quorum has been reached.
2669 n.processAppendEntryResponse(aeHeartbeat1Response)
2670 require_Equal(t, n.commit, 0)
2671
2672 // The second response means we have reached quorum and can move commit up.
2673 n.processAppendEntryResponse(aeHeartbeat2Response)
2674 require_Equal(t, n.commit, 1)
2675 }
2676
2677 func TestNRGRevalidateQuorumAfterLeaderChange(t *testing.T) {
2678 n, cleanup := initSingleMemRaftNode(t)
2679 defer cleanup()
2680
2681 nats1 := "yrzKKRBu" // "nats-1"
2682 nats2 := "cnrtt3eg" // "nats-2"
2683
2684 n.Lock()
2685 n.addPeer(nats1)
2686 n.addPeer(nats2)
2687 n.Unlock()
2688
2689 // Timeline
2690 aeHeartbeat1Response := &appendEntryResponse{term: 1, index: 1, peer: nats1, success: true}
2691 aeHeartbeat2Response := &appendEntryResponse{term: 6, index: 2, peer: nats2, success: true}
2692
2693 // Adjust cluster size, so we need at least 2 responses from other servers to establish quorum.
2694 require_NoError(t, n.AdjustBootClusterSize(5))
2695 require_Equal(t, n.csz, 5)
2696 require_Equal(t, n.qn, 3)
2697
2698 // Switch this node to leader which sends an entry.
2699 n.term++
2700 n.switchToLeader()
2701 require_Equal(t, n.term, 1)
2702 require_Equal(t, n.pindex, 1)
2703
2704 // We have one server that signals the message was stored. The leader will add 1 to the acks count.
2705 n.processAppendEntryResponse(aeHeartbeat1Response)
2706 require_Equal(t, n.commit, 0)
2707 require_Len(t, len(n.acks), 1)
2708
2709 // We stepdown now and don't know if we will have quorum on the first entry.
2710 n.stepdown(noLeader)
2711
2712 // Let's assume there are a bunch of leader elections now, data being added to the log, being truncated, etc.
2713 // We don't know what happened, maybe we were partitioned, but we can't know for sure if the first entry has quorum.
2714
2715 // We now become leader again.
2716 n.term = 6
2717 n.switchToLeader()
2718 require_Equal(t, n.term, 6)
2719
2720 // We now receive a successful response from another server saying they have stored it.
2721 // Anything can have happened to the replica that said success before, we can't assume that's still valid.
2722 // So our commit must stay the same and we restart counting for quorum.
2723 n.processAppendEntryResponse(aeHeartbeat2Response)
2724 require_Equal(t, n.commit, 0)
2725 require_Len(t, len(n.acks), 1)
2726 }
2727
2728 func TestNRGSignalLeadChangeFalseIfCampaignImmediately(t *testing.T) {
2729 tests := []struct {
2730 title string
2731 switchNode func(n *raft)
2732 }{
2733 {
2734 title: "Follower",
2735 },
2736 {
2737 title: "Candidate",
2738 switchNode: func(n *raft) {
2739 n.switchToCandidate()
2740 },
2741 },
2742 {
2743 title: "Leader",
2744 switchNode: func(n *raft) {
2745 n.switchToCandidate()
2746 n.switchToLeader()
2747 select {
2748 case <-n.LeadChangeC():
2749 t.Error("Expected no leadChange signal")
2750 default:
2751 // Expecting no signal yet.
2752 }
2753 },
2754 },
2755 }
2756 for _, test := range tests {
2757 t.Run(test.title, func(t *testing.T) {
2758 n, cleanup := initSingleMemRaftNode(t)
2759 defer cleanup()
2760
2761 // Create a sample entry, the content doesn't matter, just that it's stored.
2762 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2763 entries := []*Entry{newEntry(EntryNormal, esm)}
2764
2765 nats0 := "S1Nunr6R" // "nats-0"
2766 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
2767
2768 // Campaigning immediately signals we're the preferred leader.
2769 require_NoError(t, n.CampaignImmediately())
2770 if test.switchNode != nil {
2771 test.switchNode(n)
2772 }
2773
2774 n.processAppendEntry(aeMsg1, n.aesub)
2775
2776 select {
2777 case lc := <-n.LeadChangeC():
2778 require_False(t, lc.isLeader)
2779 default:
2780 t.Error("Expected leadChange signal")
2781 }
2782 require_Equal(t, n.State(), Follower)
2783 require_Equal(t, n.leader, nats0)
2784 require_Equal(t, n.term, 1)
2785 })
2786 }
2787 }
2788
2789 func TestNRGCatchupDontCountTowardQuorum(t *testing.T) {
2790 n, cleanup := initSingleMemRaftNode(t)
2791 defer cleanup()
2792
2793 // Create a sample entry, the content doesn't matter, just that it's stored.
2794 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2795 entries := []*Entry{newEntry(EntryNormal, esm)}
2796
2797 nats0 := "S1Nunr6R" // "nats-0"
2798
2799 aeReply := "$TEST"
2800 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
2801 require_NoError(t, err)
2802 defer nc.Close()
2803
2804 sub, err := nc.SubscribeSync(aeReply)
2805 require_NoError(t, err)
2806 defer sub.Drain()
2807 require_NoError(t, nc.Flush())
2808
2809 // Timeline
2810 aeMissedMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries, reply: aeReply})
2811 ae := appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries, reply: aeReply}
2812 aeCatchupTrigger := encode(t, &ae)
2813 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 2, entries: nil, reply: aeReply})
2814
2815 // Simulate we missed all messages up to this point.
2816 n.processAppendEntry(aeCatchupTrigger, n.aesub)
2817 require_True(t, n.catchup != nil)
2818 require_Equal(t, n.catchup.pterm, 0) // n.pterm
2819 require_Equal(t, n.catchup.pindex, 0) // n.pindex
2820 require_Equal(t, n.catchup.cterm, ae.pterm)
2821 require_Equal(t, n.catchup.cindex, ae.pindex)
2822
2823 // Should reply we require catchup.
2824 msg, err := sub.NextMsg(time.Second)
2825 require_NoError(t, err)
2826 ar := decodeAppendEntryResponse(msg.Data)
2827 require_Equal(t, ar.index, 0)
2828 require_False(t, ar.success)
2829 require_True(t, strings.HasPrefix(msg.Reply, "$NRG.CR"))
2830
2831 // Should NEVER respond to catchup messages.
2832 n.processAppendEntry(aeMissedMsg, n.catchup.sub)
2833 _, err = sub.NextMsg(time.Second)
2834 require_Error(t, err, nats.ErrTimeout)
2835
2836 n.processAppendEntry(aeCatchupTrigger, n.catchup.sub)
2837 _, err = sub.NextMsg(time.Second)
2838 require_Error(t, err, nats.ErrTimeout)
2839
2840 // Now we've received all messages, stop catchup, and respond success to new message.
2841 n.processAppendEntry(aeHeartbeat, n.aesub)
2842 msg, err = sub.NextMsg(time.Second)
2843 require_NoError(t, err)
2844 ar = decodeAppendEntryResponse(msg.Data)
2845 require_Equal(t, ar.index, aeHeartbeat.pindex)
2846 require_True(t, ar.success)
2847 require_Equal(t, msg.Reply, _EMPTY_)
2848 }
2849
2850 func TestNRGCatchupAcksProgressWhenGivenProgressInbox(t *testing.T) {
2851 n, cleanup := initSingleMemRaftNode(t)
2852 defer cleanup()
2853
2854 // Create a sample entry, the content doesn't matter, just that it's stored.
2855 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
2856 entries := []*Entry{newEntry(EntryNormal, esm)}
2857
2858 nats0 := "S1Nunr6R" // "nats-0"
2859
2860 aeReply := "$TEST"
2861 progressReply := fmt.Sprintf(raftCatchupProgressReply, "test")
2862
2863 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
2864 require_NoError(t, err)
2865 defer nc.Close()
2866
2867 sub, err := nc.SubscribeSync(aeReply)
2868 require_NoError(t, err)
2869 defer sub.Drain()
2870 psub, err := nc.SubscribeSync(progressReply)
2871 require_NoError(t, err)
2872 defer psub.Drain()
2873 require_NoError(t, nc.Flush())
2874
2875 // Timeline
2876 aeMissedMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries, reply: progressReply})
2877 ae := appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries, reply: aeReply}
2878 aeCatchupTrigger := encode(t, &ae)
2879
2880 // Simulate we missed all messages up to this point.
2881 n.processAppendEntry(aeCatchupTrigger, n.aesub)
2882 require_True(t, n.catchup != nil)
2883
2884 // Should reply we require catchup.
2885 msg, err := sub.NextMsg(time.Second)
2886 require_NoError(t, err)
2887 ar := decodeAppendEntryResponse(msg.Data)
2888 require_False(t, ar.success)
2889 require_True(t, strings.HasPrefix(msg.Reply, "$NRG.CR"))
2890
2891 // A catchup entry that carries a dedicated progress inbox MUST be acked, that
2892 // response is what lets the leader move its send window forward. Without it the
2893 // leader can only ever have one window in flight before it gives up and stalls.
2894 n.processAppendEntry(aeMissedMsg, n.catchup.sub)
2895 msg, err = psub.NextMsg(time.Second)
2896 require_NoError(t, err)
2897 ar = decodeAppendEntryResponse(msg.Data)
2898 require_Equal(t, ar.index, 1)
2899 require_True(t, ar.success)
2900
2901 // It must NOT also show up on the general append entry inbox, since that is the
2902 // path that feeds quorum.
2903 _, err = sub.NextMsg(250 * time.Millisecond)
2904 require_Error(t, err, nats.ErrTimeout)
2905 }
2906
2907 func TestNRGCatchupSendsProgressInboxAndRefillsWindow(t *testing.T) {
2908 n, cleanup := initSingleMemRaftNode(t)
2909 defer cleanup()
2910
2911 nats0 := "S1Nunr6R" // "nats-0"
2912 nats1 := "yrzKKRBu" // "nats-1"
2913
2914 n.Lock()
2915 n.addPeer(nats1)
2916 n.Unlock()
2917
2918 // Entries large enough that only a handful fit in the leader's 2MB send window,
2919 // so catching this log up must span several windows.
2920 const (
2921 entrySize = 512 * 1024
2922 numEntries = 12
2923 )
2924 entries := []*Entry{newEntry(EntryNormal, make([]byte, entrySize))}
2925
2926 // Fill our WAL, so we have something to catch a follower up on.
2927 for i := range numEntries {
2928 pterm := uint64(1)
2929 if i == 0 {
2930 pterm = 0
2931 }
2932 ae := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: pterm, pindex: uint64(i), entries: entries})
2933 n.processAppendEntry(ae, n.aesub)
2934 }
2935 require_Equal(t, n.pindex, numEntries)
2936
2937 catchupSubj := "$TEST.catchup"
2938 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
2939 require_NoError(t, err)
2940 defer nc.Close()
2941
2942 sub, err := nc.SubscribeSync(catchupSubj)
2943 require_NoError(t, err)
2944 defer sub.Drain()
2945 sub.SetPendingLimits(-1, -1)
2946 require_NoError(t, nc.Flush())
2947
2948 n.switchToLeader()
2949
2950 // Pretend we haven't heard from the follower in a while. It's the only other peer,
2951 // so as far as we're concerned right now we've lost quorum.
2952 n.Lock()
2953 n.lsut = time.Time{}
2954 n.peers[nats1].ts = time.Now().Add(-2 * lostQuorumInterval)
2955 n.Unlock()
2956 require_True(t, n.lostQuorum())
2957
2958 // Ask to be caught up from the very beginning.
2959 ar := newAppendEntryResponse(0, 0, nats1, false)
2960 ar.reply = catchupSubj
2961 n.catchupFollower(ar)
2962
2963 // Act as the follower. Every catchup entry is acknowledged on the reply subject
2964 // the leader handed us, which is what refills its send window.
2965 var received int
2966 for received < numEntries {
2967 msg, err := sub.NextMsg(time.Second)
2968 if err != nil {
2969 t.Fatalf("Only received %d of %d catchup entries before stalling: %v", received, numEntries, err)
2970 }
2971 // The leader must point catchup responses at a dedicated progress inbox, never
2972 // at its general append entry inbox, so they can't be counted towards quorum.
2973 require_True(t, strings.HasPrefix(msg.Reply, raftCatchupProgressPre))
2974
2975 cae, err := decodeAppendEntry(msg.Data, nil, msg.Reply)
2976 require_NoError(t, err)
2977 received++
2978
2979 par := newAppendEntryResponse(cae.term, cae.pindex+1, nats1, true)
2980 require_NoError(t, nc.Publish(msg.Reply, par.encode(nil)))
2981 require_NoError(t, nc.Flush())
2982 arPool.Put(par)
2983
2984 // These acks don't go through processAppendEntryResponse, but they must still
2985 // count as having heard from the peer. Otherwise, a catchup outlasting
2986 // lostQuorumInterval makes us step down, while the follower is responding to us.
2987 checkFor(t, time.Second, 10*time.Millisecond, func() error {
2988 if n.lostQuorum() {
2989 return errors.New("should not have lost quorum, peer is acking catchup progress")
2990 }
2991 return nil
2992 })
2993 }
2994 }
2995
2996 func TestNRGCatchupLargeEntriesProgressesAcrossWindows(t *testing.T) {
2997 c := createJetStreamClusterExplicit(t, "R3S", 3)
2998 defer c.shutdown()
2999
3000 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
3001 rg.waitOnLeader()
3002
3003 // The leader keeps at most maxOutstanding (2MB) of catchup entries in flight, so
3004 // entries this large mean a catchup spans many send windows. A window can only be
3005 // refilled once the follower reports progress on what it already received.
3006 const (
3007 entrySize = 512 * 1024
3008 numEntries = 64
3009 )
3010
3011 // Take a follower down so it misses everything that follows.
3012 follower := rg.nonLeader().(*stateAdder)
3013 follower.stop()
3014
3015 leader := rg.leader().(*stateAdder)
3016 for range numEntries {
3017 data := make([]byte, entrySize)
3018 binary.PutVarint(data, 1)
3019 leader.propose(data)
3020 }
3021 rg.waitOnTotal(t, numEntries)
3022
3023 // Bring it back with an empty log, it must now be caught up from scratch.
3024 follower.restart()
3025
3026 // Without working catchup flow control the leader pushes one 2MB window and then
3027 // stalls out for a couple of seconds before the follower re-requests, which for a
3028 // log this size takes the better part of a minute.
3029 checkFor(t, 2*time.Second, 100*time.Millisecond, func() error {
3030 var err error
3031 for _, sm := range rg {
3032 asm := sm.(*stateAdder)
3033 if total := asm.total(); total != numEntries {
3034 err = errors.Join(err, fmt.Errorf("Adder on %v has wrong total: %d vs %d",
3035 asm.server(), total, numEntries))
3036 }
3037 }
3038 return err
3039 })
3040 }
3041
3042 func TestNRGIgnoreTrackResponseWhenNotLeader(t *testing.T) {
3043 n, cleanup := initSingleMemRaftNode(t)
3044 defer cleanup()
3045
3046 nats1 := "yrzKKRBu" // "nats-1"
3047 n.Lock()
3048 n.addPeer(nats1)
3049 // Keep quorum at 2 so the initial leader NOOP does not auto-commit.
3050 n.lsut = time.Time{}
3051 n.Unlock()
3052
3053 // Switch this node to leader which sends an entry.
3054 n.term++
3055 n.switchToLeader()
3056 require_Equal(t, n.term, 1)
3057 require_Equal(t, n.pindex, 1)
3058 require_Equal(t, n.pterm, 1)
3059 require_Equal(t, n.commit, 0)
3060
3061 // Step down
3062 n.stepdown(noLeader)
3063 require_Equal(t, n.pindex, 1)
3064 require_Equal(t, n.pterm, 1)
3065 require_Equal(t, n.commit, 0)
3066
3067 // Normally would commit the entry, but since we're not leader anymore we should ignore it.
3068 n.trackResponse(&appendEntryResponse{1, 1, "peer", _EMPTY_, true})
3069 require_Equal(t, n.commit, 0)
3070 }
3071
3072 func TestNRGRejectNewAppendEntryFromPreviousLeader(t *testing.T) {
3073 n, cleanup := initSingleMemRaftNode(t)
3074 defer cleanup()
3075
3076 // Create a sample entry, the content doesn't matter, just that it's stored.
3077 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3078 entries := []*Entry{newEntry(EntryNormal, esm)}
3079
3080 nats0 := "S1Nunr6R" // "nats-0"
3081
3082 // Timeline
3083 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
3084 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
3085
3086 // Accept first message because it equals our term.
3087 n.term = 1
3088 n.processAppendEntry(aeMsg1, n.aesub)
3089 require_Equal(t, n.pterm, 1)
3090 require_Equal(t, n.pindex, 1)
3091
3092 // We are part of the successful vote for a new leader under a new term.
3093 require_NoError(t, n.processVoteRequest(&voteRequest{term: 5, lastTerm: 1, lastIndex: 2}))
3094
3095 // Must reject entry from a previous term.
3096 n.processAppendEntry(aeMsg2, n.aesub)
3097 require_Equal(t, n.pterm, 1)
3098 require_Equal(t, n.pindex, 1)
3099 }
3100
3101 func TestNRGRejectAppendEntryDuringCatchupFromPreviousLeader(t *testing.T) {
3102 test := func(t *testing.T, isCatchingUp, oldBehavior bool) {
3103 n, cleanup := initSingleMemRaftNode(t)
3104 defer cleanup()
3105
3106 // Create a sample entry, the content doesn't matter, just that it's stored.
3107 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3108 entries := []*Entry{newEntry(EntryNormal, esm)}
3109
3110 nats0 := "S1Nunr6R" // "nats-0"
3111
3112 // Timeline
3113 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
3114 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
3115
3116 // Accept first message because it equals our term.
3117 n.term = 1
3118 n.processAppendEntry(aeMsg2, n.aesub)
3119 require_True(t, n.catchup != nil)
3120 require_Equal(t, n.catchup.pterm, 0) // n.pterm
3121 require_Equal(t, n.catchup.pindex, 0) // n.pindex
3122 require_Equal(t, n.catchup.cterm, aeMsg2.pterm)
3123 require_Equal(t, n.catchup.cindex, aeMsg2.pindex)
3124
3125 // Under the new behavior the term of the leader that's doing the catchup is included.
3126 if !oldBehavior {
3127 aeMsg1.lterm = 1
3128 aeMsg2.lterm = 1
3129 }
3130
3131 // First catchup message is accepted.
3132 catchup := n.catchup
3133 n.processAppendEntry(aeMsg1, catchup.sub)
3134 require_Equal(t, n.pterm, 1)
3135 require_Equal(t, n.pindex, 1)
3136
3137 // We are part of the successful vote for a new leader under a new term.
3138 require_NoError(t, n.processVoteRequest(&voteRequest{term: 5, lastTerm: 1, lastIndex: 2}))
3139
3140 // Voting cancels catchup. For testing, revert that so we can test
3141 // what a catchup message after upping the term does.
3142 nsub := n.aesub
3143 if isCatchingUp {
3144 n.catchup = catchup
3145 nsub = catchup.sub
3146 }
3147
3148 // Now send the second catchup entry.
3149 n.processAppendEntry(aeMsg2, nsub)
3150 require_Equal(t, n.pterm, 1)
3151
3152 // Under the old behavior this entry is wrongly accepted.
3153 // A new server will also know to be backward-compatible if being caught up by an old server.
3154 if isCatchingUp && oldBehavior {
3155 require_Equal(t, n.pindex, 2)
3156 } else {
3157 // Under the new behavior the entry is correctly accepted.
3158 require_Equal(t, n.pindex, 1)
3159 }
3160 }
3161
3162 for _, isCatchingUp := range []bool{false, true} {
3163 for _, oldBehavior := range []bool{false, true} {
3164 title := "new-entry"
3165 if isCatchingUp {
3166 title = "catchup"
3167 }
3168 if oldBehavior {
3169 title += "-backward-compatible"
3170 }
3171 t.Run(title, func(t *testing.T) { test(t, isCatchingUp, oldBehavior) })
3172 }
3173 }
3174 }
3175
3176 func TestNRGDontRejectAppendEntryFromReplay(t *testing.T) {
3177 test := func(t *testing.T, restart bool) {
3178 c := createJetStreamClusterExplicit(t, "R3S", 3)
3179 defer c.shutdown()
3180
3181 rg := c.createRaftGroup("TEST", 3, newStateAdder)
3182 rg.waitOnLeader()
3183
3184 // Stop all servers except the leader.
3185 l := rg.leader().(*stateAdder)
3186 rs := rg.nonLeader()
3187 for _, sm := range rg {
3188 if sm != l {
3189 sm.stop()
3190 }
3191 }
3192
3193 // Propose a new entry to the leader and confirm it's stored in its log.
3194 pindex, _, _ := l.node().Progress()
3195 l.proposeDelta(10)
3196 checkFor(t, 2*time.Second, 200*time.Millisecond, func() error {
3197 if index, _, _ := l.node().Progress(); index == pindex {
3198 return errors.New("proposal not stored yet")
3199 }
3200 return nil
3201 })
3202
3203 // Optionally restart the leader, which will require replay of the entries in the log.
3204 if restart {
3205 l.stop()
3206 l.restart()
3207 }
3208
3209 // Shutdown server should be caught up.
3210 rs.restart()
3211
3212 // Wait for both online servers to have applied the delta.
3213 checkFor(t, 5*time.Second, 200*time.Millisecond, func() (err error) {
3214 for _, sm := range rg {
3215 if sm != l && sm != rs {
3216 break
3217 }
3218 if total := sm.(*stateAdder).total(); total != 10 {
3219 err = errors.Join(err, fmt.Errorf("expected 10 total, got: %d", total))
3220 }
3221 }
3222 return err
3223 })
3224 }
3225
3226 t.Run("no-restart", func(t *testing.T) { test(t, false) })
3227 t.Run("with-restart", func(t *testing.T) { test(t, true) })
3228 }
3229
3230 func TestNRGSimpleCatchup(t *testing.T) {
3231 test := func(t *testing.T, leaderChange bool) {
3232 c := createJetStreamClusterExplicit(t, "R3S", 3)
3233 defer c.shutdown()
3234
3235 rg := c.createRaftGroup("TEST", 3, newStateAdder)
3236 rg.waitOnLeader()
3237
3238 // Shutdown a single group, we'll start it later for catchup.
3239 nl := rg.nonLeader()
3240 nl.stop()
3241
3242 l := rg.leader().(*stateAdder)
3243 l.proposeDelta(10)
3244
3245 // Wait for remaining servers to have applied the delta.
3246 checkFor(t, 2*time.Second, 200*time.Millisecond, func() (err error) {
3247 for _, sm := range rg {
3248 total := sm.(*stateAdder).total()
3249 if sm == nl && total != 0 {
3250 err = errors.Join(err, errors.New("expected shutdown server to not get data"))
3251 } else if sm != nl && total != 10 {
3252 err = errors.Join(err, fmt.Errorf("expected 10 total, got: %d", total))
3253 }
3254 }
3255 return err
3256 })
3257
3258 if leaderChange {
3259 require_NoError(t, l.node().StepDown())
3260 }
3261
3262 // Shutdown server should be caught up.
3263 nl.restart()
3264 rg.waitOnTotal(t, 10)
3265 }
3266
3267 t.Run("same-leader", func(t *testing.T) { test(t, false) })
3268 t.Run("change-leader", func(t *testing.T) { test(t, true) })
3269 }
3270
3271 func TestNRGSnapshotCatchup(t *testing.T) {
3272 test := func(t *testing.T, restart bool) {
3273 c := createJetStreamClusterExplicit(t, "R3S", 3)
3274 defer c.shutdown()
3275
3276 rg := c.createRaftGroup("TEST", 3, newStateAdder)
3277 rg.waitOnLeader()
3278
3279 l := rg.leader().(*stateAdder)
3280 var s1 stateMachine
3281 var s2 stateMachine
3282 for _, sm := range rg {
3283 if sm == l {
3284 continue
3285 }
3286 if s1 == nil {
3287 s1 = sm
3288 } else {
3289 s2 = sm
3290 }
3291 }
3292
3293 // Stop one non-leader server.
3294 s1.stop()
3295
3296 // Wait for both online servers to have applied the delta.
3297 l.proposeDelta(10)
3298 checkFor(t, 5*time.Second, 200*time.Millisecond, func() (err error) {
3299 for _, sm := range rg {
3300 if sm == s1 {
3301 continue
3302 }
3303 if total := sm.(*stateAdder).total(); total != 10 {
3304 err = errors.Join(err, fmt.Errorf("expected 10 total, got: %d", total))
3305 }
3306 }
3307 return err
3308 })
3309
3310 // Shutdown last non-leader server.
3311 s2.stop()
3312
3313 // Snapshot so outdated server needs to catchup based on it.
3314 l.snapshot(t)
3315
3316 // Propose a new entry to the leader and confirm it's stored in its log.
3317 pindex, _, _ := l.node().Progress()
3318 l.proposeDelta(10)
3319 checkFor(t, 2*time.Second, 200*time.Millisecond, func() error {
3320 if index, _, _ := l.node().Progress(); index == pindex {
3321 return errors.New("proposal not stored yet")
3322 }
3323 return nil
3324 })
3325
3326 // Optionally restart the leader, which will require replay of the entries in the log.
3327 if restart {
3328 l.stop()
3329 l.restart()
3330 }
3331
3332 // Shutdown server should be caught up.
3333 s1.restart()
3334
3335 // Wait for both online servers to have applied the delta.
3336 checkFor(t, 5*time.Second, 200*time.Millisecond, func() (err error) {
3337 for _, sm := range rg {
3338 if sm == s2 {
3339 break
3340 }
3341 if total := sm.(*stateAdder).total(); total != 20 {
3342 err = errors.Join(err, fmt.Errorf("expected 20 total, got: %d", total))
3343 }
3344 }
3345 return err
3346 })
3347 }
3348
3349 t.Run("no-restart", func(t *testing.T) { test(t, false) })
3350 t.Run("with-restart", func(t *testing.T) { test(t, true) })
3351 }
3352
3353 func TestNRGSnapshotRecovery(t *testing.T) {
3354 n, cleanup := initSingleMemRaftNode(t)
3355 defer cleanup()
3356
3357 // Create a sample entry, the content doesn't matter, just that it's stored.
3358 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3359 entries := []*Entry{newEntry(EntryNormal, esm)}
3360
3361 nats0 := "S1Nunr6R" // "nats-0"
3362
3363 // Timeline
3364 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 0, pindex: 0, entries: entries})
3365
3366 // Store one entry.
3367 n.processAppendEntry(aeMsg, n.aesub)
3368 require_Equal(t, n.pindex, 1)
3369 require_Equal(t, n.commit, 1)
3370 require_Equal(t, n.applied, 0)
3371
3372 // Apply it.
3373 n.Applied(1)
3374 require_Equal(t, n.applied, 1)
3375
3376 // Install the snapshot.
3377 require_NoError(t, n.InstallSnapshot(nil, false))
3378
3379 // Restoring the snapshot should not up applied, because the apply queue is async.
3380 n.pindex, n.commit, n.processed, n.applied = 0, 0, 0, 0
3381 n.setupLastSnapshot()
3382 require_Equal(t, n.pindex, 1)
3383 require_Equal(t, n.commit, 1)
3384 require_Equal(t, n.processed, 0)
3385 require_Equal(t, n.applied, 0)
3386 }
3387
3388 func TestNRGLoadLastSnapshotCleansLegacyZeroIndexSnapshot(t *testing.T) {
3389 n, cleanup := initSingleMemRaftNode(t)
3390 defer cleanup()
3391
3392 snapDir := filepath.Join(n.sd, snapshotsDir)
3393 require_NoError(t, os.MkdirAll(snapDir, defaultDirPerms))
3394
3395 legacy := &snapshot{
3396 lastTerm: 1,
3397 lastIndex: 0,
3398 peerstate: encodePeerState(&peerState{n.peerNames(), n.csz, n.extSt}),
3399 data: []byte("legacy"),
3400 }
3401 sfile := filepath.Join(snapDir, fmt.Sprintf(snapFileT, legacy.lastTerm, legacy.lastIndex))
3402 require_NoError(t, writeFileWithSync(n.dios, sfile, n.encodeSnapshot(legacy), defaultFilePerms))
3403
3404 n.Lock()
3405 n.snapfile = sfile
3406 snap, err := n.loadLastSnapshot()
3407 snapfile := n.snapfile
3408 n.Unlock()
3409
3410 require_Error(t, err, errNoSnapAvailable)
3411 require_True(t, snap == nil)
3412 require_Equal(t, snapfile, _EMPTY_)
3413 _, err = os.Stat(sfile)
3414 require_True(t, os.IsNotExist(err))
3415 }
3416
3417 func TestNRGSetupLastSnapshotIgnoresTmpFile(t *testing.T) {
3418 n, cleanup := initSingleMemRaftNode(t)
3419 defer cleanup()
3420
3421 // Make a snapshot file
3422 snapDir := filepath.Join(n.sd, snapshotsDir)
3423 require_NoError(t, os.MkdirAll(snapDir, defaultDirPerms))
3424
3425 snap := &snapshot{
3426 lastTerm: 1,
3427 lastIndex: 1,
3428 peerstate: encodePeerState(n.currentPeerState()),
3429 data: []byte("snapshot"),
3430 }
3431
3432 sfile := filepath.Join(snapDir, fmt.Sprintf(snapFileT, snap.lastTerm, snap.lastIndex))
3433 require_NoError(t, os.WriteFile(sfile, n.encodeSnapshot(snap), defaultFilePerms))
3434
3435 // Make a empty snapshot file with a higher index, and extension
3436 // .tmp to simulate the intermediate step in writeAtomically.
3437 tmpSnap := filepath.Join(snapDir, fmt.Sprintf(snapFileT, uint64(1), uint64(2))+".tmp")
3438 require_NoError(t, os.WriteFile(tmpSnap, nil, defaultFilePerms))
3439
3440 // If bug is present: setupLastSnapshot() selects
3441 // the higher numbered snapshot file, even if it
3442 // has the .tmp extension. The presence of a .tmp
3443 // snapshot file means the server crashed, preventing
3444 // writeAtomically() to finish. The contents of a
3445 // .tmp snapshot file may be incomplete.
3446 // Verify that setupLastSnapshot selects the "good"
3447 // snapshot.
3448 err := n.setupLastSnapshot()
3449 require_NoError(t, err)
3450 require_Equal(t, n.snapfile, sfile)
3451 }
3452
3453 func TestNRGKeepRunningOnServerShutdown(t *testing.T) {
3454 n, cleanup := initSingleMemRaftNode(t)
3455 defer cleanup()
3456
3457 n.RLock()
3458 s := n.s
3459 wal := n.wal.(*memStore)
3460 n.RUnlock()
3461
3462 n.wg.Add(1)
3463 s.startGoRoutine(n.run, nil)
3464
3465 s.running.Store(false)
3466 time.Sleep(time.Second)
3467
3468 wal.mu.RLock()
3469 msgs := wal.msgs
3470 wal.mu.RUnlock()
3471 require_NotNil(t, msgs)
3472
3473 n.Stop()
3474 n.WaitForStop()
3475
3476 wal.mu.RLock()
3477 msgs = wal.msgs
3478 wal.mu.RUnlock()
3479 require_True(t, msgs == nil)
3480 }
3481
3482 func TestNRGVoteResponseEncoding(t *testing.T) {
3483 vr := &voteResponse{term: 1, peer: "S1Nunr6R"}
3484 vr.granted, vr.empty = false, false
3485 res := vr.encode()
3486 require_Equal(t, res[16], 0)
3487 require_True(t, reflect.DeepEqual(decodeVoteResponse(res), vr))
3488
3489 vr.granted, vr.empty = true, false
3490 res = vr.encode()
3491 require_Equal(t, res[16], 1)
3492 require_True(t, reflect.DeepEqual(decodeVoteResponse(res), vr))
3493
3494 vr.granted, vr.empty = false, true
3495 res = vr.encode()
3496 require_Equal(t, res[16], 2)
3497 require_True(t, reflect.DeepEqual(decodeVoteResponse(res), vr))
3498
3499 vr.granted, vr.empty = true, true
3500 res = vr.encode()
3501 require_Equal(t, res[16], 3)
3502 require_True(t, reflect.DeepEqual(decodeVoteResponse(res), vr))
3503 }
3504
3505 func TestNRGDoesntRequestVoteOnWriteError(t *testing.T) {
3506 n, cleanup := initSingleMemRaftNode(t)
3507 defer cleanup()
3508
3509 // Snoop on the vote request subject so we can tell whether we campaign.
3510 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
3511 require_NoError(t, err)
3512 defer nc.Close()
3513
3514 sub, err := nc.SubscribeSync(n.vsubj)
3515 require_NoError(t, err)
3516 defer sub.Unsubscribe()
3517 require_NoError(t, nc.Flush())
3518
3519 // Specifically not using setWriteError here because that shuts down the node
3520 // and causes problems with the defer cleanup.
3521 n.werr = errors.New("test write error")
3522 n.state.Store(int32(Candidate))
3523
3524 // We can't persist our own vote, so asking for votes must be a no-op,
3525 // otherwise after a restart we could vote for someone else in this term.
3526 n.requestVote()
3527
3528 // Nothing should have been published to the vote subject.
3529 _, err = sub.NextMsg(250 * time.Millisecond)
3530 require_Error(t, err, nats.ErrTimeout)
3531 }
3532
3533 func TestNRGInitializeAndScaleUp(t *testing.T) {
3534 n, cleanup := initSingleMemRaftNode(t)
3535 defer cleanup()
3536
3537 // Create a sample entry, the content doesn't matter, just that it's stored.
3538 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3539 entries := []*Entry{newEntry(EntryNormal, esm)}
3540
3541 nats0 := "S1Nunr6R" // "nats-0"
3542
3543 // Timeline
3544 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 0, pindex: 0, entries: entries})
3545
3546 require_True(t, n.initializing)
3547 n.scaleUp = true
3548 n.SetObserver(true)
3549 require_Equal(t, n.term, 0)
3550
3551 voteReply := "$TEST"
3552 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
3553 require_NoError(t, err)
3554 defer nc.Close()
3555
3556 sub, err := nc.SubscribeSync(voteReply)
3557 require_NoError(t, err)
3558 defer sub.Drain()
3559 require_NoError(t, nc.Flush())
3560
3561 // Votes on a new leader, and resets notion of "empty vote" to ease getting quorum.
3562 require_NoError(t, n.processVoteRequest(&voteRequest{term: 1, candidate: nats0, reply: voteReply}))
3563 require_Equal(t, n.term, 1)
3564 require_Equal(t, n.vote, nats0)
3565 require_True(t, n.initializing)
3566 require_True(t, n.scaleUp)
3567 require_True(t, n.observer)
3568
3569 msg, err := sub.NextMsg(time.Second)
3570 require_NoError(t, err)
3571 vr := decodeVoteResponse(msg.Data)
3572 require_True(t, vr.granted)
3573 require_False(t, vr.empty)
3574
3575 // Processing an append entry resets scale up and puts us out of observer mode.
3576 n.processAppendEntry(aeMsg, n.aesub)
3577 require_Equal(t, n.pindex, 1)
3578 require_False(t, n.initializing)
3579 require_False(t, n.scaleUp)
3580 require_False(t, n.observer)
3581
3582 // Simulate a reset.
3583 n.resetWAL()
3584 require_Equal(t, n.pindex, 0)
3585
3586 // Vote after a WAL reset must be an "empty vote".
3587 require_NoError(t, n.processVoteRequest(&voteRequest{term: 2, candidate: "_random_", reply: voteReply}))
3588 require_Equal(t, n.term, 2)
3589 require_Equal(t, n.vote, "_random_")
3590
3591 // Vote is still granted, but now marked as "empty".
3592 msg, err = sub.NextMsg(time.Second)
3593 require_NoError(t, err)
3594 vr = decodeVoteResponse(msg.Data)
3595 require_True(t, vr.granted)
3596 require_True(t, vr.empty)
3597
3598 // Reset to check if snapshot on catchup can also reset this.
3599 n.initializing = true
3600 n.scaleUp = true
3601 n.SetObserver(true)
3602 snapshotEntries := []*Entry{
3603 newEntry(EntrySnapshot, nil),
3604 newEntry(EntryPeerState, encodePeerState(&peerState{n.peerNames(), n.csz, n.extSt})),
3605 }
3606 aeSnapshot := encode(t, &appendEntry{leader: nats0, term: 2, commit: 1, pterm: 1, pindex: 1, entries: snapshotEntries})
3607 n.createCatchup(aeSnapshot)
3608 n.processAppendEntry(aeSnapshot, n.catchup.sub)
3609 require_False(t, n.initializing)
3610 require_False(t, n.scaleUp)
3611 require_False(t, n.observer)
3612
3613 // Simulate a reset.
3614 n.resetWAL()
3615 require_Equal(t, n.pindex, 0)
3616
3617 // Vote when initializing but not scaling up, must also NOT be an "empty vote".
3618 n.initializing = true
3619 require_NoError(t, n.processVoteRequest(&voteRequest{term: 3, candidate: "_random_", reply: voteReply}))
3620 require_Equal(t, n.term, 3)
3621 require_Equal(t, n.vote, "_random_")
3622
3623 // Vote is still granted, but now marked as "empty".
3624 msg, err = sub.NextMsg(time.Second)
3625 require_NoError(t, err)
3626 vr = decodeVoteResponse(msg.Data)
3627 require_True(t, vr.granted)
3628 require_False(t, vr.empty)
3629 }
3630
3631 func TestNRGReplayOnSnapshotSameTerm(t *testing.T) {
3632 n, cleanup := initSingleMemRaftNode(t)
3633 defer cleanup()
3634
3635 // Create a sample entry, the content doesn't matter, just that it's stored.
3636 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3637 entries := []*Entry{newEntry(EntryNormal, esm)}
3638
3639 nats0 := "S1Nunr6R" // "nats-0"
3640
3641 // Timeline
3642 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 0, pindex: 0, entries: entries})
3643 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
3644 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 2, entries: entries})
3645
3646 // Process the first append entry.
3647 n.processAppendEntry(aeMsg1, n.aesub)
3648 require_Equal(t, n.pindex, 1)
3649
3650 // Commit and apply.
3651 require_NoError(t, n.applyCommit(1))
3652 require_Equal(t, n.commit, 1)
3653 n.Applied(1)
3654 require_Equal(t, n.applied, 1)
3655
3656 // Install snapshot.
3657 require_NoError(t, n.InstallSnapshot(nil, false))
3658 snap, err := n.loadLastSnapshot()
3659 require_NoError(t, err)
3660 require_Equal(t, snap.lastIndex, 1)
3661
3662 // Process other messages.
3663 n.processAppendEntry(aeMsg2, n.aesub)
3664 require_Equal(t, n.pindex, 2)
3665 n.processAppendEntry(aeMsg3, n.aesub)
3666 require_Equal(t, n.pindex, 3)
3667
3668 // Replay the append entry that matches our snapshot.
3669 // This can happen as a repeated entry, or a delayed append entry after having already received it in a catchup.
3670 // Should be recognized as a replay with the same term, marked as success, and not truncate.
3671 n.processAppendEntry(aeMsg2, n.aesub)
3672 require_Equal(t, n.pindex, 3)
3673 }
3674
3675 func TestNRGReplayOnSnapshotDifferentTerm(t *testing.T) {
3676 n, cleanup := initSingleMemRaftNode(t)
3677 defer cleanup()
3678
3679 // Create a sample entry, the content doesn't matter, just that it's stored.
3680 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3681 entries := []*Entry{newEntry(EntryNormal, esm)}
3682
3683 nats0 := "S1Nunr6R" // "nats-0"
3684
3685 // Timeline
3686 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 0, pindex: 0, entries: entries, lterm: 2})
3687 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 2, commit: 1, pterm: 1, pindex: 1, entries: entries, lterm: 2})
3688 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 2, commit: 1, pterm: 2, pindex: 2, entries: entries, lterm: 2})
3689
3690 // Process the first append entry.
3691 n.processAppendEntry(aeMsg1, n.aesub)
3692 require_Equal(t, n.pindex, 1)
3693
3694 // Commit and apply.
3695 require_NoError(t, n.applyCommit(1))
3696 require_Equal(t, n.commit, 1)
3697 n.Applied(1)
3698 require_Equal(t, n.applied, 1)
3699
3700 // Install snapshot.
3701 require_NoError(t, n.InstallSnapshot(nil, false))
3702 snap, err := n.loadLastSnapshot()
3703 require_NoError(t, err)
3704 require_Equal(t, snap.lastIndex, 1)
3705
3706 // Reset applied to simulate having received the snapshot from
3707 // another leader, and we didn't apply yet since it's async.
3708 n.applied = 0
3709
3710 // Process other messages.
3711 n.processAppendEntry(aeMsg2, n.aesub)
3712 require_Equal(t, n.pindex, 2)
3713 n.processAppendEntry(aeMsg3, n.aesub)
3714 require_Equal(t, n.pindex, 3)
3715
3716 // Replay the append entry that matches our snapshot.
3717 // This can happen as a repeated entry, or a delayed append entry after having already received it in a catchup.
3718 // Should be recognized as truncating back to the installed snapshot, not reset the WAL fully.
3719 // Since all is aligned after truncation, should also be able to apply the entry.
3720 n.processAppendEntry(aeMsg2, n.aesub)
3721 require_Equal(t, n.pindex, 2)
3722
3723 // Should now also be able to apply the third entry.
3724 n.processAppendEntry(aeMsg3, n.aesub)
3725 require_Equal(t, n.pindex, 3)
3726 }
3727
3728 func TestNRGSizeAndApplied(t *testing.T) {
3729 n, cleanup := initSingleMemRaftNode(t)
3730 defer cleanup()
3731
3732 // Create a sample entry, the content doesn't matter, just that it's stored.
3733 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3734
3735 nats0 := "S1Nunr6R" // "nats-0"
3736 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: []*Entry{newEntry(EntryNormal, esm)}})
3737 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: []*Entry{newEntry(EntryNormal, esm)}})
3738
3739 var (
3740 entries uint64
3741 bytes uint64
3742 )
3743
3744 // Initially our WAL is empty.
3745 entries, bytes = n.Size()
3746 require_Equal(t, entries, 0)
3747 require_Equal(t, bytes, 0)
3748
3749 // Store the first append entry.
3750 require_NoError(t, n.storeToWAL(aeMsg1))
3751 entries, bytes = n.Size()
3752 require_Equal(t, entries, 1)
3753 require_Equal(t, bytes, 105)
3754
3755 // Store the second append entry.
3756 require_NoError(t, n.storeToWAL(aeMsg2))
3757 entries, bytes = n.Size()
3758 require_Equal(t, entries, 2)
3759 require_Equal(t, bytes, 210)
3760
3761 // Applying should return what part of the WAL can be compacted.
3762 n.commit = 1
3763 entries, bytes = n.Applied(1)
3764 require_Equal(t, entries, 1)
3765 require_Equal(t, bytes, 105)
3766
3767 // After applying all should return our whole WAL can be compacted.
3768 n.commit = 2
3769 entries, bytes = n.Applied(2)
3770 require_Equal(t, entries, 2)
3771 require_Equal(t, bytes, 210)
3772
3773 // Installing a snapshot should properly correct n.papplied and n.bytes
3774 n.applied = 1 // Reset just for testing.
3775 require_NoError(t, n.InstallSnapshot(nil, false))
3776 require_Equal(t, n.papplied, 1)
3777 require_Equal(t, n.bytes, 105)
3778 entries, bytes = n.Size()
3779 require_Equal(t, entries, 1)
3780 require_Equal(t, bytes, 105)
3781
3782 entries, bytes = n.Applied(2)
3783 require_Equal(t, entries, 1)
3784 require_Equal(t, bytes, 105)
3785
3786 require_NoError(t, n.InstallSnapshot(nil, false))
3787 require_Equal(t, n.papplied, 2)
3788 require_Equal(t, n.bytes, 0)
3789 entries, bytes = n.Size()
3790 require_Equal(t, entries, 0)
3791 require_Equal(t, bytes, 0)
3792 }
3793
3794 func TestNRGIgnoreEntryAfterCanceledCatchup(t *testing.T) {
3795 n, cleanup := initSingleMemRaftNode(t)
3796 defer cleanup()
3797
3798 // Create a sample entry, the content doesn't matter, just that it's stored.
3799 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3800 entries := []*Entry{newEntry(EntryNormal, esm)}
3801
3802 nats0 := "S1Nunr6R" // "nats-0"
3803
3804 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
3805 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
3806
3807 n.processAppendEntry(aeMsg2, n.aesub)
3808 require_True(t, n.catchup != nil)
3809
3810 csub := n.catchup.sub
3811 n.cancelCatchup()
3812
3813 // Catchup was canceled, a message on this canceled catchup should not be stored.
3814 n.processAppendEntry(aeMsg1, csub)
3815 require_Equal(t, n.pindex, 0)
3816 }
3817
3818 func TestNRGDelayedMessagesAfterCatchupDontCountTowardQuorum(t *testing.T) {
3819 n, cleanup := initSingleMemRaftNode(t)
3820 defer cleanup()
3821
3822 // Create a sample entry, the content doesn't matter, just that it's stored.
3823 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3824 entries := []*Entry{newEntry(EntryNormal, esm)}
3825
3826 aeReply := "$TEST"
3827 nats0 := "S1Nunr6R" // "nats-0"
3828 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries, reply: aeReply})
3829 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries, reply: aeReply})
3830 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 2, entries: entries, reply: aeReply})
3831
3832 // Triggers catchup.
3833 n.processAppendEntry(aeMsg3, n.aesub)
3834 require_True(t, n.catchup != nil)
3835
3836 // Catchup runs partially.
3837 n.processAppendEntry(aeMsg1, n.catchup.sub)
3838 n.processAppendEntry(aeMsg2, n.catchup.sub)
3839 require_Equal(t, n.pindex, 2)
3840 require_Equal(t, n.commit, 1)
3841 n.Applied(1)
3842 require_Equal(t, n.applied, 1)
3843 require_NoError(t, n.InstallSnapshot(nil, false))
3844
3845 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
3846 require_NoError(t, err)
3847 defer nc.Close()
3848
3849 sub, err := nc.SubscribeSync(aeReply)
3850 require_NoError(t, err)
3851 defer sub.Drain()
3852 require_NoError(t, nc.Flush())
3853
3854 // We now receive delayed "real-time" messages.
3855 // The first message needs to be a copy, because we've committed it before and returned it to the pool.
3856 aeMsg1Copy := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries, reply: aeReply})
3857 n.processAppendEntry(aeMsg1Copy, n.aesub)
3858 require_Equal(t, n.pindex, 2)
3859 // Should NOT reply "success", otherwise we would wrongfully provide quorum while not having an up-to-date log.
3860 _, err = sub.NextMsg(500 * time.Millisecond)
3861 require_Error(t, err, nats.ErrTimeout)
3862
3863 n.processAppendEntry(aeMsg2, n.aesub)
3864 require_Equal(t, n.pindex, 2)
3865 // Should NOT reply "success", otherwise we would wrongfully provide quorum while not having an up-to-date log.
3866 _, err = sub.NextMsg(500 * time.Millisecond)
3867 require_Error(t, err, nats.ErrTimeout)
3868
3869 n.processAppendEntry(aeMsg3, n.aesub)
3870 require_Equal(t, n.pindex, 3)
3871 // Should reply "success", this is the latest message.
3872 msg, err := sub.NextMsg(500 * time.Millisecond)
3873 require_NoError(t, err)
3874 ar := decodeAppendEntryResponse(msg.Data)
3875 require_Equal(t, ar.index, 3)
3876 require_True(t, ar.success)
3877 require_Equal(t, msg.Reply, _EMPTY_)
3878 }
3879
3880 func TestNRGStepdownWithHighestTermDuringCatchup(t *testing.T) {
3881 n, cleanup := initSingleMemRaftNode(t)
3882 defer cleanup()
3883
3884 // Create a sample entry, the content doesn't matter, just that it's stored.
3885 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3886 entries := []*Entry{newEntry(EntryNormal, esm)}
3887
3888 nats0 := "S1Nunr6R" // "nats-0"
3889 aeMsg1 := encode(t, &appendEntry{leader: nats0, lterm: 10, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
3890 aeMsg2 := encode(t, &appendEntry{leader: nats0, lterm: 20, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
3891
3892 // Need to store the message, stepdown, and up term.
3893 n.switchToCandidate()
3894 require_Equal(t, n.term, 1)
3895 n.processAppendEntry(aeMsg1, n.aesub)
3896 require_Equal(t, n.term, 10)
3897 require_Equal(t, n.pindex, 1)
3898
3899 // Need to store the message, stepdown, and up term.
3900 n.switchToLeader()
3901 n.processAppendEntry(aeMsg2, n.aesub)
3902 require_Equal(t, n.term, 20)
3903 require_Equal(t, n.pindex, 2)
3904 }
3905
3906 func TestNRGTruncateOnStartup(t *testing.T) {
3907 c := createJetStreamClusterExplicit(t, "R3S", 3)
3908 s := c.servers[0] // RunBasicJetStreamServer not available
3909 defer c.shutdown()
3910
3911 storeDir := t.TempDir()
3912 fcfg := FileStoreConfig{StoreDir: storeDir, BlockSize: defaultMediumBlockSize, AsyncFlush: false, srv: s}
3913 scfg := StreamConfig{Name: "RAFT", Storage: FileStorage}
3914 fs, err := newFileStore(fcfg, scfg)
3915 require_NoError(t, err)
3916
3917 cfg := &RaftConfig{Name: "TEST", Store: storeDir, Log: fs}
3918
3919 err = s.bootstrapRaftNode(cfg, nil, false)
3920 require_NoError(t, err)
3921 n, err := s.initRaftNode(globalAccountName, cfg, pprofLabels{})
3922 require_NoError(t, err)
3923
3924 // Create a sample entry, the content doesn't matter, just that it's stored.
3925 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
3926 entries := []*Entry{newEntry(EntryNormal, esm)}
3927
3928 nats0 := "S1Nunr6R" // "nats-0"
3929 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
3930 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
3931
3932 // Store two messages the normal way.
3933 n.processAppendEntry(aeMsg1, n.aesub)
3934 n.processAppendEntry(aeMsg2, n.aesub)
3935 require_Equal(t, n.pindex, 2)
3936
3937 state := n.wal.State()
3938 require_Equal(t, state.Msgs, 2)
3939 require_Equal(t, state.FirstSeq, 1)
3940 require_Equal(t, state.LastSeq, 2)
3941 require_Equal(t, state.NumDeleted, 0)
3942
3943 // Simulate a truncation that's only performed halfway, and we got hard killed at some point.
3944 removed, err := n.wal.RemoveMsg(2)
3945 require_True(t, removed)
3946 require_NoError(t, err)
3947
3948 state = n.wal.State()
3949 require_Equal(t, state.Msgs, 1)
3950 require_Equal(t, state.FirstSeq, 1)
3951 require_Equal(t, state.LastSeq, 2)
3952 require_Equal(t, state.NumDeleted, 1)
3953
3954 // Restart.
3955 n.Stop()
3956 n.WaitForStop()
3957 require_NoError(t, fs.Stop())
3958 fs, err = newFileStore(fcfg, scfg)
3959 require_NoError(t, err)
3960 cfg = &RaftConfig{Name: "TEST", Store: storeDir, Log: fs}
3961 n, err = s.initRaftNode(globalAccountName, cfg, pprofLabels{})
3962 require_NoError(t, err)
3963
3964 // Should truncate the WAL on startup, the message was removed.
3965 state = n.wal.State()
3966 require_Equal(t, state.Msgs, 1)
3967 require_Equal(t, state.FirstSeq, 1)
3968 require_Equal(t, state.LastSeq, 1)
3969 require_Equal(t, state.NumDeleted, 0)
3970
3971 // Store an invalid append entry manually.
3972 aeMsg2.pindex = 0
3973 aeMsg2 = encode(t, aeMsg2)
3974 _, _, err = n.wal.StoreMsg(_EMPTY_, nil, aeMsg2.buf, 0)
3975 require_NoError(t, err)
3976
3977 state = n.wal.State()
3978 require_Equal(t, state.Msgs, 2)
3979 require_Equal(t, state.FirstSeq, 1)
3980 require_Equal(t, state.LastSeq, 2)
3981 require_Equal(t, state.NumDeleted, 0)
3982
3983 // Restart.
3984 n.Stop()
3985 n.WaitForStop()
3986 require_NoError(t, fs.Stop())
3987 fs, err = newFileStore(fcfg, scfg)
3988 require_NoError(t, err)
3989 cfg = &RaftConfig{Name: "TEST", Store: storeDir, Log: fs}
3990 n, err = s.initRaftNode(globalAccountName, cfg, pprofLabels{})
3991 require_NoError(t, err)
3992
3993 // Should truncate the WAL on startup, the append entry is invalid.
3994 state = n.wal.State()
3995 require_Equal(t, state.Msgs, 1)
3996 require_Equal(t, state.FirstSeq, 1)
3997 require_Equal(t, state.LastSeq, 1)
3998 require_Equal(t, state.NumDeleted, 0)
3999 }
4000
4001 func TestNRGLeaderCatchupHandling(t *testing.T) {
4002 n, cleanup := initSingleMemRaftNode(t)
4003 defer cleanup()
4004
4005 // Create a sample entry, the content doesn't matter, just that it's stored.
4006 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
4007 entries := []*Entry{newEntry(EntryNormal, esm)}
4008
4009 nats0 := "S1Nunr6R" // "nats-0"
4010 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
4011 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
4012 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 2, entries: entries})
4013
4014 n.processAppendEntry(aeMsg1, n.aesub)
4015 n.processAppendEntry(aeMsg2, n.aesub)
4016 n.processAppendEntry(aeMsg3, n.aesub)
4017 require_Equal(t, n.pindex, 3)
4018
4019 n.switchToLeader()
4020
4021 catchupReply := "$TEST"
4022 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
4023 require_NoError(t, err)
4024 defer nc.Close()
4025
4026 sub, err := nc.SubscribeSync(catchupReply)
4027 require_NoError(t, err)
4028 defer sub.Drain()
4029 require_NoError(t, nc.Flush())
4030
4031 // Simulate a follower that's up-to-date with only the first message.
4032 n.catchupFollower(&appendEntryResponse{success: false, term: 1, index: 1, reply: catchupReply})
4033
4034 // Should receive all messages the leader knows up to this point.
4035 msg, err := sub.NextMsg(500 * time.Millisecond)
4036 require_NoError(t, err)
4037 ae, err := decodeAppendEntry(msg.Data, nil, _EMPTY_)
4038 require_NoError(t, err)
4039 require_Equal(t, ae.pterm, 1)
4040 require_Equal(t, ae.pindex, 1)
4041
4042 msg, err = sub.NextMsg(500 * time.Millisecond)
4043 require_NoError(t, err)
4044 ae, err = decodeAppendEntry(msg.Data, nil, _EMPTY_)
4045 require_NoError(t, err)
4046 require_Equal(t, ae.pterm, 1)
4047 require_Equal(t, ae.pindex, 2)
4048 }
4049
4050 func TestNRGNewEntriesFromOldLeaderResetsWALDuringCatchup(t *testing.T) {
4051 n, cleanup := initSingleMemRaftNode(t)
4052 defer cleanup()
4053
4054 // Create a sample entry, the content doesn't matter, just that it's stored.
4055 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
4056 entries := []*Entry{newEntry(EntryNormal, esm)}
4057
4058 nats0 := "S1Nunr6R" // "nats-0"
4059 aeMsg1 := encode(t, &appendEntry{leader: nats0, lterm: 20, term: 20, commit: 0, pterm: 0, pindex: 0, entries: entries})
4060 aeMsg2 := encode(t, &appendEntry{leader: nats0, lterm: 20, term: 20, commit: 0, pterm: 20, pindex: 1, entries: entries})
4061 aeMsg3 := encode(t, &appendEntry{leader: nats0, lterm: 20, term: 20, commit: 0, pterm: 20, pindex: 2, entries: entries})
4062
4063 aeReply := "$TEST"
4064 aeMsg1Fork := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries, reply: aeReply})
4065 aeMsg2Fork := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
4066
4067 // Trigger a catchup.
4068 n.processAppendEntry(aeMsg2, n.aesub)
4069 validateCatchup := func() {
4070 t.Helper()
4071 require_True(t, n.catchup != nil)
4072 require_Equal(t, n.catchup.cterm, 20)
4073 require_Equal(t, n.catchup.cindex, 1)
4074 }
4075 validateCatchup()
4076
4077 // Catchup the first missed entry.
4078 csub := n.catchup.sub
4079 n.processAppendEntry(aeMsg1, csub)
4080 require_Equal(t, n.pindex, 1)
4081 require_Equal(t, n.pterm, 20)
4082
4083 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
4084 require_NoError(t, err)
4085 defer nc.Close()
4086
4087 sub, err := nc.SubscribeSync(aeReply)
4088 require_NoError(t, err)
4089 defer sub.Drain()
4090 require_NoError(t, nc.Flush())
4091
4092 // Would previously stall the catchup and restart it with a previous leader.
4093 n.catchup.pindex = aeMsg1.pindex + 1
4094 n.catchup.active = time.Time{}
4095 n.processAppendEntry(aeMsg1Fork, n.aesub)
4096 require_Equal(t, n.pindex, 1)
4097 require_Equal(t, n.pterm, 20)
4098 validateCatchup()
4099
4100 // Should reply we have a higher term, prompting the server to step down.
4101 msg, err := sub.NextMsg(time.Second)
4102 require_NoError(t, err)
4103 ar := decodeAppendEntryResponse(msg.Data)
4104 require_False(t, ar.success)
4105 require_Equal(t, ar.index, 1)
4106 require_Equal(t, ar.term, 20)
4107
4108 // Would previously reset the WAL.
4109 n.processAppendEntry(aeMsg2Fork, n.aesub)
4110 require_Equal(t, n.pindex, 1)
4111 require_Equal(t, n.pterm, 20)
4112 validateCatchup()
4113
4114 // Now the catchup should continue, undisturbed by an old leader sending append entries.
4115 n.processAppendEntry(aeMsg2, csub)
4116 require_Equal(t, n.pindex, 2)
4117 require_Equal(t, n.pterm, 20)
4118 require_True(t, n.catchup == nil)
4119
4120 // A remaining catchup entry can still be ingested, even if the catchup state itself is gone.
4121 n.processAppendEntry(aeMsg3, csub)
4122 require_Equal(t, n.pindex, 3)
4123 require_Equal(t, n.pterm, 20)
4124 }
4125
4126 func TestNRGProcessed(t *testing.T) {
4127 n, cleanup := initSingleMemRaftNode(t)
4128 defer cleanup()
4129
4130 // Create a sample entry, the content doesn't matter, just that it's stored.
4131 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
4132 entries := []*Entry{newEntry(EntryNormal, esm)}
4133
4134 nats0 := "S1Nunr6R" // "nats-0"
4135
4136 // Timeline
4137 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 0, pindex: 0, entries: entries})
4138 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 1, entries: entries})
4139 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 3, pterm: 1, pindex: 2, entries: entries})
4140 aeMsg4 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 4, pterm: 1, pindex: 3, entries: entries})
4141 aeMsg5 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 5, pterm: 1, pindex: 4, entries: entries})
4142
4143 // Store three entries.
4144 for i, aeMsg := range []*appendEntry{aeMsg1, aeMsg2, aeMsg3} {
4145 n.processAppendEntry(aeMsg, n.aesub)
4146 require_Equal(t, n.pindex, uint64(i+1))
4147 require_Equal(t, n.commit, uint64(i+1))
4148 require_Equal(t, n.processed, 0)
4149 require_Equal(t, n.applied, 0)
4150 }
4151
4152 // n.Processed can move both n.processed and n.applied up, with different values.
4153 n.Processed(1, 0)
4154 require_Equal(t, n.pindex, 3)
4155 require_Equal(t, n.commit, 3)
4156 require_Equal(t, n.processed, 1)
4157 require_Equal(t, n.applied, 0)
4158
4159 n.Processed(2, 1)
4160 require_Equal(t, n.pindex, 3)
4161 require_Equal(t, n.commit, 3)
4162 require_Equal(t, n.processed, 2)
4163 require_Equal(t, n.applied, 1)
4164
4165 // n.Applied moves both n.processed and n.applied up to the same value.
4166 n.Applied(3)
4167 require_Equal(t, n.pindex, 3)
4168 require_Equal(t, n.commit, 3)
4169 require_Equal(t, n.processed, 3)
4170 require_Equal(t, n.applied, 3)
4171
4172 // Store the remaining messages.
4173 for i, aeMsg := range []*appendEntry{aeMsg4, aeMsg5} {
4174 n.processAppendEntry(aeMsg, n.aesub)
4175 require_Equal(t, n.pindex, uint64(i+4))
4176 require_Equal(t, n.commit, uint64(i+4))
4177 require_Equal(t, n.processed, 3)
4178 require_Equal(t, n.applied, 3)
4179 }
4180
4181 // An invalid processed call with a higher applied should be clamped back down to the processed index.
4182 n.Processed(4, 5)
4183 require_Equal(t, n.pindex, 5)
4184 require_Equal(t, n.commit, 5)
4185 require_Equal(t, n.processed, 4)
4186 require_Equal(t, n.applied, 4)
4187 }
4188
4189 func TestNRGSendAppendEntryNotLeader(t *testing.T) {
4190 n, cleanup := initSingleMemRaftNode(t)
4191 defer cleanup()
4192
4193 require_Equal(t, n.State(), Follower)
4194 require_Equal(t, n.pindex, 0)
4195
4196 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
4197 require_NoError(t, err)
4198 defer nc.Close()
4199
4200 sub, err := nc.SubscribeSync(n.asubj)
4201 require_NoError(t, err)
4202 defer sub.Drain()
4203 require_NoError(t, nc.Flush())
4204
4205 // sendAppendEntry acquires the lock by itself, so it must also protect against us not being leader anymore.
4206 n.sendAppendEntry([]*Entry{newEntry(EntryNormal, nil)})
4207
4208 // We're a follower, so we should not be able to send or store a message.
4209 require_Equal(t, n.pindex, 0)
4210 msg, err := sub.NextMsg(250 * time.Millisecond)
4211 require_Error(t, err, nats.ErrTimeout)
4212 require_True(t, msg == nil)
4213 }
4214
4215 func TestNRGDrainAndReplaySnapshot(t *testing.T) {
4216 n, cleanup := initSingleMemRaftNode(t)
4217 defer cleanup()
4218
4219 // Create a sample entry, the content doesn't matter, just that it's stored.
4220 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
4221 entries := []*Entry{newEntry(EntryNormal, esm)}
4222
4223 nats0 := "S1Nunr6R" // "nats-0"
4224
4225 // Timeline
4226 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
4227 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
4228 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 2, entries: entries})
4229 aeHeartbeat1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 3, pterm: 1, pindex: 3, entries: nil})
4230 aeMsg4 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 3, pterm: 1, pindex: 3, entries: entries})
4231 aeHeartbeat2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 4, pterm: 1, pindex: 4, entries: nil})
4232
4233 // Stage some entries as normal.
4234 require_Len(t, n.apply.len(), 0)
4235 n.processAppendEntry(aeMsg1, n.aesub)
4236 n.processAppendEntry(aeMsg2, n.aesub)
4237 n.processAppendEntry(aeMsg3, n.aesub)
4238 n.processAppendEntry(aeHeartbeat1, n.aesub)
4239 require_Equal(t, n.pindex, 3)
4240 require_Len(t, n.apply.len(), 3)
4241 require_Equal(t, n.commit, 3)
4242 require_Equal(t, n.hcommit, 0)
4243
4244 // Just a sanity-check, if we have no snapshot then this should fail.
4245 require_False(t, n.DrainAndReplaySnapshot())
4246 require_Len(t, n.apply.len(), 3)
4247 require_Equal(t, n.commit, 3)
4248 require_Equal(t, n.hcommit, 0)
4249
4250 // Simulate this server processing a snapshot that requires upper layer catchup.
4251 // This catchup timed out and we would then call into DrainAndReplaySnapshot.
4252 snap := []byte("snapshot")
4253 n.Applied(1)
4254 require_NoError(t, n.InstallSnapshot(snap, false))
4255
4256 require_True(t, n.DrainAndReplaySnapshot())
4257 require_True(t, n.paused)
4258 require_Len(t, n.apply.len(), 1)
4259 require_Equal(t, n.commit, 1)
4260 require_Equal(t, n.hcommit, 3)
4261
4262 // Simulate snapshot processing being successful and restoring the apply queue when resuming.
4263 n.ResumeApply()
4264 require_False(t, n.paused)
4265 require_Len(t, n.apply.len(), 3)
4266 require_Equal(t, n.commit, 3)
4267 require_Equal(t, n.hcommit, 0)
4268
4269 // Now simulate another case where the snapshot processing times out multiple times.
4270 require_True(t, n.DrainAndReplaySnapshot())
4271 require_True(t, n.paused)
4272 require_Len(t, n.apply.len(), 1)
4273 require_Equal(t, n.commit, 1)
4274 require_Equal(t, n.hcommit, 3)
4275
4276 // Could receive new messages in the meantime and need to keep tracking the highest known commit properly.
4277 n.processAppendEntry(aeMsg4, n.aesub)
4278 n.processAppendEntry(aeHeartbeat2, n.aesub)
4279 require_Equal(t, n.pindex, 4)
4280 require_True(t, n.paused)
4281 require_Len(t, n.apply.len(), 1)
4282 require_Equal(t, n.commit, 1)
4283 require_Equal(t, n.hcommit, 4)
4284
4285 // Replaying again should preserve the highest known commit.
4286 require_True(t, n.DrainAndReplaySnapshot())
4287 require_True(t, n.paused)
4288 require_Len(t, n.apply.len(), 1)
4289 require_Equal(t, n.commit, 1)
4290 require_Equal(t, n.hcommit, 4)
4291
4292 // Resume applies, and ensure correct state.
4293 n.ResumeApply()
4294 require_False(t, n.paused)
4295 require_Len(t, n.apply.len(), 4)
4296 require_Equal(t, n.commit, 4)
4297 require_Equal(t, n.hcommit, 0)
4298 }
4299
4300 func TestNRGTrackPeerActive(t *testing.T) {
4301 // The leader should track timestamps for all peers.
4302 // Each follower should only track the leader, otherwise we would get outdated timestamps.
4303 checkLastSeen := func(peers map[string]RaftzGroupPeer) {
4304 for _, peer := range peers {
4305 if peer.LastSeen == _EMPTY_ {
4306 continue
4307 }
4308 elapsed, err := time.ParseDuration(peer.LastSeen)
4309 require_NoError(t, err)
4310 require_LessThan(t, elapsed, time.Second)
4311 }
4312 }
4313
4314 c := createJetStreamClusterExplicit(t, "R3S", 3)
4315 defer c.shutdown()
4316
4317 ml := c.leader()
4318 rs := c.randomNonLeader()
4319 var preferred *Server
4320 for _, s := range c.servers {
4321 if s == ml || s == rs {
4322 continue
4323 }
4324 preferred = s
4325 break
4326 }
4327 require_NotNil(t, preferred)
4328
4329 time.Sleep(2 * time.Second)
4330 before := (*rs.Raftz(&RaftzOptions{}))[DEFAULT_SYSTEM_ACCOUNT][defaultMetaGroupName].Peers
4331 checkLastSeen(before)
4332
4333 js := ml.getJetStream()
4334 n := js.getMetaGroup()
4335 require_NoError(t, n.StepDown(preferred.NodeName()))
4336
4337 time.Sleep(2 * time.Second)
4338 after := (*rs.Raftz(&RaftzOptions{}))[DEFAULT_SYSTEM_ACCOUNT][defaultMetaGroupName].Peers
4339 checkLastSeen(after)
4340 }
4341
4342 func TestNRGLostQuorum(t *testing.T) {
4343 n, cleanup := initSingleMemRaftNode(t)
4344 defer cleanup()
4345
4346 nats0 := "S1Nunr6R" // "nats-0"
4347
4348 nats1 := "yrzKKRBu" // "nats-1"
4349 n.Lock()
4350 n.addPeer(nats1)
4351 // Ignore scale-up grace period so this
4352 // test focuses on lost-quorum tracking.
4353 n.lsut = time.Time{}
4354 n.Unlock()
4355
4356 require_Equal(t, n.State(), Follower)
4357 require_False(t, n.Quorum())
4358 require_True(t, n.lostQuorum())
4359
4360 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
4361 require_NoError(t, err)
4362 defer nc.Close()
4363
4364 // Respond to a vote request.
4365 sub, err := nc.Subscribe(n.vsubj, func(m *nats.Msg) {
4366 req := decodeVoteRequest(m.Data, m.Reply)
4367 resp := voteResponse{term: req.term, peer: nats0, granted: true}
4368 m.Respond(resp.encode())
4369 })
4370 require_NoError(t, err)
4371 defer sub.Drain()
4372 require_NoError(t, nc.Flush())
4373
4374 // Switch to candidate and make sure we properly track the peer as active.
4375 n.switchToCandidate()
4376 require_Equal(t, n.State(), Candidate)
4377 require_False(t, n.Quorum())
4378 require_True(t, n.lostQuorum())
4379
4380 n.Lock()
4381 n.addPeer(nats0)
4382 n.Unlock()
4383
4384 n.runAsCandidate()
4385 require_Equal(t, n.State(), Leader)
4386 require_True(t, n.Quorum())
4387 require_False(t, n.lostQuorum())
4388 }
4389
4390 func TestNRGParallelCatchupRollback(t *testing.T) {
4391 n, cleanup := initSingleMemRaftNode(t)
4392 defer cleanup()
4393
4394 // Create a sample entry, the content doesn't matter, just that it's stored.
4395 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
4396 entries := []*Entry{newEntry(EntryNormal, esm)}
4397
4398 nats0 := "S1Nunr6R" // "nats-0"
4399
4400 aeReply := "$TEST"
4401 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
4402 require_NoError(t, err)
4403 defer nc.Close()
4404
4405 sub, err := nc.SubscribeSync(aeReply)
4406 require_NoError(t, err)
4407 defer sub.Drain()
4408 require_NoError(t, nc.Flush())
4409
4410 // Timeline
4411 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, lterm: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
4412 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, lterm: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
4413 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 2, entries: nil, reply: aeReply})
4414
4415 // Trigger a catchup.
4416 n.processAppendEntry(aeMsg2, n.aesub)
4417 require_Equal(t, n.pindex, 0)
4418 require_NotNil(t, n.catchup)
4419 require_Equal(t, n.catchup.cterm, aeMsg2.pterm)
4420 require_Equal(t, n.catchup.cindex, aeMsg2.pindex)
4421 csub := n.catchup.sub
4422
4423 // Receive the missed messages.
4424 n.processAppendEntry(aeMsg1, csub)
4425 require_Equal(t, n.pindex, 1)
4426 n.processAppendEntry(aeMsg2, csub)
4427 require_Equal(t, n.pindex, 2)
4428 require_True(t, n.catchup == nil)
4429
4430 // Should respond to the heartbeat and allow the leader to commit.
4431 n.processAppendEntry(aeHeartbeat, n.aesub)
4432 msg, err := sub.NextMsg(time.Second)
4433 require_NoError(t, err)
4434 ar := decodeAppendEntryResponse(msg.Data)
4435 require_NotNil(t, ar)
4436 require_True(t, ar.success)
4437 require_Equal(t, ar.term, aeHeartbeat.term)
4438 require_Equal(t, ar.index, aeHeartbeat.pindex)
4439
4440 // Now replay a message that was already received as a catchup entry.
4441 // Likely due to running multiple catchups in parallel.
4442 // Since our WAL is already ahead, we should not truncate based on this.
4443 n.processAppendEntry(aeMsg1, csub)
4444 require_Equal(t, n.pindex, 2)
4445 }
4446
4447 func TestNRGReportLeaderAfterNoopEntry(t *testing.T) {
4448 n, cleanup := initSingleMemRaftNode(t)
4449 defer cleanup()
4450
4451 require_Equal(t, n.State(), Follower)
4452 require_Equal(t, n.term, 0)
4453 require_False(t, n.Leader())
4454
4455 n.switchToCandidate()
4456 require_Equal(t, n.State(), Candidate)
4457 require_Equal(t, n.term, 1)
4458 require_False(t, n.Leader())
4459
4460 // Switching to leader will put us into Leader state,
4461 // but we're not necessarily an up-to-date leader yet.
4462 n.switchToLeader()
4463 require_Equal(t, n.State(), Leader)
4464 require_Equal(t, n.term, 1)
4465 require_Equal(t, n.pindex, 1) // Should've sent a NOOP-entry to establish leadership.
4466 require_Equal(t, n.applied, 0)
4467 require_False(t, n.Leader())
4468
4469 // Once we commit and apply the final entry, we should starting to report we're leader.
4470 n.commit = 1
4471 n.Applied(1)
4472 require_Equal(t, n.applied, 1)
4473 require_True(t, n.Leader())
4474 }
4475
4476 func TestNRGSendSnapshotInstallsSnapshot(t *testing.T) {
4477 n, cleanup := initSingleMemRaftNode(t)
4478 defer cleanup()
4479
4480 nats0 := "S1Nunr6R" // "nats-0"
4481 nats1 := "yrzKKRBu" // "nats-1"
4482
4483 n.Lock()
4484 n.addPeer(nats0)
4485 n.addPeer(nats1)
4486 n.Unlock()
4487
4488 require_Equal(t, n.pindex, 0)
4489 require_Equal(t, n.snapfile, _EMPTY_)
4490
4491 // Switch to candidate, to become leader.
4492 require_Equal(t, n.term, 0)
4493 n.switchToCandidate()
4494 require_Equal(t, n.term, 1)
4495
4496 // When switching to leader a NOOP-entry is sent.
4497 n.switchToLeader()
4498 require_Equal(t, n.pindex, 1)
4499 require_Equal(t, n.snapfile, _EMPTY_)
4500 require_NoError(t, n.applyCommit(1))
4501 require_Equal(t, n.snapfile, _EMPTY_)
4502
4503 // On scaleup, we send a snapshot.
4504 require_NoError(t, n.SendSnapshot([]byte("snapshot_data")))
4505 require_Equal(t, n.pindex, 2)
4506 require_Equal(t, n.snapfile, _EMPTY_)
4507
4508 // When applying the entry, the sent snapshot should be installed.
4509 require_NoError(t, n.applyCommit(2))
4510 require_NotEqual(t, n.snapfile, _EMPTY_)
4511
4512 snap, err := n.loadLastSnapshot()
4513 require_NoError(t, err)
4514 require_NotNil(t, snap)
4515 require_Equal(t, snap.lastTerm, 1)
4516 require_Equal(t, snap.lastIndex, 1)
4517 require_Equal(t, string(snap.data), "snapshot_data")
4518
4519 // Draining and replaying the snapshot should work.
4520 require_True(t, n.DrainAndReplaySnapshot())
4521 }
4522
4523 func TestNRGQuorumAfterLeaderStepdown(t *testing.T) {
4524 origMinTimeout, origMaxTimeout, origHBInterval := minElectionTimeout, maxElectionTimeout, hbInterval
4525 minElectionTimeout, maxElectionTimeout, hbInterval = minElectionTimeoutDefault, maxElectionTimeoutDefault, hbIntervalDefault
4526 defer func() {
4527 minElectionTimeout, maxElectionTimeout, hbInterval = origMinTimeout, origMaxTimeout, origHBInterval
4528 }()
4529
4530 n, cleanup := initSingleMemRaftNode(t)
4531 defer cleanup()
4532
4533 nats0 := "S1Nunr6R" // "nats-0"
4534 nats1 := "yrzKKRBu" // "nats-1"
4535
4536 n.Lock()
4537 n.addPeer(nats0)
4538 n.addPeer(nats1)
4539 n.Unlock()
4540
4541 // Become leader.
4542 n.switchToCandidate()
4543 n.switchToLeader()
4544
4545 // Should not report having quorum, unless at least 1 peer is seen.
4546 require_False(t, n.Quorum())
4547 n.s.nodeToInfo.Store(nats0, nodeInfo{})
4548 require_NoError(t, n.trackPeer(nats0))
4549 require_True(t, n.Quorum())
4550 n.s.nodeToInfo.Store(nats1, nodeInfo{})
4551 require_NoError(t, n.trackPeer(nats1))
4552 require_True(t, n.Quorum())
4553 require_Len(t, len(n.peers), 3)
4554
4555 // If we hand off leadership to another server, we should
4556 // still be reporting we have quorum.
4557 require_NoError(t, n.StepDown())
4558 require_True(t, n.Quorum())
4559 require_Len(t, len(n.peers), 3)
4560 for peer, ps := range n.peers {
4561 if peer == n.id {
4562 continue
4563 }
4564 // All peer timestamps should be preserved.
4565 require_False(t, ps.ts.IsZero())
4566 }
4567
4568 // After our new leader comes online, we should still have quorum,
4569 // but the other follower's timestamp should be cleared.
4570 n.updateLeader(nats0)
4571 require_Equal(t, n.leader, nats0)
4572 require_True(t, n.Quorum())
4573 require_Len(t, len(n.peers), 3)
4574 for peer, ps := range n.peers {
4575 if peer == n.id {
4576 continue
4577 }
4578 if peer == nats0 {
4579 require_False(t, ps.ts.IsZero()) // Leader is preserved.
4580 } else {
4581 require_True(t, ps.ts.IsZero()) // Other follower is cleared.
4582 }
4583 }
4584 }
4585
4586 func TestNRGNoLogResetOnCorruptedSendToFollower(t *testing.T) {
4587 c := createJetStreamClusterExplicit(t, "R3S", 2)
4588 defer c.shutdown()
4589
4590 rg := c.createRaftGroup("TEST", 2, newStateAdder)
4591 rg.waitOnLeader()
4592
4593 leader := rg.leader().(*stateAdder)
4594 follower := rg.nonLeader().(*stateAdder)
4595
4596 leaderrg := leader.node().(*raft)
4597 followerrg := follower.node().(*raft)
4598
4599 for i := range int64(10) {
4600 leader.proposeDelta(i + 1)
4601 time.Sleep(50 * time.Millisecond) // ... for multiple AEs.
4602 }
4603
4604 // Snapshot and compact.
4605 rg.waitOnTotal(t, 55)
4606 leader.snapshot(t)
4607
4608 // Above snapshot should have resulted in compaction of the WAL.
4609 var ss StreamState
4610 leaderrg.wal.FastState(&ss)
4611 require_Equal(t, ss.Msgs, 0)
4612
4613 // Stop the follower, we'll flatten their state so they have to
4614 // request a snapshot.
4615 require_NoError(t, followerrg.wal.Truncate(0))
4616 follower.stop()
4617
4618 // Now we're going to subtly corrupt the snapshot on the leader.
4619 stat, err := os.Stat(leaderrg.snapfile)
4620 require_NoError(t, err)
4621 require_NoError(t, os.Truncate(leaderrg.snapfile, stat.Size()-1))
4622
4623 // Now we'll bring the follower back. It should request a snapshot
4624 // from the leader. Previously this would have caused the leader to
4625 // blow away the entire log, but in reality we will probably just
4626 // install a new snapshot at some point soon anyway.
4627 follower.restart()
4628 c.waitOnAllCurrent()
4629 leaderrg.wal.FastState(&ss)
4630 require_NotEqual(t, ss.LastSeq, 0)
4631 }
4632
4633 func TestNRGTruncateLogWithMisalignedSnapshotGap(t *testing.T) {
4634 c := createJetStreamClusterExplicit(t, "R3S", 3)
4635 s := c.servers[0] // RunBasicJetStreamServer not available
4636 defer c.shutdown()
4637
4638 storeDir := t.TempDir()
4639 fcfg := FileStoreConfig{StoreDir: storeDir, BlockSize: defaultMediumBlockSize, AsyncFlush: false, srv: s}
4640 scfg := StreamConfig{Name: "RAFT", Storage: FileStorage}
4641 fs, err := newFileStore(fcfg, scfg)
4642 require_NoError(t, err)
4643
4644 cfg := &RaftConfig{Name: "TEST", Store: storeDir, Log: fs}
4645
4646 err = s.bootstrapRaftNode(cfg, nil, false)
4647 require_NoError(t, err)
4648 n, err := s.initRaftNode(globalAccountName, cfg, pprofLabels{})
4649 require_NoError(t, err)
4650
4651 // Create a sample entry, the content doesn't matter, just that it's stored.
4652 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
4653 entries := []*Entry{newEntry(EntryNormal, esm)}
4654
4655 nats0 := "S1Nunr6R" // "nats-0"
4656
4657 // Timeline
4658 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
4659 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
4660 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: entries})
4661
4662 for i, ae := range []*appendEntry{aeMsg1, aeMsg2, aeMsg3} {
4663 n.processAppendEntry(ae, n.aesub)
4664 require_Equal(t, n.pindex, uint64(i+1))
4665 }
4666
4667 // Manually call back down to applied, and then snapshot.
4668 n.Applied(1)
4669 require_NoError(t, n.InstallSnapshot(nil, false))
4670
4671 state := n.wal.State()
4672 require_Equal(t, state.FirstSeq, 2)
4673 require_Equal(t, state.LastSeq, 3)
4674
4675 // Manually compact the WAL further so it doesn't align anymore with the snapshot.
4676 _, err = n.wal.Compact(3)
4677 require_NoError(t, err)
4678 state = n.wal.State()
4679 require_Equal(t, state.FirstSeq, 3)
4680 require_Equal(t, state.LastSeq, 3)
4681
4682 // Restart.
4683 n.Stop()
4684 n.WaitForStop()
4685 require_NoError(t, fs.Stop())
4686 fs, err = newFileStore(fcfg, scfg)
4687 require_NoError(t, err)
4688 cfg = &RaftConfig{Name: "TEST", Store: storeDir, Log: fs}
4689 n, err = s.initRaftNode(globalAccountName, cfg, pprofLabels{})
4690 require_NoError(t, err)
4691
4692 // The gap between the snapshot and the WAL should be detected, and the WAL should truncate.
4693 // Can't continue normally with missing entries.
4694 state = n.wal.State()
4695 require_Equal(t, state.Msgs, 0)
4696 require_Equal(t, state.FirstSeq, 2)
4697 require_Equal(t, state.LastSeq, 1)
4698 require_Equal(t, n.pindex, 1)
4699
4700 // Should be able to re-populate the missing messages.
4701 // Need to re-encode them, though, since they would have been returned to the pool before.
4702 aeMsg2 = encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
4703 aeMsg3 = encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: entries})
4704 for i, ae := range []*appendEntry{aeMsg2, aeMsg3} {
4705 n.processAppendEntry(ae, n.aesub)
4706 require_Equal(t, n.pindex, uint64(i+2))
4707 }
4708 }
4709
4710 func TestNRGTruncateLogWithMissingSnapshot(t *testing.T) {
4711 c := createJetStreamClusterExplicit(t, "R3S", 3)
4712 s := c.servers[0] // RunBasicJetStreamServer not available
4713 defer c.shutdown()
4714
4715 storeDir := t.TempDir()
4716 fcfg := FileStoreConfig{StoreDir: storeDir, BlockSize: defaultMediumBlockSize, AsyncFlush: false, srv: s}
4717 scfg := StreamConfig{Name: "RAFT", Storage: FileStorage}
4718 fs, err := newFileStore(fcfg, scfg)
4719 require_NoError(t, err)
4720
4721 cfg := &RaftConfig{Name: "TEST", Store: storeDir, Log: fs}
4722
4723 err = s.bootstrapRaftNode(cfg, nil, false)
4724 require_NoError(t, err)
4725 n, err := s.initRaftNode(globalAccountName, cfg, pprofLabels{})
4726 require_NoError(t, err)
4727
4728 // Create a sample entry, the content doesn't matter, just that it's stored.
4729 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
4730 entries := []*Entry{newEntry(EntryNormal, esm)}
4731
4732 nats0 := "S1Nunr6R" // "nats-0"
4733
4734 // Timeline
4735 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
4736 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
4737 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: entries})
4738
4739 for i, ae := range []*appendEntry{aeMsg1, aeMsg2, aeMsg3} {
4740 n.processAppendEntry(ae, n.aesub)
4741 require_Equal(t, n.pindex, uint64(i+1))
4742 }
4743
4744 // Manually simulate a snapshot being made, only compacting but not actually installing a snapshot.
4745 _, err = n.wal.Compact(2)
4746 require_NoError(t, err)
4747
4748 state := n.wal.State()
4749 require_Equal(t, state.FirstSeq, 2)
4750 require_Equal(t, state.LastSeq, 3)
4751
4752 // Restart.
4753 n.Stop()
4754 n.WaitForStop()
4755 require_NoError(t, fs.Stop())
4756 fs, err = newFileStore(fcfg, scfg)
4757 require_NoError(t, err)
4758 cfg = &RaftConfig{Name: "TEST", Store: storeDir, Log: fs}
4759 n, err = s.initRaftNode(globalAccountName, cfg, pprofLabels{})
4760 require_NoError(t, err)
4761
4762 // The gap between the snapshot and the WAL should be detected, and the WAL should truncate.
4763 // Can't continue normally with missing entries.
4764 state = n.wal.State()
4765 require_Equal(t, state.Msgs, 0)
4766 require_Equal(t, state.FirstSeq, 0)
4767 require_Equal(t, state.LastSeq, 0)
4768 require_Equal(t, n.pindex, 0)
4769 }
4770
4771 // This is a RaftChainOfBlocks test where a block is proposed and then we wait for all replicas to apply it before
4772 // proposing the next one.
4773 // The test may fail if:
4774 // - Replicas hash diverge
4775 // - One replica never applies the N-th block applied by the rest
4776 // - The given number of blocks cannot be applied within some amount of time
4777 func TestNRGChainOfBlocksRunInLockstep(t *testing.T) {
4778 const iterations = 50
4779 const applyTimeout = 3 * time.Second
4780 const testTimeout = iterations * time.Second
4781
4782 c := createJetStreamClusterExplicit(t, "R3S", 3)
4783 defer c.shutdown()
4784
4785 rg := c.createRaftGroup("TEST", 3, newRaftChainStateMachine)
4786 rg.waitOnLeader()
4787
4788 testTimer := time.NewTimer(testTimeout)
4789
4790 for iteration := uint64(1); iteration <= iterations; iteration++ {
4791 select {
4792 case <-testTimer.C:
4793 t.Fatalf("Timeout, completed %d/%d iterations", iteration-1, iterations)
4794 default:
4795 // Continue
4796 }
4797
4798 // Propose the next block (this test assumes the proposal always goes through)
4799 rg.randomMember().(*RCOBStateMachine).proposeBlock()
4800
4801 var currentHash string
4802
4803 // Wait on participants to converge
4804 checkFor(t, applyTimeout, 500*time.Millisecond, func() error {
4805 var previousNodeName string
4806 var previousNodeHash string
4807 for _, sm := range rg {
4808 stateMachine := sm.(*RCOBStateMachine)
4809 nodeName := fmt.Sprintf(
4810 "%s/%s",
4811 stateMachine.server().Name(),
4812 stateMachine.node().ID(),
4813 )
4814
4815 running, blocksCount, hash := stateMachine.getCurrentHash()
4816 // All nodes always running
4817 if !running {
4818 return fmt.Errorf(
4819 "node %s is not running",
4820 nodeName,
4821 )
4822 }
4823 // Node is behind
4824 if blocksCount != iteration {
4825 return fmt.Errorf(
4826 "node %s applied %d blocks out of %d expected",
4827 nodeName,
4828 blocksCount,
4829 iteration,
4830 )
4831 }
4832 // Make sure hash is not empty
4833 if hash == "" {
4834 return fmt.Errorf(
4835 "node %s has empty hash after applying %d blocks",
4836 nodeName,
4837 blocksCount,
4838 )
4839 }
4840 // Check against previous node hash, unless this is the first node and we don't have anyone to compare
4841 if previousNodeHash != "" && previousNodeHash != hash {
4842 return fmt.Errorf(
4843 "hash mismatch after %d blocks: %s hash: %s != %s hash: %s",
4844 iteration,
4845 nodeName,
4846 hash,
4847 previousNodeName,
4848 previousNodeHash,
4849 )
4850 }
4851 // Set node name and hash for next node to compare against
4852 previousNodeName, previousNodeHash = nodeName, hash
4853
4854 }
4855 // All replicas applied the last block and their hashes match
4856 currentHash = previousNodeHash
4857 return nil
4858 })
4859 if RCOBOptions.verbose {
4860 t.Logf(
4861 "Verified chain hash %s for %d/%d nodes after %d/%d iterations",
4862 currentHash,
4863 len(rg),
4864 len(rg),
4865 iteration,
4866 iterations,
4867 )
4868 }
4869 }
4870 }
4871
4872 // This is a RaftChainOfBlocks test where one of the replicas is stopped before proposing a short burst of blocks.
4873 // Upon resuming the replica, we check it is able to catch up to the rest.
4874 // The test may fail if:
4875 // - Replicas hash diverge
4876 // - One replica never applies the N-th block applied by the rest
4877 // - The given number of blocks cannot be applied within some amount of time
4878 func TestNRGChainOfBlocksStopAndCatchUp(t *testing.T) {
4879 const iterations = 50
4880 const blocksPerIteration = 3
4881 const applyTimeout = 3 * time.Second
4882 const testTimeout = 2 * iterations * time.Second
4883
4884 c := createJetStreamClusterExplicit(t, "R3S", 3)
4885 defer c.shutdown()
4886
4887 rg := c.createRaftGroup("TEST", 3, newRaftChainStateMachine)
4888 rg.waitOnLeader()
4889
4890 testTimer := time.NewTimer(testTimeout)
4891 highestBlockSeen := uint64(0)
4892
4893 for iteration := uint64(1); iteration <= iterations; iteration++ {
4894
4895 select {
4896 case <-testTimer.C:
4897 t.Fatalf("Timeout, completed %d/%d iterations", iteration-1, iterations)
4898 default:
4899 // Continue
4900 }
4901
4902 // Stop a random node
4903 stoppedNode := rg.randomMember()
4904 leader := stoppedNode.node().Leader()
4905 stoppedNode.stop()
4906
4907 // Snapshot a random (non-stopped) node
4908 snapshotNode := rg.randomMember()
4909 for snapshotNode == stoppedNode {
4910 snapshotNode = rg.randomMember()
4911 }
4912 snapshotNode.(*RCOBStateMachine).createSnapshot()
4913
4914 if RCOBOptions.verbose {
4915 t.Logf(
4916 "Iteration %d/%d: stopping node: %s/%s (leader: %v)",
4917 iteration,
4918 iterations,
4919 stoppedNode.server().Name(),
4920 stoppedNode.node().ID(),
4921 leader,
4922 )
4923 }
4924
4925 // Propose some new blocks
4926 rg.waitOnLeader()
4927 for i := 0; i < blocksPerIteration; i++ {
4928 proposer := rg.randomMember()
4929 // Pick again if we randomly chose the stopped node
4930 for proposer == stoppedNode {
4931 proposer = rg.randomMember()
4932 }
4933
4934 proposer.(*RCOBStateMachine).proposeBlock()
4935 }
4936
4937 // Restart the stopped node
4938 stoppedNode.restart()
4939
4940 // Wait on participants to converge
4941 expectedBlocks := iteration * blocksPerIteration
4942 var currentHash string
4943 checkFor(t, applyTimeout, 250*time.Millisecond, func() error {
4944 var previousNodeName string
4945 var previousNodeHash string
4946 for _, sm := range rg {
4947 stateMachine := sm.(*RCOBStateMachine)
4948 nodeName := fmt.Sprintf(
4949 "%s/%s",
4950 stateMachine.server().Name(),
4951 stateMachine.node().ID(),
4952 )
4953 running, blocksCount, currentHash := stateMachine.getCurrentHash()
4954 // Track the highest block seen by any replica
4955 if blocksCount > highestBlockSeen {
4956 highestBlockSeen = blocksCount
4957 // Must check all replicas again
4958 return fmt.Errorf("updated highest block to %d (%s)", highestBlockSeen, nodeName)
4959 }
4960 // All nodes should be running
4961 if !running {
4962 return fmt.Errorf(
4963 "node %s not running",
4964 nodeName,
4965 )
4966 }
4967 // Node is behind
4968 if blocksCount != expectedBlocks {
4969 return fmt.Errorf(
4970 "node %s applied %d blocks out of %d expected",
4971 nodeName,
4972 blocksCount,
4973 expectedBlocks,
4974 )
4975 }
4976 // Make sure hash is not empty
4977 if currentHash == "" {
4978 return fmt.Errorf(
4979 "node %s has empty hash after applying %d blocks",
4980 nodeName,
4981 blocksCount,
4982 )
4983 }
4984 // Check against previous node hash, unless this is the first node to be checked
4985 if previousNodeHash != "" && previousNodeHash != currentHash {
4986 return fmt.Errorf(
4987 "hash mismatch after %d blocks: %s hash: %s != %s hash: %s",
4988 expectedBlocks,
4989 nodeName,
4990 currentHash,
4991 previousNodeName,
4992 previousNodeHash,
4993 )
4994 }
4995 // Set node name and hash for next node to compare against
4996 previousNodeName, previousNodeHash = nodeName, currentHash
4997 }
4998 // All is well
4999 currentHash = previousNodeHash
5000 return nil
5001 })
5002
5003 if RCOBOptions.verbose {
5004 t.Logf(
5005 "Verified chain hash %s for %d/%d nodes after %d blocks, %d/%d iterations (%d lost proposals)",
5006 currentHash,
5007 len(rg),
5008 len(rg),
5009 highestBlockSeen,
5010 iteration,
5011 iterations,
5012 expectedBlocks-highestBlockSeen,
5013 )
5014 }
5015 }
5016 }
5017
5018 func TestNRGProposeRemovePeer(t *testing.T) {
5019 c := createJetStreamClusterExplicit(t, "R3S", 3)
5020 defer c.shutdown()
5021
5022 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5023 rg.waitOnLeader()
5024
5025 n := rg.leader().node()
5026 rg.waitOnLeader()
5027
5028 peerId := rg.nonLeader().node().ID()
5029 require_NoError(t, n.ProposeRemovePeer(peerId))
5030
5031 checkFor(t, 10*time.Second, 200*time.Millisecond, func() error {
5032 var err error
5033 for _, r := range rg {
5034 if len(r.node().Peers()) != 2 {
5035 err = errors.New("has not removed peer")
5036 break
5037 }
5038
5039 }
5040 return err
5041 })
5042 }
5043
5044 func TestNRGProposeRemovePeerNonExistent(t *testing.T) {
5045 c := createJetStreamClusterExplicit(t, "R3S", 3)
5046 defer c.shutdown()
5047
5048 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5049 rg.waitOnLeader()
5050
5051 leader := rg.leader().node().(*raft)
5052
5053 const bogus = "deadbeef" // 8 chars, matches idLen
5054 leader.RLock()
5055 _, exists := leader.peers[bogus]
5056 leader.RUnlock()
5057 require_False(t, exists)
5058
5059 // Removing a peer not in the group should fail synchronously and have no side effects.
5060 require_Error(t, leader.ProposeRemovePeer(bogus), errPeerNotFound)
5061 require_False(t, leader.MembershipChangeInProgress())
5062
5063 for _, r := range rg {
5064 n := r.node().(*raft)
5065 n.RLock()
5066 _, removed := n.removed[bogus]
5067 n.RUnlock()
5068 require_False(t, removed)
5069 require_Equal(t, len(r.node().Peers()), 3)
5070 }
5071
5072 // A real removal still works afterward.
5073 realPeer := rg.nonLeader().node().ID()
5074 require_NoError(t, leader.ProposeRemovePeer(realPeer))
5075 checkFor(t, 2*time.Second, 200*time.Millisecond, func() error {
5076 for _, r := range rg {
5077 if len(r.node().Peers()) != 2 {
5078 return errors.New("has not removed peer")
5079 }
5080 }
5081 return nil
5082 })
5083 }
5084
5085 func TestNRGForwardedRemovePeerProposalNonExistent(t *testing.T) {
5086 c := createJetStreamClusterExplicit(t, "R3S", 3)
5087 defer c.shutdown()
5088
5089 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5090 rg.waitOnLeader()
5091
5092 leader := rg.leader().node().(*raft)
5093 follower := rg.nonLeader().node()
5094
5095 const bogus = "deadbeef" // 8 chars, matches idLen
5096 leader.RLock()
5097 _, exists := leader.peers[bogus]
5098 leader.RUnlock()
5099 require_False(t, exists)
5100
5101 // ProposeRemovePeer on a follower forwards to the leader's
5102 // handleForwardedRemovePeerProposal. The follower returns nil regardless,
5103 // so we have to inspect the leader directly for the side effects.
5104 require_NoError(t, follower.ProposeRemovePeer(bogus))
5105
5106 // Give the forwarded RPC plenty of time to arrive and (incorrectly) take
5107 // effect if the existence check were missing. With the check, no
5108 // membership change is queued and the removed map stays clean.
5109 time.Sleep(500 * time.Millisecond)
5110
5111 require_False(t, leader.MembershipChangeInProgress())
5112 for _, r := range rg {
5113 n := r.node().(*raft)
5114 n.RLock()
5115 _, removed := n.removed[bogus]
5116 n.RUnlock()
5117 require_False(t, removed)
5118 require_Equal(t, len(r.node().Peers()), 3)
5119 }
5120
5121 // A real forwarded removal still works.
5122 realPeer := follower.ID()
5123 require_NoError(t, follower.ProposeRemovePeer(realPeer))
5124 checkFor(t, 2*time.Second, 200*time.Millisecond, func() error {
5125 for _, r := range rg {
5126 if len(r.node().Peers()) != 2 {
5127 return errors.New("has not removed peer")
5128 }
5129 }
5130 return nil
5131 })
5132 }
5133
5134 func TestNRGProposeRemovePeerConcurrent(t *testing.T) {
5135 c := createJetStreamClusterExplicit(t, "R3S", 3)
5136 defer c.shutdown()
5137
5138 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5139 rg.waitOnLeader()
5140
5141 n := rg.leader().node()
5142
5143 locked := rg.lockFollowers()
5144
5145 // Attempt to remove the first follower, should succeed.
5146 err := n.ProposeRemovePeer(locked[0].node().ID())
5147 require_NoError(t, err)
5148
5149 // Check that membership change is in progress.
5150 checkFor(t, 2*time.Second, 200*time.Millisecond, func() error {
5151 if n.MembershipChangeInProgress() {
5152 return nil
5153 } else {
5154 return errors.New("membership not in progress")
5155 }
5156 })
5157
5158 // Attempt to remove the second follower, should fail.
5159 err = n.ProposeRemovePeer(locked[1].node().ID())
5160 require_Error(t, err, errMembershipChange)
5161
5162 for _, l := range locked {
5163 l.node().(*raft).Unlock()
5164 }
5165
5166 // Expect only one peer removal to succeed
5167 checkFor(t, 10*time.Second, 200*time.Millisecond, func() error {
5168 var err error
5169 for _, r := range rg {
5170 if len(r.node().Peers()) != 2 {
5171 err = errors.New("has not removed peer")
5172 break
5173 }
5174
5175 }
5176 return err
5177 })
5178 }
5179
5180 func TestNRGUncommittedMembershipChangeOnNewLeader(t *testing.T) {
5181 n, cleanup := initSingleMemRaftNode(t)
5182 defer cleanup()
5183
5184 nats1 := "yrzKKRBu" // "nats-1"
5185 nats2 := "cnrtt3eg" // "nats-2"
5186
5187 n.Lock()
5188 n.addPeer(nats1)
5189 n.addPeer(nats2)
5190 n.Unlock()
5191
5192 entries := []*Entry{newEntry(EntryRemovePeer, []byte(nats2))}
5193 aeRemovePeer := encode(t, &appendEntry{leader: nats1, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5194
5195 // plant a EntryRemovePeer in the log
5196 n.processAppendEntry(aeRemovePeer, n.aesub)
5197 require_Equal(t, n.pindex, 1)
5198 require_False(t, n.Healthy())
5199
5200 // become the new leader
5201 n.term = 2
5202 n.switchToLeader()
5203
5204 err := n.ProposeRemovePeer(nats1)
5205 require_Error(t, err, errMembershipChange)
5206 }
5207
5208 func TestNRGUncommittedMembershipChangeGetsTruncated(t *testing.T) {
5209 n, cleanup := initSingleMemRaftNode(t)
5210 defer cleanup()
5211
5212 nats1 := "yrzKKRBu" // "nats-1"
5213
5214 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
5215 entries := []*Entry{newEntry(EntryNormal, esm)}
5216 aeMsg := encode(t, &appendEntry{leader: nats1, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5217 entries = []*Entry{newEntry(EntryAddPeer, []byte(nats1))}
5218 aeAddPeer := encode(t, &appendEntry{leader: nats1, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
5219
5220 // Set up a membership change.
5221 n.processAppendEntry(aeMsg, n.aesub)
5222 n.processAppendEntry(aeAddPeer, n.aesub)
5223 require_Equal(t, n.pindex, 2)
5224 require_True(t, n.MembershipChangeInProgress())
5225 require_Equal(t, n.membChange.index, 2)
5226
5227 // If the entry containing the membership change isn't truncated, it should remain in progress.
5228 n.truncateWAL(n.pterm, n.pindex)
5229 require_True(t, n.MembershipChangeInProgress())
5230 require_Equal(t, n.membChange.index, 2)
5231
5232 // If the entry IS truncated, then it shouldn't be in progress anymore.
5233 n.truncateWAL(n.pterm, n.pindex-1)
5234 require_False(t, n.MembershipChangeInProgress())
5235 require_True(t, n.membChange == nil)
5236 }
5237
5238 func TestNRGUncommittedMembershipChangeOnNewLeaderForwardedRemovePeerProposal(t *testing.T) {
5239 n, cleanup := initSingleMemRaftNode(t)
5240 defer cleanup()
5241
5242 nats1 := "yrzKKRBu" // "nats-1"
5243 nats2 := "cnrtt3eg" // "nats-2"
5244
5245 n.Lock()
5246 n.addPeer(nats1)
5247 n.addPeer(nats2)
5248 n.Unlock()
5249
5250 entries := []*Entry{newEntry(EntryRemovePeer, []byte(nats2))}
5251 aeRemovePeer := encode(t, &appendEntry{leader: nats1, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5252
5253 // plant a EntryRemovePeer in the log
5254 n.processAppendEntry(aeRemovePeer, n.aesub)
5255 require_Equal(t, n.pindex, 1)
5256 require_False(t, n.Healthy())
5257
5258 // become the new leader
5259 n.term = 2
5260 n.switchToLeader()
5261 n.leaderState.Store(true)
5262 var wg sync.WaitGroup
5263 wg.Add(1)
5264 go func() {
5265 defer wg.Done()
5266 n.runAsLeader()
5267 }()
5268 defer wg.Wait()
5269
5270 n.RLock()
5271 rpsubj := n.rpsubj
5272 n.RUnlock()
5273
5274 nc, _ := jsClientConnect(t, n.s, nats.UserInfo("admin", "s3cr3t!"))
5275 defer nc.Close()
5276
5277 // Forward a peer-remove proposal to the new leader.
5278 before, _, _ := n.Progress()
5279 require_True(t, n.MembershipChangeInProgress())
5280 checkFor(t, 2*time.Second, 200*time.Millisecond, func() error {
5281 _, err := nc.Request(rpsubj, []byte(nats1), 100*time.Millisecond)
5282 // Wait for the server to be subscribed and either respond or time out.
5283 if err == nil || errors.Is(err, nats.ErrTimeout) {
5284 return nil
5285 }
5286 return err
5287 })
5288 // The forwarded peer-remove should not be accepted.
5289 time.Sleep(200 * time.Millisecond)
5290 after, _, _ := n.Progress()
5291 require_Equal(t, before, after)
5292 require_True(t, n.MembershipChangeInProgress())
5293 }
5294
5295 func TestNRGIgnoreForwardedProposalIfNotCaughtUpLeader(t *testing.T) {
5296 n, cleanup := initSingleMemRaftNode(t)
5297 defer cleanup()
5298
5299 nats1 := "yrzKKRBu" // "nats-1"
5300 nats2 := "cnrtt3eg" // "nats-2"
5301
5302 n.Lock()
5303 n.addPeer(nats1)
5304 n.addPeer(nats2)
5305 n.Unlock()
5306
5307 n.term = 1
5308 n.switchToLeader()
5309 var wg sync.WaitGroup
5310 wg.Add(1)
5311 go func() {
5312 defer wg.Done()
5313 n.runAsLeader()
5314 }()
5315 defer wg.Wait()
5316
5317 n.RLock()
5318 // Although this server is the leader, mark it as not caught up yet.
5319 n.leaderState.Store(false)
5320 psubj := n.psubj
5321 n.RUnlock()
5322
5323 nc, _ := jsClientConnect(t, n.s, nats.UserInfo("admin", "s3cr3t!"))
5324 defer nc.Close()
5325
5326 // Forward a normal proposal to the new leader.
5327 before, _, _ := n.Progress()
5328 checkFor(t, 2*time.Second, 200*time.Millisecond, func() error {
5329 _, err := nc.Request(psubj, nil, 100*time.Millisecond)
5330 // Wait for the server to be subscribed and either respond or time out.
5331 if err == nil || errors.Is(err, nats.ErrTimeout) {
5332 return nil
5333 }
5334 return err
5335 })
5336 // The forwarded proposal should not be accepted.
5337 time.Sleep(200 * time.Millisecond)
5338 after, _, _ := n.Progress()
5339 require_Equal(t, before, after)
5340 }
5341
5342 func TestNRGProposeRemovePeerQuorum(t *testing.T) {
5343 c := createJetStreamClusterExplicit(t, "R3S", 3)
5344 defer c.shutdown()
5345
5346 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5347 rg.waitOnLeader()
5348
5349 leader := rg.leader().node()
5350 followers := rg.followers()
5351
5352 require_True(t, len(followers) == 2)
5353
5354 // Block follower 0 and remove follower 1
5355 followers[0].node().(*raft).Lock()
5356 err := leader.ProposeRemovePeer(followers[1].node().ID())
5357 require_NoError(t, err)
5358
5359 // Should not be able to make progress
5360 time.Sleep(time.Second)
5361 require_True(t, leader.MembershipChangeInProgress())
5362
5363 // Unlock the other follower and expect the membership
5364 // change to eventually finish
5365 followers[0].node().(*raft).Unlock()
5366 checkFor(t, 10*time.Second, 200*time.Millisecond, func() error {
5367 if leader.MembershipChangeInProgress() {
5368 return errors.New("membership still in progress")
5369 } else {
5370 return nil
5371 }
5372 })
5373 }
5374
5375 // Test outline:
5376 // - In a R3 cluster, PeerRemove the leader and block on of
5377 // the followers.
5378 // - Verify that the membership change can't make progress,
5379 // the leader should not count its own ack towards quorum.
5380 // - Release the previously blocked follower and expect the
5381 // membership change to take place.
5382 func TestNRGProposeRemovePeerLeader(t *testing.T) {
5383 c := createJetStreamClusterExplicit(t, "R3S", 3)
5384 defer c.shutdown()
5385
5386 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5387 rg.waitOnLeader()
5388
5389 leader := rg.leader().node()
5390 followers := rg.followers()
5391 leaderID := leader.ID()
5392 require_True(t, len(followers) == 2)
5393
5394 // Block follower 0 and remove the leader
5395 followers[0].node().(*raft).Lock()
5396 err := leader.ProposeRemovePeer(leader.ID())
5397 require_NoError(t, err)
5398
5399 // Should not be able to make progress
5400 time.Sleep(time.Second)
5401 require_True(t, leader.MembershipChangeInProgress())
5402
5403 // Unlock the follower and expect the membership
5404 // change to eventually finish
5405 followers[0].node().(*raft).Unlock()
5406 checkFor(t, 10*time.Second, 200*time.Millisecond, func() error {
5407 if leader.MembershipChangeInProgress() {
5408 return errors.New("membership still in progress")
5409 } else {
5410 return nil
5411 }
5412 })
5413
5414 // Old leader steps down
5415 checkFor(t, 10*time.Second, 200*time.Millisecond, func() error {
5416 newLeader := rg.waitOnLeader()
5417 if newLeader.node().ID() == leaderID {
5418 return errors.New("leader has not changed yet")
5419 }
5420 return nil
5421 })
5422
5423 newLeader := rg.waitOnLeader()
5424 require_Equal(t, leader.State(), Closed)
5425 require_NotEqual(t, leader.ID(), newLeader.node().ID())
5426 require_Equal(t, len(newLeader.node().Peers()), 2)
5427 require_False(t, newLeader.node().MembershipChangeInProgress())
5428 }
5429
5430 func TestNRGProposeRemovePeerAll(t *testing.T) {
5431 c := createJetStreamClusterExplicit(t, "R3S", 3)
5432 defer c.shutdown()
5433
5434 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5435 rg.waitOnLeader()
5436
5437 leader := rg.leader()
5438 followers := rg.followers()
5439 require_Equal(t, len(followers), 2)
5440
5441 peers := leader.node().Peers()
5442 require_Equal(t, len(peers), 3)
5443 for i, follower := range followers {
5444 require_NoError(t, leader.node().ProposeRemovePeer(follower.node().ID()))
5445 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
5446 if peers = leader.node().Peers(); len(peers) == 2-i {
5447 return nil
5448 }
5449 return errors.New("membership still in progress")
5450 })
5451 }
5452
5453 peers = leader.node().Peers()
5454 leaderID := leader.node().ID()
5455
5456 // The leader is the only one left...
5457 require_Equal(t, len(peers), 1)
5458 require_Equal(t, peers[0].ID, leaderID)
5459 // and we can't remove it
5460 require_Error(t, leader.node().ProposeRemovePeer(leaderID), errRemoveLastNode)
5461 }
5462
5463 func TestNRGLeaderResurrectsRemovedPeers(t *testing.T) {
5464 c := createJetStreamClusterExplicit(t, "R3S", 3)
5465 defer c.shutdown()
5466
5467 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5468 rg.waitOnLeader()
5469
5470 leader := rg.leader()
5471 followers := rg.followers()
5472 require_Equal(t, len(followers), 2)
5473
5474 // Remove one follower
5475 require_NoError(t, leader.node().ProposeRemovePeer(followers[0].node().ID()))
5476 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
5477 if peers := leader.node().Peers(); len(peers) == 2 {
5478 return nil
5479 }
5480 return errors.New("membership still in progress")
5481 })
5482
5483 // Stop the leader and restart it.
5484 // If bug is present: the leader resurrects the previously removed peer.
5485 leader.stop()
5486 followers[1].stop()
5487
5488 leader.restart()
5489 require_Equal(t, len(leader.node().Peers()), 2)
5490
5491 followers[1].restart()
5492 require_Equal(t, len(leader.node().Peers()), 2)
5493 }
5494
5495 func TestNRGAddPeers(t *testing.T) {
5496 c := createJetStreamClusterExplicit(t, "R3S", 3)
5497 defer c.shutdown()
5498
5499 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5500 leader := rg.waitOnLeader()
5501
5502 require_Equal(t, leader.node().ClusterSize(), 3)
5503
5504 for range 6 {
5505 rg = append(rg, c.addMemRaftNode("TEST", newStateAdder))
5506 }
5507
5508 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
5509 if leader.node().ClusterSize() != 9 {
5510 return errors.New("node additions still in progress")
5511 }
5512 return nil
5513 })
5514
5515 require_Equal(t, leader.node().ClusterSize(), 9)
5516 }
5517
5518 func TestNRGDisjointMajorities(t *testing.T) {
5519 c := createJetStreamClusterExplicit(t, "R3S", 3)
5520 defer c.shutdown()
5521
5522 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5523 rg.waitOnLeader()
5524
5525 leader := rg.leader()
5526 followers := rg.followers()
5527 require_Equal(t, len(followers), 2)
5528
5529 // Lock all followers, a majority.
5530 locked := rg.lockFollowers()
5531 require_Equal(t, len(locked), 2)
5532
5533 defer func() {
5534 for _, l := range locked {
5535 l.node().(*raft).Unlock()
5536 }
5537 }()
5538
5539 // Add one node (cluster size is 4)
5540 c.addMemRaftNode("TEST", newStateAdder)
5541
5542 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
5543 if leader.node().ClusterSize() != 4 {
5544 return errors.New("node addition still in progress")
5545 }
5546 return nil
5547 })
5548
5549 // Attempt another node addition
5550 c.addMemRaftNode("TEST", newStateAdder)
5551
5552 // If bug is present:
5553 // The leader is able to form a majority because it would
5554 // add peers immediately, and readjust cluster size and
5555 // quorum only after committing EntryAddPeer. This allowed
5556 // the leader to commit the entries using only newly added
5557 // nodes (the original followers are locked and not
5558 // acknowledging the EntryAddPeer proposals!)
5559 // This should not never happen. In a real scenario the
5560 // followers could be partitioned, and they actually have
5561 // a majority... so they could diverge and we end up with
5562 // two different histories.
5563 //
5564 // Here wait a little bit, and check that the leader is
5565 // unable to make any progess.
5566 time.Sleep(time.Second)
5567
5568 require_Equal(t, leader.node().ClusterSize(), 4)
5569 require_Equal(t, leader.node().MembershipChangeInProgress(), true)
5570 }
5571
5572 func TestNRGAppendEntryResurrectsLeader(t *testing.T) {
5573 n, cleanup := initSingleMemRaftNode(t)
5574 defer cleanup()
5575
5576 S2 := "z3WIzPtj" // S-2
5577
5578 n.Lock()
5579 n.addPeer(S2)
5580 n.Unlock()
5581 require_Len(t, len(n.Peers()), 2)
5582 require_Equal(t, n.ClusterSize(), 2)
5583
5584 // PeerRemove S2
5585 entries := []*Entry{newEntry(EntryRemovePeer, []byte(S2))}
5586 aeRemovePeer := encode(t, &appendEntry{
5587 leader: S2, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5588 n.processAppendEntry(aeRemovePeer, n.aesub)
5589
5590 // Heartbeat commits the PeerRemove
5591 aeHeartBeat := encode(t, &appendEntry{
5592 leader: S2, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
5593 n.processAppendEntry(aeHeartBeat, n.aesub)
5594
5595 require_Len(t, len(n.Peers()), 1)
5596 require_Equal(t, n.ClusterSize(), 1)
5597
5598 // If bug is present: receiving a appendEntry from the old leader
5599 // will resurrect it. In practice, this has been observed with
5600 // LeaderTransfer entries, but any type of entry will do...
5601 aeHeartBeat2 := encode(t, &appendEntry{
5602 leader: S2, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
5603 n.processAppendEntry(aeHeartBeat2, n.aesub)
5604
5605 // Expect the cluster size to be unchanged
5606 require_Len(t, len(n.Peers()), 1)
5607 require_Equal(t, n.ClusterSize(), 1)
5608 }
5609
5610 func TestNRGSingleNodeElection(t *testing.T) {
5611 c := createJetStreamClusterExplicit(t, "R3S", 3)
5612 defer c.shutdown()
5613
5614 rg := c.createMemRaftGroup("TEST", 3, newStateAdder)
5615
5616 // Remove the cluster leader, and then again
5617 for range 2 {
5618 leader := rg.waitOnLeader().node()
5619 require_NoError(t, leader.ProposeRemovePeer(leader.ID()))
5620 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
5621 if leader.State() == Leader {
5622 return errors.New("Removed node is still leader")
5623 }
5624 return nil
5625 })
5626 require_False(t, leader.MembershipChangeInProgress())
5627 }
5628
5629 // The remaining follower must be able to become leader
5630 // on its own
5631 newLeader := rg.waitOnLeader()
5632 require_Equal(t, len(newLeader.node().Peers()), 1)
5633 require_Equal(t, newLeader.node().ClusterSize(), 1)
5634 require_False(t, newLeader.node().MembershipChangeInProgress())
5635
5636 adder := newLeader.(*stateAdder)
5637 adder.proposeDelta(1)
5638 adder.proposeDelta(10)
5639 adder.proposeDelta(100)
5640
5641 rg.waitOnTotal(t, 111)
5642
5643 // Add two nodes back
5644 rg = append(rg, c.addMemRaftNode("TEST", newStateAdder))
5645 rg = append(rg, c.addMemRaftNode("TEST", newStateAdder))
5646
5647 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
5648 if newLeader.node().ClusterSize() != 3 {
5649 return errors.New("node additions still in progress")
5650 }
5651 return nil
5652 })
5653
5654 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
5655 if newLeader.node().MembershipChangeInProgress() {
5656 return errors.New("membership still in progress")
5657 }
5658 return nil
5659 })
5660
5661 rg.waitOnTotal(t, 111)
5662 require_Equal(t, newLeader.node().ClusterSize(), 3)
5663 require_False(t, newLeader.node().MembershipChangeInProgress())
5664 }
5665
5666 func TestNRGMustNotResetVoteOnStepDownOrLeaderTransfer(t *testing.T) {
5667 n, cleanup := initSingleMemRaftNode(t)
5668 defer cleanup()
5669
5670 nats0 := "S1Nunr6R" // "nats-0"
5671
5672 // Vote for a new leader.
5673 require_NoError(t, n.processVoteRequest(&voteRequest{term: 1, candidate: nats0}))
5674 require_Equal(t, n.term, 1)
5675 require_Equal(t, n.vote, nats0)
5676
5677 // Stepping down as leader must NOT reset the vote info.
5678 n.state.Store(int32(Leader))
5679 require_NoError(t, n.StepDown())
5680 require_Equal(t, n.vote, nats0)
5681
5682 // A leader transfer must NOT reset the vote info.
5683 // This is automatically cleared once the intended leader starts a new election with a higher term.
5684 entries := []*Entry{newEntry(EntryLeaderTransfer, []byte(nats0))}
5685 aeLeaderTransfer := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5686 n.processAppendEntry(aeLeaderTransfer, n.aesub)
5687 require_Equal(t, n.term, 1)
5688 require_Equal(t, n.vote, nats0)
5689 }
5690
5691 func TestNRGAppendEntriesSeqStopsOnRangeBreak(t *testing.T) {
5692 n, cleanup := initSingleMemRaftNode(t)
5693 defer cleanup()
5694
5695 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
5696 entries := []*Entry{newEntry(EntryNormal, esm)}
5697 nats0 := "S1Nunr6R" // "nats-0"
5698
5699 // Store and commit two entries
5700 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5701 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
5702 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2})
5703
5704 n.processAppendEntry(aeMsg1, n.aesub)
5705 n.processAppendEntry(aeMsg2, n.aesub)
5706 n.processAppendEntry(aeHeartbeat, n.aesub)
5707 n.Applied(2)
5708
5709 c, err := n.CreateSnapshotCheckpoint(false)
5710 require_NoError(t, err)
5711 defer c.Abort()
5712
5713 var calls int
5714 for ae, err := range c.AppendEntriesSeq() {
5715 calls++
5716 require_NoError(t, err)
5717 require_NotNil(t, ae)
5718 // If bug is present: the iterator keeps
5719 // yielding even if we break, causing a
5720 // runtime panic.
5721 break
5722 }
5723 require_Equal(t, calls, 1)
5724 }
5725
5726 func TestNRGInstallSnapshotFromCheckpoint(t *testing.T) {
5727 n, cleanup := initSingleMemRaftNode(t)
5728 defer cleanup()
5729
5730 // Create a sample entry, the content doesn't matter, just that it's stored.
5731 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
5732 entries := []*Entry{newEntry(EntryNormal, esm)}
5733
5734 nats0 := "S1Nunr6R" // "nats-0"
5735
5736 // Timeline
5737 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5738 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
5739 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: entries})
5740 aeMsg4 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 3, pterm: 1, pindex: 3, entries: entries})
5741 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 4, pterm: 1, pindex: 4, entries: nil})
5742
5743 // Process the first set of messages.
5744 n.processAppendEntry(aeMsg1, n.aesub)
5745 require_Equal(t, n.pindex, 1)
5746 require_Equal(t, n.commit, 0)
5747 n.processAppendEntry(aeMsg2, n.aesub)
5748 require_Equal(t, n.pindex, 2)
5749 require_Equal(t, n.commit, 1)
5750 n.Applied(1)
5751 require_Equal(t, n.applied, 1)
5752
5753 // Start the first checkpoint, creating the first snapshot.
5754 c, err := n.CreateSnapshotCheckpoint(false)
5755 require_NoError(t, err)
5756
5757 // There's no previous snapshot.
5758 buf, err := c.LoadLastSnapshot()
5759 require_Error(t, err, errNoSnapAvailable)
5760 require_True(t, buf == nil)
5761
5762 // Since only 1 entry was applied, we should be able to retrieve that here.
5763 var count int
5764 for ae, err := range c.AppendEntriesSeq() {
5765 count++
5766 require_NoError(t, err)
5767 require_Equal(t, ae.pindex, 0)
5768 }
5769 require_Equal(t, count, 1)
5770
5771 // Install the snapshot and confirm we can retrieve it.
5772 _, err = c.InstallSnapshot([]byte("old"))
5773 require_NoError(t, err)
5774 snap, err := n.loadLastSnapshot()
5775 require_NoError(t, err)
5776 require_True(t, bytes.Equal(snap.data, []byte("old")))
5777
5778 // Checkpoint was installed, so all should now abort.
5779 _, err = c.LoadLastSnapshot()
5780 require_Error(t, err, errSnapAborted)
5781 count = 0
5782 for _, err = range c.AppendEntriesSeq() {
5783 count++
5784 require_Error(t, err, errSnapAborted)
5785 }
5786 require_Equal(t, count, 1)
5787 _, err = c.InstallSnapshot(nil)
5788 require_Error(t, err, errSnapAborted)
5789
5790 // Process the next set of messages, we'll be able to compact two append entries now.
5791 n.processAppendEntry(aeMsg3, n.aesub)
5792 require_Equal(t, n.pindex, 3)
5793 require_Equal(t, n.commit, 2)
5794 n.processAppendEntry(aeMsg4, n.aesub)
5795 require_Equal(t, n.pindex, 4)
5796 require_Equal(t, n.commit, 3)
5797 n.Applied(3)
5798 require_Equal(t, n.applied, 3)
5799
5800 // Check a couple edge cases now, a second checkpoint should fail noting a snapshot is already in progress.
5801 c, err = n.CreateSnapshotCheckpoint(false)
5802 require_NoError(t, err)
5803 _, err = n.CreateSnapshotCheckpoint(false)
5804 require_Error(t, err, errSnapInProgress)
5805
5806 // Abort checkpoint, so all should now abort.
5807 c.Abort()
5808 _, err = c.LoadLastSnapshot()
5809 require_Error(t, err, errSnapAborted)
5810 count = 0
5811 for _, err = range c.AppendEntriesSeq() {
5812 count++
5813 require_Error(t, err, errSnapAborted)
5814 }
5815 require_Equal(t, count, 1) // Must always iterate at least once to retrieve the error.
5816 _, err = c.InstallSnapshot(nil)
5817 require_Error(t, err, errSnapAborted)
5818
5819 // Start the second checkpoint, creating the second snapshot.
5820 c, err = n.CreateSnapshotCheckpoint(false)
5821 require_NoError(t, err)
5822
5823 // Should load the previous snapshot.
5824 buf, err = c.LoadLastSnapshot()
5825 require_NoError(t, err)
5826 require_True(t, bytes.Equal(buf, []byte("old")))
5827
5828 // Iterate over the two append entries part of this new snapshot.
5829 count = 0
5830 for ae, err := range c.AppendEntriesSeq() {
5831 count++
5832 require_NoError(t, err)
5833 require_Equal(t, ae.pindex, uint64(count))
5834 }
5835 require_Equal(t, count, 2)
5836
5837 // Install the snapshot and confirm we can retrieve it.
5838 _, err = c.InstallSnapshot([]byte("new"))
5839 require_NoError(t, err)
5840 snap, err = n.loadLastSnapshot()
5841 require_NoError(t, err)
5842 require_True(t, bytes.Equal(snap.data, []byte("new")))
5843
5844 // Commit and apply the last entry to test for the final edge case.
5845 n.processAppendEntry(aeHeartbeat, n.aesub)
5846 require_Equal(t, n.pindex, 4)
5847 require_Equal(t, n.commit, 4)
5848 n.Applied(4)
5849 require_Equal(t, n.applied, 4)
5850
5851 // Start an async snapshot.
5852 c, err = n.CreateSnapshotCheckpoint(false)
5853 require_NoError(t, err)
5854
5855 // Installing a snapshot normally should be denied, as one is already in progress.
5856 require_Error(t, n.InstallSnapshot(nil, false), errSnapInProgress)
5857
5858 // The checkpoint should still work successfully.
5859 buf, err = c.LoadLastSnapshot()
5860 require_NoError(t, err)
5861 require_True(t, bytes.Equal(buf, []byte("new")))
5862
5863 // However, if we install using the internal API, this should be allowed and abort our checkpoint.
5864 // This API will be used as a result of receiving a snapshot as part of catchup, so it's really important
5865 // we aren't allowed to replace this newest snapshot with an older snapshot from an earlier checkpoint.
5866 snap.lastIndex++
5867 require_NoError(t, n.installSnapshot(snap))
5868
5869 // Check it's aborted.
5870 _, err = c.LoadLastSnapshot()
5871 require_Error(t, err, errSnapAborted)
5872
5873 // Check if the last snapshot was updated from underneath of us.
5874 n.Lock()
5875 n.snapshotting = true
5876 n.Unlock()
5877 _, err = c.LoadLastSnapshot()
5878 require_Error(t, err, errors.New("snapshot index mismatch"))
5879 }
5880
5881 // A forced install must be able to take over from an async snapshot that's still in
5882 // progress, otherwise a shutdown snapshot gets suppressed.
5883 func TestNRGForcedInstallSnapshotAbortsInProgressCheckpoint(t *testing.T) {
5884 n, cleanup := initSingleMemRaftNode(t)
5885 defer cleanup()
5886
5887 // Create a sample entry, the content doesn't matter, just that it's stored.
5888 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
5889 entries := []*Entry{newEntry(EntryNormal, esm)}
5890
5891 nats0 := "S1Nunr6R" // "nats-0"
5892
5893 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5894 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
5895 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2})
5896
5897 n.processAppendEntry(aeMsg1, n.aesub)
5898 n.processAppendEntry(aeMsg2, n.aesub)
5899 n.processAppendEntry(aeHeartbeat, n.aesub)
5900 n.Applied(2)
5901
5902 // An async snapshot is in progress.
5903 c, err := n.CreateSnapshotCheckpoint(false)
5904 require_NoError(t, err)
5905
5906 // Without forcing we can't snapshot, this is what would suppress a shutdown snapshot.
5907 require_Error(t, n.InstallSnapshot([]byte("blocked"), false), errSnapInProgress)
5908
5909 // Forcing installs directly, which aborts the checkpoint that was in progress.
5910 require_NoError(t, n.InstallSnapshot([]byte("fresh"), true))
5911
5912 // The aborted checkpoint must not be able to install or read anything anymore.
5913 _, err = c.LoadLastSnapshot()
5914 require_Error(t, err, errSnapAborted)
5915 _, err = c.InstallSnapshot([]byte("stale"))
5916 require_Error(t, err, errSnapAborted)
5917
5918 // And its late abort must not cancel anything installed after it.
5919 c.Abort()
5920
5921 snap, err := n.loadLastSnapshot()
5922 require_NoError(t, err)
5923 require_True(t, bytes.Equal(snap.data, []byte("fresh")))
5924
5925 // The aborted checkpoint targets the same file for the same term/applied index, so
5926 // it must not have written anything, not even a temporary file it never renamed.
5927 files, err := os.ReadDir(filepath.Join(n.sd, snapshotsDir))
5928 require_NoError(t, err)
5929 require_Len(t, len(files), 1)
5930 require_Equal(t, files[0].Name(), fmt.Sprintf(snapFileT, 1, 2))
5931 }
5932
5933 // A direct install must wait for a snapshot write that's already in flight. The async
5934 // install path releases the Raft lock while writing, and both would target the same
5935 // file, and the same temporary file it's renamed from.
5936 func TestNRGDirectInstallSnapshotWaitsForInFlightWrite(t *testing.T) {
5937 n, cleanup := initSingleMemRaftNode(t)
5938 defer cleanup()
5939
5940 // Create a sample entry, the content doesn't matter, just that it's stored.
5941 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
5942 entries := []*Entry{newEntry(EntryNormal, esm)}
5943
5944 nats0 := "S1Nunr6R" // "nats-0"
5945
5946 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5947 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
5948 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2})
5949
5950 n.processAppendEntry(aeMsg1, n.aesub)
5951 n.processAppendEntry(aeMsg2, n.aesub)
5952 n.processAppendEntry(aeHeartbeat, n.aesub)
5953 n.Applied(2)
5954
5955 // Stand in for a checkpoint that's in the middle of writing its snapshot file.
5956 n.snapLock.Lock()
5957
5958 installed := make(chan error, 1)
5959 go func() {
5960 installed <- n.InstallSnapshot([]byte("fresh"), true)
5961 }()
5962
5963 select {
5964 case err := <-installed:
5965 t.Fatalf("Expected install to wait for the in-flight snapshot write, got %v", err)
5966 case <-time.After(250 * time.Millisecond):
5967 }
5968
5969 n.snapLock.Unlock()
5970 require_NoError(t, <-installed)
5971
5972 snap, err := n.loadLastSnapshot()
5973 require_NoError(t, err)
5974 require_True(t, bytes.Equal(snap.data, []byte("fresh")))
5975 }
5976
5977 // An async install must claim the snapshot write lock before it gives up the Raft lock,
5978 // otherwise a direct install could slip in between its checks and its write.
5979 func TestNRGCheckpointInstallSnapshotWaitsForInFlightWrite(t *testing.T) {
5980 n, cleanup := initSingleMemRaftNode(t)
5981 defer cleanup()
5982
5983 // Create a sample entry, the content doesn't matter, just that it's stored.
5984 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
5985 entries := []*Entry{newEntry(EntryNormal, esm)}
5986
5987 nats0 := "S1Nunr6R" // "nats-0"
5988
5989 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
5990 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
5991 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2})
5992
5993 n.processAppendEntry(aeMsg1, n.aesub)
5994 n.processAppendEntry(aeMsg2, n.aesub)
5995 n.processAppendEntry(aeHeartbeat, n.aesub)
5996 n.Applied(2)
5997
5998 c, err := n.CreateSnapshotCheckpoint(false)
5999 require_NoError(t, err)
6000
6001 snapDir := filepath.Join(n.sd, snapshotsDir)
6002
6003 // Stand in for another snapshot write that's already in flight.
6004 n.snapLock.Lock()
6005
6006 installed := make(chan error, 1)
6007 go func() {
6008 _, err := c.InstallSnapshot([]byte("async"))
6009 installed <- err
6010 }()
6011
6012 // Must not have written anything yet, not even a temporary file.
6013 time.Sleep(250 * time.Millisecond)
6014 files, err := os.ReadDir(snapDir)
6015 require_NoError(t, err)
6016 require_Len(t, len(files), 0)
6017
6018 n.snapLock.Unlock()
6019 require_NoError(t, <-installed)
6020
6021 snap, err := n.loadLastSnapshot()
6022 require_NoError(t, err)
6023 require_True(t, bytes.Equal(snap.data, []byte("async")))
6024 }
6025
6026 func TestNRGSnapshotCheckpointNodeClosed(t *testing.T) {
6027 for _, test := range []struct {
6028 title string
6029 close func(n *raft)
6030 }{
6031 {title: "Stop", close: func(n *raft) { n.Stop() }},
6032 {title: "Delete", close: func(n *raft) { n.Delete() }},
6033 } {
6034 t.Run(test.title, func(t *testing.T) {
6035 n, cleanup := initSingleMemRaftNode(t)
6036 defer cleanup()
6037
6038 // Create a sample entry, the content doesn't matter, just that it's stored.
6039 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
6040 entries := []*Entry{newEntry(EntryNormal, esm)}
6041
6042 nats0 := "S1Nunr6R" // "nats-0"
6043
6044 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
6045 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
6046
6047 n.processAppendEntry(aeMsg, n.aesub)
6048 n.processAppendEntry(aeHeartbeat, n.aesub)
6049 require_Equal(t, n.commit, 1)
6050 n.Applied(1)
6051 require_Equal(t, n.applied, 1)
6052
6053 // Create the checkpoint while the node is still healthy.
6054 c, err := n.CreateSnapshotCheckpoint(false)
6055 require_NoError(t, err)
6056
6057 // Stop/delete the node.
6058 test.close(n)
6059
6060 // All checkpoint paths must now report the node as closed.
6061 _, err = c.LoadLastSnapshot()
6062 require_Error(t, err, errNodeClosed)
6063 var count int
6064 for _, err = range c.AppendEntriesSeq() {
6065 count++
6066 require_Error(t, err, errNodeClosed)
6067 }
6068 require_Equal(t, count, 1) // Must always iterate at least once to retrieve the error.
6069 _, err = c.InstallSnapshot(nil)
6070 require_Error(t, err, errNodeClosed)
6071 })
6072 }
6073 }
6074
6075 func TestNRGDrainAndReplaySnapshotNodeClosed(t *testing.T) {
6076 for _, test := range []struct {
6077 title string
6078 close func(n *raft)
6079 replay bool
6080 }{
6081 {title: "Stop", close: func(n *raft) { n.Stop() }, replay: true},
6082 {title: "Delete", close: func(n *raft) { n.Delete() }, replay: false},
6083 } {
6084 t.Run(test.title, func(t *testing.T) {
6085 n, cleanup := initSingleMemRaftNode(t)
6086 defer cleanup()
6087
6088 // Create a sample entry, the content doesn't matter, just that it's stored.
6089 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
6090 entries := []*Entry{newEntry(EntryNormal, esm)}
6091
6092 nats0 := "S1Nunr6R" // "nats-0"
6093
6094 // Timeline, the second message ups the pterm so we can snapshot on the first.
6095 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
6096 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
6097 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 2, commit: 1, pterm: 1, pindex: 1, entries: entries})
6098
6099 n.processAppendEntry(aeMsg1, n.aesub)
6100 n.processAppendEntry(aeHeartbeat, n.aesub)
6101 require_Equal(t, n.commit, 1)
6102 n.Applied(1)
6103 n.processAppendEntry(aeMsg2, n.aesub)
6104
6105 // Snapshot, so we have something to replay.
6106 require_NoError(t, n.InstallSnapshot(nil, false))
6107 require_True(t, n.snapfile != _EMPTY_)
6108 sfile := n.snapfile
6109 sdata, err := os.ReadFile(sfile)
6110 require_NoError(t, err)
6111
6112 test.close(n)
6113
6114 if test.replay {
6115 require_True(t, n.snapfile != _EMPTY_)
6116 require_True(t, n.DrainAndReplaySnapshot())
6117 return
6118 }
6119
6120 // Delete must not leave us pointing at a file it just removed.
6121 require_Equal(t, n.snapfile, _EMPTY_)
6122 require_False(t, n.DrainAndReplaySnapshot())
6123
6124 // Snapshot filenames are only "snap.<term>.<index>", so a later
6125 // incarnation of a same-named group can recreate this exact path.
6126 // Even then a deleted node must refuse to replay, or we'd adopt
6127 // another generation's state.
6128 require_NoError(t, os.MkdirAll(filepath.Dir(sfile), defaultDirPerms))
6129 require_NoError(t, os.WriteFile(sfile, sdata, defaultFilePerms))
6130 n.snapfile = sfile
6131 require_False(t, n.DrainAndReplaySnapshot())
6132 })
6133 }
6134 }
6135
6136 func TestNRGInstallSnapshotForce(t *testing.T) {
6137 n, cleanup := initSingleMemRaftNode(t)
6138 defer cleanup()
6139
6140 // Create a sample entry, the content doesn't matter, just that it's stored.
6141 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
6142 entries := []*Entry{newEntry(EntryNormal, esm)}
6143
6144 nats0 := "S1Nunr6R" // "nats-0"
6145
6146 // Timeline
6147 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
6148 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
6149
6150 n.processAppendEntry(aeMsg, n.aesub)
6151 require_Equal(t, n.pindex, 1)
6152 require_Equal(t, n.commit, 0)
6153 n.processAppendEntry(aeHeartbeat, n.aesub)
6154 require_Equal(t, n.pindex, 1)
6155 require_Equal(t, n.commit, 1)
6156 n.Applied(1)
6157 require_Equal(t, n.applied, 1)
6158
6159 // Block snapshots unless they're forced to skip in-progress catchups.
6160 n.progress = make(map[string]*ipQueue[uint64])
6161 n.progress["blockSnapshots"] = newIPQueue[uint64](n.s, "blockSnapshots")
6162
6163 require_Error(t, n.InstallSnapshot(nil, false), errCatchupsRunning)
6164 require_Equal(t, n.papplied, 0)
6165
6166 require_NoError(t, n.InstallSnapshot(nil, true))
6167 require_Equal(t, n.papplied, 1)
6168 }
6169
6170 func TestNRGInstallSnapshotFromCheckpointAfterTruncateToSnapshot(t *testing.T) {
6171 n, cleanup := initSingleMemRaftNode(t)
6172 defer cleanup()
6173
6174 // Create a sample entry, the content doesn't matter, just that it's stored.
6175 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
6176 entries := []*Entry{newEntry(EntryNormal, esm)}
6177
6178 nats0 := "S1Nunr6R" // "nats-0"
6179
6180 // Timeline
6181 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
6182 aeHeartbeat1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
6183 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 100, pterm: 1, pindex: 100, entries: entries})
6184 aeHeartbeat2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 101, pterm: 1, pindex: 101, entries: nil})
6185
6186 // Process the first message.
6187 n.processAppendEntry(aeMsg1, n.aesub)
6188 require_Equal(t, n.pindex, 1)
6189 require_Equal(t, n.commit, 0)
6190 n.processAppendEntry(aeHeartbeat1, n.aesub)
6191 require_Equal(t, n.pindex, 1)
6192 require_Equal(t, n.commit, 1)
6193 n.Applied(1)
6194 require_Equal(t, n.applied, 1)
6195
6196 // Install a snapshot as normal to set up papplied.
6197 require_NoError(t, n.InstallSnapshot(nil, false))
6198 require_Equal(t, n.papplied, 1)
6199
6200 // Simulate being caught up from a leader with a snapshot.
6201 snap := &snapshot{
6202 lastTerm: 1,
6203 lastIndex: 100,
6204 peerstate: encodePeerState(n.currentPeerState()),
6205 data: []byte("catchup"),
6206 }
6207 n.pterm = snap.lastTerm
6208 n.pindex = snap.lastIndex
6209 n.commit = snap.lastIndex
6210 require_NoError(t, n.installSnapshot(snap))
6211 require_Equal(t, n.papplied, 100)
6212 require_Equal(t, n.applied, 1)
6213
6214 // Simulate uncommitted entries being truncated up to the above snapshot.
6215 n.truncateWAL(1, 100)
6216 require_Equal(t, n.papplied, 100)
6217
6218 // We haven't applied anything since the previous snapshot, so should error.
6219 _, err := n.CreateSnapshotCheckpoint(false)
6220 require_Error(t, err, errNoSnapAvailable)
6221
6222 // We have only applied the previous snapshot, so should still error as there's nothing (new) to snapshot.
6223 n.Applied(100)
6224 require_Equal(t, n.applied, 100)
6225 _, err = n.CreateSnapshotCheckpoint(false)
6226 require_Error(t, err, errNoSnapAvailable)
6227
6228 // Process a second message such that we can snapshot.
6229 n.processAppendEntry(aeMsg2, n.aesub)
6230 require_Equal(t, n.pindex, 101)
6231 require_Equal(t, n.commit, 100)
6232 n.processAppendEntry(aeHeartbeat2, n.aesub)
6233 require_Equal(t, n.pindex, 101)
6234 require_Equal(t, n.commit, 101)
6235 n.Applied(101)
6236 require_Equal(t, n.applied, 101)
6237
6238 // The checkpoint should function, load the previous/catchup snapshot and load above entry.
6239 c, err := n.CreateSnapshotCheckpoint(false)
6240 require_NoError(t, err)
6241
6242 buf, err := c.LoadLastSnapshot()
6243 require_NoError(t, err)
6244 require_True(t, bytes.Equal(buf, []byte("catchup")))
6245
6246 var count int
6247 for ae, err := range c.AppendEntriesSeq() {
6248 count++
6249 require_NoError(t, err)
6250 require_Equal(t, ae.pindex, 100)
6251 }
6252 require_Equal(t, count, 1)
6253 }
6254
6255 func TestNRGCheckpointInstallSnapshotAbortDuringWrite(t *testing.T) {
6256 type tc struct {
6257 name string
6258 preinstall func(n *raft, cp *checkpoint)
6259 check func(t *testing.T, n *raft, cp *checkpoint)
6260 }
6261 cases := []tc{
6262 {
6263 name: "RemoveOrphan",
6264 preinstall: func(*raft, *checkpoint) {},
6265 check: func(t *testing.T, _ *raft, cp *checkpoint) {
6266 if _, err := os.Stat(cp.snapFile); !os.IsNotExist(err) {
6267 t.Fatalf("orphan snapshot file remains at %q (stat err=%v)", cp.snapFile, err)
6268 }
6269 },
6270 },
6271 {
6272 name: "KeepAdoptedSnapshot",
6273 preinstall: func(n *raft, cp *checkpoint) {
6274 n.Lock()
6275 n.snapfile = cp.snapFile
6276 n.Unlock()
6277 },
6278 check: func(t *testing.T, n *raft, cp *checkpoint) {
6279 n.RLock()
6280 sf := n.snapfile
6281 n.RUnlock()
6282 require_Equal(t, sf, cp.snapFile)
6283 if _, err := os.Stat(cp.snapFile); err != nil {
6284 t.Fatalf("adopted snapshot file was removed: %v", err)
6285 }
6286 },
6287 },
6288 }
6289
6290 for _, c := range cases {
6291 t.Run(c.name, func(t *testing.T) {
6292 n, cleanup := initSingleMemRaftNode(t)
6293 defer cleanup()
6294
6295 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
6296 entries := []*Entry{newEntry(EntryNormal, esm)}
6297 nats0 := "S1Nunr6R" // "nats-0"
6298
6299 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
6300 aeHB := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
6301 n.processAppendEntry(aeMsg, n.aesub)
6302 n.processAppendEntry(aeHB, n.aesub)
6303 n.Applied(1)
6304 require_Equal(t, n.applied, 1)
6305
6306 ck, err := n.CreateSnapshotCheckpoint(false)
6307 require_NoError(t, err)
6308 cp := ck.(*checkpoint)
6309 c.preinstall(n, cp)
6310
6311 // Drain dios so writeFileWithSync parks inside writeAtomically.
6312 drained := 0
6313 drain:
6314 for {
6315 select {
6316 case <-n.dios.ch:
6317 drained++
6318 default:
6319 break drain
6320 }
6321 }
6322 refill := func() {
6323 for i := 0; i < drained; i++ {
6324 n.dios.ch <- struct{}{}
6325 }
6326 drained = 0
6327 }
6328 defer refill()
6329
6330 errCh := make(chan error, 1)
6331 go func() {
6332 _, err := ck.InstallSnapshot([]byte("data"))
6333 errCh <- err
6334 }()
6335
6336 // 100ms is empirical: enough for the writer to reach <-dios on any
6337 // reasonable host. With dios drained it cannot progress past this
6338 // point, so the sanity check below would catch a too-short wait.
6339 time.Sleep(100 * time.Millisecond)
6340 select {
6341 case err = <-errCh:
6342 t.Fatalf("writer returned before dios refill: %v", err)
6343 default:
6344 }
6345
6346 n.Lock()
6347 require_True(t, n.snapshotting)
6348 n.snapshotting = false
6349 n.Unlock()
6350
6351 refill()
6352
6353 select {
6354 case err = <-errCh:
6355 require_Error(t, err, errSnapAborted)
6356 case <-time.After(5 * time.Second):
6357 t.Fatal("c.InstallSnapshot did not return")
6358 }
6359
6360 c.check(t, n, cp)
6361 })
6362 }
6363 }
6364
6365 func TestNRGSwitchToCandidateResetsVote(t *testing.T) {
6366 n, cleanup := initSingleMemRaftNode(t)
6367 defer cleanup()
6368
6369 nats0 := "S1Nunr6R" // "nats-0"
6370
6371 require_Equal(t, n.term, 0)
6372 n.vote = nats0
6373 n.switchToCandidate()
6374
6375 // Confirm the term was incremented and the vote reset.
6376 require_Equal(t, n.term, 1)
6377 require_Equal(t, n.vote, _EMPTY_)
6378
6379 // Confirm this was written to disk.
6380 term, voted, err := n.readTermVote()
6381 require_NoError(t, err)
6382 require_Equal(t, term, 1)
6383 require_Equal(t, voted, _EMPTY_)
6384 }
6385
6386 func TestNRGInitSingleMemRaftNodeDefaults(t *testing.T) {
6387 n, cleanup := initSingleMemRaftNode(t)
6388 defer cleanup()
6389 require_Equal(t, n.ID(), "esFhDys3")
6390 require_Equal(t, len(n.Peers()), 1)
6391 require_Equal(t, n.Peers()[0].ID, "esFhDys3")
6392 require_Equal(t, n.ClusterSize(), 1)
6393 require_True(t, n.Quorum())
6394 }
6395
6396 func TestNRGReplayAddPeerKeepsClusterSize(t *testing.T) {
6397 c := createJetStreamClusterExplicit(t, "R3S", 3)
6398 s := c.servers[0]
6399 defer c.shutdown()
6400
6401 storeDir := t.TempDir()
6402 fcfg := FileStoreConfig{
6403 StoreDir: storeDir,
6404 BlockSize: defaultMediumBlockSize,
6405 AsyncFlush: false,
6406 srv: s,
6407 }
6408 scfg := StreamConfig{Name: "RAFT", Storage: FileStorage}
6409 fs, err := newFileStore(fcfg, scfg)
6410 require_NoError(t, err)
6411
6412 cfg := &RaftConfig{Name: "TEST", Store: storeDir, Log: fs}
6413
6414 // Seed peer state as a 3-node group.
6415 s.mu.RLock()
6416 self := s.sys.shash[:idLen]
6417 s.mu.RUnlock()
6418 peerA, peerB := "yrzKKRBu", "cnrtt3eg"
6419 require_NoError(t, s.bootstrapRaftNode(cfg, []string{self, peerA, peerB}, true))
6420
6421 n, err := s.initRaftNode(globalAccountName, cfg, pprofLabels{})
6422 require_NoError(t, err)
6423 require_Equal(t, n.ClusterSize(), 3)
6424
6425 // Store a normal entry and a EntryAddPeer and commit them.
6426 // The latter triggered the bug at restart.
6427 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
6428 aeMsg1 := encode(t, &appendEntry{
6429 leader: self,
6430 term: 2,
6431 commit: 0,
6432 pterm: 0,
6433 pindex: 0,
6434 entries: []*Entry{newEntry(EntryNormal, esm)},
6435 })
6436 aeMsg2 := encode(t, &appendEntry{
6437 leader: self,
6438 term: 2,
6439 commit: 2,
6440 pterm: 2,
6441 pindex: 1,
6442 entries: []*Entry{newEntry(EntryAddPeer, []byte(peerA))},
6443 })
6444 n.processAppendEntry(aeMsg1, n.aesub)
6445 n.processAppendEntry(aeMsg2, n.aesub)
6446
6447 // Restart from disk, forcing replay of the two WAL entries.
6448 n.Stop()
6449 n.WaitForStop()
6450 fs.Stop()
6451
6452 fs, err = newFileStore(fcfg, scfg)
6453 require_NoError(t, err)
6454 cfg = &RaftConfig{Name: "TEST", Store: storeDir, Log: fs}
6455 n, err = s.initRaftNode(globalAccountName, cfg, pprofLabels{})
6456 require_NoError(t, err)
6457
6458 // If bug is present, cluster size is 1 instead of 3.
6459 // EntryAddPeer would increases the initial cluster
6460 // of size of 0 to 1. initRaftNode() would then add
6461 // the remaining peers from peer state file, but would
6462 // not adjust cluster size and quorum accordingly.
6463 // This could lead to erroneously create singleton
6464 // clusters after restart.
6465 require_Equal(t, n.ClusterSize(), 3)
6466 require_Equal(t, n.qn, 2)
6467
6468 n.Stop()
6469 n.WaitForStop()
6470 fs.Stop()
6471 }
6472
6473 func TestNRGSnapshotExcludesUncommittedMembershipChange(t *testing.T) {
6474 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
6475
6476 t.Run("AddPeer", func(t *testing.T) {
6477 n, cleanup := initSingleMemRaftNode(t)
6478 defer cleanup()
6479
6480 nats0 := "S1Nunr6R" // "nats-0"
6481 newPeer := "yrzKKRBu" // "nats-1"
6482
6483 n.Lock()
6484 n.addPeer(nats0)
6485 n.Unlock()
6486 require_Equal(t, len(n.peers), 2)
6487
6488 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: []*Entry{newEntry(EntryNormal, esm)}})
6489 aeAddPeer := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: []*Entry{newEntry(EntryAddPeer, []byte(newPeer))}})
6490 n.processAppendEntry(aeMsg, n.aesub)
6491 n.processAppendEntry(aeAddPeer, n.aesub)
6492
6493 // The peer is tracked speculatively and the change is inflight at index 2.
6494 require_Equal(t, n.commit, 1)
6495 _, ok := n.peers[newPeer]
6496 require_True(t, ok)
6497 require_Equal(t, n.csz, 3)
6498 require_NotNil(t, n.membChange)
6499 require_Equal(t, n.membChange.index, 2)
6500
6501 // Apply the committed normal entry, then snapshot at applied (index 1).
6502 n.Applied(1)
6503 require_NoError(t, n.InstallSnapshot(nil, false))
6504
6505 // The snapshot's peer state must reflect committed membership only,
6506 // i.e. it must not contain the not-yet-committed peer.
6507 snap, err := n.loadLastSnapshot()
6508 require_NoError(t, err)
6509 require_Equal(t, snap.lastIndex, 1)
6510 ps, err := decodePeerState(snap.peerstate)
6511 require_NoError(t, err)
6512 require_Equal(t, ps.clusterSize, 2)
6513 require_Len(t, len(ps.knownPeers), 2)
6514 require_False(t, slices.Contains(ps.knownPeers, newPeer))
6515 })
6516
6517 t.Run("RemovePeer", func(t *testing.T) {
6518 n, cleanup := initSingleMemRaftNode(t)
6519 defer cleanup()
6520
6521 nats0 := "S1Nunr6R" // "nats-0"
6522 oldPeer := "yrzKKRBu" // "nats-1"
6523
6524 n.Lock()
6525 n.addPeer(nats0)
6526 n.addPeer(oldPeer)
6527 n.Unlock()
6528 require_Equal(t, len(n.peers), 3)
6529
6530 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: []*Entry{newEntry(EntryNormal, esm)}})
6531 aeRemovePeer := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: []*Entry{newEntry(EntryRemovePeer, []byte(oldPeer))}})
6532 n.processAppendEntry(aeMsg, n.aesub)
6533 n.processAppendEntry(aeRemovePeer, n.aesub)
6534
6535 // The peer is removed speculatively and the change is inflight at index 2.
6536 require_Equal(t, n.commit, 1)
6537 _, ok := n.peers[oldPeer]
6538 require_False(t, ok)
6539 require_Equal(t, n.csz, 2)
6540 require_NotNil(t, n.membChange)
6541 require_Equal(t, n.membChange.index, 2)
6542
6543 // Apply the committed normal entry, then snapshot at applied (index 1).
6544 n.Applied(1)
6545 require_NoError(t, n.InstallSnapshot(nil, false))
6546
6547 // The snapshot's peer state must reflect committed membership only,
6548 // i.e. it must still include the not-yet-removed peer.
6549 snap, err := n.loadLastSnapshot()
6550 require_NoError(t, err)
6551 require_Equal(t, snap.lastIndex, 1)
6552 ps, err := decodePeerState(snap.peerstate)
6553 require_NoError(t, err)
6554 require_Equal(t, ps.clusterSize, 3)
6555 require_Len(t, len(ps.knownPeers), 3)
6556 require_True(t, slices.Contains(ps.knownPeers, oldPeer))
6557 })
6558 }
6559
6560 func TestNRGDontSwitchToCandidateWithInflightSelfMembershipChange(t *testing.T) {
6561 n, cleanup := initSingleMemRaftNode(t)
6562 defer cleanup()
6563
6564 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
6565
6566 nats0 := "S1Nunr6R" // "nats-0"
6567 nats1 := "yrzKKRBu" // "nats-1"
6568
6569 n.Lock()
6570 n.addPeer(nats0)
6571 n.addPeer(nats1)
6572 n.Unlock()
6573 require_Equal(t, len(n.peers), 3)
6574
6575 // Receive an uncommitted EntryRemovePeer that targets us.
6576 aeMsg := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: []*Entry{newEntry(EntryNormal, esm)}})
6577 aeRemoveSelf := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: []*Entry{newEntry(EntryRemovePeer, []byte(n.id))}})
6578 n.processAppendEntry(aeMsg, n.aesub)
6579 n.processAppendEntry(aeRemoveSelf, n.aesub)
6580
6581 // We've speculatively removed ourselves, and the change is inflight at index 2.
6582 _, ok := n.peers[n.id]
6583 require_False(t, ok)
6584 require_NotNil(t, n.membChange)
6585 require_Equal(t, n.membChange.peer, n.id)
6586 require_Equal(t, n.membChange.index, 2)
6587
6588 // We must not become a candidate while our own removal is uncommitted.
6589 n.Applied(1)
6590 n.switchToCandidate()
6591 require_Equal(t, n.State(), Follower)
6592
6593 // Truncate the uncommitted removal back to the committed index. This
6594 // restores us to our own peer set and clears the inflight change.
6595 n.Lock()
6596 n.truncateWAL(1, 1)
6597 n.Unlock()
6598 _, ok = n.peers[n.id]
6599 require_True(t, ok)
6600 require_True(t, n.membChange == nil)
6601
6602 // Now that we're a settled member again, we can campaign.
6603 n.switchToCandidate()
6604 require_Equal(t, n.State(), Candidate)
6605 }
6606
6607 func TestNRGTrackPeerLag(t *testing.T) {
6608 c := createJetStreamClusterExplicit(t, "R3S", 3)
6609 defer c.shutdown()
6610
6611 rg := c.createRaftGroup("TEST", 3, newStateAdder)
6612 lsm := rg.waitOnLeader()
6613 require_NotNil(t, lsm)
6614 ls := lsm.(*stateAdder)
6615
6616 checkPeerData := func() {
6617 for _, sm := range rg {
6618 rn := sm.node().(*raft)
6619 rn.RLock()
6620 leader := rn.leader
6621 isLeader := RaftState(rn.state.Load()) == Leader
6622 for id, ps := range rn.peers {
6623 // If this peer is the leader (but not ourselves), then these values need to be populated.
6624 if isLeader && id != rn.id {
6625 if li := ps.li; li == 0 {
6626 rn.RUnlock()
6627 t.Fatal("require last replicated index to be set")
6628 }
6629 if ts := ps.ts; ts.IsZero() {
6630 rn.RUnlock()
6631 t.Fatal("require last seen timestamp to be set")
6632 }
6633 continue
6634 }
6635 if li := ps.li; li != 0 {
6636 rn.RUnlock()
6637 t.Fatalf("require equal, but got: %v != %v", ps.li, 0)
6638 }
6639 if ts := ps.ts; id != rn.leader && !ts.IsZero() {
6640 rn.RUnlock()
6641 t.Fatalf("require zero ts, but got: %v", ts)
6642 }
6643 }
6644 rn.RUnlock()
6645
6646 // This test expects no lag and all nodes as current (except for followers as seen by other followers).
6647 for _, ps := range rn.Peers() {
6648 require_Equal(t, ps.Lag, 0)
6649 require_Equal(t, ps.Current, ps.ID == rn.id || ps.ID == leader || isLeader)
6650 }
6651 }
6652 }
6653
6654 for i := range 5 {
6655 ls.proposeDelta(10)
6656 rg.waitOnTotal(t, int64(10*(i+1)))
6657 }
6658 checkPeerData()
6659
6660 require_NoError(t, lsm.node().StepDown())
6661 lsm = rg.waitOnLeader()
6662 require_NotNil(t, lsm)
6663 ls = lsm.(*stateAdder)
6664
6665 for i := range 5 {
6666 ls.proposeDelta(10)
6667 rg.waitOnTotal(t, int64(50+10*(i+1)))
6668 }
6669 checkPeerData()
6670 }
6671
6672 func TestNRGPeersResponse(t *testing.T) {
6673 // As a leader.
6674 rn := &raft{
6675 id: "me",
6676 leader: "me",
6677 peers: map[string]*lps{
6678 "me": {li: 0},
6679 "peer1": {li: 10},
6680 "peer2": {li: 3},
6681 "peer3": {li: 0},
6682 },
6683 pindex: 10,
6684 commit: 10,
6685 applied: 10,
6686 }
6687 rn.state.Store(int32(Leader))
6688 for _, ps := range rn.Peers() {
6689 switch ps.ID {
6690 case "me":
6691 require_Equal(t, ps.Lag, 0)
6692 require_True(t, ps.Current)
6693 case "peer1":
6694 require_Equal(t, ps.Lag, 0)
6695 require_True(t, ps.Current)
6696 case "peer2":
6697 require_Equal(t, ps.Lag, 7) // We persisted 10 entries, they have only 3.
6698 require_False(t, ps.Current)
6699 case "peer3":
6700 require_Equal(t, ps.Lag, 10) // We persisted 10 entries, they have none.
6701 require_False(t, ps.Current)
6702 default:
6703 t.Fatalf("unexpected peer ID: %s", ps.ID)
6704 }
6705 }
6706
6707 // As a follower.
6708 rn = &raft{
6709 id: "me",
6710 leader: "leader",
6711 peers: map[string]*lps{
6712 "me": {li: 0},
6713 "leader": {li: 0},
6714 "peer": {li: 0},
6715 },
6716 }
6717 rn.state.Store(int32(Follower))
6718 for _, ps := range rn.Peers() {
6719 switch ps.ID {
6720 case "me":
6721 require_Equal(t, ps.Lag, 0)
6722 require_True(t, ps.Current)
6723 case "leader":
6724 require_Equal(t, ps.Lag, 0)
6725 require_False(t, ps.Current)
6726 default:
6727 // As a follower ourselves, we don't know about the state of other followers.
6728 require_Equal(t, ps.Lag, 0)
6729 require_False(t, ps.Current)
6730 }
6731 }
6732
6733 // If we've heard from the leader recently, we report it as current.
6734 rn.peers["leader"].ts = time.Now()
6735 for _, ps := range rn.Peers() {
6736 if ps.ID == "leader" {
6737 require_Equal(t, ps.Lag, 0)
6738 require_True(t, ps.Current)
6739 }
6740 }
6741 }
6742
6743 func TestNRGOnlyCommitIfCurrentTerm(t *testing.T) {
6744 n, cleanup := initSingleMemRaftNode(t)
6745 defer cleanup()
6746
6747 // Create a sample entry, the content doesn't matter, just that it's stored.
6748 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
6749 entries := []*Entry{newEntry(EntryNormal, esm)}
6750
6751 s1 := getHash("S-1")
6752 s2 := getHash("S-2")
6753 s3 := getHash("S-3")
6754
6755 n.Lock()
6756 n.addPeer(s2)
6757 n.addPeer(s3)
6758 n.Unlock()
6759 require_Len(t, len(n.Peers()), 3)
6760
6761 // The below timeline describes a test ensuring a leader doesn't commit entries from previous terms.
6762
6763 // This server became leader twice and stored two entries.
6764 aeMsg1 := encode(t, &appendEntry{leader: s1, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
6765 require_NoError(t, n.storeToWAL(aeMsg1))
6766 aeMsg2 := encode(t, &appendEntry{leader: s1, term: 2, commit: 0, pterm: 1, pindex: 1, entries: entries})
6767 require_NoError(t, n.storeToWAL(aeMsg2))
6768
6769 // Another server became leader for term 3 without us knowing and stored a different entry at index 2.
6770 // We now become leader again and store a new entry at index 3, but unaware of the above term 3 entry.
6771 aeMsg3 := encode(t, &appendEntry{leader: s1, term: 4, commit: 0, pterm: 2, pindex: 2, entries: entries})
6772 require_NoError(t, n.storeToWAL(aeMsg3))
6773
6774 // Set up leader state for below response handling.
6775 n.switchToLeader()
6776 n.term = 4
6777 require_Equal(t, n.commit, 0)
6778
6779 // When we get quorum on the first two entries this doesn't count toward upping the commit yet.
6780 n.processAppendEntryResponse(&appendEntryResponse{term: 1, index: 1, peer: s2, success: true})
6781 require_Equal(t, n.commit, 0)
6782 n.processAppendEntryResponse(&appendEntryResponse{term: 2, index: 2, peer: s2, success: true})
6783 require_Equal(t, n.commit, 0)
6784 // Only once we receive quorum on an entry of our current term do we count this toward upping the commit.
6785 // If we wouldn't have waited to up our commit until now, the server that was leader during term 3
6786 // could still have overwritten the entry at index 2, resulting in a desync.
6787 n.processAppendEntryResponse(&appendEntryResponse{term: 4, index: 3, peer: s2, success: true})
6788 require_Equal(t, n.commit, 3)
6789 }
6790
6791 func TestNRGTermFencedProposals(t *testing.T) {
6792 n, cleanup := initSingleMemRaftNode(t)
6793 defer cleanup()
6794
6795 // Simulate winning an election.
6796 n.switchToCandidate()
6797 n.switchToLeader()
6798 require_Equal(t, n.State(), Leader)
6799 term := n.Term()
6800 require_Equal(t, term, 1)
6801
6802 // Proposals with the current term are accepted.
6803 require_NoError(t, n.Propose(term, nil))
6804 require_NoError(t, n.ProposeMulti(term, []*Entry{newEntry(EntryNormal, nil)}))
6805
6806 // Proposals with a stale or future term are rejected, even though we are leader.
6807 // Term 0 can never be a valid proposing term, elected leaders always have term >= 1.
6808 require_Error(t, n.Propose(0, nil), errNotLeader)
6809 require_Error(t, n.Propose(term+1, nil), errNotLeader)
6810 require_Error(t, n.ProposeMulti(0, []*Entry{newEntry(EntryNormal, nil)}), errNotLeader)
6811 require_Error(t, n.ProposeMulti(term+1, []*Entry{newEntry(EntryNormal, nil)}), errNotLeader)
6812 require_Equal(t, n.State(), Leader)
6813
6814 // Losing leadership signals the upper layer with the term the loss happened in.
6815 n.stepdown(noLeader)
6816 select {
6817 case lc := <-n.LeadChangeC():
6818 require_False(t, lc.isLeader)
6819 require_Equal(t, lc.term, term)
6820 default:
6821 t.Fatal("Expected leadChange signal")
6822 }
6823
6824 // Get re-elected at a higher term.
6825 checkFor(t, 2*time.Second, 100*time.Millisecond, func() error {
6826 n.RLock()
6827 prop, commit, processed := n.prop.len(), n.commit, n.processed
6828 n.RUnlock()
6829 if prop > 0 {
6830 return fmt.Errorf("expected prop to be 0, got %d", prop)
6831 }
6832 if processed >= commit {
6833 return nil
6834 }
6835 n.Applied(commit)
6836 return fmt.Errorf("processed %d < commit %d", processed, commit)
6837 })
6838 n.switchToCandidate()
6839 n.switchToLeader()
6840 newTerm := n.Term()
6841 require_Equal(t, newTerm, term+1)
6842
6843 // A stale process still holding the previous epoch's term must not be able
6844 // to propose into the new epoch.
6845 require_Error(t, n.Propose(term, nil), errNotLeader)
6846 require_Error(t, n.ProposeMulti(term, []*Entry{newEntry(EntryNormal, nil)}), errNotLeader)
6847
6848 // Proposals with the new term are accepted, and forwarded proposals always
6849 // use the node's current term.
6850 require_NoError(t, n.Propose(newTerm, nil))
6851 require_NoError(t, n.ForwardProposal(nil))
6852 }
6853
6854 func TestNRGLeaderStepsDownIfOverrun(t *testing.T) {
6855 n, cleanup := initSingleMemRaftNode(t)
6856 defer cleanup()
6857
6858 // Proposals are only accepted if we're the leader.
6859 term := n.Term()
6860 require_Equal(t, term, 0)
6861 require_Error(t, n.Propose(term, nil), errNotLeader)
6862 require_Error(t, n.ProposeMulti(term, nil), errNotLeader)
6863
6864 // Simulate winning an election.
6865 n.switchToCandidate()
6866 n.switchToLeader()
6867 term = n.Term()
6868 require_Equal(t, term, 1)
6869 require_NoError(t, n.Propose(term, nil))
6870 require_NoError(t, n.ProposeMulti(term, nil))
6871 require_Equal(t, n.State(), Leader)
6872
6873 // Too many uncommitted entries in our log.
6874 t.Run("Uncommitted", func(t *testing.T) {
6875 n.state.Store(int32(Leader))
6876
6877 // Proposing while we're exactly at the threshold still succeeds.
6878 n.pindex, n.commit, n.applied = pauseQuorumThreshold, 0, 0
6879 require_NoError(t, n.Propose(term, nil))
6880 require_NoError(t, n.ProposeMulti(term, nil))
6881 require_Equal(t, n.State(), Leader)
6882
6883 // While we're over the threshold, we temporarily don't send proposals.
6884 n.pindex, n.commit, n.applied = pauseQuorumThreshold+1, 0, 0
6885 require_Error(t, n.Propose(term, nil), errNotLeader)
6886 require_Equal(t, n.State(), Follower)
6887
6888 n.state.Store(int32(Leader))
6889 require_Error(t, n.ProposeMulti(term, nil), errNotLeader)
6890 require_Equal(t, n.State(), Follower)
6891 })
6892
6893 // Too many unapplied entries in our log and in-memory.
6894 t.Run("Unapplied", func(t *testing.T) {
6895 n.state.Store(int32(Leader))
6896
6897 // Proposing while we're exactly at the threshold still succeeds.
6898 n.pindex, n.commit, n.applied = pauseQuorumThreshold, pauseQuorumThreshold, 0
6899 require_NoError(t, n.Propose(term, nil))
6900 require_NoError(t, n.ProposeMulti(term, nil))
6901 require_Equal(t, n.State(), Leader)
6902
6903 // While we're over the threshold, we temporarily don't send proposals.
6904 n.pindex, n.commit, n.applied = pauseQuorumThreshold+1, pauseQuorumThreshold+1, 0
6905 require_Error(t, n.Propose(term, nil), errNotLeader)
6906 require_Equal(t, n.State(), Follower)
6907
6908 n.state.Store(int32(Leader))
6909 require_Error(t, n.ProposeMulti(term, nil), errNotLeader)
6910 require_Equal(t, n.State(), Follower)
6911 })
6912 }
6913
6914 func TestNRGFollowerPausesQuorumIfOverrun(t *testing.T) {
6915 test := func(t *testing.T, new bool) {
6916 n, cleanup := initSingleMemRaftNode(t)
6917 defer cleanup()
6918
6919 aeReply := "$TEST"
6920 nc, err := nats.Connect(n.s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
6921 require_NoError(t, err)
6922 defer nc.Close()
6923
6924 sub, err := nc.SubscribeSync(aeReply)
6925 require_NoError(t, err)
6926 defer sub.Drain()
6927 require_NoError(t, nc.Flush())
6928
6929 // Timeline
6930 nats0 := "S1Nunr6R" // "nats-0"
6931 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: nil, reply: aeReply})
6932
6933 aesub := n.aesub
6934 if !new {
6935 aesub = nil
6936 }
6937
6938 n.processAppendEntry(aeHeartbeat, aesub)
6939 msg, err := sub.NextMsg(200 * time.Millisecond)
6940 if new {
6941 require_NoError(t, err)
6942 ar := decodeAppendEntryResponse(msg.Data)
6943 require_True(t, ar.success)
6944 require_Equal(t, msg.Reply, _EMPTY_)
6945 } else {
6946 require_Error(t, err, nats.ErrTimeout)
6947 }
6948
6949 // Processing while we're exactly at the threshold still succeeds.
6950 n.commit, n.applied = pauseQuorumThreshold, 0
6951 n.processAppendEntry(aeHeartbeat, aesub)
6952 msg, err = sub.NextMsg(200 * time.Millisecond)
6953 if new {
6954 require_NoError(t, err)
6955 ar := decodeAppendEntryResponse(msg.Data)
6956 require_True(t, ar.success)
6957 require_Equal(t, msg.Reply, _EMPTY_)
6958 } else {
6959 require_Error(t, err, nats.ErrTimeout)
6960 }
6961
6962 // When we're over the threshold, we pause processing until we're sufficiently below it again.
6963 n.commit, n.applied = pauseQuorumThreshold+1, 0
6964 n.processAppendEntry(aeHeartbeat, aesub)
6965 _, err = sub.NextMsg(200 * time.Millisecond)
6966 require_Error(t, err, nats.ErrTimeout)
6967 require_Equal(t, n.quorumPaused, new)
6968
6969 // Confirm we remain paused while we're almost at the unpause threshold.
6970 n.applied = n.commit - paeWarnThreshold - 1
6971 n.processAppendEntry(aeHeartbeat, aesub)
6972 _, err = sub.NextMsg(200 * time.Millisecond)
6973 require_Error(t, err, nats.ErrTimeout)
6974 require_Equal(t, n.quorumPaused, new)
6975
6976 // Once we're at the lower threshold, we should be unpaused and accept new entries again.
6977 // Afterward we'd likely catch up from a snapshot instead of normal append entries.
6978 n.applied = n.commit - paeWarnThreshold
6979 n.processAppendEntry(aeHeartbeat, aesub)
6980 require_False(t, n.quorumPaused)
6981
6982 msg, err = sub.NextMsg(200 * time.Millisecond)
6983 if new {
6984 require_NoError(t, err)
6985 ar := decodeAppendEntryResponse(msg.Data)
6986 require_True(t, ar.success)
6987 require_Equal(t, msg.Reply, _EMPTY_)
6988 } else {
6989 require_Error(t, err, nats.ErrTimeout)
6990 }
6991
6992 if new {
6993 // Guard against an underflow. We should unpause shortly after snapshot install.
6994 n.quorumPaused = true
6995 n.applied, n.papplied = paeWarnThreshold, paeWarnThreshold
6996 n.commit = 0
6997 n.processAppendEntry(aeHeartbeat, aesub)
6998 require_False(t, n.quorumPaused)
6999
7000 msg, err = sub.NextMsg(200 * time.Millisecond)
7001 require_NoError(t, err)
7002 ar := decodeAppendEntryResponse(msg.Data)
7003 require_True(t, ar.success)
7004 require_Equal(t, msg.Reply, _EMPTY_)
7005 }
7006 }
7007
7008 t.Run("Replay", func(t *testing.T) { test(t, false) })
7009 t.Run("New", func(t *testing.T) { test(t, true) })
7010 }
7011
7012 func TestNRGSwitchToCandidateResetsQuorumPaused(t *testing.T) {
7013 n, cleanup := initSingleMemRaftNode(t)
7014 defer cleanup()
7015
7016 // Manually set the quorumPaused flag as if the follower was overrun.
7017 n.quorumPaused = true
7018 require_Equal(t, n.term, 0)
7019
7020 // Switching to a candidate has a similar prerequisite to check all committed entries
7021 // have been applied. We can therefore reset quorumPaused.
7022 n.switchToCandidate()
7023 require_Equal(t, n.term, 1)
7024 require_False(t, n.quorumPaused)
7025 }
7026
7027 func TestNRGPausingQuorumCancelsCatchup(t *testing.T) {
7028 // If a follower is already catching up and it also falls far enough behind to
7029 // hit the quorum-pause threshold, the in-flight catchup should be canceled
7030 // so the leader re-sends a fresher snapshot rather than continuing to stream
7031 // entries we can't absorb.
7032 test := func(t *testing.T, alreadyPaused bool) {
7033 n, cleanup := initSingleMemRaftNode(t)
7034 defer cleanup()
7035
7036 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
7037 entries := []*Entry{newEntry(EntryNormal, esm)}
7038
7039 nats0 := "S1Nunr6R" // "nats-0"
7040 nats1 := "yrzKKRBu" // "nats-1"
7041
7042 // Initial entry and heartbeat from nats0 so the follower has a committed baseline.
7043 aeInitial := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
7044 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: nil})
7045
7046 n.processAppendEntry(aeInitial, n.aesub)
7047 n.processAppendEntry(aeHeartbeat, n.aesub)
7048 require_Equal(t, n.commit, 1)
7049
7050 // Leader change. The new leader references pindex=3, which the follower
7051 // doesn't have, so the follower requests a catchup.
7052 aeCatchupTrigger := encode(t, &appendEntry{leader: nats1, term: 2, commit: 1, pterm: 2, pindex: 3, entries: entries})
7053 n.processAppendEntry(aeCatchupTrigger, n.aesub)
7054 require_True(t, n.catchup != nil)
7055 require_True(t, n.catchup.sub != nil)
7056 catchupSub := n.catchup.sub
7057
7058 // Put the follower into a state where the next append entry will trip the
7059 // pause logic: either already paused with a backlog above the warn threshold,
7060 // or fresh but with a backlog above the pause threshold.
7061 if alreadyPaused {
7062 n.quorumPaused = true
7063 n.commit, n.applied, n.papplied = paeWarnThreshold+1, 0, 0
7064 } else {
7065 n.commit, n.applied, n.papplied = pauseQuorumThreshold+1, 0, 0
7066 }
7067
7068 // Deliver an append entry on the catchup sub. Its contents don't matter –
7069 // the pause check runs before the entry is applied.
7070 aeCatchup := encode(t, &appendEntry{leader: nats1, term: 2, commit: 1, pterm: 1, pindex: 1, lterm: 2, entries: entries})
7071 n.processAppendEntry(aeCatchup, catchupSub)
7072
7073 // The catchup should have been canceled, so the leader will re-send a fresher snapshot.
7074 require_True(t, n.catchup == nil)
7075 require_True(t, n.quorumPaused)
7076 }
7077
7078 t.Run("EnteringPause", func(t *testing.T) { test(t, false) })
7079 t.Run("AlreadyPaused", func(t *testing.T) { test(t, true) })
7080 }
7081
7082 func TestNRGApplyCommitDoesNotResetWALAtSnapshotBoundary(t *testing.T) {
7083 n, cleanup := initSingleMemRaftNode(t)
7084 defer cleanup()
7085
7086 nats0 := "S1Nunr6R" // "nats-0"
7087 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
7088 entry := []*Entry{newEntry(EntryNormal, esm)}
7089
7090 // Build a WAL with 3 entries.
7091 ae1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entry})
7092 ae2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entry})
7093 ae3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 2, entries: entry})
7094 n.processAppendEntry(ae1, n.aesub)
7095 n.processAppendEntry(ae2, n.aesub)
7096 n.processAppendEntry(ae3, n.aesub)
7097 require_Equal(t, n.pindex, 3)
7098 require_Equal(t, n.commit, 0)
7099
7100 // Install a snapshot past our commit, not overwriting commit here.
7101 snap := &snapshot{
7102 lastTerm: 1,
7103 lastIndex: 2,
7104 peerstate: encodePeerState(&peerState{n.peerNames(), n.csz, n.extSt}),
7105 }
7106 n.Lock()
7107 require_NoError(t, n.installSnapshot(snap))
7108 n.Unlock()
7109 require_Equal(t, n.papplied, 2)
7110 require_Equal(t, n.commit, 0)
7111
7112 var before StreamState
7113 n.wal.FastState(&before)
7114 require_Equal(t, before.FirstSeq, 3)
7115 require_Equal(t, before.Msgs, 1)
7116
7117 // A heartbeat advances commit through the snapshot boundary. The apply loop
7118 // should skip entries that are already compacted away.
7119 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 3, pterm: 1, pindex: 3, entries: nil})
7120 n.processAppendEntry(aeHeartbeat, n.aesub)
7121
7122 // The WAL must be intact: entry 3 still present, no reset to [0,0].
7123 var after StreamState
7124 n.wal.FastState(&after)
7125 require_Equal(t, after.FirstSeq, 3)
7126 require_Equal(t, after.Msgs, 1)
7127 // And we should have applied past the snapshot boundary up to the new commit.
7128 require_Equal(t, n.commit, 3)
7129 }
7130
7131 func TestNRGProcessAppendEntryTermMismatchDoesNotRegressCommit(t *testing.T) {
7132 n, cleanup := initSingleMemRaftNode(t)
7133 defer cleanup()
7134
7135 // Create a sample entry
7136 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
7137 entries := []*Entry{newEntry(EntryNormal, esm)}
7138
7139 nats0 := "S1Nunr6R" // "nats-0"
7140
7141 // Timeline
7142 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
7143 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: entries})
7144 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 2, pterm: 1, pindex: 2, entries: entries})
7145 aeMsg4 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 3, pterm: 1, pindex: 3, entries: entries})
7146 aeMsg5 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 4, pterm: 1, pindex: 4, entries: entries})
7147 aeHeartbeat := encode(t, &appendEntry{leader: nats0, term: 1, commit: 5, pterm: 1, pindex: 5, entries: nil})
7148
7149 // Store five entries and commit.
7150 n.processAppendEntry(aeMsg1, n.aesub)
7151 n.processAppendEntry(aeMsg2, n.aesub)
7152 n.processAppendEntry(aeMsg3, n.aesub)
7153 n.processAppendEntry(aeMsg4, n.aesub)
7154 n.processAppendEntry(aeMsg5, n.aesub)
7155 n.processAppendEntry(aeHeartbeat, n.aesub)
7156 require_Equal(t, n.commit, 5)
7157 require_Equal(t, n.pindex, 5)
7158
7159 // Send an append entry with a mismatched pterm. This will trigger
7160 // the term mismatch path in processAppendEntry which calls
7161 // truncateWAL. The commit must not regress below what was
7162 // already committed.
7163 aeBadPterm := encode(t, &appendEntry{leader: nats0, term: 2, commit: 5, pterm: 2, pindex: 5, entries: entries})
7164 n.processAppendEntry(aeBadPterm, n.aesub)
7165 require_Equal(t, n.commit, 5)
7166 }
7167
7168 func TestNRGReset(t *testing.T) {
7169 n, cleanup := initSingleMemRaftNode(t)
7170 defer cleanup()
7171
7172 // Simulate this node having operated as its own group: WAL entries,
7173 // extra peers, advanced commit/applied, a snapshot file, and a known
7174 // leader. Reset must clear all of it.
7175 nats0 := "S1Nunr6R" // "nats-0"
7176 nats1 := "yrzKKRBu" // "nats-1"
7177 esm := encodeStreamMsgAllowCompress("foo", "_INBOX.foo", nil, nil, 0, 0, true)
7178 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: []*Entry{newEntry(EntryNormal, esm)}})
7179 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 1, pterm: 1, pindex: 1, entries: []*Entry{newEntry(EntryNormal, esm)}})
7180 require_NoError(t, n.storeToWAL(aeMsg1))
7181 require_NoError(t, n.storeToWAL(aeMsg2))
7182 require_Equal(t, n.pindex, 2)
7183
7184 // Populate the cache, to check that it gets reset below.
7185 n.pae[1] = &appendEntry{leader: nats0, term: 1, pindex: 0}
7186 n.pae[2] = &appendEntry{leader: nats0, term: 1, pindex: 1}
7187
7188 n.commit = 2
7189 n.applied = 2
7190 n.processed = 2
7191 n.papplied = 1
7192 n.hcommit = 2
7193 n.term = 7
7194 n.vote = nats1
7195 n.writeTermVote()
7196
7197 // Add another peer in addition to ourselves.
7198 other := nats1
7199 n.peers[other] = &lps{time.Time{}, 0}
7200 n.adjustClusterSizeAndQuorum()
7201 n.updateLeader(other)
7202
7203 // Drop a fake snapshot file plus an orphan to verify the whole
7204 // snapshots directory is wiped, not just n.snapfile.
7205 snapDir := filepath.Join(n.sd, snapshotsDir)
7206 require_NoError(t, os.MkdirAll(snapDir, defaultDirPerms))
7207 sfile := filepath.Join(snapDir, "snap.fake")
7208 require_NoError(t, os.WriteFile(sfile, []byte("stale"), defaultFilePerms))
7209 orphan := filepath.Join(snapDir, "snap.orphan")
7210 require_NoError(t, os.WriteFile(orphan, []byte("orphan"), defaultFilePerms))
7211 n.snapfile = sfile
7212
7213 // Push something onto each queue so we can verify they are drained.
7214 _, err := n.prop.push(&proposedEntry{&Entry{}, _EMPTY_})
7215 require_NoError(t, err)
7216 _, err = n.entry.push(&appendEntry{})
7217 require_NoError(t, err)
7218 _, err = n.resp.push(&appendEntryResponse{})
7219 require_NoError(t, err)
7220 _, err = n.apply.push(newCommittedEntry(1, nil))
7221 require_NoError(t, err)
7222 _, err = n.reqs.push(&voteRequest{})
7223 require_NoError(t, err)
7224 _, err = n.votes.push(&voteResponse{})
7225 require_NoError(t, err)
7226
7227 // Start an async checkpoint so Reset has to clear n.snapshotting too.
7228 _, err = n.CreateSnapshotCheckpoint(false)
7229 require_NoError(t, err)
7230 require_True(t, n.snapshotting)
7231
7232 // Park the node before resetting, mirroring how callers (e.g. the SYS-account
7233 // leaf extension path) use Reset: observer mode is set first so the
7234 // node doesn't compete for leadership immediately after step-down.
7235 n.setObserver(true, extExtended)
7236 n.Reset()
7237
7238 // All log state cleared.
7239 require_Equal(t, n.pterm, 0)
7240 require_Equal(t, n.pindex, 0)
7241 require_Equal(t, n.commit, 0)
7242 require_Equal(t, n.applied, 0)
7243 require_Equal(t, n.processed, 0)
7244 require_Equal(t, n.papplied, 0)
7245 require_Equal(t, n.hcommit, 0)
7246
7247 // Peer set reset to just self, cluster size and quorum adjusted.
7248 require_Equal(t, len(n.peers), 1)
7249 if _, ok := n.peers[n.id]; !ok {
7250 t.Fatalf("expected self %q to remain in peers after reset, got %v", n.id, n.peers)
7251 }
7252 require_Equal(t, n.csz, 1)
7253 require_Equal(t, n.qn, 1)
7254
7255 // Leader forgotten so the parent leader can re-establish via heartbeat.
7256 require_Equal(t, n.leader, noLeader)
7257
7258 // State transitions: stepped down to follower, observer mode left as the
7259 // caller set it, term/vote cleared so the new leader's term wins.
7260 require_Equal(t, n.State(), Follower)
7261 require_True(t, n.observer)
7262 require_Equal(t, n.extSt, extExtended)
7263 require_Equal(t, n.term, 0)
7264 require_Equal(t, n.vote, noVote)
7265
7266 // Snapshot reference cleared, in-flight checkpoint flag cleared, and the
7267 // entire snapshots directory was wiped (both the referenced file and the
7268 // orphan), then recreated empty.
7269 require_Equal(t, n.snapfile, _EMPTY_)
7270 require_False(t, n.snapshotting)
7271 if _, err = os.Stat(sfile); !os.IsNotExist(err) {
7272 t.Fatalf("expected snapshot file %q to be removed, stat err=%v", sfile, err)
7273 }
7274 if _, err = os.Stat(orphan); !os.IsNotExist(err) {
7275 t.Fatalf("expected orphan snapshot %q to be removed, stat err=%v", orphan, err)
7276 }
7277 snapEntries, err := os.ReadDir(snapDir)
7278 require_NoError(t, err)
7279 require_Equal(t, len(snapEntries), 0)
7280
7281 // Queues drained.
7282 require_Equal(t, n.prop.len(), 0)
7283 require_Equal(t, n.entry.len(), 0)
7284 require_Equal(t, n.resp.len(), 0)
7285 require_Equal(t, n.apply.len(), 0)
7286 require_Equal(t, n.reqs.len(), 0)
7287 require_Equal(t, n.votes.len(), 0)
7288
7289 // WAL is empty.
7290 walEntries, _ := n.Size()
7291 require_Equal(t, walEntries, 0)
7292
7293 // Append entry cache cleared.
7294 require_Equal(t, len(n.pae), 0)
7295 }
7296
7297 func TestNRGBootstrapExpectedClusterSize(t *testing.T) {
7298 urls := func(host string, ports ...int) []*url.URL {
7299 t.Helper()
7300 urls := make([]*url.URL, 0, len(ports))
7301 for _, p := range ports {
7302 u, err := url.Parse(fmt.Sprintf("nats-route://%s:%d", host, p))
7303 require_NoError(t, err)
7304 urls = append(urls, u)
7305 }
7306 return urls
7307 }
7308
7309 for _, test := range []struct {
7310 name string
7311 routes int
7312 gateways []*RemoteGatewayOpts
7313 expected int
7314 }{
7315 {
7316 name: "ip literal gateway urls",
7317 routes: 3,
7318 gateways: []*RemoteGatewayOpts{
7319 {Name: "C1", URLs: urls("127.0.0.1", 6222, 6223, 6224)}, // own cluster, skipped
7320 {Name: "C2", URLs: urls("127.0.0.1", 7222, 7223, 7224)},
7321 },
7322 expected: 6, // 3 routes + 3 remote gateway urls
7323 },
7324 {
7325 name: "hostname gateway urls are not resolved",
7326 routes: 3,
7327 gateways: []*RemoteGatewayOpts{
7328 {Name: "C1", URLs: urls("localhost", 6222, 6223, 6224)}, // own cluster, skipped
7329 // "localhost" may resolve to both 127.0.0.1 and ::1; each url
7330 // must still count as a single peer.
7331 {Name: "C2", URLs: urls("localhost", 7222, 7223, 7224)},
7332 },
7333 expected: 6, // 3 routes + 3 remote gateway urls (not 9)
7334 },
7335 {
7336 name: "multiple remote clusters",
7337 routes: 3,
7338 gateways: []*RemoteGatewayOpts{
7339 {Name: "C1", URLs: urls("localhost", 6222, 6223, 6224)}, // own cluster, skipped
7340 {Name: "C2", URLs: urls("localhost", 7222, 7223, 7224)},
7341 {Name: "C3", URLs: urls("localhost", 8222, 8223, 8224)},
7342 },
7343 expected: 9, // 3 routes + 3 + 3 remote gateway urls
7344 },
7345 } {
7346 t.Run(test.name, func(t *testing.T) {
7347 opts := &Options{}
7348 for i := 0; i < test.routes; i++ {
7349 u, err := url.Parse(fmt.Sprintf("nats-route://127.0.0.1:%d", 5000+i))
7350 require_NoError(t, err)
7351 opts.Routes = append(opts.Routes, u)
7352 }
7353 opts.Gateway.Gateways = test.gateways
7354
7355 s := &Server{opts: opts}
7356 s.info.Cluster = "C1"
7357
7358 cfg := &RaftConfig{Name: "_meta_", Store: t.TempDir()}
7359 // allPeersKnown=false forces the estimate path.
7360 require_NoError(t, s.bootstrapRaftNode(cfg, nil, false))
7361
7362 ps, err := readPeerState(s.diskIOSemaphore(), cfg.Store)
7363 require_NoError(t, err)
7364 require_Equal(t, ps.clusterSize, test.expected)
7365 })
7366 }
7367 }
7368
7369 func TestNRGCatchupRerequestDoesNotOrphanProgressQueue(t *testing.T) {
7370 n, cleanup := initSingleMemRaftNode(t)
7371 defer cleanup()
7372
7373 // Use large entries so a catchup run exceeds its outstanding limit and
7374 // must block waiting for index updates instead of finishing immediately.
7375 msg := make([]byte, 1024*1024)
7376 entries := []*Entry{newEntry(EntryNormal, msg)}
7377
7378 nats0 := "S1Nunr6R" // "nats-0"
7379 nats1 := "yrzKKRBu" // "nats-1"
7380
7381 aeMsg1 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 0, pindex: 0, entries: entries})
7382 aeMsg2 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 1, entries: entries})
7383 aeMsg3 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 2, entries: entries})
7384 require_NoError(t, n.storeToWAL(aeMsg1))
7385 require_NoError(t, n.storeToWAL(aeMsg2))
7386 require_NoError(t, n.storeToWAL(aeMsg3))
7387
7388 // Switching to leader stores a peer state entry at index 4.
7389 n.term = 1
7390 n.switchToLeader()
7391 require_Equal(t, n.pindex, 4)
7392
7393 // Follower requests a catchup, which starts a catchup run that blocks
7394 // waiting for index updates after sending up to 2MB of entries.
7395 n.catchupFollower(&appendEntryResponse{term: 1, index: 0, peer: nats1, reply: "$NRG.CR.TEST.1"})
7396 n.RLock()
7397 q1 := n.progress[nats1]
7398 n.RUnlock()
7399 require_True(t, q1 != nil)
7400
7401 // Wait for the first run to consume the initial index update, so we know
7402 // it has started and captured its view of the last index (4) before we
7403 // store more entries below.
7404 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
7405 if q1.len() > 0 {
7406 return errors.New("first catchup run has not started yet")
7407 }
7408 return nil
7409 })
7410
7411 // Store another entry so the cancel signal pushed by the re-request below
7412 // (n.pindex) exceeds the first run's view of the last index, making the
7413 // first run return promptly instead of waiting for its stall timeout.
7414 aeMsg4 := encode(t, &appendEntry{leader: nats0, term: 1, commit: 0, pterm: 1, pindex: 4, entries: entries})
7415 require_NoError(t, n.storeToWAL(aeMsg4))
7416
7417 // Follower re-requests the catchup while the first run is still active.
7418 // This cancels the first run and installs a fresh progress queue.
7419 n.catchupFollower(&appendEntryResponse{term: 1, index: 0, peer: nats1, reply: "$NRG.CR.TEST.2"})
7420 n.RLock()
7421 q2 := n.progress[nats1]
7422 n.RUnlock()
7423 require_True(t, q2 != nil)
7424 require_True(t, q1 != q2)
7425
7426 // Wait for the first run's deferred cleanup. On exit it proposes adding
7427 // the (unknown) peer, which is observable on the proposal queue since the
7428 // run loop isn't started in this test.
7429 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
7430 if n.prop.len() == 0 {
7431 return errors.New("first catchup run still active")
7432 }
7433 return nil
7434 })
7435
7436 // The first run's cleanup must only remove its own progress queue. If it
7437 // removed the re-requested run's queue, index updates would no longer
7438 // reach that run and the catchup would stall.
7439 n.RLock()
7440 q := n.progress[nats1]
7441 n.RUnlock()
7442 require_True(t, q == q2)
7443 }
7444
7445 func TestNRGCatchupFollowerNoWaitGroupLeakWhenGoRoutineFails(t *testing.T) {
7446 n, cleanup := initSingleMemRaftNode(t)
7447 defer cleanup()
7448
7449 // Store a single entry to the WAL so catchupFollower can load a valid starting entry
7450 // and proceed to the point where it launches the catchup goroutine.
7451 var scratch [1024]byte
7452 n.Lock()
7453 entries := []*Entry{newEntry(EntryNormal, []byte("hello"))}
7454 ae := n.buildAppendEntry(entries)
7455 buf, err := ae.encode(scratch[:])
7456 require_NoError(t, err)
7457 ae.buf = buf
7458 err = n.storeToWAL(ae)
7459 n.Unlock()
7460 require_NoError(t, err)
7461
7462 // Simulate server shutdown: goroutines are no longer started.
7463 s := n.s
7464 s.grMu.Lock()
7465 s.grRunning = false
7466 s.grMu.Unlock()
7467
7468 // Ask to catch up a follower.
7469 ar := newAppendEntryResponse(ae.term, 0, "follower-peer", true)
7470 n.catchupFollower(ar)
7471
7472 // startGoRoutine returned false, so the catchup goroutine never ran. With the bug,
7473 // the wg counter is still +1 (and progress/indexUpdates leaked). Verify Delete() (which
7474 // does n.wg.Wait()) returns promptly instead of hanging forever.
7475 done := make(chan struct{})
7476 go func() {
7477 n.Delete()
7478 close(done)
7479 }()
7480
7481 select {
7482 case <-done:
7483 // Good: wg reached zero, no leak.
7484 case <-time.After(2 * time.Second):
7485 t.Fatal("raft.Delete() hung: n.wg leaked because startGoRoutine failed but wg.Done() was never called")
7486 }
7487
7488 // Also confirm the per-catchup bookkeeping was cleaned up.
7489 n.RLock()
7490 _, progressLeaked := n.progress["follower-peer"]
7491 n.RUnlock()
7492 if progressLeaked {
7493 t.Fatal("progress map entry for the follower leaked after failed catchup")
7494 }
7495 }
7496
7497 // Must be run with -race.
7498 func TestNRGProcessAppendEntryResponseTermRace(t *testing.T) {
7499 n, cleanup := initSingleMemRaftNode(t)
7500 defer cleanup()
7501
7502 // Use this node's own id as the peer so trackPeer is happy.
7503 peer := n.id
7504
7505 var wg sync.WaitGroup
7506 stop := make(chan struct{})
7507
7508 // Writer goroutine: write n.term under n.Lock, exactly as raft.Reset does.
7509 wg.Add(1)
7510 go func() {
7511 defer wg.Done()
7512 for i := uint64(0); ; i++ {
7513 select {
7514 case <-stop:
7515 return
7516 default:
7517 }
7518 n.Lock()
7519 n.term = i
7520 n.Unlock()
7521 }
7522 }()
7523
7524 // Reader goroutine: call processAppendEntryResponse with an ar that reaches
7525 // the unlocked `ar.term > n.term` comparison. ar.success=false and
7526 // ar.reply=="" route us past the earlier branches to that read.
7527 wg.Add(1)
7528 go func() {
7529 defer wg.Done()
7530 for {
7531 select {
7532 case <-stop:
7533 return
7534 default:
7535 }
7536 ar := &appendEntryResponse{
7537 term: 0, // 0 > n.term is false, so the heavy stepdown branch is skipped.
7538 index: 0,
7539 peer: peer,
7540 reply: _EMPTY_,
7541 success: false,
7542 }
7543 n.processAppendEntryResponse(ar)
7544 }
7545 }()
7546
7547 time.Sleep(300 * time.Millisecond)
7548 close(stop)
7549 wg.Wait()
7550 }
7551
7552 func TestNRGPartitionedPeerRemove(t *testing.T) {
7553 c := createJetStreamClusterExplicit(t, "R2S", 2)
7554 defer c.shutdown()
7555
7556 hub, rg := c.createMockMemRaftGroup("MOCK", 2, newStateAdder)
7557 defer hub.healPartitions()
7558
7559 leader := rg.waitOnLeader().node()
7560 require_Equal(t, leader.ClusterSize(), 2)
7561 require_Equal(t, len(rg.followers()), 1)
7562 follower := rg.followers()[0].node()
7563
7564 var hookCalls atomic.Int64
7565 hub.setAfterMsgHook(func(subject, reply string, msg []byte) {
7566 hookCalls.Add(1)
7567 })
7568
7569 // Remove the follower while the leader is partitioned away
7570 hub.partition(leader.ID(), 1)
7571 leader.ProposeRemovePeer(follower.ID())
7572
7573 // Follower can't get elected as leader, but let's try anyway
7574 follower.CampaignImmediately()
7575
7576 // Expect progress on the leader side
7577 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
7578 if leader.ClusterSize() != 1 {
7579 return errors.New("node removal still in progress")
7580 }
7581 return nil
7582 })
7583
7584 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
7585 if leader.MembershipChangeInProgress() {
7586 return errors.New("membership still in progress")
7587 }
7588 return nil
7589 })
7590
7591 require_Equal(t, leader.ClusterSize(), 1)
7592 require_False(t, leader.MembershipChangeInProgress())
7593 require_True(t, hookCalls.Load() > 0)
7594
7595 // Follower has not become leader and its membership has not changed.
7596 require_NotEqual(t, follower.State(), Leader)
7597 require_Equal(t, follower.ClusterSize(), 2)
7598 require_False(t, follower.MembershipChangeInProgress())
7599
7600 // Heal the partition, and expect the follower to get the bad news...
7601 hub.heal(leader.ID())
7602
7603 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
7604 if follower.ClusterSize() != 1 {
7605 return errors.New("node removal still in progress")
7606 }
7607 return nil
7608 })
7609 }
7610
7611 func TestNRGPeerAddAndPartitionLeader(t *testing.T) {
7612 c := createJetStreamClusterExplicit(t, "R3S", 3)
7613 defer c.shutdown()
7614
7615 hub, rg := c.createMockMemRaftGroup("MOCK", 3, newStateAdder)
7616
7617 leader := rg.waitOnLeader()
7618 followers := rg.followers()
7619
7620 // When the leader sends a EntryAddPeer, isolate it from
7621 // the rest of the cluster.
7622 hub.setAfterMsgHook(func(subject, reply string, msg []byte) {
7623 if subject != "$NRG.AE.MOCK" {
7624 return
7625 }
7626 ae, _ := decodeAppendEntry(msg, nil, reply)
7627 if ae == nil || len(ae.entries) != 1 {
7628 return
7629 }
7630 if ae.leader != leader.node().ID() {
7631 return
7632 }
7633 if ae.entries[0].Type == EntryAddPeer {
7634 hub.partition(leader.node().ID(), 1)
7635 }
7636 })
7637
7638 // Add a new node and expect a new leader to be elected
7639 newNode := c.addMockMemRaftNode("MOCK", hub, newStateAdder)
7640 newGroup := append(followers, newNode)
7641 newLeader := newGroup.waitOnLeader()
7642 require_True(t, newLeader != nil)
7643
7644 // If bug is present: The new leader has not yet committed the
7645 // appendEntry containing EntryAddPeer. The new leader (and
7646 // followers) would not update their cluster size until the
7647 // EntryAddPeer was committed, allowing the following
7648 // sequence of events:
7649 // 1) the new leader has initially cluster size of 3
7650 // 2) it sends a peerState message with cluster size 3
7651 // 3) the leader commits the EntryAddPeer from the previous
7652 // leader, and adjusts its cluster size to 4.
7653 // 4) the followers commit the EntryAddPeer, incrementing
7654 // their cluster size to 4. Next, the EntryPeerState is
7655 // committed and the cluster size goes back to 3.
7656 // 5) At this point cluster size from the leader has diverged
7657 // from the cluster size of its followers.
7658
7659 // Expect all nodes to report cluster size of 4
7660 for _, n := range newGroup {
7661 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
7662 if n.node().ClusterSize() != 4 {
7663 return errors.New("node addition still in progress")
7664 }
7665 return nil
7666 })
7667 }
7668
7669 // Finally bring back the old leader
7670 hub.healPartitions()
7671 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
7672 if leader.node().MembershipChangeInProgress() {
7673 return errors.New("membership still in progress")
7674 }
7675 if leader.node().ClusterSize() != 4 {
7676 return errors.New("node addition still in progress")
7677 }
7678 return nil
7679 })
7680
7681 for _, n := range newGroup {
7682 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
7683 if n.node().ClusterSize() != 4 {
7684 return errors.New("node addition still in progress")
7685 }
7686 return nil
7687 })
7688 }
7689
7690 }
7691
7692 func TestNRGLeaderWithoutQuorumAfterPeerAdd(t *testing.T) {
7693 c := createJetStreamClusterExplicit(t, "R3S", 3)
7694 defer c.shutdown()
7695
7696 hub, rg := c.createMockMemRaftGroup("MOCK", 3, newStateAdder)
7697 defer hub.healPartitions()
7698
7699 leader := rg.waitOnLeader()
7700 followers := rg.followers()
7701
7702 // Setup a after message hook to create a partition as soon as
7703 // the leader publishes a EntryAddPeer. The partition will
7704 // prevent committing the entry.
7705 hub.setAfterMsgHook(func(subject, reply string, msg []byte) {
7706 if subject != "$NRG.AE.MOCK" {
7707 return
7708 }
7709 ae, _ := decodeAppendEntry(msg, nil, reply)
7710 if ae == nil || len(ae.entries) != 1 {
7711 return
7712 }
7713 if ae.leader != leader.node().ID() {
7714 return
7715 }
7716
7717 // After EntryAddPeer is published, partition the
7718 // leader and one of the followers. This partition
7719 // can't commit the entry.
7720 if ae.entries[0].Type == EntryAddPeer {
7721 hub.partition(leader.node().ID(), 1)
7722 hub.partition(followers[0].node().ID(), 1)
7723 }
7724 })
7725
7726 newNode := c.addMockMemRaftNode("MOCK", hub, newStateAdder)
7727
7728 // At some point here the cluster gets partitioned in two
7729 // parts: {leader, followers[0]} and {newNode, followers[1]}.
7730 // Neither side should be able to make progress.
7731 newGroup := smGroup{newNode, followers[1]}
7732 newLeader := newGroup.waitOnLeader()
7733
7734 // If the bug is present: we managed to elect a new leader,
7735 // in a 4 node cluster, with only two nodes in the partition!
7736 // This is because of the following sequence of events:
7737 // 1) the follower has received the EntryPeerAdd
7738 // 2) the leader and the other follower have partitioned away
7739 // 3) the entry is uncommitted, however the follower has added
7740 /// the new peer to its peer set, but won't adjust cluster
7741 // size and quorum until after the entry is committed.
7742 // 4) follower becomes a canditate and will become leader with
7743 // a single vote from the new node
7744 require_Equal(t, newLeader, nil)
7745
7746 // Check that node addition completes after healing the partition
7747 hub.healPartitions()
7748 rg = append(rg, newNode)
7749 newLeader = rg.waitOnLeader()
7750 require_True(t, newLeader != nil)
7751 for _, n := range rg {
7752 checkFor(t, 1*time.Second, 10*time.Millisecond, func() error {
7753 if n.node().ClusterSize() != 4 {
7754 return errors.New("node addition still in progress")
7755 }
7756 return nil
7757 })
7758 }
7759 }
7760
7761 func TestNRGRemovedPeerVoteDoesNotElectLeader(t *testing.T) {
7762 c := createJetStreamClusterExplicit(t, "R4S", 4)
7763 defer c.shutdown()
7764
7765 hub, rg := c.createMockMemRaftGroup("MOCK", 4, newStateAdder)
7766 defer hub.healPartitions()
7767
7768 nodeA := rg.waitOnLeader()
7769 require_NotNil(t, nodeA)
7770
7771 followers := rg.followers()
7772 require_Equal(t, len(followers), 3)
7773 nodeB, nodeC, nodeD := followers[0], followers[1], followers[2]
7774
7775 // Partition D away and then remove it.
7776 // D never learns that it is no longer part of the group.
7777 hub.partition(nodeD.node().ID(), 1)
7778
7779 require_NoError(t, nodeA.node().ProposeRemovePeer(nodeD.node().ID()))
7780 valid := smGroup{nodeA, nodeB, nodeC}
7781 checkFor(t, time.Second, 10*time.Millisecond, func() error {
7782 for _, sm := range valid {
7783 node := sm.node()
7784 if size := node.ClusterSize(); size != 3 {
7785 return fmt.Errorf("%q has cluster size %d", node.ID(), size)
7786 }
7787 }
7788 return nil
7789 })
7790
7791 // Partition C with D, leaving two partitions:
7792 // - {A, B} which has a valid quorum
7793 // - {C, D} which is not supposed to have a leader
7794 hub.partition(nodeC.node().ID(), 1)
7795 require_NoError(t, nodeC.node().CampaignImmediately())
7796
7797 err := checkForErr(time.Second, 10*time.Millisecond, func() error {
7798 if nodeC.node().State() == Leader {
7799 return nil
7800 }
7801 return fmt.Errorf("%q has not become leader", nodeC.node().ID())
7802 })
7803 if err == nil {
7804 t.Fatalf("removed peer %q helped elect second leader %q while %q was leader",
7805 nodeD.node().ID(), nodeC.node().ID(), nodeA.node().ID())
7806 }
7807 }
7808
7809 func TestNRGEntryBytesEstimate(t *testing.T) {
7810 n, cleanup := initSingleMemRaftNode(t)
7811 defer cleanup()
7812
7813 n.Lock()
7814 defer n.Unlock()
7815
7816 const largeEntryBytes = 512 * 1024
7817 for _, test := range []struct {
7818 name string
7819 pindex uint64
7820 papplied uint64
7821 bytes uint64
7822 entries uint64
7823 expected uint64
7824 }{
7825 {"no entries in the wal", 0, 0, 0, 100, 0},
7826 {"no bytes in the wal", 1000, 0, 0, 100, 0},
7827 {"pindex equals papplied", 1000, 1000, 1024, 100, 0},
7828 {"large entries", 1000, 0, 1000 * largeEntryBytes, 100, 100 * largeEntryBytes},
7829 {"small entries", 1000, 0, 1000 * 1024, 100, 100 * 1024},
7830 {"offset by papplied", 1500, 500, 1000 * largeEntryBytes, 100, 100 * largeEntryBytes},
7831 {"asking for more than we hold", 1000, 0, 1000 * largeEntryBytes, 2000, 2000 * largeEntryBytes},
7832 } {
7833 t.Run(test.name, func(t *testing.T) {
7834 n.pindex, n.papplied, n.bytes = test.pindex, test.papplied, test.bytes
7835 require_Equal(t, n.entryBytes(test.entries), test.expected)
7836 })
7837 }
7838 }
7839
7840 func TestNRGOverrunUsesBytesWhenEntryCountIsLow(t *testing.T) {
7841 n, cleanup := initSingleMemRaftNode(t)
7842 defer cleanup()
7843
7844 n.Lock()
7845 defer n.Unlock()
7846
7847 // A backlog of large entries. The entry count stays two orders of magnitude
7848 // below the count threshold the whole time, so only the byte threshold can
7849 // catch this.
7850 const largeEntryBytes = 512 * 1024
7851 setAverage := func(entries, avg uint64) {
7852 n.papplied, n.pindex, n.bytes = 0, entries, entries*avg
7853 }
7854
7855 // 2500 entries of 512KiB is ~1.22GB, over pauseQuorumBytes.
7856 setAverage(2500, largeEntryBytes)
7857 require_True(t, 2500 < uint64(pauseQuorumThreshold))
7858 require_True(t, n.overrun(2500, pauseQuorumThreshold, pauseQuorumBytes))
7859
7860 // 900 entries of 512KiB is ~460MB, under pauseQuorumBytes.
7861 setAverage(900, largeEntryBytes)
7862 require_False(t, n.overrun(900, pauseQuorumThreshold, pauseQuorumBytes))
7863
7864 // The entry count path must still work for small entries.
7865 setAverage(2500, 1024)
7866 require_False(t, n.overrun(2500, pauseQuorumThreshold, pauseQuorumBytes))
7867 setAverage(pauseQuorumThreshold+1, 1024)
7868 require_True(t, n.overrun(pauseQuorumThreshold+1, pauseQuorumThreshold, pauseQuorumBytes))
7869 }
7870
7871 func TestNRGLeaderOverrunOnLargeEntries(t *testing.T) {
7872 const largeEntryBytes = 512 * 1024
7873 for _, test := range []struct {
7874 name string
7875 lagging string // which counter lags behind
7876 expected bool
7877 avg uint64
7878 }{
7879 {"uncommitted large entries", "commit", true, largeEntryBytes},
7880 {"uncommitted small entries", "commit", false, 1024},
7881 {"unapplied large entries", "applied", true, largeEntryBytes},
7882 {"unapplied small entries", "applied", false, 1024},
7883 } {
7884 t.Run(test.name, func(t *testing.T) {
7885 n, cleanup := initSingleMemRaftNode(t)
7886 defer cleanup()
7887
7888 n.Lock()
7889 defer n.Unlock()
7890
7891 // 2500 entries is far below pauseQuorumThreshold, so whether we are
7892 // overrun depends entirely on the byte estimate.
7893 const entries = 2500
7894 n.papplied, n.pindex, n.bytes = 0, entries, entries*test.avg
7895 if test.lagging == "commit" {
7896 // We are not getting quorum from our followers.
7897 n.commit, n.applied = 0, 0
7898 } else {
7899 // We are committing but too slow to apply.
7900 n.commit, n.applied = entries, 0
7901 }
7902
7903 require_Equal(t, n.isLeaderOverrun(), test.expected)
7904 })
7905 }
7906 }
7907
7908 func TestNRGCachePendingEntryBoundedByBytes(t *testing.T) {
7909 for _, test := range []struct {
7910 name string
7911 payloadSize int
7912 inserts int
7913 capped bool
7914 }{
7915 // Large entries: the cache fills up to paeDropBytes and stops
7916 // there, nowhere near paeDropThreshold.
7917 {"large entries stop at the byte cap", 512 * 1024, 1000, true},
7918 // Small entries: 1000 of them is ~1MB, so nothing is dropped.
7919 {"small entries are all cached", 1024, 1000, false},
7920 } {
7921 t.Run(test.name, func(t *testing.T) {
7922 n, cleanup := initSingleMemRaftNode(t)
7923 defer cleanup()
7924
7925 entries := []*Entry{newEntry(EntryNormal, make([]byte, test.payloadSize))}
7926 ae := encode(t, &appendEntry{leader: "S1Nunr6R", term: 1, entries: entries})
7927
7928 n.Lock()
7929 defer n.Unlock()
7930
7931 sz := n.entryStoreSize(ae)
7932 require_True(t, sz > 0)
7933
7934 // We stop caching once we'd go over paeDropBytes.
7935 expected := test.inserts
7936 if test.capped {
7937 expected = int((paeDropBytes + sz - 1) / sz)
7938 }
7939
7940 // A long history of entries that were applied but not snapshotted yet
7941 // must not dilute what we account for, only what's cached counts.
7942 n.papplied, n.bytes = 0, 100*1024*1024
7943
7944 for i := 1; i <= test.inserts; i++ {
7945 n.pindex = uint64(i)
7946 n.cachePendingEntry(ae)
7947 }
7948
7949 require_Len(t, len(n.pae), expected)
7950 // Whatever we dropped, it was not because of the entry count.
7951 require_True(t, len(n.pae) < paeDropThreshold)
7952 // We must account for exactly what we've cached.
7953 require_Equal(t, n.paeBytes, uint64(len(n.pae))*sz)
7954 })
7955 }
7956 }
7957
7958 func TestNRGCachePendingEntryBytesAccounting(t *testing.T) {
7959 n, cleanup := initSingleMemRaftNode(t)
7960 defer cleanup()
7961
7962 nats0 := "S1Nunr6R" // "nats-0"
7963 newAE := func(index uint64, payload int) *appendEntry {
7964 entries := []*Entry{newEntry(EntryNormal, make([]byte, payload))}
7965 return encode(t, &appendEntry{leader: nats0, term: 1, pterm: 1, pindex: index - 1, entries: entries})
7966 }
7967
7968 n.Lock()
7969 defer n.Unlock()
7970
7971 large := newAE(3, 4*1024)
7972 ssz, lsz := n.entryStoreSize(newAE(1, 128)), n.entryStoreSize(large)
7973 require_True(t, lsz > ssz)
7974
7975 // Cache a couple of entries.
7976 for i := uint64(1); i <= 3; i++ {
7977 n.pindex = i
7978 n.cachePendingEntry(newAE(i, 128))
7979 }
7980 require_Len(t, len(n.pae), 3)
7981 require_Equal(t, n.paeBytes, 3*ssz)
7982
7983 // Re-caching an index with a different value must not account for it twice.
7984 n.pindex = 3
7985 n.cachePendingEntry(large)
7986 require_Len(t, len(n.pae), 3)
7987 require_Equal(t, n.paeBytes, 2*ssz+lsz)
7988
7989 // Truncating must remove the bytes of the entries the WAL no longer has.
7990 n.pterm, n.pindex = 1, 3
7991 n.truncateWAL(1, 2)
7992 require_Len(t, len(n.pae), 2)
7993 require_Equal(t, n.paeBytes, 2*ssz)
7994
7995 // Resetting the cache clears our accounting.
7996 n.resetPendingEntries()
7997 require_Len(t, len(n.pae), 0)
7998 require_Equal(t, n.paeBytes, 0)
7999 }