Repository navigation
Conversation
A string pack's values are now FSST codes over one symbol table trained on the pack: up to 255 symbols of 1-8 bytes, with code 255 escaping a literal byte, so any one value decodes on its own. On BSBM 100M the string packs shrink from 4.22 GB to 2.15 GB and the ledger by 24%. Cold queries run about twice as fast, and warm throughput is level. - Coded packs are FPK1 version 2. The header's reserved word holds the length of a codec section after it, which maps runs of pages to a table or to raw. A pack whose codes would not be smaller stays version 1, as do subject and triple-term packs. - Readers decode on whole-pack and ranged lookups. A pack opened by range reads its codec section along with its header, once. - Compaction still copies pages verbatim. Each input's runs move with its pages, and a version 1 input becomes a raw run. - Erasure re-encodes the pack, so its new table is trained without the erased values. - A full build encodes string packs in parallel, a batch at a time. BREAKING CHANGE: string forward packs are written as FPK1 version 2, which earlier builds refuse.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz the codec work here is careful, and FSST is the codec I'd have picked. But by our speed-first rule I don't think string coding should be on by default yet. On a 35M-triple BSBM box, Claude reproduced the slowdown on text scans (+24–50%) and the space saving (string packs −48.9%). The cold speedup that's meant to pay for them depends on the protocol: two were level, and a warm-process one showed Q2 1.8× faster with Q8 level. Claude also found no variant that keeps those scans level without giving back ~89% of the saving. So I'd ship the codec opt-in, default raw, until the cold win is shown on the storage it targets. Separately, decoded strings keep 4× capacity.
Full review below:
The format is careful: per-run codecs, the version 1 fallback, verbatim compaction and erasure retraining all check out on the box. But as written it makes text scans 24–50% slower on every ledger, for a space win and a cold-read gain that shows up only under some protocols (Q2 1.8× faster in a warm process with a dropped page cache, level otherwise). By our speed-first rule that needs either the cold win shown where it applies, or the coding off by default.
Before merging:
forward_pack.rs:871: make string-pack coding opt-in (default raw), or show the cold gain on the storage it targets and default it on there.forward_pack.rs:237: decoded strings keep 8× their code length as capacity (4.07×; 1,888 vs 737 MB on a large sort). Decode into a scratch buffer and copy exactly inforward_lookup_str, as measured.
Notes:
- The cold result, stated plainly: your body's "cold queries about twice as fast" reproduced on Claude's box under one protocol of three, and for one query shape of two. It ran c7i.4xlarge, BSBM pc=100000 (35.3M triples), file storage on the local EBS root volume with packs memory-mapped, the page cache dropped with
sync; echo 3 > /proc/sys/vm/drop_caches, and 10 runs per build per protocol. A fresh server and a preloaded ledger were both level (0.96–0.99). A warmed process with a cold page cache showed the Q2 shape at 17.2 → 9.4 ms (level to 2× by product) and the Q8 shape level, against your 24.0 → 3.6 ms. Your protocol, scale and storage aren't in the body; could you add them? On remote or encrypted stores, where cold reads pay for bytes, this is unverified rather than refuted. - Head got slower after the one write and base didn't (
CONTAINS+34% → +48%). Claude didn't isolate why; the pack the incremental pass merged decodes at the same 3.1 GB/s as the rest. - Early exit for the
CONTAINSfold: in Claude's single-thread bench it makes the common-needle work 27% faster than base today, and a prefix-only decode would do the same forSTRSTARTS-shaped folds. Worth folding in with the opt-in. - CI run 44391774869 on this head is green, but it predates the
risc0-zkvmyank, so a re-run before #2478 lands goes red onwasm32for an unrelated reason. - #2436 and #2445 merge cleanly with this (
git merge-tree). On #2445,remove_from_reverse_tree_asynckeys erased values by the tree's own scheme, so this PR's erasure, which hands it decoded values, composes with #2445's hashed long-string keys.
Every measured row (Claude, one EC2 c7i.4xlarge, release LTO builds of base 1d5f827 and head 9f8397b)
Warm, end to end: one server per round, 2 warm-ups, 5 timed runs, median of per-round medians, builds alternating; result bodies identical across builds.
| Shape | Index state | Base ms | Head ms | Change |
|---|---|---|---|---|
COUNT + CONTAINS "ness" over texts |
import | 140.1 | 185.2 | +32.2% |
COUNT + CONTAINS "bombardiers" |
import | 141.0 | 186.4 | +32.2% |
COUNT + CONTAINS "xyzzyq" |
import | 134.6 | 180.6 | +34.2% |
| same | +1 write, incremental | 135.7 | 200.1 | +47.5% |
| same | +1 write (probe, 2 rounds) | 133.8 | 198.2 | +48.1% |
| same | full reindex (2 rounds) | 109.5 | 146.8 | +34.0% |
SELECT ?r + CONTAINS (generic lane) |
import | 1,143.5 | 1,416.2 | +23.8% |
COUNT + REGEX "ing$" over titles |
import | 81.0 | 66.3 | −18.1% |
SUM(STRLEN) over texts |
import | 130.6 | 177.6 | +35.9% |
| same | +1 write (probe) | 129.6 | 193.8 | +49.6% |
| same | full reindex | 96.2 | 129.2 | +34.4% |
COUNT + STRLEN(LCASE) over texts |
import | 1,252.9 | 1,411.4 | +12.6% |
| ORDER BY title LIMIT 10 | import (ids lex-sorted) | 93.9 | 94.0 | +0.2% |
| same | +1 write | 704.0 | 733.0 | +4.1% |
| ORDER BY title LIMIT 10 OFFSET 300000 | +1 write | 2,282.4 | 2,558.5 | +12.1% |
MAX over titles |
+1 write | 920.6 | 1,012.8 | +10.0% |
| ORDER BY text LIMIT 10 (language-tagged) | import | 1,000.7 | 1,122.2 | +12.1% |
| same | +1 write | 1,004.2 | 1,335.9 | +33.0% |
| same | +1 write (probe) | 986.9 | 1,302.5 | +32.0% |
| same | full reindex | 523.0 | 672.2 | +28.5% |
| ORDER BY text LIMIT 10 OFFSET 300000 | +1 write | 3,246.7 | 4,434.2 | +36.6% |
SELECT ?t LIMIT 200000 over texts |
import | 907.9 | 988.7 | +8.9% (runs overlap: 873–1,278 vs 868–1,265) |
The capacity fix, after a write and a full reindex, 4 rounds. fix is shrink_to_fit; fix2 is the scratch buffer with an exact copy. The last column is peak RSS over starting RSS, in MB.
| Shape | Base | Head | fix |
fix2 |
MB base / head / fix / fix2 |
|---|---|---|---|---|---|
| ORDER BY text OFFSET 300000 | 2,850.1 | 3,757.8 (+31.8%) | 3,051.2 (+7.1%) | 2,912.9 (+2.2%) | 737 / 1,888 / 745 / 737 |
| ORDER BY title OFFSET 300000 | 1,883.8 | 2,011.9 (+6.8%) | 1,947.3 (+3.4%) | 1,958.7 (+4.0%) | 130 / 208 / 136 / 127 |
| ORDER BY text LIMIT 10 | 526.9 | 682.2 (+29.5%) | 730.4 (+38.6%) | 705.9 (+34.0%) | 3 / 4 / 3 / 4 |
COUNT + STRLEN(LCASE) |
779.5 | 949.9 (+21.9%) | 1,020.8 (+31.0%) | 1,000.1 (+28.3%) | ~0 |
SELECT ?r + CONTAINS |
665.8 | 833.3 (+25.2%) | 885.9 (+33.1%) | 842.3 (+26.5%) | ~0 |
Cold, 10 runs per build over 5 products, medians, base vs head, in ms:
| Protocol | Q8 shape | Q2 shape |
|---|---|---|
| fresh server, page cache dropped | 557.5 vs 534.1 (0.96) | 340.1 vs 337.9 (0.99) |
| ledger loaded, then page cache dropped | 440.7 vs 437.9 (0.99) | 239.8 vs 236.3 (0.99) |
| process warmed on another product, then page cache dropped | 193.0 vs 186.4 (0.97) | 17.2 vs 9.4 (0.54) |
| warm repeat | 2.4 vs 2.3 | 2.0 vs 2.0 |
Single-thread microbench, warm, all 3,673,552 string values (1,485,968,981 bytes decoded), median of 5. Each cell is base / head, in ms.
| Work per value | "ness" | "bombardiers" | "xyzzyq" |
|---|---|---|---|
lookup + from_utf8 + str::contains |
498.4 / 716.3 | 478.0 / 691.0 | 452.3 / 666.4 |
decode + memmem |
304.1 / 514.3 | 285.6 / 489.8 | 283.8 / 487.5 |
| decode 64 codes at a time, stop at the first match (head) | 363.3 | 659.3 | 657.7 |
| KMP automaton per code (head) | 729.4 | 1,997.9 | 1,998.7 |
lookup_into alone: 235.5 / 487.2 ms. Sizes: string packs 1,500,746,953 → 767,102,496 bytes; ledger 5,632,057,007 → 4,900,323,573 bytes. Full reindex: 104.5 vs 97.8 s.
Adherence: Patterns ✔ · Performance ✖ · Deployment targets ✔ · Testing ✔ · Conventions ⚠️ · verification
- Patterns/abstractions: ✔ The codec lives inside the existing pack format, kept per run of pages so compaction keeps copying pages verbatim. Readers go through the one
lookup_in_pack_into/ranged_lookuppair, and the new dependency (fsst-rs, Apache-2.0) is small. - Performance (speed first, memory second): ✖ CRITICAL. Scans that decode every long text value regress 24–50% on every ledger, and the cold gain that pays for it depends on the protocol (Q2 0.54 in a warm process, level in two others). The 4× string capacity is a memory regression with a fix measured to get both.
- Deployment targets: ✔ Shared code in every host.
fsst-rsis pure Rust, andwasm32andwasm-smokepassed on the head SHA. The one host-relevant point is the panic on damaged codes, which ends a serverless invocation (optional comment). - Testing: ✔ Unit coverage of coded read-back, mixed concat, blanking, bad codec sections and ranged reads, plus an import → incremental → rebuild integration test wired through
grp_import. Claude's mutations of the whole-pack decode and of the ranged table each turn them red (16 and 1 failures). - Conventions:
⚠️ Multi-line commit with aBREAKING CHANGEfooter anddocs/design/index-format.mdupdated, but the three excluded lockfiles weren't refreshed (optional comment).
Verified at 9f8397bb8: Claude ran base 1d5f82783 and head as release builds on one EC2 c7i.4xlarge over BSBM pc=100000 (35.3M triples). That covered warm end-to-end A/Bs on three index states, three cold protocols, two builds of the capacity fix, a single-thread microbench of the alternatives, an erasure symbol-table check, a damaged-code check, the crate's forward_pack/pack_reader tests (64 passed) plus two mutations, and merge-tree against #2436 and #2445. CI run 44391774869 on the head SHA is green.
Happy to talk any of this through. If the cold numbers hold on the storage you had in mind, defaulting coding on there seems right to me; it's the default everywhere else that I'd hold back.
| ns_code: u16, | ||
| target_page_bytes: usize, | ||
| ) -> io::Result<Vec<u8>> { | ||
| if kind == KIND_STRING_FWD && !entries.is_empty() { |
There was a problem hiding this comment.
CRITICAL (performance): every ledger now codes its string packs. The scans this slows are slower in every run Claude made, while the cold win meant to pay for them shows up only under some protocols.
Every string pack goes through FSST at this branch, so every value a query decodes pays FSST's decode rate. On BSBM text that's 3.1–3.3 GB/s per core, against about 6.3 GB/s for the raw copy. Queries that decode every long text value pay it on every row.
Claude ran base and this branch as release builds on one c7i.4xlarge over BSBM at 35.3M triples (1M reviews). Warm, 4 rounds with the builds alternating:
COUNT+CONTAINSover all review texts: +32–34% on the import's index, +47.5% after one write and an incremental index, +34% after a full reindex.SUM(STRLEN): +34–50%.- ORDER BY on the language-tagged texts: +12–33%.
CONTAINSthrough the generic lane: +24%.LCASE: +13%.
Every row, including the ones that moved the right way, is in the review body.
What pays for that is half the string bytes (string packs −48.9%, the ledger −13% at this scale) and a faster cold read. The cold read is real but depends on the protocol. With the ledger on the box's local EBS volume (packs memory-mapped) and the page cache dropped (sync; echo 3 > /proc/sys/vm/drop_caches), three protocols, 10 runs per build each:
- Server restarted before each query: head/base 0.96 for a Q8-shaped query, 0.99 for a Q2-shaped one.
- Ledger loaded by a query that reads no strings, then the cache dropped: 0.99 and 0.99.
- Process warmed on another product's same query, then the cache dropped: the Q2 shape went 17.2 → 9.4 ms (median, 0.54, from level to 2× by product); the Q8 shape stayed level.
So the win reproduces where a warm process fetches long strings from a cold disk, at a smaller multiple than your 24.0 → 3.6 ms. The scan slowdown, on the other hand, showed up in every index state Claude measured.
Claude also looked for a variant that keeps these scans level while still coding long text, and didn't find one. Single thread, all 3.67M values, needle common / rare / absent:
- Base today: 498 / 478 / 452 ms. This branch: 716 / 691 / 666 ms.
- A KMP automaton stepped per code, with no decode at all: 729 / 1,998 / 1,999 ms.
- Decoding 64 codes at a time and stopping at the first match: 363 / 659 / 658 ms. That helps only the common needle.
- Values over 512 bytes carry 88.8% of the saving, so leaving them raw undoes the PR.
- The
fsst-rsdecoder already works 8 codes per step, so a faster decoder isn't sitting on the table either.
My recommendation is to make string coding opt-in, default raw, until the cold gain is shown on the storage it targets. The readers already take version 1 and version 2 per run, so it's this branch plus a build option passed to its three callers (full build, incremental extend, erasure). A ledger that wants the space opts in, and nobody's text scans get slower by default.
If your 100M numbers come from a store where cold reads pay for bytes, it'd be good to put that in the body and default coding on for that store. Two candidates: a remote store, whose fetch_and_load fetches a whole pack, and an encrypted local store, whose ranged reads decrypt units. Claude couldn't test either cheaply here, so on those stores the cold gain is unverified rather than refuted. Early exit in fast_string_fold.rs is worth having either way.
| /// Append the value `codes` stand for to `out`. | ||
| pub(crate) fn decode_value_into(&self, codes: &[u8], out: &mut Vec<u8>) { | ||
| let decompressor = fsst::Decompressor::new(&self.symbols, &self.lengths); | ||
| out.reserve(decompressor.max_decompression_capacity(codes)); |
There was a problem hiding this comment.
Blocking (memory): a decoded string keeps 8× its code length as heap capacity.
decode_value_into reserves decompressor.max_decompression_capacity(codes) on out, and in fsst-rs 0.7 that bound is 8 × (codes.len() + 1) (lib.rs:244). That's fine for a reused buffer like the fold lane's. But ForwardPackReader::forward_lookup_str (pack_reader.rs:608-620) passes a fresh Vec and hands it straight to String::from_utf8, which keeps the capacity. That's the path behind resolve_string_value, so every FlakeValue::String the generic lanes build from a coded pack carries it. ForwardPack::lookup does the same at :813-815.
Claude measured it on the box over all 3,673,552 strings: 6,046,638,016 bytes of capacity for 1,485,968,981 bytes of text, or 4.07× (1.00× on base). End to end it shows wherever strings are held: ORDER BY on the review texts with OFFSET 300000 peaks 1,888 MB over its starting RSS on this branch, against 737 MB on base, and runs +31.8%.
Claude built two fixes in forward_lookup_str and A/B'd them against base and this branch (4 rounds):
value.shrink_to_fit()fixes the memory (745 MB) and most of that time (+7.1%). But its realloc taxes the paths that build a string and drop it: ORDER BY text LIMIT 10 goes from +29.5% to +38.6%, andLCASEfrom +21.9% to +31.0%.- Decoding into a thread-local scratch buffer and then copying exactly gets both. Memory is level with base (737 MB), the big sort is +2.2%, and the transient paths move only 1–6 points (+34.0%, +28.3%, +26.5%):
thread_local! {
static SCRATCH: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
let value = SCRATCH.with(|scratch| -> io::Result<Option<Vec<u8>>> {
let mut scratch = scratch.borrow_mut();
scratch.clear();
if !backing.lookup_into(meta, id, &mut scratch)? {
return Ok(None);
}
Ok(Some(scratch.as_slice().to_vec()))
})?;
let Some(value) = value else {
return Ok(None);
};
String::from_utf8(value)ForwardPack::lookup's Cow::Owned arm and ranged_lookup's per-lookup codes Vec (pack_reader.rs:260) could use the same buffer. This stands with or without the opt-in, since an opted-in ledger hits it on every string. Commenting here because pack_reader.rs:608-620 is not in this diff.
| pub(crate) fn decode_value_into(&self, codes: &[u8], out: &mut Vec<u8>) { | ||
| let decompressor = fsst::Decompressor::new(&self.symbols, &self.lengths); | ||
| out.reserve(decompressor.max_decompression_capacity(codes)); | ||
| let written = decompressor.decompress_into(codes, out.spare_capacity_mut()); |
There was a problem hiding this comment.
This is minor, but a damaged code stream panics here rather than returning an error. A coded value whose last code is the escape (255) reaches fsst-rs's assert! at lib.rs:477 ("truncated compressed string: escape code at end of input"). Claude reproduced it on a box by flipping a value's last stored byte in an otherwise valid pack: lookup_into panics.
The rest of the PR is deliberate about corrupt input: a bad codec section is refused, and ranged reads bounds-check offsets so they can return an error. So it seems worth closing this one too. Valid UTF-8 never holds 0xFF, so a value whose last code is 255 is damaged, and a cheap check before decoding could return InvalidData (with decode_value_into returning io::Result). On an embedded serverless host a panic ends the whole invocation, not one query. 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.
| fn blanking_a_coded_pack_keeps_every_other_value() { | ||
| let entries = text_entries(0, 1_000); | ||
| let bytes = encode_forward_pack(&as_refs(&entries), KIND_STRING_FWD, 0, 4096).unwrap(); | ||
| let blanked = blank_forward_entries(&bytes, &[1, 6], 4096).unwrap(); |
There was a problem hiding this comment.
Erasure re-encoding the whole pack so the table is retrained on survivors is the right call. Claude checked it holds on a box. One pack held an erased value with a distinctive token, small enough that training saw every value. Its table held symbols that only the erased value had ("WVKQ", "QZXJ"); after blank_forward_entries it held none, and no value or raw byte held the token. A two-run compacted pack behaved the same.
This test doesn't pin that, though. Unlike the raw-pack test above it, which asserts the erased bytes are gone, it checks only the survivors, and its erased values aren't distinctive enough to show up in a table either way. Maybe worth giving it a distinctive erased value and asserting both sides, so it can't pass vacuously:
// erased value: "QZXJWVKQ".repeat(200), in a pack under 16 KB so training sees every value
// before blanking: some symbol in parse_pack_meta(&bytes).codecs holds an uppercase byte
// after blanking: no symbol in parse_pack_meta(&blanked).codecs doesI recognize this is minor and non-blocking, but if you agree it's right I'd rather see it folded in now than lost in the backlog.
|
|
||
| # Index format dependencies | ||
| zstd.workspace = true | ||
| fsst-rs = "0.7" |
There was a problem hiding this comment.
The new fsst-rs dependency lands in the root Cargo.lock only. testsuite-sparql/Cargo.lock, testsuite-shacl/Cargo.lock and wasm-probe/Cargo.lock each reach fluree-db-binary-index but carry no fsst-rs entry, so each resolves it fresh on every run. No CI job builds those three with --locked, so nothing catches it. It's the same drift class #2478 repairs for risc0-zkvm. A cargo update -p fsst-rs in each of the three directories would fold it in. Minor and non-blocking, but if you agree I'd rather see it in this PR than lost in the backlog.
fluree-db-binary-index's new fsst-rs dependency landed in the workspace lockfile only. testsuite-shacl, testsuite-sparql and wasm-probe each reach fluree-db-binary-index through their own lockfile, which lacked it, so each resolved it fresh on every build and none resolved with --locked, which the lockfiles CI job requires. Each now holds fsst-rs 0.7.0 with the workspace lockfile's checksum; no package version any of them held changes. testsuite-shacl's data-encoding-macro-internal now builds against syn 2, as the workspace's does.
A coded value whose last byte is the escape code reached fsst-rs's
assert ("truncated compressed string: escape code at end of input") and
panicked the reader, where the rest of the pack format refuses damaged
input with an error. An escape takes the literal byte after it, and a
literal 0xFF never occurs in UTF-8, so any coded value ending in 0xFF is
damaged.
FsstTable::decode_value_into checks the last byte and returns
InvalidData; it and the lookups over it (lookup_in_pack_into,
ForwardPack::lookup and lookup_into, the whole and ranged readers)
return io::Result. Other damaged codes can't panic: the decoder's
tables are fixed 255-entry arrays.
FsstTable::decode_value_into reserves the decoder's bound on its output, 8 bytes per code. forward_lookup_str decoded into a fresh Vec and handed it to String::from_utf8, which kept that capacity, so every string the generic lanes built from a coded pack held about four times its length for as long as it lived; a large ORDER BY over review texts peaked at 2.6 times base's memory. ForwardPack::lookup's decoded arm did the same. Both now decode into a thread-local scratch buffer and copy the value out at its exact length. The ranged reader's per-lookup Vec for a value's codes uses a second thread-local buffer. A buffer grown past 1 MiB is dropped rather than kept for the thread's life, and a nested use falls back to a fresh Vec.
Erasure re-encodes a coded string pack so its FSST table is trained on the surviving values only, which keeps a symbol only the erased value spelled out of the pack. The test for it checked the survivors read back, but its erased values shared their bytes with the rest, so it would pass whether the table was retrained or not. The new test erases a value spelled in letters no other value uses, from a pack small enough that training sees every value. It checks the table learned those letters before erasure, that no symbol holds them after, and that the blanked pack is still coded.
String forward packs (string id → value) stored every value as it is, and on BSBM 100M they are 4.2 GB of an 8.7 GB ledger. They now store each value as FSST codes over a symbol table trained per pack, so any one value still decodes on its own. The string packs shrink to 2.15 GB and the ledger by 24%. Cold queries run about twice as fast, and warm throughput is level.
The cost falls on filters that decode the text of every row: a
CONTAINSover all 2.85M review texts runs 47% slower (137 → 202 ms).What changes
FPK1version 2. Header bytes 36–39, reserved until now, hold the length of a codec section after the header. The section maps runs of pages either to a symbol table or to raw. A table holds up to 255 symbols of 1–8 bytes, with code 255 escaping a literal byte.ForwardPack::lookupreturns aCow: borrowed from a raw page, owned from a coded one.fsst-rs0.7 (Apache-2.0, depending only onrustc-hash).Measurements
BSBM 100M. The baseline is the same build without this change. That build includes #2436 and #2445, which shrink the reverse trees and leave the forward packs as the largest part of the dictionary. Query runs swapped builds between boxes each round, over four rounds.
String-heavy queries, warm:
CONTAINSover all 2.85M review textsREGEXover all review titlesORDER BYon a string, 285k / 2.85M rowsSTRSTARTSreturning 26k / 27k rowsThese ledgers had taken no writes, so
ORDER BYcompared ids without decoding. On a ledger with writes it decodes to sort, which was not measured.Encodings compared on the same packs, before choosing:
Compatibility
A string pack this build writes is version 2, which earlier builds refuse as an unsupported version. This build reads version 1 packs and keeps them until a full rebuild.
The mixed case was checked end to end: this build ran 20 rounds of writes and incremental indexes on a ledger an earlier build had imported. Compaction folded the last raw pack's pages into a coded pack. Every check passed, with no answer differences against the earlier build.