Skip to content

perf(indexer): warm-on-write only the leaflets readers had cached, on a bounded pool - #2068

Merged
bplatz merged 4 commits into
mainfrom
perf/selective-warm-on-write
Oct 13, 2026
Merged

bplatz merged 4 commits into
mainfrom
perf/selective-warm-on-write

Conversation

@bplatz

@bplatz bplatz commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

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_blocking task per leaf with no concurrency limit. Under sustained writes that is far more decoding than readers use:

  • It fills the shared cache with leaflets nobody reads, which evicts what readers do read, dictionary leaves among them.
  • It queues decode work without limit.

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:

  • Origins. update_leaf records, 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.
  • Copied leaflets. If the source was cached, the new leaflet takes the cached batch and its columns under the new key, with no decode.
  • Re-encoded leaflets. If the source was cached, the new leaflet is decoded for the columns that were cached. Decoding runs on a pool of a quarter of the cores. When the pool is busy the leaf is skipped, with a debug! event, and its first reader decodes it, so a large build can't queue unbounded decode work.
  • Leaflets no reader touched are not warmed.
  • Leaf directory. It is seeded whenever any of the leaf's leaflets is.
  • Reverse-dictionary warming only copies raw bytes, and is unchanged.

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.

Rows per leaflet Warm-on-write Query mixes/hour Peak RSS Bytes decoded by warming Dictionary re-reads
25,000 (default) previous 7,467 55.9 GB 135 GB 220 GB
25,000 (default) this PR 10,274 40.6 GB 5.1 GB 25 GB
25,000 (default) off 9,995 43.6 GB 0 20 GB
8,192 previous out of memory (3/3) 60+ GB — —
8,192 this PR 10,271 39.3 GB 1.7 GB 64 GB
4,096 previous out of memory (3/3) 60+ GB — —
4,096 this PR 10,263 40.0 GB 0.9 GB 33 GB
  • At most 4 warm tasks ran at once, where the previous code reached 46–137.
  • The pool skipped 5 leaves in a whole 25,000-row run.

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:

Rows per leaflet Previous This PR Off
25,000 0.091 0.033 0.035
8,192 0.063 0.035 0.167
4,096 0.044 0.056 0.160
  • With this PR the harness's cache ends about 4× smaller (145–174 MB against about 645 MB), and its index builds run about 10% faster.
  • A product that was itself just written reads at about 0.3 ms in every mode, so warming never helped that case.

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:

    • a copied leaflet takes its cached columns without a decode;
    • the re-encoded halves are decoded for the cached columns;
    • a leaflet no reader touched stays cold;
    • the directory is seeded;
    • every warmed batch holds the new leaf's rows, compared with a fresh decode.

    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.

… 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.
@bplatz bplatz added area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches performance Performance improvement (release notes: Performance) labels Oct 11, 2026
@bplatz
bplatz requested a review from a team October 11, 2026 17: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 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_cid is set only in drain_touched_output, which the serial and parallel drains share, and only update_leaf / NewLeafBlob::fresh build a NewLeafBlob. 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. Inverting copied turns both your tests red, and restoring warm-everything fails warm_carries_only_cached_leaflets_to_the_rewritten_leaf on "never read, never warmed".
  • The bound. A process-global cores/4 semaphore with try_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 release plan job.
  • 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 {

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

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 bd1525b

);

let columns = |idx| cache.v3_leaflet_entry(new_id, idx).map(|(c, _)| c);
assert_eq!(columns(0), Some(ColumnSet::CORE), "copied without a decode");

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

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 bd1525b

…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.
Base automatically changed from perf/narrow-count-decodes to main October 13, 2026 18:41
@bplatz
bplatz merged commit 5b104ca into main Oct 13, 2026
19 checks passed
@bplatz
bplatz deleted the perf/selective-warm-on-write branch October 13, 2026 19:30
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.
aaj3f added a commit that referenced this pull request Oct 14, 2026
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.
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