Repository navigation
perf: decode only the columns count fast paths read; one cached entry per leaflet - #2053
Conversation
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.
aaj3f
left a comment
There was a problem hiding this comment.
@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
wantinstead ofmissing, and a torn widen where the tag grows but the batch doesn't. Racing widenings can re-decode a column or drop a widening, butcolumnsalways 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_batchread throughget, which panics on an absent column rather than defaulting.load_v6_batch'sget_orreads are exactly the columnsneededadds. - 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( |
There was a problem hiding this comment.
🟡 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.
|
|
||
| /// Insert `widened` unless a concurrent widening already covers it, | ||
| /// keeping any columns that one added. | ||
| fn store_widened(&self, slot: V3LeafletKey, widened: CachedV3Batch) { |
There was a problem hiding this comment.
❓ 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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
🟡 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.
| handle.as_ref(), | ||
| idx, | ||
| if mixed { | ||
| &proj_sid_otype_okey |
There was a problem hiding this comment.
🟡 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.
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.
…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.
Summary
Two changes to how decoded leaflets are read and cached:
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.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
ALLbatch could serve a narrower read. This already happened onmain: a read without thetcolumn and a full read kept separate copies. Each leaflet now has one entry that records which columns it holds:The entry records its column set explicitly because
ColumnData::AbsentDefaultcan 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:
mainmain(3 rotated rounds)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_decodestill holds.it_fastpath_1652_regressiongains an OPTIONAL chain head through a predicate whose objects mix IRIs and literals. Its mixed leaflets reachPsotSubjectWeightedSumIter's mixed-type projection, which the cached path now decodes too and which no test reached. Witho_typedropped from that projection, the case panics on the absent column.