Skip to content

perf(index)!: front-code subject reverse leaves - #2436

Merged
bplatz merged 10 commits into
nextfrom
perf/front-coded-subject-leaves
Nov 21, 2026
Merged

bplatz merged 10 commits into
nextfrom
perf/front-coded-subject-leaves

Conversation

@bplatz

@bplatz bplatz commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Subject reverse leaves are now written in a front-coded layout, DLR2. Each key stores only the bytes it does not share with the key before it, restarting every 16 entries. Ids are varints with the key's namespace code XORed out of the top 16 bits, which leaves a subject's local id. On BSBM 100M the subject reverse tree shrinks from 448 MB to 90 MB. Cold lookups of constant IRIs, which fetch a whole leaf, get 2–3× faster. Import, indexing and warm queries that name subjects the index holds are level. Lookups of subjects it doesn't hold cost a few percent more (see Measurements).

Partially addresses #2428: cold Q11/Q12 now fetch about half as much data. The rest of that gap is the blob mapping the issue describes.

What changes

  • Only subject reverse trees are front-coded. String and triple-term trees stay DLR1. On BSBM, front coding the string tree measured 1.03×: review text shares almost no prefixes, and long keys would make the in-block scan expensive.
  • Readers accept either layout, leaf by leaf. Existing indexes keep working. An incremental pass rewrites only the leaves it touches, so a tree can mix the two layouts.
  • Leaves are cut where a DLR1 leaf would reach the target size. A leaf holds the same entries as before, and an incremental pass rewrites the same number of entries per touched leaf. Each leaf simply comes out smaller.
  • A lookup does not rebuild keys. It binary-searches the restart keys, then walks at most 15 entries, comparing only the bytes each entry adds.
  • Fenced range reads apply to DLR1 leaves only. These are the reads used for encrypted local stores. A front-coded leaf is read whole, once: the read made to fence it is kept for the lookup.
  • Every subject-tree writer uses the new layout, taken from LeafFormat::for_dict: the full rebuild (upload_dicts), incremental updates and removals (dicts.rs), and import extension (dict_extend).
  • A subject lookup that misses doesn't search for the same key again. After a lookup by a Sid's parts misses, the IRI is looked up under every other key it could be stored under, but not the split that just missed (find_subject_id_after_parts_miss). The staging absence check, the scan's filter and its last-chance probe, and subject_ref_to_s_id use it. In subject leaf lookups: an absent subject in a pattern takes 1 instead of 4, a new subject staged by an upsert 1 instead of 2, and an absent VALUES subject 2 instead of 5.
  • API change: ReverseLeaf::iter, scan_range, first_key and last_key return Cow keys. A front-coded leaf's keys come back owned. ReverseLeaf::fences returns Option<Fences>, None for a leaf a fenced scan can't read.
  • New criterion bench (fluree-db-binary-index/benches/reverse_leaf.rs): probe and leaf-rewrite cost for both layouts, over two key shapes.

Measurements

BSBM 100M. The baseline is next plus the other open perf PRs, including #2422, so subject keys are short local names. The comparison is that baseline with and without this change, run on the same box in the same session, with builds swapped between boxes for the query runs.

Without With
Subject reverse tree 448 MB, 186 leaves 90 MB, 186 leaves (4.97×)
Ledger 12.83 GB 12.47 GB
Import 181.1 s 180.6 s
Full reindex 196.6 s 197.4 s
Incremental, 30k new subjects (commit ack / new root) 1.09–0.42 s / 0.49–7.1 s 1.10–0.39 s / 0.49–7.1 s
Fully cold mix 4,860 QMpH 6,910 QMpH (+42%)
Cold Q9 / Q11 / Q12 34 / 124 / 126 ms 17 / 50 / 45 ms
Single client, warm 51,580 QMpH 51,150 QMpH (every query within 0.1 ms)
128 clients, warm 2.96M QMpH 3.01M QMpH
  • Isolated cold Q11 and Q12, from the same preload:

    • Q11 fetches 0.82 MB instead of 1.56 MB and runs in 11.5 ms instead of 19.6 ms.
    • Q12 fetches 1.59 MB instead of 2.30 MB and runs in 20.5 ms instead of 27.3 ms.
  • Microbenchmark, one leaf:

    Key shape Leaf size Lookup, per probe Leaf rewrite
    Short local names 2.40 → 0.82 MB ~140 → ~360 ns 1.6× slower
    Full IRIs under the overflow namespace 2.18 → 0.37 MB ~165 → ~360 ns 2.2× slower

    The second shape is what most subjects look like on next without feat(core)!: a new ledger files an IRI ending in a delimiter under the namespace before it #2422. Neither the probe cost nor the rewrite cost shows up in whole-query or indexing times above.

  • Lookups of subjects the index doesn't hold cost more. Measured in review against next, with the repeated lookup removed on both sides: new-subject upserts +3.1% (+2.8% to +6.0% over four runs on two boxes), a warm VALUES of 2,000 absent IRIs +9.9%, and hit-heavy lanes on a small tree +1–3%. On a 1.65M-subject ledger, hit-heavy queries were 4–6% faster. The warm rows above are BSBM's queries, which name subjects that exist. The same build writing DLR1 subject leaves came in at +1.6% on the upsert lane, so the leaf format accounts for the gap above that. Tightening the leaf's probe halved its cost in the microbenchmark but did not move the upsert lane, so where that lane's cost sits is not established.

  • Cold Q2 was 20.4 ms against 15.8 ms over two runs. The cause is not established. It needs more runs before it reads as a change.

Compatibility

An index this build writes holds DLR2 subject leaves, which earlier builds refuse as an invalid leaf magic. This build reads indexes earlier builds wrote. The change is one-way within the 5.0 alphas: v5.0.0-alpha.2 and alpha.3 open an index this build wrote and fail at the first subject lookup, in a query or a write, and a full reindex on the earlier build recovers. docs/reference/compatibility.md records this, with the API changes. The mixed case was checked end to end: this build ran on a ledger an earlier build had indexed, then wrote new leaves next to the old ones through writes and an incremental index pass. All correctness checks passed, with no answer differences against the earlier build.

Subject reverse leaves are written in a new front-coded layout, DLR2:
each key stores only the bytes it does not share with the key before
it, restarting every 16 entries, and ids are varints with the key's
namespace code XORed out of the top 16 bits, which leaves a subject's
local id. String and triple-term trees stay DLR1, since their keys share
too little to pay for the scan front coding adds to a lookup.

Readers take either layout leaf by leaf, so existing indexes keep
working and a tree an incremental pass has partly rewritten may mix
them. Leaves are cut where a DLR1 leaf would reach the target size, so
an incremental pass rewrites as many entries per touched leaf as before
and each leaf comes out smaller. A lookup binary-searches the restart
keys and walks at most one restart interval without rebuilding keys.
Fenced range reads apply to DLR1 leaves only; a front-coded leaf is read
whole.

The full rebuild, incremental updates and import extension all write
subject trees front-coded. A criterion bench compares probe and
leaf-rewrite cost for both layouts.

BREAKING CHANGE: an index this build writes has DLR2 subject leaves,
which earlier builds refuse as an invalid leaf magic. This build reads
indexes earlier builds wrote.
@bplatz bplatz added breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches performance Performance improvement (release notes: Performance) labels Nov 18, 2026
@bplatz
bplatz requested a review from a team November 18, 2026 00:00
@bplatz
bplatz added this pull request to stack #2446 November 18, 2026 15:40

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@bplatz this is really nice, and at a design level no pushback from me: restart-point front coding is the right shape for subject keys, and cutting leaves where a DLR1 leaf would end keeps the cold win without growing incremental rewrites. Claude reproduced it against next on a box: the subject tree is 3.7× smaller and cold lookups read 19–49% fewer bytes.

My reading is that this makes the v5 index one-way within the alphas (alpha.2/alpha.3 fail at the first subject lookup; going back means a reindex). Fine for an alpha I think, but I'd like your confirmation, plus a compatibility-notes line.

The one thing I'd want in before merging: the miss paths look the same key up twice and each lookup now costs more, so new-subject writes land ~7% slower. Dropping the repeat (Claude measured it) gets them back to today's next; the ~3–6% left against next with the same fix I think the size and cold wins pay for. Details below.

Full review below:


✅ Approving to unblock: please get the repeated subject lookup dropped before merging. The format and the leaf-cutting choice are right, and the box A/B backs the size and cold claims; the one must is a few lines outside this diff, and the warm cost that remains after it is a trade I'd take (numbers inline).

Before merging:

  1. fluree-db-binary-index/src/dict/reverse_leaf.rs:514: skip the canonical lookup that repeats a by-parts miss (sid_iri.rs, stage.rs, fast_path_common.rs, binary_scan.rs); new-subject upserts are +6.7% without it.

Notes:

  • The body's "warm query speed is level" holds for queries that name subjects that exist; lookups that miss (a write's new subjects, absent IRIs) pay the new leaves' cost even with the fix above. Worth a line in the body so the trade is on the record.
  • Class across the v5 format PRs: an earlier v5 build opens a ledger this PR indexed and refuses the changed artifact only at first use (#2436's DLR2 leaves; #2454's FPK1 v2 packs look the same), while #2445's DTB2 branch is decoded at load and so is refused there; v5.0.0-alpha.2 and alpha.3 accept root versions 2 and 4 (format/index_root.rs:1085), so they open a ledger this PR indexed. Claude checked it with next standing in for the earlier build: on an index this PR wrote, a query fails with build_filter: reverse leaf: invalid magic and an insert with populate_dict_novelty_safe: reverse leaf: invalid magic, and a full reindex on the earlier build recovers. One bump of ROOT_V6_VERSION_V5 for the alpha that ships these would make an earlier alpha refuse at load instead, as alpha.1 already refuses a version-4 root. Not for this PR, which is right as it is; it's a call for whoever cuts that alpha.
  • #2445 is stacked on this PR, so this merges first. git merge-tree of this head against origin/next, #2454 and #2477 is clean, and the merged tree passes the fluree-db-binary-index and fluree-db-indexer suites (--all-features, 1,005 tests) and clippy with -D warnings.
  • Mixed trees hold up end to end: on an index next wrote, this build's incremental pass for 30k new subjects wrote 12 DLR2 subject leaves next to the plain ones, and five queries (old and new subjects) answered exactly as next did on its own extended copy.
Adherence: Patterns ✔ · Performance ⚠️ · Deployment targets ✔ · Testing ✔ · Conventions ⚠️ · verification
  • Patterns/abstractions: ✔ Extends ReverseLeaf with a per-leaf layout behind one LeafFormat decision and threads it through every writer; one writer still decides the format itself (upload_dicts.rs:447, nit).
  • Performance (speed first, memory second): ⚠️ Subject tree 3.7× smaller (48.3 → 12.9 MB, same 20 leaves), ledger −12.7%, cold reads −19% to −22% (one IRI) and −49% (2,000 IRIs), incremental index −11%, import and full reindex level. As shipped, warm misses regress (+6.7% new-subject upserts, +14.3% absent IRIs); the repeated-lookup fix brings upserts back to today's next. Against next with the same fix, the leaf format itself costs +3–6% on that lane, +9.9% on absent IRIs and +1–3% on hit-heavy small-tree lanes, while hit-heavy queries on a larger tree are 4–6% faster. Recommend accepting that residual.
  • Deployment targets: ✔ Shared format code for the embedded library, server and wasm32 (residency loads go through ReverseLeaf::from_bytes); CI's wasm32 and wasm-smoke passed at this head. Encrypted local stores pay the fenced double read (optional above).
  • Testing: ✔ A differential reader test plus one per writer path; all nine new tests ran in CI's test job at 170d47026 (17,828 passed). Six mutations Claude ran were each caught. The fenced test counts only get_local reads (optional above).
  • Conventions: ⚠️ Thorough commit message and labels; the format doc lacks the DLR2 wire layout and versioning line, and there's no compatibility note (optional above).

Verified at 170d47026: Claude merged it into origin/next (c23fd2246) on a box, ran the binary-index and indexer suites and clippy there, ran six mutation checks and a fenced-read probe with two candidate fixes, swept the restart interval, and ran an A/B against origin/next (fat-LTO builds): the PR's microbench, a BSBM-shaped import of 1.65M subjects / 9.65M triples (size, import, reindex, a 30k-subject incremental pass, cold and warm queries), and transact_upsert_replace and query_hot_point_lookup at medium scale, plus the same with the repeated lookup removed. On a second box: a tightened DLR2 lookup and cached restart keys (microbench and upsert lane), and a control build writing DLR1 subject leaves.

Approving so you can merge once the repeated lookup is gone; the rest are small and I'd fold them in while you're there, but they don't hold this up.


/// Exact lookup within the key's restart block, without rebuilding keys:
/// `matched` tracks how much of `target` the previous key shares.
fn fc_lookup(&self, fc: FrontCoded, target: &[u8]) -> Option<u64> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocking (perf): new-subject writes and absent-IRI lookups get slower, partly because every miss path looks the same key up twice and partly because of the new leaves themselves. Claude measured it on a box against origin/next (fat-LTO builds, interleaved runs):

next this PR next + fix below this PR + fix below
transact_upsert_replace/new_subjects (medium) 47.00 ms 50.16 ms (+6.7%) 45.44 ms 46.83 ms
warm VALUES of 2,000 absent IRIs 9.02 ms 10.31 ms (+14.3%) 8.50 ms 9.34 ms

The first part is the must. After find_subject_id_by_parts misses, each miss path decodes the Sid and calls find_subject_id(iri), and under canonical encoding that IRI's canonical split is the key that just missed: sid_to_store_s_id (fluree-db-query/src/sid_iri.rs:14-19), the absence check in staging (fluree-db-transact/src/stage.rs:3509-3533), subject_ref_to_s_id (fluree-db-query/src/fast_path_common.rs:3802-3811), and binary_scan.rs:1343-1350, which repeats it once more. The repeat predates this PR, but each lookup now costs more (about 380 ns a probe into a cache-hot front-coded leaf against 216 ns for DLR1, your reverse_leaf bench on the box), so this is the PR to drop it in. Skipping the canonical lookup when its split is the parts that just missed, and keeping the full-IRI fallback, gives the last two columns (Claude wired it at sid_iri.rs and stage.rs only; answers were identical in all four builds):

// BinaryIndexStore: resolve after a by-parts miss without retrying that key.
pub fn find_subject_id_after_parts_miss(&self, ns_code: u16, name: &str, iri: &str) -> io::Result<Option<u64>> {
    let (prefix, suffix) = canonical_split(iri, self.ns_split_mode);
    if let Some(&code) = self.dicts.namespace_reverse.get(prefix) {
        if !(code == ns_code && suffix == name) {
            if let Some(s_id) = self.reverse_lookup_subject_key(code, suffix.as_bytes())? {
                return Ok(Some(s_id));
            }
        }
    }
    Ok(self.find_full_iri_subject_fallback(iri)?.map(|(_, s_id)| s_id))
}

The second part is the trade, and I'd take it. Compared fairly, against next with the same fix, the new leaves still cost +3.1% on new_subjects (+2.8% to +6.0% across four runs on two boxes), +1.4–3% on default_indexed, and +9.9% on the absent IRIs. It is the leaf format: the same build writing DLR1 subject leaves comes in at +1.6% on new_subjects and +0.8% on new_subjects_novelty_heavy. Claude tried the cheap levers. A restart interval of 8 buys back only 4–8% of the probe. Skipping the id varint until a match, with a one-byte varint fast path (or, separately, caching the decoded restart keys), halves the per-probe overhead in the microbench (+163 → +80 ns over DLR1), but it didn't move the upsert lane (+6.0% vs +6.5% in the same run), so that lane's cost sits somewhere the microbench doesn't model. Against that: a 3.7× smaller subject tree, 19–49% fewer bytes on cold lookups, an 11% faster incremental pass, and on a 1.65M-subject ledger a 30k-subject insert is level and hit-heavy queries are 4–6% faster. I'd just say so in the body, since "warm query speed is level" holds for BSBM's queries, which name subjects that exist, and not for lookups that miss. If you have time to profile the upsert lane's measured region, that's where the rest is.

Commenting here because sid_iri.rs and stage.rs aren't in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 0503839. It also covers the scan's last-chance probe in BinaryScanOperator::open, which repeated the key once more: an absent subject in a pattern is now 1 leaf lookup (4 before), a staged new subject 1 (2), an absent VALUES subject 2 (5; the join's lookup, then the scan's).

.map(|e| (e.key.clone(), e.id))
.collect();
assert_eq!(scanned, want);
assert_eq!(cs.whole_reads.load(AtomicOrdering::SeqCst), 1, "read whole");

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.

Optional: under a fencing reader, a front-coded leaf is read twice on first touch, and this test can't see it. FencedLeaf::open (reader.rs:42-50) reads the whole leaf by range, sees is_sequential() == false, drops the bytes and caches None; reverse_lookup then reads the leaf whole again through load_leaf. The test counts only whole_reads (get_local), not the ranged read, so "read whole, once" passes either way.

Claude's probe on a box (same 500 entries as this test): leaf_len=13080 whole_reads=1 ranged_reads=[0..13080]. It isn't a regression against next, since fencing a DLR1 leaf read the whole 2.4 MB leaf too, but on an encrypted store it gives back about half of the cold win this PR is after (two reads of a 0.8 MB leaf where one would do).

The fix Claude ran there: when open declines to fence, hand the bytes it already holds to the dict-leaf cache instead of dropping them. That gave whole_reads=0 and one ranged read, and the dict:: suite passed apart from the two asserts that encode whole_reads == 1 (this one and a_leaf_out_of_layout_is_read_whole, whose double read predates this PR). Those would become "one read in total" (whole_reads + ranged reads).

// FencedLeaf::open returns io::Result<Result<Self, Vec<u8>>>, Err(bytes) when it won't fence.
match FencedLeaf::open(source, self.fence_spacing)? {
    Ok(leaf) => Ok(Some(Arc::new(leaf))),
    Err(whole) => {
        cache.insert_dict_leaf(xxhash_rust::xxh3::xxh3_128(address.as_bytes()), whole.into());
        Ok(None)
    }
}

Peeking the 4-byte magic first also works for DLR2 (ranged_bytes=4), but it adds a read to every DLR1 open and breaks a_fenced_scan_reads_one_stretch_after_opening. I know this is non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog. Commenting here because reader.rs:42-50 isn't in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 58faed7

/// [`Self::is_sequential`].
pub fn fences(&self, spacing: usize) -> Fences {
debug_assert!(
self.front_coded.is_none(),

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.

Optional. fences() is pub, and the only thing stopping it from reading a front-coded leaf's restart table as a per-entry offset table is this debug_assert!. In a release build that's garbage fences or a slice panic. Today its one caller (FencedLeaf::open) checks is_sequential() first, so it's latent, but we may want fences() to return Option<Fences> (None for DLR2) and let open use that in place of the separate check, so the misuse can't compile into something that runs. Minor, but if you agree I'd rather see it in this PR than 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 f9fc89d

if cursor.key.as_slice() >= end_key {
break;
}
results.push((Cow::Owned(cursor.key.clone()), id));

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.

Nit. For a front-coded leaf scan_range already returns owned keys, and reverse_range_scan (reader.rs:654) then copies each one again with key.to_vec(). key.into_owned() there makes it one allocation for DLR2 and leaves DLR1 as it was. (The only subject caller, find_subjects_by_prefix, then throws the keys away.) Commenting here because reader.rs:654 isn't in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 989fda2


let mut leaf_offsets: Vec<u32> = Vec::new();
let mut leaf_data: Vec<u8> = Vec::new();
let mut writer = FrontCodedLeafWriter::new(true);

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.

Nit. This is the one writer that decides the subject format itself (FrontCodedLeafWriter::new(true)); the incremental, removal and import paths ask LeafFormat::for_dict. If for_dict ever changes, the full rebuild would quietly write one layout and the other paths another. Deriving the writer from LeafFormat::for_dict(DictKind::SubjectReverse) keeps it one decision. Minor, but cheap to fold in now.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in eb5f5a3

- **Column block**: a separately compressed single-column section inside a leaflet.
- **History sidecar**: a separate CAS object holding a leaf's time-travel transition log.
- **Dictionary tree**: a `DTB1` branch + `DLR1` leaves, holding the reverse (value → ID) direction for large keyspaces (subjects/strings).
- **Dictionary tree**: a `DTB1` branch + `DLR1` leaves, holding the reverse (value → ID) direction for large keyspaces (subjects/strings). Subject leaves are written front-coded (`DLR2`): each key stores only what it does not share with the one before, restarting every 16 entries, and ids are varints of the local id. Readers take either layout, so a tree may mix them.

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.

Optional (docs). The glossary and root list mention DLR2, but the wire-layout section "Reverse dict leaf (DLR1)" (line 589) has no DLR2 block, "Large dictionaries" (line 452) still says reverse trees map to DLR1 leaves, and "Versioning notes" (line 632) lists only DLR1. The layout already lives in the module doc (reverse_leaf.rs:17-35), so it's mostly a copy. A short docs/reference/compatibility.md entry would also carry the alpha-rollback note below and the ReverseLeaf Cow return types for Rust embedders, the way #2422's entry does. Commenting here because those lines aren't in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 84b4299

/// misses on both sides, keys before and after the leaf — for both id
/// modes and for entry counts on and off a restart boundary.
#[test]
fn front_coded_leaves_agree_with_plain_leaves() {

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.

Praise. This differential test is the right oracle for the format: Claude mutation-checked block_for's bound, the in-block ordering test, the early exit on a smaller shared prefix and scan_range's start block on a box, and each mutation failed it (the early-exit one by a real false positive at 1,000 entries). Worth keeping as the gate for any later change to the walk.

A bound subject is looked up in the subject dictionary by its Sid's
parts, and on a miss by its IRI. Under canonical encoding the IRI's
split is usually the parts that just missed, so the IRI lookup searched
the same leaf for the same key again. That followed every miss: once
per new subject a write stages, and up to three times per absent IRI a
query scans (the scan's filter retried it, retried it again through the
snapshot, then once more before falling back to novelty). With
front-coded subject leaves each search costs more, so the repeats
showed up as slower new-subject writes and slower absent-IRI lookups.

BinaryIndexStore::find_subject_id_after_parts_miss tries every key the
IRI could be stored under except the one that missed: its canonical
split, then the full-IRI namespaces. The staging absence check, the
scan's filter, its last-chance probe and subject_ref_to_s_id use it.
The scan's last-chance probe makes no lookup at all for a subject bound
as an IRI, which its filter has already looked up whole.

A lookup error on the parts now reads as present in the staging
absence check directly, as that check documents, instead of falling
through to the IRI lookup.

Measured in subject leaf lookups: an absent subject in a pattern takes
1 instead of 4, a new subject staged by an upsert 1 instead of 2, and
an absent VALUES subject 2 instead of 5 (the join's lookup, then the
scan's, which is not told the join's lookup missed).
Under a fencing reader (an encrypted local store), the first lookup in
a reverse leaf reads it whole by range to fence it. A leaf whose entries
don't lie one after another in key order, which every front-coded DLR2
leaf is, isn't fenced: FencedLeaf::open dropped the bytes it had just
read, and the lookup then read the leaf whole a second time through the
dict-leaf cache.

open now hands those bytes back, and the reader puts them in the
dict-leaf cache under the key a whole read uses, so the lookup reads the
leaf once. The two tests that pinned "read whole" counted only whole
reads, which the ranged read escaped; they now check one read in total,
covering the whole leaf.
…fence

fences() is public, and only a debug_assert stopped it from reading a
front-coded leaf's restart table as a per-entry offset table: in a
release build that gives garbage fences or a slice panic. Its one caller
checked is_sequential() first, so this was latent.

fences() now returns Option<Fences>, None unless the leaf's entries lie
one after another in key order (is_sequential), and FencedLeaf::open
takes that answer in place of its own check.
ReverseLeaf::scan_range returns Cow keys: borrowed from a DLR1 leaf,
owned for a front-coded one, whose keys are rebuilt as it walks.
reverse_range_scan copied every key with to_vec(), so a front-coded
leaf's keys were allocated twice. into_owned() moves an owned key and
copies a borrowed one, as before.
The full rebuild was the one subject-tree writer that chose the leaf
format itself (FrontCodedLeafWriter::new(true)); the incremental,
removal and import paths ask LeafFormat::for_dict. If for_dict changed,
the rebuild would quietly write one layout and the other paths another.

LeafFormat::writer returns a LeafWriter that streams sorted entries
into leaves of that format, plain or front-coded, and the rebuild takes
its writer from LeafFormat::for_dict(DictKind::SubjectReverse). The
writer test now covers every format, checking each leaf it cuts is the
one LeafFormat::encode writes for its entries alone.
The format doc named DLR2 in its glossary and root list but still
described reverse trees as DLR1 leaves, had no DLR2 wire layout, and
listed only DLR1 in its versioning notes. It now has the DLR2 layout
beside DLR1's, says which trees use which layout and that a subject tree
can mix them, and lists both magics.

The compatibility notes gain an entry for the change: an index this
release writes is refused by v5.0.0-alpha.2 and alpha.3 at its first
subject lookup, and going back needs a reindex there. It also records
the warm cost of looking up subjects the index doesn't hold, and the
ReverseLeaf API changes for Rust embedders.
@bplatz

bplatz commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

From the review summary:

  • Before merging: skip the canonical lookup that repeats a by-parts miss

    Addressed in 0503839

  • "warm query speed is level" holds for queries that name subjects that exist; worth a line in the body

    Addressed in the PR body: the summary and a new Measurements bullet with your numbers.

  • This makes the v5 index one-way within the alphas; I'd like your confirmation, plus a compatibility-notes line

    Confirmed: alpha.2 and alpha.3 fail at the first subject lookup, and a reindex on the earlier build recovers. Addressed in 84b4299, and in the body's Compatibility section.

@bplatz

bplatz commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

One bump of ROOT_V6_VERSION_V5 for the alpha that ships these would make an earlier alpha refuse at load instead

The 5.0 alphas aren't backward compatible with each other, so there's no bump: an earlier alpha that opens a newer alpha's index can fail at first use, and going back means a reindex on the earlier build, as the compatibility note says.

@bplatz
bplatz merged commit a24c33b into next Nov 21, 2026
24 checks passed
@bplatz
bplatz deleted the perf/front-coded-subject-leaves branch November 21, 2026 12:29
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 breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants