Skip to content

Write-ahead log for file storage and a segmented Raft log - #1820

Merged
bplatz merged 24 commits into
mainfrom
feat/storage-wal
Sep 12, 2026
Merged

bplatz merged 24 commits into
mainfrom
feat/storage-wal

Conversation

@bplatz

@bplatz bplatz commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Summary

File storage acknowledges a commit after one flush instead of six, and the Raft log appends with one flush per batch instead of one per entry. Durability is unchanged: an acknowledged commit still survives power loss.

Under the previous default every source-of-truth file was written with its own fsync plus a directory fsync. A commit with a recorded transaction paid six. This PR puts a write-ahead log beneath FileStorage and makes it the default durability mode:

  • Every source-of-truth write is appended to <root>/.fluree-wal/ and the file itself is written page-cache. Content writes append without flushing; the head publication that ends a commit appends with a flush, and that one flush covers everything before it.
  • A background thread flushes the files a closed segment covered and retires the segment, so the log only ever holds the recent tail. Opening a root replays whatever is left before anything reads it. A clean shutdown leaves no segments.
  • The files on disk remain the database. After a clean shutdown, or after any start of a WAL-aware binary, the root reads exactly as it did before.
  • A Raft cluster's shared payload root is journaled by each node under a log of its own, flushed on every write, since the head lives in Raft rather than in a file. Any node applies a stopped node's tail when it opens the root or misses a file.
  • The Raft log itself moves from one file per entry to append-only segments with one flush per append batch, and the committed watermark is rewritten in place with one flush.
  • Index artifacts are flushed once, as a batch, before the pointer that names them is published, rather than never. That cost lands on the indexer, not the transaction path.

Timing

Single client, recorded 4.2.0 against this branch:

Write operation Recorded 4.2.0 WAL candidate Latency reduction
INSERT 69.05 ms 55.00 ms 20.4%
DELETE 60.01 ms 45.46 ms 24.3%
Weighted mix 63.63 ms 49.27 ms 22.6%

Small transactions benefit more and large ones less, since the saving is a fixed number of flushes per commit. A follow-up PR with further write-path work depends on this one.

Raft log, 3-node in-process cluster, release build, 100 sequential inserts through the leader: median per insert went from roughly 150 to 175 ms with one file per entry to 70 to 80 ms with segments.

Operator notes

  • durability on a file storage node, or FLUREE_STORAGE_FSYNC, now accepts wal (the default), sync (the previous per-file behavior) and page-cache.
  • The log is Unix-only. Where the root is already owned by another process, or the filesystem refuses advisory locks, the handle falls back to sync with a warning.
  • Downgrading: start a WAL-aware binary once after a crash before pointing an older binary at the root, so the tail is applied. Nothing else is needed.
  • The Raft log layout change is folded on first open, per node, and rolls with a normal upgrade. An older binary cannot read segments; downgrading a node means restoring its Raft storage path or rejoining as a fresh node.

Full detail in docs/operations/storage.md and docs/operations/raft-clusters.md.

Recovery model

The branch went through six rounds of adversarial review with crash-state reproductions, each modelling a persistence boundary (a rename that reached the device ahead of its inode's contents, an unlink lost before its directory flush, a write that failed after its record was logged). The invariants that came out of it, each pinned by a test shown to fail without its fix:

  • A record is durable no later than the next head publication or the next flusher tick, and retirement never removes a segment ahead of an earlier one.
  • A head write that fails after its record is logged cancels that record by sequence number, so replay never installs a failed transition or undoes a good one another writer landed afterwards.
  • A key's records sit in the log in the order its file operations landed, held by a per-root lock every logged operation takes, so recovery agrees with what the process saw. A write too large for a record checkpoints the log before landing directly.
  • An empty or missing head with a live record is a torn write to repair, not a later state to leave alone.
  • Raft truncation and purge make each unlink durable before the next step, so the segments on disk are a prefix or suffix of the log at every crash point.

Follow-ups

Follow-up: #1817 (index recovery on load).

Not in this PR: NFS qualification of the owned logs and the segmented Raft log, and a Linux power-loss run. Cross-process ordering of one key on a shared Raft payload root relies on the rendezvous hash giving each key a single writer.

Durability::Journal appends each source-of-truth write to a per-root
segment log and writes the file itself page-cache. Content writes append
without flushing; the head compare-and-swap appends with a flush that
covers everything before it, so a commit costs one device flush where
per-write flushing cost six. A background thread flushes the files a
closed segment covered and retires the segment, so the log only ever
holds the recent tail.

The files on disk stay the database. The connection and builder startup
paths replay whatever a crash left before anything reads the root, and
Fluree::disconnect and server teardown checkpoint the log, so a clean
stop leaves no segments and the root reads the same to a binary that
knows nothing about the log. After a crash, start a journaling binary
once before downgrading.

- `sync` keeps per-write flushing by name; Raft mode pins it for the
  shared payload root via FlureeBuilder::with_storage_durability.
- A second process on a root, or a filesystem without advisory locks,
  falls back to per-write flushing with a warning rather than failing.
- FileNameService::with_storage shares the builder's storage handle so
  the nameservice inherits its durability and log ownership.
- Writes above 256 MiB bypass the log; a torn final frame is discarded,
  damage before a later segment fails the open naming the segment.
- Tests pin one flush per commit against a six-flush control at both
  the storage and API level, replay after a simulated crash that loses
  every unflushed file, write/delete ordering, a head that moved on,
  clean close, second-owner fallback and derived content staying off
  the log.
Prints per-commit median, p95 and mean for both durable modes, with and
without raw transaction recording, so the saving can be read off the
machine at hand rather than inferred from flush counts.
A Raft cluster's nodes share one payload root, so no single process can
own its redo log. Each node now journals the root under a log of its
own at .fluree-redo/owners/node-<id>/, keyed by the Raft node id from
the integration rather than the CLI flag, so the in-process cluster
tests take the same path production does.

An owned log flushes on every append: the head lives in Raft rather
than in a file under the root, so nothing later would flush on a
payload's behalf, and a payload must be durable before its reference
is proposed. That is one flush per payload instead of a file flush and
a directory flush.

A node that stops with records still in its log leaves payloads only
it had written. Any node applies stopped owners' logs when it opens
the root, and again when a read misses a file, on the plain, ranged
and local-path read routes, so a commit survives the loss of the node
that wrote it as long as the shared store does. Live owners' logs are
never touched: the lock says who is still running.

Tests: every node that takes a write owns a log and none journals the
root as if alone; the branch's commit worker is found by the log that
holds the commit keys, abandoned as a crash would leave it, stopped,
and every commit file removed, after which a survivor that never
loaded the ledger serves it and the files are back. Core tests cover
separate owner directories, one flush per owned write, recovery on a
miss and on open, and owner-name validation.
The file-per-entry log paid a file flush per entry plus a directory
flush per batch, and the committed watermark two more, on every node
for every proposal. Entries now append to segments under log/ with one
flush per batch, and the committed watermark is rewritten in place in
a two-slot file with one flush; the newer valid slot wins on read, so
a torn write falls back one step rather than to nothing. Vote, purge
marker and snapshots keep their atomic-write discipline.

Truncation shortens the segment holding the cut and removes later
segments; purge records its marker first and removes segments that
lie entirely at or below it, leaving entries below the cutoff inside
a kept segment invisible as before. Recovery replays segments in
order: a frame that does not decode at the end of the last segment is
a torn append that was never acknowledged and is cut off, while
damage before a later segment cannot be explained that way and fails
the open naming the segment. Per-entry files from earlier releases,
and the old committed marker, are folded in once on open, keeping the
contiguous run above the purge cutoff exactly as the old log_state
reported it. The format is per node and the wire protocol is
unchanged, so nodes upgrade one at a time.

Tests cover rotation across segments with reopen, truncation inside a
segment followed by appends, legacy migration with a gap and a purge
cutoff, orphans below the marker, a torn tail, a torn first frame,
damage before a later segment, and committed falling back to the
older slot.
Redo log:
- A segment is not retired while an append's file is still being
  written. The flush would miss the file and the record would be gone
  when the file landed unflushed. Appends now return a guard the write
  paths hold until the file exists, and retirement skips segments with
  a guard outstanding; checkpoint waits for them briefly.
- Only the insert whose link won logs a record, so replay installs the
  value that was acknowledged rather than the first to reach the log.
- A failed flush poisons the log: the durable boundary is unknown, so
  no further append is accepted until a reopen replays what landed. A
  failed write is cut back to the last frame boundary instead.
- The next segment is created under a temporary name and renamed into
  place once its header is flushed, and a published final segment with
  no valid header is removed rather than failing the open.
- Replaying a compare-and-swap or insert takes the same sidecar lock a
  live writer holds, so a per-write writer publishing the same head at
  that moment cannot be overwritten by an older transition.

Raft log:
- Truncation that empties a segment removes it; purge removes an empty
  segment whose first index it has passed; an append never reuses an
  empty segment whose header names a different first index. Any of
  those left a header that made later entries read as torn on reopen.
- Segment creation publishes by rename as above, and a final segment
  with no valid header is removed on open.

Each gap has a regression test modelled on the interleaving that
exposed it, including a replay that must block on a held CAS lock and
an entry appended after a full truncation and purge.
- Retirement now removes only a contiguous prefix of closed segments.
  A segment kept for an unfinished write keeps every later segment
  too; retiring one in the middle left a sequence hole that replay
  refused, taking the surviving tail with it.
- An insert holds the key's sidecar lock from the link to its record,
  the same lock a compare-and-swap on the key takes. Without it a
  writer could advance the head and log its transition before the
  creation it built on was logged, and replay then restored the
  initial value over the acknowledged one.
- Every append seeks to the frame boundary the log knows about before
  writing, and a failed write is cut back to it. Truncation alone left
  the cursor past the new end, so the next append opened a hole that
  ended replay before the acknowledged record.
- Availability is rechecked under the log mutex, so an append that
  waited behind one whose flush failed cannot reuse the failed
  record's sequence number.

Regressions: retirement with a held middle segment reopens and keeps
the tail; a short write followed by an append is replayable; an insert
blocks while the key's lock is held and lands once it is released.
Retirement from the background thread and from a checkpoint each drained
the closed queue and retired outside the mutex, so the contiguous-prefix
rule held only within a batch: a checkpoint could remove segment two
while the background thread still held segment one back, and reopening
found the gap. A flush or unlink error also returned early, dropping
the failed segment and everything after it from the queue, so later
ticks retired their successors past it.

One retirement now runs at a time, from draining the queue to the last
unlink, and stops at the first segment it cannot retire yet, whether
held for an unfinished write or failed, putting it and every later
segment back in order.

Regressions: four threads retiring concurrently around a held first
segment remove nothing, then everything closed once it is released; a
retirement that fails on a device node keeps its segment and proceeds
in order once the file is restored.
The module, type, directory, durability mode and every method now say
`wal`: `Durability::Wal` is the default mode name, the log lives under
`.fluree-wal/`, and the API is `recover_wal`, `checkpoint_wal`,
`with_wal_owner` and `with_storage_wal_owner`. The `journal` spelling
of the mode is still accepted.

A single write above 8 MiB now bypasses the log and flushes directly,
down from 256 MiB. Past a few megabytes a flush costs bandwidth rather
than latency, so the log would only write the bytes twice and make
replay carry them; the mode exists for the small transactions whose
cost is the flush itself.
Index output is written at page-cache durability, on purpose: it is
rebuildable and written at far higher volume than commits. The pointer
that names it is a nameservice write and therefore durable, so a power
loss between the two could leave a durable pointer to files that never
reached the device, and the ledger unloadable until someone reset it.

StorageWrite and ContentStore gain `sync`, a no-op for backends whose
writes are durable on return. FileStorage remembers the derived content
it wrote since the last call and flushes those files and their
directories in one batch. Every site that publishes an index pointer
flushes first: the indexer's publish helper, both orchestrator paths,
the branch-copy used by branch creation, rebase and merge, and bulk
import. The cost lands on the indexer at the end of a build, not on
the transaction path.

The branch copy now writes through the content-addressed path, so the
copied artifacts take derived durability like every other index write
instead of the instance's, which under the redo log would have put
index bytes through the log.

Tests: derived writes issue no flush until `sync`, then one per file
plus directories, then none; page-cache instances flush nothing. An
indexer test with a publisher that records the flush count at publish
time fails if the flush is removed.
Two gaps in the derived-content flush from review. One sync at a time
per root: a second caller whose writes an earlier, still-running flush
had taken could return before those files reached the device, and a
publish behind it would name unflushed artifacts. And a batch whose
flush failed was dropped, so a retry reported success for files the
device never saw; it now goes back to the front of the pending list.

Regressions: a second sync blocks while the first is held at a FIFO
in an artifact's place, and a retry after a flush of a device node
fails still flushes the file.
The barrier guard belonged to the async future while the flush ran on
the blocking pool, so cancelling the caller released it mid-flush and
a later `sync` saw nothing pending and returned before those files had
reached the device. The owned guard now travels into the blocking task
and is released only when the flush finishes, success or failure.

Regression: a sync held at a FIFO in an artifact's place is cancelled;
a second sync still cannot return until the detached flush completes
and hands its batch back.
A write above the record cap is flushed directly instead of logged.
When that write is a head publication, the content it names may still
sit in unflushed log records, so the head could survive a crash that
loses its payload. The bypass now flushes the log's active segment
first, keeping the rule that a durable head is never ahead of what it
references. Regression test simulates exactly that crash.
A head write that failed after its record was logged left that record
replayable: a retry from the same starting value then succeeded, and a
crash recovered the failed value over the acknowledged one. The write
path now logs an undo record for the transition that never landed, and
poisons the log if even that cannot be appended.

A write too large for a record landed directly after only a flush, so
earlier records for the same key (an older overwrite, or a delete
before an identical blob was re-created) replayed over it. The log is
now checkpointed before an oversized write, and the write is refused if
records are still materializing after the wait.

Replay treated an empty head file as proof another writer had moved the
head on and skipped the transition. Nothing that replaces a head leaves
it without contents, so a rename that reached the device ahead of the
inode's data is now repaired from the record instead.

`sync` drained only derived content, though the trait promises every
completed write. It now flushes the log's tail too, for callers that
publish a pointer somewhere other than this root's own head file.

Raft truncation unlinked later segments, shortened the retained one,
and only then flushed the directory, so a crash in between could keep
the short segment while an unlink came back, leaving a hole the scan
refuses on restart. Purge had the same shape across several segments.
Both now make each unlink durable before the next step, so the segments
on the device are a prefix or suffix of the log at every crash point.

Each fix carries a test shown to fail against the previous ordering.
…ords with its files

The undo record for a head creation that failed after it was logged was
a plain delete, which replay applies to whatever is there. A writer in
per-write mode that created the head in the meantime lost it on the
next recovery. The undo is now a conditional delete that names the
value the failed write would have left, and replay removes only that.

Nothing ordered a key's records in the log against its file operations,
so two concurrent logged operations on one key could recover in the
opposite order from the one they landed in. An oversized write made
that visible: a delete appended between its checkpoint and its rename
replayed over the flushed blob. Logged writes and deletes now hold a
per-key lock from record to file operation, and an oversized write
holds it from checkpoint to rename, so the log order of a key is the
order its files landed and recovery agrees with what the process saw.

A handle whose first operation was a compare-and-swap attached the log
after taking the key's sidecar lock; replaying a record on that key
takes the same lock, so the handle waited on itself. The swap now
attaches, and so replays, before it locks the key.

Each fix carries a test shown to fail without it.
…te by record

The per-key locks that order a key's records against its file
operations lived on the storage handle, while every handle on a root
shares the root's log through the process registry. Two handles on one
root had one log and two sets of locks, so an operation through the
second handle could still land between an oversized write's checkpoint
and its rename. The locks now live on the log itself.

Inserts and compare-and-swaps were ordered by their sidecar file lock
alone, but the storage-backed nameservice deletes and rewrites head
keys with plain deletes and writes as well, so the two lock domains met
on the same keys. Every logged operation now holds the same per-key
lock; a compare-and-swap holds it from its read, across its closure, to
its write, so the locks are async-aware with owned guards.

A failed head write's undo named the value that failed, and a writer in
per-write mode that later landed the same bytes durably was
indistinguishable from the failed attempt: recovery deleted or rolled
back a good head. The undo is now a record that cancels the failed
record by sequence number, and replay collects the cancelled sequences
in a first pass over the log before applying anything, so a cancelled
record is never applied and nothing else is touched on its account.

Each fix carries a test shown to fail without it.
@bplatz bplatz added enhancement New feature or request area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches labels Sep 11, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 11, 2026 13:26

@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 you and I talked about this, and I think it's great & I'm excited for it. I'll post the rigorous Claude review below but just some questions (more than really judgments):

  • Is there a reason the WAL uses SHA256 for the frame checksum while Raft (in the same PR) uses xxh64? The goal is to detect torn writes, so it seems possibly SHA256 is overkill and also a small but constant added time delay.
  • I wonder if lock acquisition should get a retry in cases, for example, where a fluree server and a fluree CLI could contest one another. Since attach_wal stores in a OnceLock, a server could possibly start while a very short-lived CLI op holds the root's lock, so the server runs in sync until restart.

Claude review below:


This is really nice, @bplatz — the recovery model in the body maps line-for-line onto real code and real tests, the retirement and segment-publication discipline is exactly the shape I'd want, and the flush-before-publish barrier quietly fixes a pre-existing power-loss bug in index publication that I think deserves its own line in the release notes. I read the whole log and the write paths against every interleaving I could construct, ran the WAL, Raft-store and API suites locally, and mutated two invariants (drop the head-publication flush; unlink a segment before flushing its files) — both went red where they should.

The one thing I need before this merges is narrow: replay_unowned (wal.rs:461) turns any lock error other than WouldBlock into a hard error, and because the owner directory and LOCK are created before the lock is tested, a Raft shared root on a mount that refuses advisory locks (NFS nolock, SMB, some FUSE) is bricked on every restart after the first write — Claude reproduced it with a FIFO standing in for such a mount. The body and docs promise a sync fallback for exactly that case, and acquire honours it; this arm just needs the same posture (skip the owner with a warning). Everything else below is optional and small enough that I'd rather see it folded in than tracked — the SHA-256-under-the-mutex swap to xxh64 and the touched dedup are the two I'd pick first.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ sync() extends StorageWrite/ContentStore with a no-op default and every wrapper forwards it; the nameservice shares the storage handle instead of reopening the root; the Raft shared root reuses the same Wal with owner directories rather than a second log.
  • Performance (speed first, memory second): ✔ commit path goes from six device flushes to one; the costs added (two payload copies, a SHA-256 pass under the log mutex, a checkpoint stall on >8 MiB writes, background fsync work unchanged in count) are bounded and the two that matter for MiB-scale commits have one-line fixes noted inline. Measured here: median insert 18.9 → 6.0 ms (debug, macOS). No CRITICAL regression.
  • Testing: ✔ 39 WAL unit tests, 31 Raft-store tests, it_wal (a real [[test]] target), the indexer barrier test and two grp_raft tests all run in CI's test job at head and pass locally; each crash state in the body has a named test; two mutations confirmed the tests have teeth. The test job's red is it_iceberg_policy row ordering, which main itself fails at the merge-base commit — not this branch.
  • Conventions: ✔ fmt clean; clippy clean on fluree-raft-core with raft,testing,kv; the one clippy hit on fluree-db-core under --features native alone (commit.rs:943 unused import) is identical at the merge-base and invisible to CI's --all-features gate — pre-existing, not yours. No unwrap on I/O in the durability path, no new unsafe outside tests, commit bodies are thorough, PR title is self-describing, docs updated (two clarifying sentences suggested).

Verified locally at branch HEAD 59e042696: cargo test -p fluree-db-core --features native --lib -- storage:: (105 passed), cargo test -p fluree-raft-core --features raft --lib -- storage::fs (31 passed), cargo test -p fluree-db-api --features native --test it_wal (2 passed) plus the ignored timing harness; clippy/fmt as above; two mutations red then restored.

Just be sure to get the replay_unowned lock-error fallback in before this merges (it's a three-line change and a one-line test with a FIFO at an owner LOCK); happy to talk through any of the optional ones.

Comment thread fluree-db-core/src/storage/wal.rs Outdated
match lock.try_lock_exclusive() {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
Err(e) => return Err(e),

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.

fluree-db-core/src/storage/wal.rs:461 — blocking. A shared Raft root on a filesystem that refuses advisory locks cannot start (or serve a missing-file read) once any node has written to it, which contradicts the fallback the body and docs/operations/storage.md:396-398 promise. replay_unowned opens each owner's LOCK and does try_lock_exclusive; only WouldBlock is treated as "owner alive, skip" — every other error (ENOLCK on an NFS mount with nolock, EOPNOTSUPP on SMB/some FUSE mounts, EISDIR if someone put a directory there) is returned as-is, and recover_wal turns it into WAL recovery failed …, which every builder path propagates with ?. The state is reachable on the first write: acquire (wal.rs:819-847) creates owners/node-<id>/ and its LOCK file before it tests the lock, so a node whose flock fails still leaves the directory behind and falls back to sync correctly — and from then on every restart of every node fails in recover_wal, and every read miss on a live node (file.rs:1041, :1105, :1249) errors instead of returning not-found. Claude caught this and reproduced it here with a FIFO at .fluree-wal/owners/node-1/LOCK (flock on a FIFO returns EOPNOTSUPP, the same non-WouldBlock class): Wal::acquire on a FIFO root LOCK returns Unsupported and falls back as documented, while replay_unowned returns Err(Operation not supported) and FileStorage::recover_wal() fails. Consequence: a data-raft cluster on such a mount is bricked until an operator deletes .fluree-wal/owners/ by hand, with no hint in the error. Fix is to mirror acquire's posture — an owner whose lock cannot be taken for any reason is skipped with a warning (on a no-flock mount every owner is in per-write fallback anyway, so its log is empty and skipping loses nothing); and, separately, it would be cleaner for acquire to probe the lock on a file it creates before publishing the owner directory, so a no-flock mount never grows an owners/ tree at all. Something like:

Suggested change
Err(e) => return Err(e),
match lock.try_lock_exclusive() {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
Err(e) => {
tracing::warn!(owner = %dir.display(), error = %e, "cannot lock an owner's WAL; skipping it");
continue;
}
}

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 b893818.

Lock-open and acquisition failures now skip empty owner directories with a warning, covering startup and read misses. Retained segments still fail recovery because they may hold acknowledged payloads; silently skipping those would risk data loss. Regression coverage includes the macOS FIFO reproduction. We kept directory creation as-is; the optional pre-publication lock probe was not added.

Comment thread fluree-db-core/src/storage/wal.rs Outdated
frame.extend_from_slice(&(payload.len() as u32).to_le_bytes());
frame.extend_from_slice(&seq.to_le_bytes());
frame.extend_from_slice(payload);
let hash = Sha256::digest(&frame);

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.

fluree-db-core/src/storage/wal.rs:222 (and the call at :980) — optional, performance. This is more of a question than a suggestion: is SHA-256 the right checksum for a WAL frame? It exists to detect a torn or bit-rotted frame, not to resist tampering, and the Raft log in this same PR uses xxh64 for exactly that job (fluree-raft-core/src/storage/fs.rs:163). Claude measured it here in release: SHA-256 is 1.79 ms per MiB (13.9 ms for an 8 MiB record) against 42 µs for xxh64, and encode_frame runs inside the inner mutex, so for MiB-scale commits every other append on the root waits on the hash. For the small transactions this mode is for it is noise; for a 1–8 MiB commit it is the same order as the flush it replaced on Linux. I'd swap to xxh64 (already a workspace dependency, and the frame gains a magic + length + seq check on top) and hash the payload before taking the mutex, folding the header in after. Minor and non-blocking — but if you agree it's right I'd rather see it in this PR 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 b893818.

WAL frames now use xxh64; payload hashing happens before taking the log mutex, with sequence/header hashing completed inside it. Follow-up f0d8292 removes SHA-256 compatibility because WAL is new and has no existing users. Unknown formats are rejected and preserved.

Comment thread fluree-db-core/src/storage/wal.rs Outdated
kept.push(segment);
break;
}
let retired = flush_keys(&self.base, &segment.touched, &self.fsyncs)

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.

fluree-db-core/src/storage/wal.rs:1167 — optional, performance. flush_keys is handed segment.touched verbatim, and touched gets one push per record (:1002), so a head key that is compare-and-swapped once per commit is fsynced once per commit per segment by the background thread rather than once per segment. In the txn+commit+head shape that is roughly a third of the background file flushes (Claude's 600-commit run counted 4.05 flushes per commit end to end). sync() already sorts and dedups its batch (file.rs:1378-1386); the same two lines before the flush_keys call here would do it. Minor and non-blocking — fold-in-now if you agree.

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 b893818.

flush_keys deduplicates touched keys before flushing, covering retirement and recovery batches.

Comment thread fluree-db-core/src/storage/file.rs Outdated
};
// Overwrites if present, which is idempotent for content-addressed
// writes: the address is derived from these bytes.
write_atomic(&path, &bytes, &policy).map_err(|e| {

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.

fluree-db-core/src/storage/file.rs:1537 (and delete at :1437) — optional. The CAS path cancels its record when the file write fails after the append (:1713), but the plain Write and Delete paths do not: a write_atomic or remove_file that fails after its record was appended leaves a record replay will apply, so after a crash the store shows a write the caller was told did not happen. For content-addressed keys that is a harmless orphan, but StorageNameService re-creates a retracted ledger with a plain write_bytes on the head key (fluree-db-nameservice/src/storage_ns.rs:813) and drops branches with plain deletes (:720-721), so the same "a write that failed after its record was logged" hazard the body lists for heads exists there too. It's a narrow window (both the append and the file write hit the same filesystem, so most failures hit the append first), and the fix is the same three lines as the CAS arm. Non-blocking — but worth folding in for symmetry.

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 b893818.

Failed plain writes and deletes cancel their exact logged sequence while retaining the append guard. A failed cancellation poisons the WAL. Regression tests cover recovery after these failures.

Comment thread fluree-db-core/src/storage/file.rs Outdated
};
// A racing clone may have attached first; either way the root
// has one answer from here on.
self.wal.get_or_init(|| attach)

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.

fluree-db-core/src/storage/file.rs:857 (with wal.rs:845 and wal.rs:1239) — optional, design. Acquisition is decided once per handle in a OnceLock: Busy or Unsupported means per-write flushing for the life of the handle, never retried. Two consequences I think are worth a sentence or a small change. First, a long-lived fluree-db-server that happens to start while a short-lived fluree CLI (or a solo query peer, see the summary) holds the root's lock runs in sync mode until its next restart, with one warning at startup. Second, Drop for Wal runs checkpoint() before it releases the lock file and the registry entry, so in-process "drop the last handle, immediately reopen the same root" races the checkpoint and can land on Busy → silent sync fallback (the registry Weak fails to upgrade during drop, so acquire falls through to try_lock). A lazy retry — re-attempt try_lock at most every few seconds when the stored answer is Busy — would cover both; or at minimum Drop could remove the registry entry after the lock is gone rather than before. Not blocking.

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 1fb1705.

Busy acquisition retries on subsequent operations at most every two seconds per handle and its clones. Each operation pins its mode through completion, including CAS, and takeover waits for in-flight local operations. Drop releases the OS lock before removing the registry entry under the registry mutex.

A live retry only acquires a clean log or joins an existing in-process log. Retained crash history could overwrite newer completed Sync fallback writes, so that case preserves the logs and stays in Sync pending deliberate recovery. Unsupported storage stays in Sync; a poisoned attached WAL still refuses writes.

Comment thread docs/operations/storage.md Outdated
| `page-cache` | bytes reach the OS page cache | process death only |
| Mode | Acknowledged when | Survives | Flushes per commit |
|---|---|---|---|
| `wal` (default) | the write is in the root's WAL and the log is flushed | process death and power loss | one |

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.

docs/operations/storage.md:360 — optional, docs. The mode table says wal is the default without saying that on Windows (and on any mount that refuses advisory locks) the effective default is sync; :398 says "Unix-only" three paragraphs later, but an operator reading the table will not get there. One clause in the table row would do it.

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 68a6888 through a simpler user-facing description.

The storage guide now says FSYNC is on by default and shows how to turn it off and back on. The WAL mode table and implementation discussion were removed, so the guide no longer implies that every platform uses WAL. Supported platforms and per-write fallback retain the same durability guarantee.

Comment thread docs/operations/storage.md Outdated

The files on disk remain the database. The log adds nothing another version of
Fluree needs to understand: after a clean shutdown, or after any start of a
WAL-aware binary, the root reads exactly as it did under `sync`. The one rule

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.

docs/operations/storage.md:391-393 — optional, docs. The downgrade rule says what to do; it might be worth one sentence on what happens if it is not done, because the failure is not "reads stale" but "a later WAL-aware start replays the stale tail over the older binary's newer writes" — a Delete record from the crashed run will remove a head the older binary re-created, and a Write/Insert will resurrect a file it deleted. The Cas arm's moved-on check protects heads that were advanced, not ones that were removed and re-created.

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.

Originally addressed in b893818.

The downgrade explanation was subsequently removed in 68a6888 when we simplified end-user documentation to FSYNC defaults and configuration. The compatibility constraint still applies: recover with the WAL-aware binary, stop cleanly, and retire retained segments before opening the root with an older binary. Otherwise a later replay can overwrite or delete newer changes made by that binary.

/// The artifacts are flushed through `store` first. Index output is
/// written at page-cache durability, so without this the pointer,
/// which is durable, could name files that never reached the device.
pub async fn publish_index_result(

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.

fluree-db-indexer/src/lib.rs:460 — praise. Worth saying plainly in the release notes: at the merge-base the index pointer was published with no flush of the artifacts it names, so this is a fix for a latent power-loss unloadable-ledger bug, not just a cost move. Every publish site got the barrier (both orchestrator paths, the background worker, import, branch copy), and the branch-copy switch to content_write_bytes_with_hash is the right way to get derived durability there.

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.

Agreed: the index-publication barrier fixes a pre-existing power-loss recovery defect, not just flush overhead.

We initially called it out in b893818, then removed the standalone release-notes page in 19bad3d to keep end-user docs focused on configuration. The fix remains: index artifacts are flushed before publishing the pointer that names them. Recording that distinction here for the PR history.

/// of an earlier one and replay never meets a hole. One retirement runs
/// at a time, from draining the queue to the last unlink. Returns how
/// many segments are still queued.
fn retire_closed(&self) -> io::Result<usize> {

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.

fluree-db-core/src/storage/wal.rs:1143 — praise. The retirement discipline (contiguous prefix, in_flight guard, one retirement at a time, failed segment and everything after it re-queued in order) is carefully built and the commit history shows each rule was earned by a reproduced interleaving.

/// Create the next segment: header written and flushed under a temporary
/// name, then renamed into place, so a crash can never leave a segment
/// whose header is missing or partial.
fn open_segment(&self, inner: &mut Inner, first_seq: u64) -> io::Result<Segment> {

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.

fluree-db-core/src/storage/wal.rs:1040 — praise. Segment publication by header-fsync + rename + directory fsync, plus the "a header-less final segment holds nothing acknowledged" rule, is what makes the one-flush claim hold across a rotation. I checked the .fluree-wal/ creation path too (:819-830) — every new directory up to the root is fsynced deepest-first.

…at upgrades

Skip unavailable owner locks only when no segments need recovery. Cancel
failed logged writes and deletes by sequence, deduplicate retirement keys,
and recover read-only clients without retaining WAL ownership.

Hash new WAL frames with xxh64 outside the append mutex while retaining
SHA-256 segment recovery. Preserve unknown segment versions. Separate Raft
committed watermark slots by 4 KiB and atomically migrate the old layout.
Document fallback, durability fixes, and upgrade constraints.

Add regression coverage for failure recovery, reader ownership, checksum
compatibility, watermark migration, and retirement device ordering.

Validation: 113 core storage tests, 122 Raft unit tests plus 3 integration
tests, and 800 API unit tests plus 3 WAL integration tests passed. Focused
Clippy, workspace formatting, and diff checks passed. Mutation checks
confirmed the new regressions fail when the corresponding fixes are removed.
WAL has not been used or released, so retain only the xxh64 FRDOSEG2
format. Remove the legacy decoder, mixed-format recovery test, and
intermediate WAL migration guidance. Keep version rejection and the
payload/header corruption checks.

Validation: 112 core storage tests and 3 API WAL integration tests passed;
the timing benchmark remains ignored. Focused core Clippy, workspace
formatting, and diff checks passed.
Retry temporary ownership contention on later operations while pinning each
operation's mode and coordinating takeover across local FileStorage handles.
Only take over clean logs so retained history cannot overwrite completed
fallback writes; keep unsupported storage and poisoned logs distinct.

Reject damaged suffixes containing validated later frames, preserving the log
for investigation with bounded look-ahead work. Document the conservative
recovery tradeoff and cover retries, CAS ordering, stale history, and tail
validation with regression tests.
@bplatz
bplatz merged commit 6707ad7 into main Sep 12, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants