Skip to content

query: restore the whole-graph COUNT(DISTINCT ?o) fast path for NumBig-bearing ledgers with an exact counter #1638

Closed

Description

@aaj3f

Performance follow-up, not a defect. Correctness is unaffected in either direction — the behavior after #1628 is right, and the behavior proposed here is right. The question is only how fast the right answer arrives on ledgers that contain decimals.

Summary

#1628 makes the whole-graph distinct-object fast path decline whenever the graph contains any NumBig object, falling through to the general pipeline. That is the correct fix and it is cheap to evaluate, but the decline is total: because every xsd:decimal routes to the NumBig arena unconditionally, a ledger with a single decimal column anywhere loses the metadata-only COUNT(DISTINCT ?o) path entirely.

Decimal-heavy ledgers therefore trade a wrong-but-instant answer for a right-but-slower one. That is the right trade, and it is still worth improving on.

This issue proposes the exact counter that #1628's fix sketch explicitly deferred: count the non-NumBig objects from metadata as today, count the NumBig slice exactly, and restore the fast path for ledgers where the NumBig slice is small.

Background — why the fast path is currently declined

count_distinct_position_operator's DistinctPosition::Objects arm in fluree-db-query/src/fast_count.rs answers whole-graph COUNT(DISTINCT ?o) by counting distinct 10-byte OPST key leads. Those 10 bytes are o_type(2) + o_key(8), stopping immediately before p_id, which sits at bytes [14..18].

For every object kind except one, that prefix is a faithful global value identity. For NumBig it is not: the arena is per-predicate (fluree-db-binary-index/src/arena/numbig.rs — "Per-predicate equality-only arena for overflow BigInt and BigDecimal values") and handles are allocated from zero within each (g_id, p_id) arena. So the first decimal under predicate A and the first decimal under predicate B are both handle 0, share a 10-byte lead, and collapse into one group.

#1628 narrows eligibility: decline the Objects arm if any OPST leaflet's key range covers OType::NUM_BIG_OVERFLOW. The check costs a 2-byte comparison per directory entry and opens no payload, which is what makes it the right first move.

The reason the decline is so broad is the routing rule. fluree-db-indexer/src/run_index/resolve/resolver.rs carries the comment "All typed xsd:decimal values route to NumBig by default" and has no alternative branch, so this holds for every decimal in every v4 ledger — plus every xsd:integer beyond i64, which shares the same arena and the same o_type.

Proposal

Split the count rather than declining it:

  1. Count distinct leads for the non-NumBig o_type ranges exactly as today. The metadata walk is correct for every other object kind and needs no change.
  2. For the NumBig range, collect the distinct (p_id, handle) pairs actually present in rows, map each through its per-predicate arena to a canonical value representation, and count distinct canonical values.
  3. Sum the two.

Step 2 is where all the work and all the risk live.

The two traps

Arena contents over-approximate live rows. An arena retains a handle for a value whose rows have since been retracted, so unioning the per-predicate arenas' value sets — the obvious shortcut — over-counts. The distinct pairs must be derived from rows present in the index, not from arena membership. Any design that reads the arena as an authoritative value set is wrong before it is written.

p_id is not in the lead, so this costs payload reads. Recovering (p_id, handle) means reading the p_id column, which is exactly the access the current fast path avoids — the sibling per-predicate function's doc comment states the property plainly: "cached header+directory prefix reads — no payload, columns, or dictionary access". Arena loads add to that. So this is not a free refinement of a metadata walk; it is a partial materialization of one slice of the index.

Cost model, and why this needs a threshold rather than a switch

Because step 2 gives up the property that makes the fast path fast, an unconditional exact counter would be a regression on some ledgers. The shape that makes sense is a threshold: exact-count the NumBig slice when its estimated row count is small relative to the graph — a couple of decimal columns in an otherwise wide ledger, which is the common case and the one where the current decline hurts most — and keep declining to the general pipeline when most objects are NumBig, where the general pipeline is likely competitive anyway.

That makes the deliverable a refinement of #1628's gate, not a replacement for it. The gate stays; it gains a middle branch.

Whoever picks this up should measure before choosing the threshold, since the crossover depends on payload-read cost and arena size rather than on anything derivable from first principles. #1628 ships OType::o_key_is_globally_identifying and OType::range_holds_non_globally_identifying as the single source of truth for which object kinds need this handling; both the gate and the exact counter should consult those rather than testing NUM_BIG_OVERFLOW directly, so they cannot drift apart.

Effort and risk

Effort: M. The counting logic itself is not large, but it needs a row-derived pair collection, arena mapping with a canonical value representation shared with whatever the general pipeline uses, a measured threshold, and benchmarks on both sides of it.

Risk: low for correctness, moderate for performance. Correctness is bounded because the fallback is the general pipeline, and because a wrong exact counter fails loudly against the must-not-fire matrix #1628 adds (fluree-db-api/tests/it_distinct_object_numbig_gate.rs) rather than silently. The real risk is shipping a threshold that makes some ledgers slower than the plain decline, which is why the benchmarks are the deliverable as much as the code is.

Check before investing

A dormant feature/inline-decimal-encoding branch exists (last commit 7be883733, 2026-06-30; never merged and now well behind main) that explored storing decimals inline rather than routing them all to the arena. If that direction is ever revived, the population of NumBig-bearing ledgers shrinks sharply and most of this issue's value evaporates. Establishing whether that work is dead or merely parked is cheap and should happen before anyone commits M-sized effort here.

Context

Follow-up to #1628, whose own fix sketch names this work as the right eventual answer and defers it deliberately: ship the gate first, because the exact counter needs payload reads, arena loads, reconciliation against retractions, and a materially larger review surface.

Worth carrying: the defect #1628 fixes is the third independent correctness bug in the "answer a COUNT from leaflet directory metadata" lane, after #1208 / #1209 and the repeated-variable gate failure that #1628 also closes. Anyone extending this surface should treat the span-capture must-fire / must-not-fire matrix as the entry requirement rather than as follow-up work.

Activity

  1. added
    enhancement
    on Aug 11, 2026
  2. aaj3f commented on Aug 11, 2026

    @aaj3f
    ContributorAuthor

    Did the feature/inline-decimal-encoding check this issue calls for before starting on the counter, since it was the one thing that could have made the counter unnecessary. Verdict: it doesn't, and the counter proceeds. Writing it up here so the finding doesn't have to be re-derived, and so anyone tempted to revive that branch starts from the right facts.

    How far it got. Further than "spike" — 29 commits (26 files, +1911/-152) spanning the core codec, index-root versioning, the resolver, indexer rebuild, bulk import, and the query side (decode sites, MIN/MAX, ORDER BY and range pushdown), with its own tests. None of it is on main; NUM_DEC doesn't exist there.

    Why it isn't a substitute — three things, all from the branch's own code rather than inference:

    1. It's InlineWhenFits, not "inline". ObjKey::encode_decimal returns None past DEC_DIGITS = 17 significant digits or outside a ±32 base-10 exponent window, and the policy doc says those values "fall back to the arena, exactly like overflow integers". So the arena, and the per-predicate handle identity that makes the 10-byte OPST lead non-identifying, survive for everything beyond that window.
    2. It does nothing for overflow xsd:integer, which is half of what puts a graph on this path in the first place. The RawObject::BigIntStr arm never consults the encoding policy — a BigInt past i64 goes straight to NUM_BIG with a per-predicate arena handle, on that branch exactly as on main.
    3. The policy is sticky per index root and defaults to ArenaOnly. Its own comment explains that only a full reindex changes it, "because only a full reindex rewrites existing facts under a new (o_type, o_key) identity". So merging it wouldn't retroactively change a single ledger already written — the population that loses the fast path today keeps losing it until someone does a full reindex.

    Net: the gate stays either way, a NumBig-bearing ledger still falls to the general pipeline for whole-graph COUNT(DISTINCT ?o), and the exact counter is what gives that back.

    Viability, separately, since it's worth being honest about rather than leaving as a vague "dormant": it's a real rebase, not a cherry-pick. 1526 commits behind main, and 17 of its 26 files have also changed on main since the fork, concentrated in fluree-db-query / fluree-db-indexer / fluree-db-core / fluree-db-binary-index. It also carries an index-root format version and lands squarely on the (o_type, o_key)-is-fact-identity invariant, so it's an M-to-L with real correctness exposure — not something to slot in ahead of this.

    One property worth banking, though, because it means these two compose at zero cost and in the right direction: encode_decimal is a pure function of the value, so an inline NUM_DEC key is globally identifying, and OType::o_key_is_globally_identifying is false only for NUM_BIG_OVERFLOW. An inline-decimal ledger would keep the metadata-only fast path with no change to the gate at all. If that work is ever revived it just makes this counter's exact branch fire less often on freshly reindexed ledgers — which is a nice place to end up, and an argument about future priority rather than about whether to build the counter now.

    So: proceeding with the counter as described above. Reviving inline decimal encoding stays an independent, separately-scoped item.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions