Skip to content

perf(query): count NumBig distinct objects from arenas, drop the row cap - #1803

Merged
bplatz merged 2 commits into
mainfrom
investigate/truthy-count-distinct-object-regression
Sep 10, 2026
Merged

bplatz merged 2 commits into
mainfrom
investigate/truthy-count-distinct-object-regression

Conversation

@bplatz

@bplatz bplatz commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The 4.2.0 Sparqloscope refresh on Wikidata Truthy lost number-of-objects (SELECT (COUNT(DISTINCT ?o) AS ?count) WHERE { ?s ?p ?o }): 20.8 ms on 4.0.6, no response within the 300 s client limit on 4.2.0. Report: benchmark-db/runs/v420-suite-refresh-20260907/truthy-regression-report.md.

The whole-graph distinct-object fast path was gated on NumBig objects in 388bbd5 / 0b41e8b (in 4.1.6 and 4.2.0). That gate was correct to add: the 10-byte OPST lead is a per-predicate arena handle for NUM_BIG_OVERFLOW rows, so the 4.0.6 answer was a silent undercount. But the exact branch row-scanned the NumBig slice and declined above 25M NumBig rows as a rollout guard. Every xsd:decimal is arena-routed, Wikidata quantities exceed the cap, and the query fell to the general pipeline over 8.18B rows.

Fix

The NumBig arenas are already resident in memory, one per (g_id, p_id), deduplicated on a normalized value repr. The branch now reads arenas instead of rows and dedups across predicates on a compact key with a parallel sort.

Arena membership cannot say liveness: an arena keeps a handle for a value whose rows were retracted (a full rebuild replays retractions through the same insert path; an incremental build carries arenas forward). Liveness is proved per predicate from POST directory metadata: distinct live handles is the lead-group count over the predicate's type-pure NumBig leaflets with seam dedup, and when it equals the arena's size every entry is live with no column read. Only a predicate with stale handles reads its o_key column, over its own NumBig rows. A leaflet that straddles the NumBig range (a predicate carrying several datatypes) is decoded.

The row cap is removed. FLUREE_NUMBIG_EXACT_MAX_ENTRIES caps total arena entries and is unset by default: declining is the expensive outcome, since the fallback materializes every object in the graph.

The loader records whether every stored decimal is already normalized. Those arenas build distinct keys directly from stored bytes, without allocating for inline keys. Legacy arenas retain normalization during key construction; having no duplicate handles is not sufficient to take the shortcut.

New surface: StoredBigValue::normalized_repr, NumBigArena::values_are_normalized, BinaryIndexStore::numbig_arenas.

Measurements

Measurements recorded before the stored-byte shortcut; these timings have not been rerun for that optimization.

Release build, 1M decimal rows across 4 predicates (values overlapping across predicates) plus 500k strings:

Lane Time
Fast lane 20 ms
Stale-handle lane (after retractions, every arena stale) 33 ms
General pipeline (forced decline) ~1.5 s

Not run against the Wikidata ledger (terminated after the suite). On a graph with tens of millions of live arena entries, every execution builds keys and pays a parallel sort over those entries; the result is not cached. Expect hundreds of milliseconds rather than the old 20 ms, which was a wrong answer. The acceptance target should be agreement with the general pipeline, not the 4.0.6 number.

The key vector holds one key per live arena entry before cross-predicate deduplication, so repeated values across predicates each occupy a slot. On typical 64-bit targets, keys occupy 48 bytes each (about 1.44 GB for 30M live entries), excluding wide-value allocations, spare vector capacity, and temporary buffers. This is not a guarantee that peak memory is always lower than the general pipeline. Predicates with stale handles also scan their NumBig rows, and mixed-type or legacy leaflets may require decoding to establish liveness.

Tests

it_distinct_object_numbig_gate gains a mixed-datatype predicate fixture (POST leaflets are predicate-homogeneous but not type-homogeneous, so this yields an o_type-column leaflet that takes the decode arm) and a retract → rebuild → retract → incremental phase pinning fast == general == truth with the exact-branch stamp on each. Both were verified non-vacuous by sabotaging the liveness proof and the decode classification separately; a combined sabotage masks the second, which is worth knowing if the test is revisited.

The lifecycle checks now run against both decimal-only and mixed-datatype fixtures, covering the stale-handle lane with a real o_type column while preserving the numeric ordering fixture. Removing only the stale-lane datatype filter makes the mixed fixture return 9 instead of 8 after rebuild and 6 instead of 5 after incremental indexing; restoring the filter returns the test to green.

Unit tests cover normalization status on loaded modern and legacy arenas (including legacy values without duplicate handles), signed and wide key boundaries, normalized key agreement, and handle-count seams and empty chunks. All 15 targeted NumBig unit tests, the all-features API integration test, package-scoped clippy with -D warnings, formatting, and diff checks pass locally.

End-to-end integration coverage still does not construct leaves that predate lead_group_count or legacy scale-variant arenas. Per-store count caching and a maintained whole-graph NumBig distinct-count benchmark with a regression-budget entry remain deferred.

Whole-graph COUNT(DISTINCT ?o) declined to the general pipeline on any
graph holding more than 25M NumBig rows, because the exact branch added
in 388bbd5/0b41e8b4d row-scanned the NUM_BIG_OVERFLOW slice and capped
itself as a rollout guard. Every xsd:decimal is arena-routed, so on
Wikidata Truthy the Sparqloscope number-of-objects query fell from 20 ms
to a full 8B-row scan that exceeded the 300 s client limit in the 4.2.0
suite run (4.1.6 carries the same commits).

The NumBig arenas are already resident in memory, one per (g_id, p_id),
deduplicated on a normalized value repr. The union of their entries is
the set of distinct big-numeric terms the index has ever held, so the
branch now reads arenas instead of rows and dedups across predicates on a
compact key with a parallel sort. The one thing arena membership cannot
say is liveness: an arena keeps a handle for a value whose rows were
retracted (a full rebuild replays retractions through the same insert
path; an incremental build carries arenas forward). That is proved per
predicate from POST directory metadata — distinct live handles is the
lead-group count over the predicate's type-pure NumBig leaflets with seam
dedup, and when it equals the arena's size every entry is live with no
column read. Only a predicate with stale handles reads its o_key column,
and only over its own NumBig rows. A leaflet that straddles the NumBig
range (a predicate with several datatypes) is decoded; POST leaflets are
predicate-homogeneous but not type-homogeneous.

The row cap is removed. FLUREE_NUMBIG_EXACT_MAX_ENTRIES caps the total
arena entries the branch will take on and is unset by default: declining
is the expensive outcome, since the fallback materializes every object in
the graph.

Release build, 1M decimal rows across 4 predicates plus 500k strings:
fast lane 20 ms, stale-handle lane 33 ms, general pipeline ~1.5 s.

The gate test gains a mixed-datatype predicate fixture and a retract →
rebuild → retract → incremental phase pinning fast == general == truth
with the exact-branch stamp on each; both were verified non-vacuous by
sabotaging the liveness proof and the decode classification separately.
@bplatz bplatz added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Sep 7, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 7, 2026 19:10

@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 all looks good to me, @bplatz -- no objections or disagreements with objective or implementation design. Claude found some minor items possibly worth fixing before merge, so I'll include the Claude review verbatim below:


This is very good — reading the arenas as the distinct-value sets and then proving liveness from POST directory metadata instead of touching rows is the right altitude for this, and the seam-dedup partial mirroring LeadGroupPartial keeps it in the family of the existing metadata walks rather than adding a parallel construct. I attacked the two ways this could silently disagree with the general pipeline — term identity (scale variants, zero, BigInt vs BigDecimal at the same magnitude, an i64-fitting integer narrowing to Long, the lost declared datatype) and the live == arena.len() equality proof (seam across retracted-to-empty leaflets, straddling leaflets, legacy lead_group_count) — and every one resolves to agreement, because both lanes derive from the same normalized() and the resolver never arena-routes anything the general lane would narrow. Dropping the 25M row cap is structurally safe: the lane's work is bounded by distinct live NumBig values plus, for a stale predicate, its own NumBig rows, both subsets of what the fallback scans and materializes, so declining really is the expensive outcome in every case. The notes below are about the memory/time profile of the new lane (48 B per key and a full BigDecimal round-trip per entry, paid on every execution — the body's "first run" undersells that), one uncovered arm in the stale-handle lane, and a couple of doc/name nits.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends leaf_entries_for_predicate / parallel_leaf_chunk_reduce / lead_group_count and the correctness-preserving Ok(None) fallback; normalized_repr is shared with the loader rather than re-derived; no parallel dispatch, no JSON-LD/SPARQL parity concern (IR-level).
  • Performance (speed first, memory second): ✔ headline path goes from a full-graph scan to an arena-bounded lane; no other hot path touched. Memory: per-query transient of 48 B × distinct live NumBig values (~1.4 GB at 30M), uncached, strictly less than the fallback — no performance-degradation risk against base, with the cheap keys-from-stored-bytes / memo improvements noted inline.
  • Testing: ✔ it_distinct_object_numbig_gate is a real [[test]] target under --all-features in CI; passes at HEAD and goes red under each sabotage separately (and, with my sabotage forms, together). ⚠️ the stale-lane × straddling-leaflet arm is uncovered (one fixture line), no unit pins on the pure helpers, and no bench covers whole-graph COUNT(DISTINCT ?o) — query_hot_whole_graph_agg is Cypher per-property, so the body's timings are the only numbers this lane has; a NumBig-bearing case there (plus its regression-budget.json entry) would put it under the nightly.
  • Conventions: ✔ thorough multi-line commit body; cargo fmt --check and package-scoped clippy -D warnings clean locally; kill switch undocumented (one line in docs/query/explain.md), test name now inverted.

Verified locally at branch HEAD (5826279fd): gate test green; liveness-proof sabotage → red (8 vs 7, 5 vs 4); decode-classification sabotage → red (3 vs 4); fmt clean; clippy -D warnings clean for the three touched crates; numbig and fast_count / group_aggregate unit tests green; standalone key-derivation bench 10M entries ≈ 435 ms on 16 threads.

Approving so you can merge when ready, but maybe worth folding in the fixture line and the keys-from-stored-bytes shortcut first — both are small and this is the PR where they'll actually get done.

continue;
}
if live == arena.len() as u64 {
keys.par_extend(

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.

fluree-db-query/src/fast_count.rs:1290 — optional, performance (memory second axis). I don't think this is a regression against base — the fallback materializes every distinct object in the graph, which is strictly worse — but it seems worth being precise about what the new lane costs, because the PR body's "on the first run pays a parallel sort" reads as if later runs are cheaper, and as written they aren't: count_distinct_numbig_objects runs inside the operator closure on every execution and nothing memoizes it on the store.

Two pieces to the cost. NumBigDistinctKey is 48 bytes (i128 alignment), so the keys Vec is 48 B × distinct live NumBig values — ~0.5 GB transient at 10M entries, ~1.4 GB at 30M. And every entry goes through normalized_repr, which is BigInt::from_signed_bytes_le → BigDecimal::new → normalized() → to_signed_bytes_le, four allocations plus a radix conversion, even though every arena written since normalization landed already stores the normalized form (get_or_insert_bigdec persists normalized().as_bigint_and_exponent(), numbig.rs:166-181). Measured standalone on this 16-thread machine: 10M entries → 327 ms for keys + 108 ms for the sort; keying straight from the stored bytes brings the whole thing to 210 ms.

Two cheap directions, either or both: (a) the loader already computes the raw and normalized reprs side by side (numbig.rs:418-426), so it could record whether the arena is already normalized and let this lane build Dec(i128_from_signed_le(unscaled), scale) straight from StoredBigValue when it is, falling back to normalized_repr only for a legacy arena; (b) memoize the per-graph count on the store — BinaryIndexStore already carries lazily-derived data this way (p_sid_table: OnceLock at binary_index_store.rs:319) and the store is immutable per index root, so a repeat of the Sparqloscope query would be directory-only again. Minor and non-blocking — but if you agree it's right, I'd rather see (a) at least 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 cb440ee

Implemented the stored-byte shortcut using normalization status verified by the loader, with legacy normalization preserved. Corrected the recurring sort cost and pre-dedup memory description in the code and PR body. Per-store count memoization remains deferred.

@@ -126,6 +127,17 @@ const F_BIGINT_CROSS: &str = r#"
<http://ex/s2> <http://ex/p2> "170141183460469231731687303715884105999"^^<http://www.w3.org/2001/XMLSchema#integer> .

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.

fluree-db-api/tests/it_distinct_object_numbig_gate.rs:111 — optional, coverage. Claude caught this while I was tracing which fixture reaches which arm: the stale-handle lane's per-row o_type filter (fast_count.rs:1561) never runs against a real o_type column. F_MIXED_PRED has no retraction, so live == len and it never enters live_numbig_handles; F_LIFECYCLE is decimal-only, so its leaflets are type-pure and batch.o_type.get_or(row, o_type_default) is answered by o_type_const, never the column. So the one combination that exercises the fallback's decode path on a straddling leaflet — stale arena and mixed datatypes under one predicate — is uncovered.

It's a one-line fixture change: add <http://ex/a6> <http://ex/p1> "alpha" . to F_LIFECYCLE and bump the three truths (8 → 9, 7 → 8, 4 → 5). I'd rather see it in this PR than tracked-and-forgotten, since it pins the arm the body calls out as the subtle one.

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 cb440ee

Added a separate mixed-datatype lifecycle fixture alongside the decimal-only fixture, preserving its numeric ordering check. Verified that removing the stale-lane datatype filter fails after both rebuild and incremental indexing; the restored implementation passes.

for row in 0..batch.row_count {
handles.insert((batch.p_id.get_or(row, 0), batch.o_key.get(row)));
}
fn i128_from_signed_le(bytes: &[u8]) -> Option<i128> {

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.

fluree-db-query/src/fast_count.rs:1347 — optional, testing. This is more of a suggestion than a request. The integration test proves the composition end to end (and goes red under both sabotages — I reproduced them), but the pure pieces have no unit pins: i128_from_signed_le sign extension at 1, 8 and 16 bytes and the > 16 wide arm; NumBigDistinctKey::from_repr injectivity at the 16-byte boundary; NumBigHandlePartial::push_run / combine on a seam, on an empty left side, and on two chunks whose boundary handles differ. A future red on this lane would localize a lot faster with those. Minor, fold-in-now if you agree.

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 cb440ee

Added unit coverage for signed and wide key boundaries, normalized key agreement, seam deduplication, empty chunks, and disjoint chunk boundaries.

/// branch capped on NumBig *rows* (25M) and declined above it, which on a
/// Wikidata-scale ledger turned a 20 ms count into a full scan that timed out
/// at 300 s.
fn numbig_exact_max_entries() -> Option<u64> {

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.

fluree-db-query/src/fast_count.rs:1196 — optional, docs. FLUREE_NUMBIG_EXACT_MAX_ENTRIES appears only here and in the test; docs/query/explain.md:297 documents its sibling FLUREE_CYCLIC_BGP_MAX_ROWS, so one line there ("unset by default; declining is the expensive outcome") would keep an operator from having to grep for it. Commenting here because docs/query/explain.md is not in this diff.

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 cb440ee

Documented the entries cap, unset default, forced fallback, replacement of the old row cap, and recurring execution costs in docs/query/explain.md.

@@ -367,8 +385,8 @@ async fn distinct_object_count_declines_numbig_object_keys() {
let took_exact = sites.iter().any(|s| s == EXACT_SITE);

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.

fluree-db-api/tests/it_distinct_object_numbig_gate.rs:339 — nit. The test is still named distinct_object_count_declines_numbig_object_keys and now asserts the opposite (Phase 1's failure text even says "nothing here may decline"). Something like distinct_object_count_counts_numbig_object_keys_exactly would stop the next reader from second-guessing which way the pin points.

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 cb440ee

Renamed the test to distinct_object_count_counts_numbig_object_keys_exactly and corrected the stale decline comments.

@@ -1958,6 +1958,18 @@ impl BinaryIndexStore {
}

/// Reverse subject lookup by namespace parts (avoids IRI construction).

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.

fluree-db-binary-index/src/read/binary_index_store.rs:1960 — nit, pre-existing. Your change didn't introduce this, but the stray doc line "Reverse subject lookup by namespace parts (avoids IRI construction)" now heads numbig_arenas (it was already orphaned above find_numbig_handle at base). Since you're touching the spot, worth deleting it.

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 cb440ee

Removed the unrelated reverse-subject-lookup doc line above numbig_arenas.

if live == 0 {
continue;
}
if live == arena.len() as u64 {

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.

fluree-db-query/src/fast_count.rs:1289 — praise. The live == arena.len() proof is sound and I want to say why so nobody "simplifies" it later: live handles are a subset of arena handles (anything else is an inconsistent index, which the fallback lane surfaces as an error rather than a wrong count); the live count can't double-count because push_run dedups the seam and an empty-after-retract leaflet between two that share a handle is skipped without resetting last; and it can't miss because NOT_GLOBALLY_IDENTIFYING == [NUM_BIG_OVERFLOW] makes the OPST skip set exactly the arena-served rows while p_const is always Some on POST. Equal cardinalities on a subset relation is equality of sets.

},
[raw_repr, norm_repr],
);
let norm_repr = stored.normalized_repr();

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.

fluree-db-binary-index/src/arena/numbig.rs:425 — praise. Having the loader call normalized_repr means the arena's own dedup key and this lane's dedup key are literally one function. That, plus the general lane keying Decimal on normalized().to_string(), is why the two lanes can't drift on scale variants — and bigdecimal's normalized() collapsing every zero to scale 0 closes the 0.000 vs 0 case for free.

Record whether every decimal in a loaded arena is already normalized and
construct distinct keys directly from stored bytes when it is. Inline
keys avoid decimal reconstruction and allocation; legacy arenas retain
normalization, including those with no duplicate handles.

Exercise mixed-datatype stale arenas through rebuild and incremental
indexing without changing the decimal-only ordering fixture. Add unit
coverage for normalization status, signed and wide numeric keys, and
handle-count seam reduction. Document the entries cap and recurring
memory and row-scan costs, and clean up stale names and comments.

Validation: 15 targeted NumBig unit tests and the all-features API
integration test pass. Removing the stale-lane datatype filter makes the
new mixed fixture fail after both rebuild and incremental indexing;
restoring it returns the test to green. Package-scoped clippy with
-D warnings, cargo fmt --all --check, and git diff --check pass.
@bplatz

bplatz commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f Addressed in cb440ee. Replied to each of the six actionable inline comments with the corresponding changes.

Not addressed in this update:

  • Per-store/per-graph count memoization. Key construction and sorting still run on every execution; the recurring cost is now explicit in the documentation.
  • A maintained whole-graph NumBig COUNT(DISTINCT ?o) benchmark and its regression-budget entry. The existing timings remain observations from before the stored-byte shortcut, not new measurements.

These remain follow-ups. Historical leaflet metadata and legacy scale-variant arenas also still lack end-to-end integration fixtures; legacy normalization is covered at the unit level.

Validation: 15 targeted NumBig unit tests and the expanded all-features integration test pass. The missing-datatype-filter mutation is caught after both rebuild and incremental indexing. Package-scoped clippy with -D warnings, formatting, and diff checks pass locally.

@bplatz
bplatz merged commit 637ed8f into main Sep 10, 2026
16 checks passed
@bplatz
bplatz deleted the investigate/truthy-count-distinct-object-regression branch September 10, 2026 13:25
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 bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants