Skip to content

feat(raft): compact_log removes compacted entries from disk - #2391

Merged
bplatz merged 8 commits into
mainfrom
fix/raft-compact-log
Nov 15, 2026
Merged

bplatz merged 8 commits into
mainfrom
fix/raft-compact-log

Conversation

@bplatz

@bplatz bplatz commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up: #2406

Problem

openraft compacts by snapshotting and then purging the log behind the snapshot. The filesystem log store keeps entries in 4 MiB segments, and purge_through unlinks only a segment whose every entry is at or below the purge point (storage/fs.rs, Inner::purge_through). The segment that straddles the purge point is kept whole. Entries below the marker are skipped on read, but their bytes stay on disk.

On a quiet group the whole log is usually one segment, and it keeps taking appends. Snapshot plus purge removes its bytes only if nothing was appended after the snapshot index. A leader's empty entry after election (which happens at every restart), any application write, or a kv sweep landing in that window keeps the whole segment. openraft reports the purge as complete either way.

So a value deleted from the state machine stays readable under log/ until its segment ages out. With the default policy (snapshot every 5,000 entries, purge keeping 1,000), that can take months on a low-traffic group. A copy of the raft directory copies it too.

Change

RaftGroup::compact_log(covering, timeout) runs on one node. covering is the index of the write whose effect has to leave the disk: the delete's log id, which the propose relay now reports on any node (below). It:

  1. waits until this node has applied covering, so a node that hasn't yet applied the delete doesn't compact short of it;
  2. seals the tail segment, so later appends start a new one, and takes its last index N;
  3. waits until entries through N are applied;
  4. triggers a snapshot and waits until one covers N, re-triggering if a build already in flight swallowed the trigger;
  5. purges through N and waits for the purge to finish (openraft's purged metric is set only after the storage purge returns);
  6. removes superseded snapshots, failing if any removal fails;
  7. returns CompactionError::Retained unless storage reports that the oldest entry it holds is above N.

It returns Some(N), or None if the log was empty. Storage that can't report what it retains, or can't discard superseded snapshots, makes it refuse before step 1, so nothing is snapshotted or purged. Each node compacts its own log, so a cluster runs it on every node with the same covering. On a leader, openraft delays the purge while a replication task is still reading those entries, and a follower that falls behind catches up from the snapshot.

A write's log id from any node

forward::propose_via_leader now returns Proposed { log_id, response }. Before, only the leader could name a write's index (through client_write), so a follower that relayed a delete had nothing to pass as covering, and nothing to wait on before reading its own delete back. On the leader the log id is client_write's. A follower gets it from the leader's /propose reply, in an x-fluree-raft-log-id header rather than the body, so nodes on either side of an upgrade still read each other's replies. log_id is None only when the leader is too old to send the header; a malformed header is ProposeError::Unknown, like a malformed body.

RaftGroup::wait_applied(index, timeout) waits until this node has applied that index, so a read of its state afterwards sees the write.

This changes propose_via_leader's return type. Nothing else in the workspace calls it.

Storage API

All non-breaking (provided methods):

  • RaftLogStore::seal: the default returns the tail, which is right for backends whose purge is exact. The fs backend marks the segment sealed (in memory only), and append starts a new segment after a sealed one.
  • RaftLogStore::first_retained_index: the oldest index physically held. The default refuses, so a backend that can't answer can't make compaction report success.
  • RaftSnapshotStore::discard_superseded: a strict version of the reclamation that write already did. The default refuses.

The fs snapshot store now holds a lock across write and discard_superseded, so a discard can't delete the files of a snapshot that is written but not yet named current. Reclamation after a write is still best-effort and logs a warning.

The fs log now finishes an interrupted purge when it opens. purge_through writes its marker before it unlinks, and a crash between the two used to leave whole segments below the marker until a later, higher purge, which a quiet node might never run.

Why seal instead of rewriting the straddling segment

The scan on open requires contiguous, non-overlapping segments. Rewriting the straddling segment's suffix into a new file would need a new crash-recovery path for the overlap window. Sealing leaves purge_through's existing crash ordering unchanged: it still unlinks whole segments only, oldest first, each durable before the next.

Tests

  • fs storage: two paired tests. Without a seal, a purge into a segment keeps a known payload on disk. With a seal before the later append, the same sequence unlinks it. Also:
    • a sealed segment and the one after it reopen as one log;
    • entries replacing a truncated sealed tail start a new segment;
    • the open finishes a purge interrupted between its marker and its unlinks;
    • discard_superseded removes orphans, removes every snapshot file when none is current, and fails on a file it can't remove, while write still succeeds;
    • writes racing a discard never lose a staged snapshot (fails within the first few writes without the lock).
  • kv_group:
    • snapshot_and_purge_alone_leave_a_deleted_value_on_disk shows the problem: openraft's own snapshot and purge, with one write between them, leave a deleted value's bytes in a file.
    • compact_log_removes_a_deleted_value_from_disk writes the value, refreshes it, snapshots it, deletes it, and runs compact_log while another task keeps writing. It then searches every file under the group root, snapshots included, for the value's bytes, restarts the group, and checks it recovers from the compaction snapshot with the surviving writes intact. With the seal disabled, compact_log fails with Retained; with snapshot reclamation disabled, the search finds the old snapshot.
    • compaction_waits_to_apply_the_write_it_covers starts compaction with the index of a delete not yet proposed, checks it waits, then deletes and checks no file holds the value.
    • storage_on_the_defaults_refuses_before_any_step runs a log store and a snapshot store that keep the trait defaults, and checks each refuses with neither a snapshot nor a purge taken.
    • every_node_compacts_and_the_group_keeps_replicating deletes a value on a three-node group through a follower, which reads its own delete back after wait_applied. It runs compact_log on every node with the index the relay returned, checks no node's files hold the value, and checks the group still replicates.
  • multi_node_group: a follower's relayed propose reports the entry right after one the leader proposed directly, and after wait_applied the follower reads its own write. The relay fault proxy now passes the header through; new cases cover a leader that doesn't send it (None, response intact) and a malformed one (Unknown).

docs/design/raft-core.md has a new section covering the problem, the steps, what compact_log doesn't cover (a delete it isn't given, expired-but-not-evicted kv records, values removed after it returns, freed device blocks), and why the fix seals instead of rewriting.

openraft compacts by snapshotting and purging the log behind the
snapshot, but the filesystem log keeps entries in 4 MiB segments and a
purge unlinks only a segment whose every entry is purged. The segment
holding the purge point keeps its bytes, and on a quiet group that is
usually the whole log, still taking appends. A value deleted from the
state machine therefore stays readable in raft/log/ for as long as its
segment lives, and a backup of the directory copies it.

RaftGroup::compact_log seals the tail segment so later appends start a
new one, waits until entries through its last index N are applied,
snapshots, purges through N, removes superseded snapshots, and returns
an error unless storage confirms no entry at or below N is still on
disk.

Storage gains RaftLogStore::seal and first_retained_index, and
RaftSnapshotStore::discard_superseded. The fs snapshot store now
serializes writes with discard, so a discard cannot remove a snapshot
staged but not yet named current; reclamation after a write stays
best-effort.
@bplatz bplatz added the enhancement New feature or request label Nov 13, 2026
@bplatz
bplatz marked this pull request as ready for review November 13, 2026 21:23
fs storage: a purge into an unsealed segment keeps its bytes, and the
same sequence with a seal unlinks it; a sealed segment and its
successor reopen as one log; entries replacing a truncated sealed tail
start a new segment; discard_superseded removes orphans, removes every
snapshot when none is current, and fails on a file it cannot remove
while write still succeeds.

kv_group: snapshot plus purge alone leaves a deleted value's bytes on
disk once a write lands between them; compact_log, with writes landing
throughout, leaves no file holding it, and the group restarts from the
compaction snapshot with surviving writes intact; every node of a
three-node group compacts and the group keeps replicating.
Why openraft's purge leaves a deleted value in log/, what compact_log does about it, and why it seals rather than rewrites the straddling segment.
@bplatz
bplatz requested a review from a team November 13, 2026 21:29

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bplatz this is nice, and sealing rather than rewriting the straddling segment makes sense to me: purge_through keeps its crash ordering and the scan on open never has to learn about overlapping segments. Claude ran your tests and some mutations on a box, and the end-to-end grep does go red when the seal is disabled and first_retained_index is made to lie.

Two headline notes:

(1) "a cluster runs it on every node" doesn't hold for a node that hasn't applied the delete yet. compact_log compacts through that node's own tail, so a lagging follower returns Ok with the value still in its snapshot (reproduced below). I think taking the index that has to be covered (the delete's log_id.index) and waiting for it before the seal would make the per-node call mean the same thing everywhere

(2) this is another instance of a class we keep hitting, a removal the layer above reports complete while the bytes stay on storage:

a branch drop leaving the @shared/dicts blobs only it referenced (#1862); a hard drop of a nested ledger keeping its files (8519b4dbb, #1958); openraft's purge reported done while the straddling segment kept the bytes (here)

Your files_holding grep plus a verify step like first_retained_index is the shape that would catch the next one if every delete/drop/compact path ran it against its storage root, but not for this PR; the point fix here is right. Good to merge once (1) is in.

Full review below:


✅ Approving to unblock: please get the lagging-node fix (the blocking comment on compaction.rs:82) in before merging.

The paired tests are really nice here: snapshot_and_purge_alone_leave_a_deleted_value_on_disk shows the problem with openraft's own snapshot and purge, and compact_log_removes_a_deleted_value_from_disk greps the whole group root, so the claim is checked against the disk rather than the metrics. Seal-then-purge keeps every existing crash ordering, the final first_retained_index check means compaction can't report what the storage can't vouch for, and the new snapshot lock closes a real race. The one must is the target index: on a node behind the delete, the call reports success with the value still in its snapshot. The rest is optional: a crash between the purge marker and the unlink that a retry can't clear on a quiet node, four guarantees the suite doesn't pin, failing fast on the defaults, a short "what this doesn't cover" list in the design doc, and purge_through's trait doc.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends RaftLogStore / RaftSnapshotStore with provided methods and keeps purge_through's whole-segment crash ordering; no parallel mechanism. The refusing defaults are the safe form of a capability added behind a default.
  • Performance (speed first, memory second): ✔ no query-engine path; append gains one bool check in the rollover test and no allocation, a snapshot write takes one uncontended lock, recovery scans at most one extra segment per call. No performance-degradation risk.
  • Deployment targets: ✔ raft groups run in long-lived processes with a local filesystem (the server's cluster mode, or an embedder hosting its own groups), which is the shape CI and the box ran; compaction is behind the raft feature, and the trait changes still build for wasm32 (green on this head).
  • Testing: ⚠️ the new tests run in CI (all 13 by name in the test job on this head) and the seal is pinned: Claude disabled it and compact_log_removes_a_deleted_value_from_disk fails with Retained { through: 4, first: 0 }, and with the seal disabled and first_retained_index returning None it fails at the files_holding assertion. Not pinned: snapshots end to end, the refusing defaults, the snapshot lock, and any follower's disk.
  • Conventions: ✔ self-describing subjects with full bodies, design doc updated, clippy and fmt green on this head.

Verified at this head (Claude ran these on a clean box, plus CI): cargo nextest run -p fluree-raft-core --all-features → 211 passed; with five probes added → 216 passed; six mutations as described in the comments; CI test on b23f77336 → 16190 passed.

Approving so you can merge once the lagging-node fix is in, but maybe worth folding a few of the optional ones in at the same time.

Comment thread fluree-raft-core/src/compaction.rs Outdated
/// lagging follower; a follower that falls behind the purge catches
/// up from the snapshot instead. Nothing persists between calls: if
/// the process stops before this returns, call it again.
pub async fn compact_log(&self, timeout: Duration) -> Result<Option<u64>, CompactionError> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: on a node that hasn't applied the delete yet, compact_log compacts short of it and returns Ok, with the deleted value still in that node's snapshot.

seal returns this node's own tail (storage/fs.rs:883-890), and every later step checks this node's metrics against that index, so nothing ties the call to the write the caller wants gone. A follower that is one entry behind seals at the entry before the delete, snapshots a state that still holds the value, purges and discards, and first_retained_index is satisfied, so the call reports success. The doc comment above and raft-core.md:130 say a cluster runs it on every node, which reads as if that's enough.

Claude reproduced this on a box against this head, with a probe added to tests/kv_group.rs: three nodes; put the value and wait until node 3 applies it; make node 3 answer every inbound RPC with a 503 and turn its elections off; delete on the leader (committed by nodes 1 and 2 at index 7). compact_log on node 3 then returns Ok(Some(6)), and node 3's snapshots/snap-6-1.data holds the value. After healing and waiting for node 3 to apply the delete, a second call returns Ok(Some(7)) and no file under node 3's root holds it, so the steps are right and it's only the target that's missing.

I think the fix is to let the caller name the index that has to be covered (the delete's client_write(..).log_id.index) and wait for this node to apply it before the seal, something like:

pub async fn compact_log(
    &self,
    covering: Option<u64>,
    timeout: Duration,
) -> Result<Option<u64>, CompactionError> {
    let deadline = Instant::now() + timeout;
    if let Some(index) = covering {
        self.wait_until(deadline, "this node to apply the index to compact past", move |m| {
            m.last_applied.as_ref().is_some_and(|id| id.index >= index)
        })
        .await?;
    }
    let Some(through) = self.storage.seal_log().await? else {

with the docs saying "on every node, with the delete's index". The API is new, so this is the cheap moment to shape it. If you'd rather keep the signature, the minimum is the docs saying that a node's returned index has to be at or past the delete's, or that node still holds the value.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 314a097

Comment thread fluree-raft-core/src/compaction.rs Outdated
#[error("timed out waiting for {0}")]
Timeout(&'static str),
/// The steps completed, yet entries at or below `through` are still
/// held. Running compaction again normally clears it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is minor, but I think "Running compaction again normally clears it" has one case where it doesn't. purge_through writes last_purged and then unlinks (storage/fs.rs:845-874), so a crash between the two leaves segments wholly below the marker. The scan keeps them, and only a purge to a higher index removes them. compact_log purges through the sealed tail, so on a node that nothing is appended to after the restart (a quiet follower), the retry seals at that same index, openraft's purge_log is a no-op because the index is already purged, Inner::purge_through returns at its first line (storage/fs.rs:842), and first_retained_index keeps reporting the stranded segment.

Claude pinned it at the storage level with a probe in fs.rs's tests: append, seal, write the marker without the unlink, reopen, then seal → Some(2), purge_through(2) → Ok, first_retained_index → Some(1), with the value still in log/0000000000000001.seg. One later append is what clears it. It fails loud (Retained), so it isn't a silent gap, but finishing the interrupted purge on open (unlink the segments whose last index is at or below the marker, oldest first, each durable before the next, the same as purge_through) would make "run it again" always true.

I recognize this is minor and non-blocking, but if you agree it's right I'd rather see it folded in now than lost in the backlog. Commenting here because storage/fs.rs:842 and the scan on open aren't in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 70ca61c

.await?;
self.storage.discard_superseded_snapshots().await?;

match self.storage.first_retained_index().await? {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a big deal, but a log store on the defaults only refuses here, at the last step. In Claude's probe (a store that delegates the required methods to FsRaftLogStore and takes the defaults), compact_log returned Err(Storage(Other("this log store cannot report which entries it retains"))) with the purged metric already at 3, so the snapshot and the purge had both run first, and on a leader that purge can push a lagging follower onto a snapshot install. A read-only self.storage.first_retained_index().await?; before the seal would refuse before doing any of it. Minor, but cheap to fold in now.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 314a097

async fn compact_log_removes_a_deleted_value_from_disk() {
let dir = tempfile::tempdir().expect("tempdir");
let group = single_node_group(dir.path()).await;
write(&group, put_config("credential", SECRET)).await;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is more of a suggestion than a must. Claude ran mutations against this head on a box, and four of the guarantees here still pass the PR's suite when they're broken:

  • Snapshots, end to end. With remove_superseded returning early (no snapshot file ever removed), every kv_group test in this PR passes, because this test never has the value in a snapshot before the delete; only the fs unit tests catch it. Taking a snapshot between the put and the delete (trigger().snapshot(), then wait on m.snapshot) puts it in snapshots/snap-2-1.data, and then this grep covers snapshots as well as log/. Claude's version of that passes at head and fails under the mutation.
  • The refusing defaults. With first_retained_index and discard_superseded defaulting to Ok, the suite passes. The defaults-backed store from the comment on compaction.rs:111 returns the Storage error at head and fails under the mutation.
  • The snapshot write lock. With discard_superseded not taking it, the suite passes. A loop of 400 writes racing a task that calls discard_superseded fails the first time a discard removes the staged .tmp (rename tmp: No such file or directory (os error 2)), and passes with the lock.
  • A follower's disk. every_node_compacts_and_the_group_keeps_replicating checks through.is_some() and that replication continues, but not any node's files (Node keeps its directory private). With the index from the blocking comment, asserting that no node's root holds the value would pin it.

Happy to paste Claude's versions of these if they're useful. Minor and non-blocking, but if you agree I'd rather see them folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 314a097 and 70ca61c

Comment thread docs/design/raft-core.md Outdated
5. fail with `CompactionError::Retained` unless the oldest entry still on disk
is above N.

Each node holds its own log, so a cluster runs it on every node. A seal lives in

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a big deal, but since this is the section an embedder reads before copying the directory, I'd like it to say plainly what compact_log doesn't cover, the way #2280's erasure page now opens with what erasure doesn't guarantee:

  • a node that hasn't applied the delete (the comment on compaction.rs:82);
  • a value that expired rather than was deleted: kv keeps an expired record in its fragment, and so in every snapshot, until the sweep's Evict or the next write to that key reclaims it (kv.rs:660-675), so evict before compacting;
  • the seal lives in memory and nothing re-runs compaction after a restart, so the call belongs right before the copy rather than right after the delete;
  • unlink isn't sanitization: a file-level copy made afterwards is clean, but a block-level image of the volume can still hold the freed blocks (encryption at rest is the answer there).

Minor and non-blocking, but if you agree I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 8abea78

/// the last entry held, `None` when the store holds none.
///
/// The default suits a backend whose purge removes entries exactly.
async fn seal(&self) -> Result<Option<u64>, StorageError> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So minor, but purge_through's doc (storage.rs:168-171) still says "Remove all entries with index <= log_id.index", which the fs backend never did on disk. Now that seal's doc explains the gap, one more line there ("a backend may keep their bytes until [Self::seal] closes what holds them; [Self::first_retained_index] reports what's still held") would make the trait honest for the next backend author. Commenting here because storage.rs:168-171 isn't in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 70ca61c

let safe_id = validate_path_safe_id(&meta.id)?;
let meta_bytes =
postcard::to_allocvec(meta).map_err(|e| ser_err("encode snapshot meta", e))?;
let _guard = self.write_lock.lock().await;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is nice. Holding the lock across the whole write also serializes openraft's snapshot build, which openraft runs in its own spawned task (core/sm/worker.rs:186 in our openraft rev), with an install_snapshot write from the state-machine worker. Before this, one write's reclamation could remove the other's staged .tmp by the same mechanism Claude's race probe shows for an unlocked discard (not separately reproduced for two writes).

purge_through writes its marker before unlinking, so a crash between
the two leaves whole segments below the marker. A purge to the same
index returns before unlinking anything, so on a node nothing is
appended to, they stayed until a later, higher purge. The open now
unlinks them, oldest first, each unlink durable before the next.

Pins the snapshot store's write lock with writes racing a discard,
and notes on purge_through that a backend may keep purged bytes until
seal closes what holds them.
compact_log sealed this node's own tail, so a node that had not yet
applied a delete compacted short of it, kept the value in its
snapshot, and still returned Ok. It now takes covering, the index of
the write whose effect has to leave the disk, and waits until the
node has applied it before sealing.

Storage that cannot report what it retains, or cannot discard
superseded snapshots, now refuses before any snapshot or purge runs:
on a leader, a purge can push a lagging follower onto a snapshot
install.

The end-to-end test now puts the value in a snapshot before deleting
it, the three-node test checks every node's files, and stores on the
trait defaults are pinned to refuse.
propose_via_leader now returns Proposed { log_id, response }. On the
leader the log id is client_write's. A follower gets it from the
leader's /propose reply, in an x-fluree-raft-log-id header rather than
the body, so peers on either side of an upgrade still read each other's
responses. log_id is None only when the leader is too old to send the
header; a malformed one is an unknown outcome, like a malformed body.

Before this only the leader could name a write's index, so a follower
that relayed a delete had nothing to pass compact_log as covering and
nothing to wait on before reading its own delete back.
RaftGroup::wait_applied(index, timeout) is that wait.
@bplatz
bplatz merged commit dc34953 into main Nov 15, 2026
19 checks passed
@bplatz
bplatz deleted the fix/raft-compact-log branch November 15, 2026 02:30
bplatz added a commit that referenced this pull request Nov 15, 2026
Brings #2389 and #2391.

- #2389 (JSON numbers read as the nearest double) is the float_roundtrip
  change next already took in #2364; it adds main's Cargo.toml comment,
  the coerce test, and the compatibility entries. Next's own paragraph
  under "A JSON-LD number is typed by its value" now points to the
  fuller entry instead of repeating it with the older "16 or 17 digits".
- #2391 (raft compact_log, and the propose relay's log id) merges as is:
  next's only raft-core change since the last merge, a loaded snapshot
  applying its membership, does not touch compaction or the relay, and
  nothing outside raft-core implements its storage traits or calls
  propose_via_leader.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants