Repository navigation
Improve concurrent write throughput with WAL group commit and reduced lock work - #1821
Conversation
…gments in one batch Wal::append held the log's mutex across the fsync, so every appender under a root, from any ledger, waited behind each head publication's full flush. The frame is now written under the mutex and the flush happens outside it: the first waiter leads, sampling how far the log was written before it releases the mutex, and publishes that point as durable when the flush returns. Every append that landed before it looked is covered; one that lands during the flush wakes to lead the next. A lone commit still costs exactly one flush. Rotation and the ticker's idle flush publish the same watermark, a failed flush poisons and fails every waiter, and an unwinding leader wakes them. Retiring a segment flushed each touched entry, with duplicates, so a busy ledger's head file was flushed once per commit in the segment; on macOS each of those was a full drive-cache barrier. Keys are deduped, and on Apple platforms files are handed to the drive with fsync(2) and committed by one F_FULLFSYNC at the end. The same batch serves the index publish barrier. On this Mac, 16 clients on 16 ledgers went from 92 to 566 commits/s and 16 clients on one ledger from 70 to 144; sequential latency is unchanged at 6.1 ms. Harness: it_wal::timing_concurrent_wal.
The optimistic commit path stages against a snapshot and restages if the ledger moved before it took the lock. Under steady contention it always has: the lock is FIFO and some commit is in flight at snapshot time, so a client could lose the race sixteen times in a row and fail with "transaction commit retry limit exceeded". At 16 clients on one ledger that was 10% of inserts. Only the first attempt stays optimistic; every later one takes the lock and stages under it, as the fast path does.
A size-triggered rotation, or a checkpoint, flushed the active segment while a leader was flushing the same file. The kernel reports a write-back error to one flush per open file description and clears it, so the other could return success and publish frames the device had dropped. Rotation now takes the guard, waits for a leader to finish, and refuses on a poisoned log; the leader flushes through its own open of the file rather than a dup; a waiter checks for poison before the watermark; and a leader whose flush returns after the log was poisoned publishes nothing. Also from review: directories are flushed on Unix only in the retirement batch, as before; the timing tests poll the log's state instead of sleeping a fixed time; the flush-count docs say what the counter counts and that a segment open costs two more flushes.
…ng state A #config whose shapes, schema, policy, constraints or rules source names the data ledger with f:ledger opened that ledger through the ledger cache, whose read of the ledger's write lock waited on the very task holding it: every lock-held write (SPARQL, Cypher, policy, a pre-built transaction) hung the ledger, and after the lock-first restage so did a plain insert that lost one snapshot race. The resolver now answers a self-reference from the state staging already holds, or from an uncached load, and never from the cache.
Readers take the cached handle's snapshot, as the server's query route does, so a commit that runs while a query holds the dictionaries shows up as a deep copy. Prints one row per window: mean and max latency and how many commits found the dictionaries shared.
NamespaceRegistry::from_db cloned every namespace prefix in the snapshot into two fresh hash maps on every transaction. A BSBM 1M ledger carries a few thousand namespaces, and on its update workload that rebuild, with the hashing and allocator churn behind it, was about two thirds of the request thread's CPU. The registry now reads through the snapshot's code and reverse tables by refcount, both behind an Arc, and keeps only its own allocations locally; defaults the snapshot lacks are layered on top as before, and a conflicting one is still reported. BSBM 1M Explore-and-Update write-only mix on m7a.4xlarge / gp3, WAL: one client INSERT DATA 54.1 -> 16.0 ms, DELETE WHERE 41.2 -> 6.9 ms; 16 clients 14,097 -> 66,567 QMpH.
…'s tables The layered registry holds the snapshot's namespace tables by refcount, so a commit that carries a namespace delta found them shared and copied both before extending them. Dropping the registry once its delta is taken keeps the extension in place. The defaults merged under a layered registry come from one cached map rather than a map built per call.
The binary range provider holds the snapshot's namespace table as its fallback for the life of the index, so a commit carrying a namespace delta found the table shared and copied all of it before adding an entry. The provider is detached for the extension, as finalize already does before it extends the dictionaries, and put back unchanged; finalize then rebuilds it over the extended table.
…ne syncfs on Linux On the benchmark volume (EBS gp3, ext4) a 4 KiB append followed by fsync costs 2.8 ms whether the file grows or was fallocated, but 0.9 ms with fdatasync on a file whose blocks were already written: the flush then carries data only and skips the inode commit. Segments are now zero-filled to their rotation size when opened, so appends never grow them, and each flush is sync_data. Replay reads the zero tail as the end of a segment, which is also what a frame whose first bytes never landed looks like. Retirement on Linux flushed every touched file with its own fsync, serially from the flusher thread against the device the next commit was waiting on; under load that was more flushes than the commits themselves. Each file now starts write-back with sync_file_range and the batch is committed by one syncfs on the root's filesystem, the counterpart of the single drive barrier used on macOS.
An incremental index publish keeps nearly every artifact of the previous root, but installing it loaded the binary store from scratch: every forward pack was re-stated, re-opened and re-parsed, every reverse-tree leaf re-resolved, the namespace tables and prefix trie rebuilt. On a 1M-triple ledger that reload was the largest remaining CPU consumer under concurrent writes and the source of the multi-second write latency tails. The store now loads against the store it replaces and reuses, by content id, the forward pack handles, the reverse dictionary readers (whole when the branch is unchanged, otherwise their local leaf paths), named-graph branch manifests, and the namespace tables when the root's table is already covered. The store id stays fresh so the overlay translation cache still keys on the publish. The cache listener's publish and the cached-ledger reload pass their current store; fresh loads pass none. The root is decoded once per install instead of twice.
…it again A write through a cached handle stages against a snapshot and takes the ledger lock for the commit. If the ledger moved in between, the stage was redone under the lock. Under steady contention it always has: the lock is FIFO and a commit is always in flight at snapshot time, so every write staged twice and the lock hold was the whole request. SPARQL UPDATE did not even try; it held the lock across parse, lowering, staging and commit. Staged flakes name their subjects by IRI and only get dictionary ids at finalize, under the lock, so a stage computed against an older state is still a correct stage over a newer one when nothing that landed in between touched what it read or wrote. Each staging now records that as a write scope: bounded to a subject set when every read was tied to a subject the transaction named (bound-subject WHERE patterns, upsert template subjects) plus the subjects it wrote, and no validation looked further; unbounded otherwise. Each handle keeps the footprints of its last commits as one chain. At the lock, a stage whose scope is disjoint from every commit since its snapshot, and whose namespace allocations still fit the table, is restamped to the new t and committed over a clone of the locked state; anything else is staged again under the held lock, without giving up its place in the queue. SPARQL UPDATE joins the optimistic path. The handle counts how its writes reached their commits (direct, re-based, restaged), and a test hook parks the next optimistic stage between its stage and its lock so the race can be staged deterministically.
Under sixteen writers the ledger lock is held by commits alone for most of the run, at about 4 ms per commit, so what runs inside that hold is now the ceiling. Four pieces of it did the same work over and over: - Dictionary population probed the persisted reverse trees once per flake, so a subject with twelve triples cost twelve tree lookups. Entries the novelty layer already holds are not probed, and an entry found persisted is remembered for the rest of the commit. - Every write called create_dir_all on its parent. File storage now remembers the directories it has created; a write that finds one gone forgets it and retries once. - The head publish appended the commit-CID index line inline. The line is a discovery accelerator whose reader sorts by t and walks the chain for any gap, so it is now appended on a detached task. - The publish event made the cache listener re-read and re-parse the record the commit had just written. A handle remembers the t of the last commit it installed and the listener skips those. The write-path debug target now reports each commit's phases (lock acquisition to detach, build, blob write, head publish split into its read, write and index parts, finalize, install) so the next cut is measured rather than guessed.
…nning the table A commit that introduces namespace codes extends the snapshot's namespace table in place, but the binary range provider holds that table as its decode fallback, so while the provider lived the extension copied the whole table twice. Taking the provider off the snapshot did not help: the taken value still held it. BSBM makes this the common case, since every offer's webpage IRI ends in a slash and mints a namespace, and its ledger carries forty thousand of them, so each such insert copied eighty thousand strings inside the lock. The provider's store is kept, the provider dropped, the table extended, and a provider rebuilt over the extended table; a provider of another kind is put back as before. A commit with no delta does not touch the snapshot at all.
Installing a published index rebuilt the dictionary novelty from scratch and walked the remaining novelty flakes three times, all under the ledger's write lock: 30 to 215 ms per publish on a busy ledger, during which no commit could land. Each novelty entry now remembers the earliest commit t it was seen at. An install covering index t drops every entry seen at or before it and renumbers the rest contiguously above the new watermarks. That is sound without any agreement with the index's own dictionaries: a flake that remains can only name an entry seen at or before t if the index persisted it, and an entry first seen later is not in the index. (Agreement cannot be assumed: the index interns the commit address as hex where the novelty holds the base32 form, for one.) The runtime small dictionaries are reseeded from the previous ones rather than from a flake walk.
With the dictionary retire in place the install's remaining cost was three loops over things that had not changed. The novelty segment straddling the index point was rebuilt from its survivors with four sorts; it is now filtered, each of its orders kept as it was. The namespace merge into the new snapshot and the store-to-snapshot sync each walked every namespace of the ledger — forty thousand on the BSBM ledger, where every offer's webpage IRI is one — inserting entries that were already there; the merge now carries only the codes above the new root's highest, and the sync skips entries the snapshot agrees on. Off the lock, the store load built a pack reader per namespace through a lookup map even when the namespace's routing table was unchanged; an unchanged table is now recognised in order and its handles cloned.
The commit-hold timers said where a hold went; a request's time before the lock was still unaccounted for. One debug event per optimistic write now carries the three parts, so a latency tail can be placed on the read side (a cold snapshot after a publish), the stage, or the queue.
… on commits A reconcile reads the nameservice record before the local metrics, so a commit landing in between leaves the record one behind. The plan treated that as "nothing to do" and dropped the index the record named; on a busy writer the same race hit every publish, the novelty never cleared, and every commit re-triggered a build while stagings paid a full overlay translation.
…e shape changes a barrier A stage names its subjects under the namespace codes it allocated, while the commits in between name theirs under the codes the ledger gave the same prefixes. Once a commit had taken the stage's code the same IRI carried different codes on the two sides, so a write to the stage's own subject compared as disjoint and an upsert re-based over it, leaving both values. The namespaces are now re-allocated before the footprints are compared, and the stage's subjects are compared under the codes the ledger uses. A stage staged while the ledger had no shapes is bounded to its subjects, and a commit that adds a shape touches only the shape's own subjects, so the stage re-based over it without ever being validated. A commit whose flakes touch the SHACL vocabulary, the class hierarchy shapes target through, or any named graph, where shapes and the ledger's config live, now records no subject set; the ring reads that as touching everything, so what was staged before it stages again and meets the new rules. Installing an index cloned the dictionary novelty's Arc before making it mutable, which guaranteed a second reference and copied the whole dictionary under the write lock on every install, reader or not. The retire now mutates the field itself, so an unshared dictionary is trimmed in place and only a dictionary a reader still holds is copied. Each fix carries a test shown to fail without it.
Preserve group-commit flushing, preallocated segments, and cached parent creation while incorporating the reviewed WAL recovery and ownership fixes. Keep both branches' regression tests and main's simplified FSYNC documentation. Validate a zeroed frame header as damage when nonzero bytes follow it, so preallocated tails cannot bypass corruption look-ahead. Adapt retirement flush-count assertions to the platform batch barrier.
aaj3f
left a comment
There was a problem hiding this comment.
I started this review on Friday prior to some additional commits from you that corrected / changed some review items. For clarity/coverage, I've included below (1st) the original review and (2nd) the updated review considering the subsequent commits. The only thing I might (as a human) spotlight for consideration (also mentioned in the full reviews below)
- it seems
commit_and_finalizewalks staged flakes 2x (once for staged dependencies, once to collect subjects) and both under the write guard lock, butwrite_scopealready exhibits a pattern of walking them off-lock at stage-time. It seems possible maybe that we could that work in one pass inwrite_scopecarrying the set inStageResultto take that off the lock/hold
Full review(s) below
(Initial Review)
This is really nice — the shared flush is the shape I'd want (covered watermark sampled before the mutex drops, poison-before-wake, an unwind guard for the leader), the rebase is careful in exactly the places it needed to be (namespace re-allocation before the footprint compare, a barrier on shapes and named graphs, restage under the held lock so a stage can't lose twice), and the lock-hold work — layered registries, in-place dictionary retirement, content-id-keyed store reuse, the reconcile fix — is each a real cost I could see at the base. I ran every suite in the PR locally (nothing runs in CI on a stacked branch), plus fmt and clippy on all seven crates, and mutated six invariants: four went red where they should. Two things need to land before this merges. First, wal.rs:1274: zero-filling every segment to 8 MiB, combined with the one-second age rotation, makes a writer at or above one commit a second write a fresh 8 MiB every second and a slower writer write 8 MiB per commit — measured here as 5.8 ms per commit in a burst versus 24.8 ms for a trickle writer, with 8 MiB of device writes per open; recycling retired segments (rename, don't unlink) gets the fdatasync win without the fill. Second, the two Unbounded arms in tx.rs (:2158, :2208) — the only guards against write skew on a ledger with shapes, uniqueness, policy, or a SPARQL WHERE — have no test: I mutated each away and every suite stayed green; the code is right, but two gate-based tests would pin it. Everything else below is optional and small enough that I'd rather see it folded in than tracked — the short-zero-tail decode edge and the syncfs note are the two I'd pick first. On #1820's findings: this PR fixes the touched dedup and leaves the rest (including the replay_unowned blocker) untouched with no conflicting hunks, so land those in #1820 and rebase; the SHA-256-under-the-mutex swap is the one I'd move here since this PR restructures append.
(After additional commits)
Re-landing this on main got it its first CI run, and both things that run caught (the wasm clocks, the Raft survivor test) are fixed honestly in e28ba1067; the metadata-namespace remap and the annotation barrier are both right and both pinned by tests that go red under mutation. #1820's final form sits underneath cleanly: xxh64 with the payload hashed before the mutex (which retires my SHA-256 note), the ownership retry and replay_unowned untouched, and the zero-header look-ahead resolved the right way. Three things still need to land before this merges, two of them carried from the first pass. First, wal.rs:1469: zero-filling every segment to 8 MiB, combined with the one-second age rotation, still makes a writer at or above one commit a second write a fresh 8 MiB every second and a slower writer write 8 MiB per commit — re-measured at this head as 8.0 ms per commit in a burst versus 25.9 ms for a trickle writer with three flushes and one 8 MiB segment open per commit; recycling retired segments (rename, don't unlink) gets the fdatasync win without the fill. Second, the two Unbounded arms in tx.rs (:2158, :2208) — the only guards against write skew on a ledger with shapes, uniqueness, policy, or a SPARQL WHERE — still have no test: I re-applied both mutations and all ten tests in the three suites stayed green. Third, new: binary_index_store.rs:383 and :396 still read std::time::Instant::now(), which is the same abort wasm-smoke hit at the merge commit, on the index-attach path the wasm residency tier uses; the smoke probe has no index so CI can't see it, and it's the same two-line clock::Instant swap as the other three files. Everything else below is optional and small — the short-zero-tail decode edge and the storage.md sentence (this PR's doc paragraphs were dropped in the merge, so the 8 MiB footprint and the filesystem-wide syncfs are now undocumented) are the two I'd pick first. On stacking: #1824 and #1825 base on this branch and #1826 on #1825, so all three inherit these until this lands; I'd fix here and retarget them afterwards rather than carry the wasm abort three PRs deep.
Adherence to repo commitments:
- Patterns/abstractions: ✔
NamespaceCodes::layered_overis the same type with a shared base;DictNovelty::retire_seen_throughfalls back to the existing rebuild when it can't trim;load_from_root_v6_reusingwraps the existing loader keyed on content ids;ResolveCtx::open_model_dbis the one seam every materializer now uses; the wasm clock fix reusesfluree_db_core::clock— in three of the four files that needed it. - Performance (speed first, memory second): ✖ CRITICAL on the segment preallocation for low-rate writers (
wal.rs:1469, re-measured at this head); otherwise a large concurrent-writer win (r1's 547 vs 92 commits/s on 16 ledgers, 139 vs 70 on one, author's base numbers), sequential unchanged, and the footprint set (a second pass under the lock, now with a per-flake name match) and ring memory bound are minor notes. - Testing:
⚠️ CI now runs on this PR and is green ate28ba1067(test 12,530 nextest cases incl. every suite this PR adds, clippy, fmt, wasm32, wasm-smoke, sql-bridge, testsuite-sparql); the two new rebase tests go red under mutation; but the twoUnboundedarms are still unpinned (two mutations, nothing red), and the wasm index-attach path is covered by no job. - Conventions: ✔ fmt clean (CI + locally on all eight touched crates); clippy
--all --all-features --all-targets -D warningsgreen in CI;git diff --checkclean; no new deps; the twounsafeFFI blocks still carry no// SAFETY:(not lint-gated); PR body stale on base, commit count and CI status; three subject-only commits.
Verified locally at branch HEAD e28ba1067: cargo test -p fluree-db-core --features native --lib -- storage:: (129 passed); cargo test -p fluree-db-api --features native,shacl on it_optimistic_rebase (8), it_concurrent_writers (1), it_wal (4 + 2 ignored, the trickle probe run by hand), it_cached_handle_cow (1), grp_index -- it_indexing_wait, grp_graphsource -- it_shapes_cross_ledger; binary-index/ledger/novelty/transact/nameservice suites; fmt on all eight crates; four mutations (two red, two green) and two probes, all restored; CI job logs at 8aebe369d and e28ba1067 read.
Just be sure to get the segment recycling (or an equivalent that stops the per-rotation fill), the two Unbounded tests, and the clock::Instant swap in binary_index_store.rs in before this merges; happy to talk through any of the optional ones.
Notes with no line in this diff to anchor to:
PR body / commit list — optional, conventions. CHANGED from r1. 2517d0e51 is on origin/main now (it landed through #1820), so that thread is resolved. The body is stale in three places: it still says "Base: feat/storage-wal" and "the rebase onto 2517d0e51 preserved all 19 commits" (base is main, 22 commits over it), and "the full test suite has not been rerun" (CI is green at this head, all jobs). And three commits are subject-only now: ef7094278, 12c04243f, e28ba1067 — the last two are the ones a future reader will most want a body for (what was wrong with metadata codes and the annotation cascade; which CI failures the clocks and Raft changes answer).
| // the file: a flush then carries only data, which on Linux is a | ||
| // fraction of the cost of one that must also commit the inode. | ||
| // Replay reads the zero tail as the end of the segment. | ||
| let zeros = vec![0u8; 1 << 20]; |
There was a problem hiding this comment.
fluree-db-core/src/storage/wal.rs:1469 — blocking, CRITICAL (performance). UNCHANGED from r1 (was :1274). Preallocating every segment as 8 MiB of zeros turns the one-second age rotation into an 8 MiB write per second for any writer at or above one append a second, and into an 8 MiB write per commit for any writer slower than that. open_segment still writes ROTATE_BYTES of zeros and sync_alls them before the rename (:1469-1476), and tick still closes a touched segment after ROTATE_AGE = 1 s (:59, :1548), so the next append opens a fresh one inline, under inner, on the commit path. Re-measured at this head with the PR's own it_wal helpers: the same insert costs 8.0 ms median in a burst (one flush per commit) and 25.9 ms median (21.6–73.6) with a 1.3 s pause between commits, three foreground flushes per commit, and the WAL directory is left holding 00000019.wal at exactly 8,388,608 bytes after 49 commits of which 18 were trickled — eighteen of the nineteen segment opens were trickle commits, each a header write, an 8 MiB fill, a full flush and a directory flush. The fdatasync win the body measured (2.8 → 0.9 ms per flush) needs blocks that were written once; it does not need writing them again every rotation. The fix I would want is recycling: on retirement, rewrite the header and rename the retired file into the next segment id instead of unlinking it (PostgreSQL's WAL recycling), so the blocks stay already-written for free after the first few segments and retirement loses its unlink + directory fsync too. Failing that, fill lazily in 1 MiB steps as len approaches the fill, or stop age-rotating into a fresh 8 MiB when the closing segment used a small fraction of it. Either way the trickle writer should pay what it paid at the base — a header write and one flush. And since the merge kept main's simplified storage doc (this PR's storage.md paragraphs are gone; the docs diff against main is now empty), the 8 MiB-per-open-segment footprint — per root, and per owner log in a Raft cluster — is undocumented; whatever shape the fix takes, a sentence under the Durability paragraph at docs/operations/storage.md:350 should state the disk footprint.
| if txn.graph_mgmt.is_some() | ||
| || txn.sync_graph.is_some() | ||
| || !txn.graph_delta.is_empty() | ||
| || txn.sparql_where.is_some() |
There was a problem hiding this comment.
fluree-db-api/src/tx.rs:2158 — blocking (testing). UNCHANGED from r1 (same line). The two Unbounded arms — the only thing standing between the rebase and write skew on a governed ledger — still have no test. I re-applied both mutations at this head: bounded_read_subjects treating a SPARQL WHERE as bounded (drop the sparql_where.is_some() clause here) and, separately, write_scope ignoring read_beyond_subjects (:2208, so validation, uniqueness and policy no longer unbound the scope); all eight it_optimistic_rebase tests plus it_concurrent_writers and it_cached_handle_cow stayed green both times. The two tests this revision adds (a_rebase_preserves_transaction_metadata_namespaces, a_delete_behind_a_new_annotation_is_restaged_to_cascade_it) are good and both go red under their own mutations, but neither touches these arms, and sparql_writes_under_contention_land_by_rebase uses INSERT DATA with no WHERE. The code is right today — I traced both arms again — but the failure they prevent is a real one. Under the first mutant: A = INSERT { ex:t ex:q 1 } WHERE { FILTER NOT EXISTS { ex:s ex:p 1 } }, B = INSERT { ex:s ex:p 1 } WHERE { FILTER NOT EXISTS { ex:t ex:q 1 } }, both staged at t0 where neither exists; B commits first, A's scope is {ex:t}, B's footprint is {ex:s}, disjoint → A re-bases and both land, which no serial order produces. Under the second: a #config with f:uniqueProperties ex:email, A inserts ex:u1 ex:email "x", B inserts ex:u2 ex:email "x", both pass uniqueness at t0, disjoint subjects → both land. Two tests in it_optimistic_rebase would pin them, each using gate_next_optimistic_stage_for_test exactly like a_delete_behind_a_new_annotation_is_restaged_to_cascade_it does: park the WHERE/NOT EXISTS write, commit the conflicting one, release, and assert write_path_stats().restaged == 1 and the serial outcome; and park a second insert of a unique-property value behind a first, release, and assert the second is rejected. Both are twenty lines against helpers that already exist, so I'd rather see them in this PR than in the backlog.
| ) -> io::Result<Self> { | ||
| tracing::debug!("BinaryIndexStore::load_from_root_v6 starting"); | ||
| fluree_db_core::disk_cache::ensure_cache_dir(cache_dir)?; | ||
| let phase = std::time::Instant::now(); |
There was a problem hiding this comment.
fluree-db-binary-index/src/read/binary_index_store.rs:383 — blocking (correctness, browser build). NEW in r2. load_from_root_v6_reusing reads std::time::Instant::now() twice (:383, :396), and on wasm32-unknown-unknown that aborts the process with "time not implemented on this platform" the first time the browser attaches a binary index. Claude caught this while reading the failed CI run at the merge commit: wasm-smoke at 8aebe369d died five times with exactly that message from the timing instrumentation this PR added, and e28ba1067 moved tx_builder.rs, commit.rs and ledger/lib.rs onto fluree_db_core::clock::Instant — but not this file, whose two reads were added by the same instrumentation commit and did not exist on main (git show origin/main:…/binary_index_store.rs has no Instant at all). The call path is not gated: load_and_attach_binary_store (fluree-db-api/src/ledger_manager.rs:1149, no cfg) calls it at :1185 and is the index-attach path for every load (ledger/loading.rs:13), including the wasm residency read tier that it_residency_retry.rs describes as "read arms wasm32 gets unconditionally" and that fluree-db-nameservice-sync/src/driver.rs:128 feeds index heads to. wasm-smoke cannot see it because the probe drives a memory ledger with no index, so CI is green on a build that aborts on its first indexed ledger. Same two-line fix as the other three files: fluree_db_core::clock::Instant::now() (the crate already depends on fluree_db_core, :382). I could not run a wasm build here; the evidence is CI's own abort log plus the ungated call chain, so if there is a reason index attach is unreachable on wasm I'd want it in a comment on the call.
There was a problem hiding this comment.
Addressed in 41943a9
Deferring indexed-load coverage in wasm-smoke. The playground only drives memory ledgers, so it needs a natively built index fixture served to the browser. That's a separate piece of harness work.
| let Some(header) = bytes.get(at..at + FRAME_HEADER) else { | ||
| break false; | ||
| }; | ||
| if header[..4] == [0; 4] { |
There was a problem hiding this comment.
fluree-db-core/src/storage/wal.rs:334 — optional, correctness edge. UNCHANGED from r1 (was :264). Claude caught this in r1 and I reproduced it again at this head: the zero-tail check still runs only after bytes.get(at..at + FRAME_HEADER) succeeds (:331-333), so a preallocated segment whose last frame ends within 1–15 bytes of the file end decodes as clean = false (a throwaway test: valid frame + 7 zero bytes → unclean; + 64 zero bytes → clean). The merge's new rule at :334-338 — a zero header followed by non-zero bytes runs the damage look-ahead — is right and is pinned by the "zeroed header" case in lookahead_preserves_the_log_and_files_on_ambiguous_tail_damage, but it does not reach the short tail, because the get fails first. Reachable when a segment fills to just short of ROTATE_BYTES (which never triggers the size rotation) and is then age-rotated or checkpointed; if a later segment exists at the next open, walk_segments (:966-978) refuses the root with "damaged before a later segment; move it aside", and moving it aside drops its acknowledged records. Rare, but the failure mode is an operator being steered into data loss. Checking the zero magic on whatever bytes remain before requiring a full header would close it, e.g. if bytes[at..].iter().all(|b| *b == 0) { break true; } ahead of the get. Minor and non-blocking — but if you agree it's right I'd rather see it folded in now than lost in the backlog.
| fn syncfs(base: &Path, fsyncs: &AtomicU64) -> io::Result<()> { | ||
| use std::os::fd::AsRawFd; | ||
| let dir = File::open(base)?; | ||
| if unsafe { libc::syncfs(dir.as_raw_fd()) } != 0 { |
There was a problem hiding this comment.
fluree-db-core/src/storage/wal.rs:739 — optional, design + docs. CHANGED from r1 (was :575): the Linux arms have now been compiled and exercised by CI on ubuntu, which removes the "never compiled" caveat; the two substantive notes stand. syncfs commits every dirty page on the filesystem, not the batch's, so a co-located import or index build (hundreds of MB of page-cache derived artifacts) or another tenant's writes on a shared volume extend every retirement — correct, but a latency exposure the per-file fsync did not have. And before kernel 5.8 syncfs reports no write-back error at all (the errseq_t plumbing for it landed in 5.8), so on an older kernel a failed write-back can be unlinked over where the base's per-file fsync would have failed the batch. A per-file fdatasync for small batches (most retirements on a busy ledger are a few files) would sidestep both without giving up the batch win for large ones. With this PR's storage.md paragraphs dropped in the merge, neither the filesystem-wide scope nor the preallocation is documented anywhere now; a sentence under docs/operations/storage.md:350 would do. Non-blocking.
There was a problem hiding this comment.
The documentation part is addressed in fcafe23. storage.md now says retirement syncs the whole filesystem on Linux, and recommends putting the root on its own volume.
Deferring the per-file fdatasync for small batches. The cutoff should come from measuring retirement next to a co-located import, and I haven't run that yet.
| // subjects have to be compared under those same codes, or a write | ||
| // to one of them under a moved code reads as disjoint. | ||
| let mut ns_registry = NamespaceRegistry::from_db(¤t.snapshot); | ||
| let mut remap: HashMap<u16, u16> = HashMap::new(); |
There was a problem hiding this comment.
fluree-db-api/src/tx_builder.rs:2055 — praise (r1 :2063). Re-allocating the stage's namespace delta against the current table before comparing footprints, and remapping s, p, dt, Ref objects — and now the transaction-metadata predicate, Ref and datatype codes too (:2120-2137) — is exactly the fix the moved-code false negative needed. Mutating the metadata remap away turns a_rebase_preserves_transaction_metadata_namespaces red, and the test checks both the cached state and the replayed commit envelope.
| let changes_dependencies = staged.iter().any(|flake| { | ||
| use fluree_vocab::namespaces::{RDFS, SHACL}; | ||
| flake.g.is_some() | ||
| || fluree_db_core::is_reserved_reifies_predicate(&flake.p) |
There was a problem hiding this comment.
fluree-db-api/src/tx_builder.rs:1841 — praise. Making any reifies flake a barrier closes the first-annotation hole precisely where it lives: an upsert that attaches an annotation to an unchanged edge leaves only the annotation subject in the footprint, so a delete of that edge staged before it would re-base and miss the cascade. Dropping the clause turns a_delete_behind_a_new_annotation_is_restaged_to_cascade_it red; on a ledger that already carries annotations, retracts are unbounded (tx.rs:2167), so the barrier only has to cover the transition.
| .iter() | ||
| .find(|n| n.node_id != worker && n.node_id != leader) | ||
| .map(|n| n.node_id) | ||
| .expect("three nodes leave one that is neither worker nor leader"); |
There was a problem hiding this comment.
fluree-db-server/tests/raft_multi_node.rs:1749 — praise. Reading the missing payload through the survivor's own storage and asserting the bytes, instead of inferring a miss from a query that can be served from cache, makes the test assert the property it was written for; the doc comment says plainly why.
| /// keyed purely on content ids, so a mismatched or absent `prev` only | ||
| /// costs the fresh load. The store id is still fresh: a publish can | ||
| /// re-rank dictionary ids, and the overlay translation cache keys on it. | ||
| pub async fn load_from_root_v6_reusing( |
There was a problem hiding this comment.
fluree-db-binary-index/src/read/binary_index_store.rs:374 — praise (r1, same line). The reuse is keyed purely on content ids plus id ranges (and the same cache and cache dir for reverse readers), with the same-cid-different-range and other-stream negatives tested, so a stale prev can only cost a fresh load, never serve the wrong pack.
| // Large gap — full reload | ||
| UpdatePlan::Reload | ||
| } else { | ||
| // ns.commit_t < local_t: the record is older than the cached |
There was a problem hiding this comment.
fluree-db-api/src/ledger_manager.rs:2247 — praise (r1, same line). The record-behind-the-cache case now installs the index it names; the comment explains the race precisely and the unit test pins both the install and the no-advance no-op.
decode_segment checked for the preallocated zero tail only after reading a full frame header, so a segment whose last frame ended within 15 bytes of the file's end decoded as damaged. With a later segment present at the next open, recovery refused the root and directed the operator to move the segment aside, which would drop its acknowledged records. The all-zero check now runs before the header read. A zero header followed by non-zero bytes still runs the damage look-ahead.
Every segment was zero-filled to its 8 MiB rotation size when opened. With segments closing after a second, a writer committing about once a second rewrote 8 MiB every second, and a slower writer paid the fill and its flush on every commit. A segment is now filled to twice what the previous one used, between 64 KiB and 8 MiB. An append that crosses the fill extends it to what the writer's rate so far will use before the segment ages out, at least doubling it, so a burst after an idle spell reaches full size in one or two extensions. Plain doubling took about seven, each a size-changing flush, and it showed in p99. The fill still has to be written. On ext4 a flush into a sparse (set_len) or fallocated file costs what one into a growing file does (0.35-0.38 ms against 0.056 ms zero-filled in a local VM; 2.8 ms against 0.9 ms on gp3). Recycling retired segments was not an option either: their stale frames read as tears, and replay refuses a damaged segment that has a later one. With it_wal's probes, a commit slower than rotation went from 20.5 to 10 ms on Linux (ext4 in a VM) and from 25 to 20 ms on macOS; burst and concurrent throughput are unchanged. timing_trickle_wal is new, and FLUREE_TIMING_IDLE_MS times a concurrent burst that starts from an idle log. storage.md now states the log's footprint and that retirement syncs the whole filesystem on Linux.
Two writes staged at one snapshot can each read what the other writes: a SPARQL WHERE, or a uniqueness check over every subject holding a value. Their written subjects are disjoint, so only an Unbounded scope keeps a re-base from landing both. No test covered either guard; removing one left every suite green. One test parks a WHERE ... FILTER NOT EXISTS insert behind its mirror image and expects a restage and the serial outcome. The other parks an insert of a value ledger config marks unique behind a duplicate on another subject and expects the uniqueness violation. The constraint is configured on the ledger, not passed inline, because inline properties unbound the scope through a different check. Each test fails with its own guard removed and passes with the other removed.
load_from_root_v6_reusing timed its phases with std::time::Instant, which aborts on wasm32-unknown-unknown the first time a browser attaches a binary index. This is the swap e28ba10 made on the write path; wasm-smoke cannot reach this one because its ledgers carry no index.
The condition is a cached handle at or past the event's t. A Raft follower that applied the entry from its log satisfies it too, not only a commit this process installed.
fsync, sync_file_range and syncfs each take a descriptor borrowed from a File that stays open for the call, pass no pointers, and keep nothing afterwards.
Improves throughput for concurrent transactions and for sustained writes while indexes are being published. Overlapping commits share WAL flushes, disjoint writes reuse their staged work, and commits and index installs avoid repeated dictionary and namespace work.
WHERE, uniqueness, validation, policy).Validation coverage includes shared-flush and failure ordering, segment fill sizing and zero-tail replay, concurrent writers, namespace collisions, newly introduced SHACL rules and annotations, restage guards for unbounded reads, dictionary ownership, and index publication.
Builds on the WAL from #1820. The existing BSBM measurements do not isolate this PR's incremental gain over that base.