Repository navigation
count the NumBig distinct-object slice exactly instead of declining - #1644
Conversation
The whole-graph COUNT(DISTINCT ?o) fast path declines outright when the graph holds any NumBig object, because the 10-byte OPST lead is a per-predicate arena handle rather than an object identity. Since every xsd:decimal is arena-routed, one decimal column anywhere costs a ledger the metadata-only path entirely. Give the gate a middle branch. The directory walk now excludes NumBig leaflets from the lead-group count and tallies their rows instead, so the non-NumBig part is still answered from metadata alone and the row tally that decides what to do next costs no payload reads. With no NumBig rows the walk answers as before; within the cap the slice is counted exactly and added; above it the query still declines. The exact count reads only the OPST range whose o_type is NUM_BIG_OVERFLOW, located by branch seek rather than a full walk, projecting p_id and o_key alone. Two traps shape it. An arena keeps handles for values whose rows were retracted, so the pairs come from rows present in the index and arena membership is never consulted. And one value under two predicates is two handles in two arenas — while inside a single legacy arena two handles can decode to the same value — so dedup happens on the decoded value, keyed exactly as the general pipeline keys it: normalized decimal lexical plus datatype, via the group-aggregate key. Every NumBig row enters the pipeline tagged xsd:decimal whether the arena holds a BigDecimal or an overflow BigInt, and this mirrors that, so the two lanes cannot disagree. Liveness needs no work here and the reason is worth stating: the branch sits under the same fast_path_store gate as its siblings (single ledger, no from_t, no effective overlay, to_t == max_t, root policy), so base leaflets already reflect current state. It opens leaves with need_replay false and never touches a sidecar.
The suite asserted a two-way gate: decline on any NumBig object, proceed otherwise. There are three outcomes now, and each needs its own pin or the middle one is untested. Every decimal fixture flips from must-not-fire to must-fire on a new site, "distinct object COUNT (numbig exact)", and keeps its hand-computed value — the reported 2-triple, one-predicate, same-value-two-predicates, 3-and-1, 3-and-3, 5-and-4-sharing-one, mixed, and overflow-integer shapes all still answer 2/2/1/4/6/8/8/2 through the new branch, now with the fast path serving them rather than falling through. The overflow-integer fixture is the one that pins the datatype decision: its arena holds a BigInt, but the general pipeline tags every NumBig row xsd:decimal, so keying it as xsd:integer would make the two lanes disagree. It asserts the exact branch and the kill-switch lane return the same value. The no-NumBig controls gain the opposite assertion: the operator proceeds but the exact branch must NOT run, since on those graphs it is pure added cost. And the cap gets a case of its own — a fixture forced over it must decline the whole count to the general pipeline and still answer 6, because declining changes the lane and never the answer. Verified non-vacuous by pinning the cap to zero: all eight must-fire fixtures go red on both the operator stamp and the exact-branch stamp.
zonotope
left a comment
There was a problem hiding this comment.
Approving now, but there are a few things that should be cleaned up before merging.
| /// plus datatype) so the two lanes cannot disagree. Every NumBig row enters the | ||
| /// pipeline tagged `xsd:decimal` regardless of whether the arena holds a | ||
| /// BigDecimal or an overflow BigInt, and this mirrors that. |
There was a problem hiding this comment.
This last sentence isn't completely true. binary_range.rs:730 calls resolve_datatype_sid_for_value, which for NUM_BIG_OVERFLOW falls through resolve_datatype_sid (no match arm → None) to FlakeValue::overflow_numeric_datatype_sid (value.rs:261) BigInt → xsd:integer, Decimal → xsd:decimal.
The hardcoded Explicit(DECIMAL) still produces the right count, but for a different reason than the one given: flake_value_to_key already separates BigInt (discriminant 6) from Decimal (discriminant 5), and in the general lane dtc is a function of that same variant — so a constant dtc yields an identical partition. Worth correcting precisely because the stated reason is what a maintainer would rely on. The test comment inverts the truth: "keying it as xsd:integer would make the two lanes disagree" — it wouldn't; either choice is correct, and the overflow-integer fixture passes for a reason it doesn't pin.
There was a problem hiding this comment.
You are right on both halves, and the correction is in.
I re-checked the chain rather than take it on faith: resolve_datatype_sid_for_value is resolve_datatype_sid(o_type).or_else(|| val.overflow_numeric_datatype_sid()), and that maps BigInt -> xsd:integer, Decimal -> xsd:decimal (value.rs:263). So the doc's "every NumBig row enters the pipeline tagged xsd:decimal" was simply false.
The doc now states the actual reason: flake_value_to_key gives Decimal discriminant 5 and BigInt discriminant 6, and in the general lane the datatype is a function of that same variant — so it separates nothing the discriminant has not already separated, both choices yield the same partition, and only the partition's size is read here.
Your second point was the more useful one: the fixture passes either way, so nothing was holding that invariant down. Added big_decimal_and_big_int_key_apart_regardless_of_datatype in group_aggregate, where the invariant lives rather than where it is consumed. Mutation-checked — collapsing BigInt onto discriminant 5 fails it. Without that, merging the discriminants would silently undercount a graph holding a BigInt and a BigDecimal with one lexical form, and no data fixture would necessarily catch it.
| // Declines to the general pipeline for a graph holding any | ||
| // decimal or overflow integer. |
There was a problem hiding this comment.
We should update this comment because it's now only true above the cap.
There was a problem hiding this comment.
Fixed. It now says the NumBig rows are counted exactly from the arena slice up to numbig_exact_max_rows, and that only a graph exceeding that declines.
| @@ -1186,40 +1232,185 @@ pub(crate) fn count_distinct_lead_groups( | |||
| /// their distinct big-value counts rather than the size of the union: a silent | |||
| /// undercount, never an over-report. | |||
| /// | |||
| /// Rather than special-case the NumBig slice (which needs `p_id` payload reads | |||
| /// and arena loads), decline the whole count to the general pipeline. Ledgers | |||
| /// with no decimals and no overflow integers — the overwhelming majority — keep | |||
| /// the fast path, paying one extra 2-byte comparison per directory entry. | |||
| /// The metadata walk therefore counts only the identifying part of the graph and | |||
| /// reports the NumBig slice's row count separately; [`count_distinct_objects`] | |||
| /// decides what to do with it. | |||
| /// | |||
| /// The per-predicate distinct-object count is unaffected and stays on its fast | |||
| /// path: its 14-byte POST lead starts with `p_id`, which scopes the handle | |||
| /// correctly. So is the distinct-subject count, whose SPOT lead is `s_id`. | |||
| pub(crate) fn count_distinct_object_lead_groups( | |||
| /// Whole-graph distinct objects, counting the NumBig slice exactly rather than | |||
| /// declining the whole query because of it. | |||
| /// | |||
| /// Three outcomes, in the order they are cheapest to establish: | |||
| /// | |||
| /// * no NumBig rows — the metadata walk already answered, unchanged; | |||
| /// * NumBig rows within [`numbig_exact_max_rows`] — add the exact count of the | |||
| /// arena slice, which costs a two-column payload read over *only* those rows; | |||
| /// * more than that — decline, because the general pipeline is scanning | |||
| /// everything anyway and an in-memory distinct set over the slice stops being | |||
| /// the cheaper way to answer. | |||
| /// | |||
| /// The row tally comes from leaflet directory entries, so the threshold is | |||
| /// decided before any payload is touched. | |||
There was a problem hiding this comment.
It looks like the old doc comment was kept after the rename and it was concatenated with the new one.
There was a problem hiding this comment.
Right — two doc blocks with no separator, the pre-rename one running straight into a fresh summary line. Merged into one.
| let p_id = batch.p_id.get_or(row, 0); | ||
| let o_key = batch.o_key.get(row); | ||
| let val = store | ||
| .decode_value_v3(numbig.as_u16(), o_key, p_id, g_id) |
There was a problem hiding this comment.
For each row this call runs a graph_indexes lookup + arena.get_by_handle + to_flake_value() (allocating a BigDecimal/BigInt), then flake_value_to_key allocates a String plus an Arc<str>. Handles repeat heavily. One value under one predicate is one row per subject.
A first pass collecting (p_id, o_key) into a HashSet<(u32, u64)> (Copy, no allocation) and decoding only the survivors collapses that to one decode per distinct handle; worst case costs one extra u64 hash per row. At the 25M-row cap that's the difference between 25M bignum allocations and at most arena-size many.
There was a problem hiding this comment.
Fixed, and thank you for the shape of it — the two-pass version is what landed. Pass 1 collects (p_id, o_key) into a HashSet<(u32, u64)>, pass 2 decodes only the survivors. Decodes are now bounded by the arena's size instead of the slice's row count, for one extra hash per row.
The dedup on decoded values stays where it was, since it is doing something the handle dedup cannot: two legacy handles can decode to the same value, and one value under two predicates is two handles in two arenas. Deduping handles first only removes the repeats that provably cannot differ.
| /// a graph it can be responsible for while it soaks. It is a removal | ||
| /// candidate after a release in production, not a number to tune. | ||
| /// | ||
| /// Overridable so the bench and the regression suite can sweep both sides. |
There was a problem hiding this comment.
Nothing in the repo references numbig or FLUREE_NUMBIG_EXACT_MAX_ROWS except the regression test. The five-row timing table can't be re-derived. Separately, "the fallback … costs more memory than proceeding would have" compares entry counts, not bytes: the general pipeline keys objects as GroupKeyOwned::Lit (a small Copy struct), while this branch stores a MaterializedLitKey holding an Arc<str> per distinct value. At 25M rows that's a multi-GB set. I'd either lower the default or drop the memory half of the argument and keep the (sound) time argument.
There was a problem hiding this comment.
Both halves addressed; I took the "drop the memory argument" option rather than lowering the default.
On memory: your reading holds — I checked, and GroupKeyOwned::Lit is a small Copy struct while MaterializedLitKey carries an Arc<str> per distinct value, so the fallback holds more entries but smaller ones. Which side wins depends on how many rows are distinct, so the doc now makes no memory claim and the time argument stands on its own. I left the default alone because the cap is explicitly a rollout guard rather than a memory bound — and worth noting the two-pass fix from your other comment does not change the final set's size either, so lowering it on memory grounds would have been defending a different quantity.
On reproducibility: confirmed, FLUREE_NUMBIG_EXACT_MAX_ROWS appears only in the function and the regression test, and there is no bench on this path. Rather than add a harness I wrote the recipe into the doc — N NumBig rows across two predicates plus a non-NumBig slice of N/2, timed twice with FLUREE_NUMBIG_EXACT_MAX_ROWS=1 forcing the decline — and labelled the table a recorded observation rather than a maintained benchmark, which is what it actually is.
…oning Four comment corrections and one real change, all from zonotope's review. count_distinct_numbig_objects decoded per ROW. A handle repeats once per row carrying the value — one value under one predicate is a row per subject — so every repeat allocated a BigInt/BigDecimal plus a String and an Arc<str>. It now collects the (p_id, o_key) pairs into a HashSet of Copy tuples first and decodes only the survivors, which bounds the decodes by the arena's size instead of the slice's row count for one extra hash per row. Dedup still happens on the decoded value: two legacy handles can decode to the same value, and one value under two predicates is two handles. The doc claimed every NumBig row enters the pipeline tagged xsd:decimal. It does not — resolve_datatype_sid_for_value falls through to overflow_numeric_datatype_sid, which tags an overflow BigInt xsd:integer. The constant dtc is still sound, but for the reason now stated: flake_value_to_key gives Decimal and BigInt distinct discriminants, so the datatype separates nothing the discriminant has not, and both choices yield the same partition. That invariant had nothing holding it down — the overflow-integer fixture passes either way — so big_decimal_and_big_int_key_apart_regardless_of_datatype pins it where it lives. Merging the two discriminants fails it; without it that change would silently undercount a graph holding a BigInt and a BigDecimal with one lexical form. Also: the call-site comment still said the lane declines for any decimal or overflow integer, true only above the cap now; the function carried two concatenated doc comments after a rename; and the cap's justification claimed declining costs more memory, which compares entry counts rather than bytes — the fallback holds more entries but keys them as a Copy struct where this branch holds an Arc<str> per distinct value, so no memory claim is made and the (sound) time argument stands alone. The timing table now carries the recipe to re-derive it, since nothing in the tree reproduces it.
Closes #1638.
Whole-graph
COUNT(DISTINCT ?o)currently declines to the general pipeline whenever a graph holds any NumBig object, because the 10-byte OPST lead iso_type + o_keyand for an arena value thato_keyis a per-predicate handle rather than an object identity. Everyxsd:decimalis arena-routed, so one decimal column anywhere costs a ledger the metadata-only path entirely. This gives the gate a middle branch: the non-NumBig part is still answered from directory metadata, and the arena slice is counted exactly.The directory walk now excludes NumBig leaflets from the lead-group count and tallies their rows instead, so the number that decides what happens next costs no payload reads. With no NumBig rows the walk answers exactly as before. Within the cap, the slice is counted exactly and added. Above it, the query still declines. The exact count seeks only the OPST range whose
o_typeisNUM_BIG_OVERFLOW— a branch seek, not a full walk — and projectsp_idando_keyalone.Three things shape the counting, and each of them is a way this could have been quietly wrong. An arena keeps handles for values whose rows have since been retracted, so the pairs come from rows present in the index and arena membership is never consulted. One value under two predicates is two handles in two arenas, and inside a single legacy arena two handles can decode to the same value, so dedup happens on the decoded value rather than on
(p_id, handle). And every NumBig row enters the general pipeline taggedxsd:decimalwhether the arena holds a BigDecimal or an overflow BigInt — so the values are keyed with that same datatype, through the sameflake_value_to_keythe group-aggregate path uses, and the two lanes cannot disagree by construction. The overflow-integer fixture pins that last one specifically.A note on the threshold, because it inverts what #1638 asked for. That issue assumed a latency crossover — exact-count while the NumBig slice is small, keep declining once it dominates — and asked for the number to be measured rather than guessed. It was measured, and no crossover exists. Across synthetic ledgers the exact branch beats the general pipeline 3.1x at 1k NumBig rows, 3.9x at 10k, 4.0x at 50k, 4.7x at 200k and 5.7x at 1M, with counts agreeing at every size. The advantage grows with the slice, which is structural rather than lucky: the fallback scans and materializes every object in the graph, while this branch pays payload reads for the NumBig slice only. Declining above a cap is therefore strictly worse on both time and memory than proceeding would have been. So the cap that ships here is not a crossover threshold — it is a rollout guard on a new read path (branch seek, payload decode, arena mapping), bounding how much of a graph that path is responsible for while it soaks, and it is a removal candidate after a release rather than a number to tune. The measured table lives in the constant's doc comment, next to the number it justifies.
Nothing changes about eligibility. The branch inherits the same
fast_path_storegate as its siblings — single ledger, nofrom_t, no effective overlay,to_t == max_t, root policy — plus the scan-hidden-predicate check, and it declines when novelty overlays the data exactly as before. It opens leaves withneed_replay = falseand never touches a sidecar, which is sound precisely because that gate means base leaflets already reflect current state.The regression suite moves from a two-way assertion to a three-way one, since otherwise the new middle outcome is the untested one. Every decimal fixture flips from must-not-fire to must-fire on a new
distinct object COUNT (numbig exact)stamp while keeping its hand-computed value; the no-NumBig controls gain the opposite assertion, that the exact branch must not run where it would be pure added cost; and a fixture forced over the cap has to decline the whole count and still answer correctly, because declining changes the lane and never the answer. Pinning the cap to zero turns all eight must-fire fixtures red, so the pins are not vacuous.