Repository navigation
perf(index)!: key long strings by prefix and hash - #2445
Conversation
5c60ab4 to
5f06f45
Compare
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is carefully built, and I'm on board with the design: the prefix + hash key keeps every prefix up to 48 bytes in one key range, and the cap bounds what a longer prefix has to check. Claude's boundary, split-UTF-8 and seeded import/incremental/erase probes all held.
Two things I'd want before it merges. Erasure leaves a listed group's first 48 bytes in the DTB2 branch, which Claude reproduced end to end through a purge. And speed isn't level on a string-heavy ledger: full reindex +8.7%, incremental +14.8%, and the first query after a commit over unindexed long strings +21.8%. Directions that I think get both are below.
Full review below:
Approving to unblock you The key scheme and the cap are the right shape, and the lookups and prefix scans held up under everything Claude threw at them. Two things need to land first: an erasure residue this PR introduces, and the speed it costs on string-heavy writes and on the first query after a commit, which the body's "level" doesn't show.
Before merging:
fluree-db-indexer/src/build/dicts.rs:195: prune listed groups on the erase path, and add a regression test.fluree-db-binary-index/src/dict/reader.rs:487: recover the +21.8% on the first query after a commit over unindexed long strings.fluree-db-indexer/src/build/upload_dicts.rs:580: recover the string-tree build cost (reindex +8.7%, incremental +14.8% on a string-heavy ledger), with a before/after.
Notes:
- The erasure residue is one more instance of a class this subsystem keeps meeting: a structure built from values that the leaf-by-leaf purge doesn't recompute keeps erased content. Earlier ones were the subject dictionary's IRIs (
87a66786c), arena values (29099eaf0) and search-index leftovers (e133f3eb4). Each time the scan only caught it once it was taught that structure, because it asks each structure through its own lookup (find_string_idhere). The class fix would be a scan that covers every artifact holding value bytes, so the next one blocks the purge instead of passing it. That isn't for this PR; the point fix above is right here. - Here's the full A/B (c7i.4xlarge, release profile, base #2436
170d47026, 8 interleaved runs, medians). Ledger after import −25.6% (1,117.7 MB → 832.1 MB). String tree alone −65% (437.9 MB → 152.2 MB, microbench). Import −8.0%. Peak RSS −7.1%. Warm point lookups by value +2–3% once normalised by each run's control query (long, long miss, short and listed-URL lookups, every head run above every base run). TheSTRSTARTSrows were level, but they took the generic filter lane rather than the prefix pushdown, so they don't timefind_strings_by_prefix. It'd be worth adding numbers like these to the body's measurements, since on BSBM they mostly don't show. - This doesn't stand alone without #2436: the hashed string leaves are written with its
FrontCodedLeafWriterandLeafFormat::FrontCoded, so #2436 lands first.git merge-treeagainst #2454 is clean (tree3ebad043d). - Listed groups live in the branch at 49 bytes each, so the branch is decoded on every open and rewritten on every incremental pass. That's nothing at BSBM's zero groups, but data with many high-cardinality 48-byte prefixes (per-entity templated text, per-user JSON) would grow it. A sentence on that scaling term in
docs/design/index-format.mdwould help. - The equal-key refusal in
merge_leaf_entrieslooks right to me: it's aStorageWrite, which is retryable, so an incremental pass that hits it falls back to a full rebuild (fluree-db-indexer/src/lib.rs:275-282) rather than wedging the ledger. - Same rollback shape as #2436: an earlier v5 build decodes this tree's
DTB2branch at store load and refuses it as an invalid magic. One root-version bump for the alpha that ships these format changes (#2436, this PR, #2454) would make earlier builds refuse the root up front instead. - On an encrypted local store, string leaves used to be read through fences. As front-coded leaves they're read whole, and twice on first touch until #2436's
FencedLeaf::openhand-off lands (measured on subject leaves in #2436's review). Worth confirming string lookups there once that fix is in.
Adherence: Patterns ✔ · Performance ✖ · Deployment targets ✔ · Testing ⚠️ · Conventions ✔ · verification
- Patterns/abstractions: ✔ The scheme belongs to the tree and rides the existing
DictBranch/DictTreeReadermachinery; callers keep passing values. One gap: three writers maintain the group list and the erase path doesn't. - Performance (speed first, memory second): ✖ CRITICAL. Full reindex +8.7%, incremental pass +14.8%, first query after a commit over 50k unindexed long strings +21.8%, warm point lookups +2–3%. Against that: ledger −25.6%, import −8.0%, RSS −7.1%.
- Deployment targets: ✔ Shared code that every host runs. It adds no background task or process-wide state, the CI
wasm32job is green on this head, and memory stays bounded by the cap. - Testing:
⚠️ CI's full--all-featuresnextest ran on this head (17,842 passed, new tests present by name). Four import and erase mutations survive the PR's tests (comment above). - Conventions: ✔ Self-describing
perf(index)!subject, a thorough body with aBREAKING CHANGEfooter, anddocs/design/index-format.mdupdated. fmt and clippy are green in CI.
Verified at 5f06f45f2: CI run 44352827847 green (test, clippy, fmt, wasm32). Claude ran these on a box: boundary/UTF-8/32-vs-33 strings through STRSTARTS, REGEX ^, SUM(STRSTARTS) and find_strings_by_prefix after import, incremental and reindex (7,511 queries, all correct); a seeded import/incremental/erase sequence (168 states, 91,931 prefix checks, all correct); the erasure repro (fails at 5f06f45f2, passes at 170d47026); 8 mutations (4 caught by the PR's tests, all 8 by the probes); and the A/B above.
Just be sure the erasure fix is in before this merges, and that the reindex, incremental and first-query numbers come back level or close to it. Happy to talk through any of the perf directions.
| } | ||
| }; | ||
| if scheme.reorders() { | ||
| if remove { |
There was a problem hiding this comment.
Blocking. Erasing every string of a listed group leaves that group's first 48 bytes in the string tree's DTB2 branch after the purge completes, and the purge scan reports it clean.
Leaf-by-leaf erasure removes strings through remove_strings → remove_from_reverse_tree_async (erase_dicts.rs:148-156) → this remove path, which re-keys the values but never touches the group list: remove_from_reverse_tree copies existing_branch.raw_groups into the new branch (dict/incremental.rs:476-477), and :282 here sets them back. The group list is the one place in the index that holds a value's bytes outside its key, so nothing on the remove path prunes it. The purge scan asks the tree through find_string_id (purge/scan.rs:229), which answers by key, so it can't see the list either.
Claude reproduced it end to end with the erasure suite's own helpers (it_retention_erasure.rs): 40 values for one subject, each starting "Patient Jane Q. Example, DOB 1980-01-01, MRN 4417: …", a full reindex (so the group is listed), erase_occurrences for all 40, an incremental build, then a purge (purged: 1, leafwise: 1). inspect_purge reports clean, yet files_holding(dir, "Jane Q. Example, DOB 1980") finds exactly one file: the current string reverse branch (DTB2, 217 bytes). The same probe on #2436's head (170d47026) finds none. docs/transactions/permanent-erasure.md says the purge checks dictionaries for erased values, and the IRI note there is the only documented exception.
Minimally, on the remove path, after the leaves are rewritten, drop each listed group that no remaining key starts with (a range check of [prefix, prefix_end(prefix)) on the rewritten tree answers it), and clear hashed on a listed group that has no hashed keys left. A regression test can take the probe's shape: erase every string of a listed group and assert files_holding comes back empty. If you agree, it'd also be worth having the purge scan check the branch's listed groups against erased strings that no surviving occurrence uses, so a residue like this blocks the purge instead of passing it.
Commenting here because fluree-db-binary-index/src/dict/incremental.rs:477 and fluree-db-indexer/src/build/erase_dicts.rs:149 carry it too; this is the remove path's entry.
There was a problem hiding this comment.
Addressed in 13fe50d, with the erasure regression test in your probe's shape. I left the purge scan as it is: the removal now prunes the group, so the residue can't arise, and a scan check for it couldn't be exercised end to end.
|
|
||
| /// Reverse lookup: find the ID of `value`, under each key the tree may | ||
| /// hold it by. | ||
| pub fn reverse_lookup(&self, value: &[u8]) -> io::Result<Option<u64>> { |
There was a problem hiding this comment.
Blocking (CRITICAL, performance). The first query after a commit that scans unindexed long strings got 21.8% slower: every novelty string's persisted lookup is a miss by construction, and that miss now costs a SHA-256 and a front-coded probe.
Overlay translation calls DictOverlay::assign_string_id (fluree-db-query/src/dict_overlay.rs:298-312) per novelty flake, which tries the persisted tree first (find_string_id → reverse_lookup here → lookup_keys, which hashes any value over 81 bytes) and only then DictNovelty. A string DictNovelty holds wasn't in the persisted tree when it was staged, so for those the hash and the probe buy nothing. ObjectBinding::string_id (object_binding.rs:491-497) has the same order.
Claude measured it on a c7i.4xlarge, shipped release profile, #2436's head as the base, 8 interleaved runs (ABBA then BAAB): 1M imported subjects, 50,000 unindexed ex:note strings of about 250 bytes, then COUNT over them with FILTER(STRLEN(?t) > 10), timed after a one-triple commit each time so the translation cache misses. p50 109.5 ms → 133.3 ms (all four head runs slower than all four base runs), about 0.48 µs more per novelty string. SHA-256 alone runs at 879 MB/s on 256-byte inputs on that box (openssl speed -evp sha256), so a bit over half of that is the hash. The same query on an unchanged view is level (+2.6%, overlapping).
The direction I think gets both: look a string up in DictNovelty before the persisted tree in those two places, which skips the hash and the probe for every novelty string. I'm not positive that's safe across an index adoption (whether a string can sit in DictNovelty under one id and in the new tree under another). You'd know better than me, so if it isn't, a per-epoch memo of persisted misses would do it.
Commenting here because fluree-db-query/src/dict_overlay.rs is not in this diff.
There was a problem hiding this comment.
Addressed in 28d0ab9. It's safe across an index install: DictNovelty is rebuilt from the misses when an index is loaded and retires what the indexed commits introduced when one is installed live, so it never holds a string the tree does. The same order now applies in overlay translation (find_string_id_v3 in binary_scan.rs), which is the path the test's query took.
| let invalid = | ||
| |e: std::io::Error| IndexerError::StorageWrite(format!("string reverse keys: {e}")); | ||
|
|
||
| let mut counter = GroupCounter::new(scheme); |
There was a problem hiding this comment.
Blocking (CRITICAL, performance). Building the string tree takes about twice as long, and on a string-heavy ledger that comes through as a full reindex 8.7% slower and an incremental pass that adds 50k long strings 14.8% slower.
The full build now reads every string twice (GroupCounter here, then KeyOrder), hashes every long one, and KeyOrder copies every value-keyed entry into its own Vec (key_scheme.rs:398, :415) before the front-coded writer re-encodes it. On the incremental side the resolver's batched lookup (incremental_resolve.rs:2155-2156) and the keying in dicts.rs:225 each hash the same new string.
Claude timed build_string_reverse_tree alone on the A/B dataset's 3.2M strings (release, 5 reps on each side): 0.409–0.417 s → 0.852–0.877 s, with the tree going from 437.9 MB to 152.2 MB. In the end-to-end runs: full reindex 12.34–12.89 s → 13.62–14.04 s, and the incremental pass 0.379–0.387 s → 0.418–0.451 s. Every head run was slower than every base run on both. That microbench covers about 0.44 s of the reindex's 1.1 s, and the rest isn't attributed yet.
A few directions: KeyOrder already holds a run's hashed values, so if it held the run's (value, id) pairs (at most cap + 1) it could decide a group's listing as the run closes and drop the counting pass; skip the per-entry copy for keys that pass straight through; and carry the resolver's key to the keying so a new string is hashed once. I'd want a before/after on the reindex and the incremental pass with whichever of these lands.
Commenting here because fluree-db-indexer/src/run_index/build/incremental_resolve.rs is not in this diff.
Optional
There was a problem hiding this comment.
Addressed in 68a77d1 (full build: long strings hashed in parallel batches, no per-value copy) and a7163a2 (incremental: a group's hashed keys counted by range scan, not by decoding its leaves). I kept the counting pass: deciding a group's listing as its run closes would mean holding every middling value of the run, which isn't bounded. I didn't carry the resolver's hash to the keying, which would thread it through four layers. The before/after A/B is still to run.
There was a problem hiding this comment.
The before/after, on an m7a.4xlarge (base next at the #2436 merge, head e12993a, 1M subjects with ~250-byte notes plus 50k unindexed ones, 6 interleaved rounds per variant): full reindex 8,692 → 8,601 ms; incremental pass 1,857 → 1,064 ms with the new notes spread over the tree, and 610 → 618 ms (+1.3%) with them sorting together. That last case was +15.7% before e12993a; profiled, each new long string was hashed three times (resolver prewarm, resolver lookup, tree update) and counting its group cost a copy, a map insert and two binary searches. It's hashed once now, and groups are counted in one walk. Full table in the body.
| } | ||
| } | ||
|
|
||
| fn close(&mut self) { |
There was a problem hiding this comment.
Optional (testing). This is more of a coverage note than a correctness one, since Claude's probes found the import and erase bookkeeping right. The PR's own tests don't pin four parts of it, though.
Claude ran a mutation check against the PR's tests plus a set of probes. The PR's tests catch the mutations in prefix_ranges, lookup_keys, GroupPlan::fill and the store's prefix check. They pass with any of these broken: dropping listed_hashed (:637), ignoring unseen in close here, assuming the hashed range was read (:514-517), or skipping the hashed key on the erase path (dicts.rs:201). Each of those makes an earlier hashed string unfindable by value, or lets an unlisted group pass the cap (37 in one run). Part of the reason is that HashedTree::remove in dict/incremental.rs:1473 re-implements the erase keying rather than calling remove_from_reverse_tree_async.
The shapes that caught them: an import that alone takes a group past the cap while the tree already hashes some of it (once with one big leaf, once with small leaves and value keys sitting between the new values and the hashed range), and a seeded sequence of imports, incremental writes and erasures over 512-byte leaves that checks the invariants after every step. I recognize this is non-blocking, but if you agree it's right I'd rather see those folded into this PR than lost in the backlog. Happy to hand over the probe code.
| /// with it, once the checked ranges' values are checked: with every | ||
| /// group hashed, with full groups keyed by value, and with full groups | ||
| /// whose earliest values kept their hashed keys. | ||
| #[test] |
There was a problem hiding this comment.
Praise. prefix_ranges_cover_exactly_the_matching_values is the right test for the crux: every prefix length on both sides of the cut, with plain, listed and listed-with-hashed groups, against brute force. Claude's version of it with the real 48/32 constants, 2-, 3- and 4-byte characters split at byte 48, and groups of exactly 32 and 33 found nothing either.
A new string reverse tree keys a string longer than 81 bytes by its first 48 bytes, a 0xFF marker and its 32-byte SHA-256, instead of by the whole string, and writes its leaves front-coded. On BSBM 100M the string tree shrinks from 4.3 GB to 532 MB. UTF-8 never holds 0xFF, so a hashed key cannot be mistaken for a value key, and every key keeps its value's first 48 bytes, so a prefix of up to 48 bytes still maps to one key range. A prefix longer than 48 bytes must check each hashed string sharing its first 48 bytes against its value, so a group of strings sharing those bytes hashes at most 32. Past that the branch lists the group and keys its new strings by value, where a prefix finds them exactly. - The scheme, its prefix length and cap, and the listed groups live in a DTB2 branch. A raw tree's branch stays byte-for-byte DTB1, so subject and term trees are unchanged. - A full build counts groups first, so a group it lists holds no hashed string. An incremental build counts a group's hashed keys in the leaves holding them before keying. An import into an existing tree lists the groups it alone takes past the cap and counts the rest as it merges past them, so a group there may reach 64. - A group listed after it began hashing keeps those keys and is flagged, so a lookup there tries the value key, then the hashed one. Every other lookup probes one key. - The tree reader keys values by its tree's scheme, so exact and batched lookups still take values. - A tree an incremental build or an import extends keeps the scheme it has, so an existing raw string tree stays raw until a full rebuild. - An incremental merge that meets an equal key under another id now errors instead of replacing the entry; under the same id it is a no-op. This applies to every reverse tree. The criterion bench gains string probes: raw keys in plain leaves, and hashed and filled groups in front-coded ones, key computation included. BREAKING CHANGE: a full build writes string reverse trees with a DTB2 branch, which earlier builds refuse.
5f06f45 to
22b2589
Compare
…riter Renaming LeafFormat::for_dict to for_tree(dict, scheme) left the full rebuild's subject tree writer calling the old name, which the subject writer took on in the same change that made it ask LeafFormat at all, so fluree-db-indexer didn't compile. It now asks for_tree(DictKind::SubjectReverse, KeyScheme::Raw), as every other subject writer does.
… rebuilds The full rebuild's string tree chose its leaf format itself (FrontCodedLeafWriter::new(false)), where the incremental and import paths ask LeafFormat::for_tree(dict, scheme): if for_tree changed, the rebuild would write one layout and the other paths another. It also flushed leaves through its own helper, a copy of the subject tree's flush. ReverseTreeWriter takes its LeafWriter from for_tree, cuts leaves where a DLR1 leaf of the same keys would reach the target size, refuses a key that doesn't sort after the last one, and uploads the branch with the tree's scheme and listed groups. Both rebuilds write through it.
Read accounting tells dictionary blobs apart by their format magic, and knew branches only as DTB1, so with FLUREE_IO_STATS on every read of a hashed string tree's DTB2 branch was counted as a generic dictblob, not a dict-branch, skewing cold-read comparisons. The label is now its own function, read_label, which counts both branch magics as dict-branch, with a test over each dictionary magic.
…-index An incremental write to a hashed string tree counts the hashed keys each group it hashes into already holds, lists a group the write would take past the cap, then keys the new values; a removal keys each value under every key a lookup would try. The indexer did this in upload_incremental_reverse_tree_core, and the HashedTree test helper repeated it, so the tests exercised their own copy. The indexer also set the new listed groups on the result after update_reverse_tree had encoded the branch, leaving its branch_bytes and branch_hash describing the old groups; only finalize_branch's re-encode kept the upload right. GroupPlan::key now lists the groups on the branch and keys the values, refusing two that share a key, so update_reverse_tree encodes the branch with the groups it carries. removal_keys gives a removal's keys. The indexer and the test helper both call them.
A hashed string tree's branch lists by prefix the groups it keys by value: the first 48 bytes of strings that passed the hashing cap. A removal copied that list forward unchanged, so erasing every string of a listed group left its prefix in each later branch, the start of the erased strings, and the purge scan, which asks the tree by value, reported it clean. remove_from_reverse_tree now stops listing each group it touched that the tree holds no key under, and clears hashed on one with no hashed key left. It decides from the leaves it read and the first and last keys of the rest: the one leaf that can span a group's range with neither in it is the leaf every key in the range routes to, which the removal reads. A group still holding any key stays listed, so its values stay findable. Tested in the tree, and end to end: forty long strings sharing their first 48 bytes, erased and purged leaf by leaf, leave the prefix in no file.
…g trees Four parts of how imports and erasures keep a hashed string tree's listed groups could be broken without any test failing: an import's note that a group it lists already held hashed keys in the leaves it read, its count of a group running into leaves it skipped, its check for a group's hashed keys in leaves it didn't read, and an erasure's removal of a value's hashed key in a group listed after it began hashing. Each left an earlier hashed string unfindable by value, or let an unlisted group pass the cap. An import that alone takes a group past the cap is now checked with the tree already hashing some of the group, once in one leaf the merge reads and once in small leaves it doesn't, past value keys of the group. A seeded run of sixty imports, incremental writes and erasures over small leaves checks after every step that each string resolves to its id, singly and batched, that erased ones don't, and that the listed groups describe the hashed keys. Each of the four breaks fails one of them.
Overlay translation gives every novelty flake's string its dictionary id, and object binding and the dictionary overlay do the same for the values they meet. Each asked the persisted string tree first and the novelty dictionary on a miss. A string the novelty dictionary holds was not in the persisted tree when it was staged, so for those the persisted lookup always missed, and in a hashed string tree a long string's lookup hashes it with SHA-256 and probes a front-coded leaf: the first query after a commit over unindexed long strings paid both for each one. The novelty dictionary holds only strings the persisted tree doesn't. It is populated against the tree, rebuilt from the misses when an index is loaded, and retires what the indexed commits introduced when one is installed live. So the order changes no answer, and find_string_id_v3, DictOverlay::assign_string_id and ObjectBinding's string lookup now ask it first. A test counts the string tree's leaf lookups over a query reading twenty novelty strings: none, where each used to take one.
…he string rebuild Building a hashed string tree in a full rebuild cost about twice what the raw tree did. Most of it is one SHA-256 per long string, which the build computed one at a time as KeyOrder met each value; KeyOrder also copied every value-keyed string into its own Vec before the leaf writer copied it again. The rebuild now takes the strings a batch at a time and hashes the batch's long ones on the rayon pool before keying them (KeyRules::key_hash, KeyOrder::push_hashed). KeyOrder is generic over how it holds a value, so the rebuild passes slices of the strings buffer it already holds, and pop_into writes each key into one reused buffer: the rebuild allocates nothing per string. Imports keep owned values.
…s leaves Before keying an incremental write to a hashed string tree, GroupPlan counts the hashed keys each group the write hashes into already holds. It did so by decoding every key of every leaf holding such a group, which for a front-coded leaf rebuilds each key, and the update then decodes the same leaves again to merge into them. GroupPlan::fill now range-scans each leaf for the group's hashed range only, a binary search over the leaf's restarts and a walk of the keys in range, and decodes each leaf's header once. GroupPlan::key takes the leaves by index to find the ones holding each range.
The format doc described string trees as DTB1 branches over DLR1 leaves everywhere but its glossary, which carried the whole scheme in one line. It now says which branch and leaf layout each reverse tree has, adds the DTB2 layout beside DTB1's with the key scheme, the cap and how each build path keeps it, notes that the branch grows with the number of listed groups, at 49 bytes each, and lists DTB2 in the versioning notes. The compatibility notes gain an entry: what the new keys change for a ledger, that an older string tree stays raw until a full rebuild, that earlier 5.0 alphas refuse the index at load, and the API changes for Rust embedders.
|
From the review summary:
|
… reads To decide which listed groups a removal empties, remove_from_reverse_tree kept every leaf it read, decoded, until it finished, for every reverse tree and whether or not the removal touched a listed group. An erasure reaching many leaves held all of them at once, where it used to hold one at a time. It now finds the listed groups the removal touches first, and keeps of each leaf it reads only its keys under those groups; when it touches none, the common case, it keeps nothing. A new test leaves a group's keys only inside one leaf, past its first and last keys, where those kept keys alone show the group still holds values.
… pays The string rebuild sent every batch of 4,096 strings to the rayon pool to hash its long ones, a batch of short strings included, where the dispatch is all cost. And during a fresh import the dictionary upload runs beside the index builds, so hashing threads compete with them for cores whenever they are woken. A batch now goes to the pool only when it holds at least 256 strings to hash (in chunks of at least 64); any other batch has its long strings hashed as they are keyed. Under test the bar is 8, so both ways run.
…he group A removal decides which listed groups it may have emptied from the keys it removes, and counted a key toward a group only when it was longer than the group's prefix. The one value exactly as long as the prefix, the prefix itself, is no member of the group, but its key lies in the group's range and keeps the group listed once the group's long values are gone. Erased afterwards, it touched no group, so the listing survived it, and the branch kept the erased value whole. KeyScheme::key_group now takes a key of at least the prefix's length, so that removal touches the group and prunes it. Tested by erasing a group's long values and then the value spelling its prefix.
A value in a group listed after it began hashing may be held under its value key or its hashed one, so a lookup tries the value key first. lookup_keys computed the hashed key up front anyway, so every hit on the value key in such a group paid a SHA-256 of a long literal it never used, singly and in batches. LookupKeys now carries the value and hashes it in then(), which the single lookup calls on a miss and the batched lookup calls for the values its first pass missed. Prefetch routing and removal, which need both keys, ask for both.
The rebuild sent a batch to the rayon pool when it held 256 long strings, counting those of groups the tree keys by value, which are not hashed: a batch of a listed group's strings was dispatched to compute no hash at all. And a count stands in poorly for SHA-256's cost, which grows with the bytes hashed. A batch now goes to the pool when the strings it will hash total at least 64 KiB. KeyRules::hashes is the one test of whether a value is keyed by hash, shared by key, key_hash and this count.
An incremental build adding long strings to a hashed string tree spent most of its extra time per new long string. Profiled on 50k new strings that sort together: each was hashed three times (the resolver's leaf prewarm and its lookup each computed the string's lookup keys, and the tree's update keyed it again), and counting each group's hashed keys cost an owned copy of the group, a map insert and two binary searches per new string, then a range scan that copied every key it matched. The resolver now computes the window's string lookup keys once, on the rayon pool when the strings to hash total 64 KiB or more, and uses them for both the prewarm (touched_leaf_addresses_keyed) and the lookup (reverse_lookup_keyed). LookupKeys keeps the hash behind a hashed key, and the resolver carries each new string's hash, by id, to the tree's update, which keys the string with it (KeyRules::key_hashed) rather than hashing it again; a string without one is hashed there. GroupPlan borrows its groups from the new values, sorted and counted in one pass, finds the leaves each group's hashed range overlaps in one walk over groups and leaves together, and counts the keys in that range with ReverseLeaf::count_range, which copies none. GroupPlan::fill now returns the groups to list, and key_new_values lists them and keys the values.
The hashed string leaves use #2436's front-coded
DLR2layout.The string reverse tree keyed every string by its whole value, so long literals (descriptions, review text, URLs) made it the largest part of a BSBM ledger: 4.3 GB of 12.5 GB. A string longer than 81 bytes is now keyed by its first 48 bytes, a
0xFFmarker and its 32-byte SHA-256, and the tree's leaves are front-coded. On BSBM 100M the string tree shrinks to 532 MB and the ledger by 30%, with import, indexing and query speed level. On a ledger of long strings, review measured a full reindex, an incremental pass and the first query after a commit slower; with the changes listed below they are level or faster (see Measurements).What changes
0xFF, so a hashed key cannot be mistaken for a value key. Every key keeps its value's first 48 bytes, so a prefix of up to 48 bytes still maps to one key range. 81 bytes is the hashed key's own length, so a string no longer than that stays keyed by value.DTB2branch records the scheme, prefix length, cap and listed groups. A raw tree's branch stays byte-for-byteDTB1, so subject and term trees are unchanged. The tree reader keys values by its own scheme, so callers still look up values.LeafFormat::for_dict(dict)isfor_tree(dict, scheme).DictTreeReader::reverse_lookup,reverse_lookup_manyandtouched_leaf_addressestake values.find_strings_by_prefixreturns ids unordered.DictBranchgainskey_schemeandraw_groups.benches/reverse_leaf.rs): string probes for raw keys in plain leaves, hashed keys in front-coded leaves, and a worst case where every group is listed and flagged.Measurements
BSBM 100M. The baseline is
nextplus the other open perf PRs, including #2436, measured on the same boxes.A ledger of long strings (review A/B, before the changes for speed above). c7i.4xlarge, release profile, base #2436, 8 interleaved runs, medians:
The string-tree build alone was about twice as long: it read every string twice, hashed each long one in turn, and copied every value-keyed one; it accounted for about 0.44 s of the reindex's 1.1 s. The first query after a commit paid a hash and a probe that must miss for each novelty string. The changes above address both. Warm lookups of long strings by value still pay the hash.
The same kind of ledger, after those changes. m7a.4xlarge, release profile, base
nextat the #2436 merge (a24c33b07), heade12993ad2. 1M subjects, each with a note of about 250 bytes and a short name, indexed, then 50k more notes in 5 unindexed commits; ledgers in/dev/shm; 6 interleaved rounds per variant, each measurement in its own process; medians. The query is aCOUNTover every note with aSTRLENfilter, timed right after a one-triple commit and again with none (54 timings each). The new notes either spread over the string tree (their first words vary) or all sort together at its end, which leaves per-string costs to dominate.Both variants count the same 1,050,000 notes. Before the last two changes, the incremental pass with the notes together was +15.7% (634 → 733 ms). Profiled, most of that was per new long string: it was hashed three times (the resolver's leaf prewarm, its lookup and the tree's update), and counting its group cost a copy, a map insert and two binary searches; front-coded string leaves account for the rest. Each string is now hashed once, in parallel for large windows, and the groups are counted in one walk.
Query speed is level. BSBM lists no groups, so the cap changes no lookup there, and the query runs compared an earlier version of this change, without the cap, to the baseline:
The capped version against that earlier version, in one session with the builds swapped between boxes each round, ran −0.5% single-client and −0.3% at 128 clients, every query within 0.13 ms.
Worst case: N strings of 115 bytes sharing a 60-byte prefix, so one group holds all N.
The group is listed at import, so its strings are keyed by value. Without the cap, the selective prefixes took 0.62 s at 2M and 4.3 s at 10M. The prefix matching all 10M is 28% slower; the cause is not established.
A group filling across commits (20 strings per commit, an incremental index pass after each):
Exact hits and misses, prefixes at 48–109 bytes, ORDER BY and COUNT DISTINCT were correct at every stage. Cold, a miss in the flagged group takes the same time as in the other groups (about 31 ms), so the second probe has no visible cost.
Microbenchmark, one leaf: a warm probe costs 113 ns with raw keys and 763 ns with hashed keys, mostly the SHA-256 of the probe value. A leaf where every group is flagged, so every miss probes twice, costs 1,331 ns. None of this shows up in the query times above.
Compatibility
A full build writes string trees with a
DTB2branch, which earlier builds refuse as an invalid magic. This build reads string trees earlier builds wrote, and keeps them raw. The mixed case was checked end to end: this build ran on a ledger an earlier build had indexed, then took writes and an incremental index pass. All correctness checks passed, with no answer differences against the earlier build.Follow-up: #2442