Skip to content

perf(index): reuse zstd contexts per thread for column blocks - #2049

Merged
bplatz merged 4 commits into
mainfrom
perf/zstd-context-reuse
Oct 13, 2026
Merged

bplatz merged 4 commits into
mainfrom
perf/zstd-context-reuse

Conversation

@bplatz

@bplatz bplatz commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Every column block created a fresh zstd context. Decoding a leaflet decompresses one block per column, and writing a leaf compresses one block per column per leaflet, so creating the context was a fixed cost paid many times per leaf.

This PR keeps one decompression context and one compression context per thread and reuses them:

  • Decompression: a thread-local zstd::bulk::Decompressor.
  • Compression: a thread-local zstd::bulk::Compressor, rebuilt only when the compression level changes.

The reused compressor writes byte-identical blocks, so leaf content IDs don't change and no reindex is needed. reused_compressor_matches_fresh_compress checks this.

A reused output buffer keeps the capacity of the largest block the thread has decoded, so zstd alone would accept a frame longer than the block's declared size. The decode requires exactly the declared size, which also catches a short frame (decoded_length_must_match_the_ref).

Measurements

  • Decode: on the Pokec graph (1.6M nodes, file storage, EC2 m7a.4xlarge, Linux x86_64), a min/max/avg aggregate that is bound by decoding ran about 40% faster, at each leaflet size tried (1,024 to 25,000 rows). Per block, the gain depends on block size: in the review's microbenchmark, 25,000-row blocks decode at parity, 4,096-row blocks 1.08–1.36× faster, and blocks of 500 rows or fewer up to about 2× faster.
  • Encode: on BSBM 100M Explore-and-Update (1 client, background indexing on), throughput went from 9,147 to 9,634 query mixes per hour. Those are single runs, so treat the encode-side number as directional.

…mn blocks

zstd::bulk::decompress built a fresh context (allocation + zeroed
workspace) for every column block; small leaflets pay it once per
column per leaflet. A thread-local Decompressor and output buffer
remove the per-call setup.
… blocks

zstd::bulk::compress built a fresh compression context for every column
block, a fixed cost each leaf write pays once per column per leaflet. The
reused context produces byte-identical blocks, so leaf CIDs are unchanged.
@bplatz bplatz added area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches performance Performance improvement (release notes: Performance) labels Oct 10, 2026
@bplatz
bplatz requested a review from a team October 10, 2026 15:18

@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 a nice, contained win, and at a design level no pushback from me: a thread-local context per direction is the right altitude. One note on how it relates to #2051. On my machine the gain is concentrated in small blocks (25,000-row columns decode at parity, a few hundred rows up to ~2× faster), which is exactly where #2051's "groundwork for evaluating smaller leaflet sizes" is heading, so the two compound nicely.

Full review below:


✅ Approve with nits.

This is a tidy one, @bplatz. The thread-local Compressor/Decompressor pair is the obvious-in-hindsight fix. Since leaf CIDs hash the encoded bytes, I spent most of my time on the byte-identity claim, and it holds up well beyond the test in the PR: 234 blocks of 0–250,000 values, large→small→large orderings, and levels 1/3/−5/9/19/22 interleaved on one thread all matched a fresh zstd::bulk::compress byte for byte. A decode that fails (corrupted block, truncated frame) doesn't poison the reused context; the next valid decode on that thread is correct.

I also measured the decode side with a dev-fast microbenchmark. A 25,000-row u64 block decodes at parity (1.01–1.04×); 4,096 rows are 1.08–1.36× faster, and 500 or fewer rows up to ~2×. That fits the PR's "small leaflets pay it" framing. The host for the ~40% aggregate number isn't stated, and allocator behavior differs by platform, so it may be worth a word in the body. Per-thread memory is small: 582,672 B for the level-1 CCtx index builds use, and 95,984 B for the DCtx plus an output buffer up to the largest block (200 KB at 25,000 rows), bounded by pool sizes.

The one inline note is optional: the "at most len bytes" bound in with_decompressed no longer holds once the thread's buffer has grown. Both production decode paths re-check against row_count, so it isn't a live bug.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Contained to the two column-block helpers; every encode/decode routes through them; no new construct.
  • Performance (speed first, memory second): ✔ Decode is parity at 25,000-row blocks and faster on small blocks; encode is parity within noise on my host. Memory is +~0.3 MB per decoding thread and +~0.6 MB per encoding thread, held for the thread's life. No performance-degradation risk.
  • Deployment targets: ✔ Shared code every host runs. Thread-locals coordinate nothing across processes and nothing here needs them to. Per-thread memory is small next to the Lambda envelope. wasm32 and wasm-smoke are green.
  • Testing: ✔ reused_compressor_matches_fresh_compress runs and has teeth: making the compressor ignore a level change turns it red ("level 3"). It uses equal-size inputs; I covered varied sizes separately.
  • Conventions: ✔ Multi-line commit bodies, self-describing title; clippy and fmt green.

Verified locally at branch HEAD (7d7d66ad3): cargo test -p fluree-db-binary-index --lib column_block (7 passed, new test by name); a mutation check on the level-change rebuild (red, restored); a scratch byte-identity, decode-after-error and context-size test; a dev-fast decode/encode microbenchmark.

Approving so you can merge when ready; the nit is worth folding in if you agree.

let (dctx, buf) = slot.as_mut().expect("decompressor initialized above");
buf.clear();
buf.reserve(len);
dctx.decompress_to_buffer(src, buf).map_err(invalid)?;

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 / nit: the "at most len bytes" bound in with_decompressed isn't enforced once the thread's buffer has grown

buf.clear(); buf.reserve(len) leaves the capacity from the largest block this thread has decoded, and decompress_to_buffer writes up to the capacity, not up to len. Main's zstd::bulk::decompress(src, len) sized a fresh buffer to len and errored when the frame was bigger.

I checked it with a scratch test. After a 50,000-value decode on the thread, a 1,000-value block whose ref declares half its size decodes as Ok(1000 values) here, where main returns Err("Destination buffer is too small"). Nothing reaches a reader today: both production paths re-check decoded.len() != row_count (read/column_loader.rs:61 and read/leaf_access.rs:558, plus the u32/u16 twins). So this is about the doc comment and defense in depth, not a live bug.

One line after the decode would make it stricter than main (it also catches a short frame), and keeps the doc honest (illustrative):

        dctx.decompress_to_buffer(src, buf).map_err(invalid)?;
        if buf.len() != len {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("column block decoded {} bytes, expected {len}", buf.len()),
            ));
        }

I 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.

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 b173e36

…lared size

The reused buffer keeps the capacity of the largest block the thread has
decoded, so zstd alone accepted a frame longer than the ref declares, where
a fresh `zstd::bulk::decompress(src, len)` refused it. The decode now
requires exactly `len` bytes, which also catches a short frame. Readers
re-checked the row count already, so nothing reached a query.
@bplatz
bplatz merged commit 90d2338 into main Oct 13, 2026
19 checks passed
@bplatz
bplatz deleted the perf/zstd-context-reuse branch October 13, 2026 18:25
aaj3f added a commit that referenced this pull request Oct 13, 2026
Brings in #2019, #2044, #2048, #2049 and #2052 (main at 58b5323).

#2052 keys cross-ledger governance by the model ledger's head commit and
opens the model at that commit. Two files conflicted:

- tx.rs: this branch moved the stored-shapes pass into its own block
  (`stored_cache`), which #2052 edited in its old place. The block keeps
  this branch's shape, and its compiled-SHACL cache key carries #2052's
  commit id beside the model's t, as main's does. The shapes model opener
  and the cache key type merged without conflict.
- it_policy_cross_ledger.rs: both sides appended tests; both are kept.
aaj3f added a commit that referenced this pull request Oct 14, 2026
…2068) into fix/write-fidelity-part2

Two conflicts, both with #2056, which fixed the same debug assertion this
branch fixed in 9b7cc1a (the resolver's reserved-namespace guard
rejected f:message, f:author and f:reverts in txn-meta):

- fluree-db-indexer/src/run_index/resolve/resolver.rs: took main's
  version, the guard deciding through fluree_vocab::txn_meta::may_hold.
  This branch's widened is_system_txn_meta_entry admitted the same five
  names and goes; the file now equals main's.
- fluree-db-api/tests/it_txn_meta.rs: kept both sides' tests, this
  branch's an_index_build_keeps_the_user_message_and_author (a file
  ledger through a full rebuild) beside #2056's.

template_sink.rs, trig_meta.rs, txn_meta.rs, admin.rs and fluree-vocab
merged cleanly: #2056's predicate check in the txn-meta path sits beside
this branch's statement hashing and does not touch it.
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 performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants