Repository navigation
fix(index): directory aggregates read leaflets' row groups, not routing keys - #2402
Conversation
A leaflet's first and last routing keys are widened over the history it holds, so they bound its rows without naming them. Each leaflet directory entry now also stores the group (the key prefix lead_group_count counts) of its first and last row, derived from the rows encode_leaflet encodes. A leaflet copied without re-encoding keeps its rows and so its groups. A v4 leaf stores none and decodes as LiveEdges::Legacy, so a reader can tell a legacy leaflet from an empty one.
Distinct subjects and objects over a run of leaflets are the sum of their lead_group_count, less one where a leaflet's first group is the previous leaflet's last. The walks took those groups from the routing keys, which history widens past a leaflet's rows: a retraction at a leaflet boundary named a group the next leaflet holds no row of, and the count came out one short per such boundary. The three walks (whole-graph, per predicate, and live NumBig handles) now run on one shared walk that takes the groups a v5 leaflet stores. A v4 leaflet stores none: its routing keys stand for its rows where it holds no history, and otherwise the walk reads the group from its lead column at a boundary where the routing groups meet. A leaflet with rows and no lead_group_count now declines in every walk, and a decline reaches the caller instead of reading as zero.
The numeric and string MIN/MAX fast paths took a leaflet's routing keys as its extremes, so a retracted extreme that widened them was returned. They now take the leaflet's first or last row's group: stored in a v5 leaflet, or the routing key's for a v4 leaflet with no history, or read from its lead column. The numeric path reads only the predicate's first or last leaflet, which POST orders by value under one o_type.
The walk skipped a POST leaflet whose routing keys' o_key fell outside the range, without checking the keys' o_type. A retracted value of another type on the same predicate widens a key into that type, whose o_key does not compare with the range, and a leaflet holding values in range was skipped. The prune now uses post_o_key_bounds, as the batched join does.
Distinct subjects and objects, per-predicate distinct objects and subjects (through SUM(STRLEN(GROUP_CONCAT))), MIN, MAX and the range semijoin, each over data that puts a retraction at the leaflet boundaries, after a full and an incremental build, walking serially and in parallel chunks. Every case checks the fast path and the general pipeline on the same index against an unindexed ledger, with the lane's routing stamp pinned. A subject that spans a widened boundary guards against counting it twice.
Erasing events a v4 index holds only in its history rewrote the leaves holding them and passed the rest through, which would leave a root mixing v4 and v5 artifacts; with leaflets now carrying live groups, the copy of a v4 leaflet fails outright. A root that is not of this build's format now goes to Erased::NeedsRebuild before any leaf is rewritten.
Reading a v4 leaflet's row groups now takes both from one decode of its lead columns, and the walk keeps the last leaflet it read: walking left to right, the leaflet whose first group one boundary read is the one whose last group the next boundary needs.
The parallel passes now build many leaves (leaf_rows = 6) and assert that the walk split them into chunks, and a subject filling every leaf and an object held by every subject put a shared group across each chunk seam. A fixture indexed by v4.2.6 with tiny leaflets holds retractions at leaflet boundaries, built in full and incrementally: distinct counts, MIN and MAX over it read the groups of v4 leaflets' rows, and a history-only erasure from it rebuilds the index.
A boundary that reads a v4 leaflet's rows now keeps the groups it read on the leaflet's edges, so the next boundary, a chunk seam and the pending seams settled after the reduce reuse them. The single-entry memo could evict a leaflet the next boundary needed, and parallel chunks discarded what they had read. The read goes through the leaflet cache and range-reads a remote leaf, as the store's other walks that read a few leaflets of many leaves do.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is really nice, and at a design level no pushback from me: stored live groups plus one shared walk is #2394's plan, and the latest commit's proven-edges walk is a better answer to the v4 re-reads than a bigger memo would have been.
My reading is that the alphas carry no index migration: anyone on alpha.2 or alpha.3 reindexes every ledger on the next alpha. That seems right for pre-releases, but I'd like your confirmation, plus a line in the alpha notes. Nothing enforces it yet, though: with no version byte on the new leaf layout, this build serves an alpha.3 index and misreads it (must 1; must 2 is a ten-line perf fix).
Similarly, my reading is that erasing from a ledger still on a v4 index now costs a full reindex inside the purge, not a leaf-by-leaf rewrite. That seems right, since its next build rebuilds anyway, but I'd like your confirmation it's intended.
Full review below:
✅ Approving to unblock: please get the version bump for earlier-alpha indexes and the proven-edge check at the call site in before merging. This is the right design, the tests bite (every mutation Claude ran goes red, including the three it made to the new walk), and both musts are a few lines.
Before merging:
fluree-db-binary-index/src/format/leaf.rs:1275: bump the root (and leaf) version, so an alpha.2/alpha.3 index is refused rather than misread.fluree-db-query/src/fast_lead_walk.rs:231: compare two proven edges before callingpush; whole-graph distinct counts are 3–7% slower without it.
Notes:
- This is the mirror image of the class the 11-13 sweep found (a directory fact computed over live rows, trusted below the index
t): one directory field with a meaning pert-regime, read with the other's. #1223 and #2373 trusted live-rows facts belowt, #1624 widened the routing keys for below-treads, and #2394/#2398/#2399 then read those bounds as row values at head. The shared walk and the point fixes are right here, and Claude's census found no value reader left on the routing keys. The cheap structural piece is thelive_edgescontract (optional above); renamingfirst_key/last_keyto say they're bounds belongs with #2375. - For the
mainfix the body says follows (no PR for it yet): this module withleaflet_edgescut to itsLegacyarm is #2394'smainplan, and landing it as the same file keeps the nextmain→nextmerge mechanical, where a fourth walk onmainwould conflict with this rewrite of all three. #1322's planned per-leaf summary could combine throughPartial::jointoo, rather than a fifth copy of the rule. - The v4 cost is much smaller now. On Claude's 1.05M-row v4.2.6-built index, served by this head,
COUNT(DISTINCT ?s)takes 0.44 ms warm (the merge-base's 50 µs answered 73 short), whole-graph distinct objects 58 µs against 51, andMIN23 µs against 21.5. The reads now go through the leaflet cache and open remote leaves by range first; a leaf's second open still fetches it whole, and nobody has measured the cold remote cost, so an upgrade-notes line suggesting a reindex for ledgers that lean on these aggregates would still help. - At the merge-base the same box reproduced all three issues at scale:
COUNT(DISTINCT ?s)149,928 for 150,001,MIN−5 (a retracted value), and a range semijoin that droppedex:s0149999. This head gets all three right, andMAX, which the merge-base declined to the general pipeline (about 52 ms), answers in 22 µs.
Adherence: Patterns ✔ · Performance ⚠️ · Deployment targets ⚠️ · Testing ✔ · Conventions ⚠️ · verification
- Patterns/abstractions: ✔ one shared walk replaces three hand-written copies of the boundary dedup; it reuses
post_o_key_bounds,open_leaf_handle_ranged,load_leaflet_projectionandparallel_leaf_chunk_reduce_at, and adds a typedLiveEdgesrather than overloading the routing keys. - Performance (speed first, memory second):
⚠️ v5 whole-graph distinct counts are 3–7% slower than the merge-base (down from 10–11% atc8ced95a7; must 2 recovers that and more); a v4 index pays a few lead-column reads for correct answers, far fewer than atc8ced95a7; index build time unchanged; +32 bytes per cached directory entry (144 → 176), +0.65% leaf bytes. - Deployment targets:
⚠️ host-neutral on a v5 index; the v4 boundary read now range-reads remote leaves through the leaflet cache, but a leaf's second open fetches it whole and all the evidence is file storage; wasm32 and wasm-smoke green on the head. - Testing: ✔ every case runs against an unindexed ledger, after a full and an incremental build, serially and in parallel chunks, with the lane stamp pinned; the new unit tests drive the walk under every chunking with a read-counting loader; CI runs them all by name. A test that an earlier-alpha leaf is refused goes with must 1.
- Conventions:
⚠️ thorough multi-line commits and updated design docs; the earlier-alpha rebuild requirement lives only in the PR body (must 1, plus an upgrade line).
Verified at 83f856cd4f: CI green on the head (run 43637703825; test: 17524 passed, all ten it_leaflet_live_edges tests and the four fast_lead_walk unit tests by name). On a box: the PR's integration tests (10) and walk unit tests (4) pass; five mutations each go red (three on the new walk's hand-offs, plus routing keys as live groups and the v4 history check); lead-column reads counted per walk; an index built by the v5.0.0-alpha.3 tag and served by this head is misread; interleaved base/c8ced95a7/head A/Bs on a v5 and a v4.2.6-built index, plus four walk variants (the call-site check above among them, run against the PR's tests); git merge-tree against #2390 and #2366.
Approving so you can merge once those two are in; the optional items are small enough to fold in while you're there.
| @@ -1219,11 +1272,34 @@ pub fn decode_leaf_dir_v3_with_base( | |||
| let history_max_t = u32::from_le_bytes(data[pos + 16..pos + 20].try_into().unwrap()); | |||
| pos += 20; | |||
|
|
|||
| let live_edges = if narrow { | |||
There was a problem hiding this comment.
Blocking: an index written by 5.0.0-alpha.2 or alpha.3 is served by this build and misread, because the leaf layout changed with no version byte.
Every version-2 leaf now has 2 × live_group_len(order) bytes after each entry's history ref, and this decoder reads them from any version-2 leaf. A leaf written by alpha.2 or alpha.3 has the same version byte and no such bytes, so the decoder takes the next entry's row_count, lead_group_count and keys as the first entry's live groups, and every entry after a leaf's first one, and payload_base, come out shifted. The root doesn't catch it either: ROOT_V6_VERSION_V5 (index_root.rs:210) is unchanged, so is_current_format accepts the alpha root and the ledger is served as current.
Claude reproduced it on a box against an index built by the published v5.0.0-alpha.3 tag itself (a small file-backed ledger, three leaflets a leaf), served by this head. The general pipeline errors on every row query (V3 cursor: column ref truncated, Unknown frame descriptor), and the fast paths answer wrong with no error: COUNT(DISTINCT ?o) over one predicate gives 4 where the answer is 2, and MIN/MAX give null where they're 0 and 11. One more commit and an index build over the alpha root repaired it there, but a ledger that takes no new commit stays this way. Going back from this build to alpha.3 errors on every query but a fast-path COUNT(*). An index from this PR's merge-base gives the same results, as it did when Claude first ran this on 11-14.
The body says those indexes must be rebuilt, which I agree with, but nothing makes that happen. The practice on next so far has been a version bump plus a refusal: 8a69d9262 took leaves to version 2 and the root to 4, and f8950668e made a root "from an earlier next build … refused rather than served; its ledger is reindexed." Bumping ROOT_V6_VERSION_V5 to 5 and refusing 4 in both IndexRoot::decode and decode_fir6_metadata, as f8950668e did for 3, gets that here: an alpha.2/alpha.3 ledger fails to load with a reindex hint instead of answering wrong, and an alpha.3 binary pointed at this build's index refuses it too, since it accepts only 2 and 4. Bumping LEAF_V3_VERSION to 3 as well would make a stray leaf fail loudly on its own. An upgrade line in the next alpha's notes ("indexes built by alpha.2 or alpha.3 must be rebuilt with fluree reindex") makes the requirement visible. Commenting here because fluree-db-binary-index/src/format/index_root.rs is not in this diff.
There was a problem hiding this comment.
No version bump: before 5.0 we keep no compatibility with earlier v5 formats, so an earlier alpha's index is rebuilt rather than refused. The alpha notes say so; see my PR comment.
| ) | ||
| } | ||
| }; | ||
| partial.push(count, edges, &mut read)?; |
There was a problem hiding this comment.
Blocking (performance): on a v5 index the whole-graph distinct counts are still 3–7% slower than the merge-base, and comparing two proven edges in the directory loop, before the call into push, makes them faster than it.
The latest commit took most of the 11-14 slowdown out, but not all of it. Every seam of a v5 walk has two proven edges and comes down to one LiveGroup comparison, yet each leaflet still goes through Partial::push, which carries the v4 path (seam_shares_group, prove, the chunk-first hand-off). It isn't the bigger directory entry: the 11-14 walk with an inline check of two proven edges, on the same 176-byte entry, ran 3.4% under the merge-base on the same box.
Claude ran interleaved A/Bs on a box (c7i.4xlarge, release builds, 1.05M live rows in 2,126 leaflets, retractions at every boundary). In the main run, COUNT(DISTINCT ?s) over ?s ?p ?o was 50.40 µs at the merge-base, 55.95 at c8ced95a7 and 52.45 here (+4.1%); COUNT(DISTINCT ?o) 50.75 → 52.25 (+3.0%); per-predicate distinct objects 39.40 → 40.20 (+2.0%), with the merge-base's spread at 0.2–0.5% and COUNT(*) flat. Putting the check inside push (before seam_shares_group, or as an early return) doesn't move it. Putting it at the call site does: in a three-round recheck, this head was +6.4% / +4.8% / +2.7% over the merge-base and the change below −3.5% / −3.3% / −1.4% under it, with COUNT(*) within 0.8% across all three. The PR's ten integration tests and four walk unit tests pass with it.
| partial.push(count, edges, &mut read)?; | |
| match partial.last { | |
| Some(prev) if prev.exact && edges.exact => { | |
| partial.count = partial.count.saturating_add(count); | |
| if prev.last == edges.first { | |
| partial.count = partial.count.saturating_sub(1); | |
| } | |
| partial.last = Some(edges); | |
| } | |
| _ => partial.push(count, edges, &mut read)?, | |
| } |
| pub first_key: [u8; ORDERED_KEY_V2_SIZE], | ||
| pub last_key: [u8; ORDERED_KEY_V2_SIZE], | ||
| pub live_edges: LiveEdges, |
There was a problem hiding this comment.
This is more of a suggestion than a finding. live_edges is the fourth fact on the decoded entry that describes the leaflet's rows at the index t, beside row_count, o_type_const and HAS_O_I, and it lands as a raw pub field with no word on what it means below the index. Every reader today is head-gated (fast_path_store / fast_path_store_policy_cleared require to_t == store.max_t()), so nothing is wrong now. But it's the exact shape #2373 found five readers trusting below t, and that #2375's "simpler alternative" wants behind an accessor.
The cheap version is a doc line on the field: the groups of the rows at the index t, which a read below it must not trust (a retracted first row isn't in them). The fuller version is an accessor in the style of o_type_const_for, returning None when the read replays history, so the next below-t reader declines rather than trusts. It's minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in 14597d7. Took the doc line: every reader is at the head, so an accessor would only add a false at each call.
| buf.extend_from_slice(first.as_bytes()); | ||
| buf.extend_from_slice(last.as_bytes()); | ||
| } | ||
| None => buf.resize(buf.len() + 2 * group_len, 0), |
There was a problem hiding this comment.
This is so minor, but EncodedLeaflet::live_edges is an Option, and None writes zero groups that decode as LiveEdges::Exact whenever row_count > 0: the subject or object id 0 as both edges. Every writer that sets None today has no rows (leaf.rs:661, incremental_leaf.rs:1023, and the Empty passthrough), so it's an invariant upheld by convention. The comment on emit_history_only_leaflet makes the case for checking this kind of thing with a hard assert, since release builds write the artifacts and the damage is silent until a reindex. One line would do it:
| None => buf.resize(buf.len() + 2 * group_len, 0), | |
| None => { | |
| assert_eq!(leaflet.row_count, 0, "a leaflet with rows must carry its live groups"); | |
| buf.resize(buf.len() + 2 * group_len, 0); | |
| } |
Minor and non-blocking, but if you agree it's right, I'd rather see it folded in now.
| impl Edges { | ||
| /// Makes `first` and `last` the rows' groups, reading them if they are | ||
| /// not. A leaflet is read at most once: the walk keeps the proven edges. | ||
| fn prove(&mut self, read: &mut impl FnMut(At) -> Result<(LiveGroup, LiveGroup)>) -> Result<()> { |
There was a problem hiding this comment.
Keeping what a seam proved on the Edges themselves, and handing it to the chunk seam and the next pending seam, is a nicer fix for the v4 re-reads than a bigger memo would have been: "read at most once" becomes a property of the data flow rather than of a cache that can evict. Claude checked it both ways. With a print in read_row_groups, a_v4_index_is_judged_by_its_rows_groups now reads lead columns 294 times over 20 walks, never the same leaflet twice in one walk (it was 371 reads at c8ced95a7, 45 of them near re-reads). And each of the three hand-offs, broken on its own (prove not recording that it proved, the chunk's first leaflet, the pending seams), turns a_v4_walk_reads_each_leaflet_once_however_it_is_chunked and a_v4_walk_subtracts_only_where_rows_share_a_group red on their read counts. On the 1.05M-row index v4.2.6 built, warm COUNT(DISTINCT ?s) went from 7.0 ms at c8ced95a7 to 0.44 ms, and MIN from 44.65 to 22.85 µs, about where the merge-base was (21.50 µs) when it answered wrong.
next charges the query's tracker for every leaflet a fast path reads. The distinct-group walk and leaflet_row_group read a v4 leaflet's lead column where its routing keys cannot settle a seam or an extreme, so they take the tracker too, and so do the distinct counts and the numeric MIN/MAX lane that call them.
Every seam of a v5 walk has two exact edges, so it comes down to one group comparison. Each leaflet still went through Partial::push, which carries the v4 path (proving edges, the chunk-first hand-off), and that left the whole-graph distinct counts 3-7% slower than before the walk was shared. The loop now settles a seam of two exact edges itself and calls push only when an edge is unproven. The same check inside push measured no faster. The result is the same as push's: with both edges exact, seam_shares_group reads nothing and compares the left's last group with the right's first, and a leaflet still held as the partial's last has never been proven at a seam, so the chunk's first needs no update.
A leaflet encoded without live groups gets zero bytes in their place, and the reader takes them as the groups of its first and last rows whenever it has rows: id 0 at both edges. Every writer that leaves the groups out writes no rows today, but only by convention. A hard assert, not a debug one, makes that a checked invariant, because release builds write the leaves and a wrong edge goes unnoticed until a reindex.
live_edges names the groups of the leaflet's rows as they stand at the index t, like row_count and o_type_const beside it. A read below that t replays history, and a row retracted since then is a row the stored groups leave out, so such a read must not take them as its rows' groups. Every reader today runs at the head, which is why nothing reads them wrongly; the field now says so for the next reader.
Confirmed: an earlier v5 alpha's index has no upgrade path and must be rebuilt. The alpha notes will carry:
Confirmed, intended: that ledger's next build is a full rebuild anyway, and rewriting only the touched leaves would leave a root mixing v4 and v5 artifacts.
Covered by the second sentence of the alpha-notes line above. |
Summary
Each v5 leaflet now stores the groups of its first and last rows, and the directory-only aggregates read those groups instead of the leaflet's routing keys.
A leaflet's routing keys are widened over the history it holds, so they bound its rows without naming them. Several fast paths treated them as the rows' own values:
COUNT(DISTINCT ?s),COUNT(DISTINCT ?o), per-predicate distinct counts, and the subject total of whole-graph aggregates.MINandMAXcould return a retracted extreme.Partially addresses #2394, #2398 and #2399: this fixes them for v5, and the fix for
mainfollows separately.Changes
lead_group_countcounts, 8 to 14 bytes depending on the order.encode_leafletderives the groups from the rows it encodes, so every path that changes rows recomputes them: the full build, the incremental merge, leaflet splits and erasure.LiveEdges::Legacy, so a reader can tell a legacy leaflet from an empty one.fast_lead_walk). The whole-graph, per-predicate and live-NumBig walks each had their own copy of the boundary dedup, and they treated a leaflet withoutlead_group_countthree different ways. They now share one walk with a single rule: add the counts, and subtract one where a leaflet's first group is the previous leaflet's last.MIN/MAXread the group of the first or last row. The numeric path reads only the predicate's first or last leaflet.post_o_key_bounds, as the batched join already does.Erased::NeedsRebuild.o_type_const. The NumBig classifier skips a leaflet whose rows all have one other type.Behaviour changes
lead_group_countnow sends every walk to the general pipeline. The whole-graph walk used to skip it, and undercount.count_distinct_lead_groupsreturnsOption, and its callers decline onNoneinstead of counting zero.Performance
Vecper chunk partial.MIN/MAXon such indexes read leaflet payloads they did not read before. This cost is not measured.Tests
it_leaflet_live_edges(new, its own binary). Every case puts a retraction at the leaflet boundaries, then compares the fast path and the general pipeline on the same index against an unindexed ledger, with the lane's routing stamp pinned.SUM(STRLEN(GROUP_CONCAT)).MIN,MAXand the range semijoin.tests/fixtures/leaflet-edges-4.2.6, built by v4.2.6 with tiny leaflets. Its README records how it was built.SUM(STRLEN(GROUP_CONCAT)),MINandMAXon a full-built and on an incremental-built v4 index, serial and parallel.MIN/MAX);MIN/MAX);o_key;docs/design/index-format.mdanddocs/design/performance.mddescribe routing keys and live groups.