#721·raft

InstallSnapshot keeps divergent entries below the snapshot; a later leader replicates them and other servers apply never-committed entries (safety; related to #697)

Author: allthingssecurityCreated Sep 26, 2026Updated Sep 26, 2026

Hi,

I originally reported this to HashiCorp security, and they asked me to open a public issue so it can be looked at together with #697 (OSSLIBS-9) and #704.

Short version: the same missing InstallSnapshot rule behind #697 can also make servers apply writes that were never committed. #697 shows it as a livelock, and @tehsphinx showed it as a panic with a MonotonicLogStore. With a normal log store (raft-boltdb, InmemStore) it's worse: it's a safety problem.

How it happens

A follower gets some entries from a leader (term 2), but that leader dies before they are committed. A new leader (term 3) commits different entries at the same indexes, takes a snapshot, and sends it to the follower. When the follower installs the snapshot, it only compacts its log (it keeps up to TrailingLogs entries). It never checks whether those entries match the snapshot, so the old, never-committed term-2 entries stay in its log store. Later, that follower becomes leader, via LeadershipTransfer in my test (a normal election works too). A new server joins and asks for the log from the start. The leader sends it the old stale entries straight from its log store, and the new server commits and applies them to its FSM. The new server has now applied writes that never really happened, and they conflict with what was actually committed at those indexes. It stays that way until the server gets a snapshot. If it takes its own snapshot in the meantime, the wrong state gets saved.

Tested on: v1.8.0 / main (871f108). The code goes back to 6f4a02f (2016), so I think every version since then is affected when the log store isn't a MonotonicLogStore.

Reproduction

I wrote a self-contained test (5 nodes, in memory) that runs against the unmodified library. With the default TrailingLogs:

step4: F installed snapshot 10713; F.lastLog=(212,t2) ...; 200 entries at indexes < snapshot conflict with the committed log; first: index 13: F has (t2,"STALE-0") but committed is (t3,"") step6: new server N applied 190 FSM commands in total; 180 of them are uncommitted STALE entries So 180 of the 190 commands applied on the new server were stale, never-committed entries. I also tried it with #704 applied, and the result is the same, because #704 only kicks in when the follower has an entry at the snapshot index.

Test code (drop it into the package, e.g. as l01_test.go, and run go test -run TestLeanL01 -v) // L01 harness (Lean: Replication.install_keeps_divergent / stale_served). // // Claim: installSnapshot on a non-monotonic LogStore keeps the follower's divergent, // never-committed entries *below* the snapshot index (raft.go:1966-1972 -> // compactLogs(req.LastLogIndex), snapshot.go:224-259). If that node later becomes leader, // setNewLogs (replication.go:614-630) serves those entries to a lagging/new follower, which // appends them, commits min(LeaderCommitIndex, lastIndex) (raft.go:1590) and APPLIES them to its // FSM although they were never committed and conflict with the committed log at the same index. // // Package copy of hashicorp/raft @ 871f108; nothing in the copy is modified. package raft

import ( "fmt" "strings" "sync" "testing" "time" )

type histFSM struct { *MockFSM mu sync.Mutex hist []string // every Apply ever made, never reset by Restore }

func (h *histFSM) Apply(l *Log) interface{} { h.mu.Lock() h.hist = append(h.hist, fmt.Sprintf("%d/t%d/%s", l.Index, l.Term, l.Data)) h.mu.Unlock() return h.MockFSM.Apply(l) }

func (h *histFSM) history() []string { h.mu.Lock() defer h.mu.Unlock() return append([]string{}, h.hist...) }

func waitFor(t *testing.T, what string, d time.Duration, cond func() bool) { t.Helper() deadline := time.Now().Add(d) for time.Now().Before(deadline) { if cond() { return } time.Sleep(10 * time.Millisecond) } t.Fatalf("timeout waiting for %s", what) }

func TestLeanL01_StaleEntriesBelowSnapshotAreServedAndApplied(t *testing.T) { runL01(t, 500, 1300) }

// Same scenario with the library default TrailingLogs (10240). func TestLeanL01_DefaultTrailingLogs(t *testing.T) { runL01(t, DefaultConfig().TrailingLogs, 10700) }

func runL01(t *testing.T, trailing uint64, newEntries int) { conf := inmemConfig(t) conf.TrailingLogs = trailing // any value >= the divergent follower's lastLogIndex conf.SnapshotThreshold = 1 << 40 // only explicit snapshots conf.SnapshotInterval = 1 * time.Hour // mk := func() FSM { return &histFSM{MockFSM: &MockFSM{}} } c := MakeClusterCustom(t, &MakeClusterOpts{Peers: 5, Bootstrap: true, Conf: conf, MakeFSMFunc: mk}) defer c.Close()

// 1. committed prefix
A := c.Leader()
for i := 0; i < 10; i++ {
	if err := A.Apply([]byte(fmt.Sprintf("good-%d", i)), time.Second).Error(); err != nil {
		t.Fatal(err)
	}
}
waitFor(t, "prefix replicated", 5*time.Second, func() bool {
	for _, r := range c.rafts {
		if r.AppliedIndex() < A.getLastIndex() {
			return false
		}
	}
	return true
})
F := c.Followers()[0]
aTerm := A.getCurrentTerm()
t.Logf("step1: leader A=%s term=%d, chosen follower F=%s, lastIndex=%d", A.localID, aTerm, F.localID, A.getLastIndex())

// 2. partition {A,F} | {rest}; A (still leader for ~LeaderLeaseTimeout) appends 200
//    entries that reach only F -> never committed.
c.Partition([]ServerAddress{A.localAddr, F.localAddr})
for i := 0; i < 200; i++ {
	A.Apply([]byte(fmt.Sprintf("STALE-%d", i)), 50*time.Millisecond)
}
var fLast uint64
waitFor(t, "F to receive stale entries", 3*time.Second, func() bool {
	l := F.getLastIndex()
	stable := l == fLast && l > 11
	fLast = l
	return stable && l >= 150
})
t.Logf("step2: F received uncommitted entries; F.lastIndex=%d (A.lastIndex=%d, A.commit=%d)",
	F.getLastIndex(), A.getLastIndex(), A.getCommitIndex())

// 3. majority side elects a new leader L and commits newEntries new entries, then snapshots.
var L *Raft
waitFor(t, "new leader on majority side", 5*time.Second, func() bool {
	for _, r := range c.rafts {
		if r != A && r != F && r.State() == Leader {
			L = r
			return true
		}
	}
	return false
})
var fut Future
for i := 0; i < newEntries; i++ {
	fut = L.Apply([]byte(fmt.Sprintf("new-%d", i)), 5*time.Second)
}
if err := fut.Error(); err != nil {
	t.Fatal(err)
}
if err := L.Snapshot().Error(); err != nil {
	t.Fatal(err)
}
snapIdx, _ := L.getLastSnapshot()
lFirst, _ := c.stores[c.IndexOf(L)].FirstIndex()
t.Logf("step3: new leader L=%s term=%d lastIndex=%d commit=%d snapshot=%d L.firstLogIndex=%d",
	L.localID, L.getCurrentTerm(), L.getLastIndex(), L.getCommitIndex(), snapIdx, lFirst)

// 4. A goes away for good; F rejoins the majority -> needs InstallSnapshot.
A.Shutdown().Error()
c.FullyConnect()
c.Disconnect(A.localAddr)
waitFor(t, "F to catch up via snapshot", 30*time.Second, func() bool {
	s, _ := F.getLastSnapshot()
	return s >= snapIdx && F.AppliedIndex() >= L.getLastIndex()
})
fs, _ := F.getLastSnapshot()
fl, flt := F.getLastLog()
t.Logf("step4: F installed snapshot %d; F.lastLog=(%d,t%d) F.applied=%d", fs, fl, flt, F.AppliedIndex())

// Evidence of the Log Matching violation on F: entries below the snapshot index that
// conflict with the committed log (compare with a majority node that never compacted).
var H *Raft
for _, r := range c.rafts {
	if r != A && r != F && r != L {
		H = r
		break
	}
}
fStore, hStore := c.stores[c.IndexOf(F)], c.stores[c.IndexOf(H)]
conflicts := 0
var first string
for i := uint64(1); i <= fLast; i++ {
	var fl, hl Log
	if fStore.GetLog(i, &fl) != nil || hStore.GetLog(i, &hl) != nil {
		continue
	}
	if fl.Term != hl.Term {
		conflicts++
		if first == "" {
			first = fmt.Sprintf("index %d: F has (t%d,%q) but committed is (t%d,%q)", i, fl.Term, fl.Data, hl.Term, hl.Data)
		}
	}
}
ff, _ := fStore.FirstIndex()
t.Logf("step4: F log store firstIndex=%d; %d entries at indexes < snapshot %d conflict with the committed log; first: %s",
	ff, conflicts, fs, first)

// 5. F becomes leader (ordinary leadership transfer), then a brand-new server joins.
if err := L.LeadershipTransferToServer(F.localID, F.localAddr).Error(); err != nil {
	t.Fatalf("transfer: %v", err)
}
waitFor(t, "F leader", 5*time.Second, func() bool { return F.State() == Leader })
t.Logf("step5: F is leader, term=%d commit=%d", F.getCurrentTerm(), F.getCommitIndex())

c1, err := makeCluster(t, &MakeClusterOpts{Peers: 1, Bootstrap: false, Conf: conf, MakeFSMFunc: mk})
if err != nil {
	t.Fatal(err)
}
c.Merge(c1)
c.FullyConnect()
c.Disconnect(A.localAddr)
N := c1.rafts[0]
if err := F.AddNonvoter(N.localID, N.localAddr, 0, 5*time.Second).Error(); err != nil {
	t.Fatalf("add nonvoter: %v", err)
}
waitFor(t, "N to catch up", 20*time.Second, func() bool { return N.AppliedIndex() >= F.getCommitIndex()-1 })

// 6. Did N ever apply an entry that was never committed?
nh := c.fsms[len(c.fsms)-1].(*histFSM).history()
hh := c.fsms[c.IndexOf(H)].(*histFSM).history()
committedAt := map[string]string{}
for _, e := range hh {
	committedAt[strings.SplitN(e, "/", 2)[0]] = e
}
bad := 0
var ex []string
for _, e := range nh {
	if strings.Contains(e, "STALE-") {
		bad++
		if len(ex) < 3 {
			idx := strings.SplitN(e, "/", 2)[0]
			ex = append(ex, fmt.Sprintf("N applied %s ; committed entry at %s is %s", e, idx, committedAt[idx]))
		}
	}
}
t.Logf("step6: new server N applied %d FSM commands in total; %d of them are uncommitted STALE entries", len(nh), bad)
for _, s := range ex {
	t.Logf("  %s", s)
}
if bad > 0 {
	t.Errorf("CONFIRMED L01: State Machine Safety violated - a server applied %d never-committed entries that conflict with committed entries at the same index", bad)
}

}

// Candidate (NOT confirmed as a bug): installSnapshot sets lastApplied := LastLogIndex // (raft.go:1954) but never raises commitIndex. Hypothesis: CommitIndex() stays below // AppliedIndex(). Result: only transient - the leader's next CommitTimeout-driven // replicateTo sends an (empty) AppendEntries carrying LeaderCommitIndex, which fixes it. func TestLeanCand_CommitIndexBehindAppliedAfterInstall(t testing.T) { conf := inmemConfig(t) conf.TrailingLogs = 10 conf.SnapshotThreshold = 1 << 40 conf.SnapshotInterval = time.Hour c := MakeCluster(3, t, conf) defer c.Close() L := c.Leader() F := c.Followers()[0] c.Disconnect(F.localAddr) var fut Future for i := 0; i < 100; i++ { fut = L.Apply([]byte(fmt.Sprintf("x-%d", i)), time.Second) } if err := fut.Error(); err != nil { t.Fatal(err) } if err := L.Snapshot().Error(); err != nil { t.Fatal(err) } c.FullyConnect() waitFor(t, "F snapshot", 5time.Second, func() bool { return F.AppliedIndex() >= L.getLastIndex() }) time.Sleep(500 * time.Millisecond) // idle cluster: only heartbeats t.Logf("follower after InstallSnapshot on idle cluster: CommitIndex()=%d AppliedIndex()=%d LastIndex()=%d; leader CommitIndex()=%d", F.CommitIndex(), F.AppliedIndex(), F.LastIndex(), L.CommitIndex()) if F.CommitIndex() < F.AppliedIndex() { t.Errorf("commit lag persisted: CommitIndex() %d < AppliedIndex() %d", F.CommitIndex(), F.AppliedIndex()) } }

A possible fix

When installing a snapshot, only keep the follower's existing log if it actually contains the snapshot's last entry with the same term. That's step 6 of Figure 13 in the Raft paper. If it doesn't, delete everything above the follower's commit index (from before the install) and reset lastLog to the snapshot. That's step 7. Entries up to the old commit index are safe to keep, because they're committed and match the leader's.

With this change my test passes (no stale entries applied), and the existing test suite still passes. It would need to be lined up with #704 and with the MonotonicLogStore path @tehsphinx described.

Diff against 871f108 --- a/raft.go 2026-09-24 12:23:47 +++ b/raft.go 2026-09-24 12:28:56 @@ -1951,6 +1951,7 @@ }
	// Update the lastApplied so we don't replay old logs
  • commitBefore := r.getCommitIndex() r.setLastApplied(req.LastLogIndex)

    // Update the last stable snapshot info @@ -1959,6 +1960,23 @@ // Restore the peer set r.setLatestConfiguration(reqConfiguration, reqConfigurationIndex) r.setCommittedConfiguration(reqConfiguration, reqConfigurationIndex)

  • // Raft Fig. 13 steps 6-7. If our log contains the snapshot's last entry,

  • // Log Matching guarantees every entry <= LastLogIndex equals the leader's,

  • // and the old behaviour (compact, keep trailing logs) is safe. Otherwise

  • // only entries <= our commit index are known to be committed (hence equal

  • // to the leader's); everything above may be divergent and never committed

  • // and must be discarded, or this node could later serve it as leader.

  • var snapEntry Log

  • keep := r.logs.GetLog(req.LastLogIndex, &snapEntry) == nil && snapEntry.Term == req.LastLogTerm

  • if !keep {

  •   if lastIdx, _ := r.getLastLog(); lastIdx > commitBefore {
  •       if err := r.logs.DeleteRange(commitBefore+1, lastIdx); err != nil {
  •           r.logger.Error("failed to discard unverified log suffix", "error", err)
  •       }
  •   }
  •   r.setLastLog(req.LastLogIndex, req.LastLogTerm)
  • }

    // Clear old logs if r.logs is a MonotonicLogStore. Otherwise compact the // logs. In both cases, log any errors and continue.

For transparency: I found this using a Lean 4 model of the replication and snapshot logic, with help from Claude Code (Anthropic's Claude Opus 5.5) for the analysis and the test, and then confirmed it against the real library myself. I'm happy to test any patches or send a PR if that's useful.

Thanks, Shashank Mohan Jain