Skip to content

A3-2: Log compaction and Snapshot interface #151

Closed as not planned
Closed as not planned

Description

@scttfrdmn

Summary

Add a Snapshot interface and log compaction to ConsensusEngine. Without compaction, an unbounded Raft log is a memory (and eventually disk) leak for long-running clusters. Compaction bounds log growth at LogCompactionKeep entries (default 1000) after the snapshot index.

Background

In Raft, compaction works by taking a snapshot of state machine state at a given log index, then discarding all log entries up to that index. The snapshot replaces those entries for the purpose of sending state to lagging followers. This issue implements the compaction trigger and storage interfaces without changing the Raft protocol correctness guarantees.

New Interface: Snapshot

Add to internal/distributed/log/interface.go:

// Snapshot stores a point-in-time state machine snapshot.
type Snapshot interface {
    // Save persists a snapshot at the given log index and term.
    Save(index, term uint64, data []byte) error
    // Load retrieves the most recent snapshot.
    // Returns (0, 0, nil, nil) if no snapshot exists.
    Load() (index, term uint64, data []byte, err error)
}

Add to ConsensusLog:

// TruncatePrefix removes all entries with index ≤ upToIndex.
// Used after taking a snapshot.
TruncatePrefix(upToIndex uint64) error

Compaction in ConsensusEngine

const (
    LogCompactionThreshold = 10_000  // trigger when log grows this many entries past snapshot
    LogCompactionKeep      = 1_000   // entries to retain after prefix truncation
)

After applying a log entry, if log.LastIndex() - snapshotIndex > LogCompactionThreshold:

  1. Serialize current state machine state → data
  2. Call snapshot.Save(snapshotIndex, snapshotTerm, data)
  3. Call log.TruncatePrefix(snapshotIndex - LogCompactionKeep)

Implementations

  • MemorySnapshot: in-memory, for tests
  • BboltSnapshot: stores snapshot in same bbolt database as BboltConsensusLog, different bucket

Acceptance Criteria

  • Test: append 15,000 entries (above threshold), verify compaction triggers, log length drops to ≤ 1,000
  • Test: after compaction, log.LastIndex() and log.LastTerm() still return correct values
  • Test: BboltSnapshot round-trip (save → close → reopen → load, verify data)
  • TruncatePrefix is no-op on MemoryLog when index ≤ 0
  • go test -race ./internal/distributed/log/... passes
  • go test -race ./internal/distributed/... passes

Dependencies

  • Requires A3-1 (BboltConsensusLog with TruncatePrefix, bbolt in go.mod)
  • Requires A1-1 (ConsensusLog interface to extend)

Activity

  1. added
    type: enhancement
    priority: high
    area: distributed
    on Apr 7, 2026
  2. scttfrdmn commented on Jul 30, 2026

    @scttfrdmn
    OwnerAuthor

    Correction: there is no state machine state to snapshot

    Filing note from the v0.10.0 review.

    This issue proposes serializing "state machine state" into a snapshot so the Raft log can be truncated. That state does not exist. The consensus engine has a log, but nothing is ever applied from it.

    applyLogEntry (internal/distributed/consensus.go:739-750) is three empty arms:

    func (ce *ConsensusEngine) applyLogEntry(entry *LogEntry) {
    	slog.Info("applying log entry", "index", entry.Index, "type", entry.Type)
    
    	switch entry.Type {
    	case EntryTypeLeaderElection:
    		// Leader election entry applied
    	case EntryTypeConfigChange:
    		// Apply configuration change
    	case EntryTypeOperation:
    		// Apply operation
    	}
    }

    Grep confirms the log is effectively empty of anything worth compacting: EntryTypeOperation and EntryTypeConfigChange appear only at their declaration (consensus.go:81-82) and in the dead switch arms above. Nothing anywhere appends an entry of either type. The log therefore holds one bootstrap noop plus one entry per election win — a handful of entries over a cluster's lifetime, with no application state derived from them.

    Compaction is also not on the data path: Coordinator.executeLocally (internal/distributed/coordinator.go:550-602) calls the S3 backend directly and never consults the log, commitIndex, term, or leadership. So log growth is not a real pressure today.

    Suggested adjustment

    Snapshotting is meaningful only after there is an applied state machine. Sequence this issue after a "define and apply the replicated state machine" issue — which does not yet exist and should probably be filed against v0.11.0 alongside #139.

    Related: see #169, which evaluates whether S3 conditional writes (If-None-Match/If-Match) can replace the Raft layer entirely. If that evaluation lands in favor, this issue and its prerequisite both become moot — which is a further argument for not building the snapshot machinery first.

  3. scttfrdmn commented on Aug 2, 2026

    @scttfrdmn
    OwnerAuthor

    Correction: there is no state machine state to snapshot

    Re-verified against main. The Raft mechanics in this issue are correct — the object they operate on does not exist.

    Compaction's contract is that a snapshot replaces a prefix of the log: a follower that receives the snapshot plus the retained suffix ends in the same state as one that replayed every entry. That only holds if the snapshot captures everything the discarded entries would have produced. Here, applyLogEntry (internal/distributed/consensus.go:739-750) is:

    func (ce *ConsensusEngine) applyLogEntry(entry *LogEntry) {
    	slog.Info("applying log entry", "index", entry.Index, "type", entry.Type)
    	switch entry.Type {
    	case EntryTypeLeaderElection:
    		// Leader election entry applied
    	case EntryTypeConfigChange:
    		// Apply configuration change
    	case EntryTypeOperation:
    		// Apply operation
    	}
    }

    Three empty arms. Applying an entry mutates nothing, so there is no state machine state — and step 1 of this issue's compaction sequence, "Serialize current state machine state → data", has no referent. EntryTypeOperation also has exactly two occurrences repo-wide (consensus.go:82 declaring it, :747 above): nothing ever appends an operation entry. The log is empty of the entry type compaction exists to bound.

    Meanwhile executeLocally (internal/distributed/coordinator.go:550-602) calls the backend directly and never consults the log or leadership, so filesystem operations do not flow through consensus at all. The log is not the write path; it is beside it.

    This makes the trigger unreachable too. "Append 15,000 entries, verify compaction triggers" can only be satisfied by a test that appends synthetic entries directly to the log — which tests TruncatePrefix and the threshold arithmetic, but not compaction, since there is no state whose preservation across truncation could be checked. The MemorySnapshot/BboltSnapshot round-trip test is real and worth having; it just tests a byte-blob store.

    Ordering. The prerequisite is a state machine: a definition of what an EntryTypeOperation entry contains, a deterministic apply that mutates named state, and a writer that appends those entries — which means routing executeLocally through the log for strongly-consistent operations. That is #144's territory (NegotiateConsistency) and overlaps the executeStrongConsistency problem noted in #169: today it fans the same PUT to N nodes writing the same key and calls majority success "linearizable" (internal/distributed/doc.go:47-84), which is a reachability signal, not linearizability.

    Suggested resequencing:

    1. Define the state machine and the EntryTypeOperation payload; make applyLogEntry actually apply. New issue; this is the real blocker.
    2. Route operations through the log so entries exist.
    3. Then this issue: Snapshot interface, threshold, TruncatePrefix, with a test that snapshots real state, truncates, replays the suffix, and asserts state equality against an uncompacted replica. That test is the only one that proves compaction is safe, and it is writable only after step 1.

    Doing 3 first is not wasted — the interfaces and bbolt bucket are needed regardless — but it should not close with an acceptance criterion implying compaction is proven correct. The unbounded-log memory leak this issue cites as motivation also is not live: nothing appends operation entries, so the log does not grow during normal operation.

    Worth flagging in the same breath: this is the second issue in the A3 sequence whose premise is that consensus code is further along than it is. #169 asks whether S3 conditional writes make most of this unnecessary, and that evaluation is only cheap before more consensus code is written. Answering it first may retire this issue entirely.

    Accurate as written: the Snapshot interface shape, TruncatePrefix as a ConsensusLog addition, threshold/keep as separate constants, and the memory-vs-bbolt implementation split are all right, and match how Raft implementations normally factor this.

  4. added
    effort: medium
    on Aug 3, 2026
  5. scttfrdmn commented on Aug 3, 2026

    @scttfrdmn
    OwnerAuthor

    Closing as not-the-direction, per the decision on #169.

    §5 of docs/design/conditional-writes-vs-raft.md names this one for a reason beyond the direction change: its premise does not hold on today's code. It would serialize state-machine state at a log index — and there is no state machine. applyLogEntry (internal/distributed/consensus.go) is three empty comment arms, and nothing appends EntryTypeOperation, so a snapshot at index N would capture nothing and compaction would discard entries that were never applied to anything.

    That was already true before the CAS decision; adopting CAS just removes the log the compaction would have bounded. Closing #128, #130, and #133 alongside.

    Reference: https://github.com/scttfrdmn/objectfs/blob/main/docs/design/conditional-writes-vs-raft.md

  6. added
    resolution: wontfix
    on Aug 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: distributedeffort: mediumpriority: highresolution: wontfixtype: enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions