Skip to content

refactor: Fold query fast-paths into the count planner + overlay-aware COUNT + reverse-POST ORDER BY DESC LIMIT - #1262

Merged
bplatz merged 20 commits into
mainfrom
refactor/fast-path
May 31, 2026
Merged

bplatz merged 20 commits into
mainfrom
refactor/fast-path

Conversation

@bplatz

@bplatz bplatz commented May 31, 2026

Copy link
Copy Markdown
Contributor

This sits on #1261.

This PR consolidates the query fast-path layer and extends it in two directions: it folds the sprawl of special-case detect_* COUNT operators into the single generic count planner, makes the entire COUNT surface correct (and fast) under uncommitted novelty, and adds a new bounded reverse-POST fast path for ORDER BY DESC(?o) LIMIT k "latest feed" queries.

Before this, ~30 narrow fast-path detectors and several standalone count operators each reimplemented their own scan/merge logic, and most of them silently bailed to the generic pipeline whenever a query carried overlay (novelty) — i.e. on roughly half of real queries. That was both a maintenance burden and a performance cliff for the common write-then-read pattern.

Consolidation

The standalone count fast paths are merged into the join-aware count_plan planner and a small set of shared cursor/scan primitives, removing duplicated logic:

  • One scalar-agg scan for SUM / AVG / COUNT(DISTINCT ?o) (replacing three separate operators), driven by a shared AggState.
  • One distinct-position COUNT operator in place of three near-identical detectors/operators (distinct subjects / predicates / objects).
  • Path-count unified — the transitive <p>+ and property-path COUNT operators merged into one, and the multicolumn (s,o)-join COUNT folded into the count planner as a composite-key intersection.
  • Optional-chain-head COUNT (?a p1 ?b . OPTIONAL { ?b p2 ?c . ?c p3 ?d }) folded into the count planner; the standalone operator removed.
  • A single order-parametric per-predicate cursor (build_overlay_cursor_for_predicate, PSOT + POST) underpins the count and scalar-agg paths.

Overlay-aware COUNT

The whole count_plan surface now serves COUNT(*) correctly under novelty instead of bailing. The merge is done by iterating the base-vs-overlay cursor — an arithmetic base + asserts − retracts delta is wrong (an assert of an existing row is a replace, a retract that misses is a no-op) — with the metadata-only fast lane preserved when there is no overlay:

  • Every node type — total / single-triple / star-join / subject MINUS·EXISTS·OPTIONAL / composite (s,o)-join / object-var EXISTS·MINUS / object-chain / linear-chain — has an overlay execution lane; a plan walk declines (falls back) for any shape not yet converted, so partial coverage can never miscount.
  • A drain_count count-only lane on the scan operator revives the ungrouped COUNT(*) pushdown for the generic path, and count_rows moved to the cursor-merge gate so encoded-prefilter counts run under overlay.
  • Correctness guard: a fast path that resolves a fixed subject/term through the persisted dictionary bails when that lookup misses while novelty is present (a novelty-only subject would otherwise undercount to zero).

New: reverse-POST ORDER BY DESC(?o) LIMIT k fast path

SELECT ?s ?o WHERE { ?s <p> ?o [ ; ?s a <Class> ] } ORDER BY DESC(?o) LIMIT k is served by a bounded reverse scan of the predicate's POST-index tail instead of draining the whole predicate into a top-k sort. POST is sorted (p_id, o_type, o_key, o_i, s_id), so within a single order-preserving o_type the physical tail is exactly the descending top-k.

  • Two lanes (single-ledger, root policy, to_t ≥ index_t): a plain reverse leaf-walk when there is no novelty, and a row-set merge of that walk with resolved novelty ops when there is — so "latest feed" queries against freshly-written data stay on the fast path (the common case the overlay work above targets). The overlay merge dedups by full fact identity and resolves rdf:type membership and novelty-only subjects overlay-correctly.
  • Safety gates (the detector is shape-only): a directory prepass proves a single order-preserving o_type (numeric / temporal / boolean) before collecting — string/ref/arena, mixed-leaflet, and multi-datatype predicates defer to the generic top-k rather than risk a wrong order; embedded scalar objects materialize through the normal value decode.
  • Profitability: with a class constraint, the planner consults StatsView and declines when the class is selective enough that anchoring on it directly is cheaper, so a selective filter never forces a long tail walk; the bare shape (no class) always wins. Any pattern beyond the two above is rejected, so an arbitrary selective clause never reaches this path.

Risk and compatibility

  • Public query APIs and results are unchanged; every fast path falls back to the existing generic pipeline whenever its preconditions don't hold (history mode, time-travel before the index point, non-root policy, multi-ledger, or any unconverted/ineligible shape).
  • The consolidation removes several standalone operator modules in favor of the shared count planner and cursor primitives; the externally observable query surface is the same.

bplatz added 20 commits May 30, 2026 11:22
Collapse detect_count_distinct_{subjects,predicates,objects} into one
detect_count_distinct_position returning a DistinctPosition, and the three
count_distinct_*_operator constructors into count_distinct_position_operator.
The two inner dedup algorithms (SPOT/OPST lead_group_count vs PSOT p_const
transitions) stay distinct behind the position branch; only the detector,
operator, and dispatch shells are shared. The object dispatch arm moves up to
join subjects/predicates, which is safe because that single-triple
COUNT(DISTINCT ?o) shape is mutually exclusive with every detector it
previously sat behind.
…or_predicate

fast_group_count_firsts carried a near-verbatim clone of the shared PSOT
predicate-range cursor builder. The only divergence — max_key.t = 0 vs
u32::MAX — is inert because cmp_v2_psot orders by (p_id, s_id, o_type, o_key,
o_i) and excludes t entirely. Delete the clone and point its three callers at
fast_path_common::build_psot_cursor_for_predicate; drop the now-unused
BinaryFilter import.
Combine fast_property_path_plus_count_all and fast_transitive_path_plus_count_all
into fast_path_plus_count_all — both build a PSOT(p) adjacency map and count
reachable endpoints, so they share a module and the cursor-flavored fast-path
gate.

Hoist the strategy-(b) gate to fast_path_common::allow_cursor_fast_path (one
copy, also reused by fast_group_count_firsts) and switch property-path+ COUNT
off fast_path_store onto it. fast_path_store bails the instant an uncommitted
overlay is present, which left the property-path operator's overlay-aware PSOT
cursor unreachable; it now merges novelty like the transitive operator already
did. Behavior change: <S> <p>+ ?o COUNT(*) gains overlay (and to_t<max_t)
coverage. Add indexed_overlay_property_path_plus_count_reflects_overlay covering
both an overlay assertion and retraction.
The three single-predicate row-scanning scalar aggregates each duplicated the
POST-leaflet scan scaffolding (resolve predicate, enumerate leaves, open handle,
skip empty/foreign leaflets). Fold them into one fast_predicate_scalar_agg
module: a shared scan_predicate_scalar_agg driver plus an AggState accumulator
enum (Sum / Avg / CountDistinct) that keeps each variant's per-leaflet gating,
per-row fold, and finalization. Output shapes are preserved exactly — SUM and
COUNT(DISTINCT) emit xsd:integer, AVG emits xsd:double (or Unbound on empty
input).

SUM's SumExprI64 expression machinery moves here from fast_fused_scan_sum (now
deleted); AVG leaves fast_min_max_string, which keeps the directory-only,
O(leaflets) MIN/MAX paths that would regress through a per-row cursor.
Drop the fluree-db-query bm25::analyzer re-export module and point its three
consumers (builder, text, eval::fulltext) and the crate-level re-export directly
at the canonical fluree_db_binary_index::analyzer.
The 2-pattern multicolumn join `?s p1 ?o . ?s p2 ?o` COUNT(*) had its own
detector + operator + module. Fold it into count_plan: add a
ScalarNode::CompositeJoinPairCount node, detect the shape in try_build_count_plan
(before classify_patterns, which rejects the repeated object var), and execute it
with a composite-key (s_id, o_type, o_key) merge-intersection that counts matching
(s,o) PAIRS — not the per-subject product a StarJoin would compute. The PSOT
merge-join iterator moves into count_plan_exec; the standalone
fast_multicolumn_join_count_all module + its detector and dispatch arm are removed.

Same result and same overlay behavior as before: count_plan_operator gates on
fast_path_store, so like the old operator it serves base-only state and falls back
under an uncommitted overlay. Add indexed_multicolumn_join_counts_pairs_not_product
(multi-object subjects) so the pair-vs-product distinction is regression-covered.
Item 2b made property_path_plus_count_all_operator run under an uncommitted
overlay, but its fixed-subject fallback resolves identity via the persisted
dictionary only (subject_ref_to_s_id / resolve_subject_iri). A start subject
introduced solely in novelty (e.g. ex:new, not yet indexed) never matches there,
so `<S> <p>+ ?o` COUNT(*) could undercount to 0 instead of falling back. When the
subject is absent from the persisted store and an overlay is present, return None
so the generic pipeline handles it. Regression test:
indexed_overlay_property_path_plus_count_subject_in_overlay_only.
…verlay

Generalize the per-predicate overlay cursor so object-ordered fast paths can
stay correct under novelty, and consolidate the remaining inline cursor builds.

Cursor builder (fast_path_common.rs):
- build_psot_cursor_for_predicate is now a thin wrapper over the order-parametric
  build_overlay_cursor_for_predicate(order). order must be p_id-primary (Psot or
  Post); Opst is intentionally rejected (object-keyed — predicate_range_keys does
  not bound it). Add build_post_cursor_for_predicate as the POST wrapper.
- Extract build_range_cursor (branch lookup + cursor construction) and
  collect_resolved_overlay_ops (the overlay-flake translate/sort/resolve block),
  and skip the overlay walk entirely when epoch == 0.
- Add binary_scan::sort_order_to_index_type (inverse of index_type_to_sort_order)
  to select the matching novelty index for the overlay walk.

Scalar aggregates (fast_predicate_scalar_agg.rs):
- Switch the gate from fast_path_store to allow_cursor_fast_path and split into
  two lanes: the leaflet-metadata scan when there is no overlay and to_t == max_t,
  otherwise a POST overlay cursor. Both lanes share AggState::fold_row, so the
  per-row arithmetic lives in one place. SUM / AVG / COUNT(DISTINCT ?o) now reflect
  uncommitted novelty and to_t < max_t.

Consolidation:
- Route the inline BinaryCursor::new sites in fast_label_regex_type,
  fast_string_prefix_count_all, and fast_star_const_order_topk through the shared
  build_range_cursor / build_psot_cursor_for_predicate helpers.
- Dedup the two identical chunked PSOT subject-range scans in
  fast_star_const_order_topk into for_each_subject_row_psot.

Test: indexed_overlay_scalar_agg_reflects_assert_and_retract covers SUM, AVG, and
COUNT(DISTINCT) across a baseline, an overlay assertion, and an overlay retraction.
…ount_rows

- count_rows (CountRowsOperator) now gates on allow_cursor_fast_path
  instead of fast_path_store, so the encoded-prefilter COUNT family runs
  its overlay-merging DatasetOperator::scan fast_child under novelty
  instead of bailing to the generic fallback.
- Implement drain_count on BinaryScanOperator and DatasetOperator,
  reviving GroupAggregate's ungrouped COUNT(*) pushdown for scan
  children. The BinaryScan lane counts the overlay-merged cursor's rows
  without materializing bindings when count_only_eligible; otherwise it
  returns None and the caller streams. The Dataset lane sums per-member
  counts (provenance stamping does not change row counts).

A clean COUNT(*) is now overlay-correct at cursor speed in the path
where count_plan/count_rows bail on novelty.
count_plan_exec previously gated on fast_path_store, bailing the entire
join-aware count planner to the generic fallback whenever novelty was
present or the query was time-travel. Add an overlay execution lane for
the subject-keyed shapes:

- Gate on allow_cursor_fast_path; compute an `overlay` flag (novelty
  epoch != 0 or to_t < max_t).
- plan_overlay_supported rejects not-yet-converted node types up front so
  they still bail to the correct fallback rather than read stale base
  counts.
- TotalRowCount and SubjectCountScan/StarJoin draw their (s_id, count)
  groups from the overlay-merging PSOT cursor (CursorSubjectGroups) when
  overlay is active, base-leaflet metadata otherwise. The star/sum merge
  math is unchanged.

Object/POST, composite, optional/anti/semi, and chain shapes still bail
to the fallback under overlay.
Extends the count_plan overlay lane to the subject-keyed AntiJoin/SemiJoin
shapes (`?s p ?a . MINUS|FILTER EXISTS { ?s q ?x }`):

- Subject keysets (SubjectSet/SubjectsSorted/IntersectSorted) collect
  distinct subjects from the overlay-merging PSOT cursor when overlay is
  active, base-leaflet collectors otherwise. The cursor yields subjects in
  ascending order, so distinct keys come out already sorted.
- plan_overlay_supported accepts AntiJoin/SemiJoin when their source stream
  and keyset are themselves overlay-supported; the object-keyed
  SubjectsWithObjectIn keyset stays unsupported (bails to fallback).
- execute_keyset_as_sorted/_as_hash_set thread the exec context; the
  merge/intersect logic is unchanged.

OptionalJoin and the object/POST/composite/chain shapes still bail.
Extends the count_plan overlay lane to OptionalJoin
(`?s p ?a . OPTIONAL { ?s q ?t }`), completing the subject-keyed family.

- sum_optional_join draws its required and optional subject-count streams
  from the overlay-merging PSOT cursor when overlay is active. The
  per-subject max(1, product over optional) multiply is unchanged.
- An absent optional predicate yields an Empty stream (multiplier 1)
  without overlay, matching the prior always_one behavior; under overlay
  an absent predicate bails (it may carry overlay-only rows).
- plan_overlay_supported accepts OptionalJoin when its required and
  optional streams are overlay-supported.

The object/POST/composite and chain shapes still bail to the fallback.
Extends the count_plan overlay lane to CompositeJoinPairCount
(`?s p1 ?o . ?s p2 ?o`, sharing subject and object var).

- count_composite_join_pairs draws both relations' (s, o_type, o_key) rows
  from the overlay-merging PSOT cursor (CursorSoIter) when overlay is
  active, base-leaflet PsotSoIter otherwise; the (s,o) merge-intersection
  is unchanged. SoKey orders by (s, o_type, o_key), matching PSOT row order.
- scalar_overlay_supported accepts CompositeJoinPairCount.

The object-keyed POST sums and ChainFold still bail to the fallback.
Extends the count_plan overlay lane to the POST-object filtered sums
(`?s p ?o . FILTER EXISTS|MINUS { ?o q ?x }`):

- post_object_filtered_sum streams POST(p) from the overlay-merging POST
  cursor, counting ref objects whose o_key is in the (overlay-aware)
  subject keyset of q. Both lanes bail on any non-IRI_REF object, matching
  the metadata path. PostObjectFilteredSum and
  TotalMinusPostObjectFilteredSum (the latter reusing the dual-lane
  total_row_count) are now overlay-aware.
- scalar_overlay_supported accepts both when their object/excluded keyset
  is overlay-supported.

Only SubjectsWithObjectIn (object-chain) and ChainFold still bail.
Extends the count_plan overlay lane to the SubjectsWithObjectIn keyset
(object-chain EXISTS/MINUS blocks, e.g.
`?s p ?o . FILTER EXISTS { ?o q ?m . ?m r ?t }`).

- subjects_with_object_in streams PSOT(q) from the overlay-merging cursor,
  grouping by subject and collecting subjects whose IRI_REF object key is
  in the (overlay-aware) inner object set. Bails on non-IRI_REF objects
  like the metadata path.
- keyset_overlay_supported now accepts SubjectsWithObjectIn when its inner
  object set is overlay-supported, so all KeySetNode types are covered.

Only ChainFold (the main-query linear chain) still bails under overlay.
…lane

Adds the overlay lane for ChainFold (`?a p1 ?b . ?b p2 ?c . …`), the last
count_plan node type still bailing under overlay. execute_chain (metadata)
is unchanged; execute_plan dispatches to a new execute_chain_overlay when
overlay is active.

- execute_chain_overlay folds per-hop weight maps right-to-left over
  overlay-merging PSOT cursors (no PsotSeekSumCursor): comp[v_k] = chain
  completions from v_k; built rightmost-first (per TailWeight), folded
  through p_{N-1}..p2, then summed over p1's edges.
- ChainWeight mirrors P2WeightMode exactly (CountEdges / Lookup / InSet /
  NotInSet), matching PsotSubjectCountIter / PsotSubjectWeightedSumIter /
  PsotObjectFilterCountIter semantics including non-IRI_REF handling.
- An absent chain or tail predicate under novelty bails to the fallback.

plan_overlay_supported now returns true for all node types: the entire
count_plan surface is overlay-aware.

Tests: indexed_overlay_chain{2,3}_count and chain_tail_{exists,minus}_count.
…ariants

- Extract the duplicated overlay subject-count stream into one shared
  fast_path_common::CursorSubjectCountStream; remove the
  SubjectCountStreamV6 (fast_union_star_count_all) and CursorSubjectGroups
  (count_plan_exec) clones, which were byte-for-byte identical.
- Delete the dead ScalarNode::SumExcluding / SumFiltered IR variants (both
  #[expect(dead_code)], never built by the planner) and their executor arms.

No behavior change.
`?a p1 ?b . OPTIONAL { ?b p2 ?c . ?c p3 ?d }` was a standalone fast path
(fast_optional_chain_head_count_all) that bailed on overlay. Fold it into
count_plan as CountPlanRoot::OptionalChainHead, deleting the module + its
detector + the now-dead find_two_hop_chain helper.

- Classifier try_build_optional_chain_head detects the shape up-front, since
  classify_optional_block rejects chain-shaped OPTIONAL.
- Metadata executor moved verbatim from the old operator (byte-identical
  behavior when no overlay).
- Overlay executor reuses the chain weight-map primitives: n3[c]=count_p3(c),
  comp2[b]=sum over c in p2(b) of n3[c], total = sum over p1 edges of
  max(1, comp2[b]) via a new ChainWeight::LookupMaxOne head — gaining the
  overlay coverage the standalone lacked.

Net: -1 fast-path module, -1 dispatch detector. The shape (previously
untested) now has metadata + overlay regression coverage.
The consolidated optional-chain-head COUNT(*) path mishandled two cases for
`?a p1 ?b . OPTIONAL { ?b p2 ?c . ?c p3 ?d }`:

- A non-node (literal) head object `?b` was dropped instead of contributing 1
  (the OPTIONAL keeps the `?a p1 ?b` solution even when the inner chain can
  never match). The metadata lane's IRI-only POST iterator also terminates on a
  homogeneous non-IRI leaflet, and POST orders such leaflets before IRI_REF, so
  mixed-type p1 could drop rows.
- An absent inner predicate p2 returned 0 instead of the full p1 row count.

The metadata lane now defers non-all-IRI p1 to the generic pipeline via a
predicate_objects_all_iri directory prepass, and treats an absent p2 like an
absent p3 (inner chain never matches => multiplier 1). The overlay lane's
LookupMaxOne weight returns 1 (not 0) for non-ref objects.

Adds indexed regression tests for literal head objects (metadata + overlay
lanes) and absent p2.
Serve `SELECT ?s ?o WHERE { ?s <p> ?o [; ?s a <Class>] } ORDER BY DESC(?o) LIMIT k`
by a bounded reverse scan of the POST index tail rather than draining the whole
predicate into a top-k SortOperator. POST is sorted (p_id, o_type, o_key, o_i,
s_id), so within one order-preserving o_type the physical tail is exactly the
DESC top-k.

Two lanes (gate: single-ledger, no from_t, root policy, to_t >= index_t):
- Base lane (no novelty): reverse leaf-walk over the persisted index.
- Overlay lane (novelty present): the same walk merged with resolved novelty ops
  as a row-set merge (skip retracted base rows, add asserts, dedup by full fact
  identity (s_id, o_key, o_i)); rdf:type membership and novelty-only subjects are
  resolved overlay-correctly. This also covers recent time-travel within the
  novelty window.

Correctness gates (detector is shape-only): a directory prepass proves a single
order-preserving o_type (numeric/temporal/boolean) before collecting; non-order-
preserving, mixed, or multi-type predicates defer to the generic top-k. Embedded
scalar objects materialize via decode_value_v3. A stats-based profitability gate
declines the class shape when the class is selective (anchoring on it is cheaper),
with a runtime scan budget as the backstop when stats are absent.

Adds a detector + profitability unit tests, overlay merge/identity unit tests,
and base + overlay + parity integration tests.
@bplatz
bplatz requested review from aaj3f and zonotope May 31, 2026 02:27
Base automatically changed from fix/s3-contention to main May 31, 2026 17:41
@bplatz
bplatz merged commit 042de7e into main May 31, 2026
9 checks passed
@bplatz
bplatz deleted the refactor/fast-path branch May 31, 2026 17:41
bplatz added a commit that referenced this pull request Jun 1, 2026
rollup: Cumulative work from #1258, #1260, #1261, #1262, #1263 (mis-merged to solo/latest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant