Repository navigation
perf(indexer): warm-on-write only the leaflets readers had cached, on a bounded pool - #2068
Conversation
… a bounded pool Warm-on-write decoded every leaflet of every rewritten leaf with all columns, on an unbounded spawn_blocking per leaf. Under sustained writes that is far more than readers use: it fills the shared cache with leaflets nobody reads, evicting what they do read (dictionary leaves among them), and queues decode work without limit. update_leaf now records, for each new leaflet, the leaflet of the replaced leaf it came from and whether it is a byte copy; the branch update attaches the replaced leaf's CID. Warming carries over only what readers had cached for that leaf: - a copied leaflet whose source was cached takes the cached batch and its columns under the new key, with no decode; - a re-encoded leaflet whose source was cached is decoded for the cached columns, on at most a quarter of the cores; when they are busy the leaf is skipped and its first reader decodes it; - a leaflet no reader touched is not warmed. The leaf directory is seeded whenever a leaflet is. Reverse-dictionary warming, which copies raw bytes, is unchanged.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is nice, and at a design level no pushback from me. Carrying over what readers had cached, keyed off update_leaf's own origin bookkeeping, is the cheapest predictor available, and drop-when-busy is the right failure mode for best-effort work. I re-ran #1415's reindex_swap_read_profile against #2053's head (as "previous") and this head. The cache ends ~3.9× smaller (155–177 MB vs ~643 MB), same as your numbers. I couldn't reproduce the read-after-swap p50 gain at that scale in a dev-fast build (both ~0.055 ms), but nothing regressed. One process note: since the base is perf/narrow-count-decodes, CI hasn't run on this PR at all (only the release plan job), so the two new tests have never run in CI. I ran fmt, clippy and both crates' tests locally and they're green; just let CI run once #2053 lands and this retargets to main.
Full review below:
✅ Approve with nits.
This is a really nice follow-on to #2053, @bplatz. The per-leaflet column tag is what makes "which columns did readers have" answerable at all. The origin bookkeeping is tidy: one source_idx threaded through update_leaf, stamped with the replaced CID in the single shared drain. And a byte-copied leaflet carries over the cached Arc batch with no decode. I found nothing that needs to land first.
What I checked:
- Carry-over correctness. Every new leaf comes from exactly one replaced leaf.
replaced_leaf_cidis set only indrain_touched_output, which the serial and parallel drains share, and onlyupdate_leaf/NewLeafBlob::freshbuild aNewLeafBlob. A scratch property test over 450 random updates (SPOT/PSOT/POST, asserts and retracts, 244 multi-leaf splits) confirmed one origin per leaflet, origins that ascend across leaves, and all 5,890 copied leaflets decoding identically to their source. Invertingcopiedturns both your tests red, and restoring warm-everything failswarm_carries_only_cached_leaflets_to_the_rewritten_leafon "never read, never warmed". - The bound. A process-global
cores/4semaphore withtry_acquire_owned. When it's busy the leaf's re-encoded leaflets are dropped, the copies already landed, and the indexer never blocks. That's the right shape; the one note is that the skip is silent (inline). - Performance, measured on #1415's harness (six rotated runs per build, dev-fast, defaults). Final cache: 330–371 entries / 155–177 MB here vs ~8,340 / 642–645 MB on #2053's head. Read latency (just-written ~0.18 ms, existing ~0.055 ms p50) and index time (~32 ms p50) are the same in both builds.
Adherence to repo commitments:
- Patterns/abstractions: ✔ builds on #2053's single entry and
update_leaf's existing passthrough/re-encode split, with no parallel mechanism. - Performance (speed first, memory second): ✔ an improvement. The cache is ~3.9× smaller on the #1415 harness at equal read and index latency, and warm decoding is bounded and drops rather than queues. No regression risk.
- Deployment targets: ✔ the indexer is a native-only dependency of fluree-db-api, so nothing here reaches wasm32. On solo's Lambdas, an indexer process with nothing cached now warms nothing, where before it decoded every rewritten leaf. The fire-and-forget decode lost on a freeze is pre-existing from #1415, and now smaller.
- Testing: ✔ both new tests have teeth (two mutations caught).
⚠️ They have never run in CI, because this head only got the releaseplanjob. - Conventions: ✔ thorough commit body; fmt and clippy (
-D warnings) clean locally.
Verified locally at 074f00193: cargo fmt --check; cargo clippy -p fluree-db-indexer -p fluree-db-binary-index --all-targets -- -D warnings (0 warnings); cargo test -p fluree-db-indexer -p fluree-db-binary-index --lib (438 + 415 passed, update_records_each_leaflets_origin and warm_carries_only_cached_leaflets_to_the_rewritten_leaf by name).
Approving so you can merge when ready. Just let CI run on it once it's retargeted onto main after #2053, and maybe consider the two small notes first.
| } | ||
| return; | ||
| } | ||
| let Ok(permit) = Arc::clone(warm_decode_permits()).try_acquire_owned() else { |
There was a problem hiding this comment.
🟡 Optional: when the pool is busy the leaf is skipped silently.
Dropping rather than queuing is the right failure mode. The reader just decodes on first touch, and the indexer never waits on warming. But nothing records that it happened, so in production there's no way to see how often warming is shed. I'm guessing the PR's "the pool skipped 5 leaves in a whole 25,000-row run" came from local instrumentation.
A debug! here would make that observable at no cost on the happy path. Illustrative:
let Ok(permit) = Arc::clone(warm_decode_permits()).try_acquire_owned() else {
tracing::debug!(
leaflets = to_decode.len(),
"warm-on-write pool busy; leaving the leaf to its first reader"
);
if copied {
warm_leaf_dir(cache, leaf_id, &leaf_bytes);
}
return;
};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.
| ); | ||
|
|
||
| let columns = |idx| cache.v3_leaflet_entry(new_id, idx).map(|(c, _)| c); | ||
| assert_eq!(columns(0), Some(ColumnSet::CORE), "copied without a decode"); |
There was a problem hiding this comment.
🟡 Optional: the test pins which column sets were carried, not that the carried batch is the new leaflet's.
The correctness of the copy path rests on one invariant: a copied leaflet decodes exactly like its source. The test asserts columns(0) == CORE, so a carry-over that put the right column set under the wrong leaflet would still pass. I checked the invariant itself with a scratch property test: 450 random update_leaf calls over SPOT/PSOT/POST with asserts and retracts, 244 of them splitting into more than one leaf. All 5,890 copied leaflets decode identically to their source, and the origins line up across splits.
Pinning the data here too is a few lines. I ran this addition at this head and it passes. Illustrative:
let rows = |b: &fluree_db_binary_index::read::column_types::ColumnBatch| {
(0..b.row_count).map(|i| (b.s_id.get(i), b.o_key.get(i))).collect::<Vec<_>>()
};
let header = decode_leaf_header_v3(&blob.info.leaf_bytes).unwrap();
let dir = decode_leaf_dir_v3_with_base(&blob.info.leaf_bytes, &header).unwrap();
let fresh = load_leaflet_columns(&blob.info.leaf_bytes, &dir.entries[0], dir.payload_base,
&ColumnProjection { output: ColumnSet::CORE, internal: ColumnSet::EMPTY }, header.order).unwrap();
let (_, carried) = cache.v3_leaflet_entry(new_id, 0).unwrap();
assert_eq!(rows(&carried), rows(&fresh), "the carried batch is the new leaflet's");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.
…ed rows A busy pool leaves the leaf to its first reader, which is the right failure mode but was invisible. It now logs at debug. The warm test checked which column sets reached each new leaflet, not that the batches are the new leaflet's: it now compares every warmed batch with a fresh decode of the rewritten leaf.
…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.
Brings in #2102 (one HTTP status table), #2068, #2056, #2053, #2046, #2045 and the v4.2.4 release. - api error.rs: main's exhaustive status_code / error_type tables, with ApiError::ConfigUnavailable and TransactError::ConfigUnavailable classified as 500 err:storage/ReadFailure in both, and rows for them and RequestOverrideRefused in every_variant. - server error.rs: main's derivation from ApiError; this branch's ConfigUnavailable arms move to the API tables. - consensus: SubmissionError keeps both ConfigUnavailable and CommitContention. - server routes/transact.rs: both submission arms and test rows. - transaction.rs, tx_builder.rs: main's txn_attempts loops, with this branch's request-governance argument on every stage_plan / stage_all call.
Stacked on #2053, which gives each leaflet a single cache entry. This PR uses that entry to see which columns readers had cached for a leaflet, and carries them over.
Summary
Warm-on-write (#1415) decodes every leaflet of every leaf an incremental build rewrites, with all columns, on a
spawn_blockingtask per leaf with no concurrency limit. Under sustained writes that is far more decoding than readers use:On BSBM 100M Update with smaller leaflets, it pushes the server out of memory.
Warming now carries over only what readers had cached for the leaf being replaced:
update_leafrecords, for each new leaflet, which leaflet of the replaced leaf it came from and whether it is a byte copy (LeafletOrigin). The branch update attaches the replaced leaf's CID to each new leaf.debug!event, and its first reader decodes it, so a large build can't queue unbounded decode work.Measurements
BSBM 100M Explore-and-Update, 1 client, background indexing on, cache pinned at 22,000 MB, on a 64 GB box. Three rotated runs per cell; medians shown. "Previous" is warm-on-write as it is on
main.The read-after-swap profile from #1415 (
reindex_swap_read_profile) measures what warming is for: reading an existing product whose leaf was just rewritten. Median p50 in ms:Tests
update_records_each_leaflets_origin: an insert that splits one leaflet in two records[copied 0, re-encoded 1, re-encoded 1, copied 2].warm_carries_only_cached_leaflets_to_the_rewritten_leaf:With the previous warm-everything behaviour restored, it fails on "never read, never warmed". With two re-encoded leaflets' batches swapped, it fails on the row comparison.