Skip to content

perf: decode only the columns count fast paths read; one cached entry per leaflet - #2053

Merged
bplatz merged 5 commits into
mainfrom
perf/narrow-count-decodes
Oct 13, 2026
Merged

bplatz merged 5 commits into
mainfrom
perf/narrow-count-decodes

Conversation

@bplatz

@bplatz bplatz commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two changes to how decoded leaflets are read and cached:

  1. Count fast paths decode only the columns they read. When a leaflet cache was present, these fast paths decoded every column of each leaflet, while their uncached paths decoded only what they read: PsotSubjectCountIter, PsotSubjectSeek, PostObjectGroupCountIter, PsotSubjectWeightedSumIter, the count-plan chain cursor, and the group-count-firsts loader. They now share one helper that requests just their projection from the cache.

  2. One decoded-leaflet cache entry per leaflet. Cache entries were keyed by column set, so a leaflet read with two different projections was decoded and cached twice, and only a cached ALL batch could serve a narrower read. This already happened on main: a read without the t column and a full read kept separate copies. Each leaflet now has one entry that records which columns it holds:

    • A read those columns cover is served from the entry, projected to what it asked for. A hit consumes the entry the cache handed out rather than cloning its batch again.
    • A wider read decodes only the missing columns and widens the entry.
    • A cold leaflet's first decode stays single-flight.

    The entry records its column set explicitly because ColumnData::AbsentDefault can mean either "not decoded" or "every value is the sentinel".

Change 1 needs change 2. On its own, a count query that ran first left a narrow entry, and a later full read decoded and cached the same leaflet again, so total decode work went up.

Measurements

DBLP-core (561M triples, 105 SPARQLoscope queries), 25,000-row leaflets, one EC2 box:

main change 1 only change 1 + 2 (this PR)
Bytes decoded, fixed-order pass on a fresh server 18.56 GB 19.13 GB 15.98 GB (−14%)
Peak RSS, same pass 18.1 GB 17.0 GB 14.7 GB (−19%)
Latency, geometric mean vs main (3 rotated rounds) — 1.006× 1.007×
  • Latency differences are within the 1–2% spread between rounds.
  • All 105 query outputs are byte-identical across the three builds.
  • On a count-heavy aggregate over the Pokec social graph, change 1 cut decoded bytes from 4.0 MB to 1.6 MB, with latency unchanged.

Tests

  • test_v3_batch_widens_one_entry_decoding_only_missing_columns: a narrow read, then a full read, decodes the narrow columns once and then only the missing ones. The leaflet keeps a single entry, and a later narrow read is served without decoding. With the wide read changed back to decoding every column, the test fails.
  • test_v3_batch_insert_joins_existing_columns: warm-on-write inserts join a leaflet's existing columns, and a set that was never decoded is not reported as covered.
  • test_v3_batch_superset_serves_narrow_without_decode still holds.
  • it_fastpath_1652_regression gains an OPTIONAL chain head through a predicate whose objects mix IRIs and literals. Its mixed leaflets reach PsotSubjectWeightedSumIter's mixed-type projection, which the cached path now decodes too and which no test reached. With o_type dropped from that projection, the case panics on the absent column.

With a leaflet cache, PsotSubjectCountIter, PsotSubjectSeek,
PostObjectGroupCountIter, PsotSubjectWeightedSumIter, the count-plan
chain cursor and the group-count-firsts loader decoded every column,
while their uncached paths decoded just the projection. Route all of
them through one helper that keys the cache on the projection; a cached
ALL batch still serves the narrow request.
…demand

The decoded-leaflet cache keyed batches by column set, so a leaflet read
with two projections was decoded and cached twice, and only a cached ALL
batch could serve a narrower read. Now each leaflet has one entry tagged
with the columns it holds: a read those columns cover is served projected,
and a wider read decodes only the missing columns and widens the entry.
A cold leaflet's first decode stays single-flight.
@bplatz bplatz added area:query Query execution, planning, fast paths, overlay, result formatting performance Performance improvement (release notes: Performance) labels Oct 11, 2026
@bplatz
bplatz requested a review from a team October 11, 2026 00:30

@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 at a design level no pushback from me. One entry per leaflet with an explicit column tag is the shape I'd have picked too, and I measured main against this head on the cache API: half the entries and bytes for the same reads. One headline question, about altitude rather than this diff. load_leaflet_projection is now the one helper for the six count lanes, but about twenty other fast-path loads still call handle.load_columns directly and never see the cache (fast_count.rs, fast_string_fold.rs, fast_min_max_string.rs, fast_post_order_limit.rs, PsotObjectFilterCountIter, …). Before this PR that was arguably the safer default, since a narrow cached read could duplicate a leaflet. Now a narrow read gets served by whatever a scan already decoded. Is keeping those lanes uncached deliberate (one-pass aggregates shouldn't fill the cache)? If so, could the helper's doc say which lanes go through it and why? Not for this PR either way. #2068 stacks on this one, so this merges first.

Full review below:


✅ Approve with nits.

This is really nice, @bplatz. One entry per leaflet with an explicit column tag is the right shape, and the tag is necessary because AbsentDefault means two things. Making the six cached count lanes decode what their uncached twins always did also removes a quiet split between the two paths. I checked the cache under concurrency and eviction and measured main against this head; nothing below blocks.

What I checked:

  • The shared entry. A scratch stress test never served a missing or wrong column: 8 threads × 20k random projections over 4 leaflets, once with a roomy cache and once with one small enough to evict constantly. Your tests catch all three mutations I tried: serving an uncovered entry, decoding want instead of missing, and a torn widen where the tag grows but the batch doesn't. Racing widenings can re-decode a column or drop a widening, but columns always describes exactly what the batch holds.
  • The count lanes. I traced each of the six against the columns its consumer reads, and all match. All but load_v6_batch read through get, which panics on an absent column rather than defaulting. load_v6_batch's get_or reads are exactly the columns needed adds.
  • Performance, measured (dev-fast, 25,000-row leaflets). A 4-read sequence over 200 leaflets decodes 2,000 columns into 400 entries / 180 MB on main, and 1,200 columns / 200 entries / 100 MB here. Superset hits went from ~141 to ~97 ns. Exact hits went from ~86 to ~98 ns; the inline note has a fix.

The inline notes cover the exact-hit double clone, two comments that still describe commit 1's model, a question on entries only growing, and a mixed-datatype branch in the weighted-sum lane that no test reaches.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends LeafletCache's single-flight entry rather than adding a second cache, and routes the six lanes through one helper.
  • Performance (speed first, memory second): ✔ no regression of consequence. Less decoding, half the cached copies, faster superset hits; exact hits are ~12 ns slower per leaflet read (fix inline).
  • Deployment targets: ✔ the cache is per process and content-addressed (leaf CID + leaflet index) and reaches every host. wasm32 clippy and wasm-smoke were green in CI on this head. Nothing assumes a long-lived process or memory shared across processes.
  • Testing: ✔ the two new cache tests have teeth (three mutations caught), and CI ran them by name. ⚠️ No test reaches the weighted-sum lane's mixed-datatype branch.
  • Conventions: ✔ multi-line commit bodies; fmt/clippy green in CI.

Verified locally at 091bd8a91: cargo fmt --check; cargo test -p fluree-db-binary-index -p fluree-db-query --lib (415 + 1,667 passed); fluree-db-api grp_query/grp_misc/grp_query_sparql/grp_index/it_count_datatype_pin/it_fastpath_1652_regression/it_fastpath_1863_regression all green. One tracing-capture test in grp_query is order-dependent under cargo test; it passes alone and in CI's nextest, and is unrelated.

Approving so you can merge when ready, but maybe worth considering a few of these first.

}

impl CachedV3Batch {
fn serve(

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: an exact hit now clones the batch twice.

get_v3_entry already hands back an owned CachedV3Batch (moka clones it out on get). On the columns == want path, serve(&self, want) then clones self.batch a second time. So every exact hit pays a second round of Arc increments, plus the matching decrements when the intermediate drops.

I measured it with a scratch bench on the cache API (dev-fast, 25,000-row leaflets, best of 7 × 2M hits, three runs each). An exact hit takes ~86 ns on main and ~98 ns here. The superset hit got nicely faster (~141 → ~97 ns, one lookup instead of two). Moving the batch out instead of cloning it brought the exact hit back to ~89.5 ns. This is per leaflet read, not per row, so I don't think it matters much in practice.

Minimally, the two hit paths could consume the entry they already own. Illustrative only (the widen path would keep using serve(&self) since it still stores widened):

fn into_served(self, want: ColumnSet) -> Option<ColumnBatch> {
    if self.columns == want {
        Some(self.batch)
    } else if self.columns.covers(want) {
        Some(self.batch.project_to(want))
    } else {
        None
    }
}

// try_get_or_decode_v3_batch, before the widen branch:
if entry.columns.covers(want) {
    return Ok(entry.into_served(want).expect("covered"));
}

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 75803d2


/// Insert `widened` unless a concurrent widening already covers it,
/// keeping any columns that one added.
fn store_widened(&self, slot: V3LeafletKey, widened: CachedV3Batch) {

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.

❓ Question: an entry only ever grows. Did you look at a mostly-narrow workload with occasional wide reads?

With one entry per leaflet, a one-off wide read widens the entry to carry t/o_i. That covers a time-travel query, and also any leaflet read while overlay ops are pending, since leaflet_decode_set returns ALL under has_ov. Every later narrow reader then keeps those columns resident for as long as the leaflet stays hot. On main the ALL copy was its own entry and could age out under TinyLFU while the narrow one stayed. Against a CORE entry that's roughly +22% to +50% bytes per entry (t is 4 B/row, plus 4 more when o_i is a block, over 16–18 B/row of s_id/o_key/o_type).

Your DBLP pass says it's a net win (−14% decoded bytes, −19% peak RSS), and under sustained writes it's clearly better than holding two copies. This is more of a question than a suggestion. I'm curious whether a read-mostly ledger with the occasional history query shows the opposite, and whether a narrowing path would be worth having if it does.

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.

Not measured. A widened entry is re-inserted, so TinyLFU weighs it at its new size rather than the narrow one, and the main source of wide reads you name (leaflet_decode_set returning ALL under pending overlay ops) clears once the overlay is indexed. I haven't run a read-mostly ledger with occasional history queries, and I'd want that measurement before adding a narrowing path.

}
}

/// Decode `projection`'s columns of leaflet `idx`, through the leaflet cache

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.

🟡 Nit: this doc describes commit 1's cache model, which commit 2 replaced.

The doc still says "The cache key carries the column set, so a narrow request is served by an exact or ALL entry". After 9b8fd3e89 the key is the leaflet. A narrow request is served by whatever columns that leaflet's one entry holds, and a request the entry doesn't cover widens it with just the missing columns.

fluree-db-query/src/fast_group_count_firsts.rs:1007-1010 has the same problem: "the cached path always loads p_id" is no longer true. It's still harmless, since needed adds p_id exactly when p_const is None. Commenting here because that line is not in this diff.

Something like: "Decode projection's columns of leaflet idx, through the leaflet cache when the store has one: an entry that covers them serves them projected; one that falls short decodes only the missing columns into it." Minor and non-blocking, but 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 75803d2

handle.as_ref(),
idx,
if mixed {
&proj_sid_otype_okey

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: nothing reaches this mixed-datatype branch, and the cached path now depends on its projection.

Before this PR the cached path decoded ALL here, so the mixed projection only mattered without a cache. Now it's what every API caller decodes. I swapped &proj_sid_otype_okey for &proj_sid_okey and ran grp_query, grp_misc, grp_query_sparql, grp_index, it_count_datatype_pin and it_fastpath_1652/1863; everything stayed green, and an eprintln! probe on this branch never fired. The same swap on the chain cursor's twin (count_plan_exec.rs:2754) is caught by it_fastpath_1652_regression, as an AbsentDefault panic in PsotSeekSumCursor::seek_sum_for_subject.

A dropped column here would panic rather than mis-count, so the risk is a failed query, not a wrong answer. A one-shape test would pin it next to the 1652 shapes: an indexed OPTIONAL chain whose middle predicate mixes IRIs and literals. 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 75803d2

An exact hit cloned the batch twice: once out of moka, again in `serve`.
The hit paths now consume the entry they already hold, and the widen path
projects the widened batch directly.

Pins `PsotSubjectWeightedSumIter`'s mixed-datatype projection, which the
cached path now depends on: an OPTIONAL chain head through `ex:kind`'s
mixed leaflets. Narrowing that projection to `s_id`/`o_key` panics on the
absent `o_type`.

Also refreshes two comments that still described one cache entry per
column set.
@bplatz
bplatz merged commit 5e634b3 into main Oct 13, 2026
19 checks passed
@bplatz
bplatz deleted the perf/narrow-count-decodes branch October 13, 2026 18:41
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:query Query execution, planning, fast paths, overlay, result formatting performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants