Repository navigation
feat(raft): compact_log removes compacted entries from disk - #2391
Conversation
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.
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.
aaj3f
left a comment
There was a problem hiding this comment.
@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/dictsblobs 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/RaftSnapshotStorewith provided methods and keepspurge_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;
appendgains oneboolcheck in the rollover test and no allocation, a snapshotwritetakes 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;
compactionis behind theraftfeature, and the trait changes still build forwasm32(green on this head). - Testing:
⚠️ the new tests run in CI (all 13 by name in thetestjob on this head) and the seal is pinned: Claude disabled it andcompact_log_removes_a_deleted_value_from_diskfails withRetained { through: 4, first: 0 }, and with the seal disabled andfirst_retained_indexreturningNoneit fails at thefiles_holdingassertion. 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,
clippyandfmtgreen 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.
| /// 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> { |
There was a problem hiding this comment.
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.
| #[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. |
There was a problem hiding this comment.
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.
| .await?; | ||
| self.storage.discard_superseded_snapshots().await?; | ||
|
|
||
| match self.storage.first_retained_index().await? { |
There was a problem hiding this comment.
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.
| 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; |
There was a problem hiding this comment.
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_supersededreturning early (no snapshot file ever removed), everykv_grouptest 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 onm.snapshot) puts it insnapshots/snap-2-1.data, and then this grep covers snapshots as well aslog/. Claude's version of that passes at head and fails under the mutation. - The refusing defaults. With
first_retained_indexanddiscard_supersededdefaulting toOk, the suite passes. The defaults-backed store from the comment oncompaction.rs:111returns theStorageerror at head and fails under the mutation. - The snapshot write lock. With
discard_supersedednot taking it, the suite passes. A loop of 400writes racing a task that callsdiscard_supersededfails 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_replicatingchecksthrough.is_some()and that replication continues, but not any node's files (Nodekeeps 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.
| 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 |
There was a problem hiding this comment.
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
Evictor 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.
| /// 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> { |
There was a problem hiding this comment.
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.
| 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; |
There was a problem hiding this comment.
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.
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.
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_throughunlinks 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.coveringis 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:covering, so a node that hasn't yet applied the delete doesn't compact short of it;purgedmetric is set only after the storage purge returns);CompactionError::Retainedunless storage reports that the oldest entry it holds is above N.It returns
Some(N), orNoneif 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 samecovering. 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_leadernow returnsProposed { log_id, response }. Before, only the leader could name a write's index (throughclient_write), so a follower that relayed a delete had nothing to pass ascovering, and nothing to wait on before reading its own delete back. On the leader the log id isclient_write's. A follower gets it from the leader's/proposereply, in anx-fluree-raft-log-idheader rather than the body, so nodes on either side of an upgrade still read each other's replies.log_idisNoneonly when the leader is too old to send the header; a malformed header isProposeError::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), andappendstarts 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 thatwritealready did. The default refuses.The fs snapshot store now holds a lock across
writeanddiscard_superseded, so a discard can't delete the files of a snapshot that is written but not yet namedcurrent. Reclamation after a write is still best-effort and logs a warning.The fs log now finishes an interrupted purge when it opens.
purge_throughwrites 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
discard_supersededremoves orphans, removes every snapshot file when none is current, and fails on a file it can't remove, whilewritestill succeeds;kv_group:snapshot_and_purge_alone_leave_a_deleted_value_on_diskshows 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_diskwrites the value, refreshes it, snapshots it, deletes it, and runscompact_logwhile 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_logfails withRetained; with snapshot reclamation disabled, the search finds the old snapshot.compaction_waits_to_apply_the_write_it_coversstarts 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_stepruns 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_replicatingdeletes a value on a three-node group through a follower, which reads its own delete back afterwait_applied. It runscompact_logon 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 afterwait_appliedthe 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.mdhas a new section covering the problem, the steps, whatcompact_logdoesn'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.