Skip to content

perf: batched read lanes for Cypher relationship-property queries and large UNWINDs - #1553

Merged
bplatz merged 12 commits into
mainfrom
perf/cypher-untyped-rel-scan
Jul 30, 2026
Merged

bplatz merged 12 commits into
mainfrom
perf/cypher-untyped-rel-scan

Conversation

@bplatz

@bplatz bplatz commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #1549 (stacked on that branch). Addresses the second round of KB-on-Fluree field reports: Cypher relationship-property reads (r1.p, r2.p, p.p) made queries slower or OOM'd, and the ES-reindex UNWIND shape killed the container at 21k URIs.

Problem

Reading a relationship property switches the rel var from the value-only OPTIONAL lane (batched in 4.1.3) to the required f:reifies* chain, which had no batched lane at all. On bulk-imported ledgers (annotation_index: None) five separate defects stacked on it, and a sixth planner defect capped how large an UNWIND could get before the whole plan inverted:

  1. Sidecar demotion mis-ordered untyped chains. For -[p]-> the chain's f:reifiesPredicate joins on the base predicate variable, so after the base edge is placed the connected pool can be nothing but the chain itself — and the IC5-era sidecar demotion then crowned reifiesPredicate, whose bound-object fan is ~(sidecar / #relationship-types) per driving row. This is the repeated BinaryScanOperator::open on reifiesSubject in the server log and the memory climb behind the OOM.
  2. EncodedPid predicates crashed both probe lanes (untyped rels on arena-backed ledgers were a hard internal error).
  3. The required chain evaluated per driving row. New HashAnnotationEdgeProbeOperator: drain the three f:reifies* predicates once into hash maps, sweep the base pattern once (planned scans — policy and novelty semantics preserved), hash-join each driving row on every child-bound position. Gated on driving size, sweep size (stats-bounded), current-state, single-ledger.
  4. No-new-vars filter triples ran as per-row scan re-opens. New MembershipJoinOperator (build-once hash set + exact-join fallback for unbound rows); the (s-bound, const p, const o) subset stays on the existing batched-EXISTS lane.
  5. ValuesOperator was quadratic — pairwise is_compatible over input × value rows (21k UNWIND × a broad child ≈ the entire residual). Value rows now hash-index on normalized overlap keys; a hash hit still passes is_compatible, wildcard/Iri rows keep the scan path, so results are byte-identical.
  6. Large VALUES lost the planner seed to a class scan. A ClassNotInStats fallback estimate (~20k on a 72k-node ledger) out-ranked the exact VALUES cardinality, deferring the VALUES — the join keys — to a final filter over ~21M-row intermediates (1.3s at 18k URIs → ~712s at 21k; pre-branch exceeded 25 minutes). VALUES vars now join the seed-race anchor set so the existing disconnected-class-anchor demotion fires at seed time.

Two supporting fixes surfaced along the way: the DefaultGraphSource single-graph delegate now re-projects batches to its declared schema (positional consumers could silently misread reordered inner-chain layouts), and both probe lanes now unify a pre-bound reifier var instead of overwriting it — caught by W3C sparql12 eval-triple-terms pattern-8 during validation.

Results

Repro at customer scale (fluree-db-api/examples/cypher_kb_pageload_probe.rs: bulk-imported n10s-style ledger, 72k INDEXED nodes, ~190k reified edges each carrying a p annotation, ~50 classes and relationship types):

Query Before After (1k URIs) After (21k URIs)
getObjectsByUris + p.p (the OOM query) 84.5 s @1k, OOM @21k 0.82 s 1.65 s
same, value-only 0.78 s @1k, >25 min @21k 0.75 s 1.44 s
getObjectAssociations + r1.p, r2.p 68 s 2.1 s 2.1 s
getObjectAssociations stock 1.4 s 1.3 s 1.3 s

Row counts identical before/after in every case.

Tests

  • New planner unit tests (untyped-chain ordering, object-pinned wildcard estimate, VALUES seed vs class anchor) and Cypher integration pins for the rel-prop lanes (required-lane semantics, arena EncodedPid decode, 300-row UNWIND through the hash lane).
  • Full W3C SPARQL suite green — including four eval-triple-terms tests that were previously in the skip register (basic-4, pattern-5, pattern-7, pattern-9) and now pass; their stale skip entries are removed.
  • docs/design/edge-annotations.md documents the three read lanes for the expanded chain and when each engages.

Blast radius beyond Cypher

One hunk here changes behavior for every query language, not just Cypher: in estimate_triple_row_count, a wildcard triple whose object is bound or constant (?s ?p <o>) moves from FULL_SCAN (1e12) to DEFAULT_BOUND_OBJECT_SELECTIVITY. SPARQL and JSON-LD compile to the same IR and share this estimator, so their plans move too.

The rationale is that an object-pinned wildcard is a reverse OPST probe bounded by the node's in-degree, not a world scan — right in kind, but in-degree is unbounded in practice, so for a hub object the new estimate under-estimates by orders of magnitude where the old one over-estimated. Neither is correct; without an OPST-cardinality statistic the new one is better on average and worse on hubs. Flagging it so that if a nightly query_hot_bsbm or query_hot_property_path number moves, this is the first place to look.

Review follow-ups

  • Membership lane driving-side gate (3934e108c) — the lane weighed only the build side, so a few driving rows could drain up to 250k build rows where the nested loop would have done a few probes ({ ?a :knows ?b . ?b :knows ?a } is the shape that slips past the batched-EXISTS carve-out). It now takes left.estimated_rows() and declines below 256, mirroring HASH_ANNOTATION_MIN_DRIVING_ROWS including its treatment of None as large. Four unit tests; the small-driving one goes red with the gate removed.
  • Membership lane multi-graph cardinality (e4b048486) — keep/drop is only join-equivalent when a ground triple matches at most once, which is false across a multi-graph dataset (union does not dedupe). Measured: { ?a :knows ?b . ?b :knows ?a } over a graph unioned with itself returned 4 rows through the hash set against the nested loop's 8. The operator now checks the active graph count at open() and routes every row through its existing exact per-row fallback when more than one graph is in scope, so the lane is join-equivalent unconditionally. New dataset integration test.
  • Sweep ceiling documentation (a166086a0) — BASE_SWEEP_MAX_ROWS = 20_000_000 is documented in docs/design/edge-annotations.md as a backstop ~100× the validated scale rather than a tuned optimum, with what to measure to replace it; the same section now states that both annotation probe lanes are pipeline breakers (so a small LIMIT over a large driving side pays the whole probe) and records the keep_all cliff.
  • Upsert bench — tracked as a follow-up rather than here: an upsert-shaped bench beside transact_commit with new-subject and persisted-subject variants plus a regression-budget.json entry.

bplatz added 6 commits July 29, 2026 02:27
An untyped Cypher relationship with a property read (`-[p]-> … p.prop`)
lowers to the required f:reifies* chain, and its f:reifiesPredicate
triple joins on the base edge's predicate VAR — so after the base is
placed, the connected source pool can be nothing but the chain itself.
The broad-sidecar demotion then crowned reifiesPredicate, whose
bound-object fan is ~(sidecar / #relationship-types) per driving row:
a 21k-row UNWIND ran minutes of CPU and OOM'd the container.

Demote reifiesSubject/reifiesObject only while a connected NON-chain
alternative can still seed (typed relationships keep the old behavior:
their reifiesPredicate object is a constant and never joins the pool).

Also stop scoring object-pinned wildcards (`?s ?p <o>`, or ?o bound by
an earlier pattern) as FULL_SCAN 1e12 — they are reverse probes bounded
by node in-degree, and the 1e12 poisoned every downstream driving-set
estimate (hash joins rejected with driving-est 1e12).
…ins, and VALUES

Relationship-property reads (r.prop) put the f:reifies* chain in the
main BGP, where every stage previously degraded to per-row work on
arena-less (bulk-imported) ledgers. Field shape: an 11-21k-row UNWIND
over an n10s-style reified ledger — 35-85 s at 1k rows, OOM at 21k.

- HashAnnotationEdgeProbeOperator: when the recognized chain has no
  sealed arena, drain the three f:reifies* predicates ONCE into hash
  maps and sweep the base pattern ONCE (unseeded planned scan, kept
  rows hash-filtered by the driving subjects), then hash-join each
  driving row on every child-bound position. Planned scans keep
  overlay novelty and policy semantics; gates: driving >= 256 rows or
  unknown, sweep bounded by stats, current-state, single-ledger.
  Sidecar object keys are representation-normalized GroupKeyOwned, so
  ref and literal reified objects both match. Late-materialized
  EncodedPid predicates now decode through p_sid_table in both the
  arena probe and the value-lane builder (previously a hard error).

- MembershipJoinOperator: a join whose right triple binds nothing new
  is a pure existence filter; evaluate it as a build-once hash set
  probe instead of a per-row scan re-open. Rows that do not fully
  ground the pattern keep exact join semantics via a per-row fallback.
  The (s-bound, const p, const o) subset stays on the nested-loop
  join's batched-EXISTS lane, which probes only the driving subjects.

- ValuesOperator: the input x values compatibility loop was quadratic —
  a 21k-row VALUES joined against a broad child scan burned ~30 s in
  pairwise checks. Value rows now hash-index on their normalized
  overlap keys; a hash hit still passes is_compatible, and wildcard /
  Iri-class rows keep the scan path, so results are byte-identical.

- PatternOptionalBuilder / GroupedPatternOptionalBuilder opt into
  required-side seed coalescing: their batched probes are pure per-row
  restrictions, and per-row joins upstream otherwise fragment the
  stream into 1-4-row batches that pay per-batch probe setup each.

- DefaultGraphSourceOperator re-projects single-graph delegate batches
  to its declared schema: the delegate's column order comes from the
  reordered inner chain, and positional consumers above (nested-loop
  bind instructions) read by column index.

72k nodes / 190k reified edges, import-mode (no arena), 1000 uris:
p.p UNWIND 84.5s -> 0.76s, two-rel association propread 68s -> 2.0s,
row counts identical; flat through 5k uris (0.89s).
…e docs

- cypher_kb_pageload_probe example: n10s-style reified ledger (INDEXED
  labels, value/kind props, per-edge p annotation, ~50 classes and
  relationship types) with the customer's three query shapes; import
  mode mirrors the bulk-import root (annotation_index: None),
  PROBE_BISECT peels the p.p plan one stage at a time.
- it_query_cypher: untyped rel + property read pins — required-lane
  semantics (only reified edges match, plain edges excluded), indexed
  arena path (EncodedPid decode), and a 300-row UNWIND through the
  hash-sidecar lane.
- docs/design/edge-annotations.md: document the three read lanes for
  the expanded chain (arena probe / hash sidecar probe / generic) and
  when each engages.
…anchors

A VALUES/UNWIND row set is a guaranteed producer with exact cardinality,
but the greedy seed race compared it against class-scan estimates as
peers. A ClassNotInStats fallback (count/sqrt(ndv)) reads ~20k on a
72k-node ledger, so a 21k-row UNWIND suddenly lost the seed to the
class scan and was deferred to a FINAL 21k-row filter over the whole
expanded stream — ~1.3s at 18k uris, ~712s at 21k (the KB ES-reindex
query's remaining cliff; the pre-branch baseline exceeded 25 minutes).

Feed VALUES vars into the seed-race anchor set, so the existing
disconnected-class-anchor demotion (the IC3 rule: never seed backward
off a broad class extension when a connected alternative exists) also
fires at seed time. Class-only queries keep their seed through the
demotion's non-empty-pool fallback.

72k nodes / 21k uris after: value lane 1.55s, required lane 1.70s.
Nested reifier patterns bind the reifier upstream — W3C sparql12
pattern-8: `?t :p4 :z . << ?t :p4 :z >> :q :o . << ?s ?p ?o ~ ?t >>` —
so the chain's ann var arrives already in the child schema. Both probe
lanes treated it as always-new: the hash lane stamped every candidate
row with the child's binding (cross-matching bundles across different
reifiers, 11 rows where 1 is correct), and the arena lane appended a
misaligned extra column. Candidates now UNIFY with a bound reifier
(filter, not overwrite); an unbound pre-existing column is filled per
candidate like any join output.

The full W3C SPARQL suite now passes 36/36. Beyond repairing the
pattern-8 regression, the branch's annotation-lane work makes four
previously-skipped eval-triple-terms tests pass — basic-4, pattern-5,
pattern-7, pattern-9 — so their stale skip-register entries are
removed (the harness flags stale skips as failures).
Five entries, branch narratives pruned:
- upsert staging: unresolvable bound-subject lookups degrade to PSOT
  partition walks (the fallback to watch), and the existing-subject
  probe-cost measurements + store-cached p_id->Sid table invariant
- DefaultGraphSource delegate batch/schema contract: positional column
  reads against a child's declared schema are unsound
- annotation probes must UNIFY pre-bound reifier vars (W3C
  eval-triple-terms pattern-8 guard)
- batch fragmentation as a per-row-cost amplifier + the slow-UNWIND
  diagnosis heuristic
@bplatz
bplatz requested review from aaj3f and zonotope July 29, 2026 11:28
bplatz added 2 commits July 29, 2026 08:05
…ted coalescing

Three review findings against the new probe/coalescing lanes, all valid:

- The arena probe accepted a VAR object at recognition but dropped any
  row whose runtime binding was a literal, silently losing results for
  reified literal triples on indexed ledgers. The probe now builds the
  EdgeKey with (value, effective datatype, language tag) exactly as
  EdgeKey::from_flake recorded them — sound under the arena gates, which
  require an empty overlay so every binding decodes through the same
  dictionaries the writer used. Pinned by
  arena_probe_matches_literal_object_annotation, which returns [] on the
  pre-fix code.

- Both probe lanes treated a Poisoned reifier binding as unconstrained.
  Poisoned is a failed upstream OPTIONAL and joins NOTHING (the
  nested-loop join skips poisoned rows); treating it as a wildcard could
  manufacture annotation matches. Poisoned now drops the row in both
  lanes, and a bound non-ref reifier (which can match no annotation)
  likewise joins nothing instead of going unconstrained. The hash
  lane's variable-predicate position gets the same treatment.

- supports_seed_coalescing now takes the execution context and mirrors
  each builder's build_batch admission gates (multi-ledger, binary
  store, dtc, predicate normalization, probe lane plan). Previously the
  two per-subject builders answered true unconditionally, so a driving
  side could be coalesced up to the 512k cap only for build_batch to
  decline and fall back per-row anyway — delaying the fallback,
  defeating an early LIMIT, and inflating memory.
is_multiple_of over manual modulo checks, and drop a no-op .max(0) on
an unsigned expression — all-targets clippy covers examples.

@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.

This is strong, well-evidenced work that fixes two availability failures (an OOM and a >25-minute query) at their causes rather than papering over them, and the lanes extend the codebase's existing batched-read shapes rather than inventing parallel ones. The measurements include the control that matters — the unmodified getObjectAssociations query stays flat at 1.3 s — and the row-count-identical claim is backed by 231 Cypher integration tests, 251 grp_misc tests, and 1,300 fluree-db-query unit tests, all green locally with every new test confirmed by name.

The one possibly blocking item is narrow and mechanical: MembershipJoinOperator is admitted with no regard for how many driving rows it will serve, so a three-row driving side can now drain up to 250k build rows where it previously did three scan probes — while the annotation hash lane added in this same PR gates on exactly that signal, and optional.rs in this same diff cites "defeating an early LIMIT" as the reason not to buffer speculatively. Thread left.estimated_rows() into membership_join_key_vars and this is would be resolved.

Adherence to repo commitments:

  • Performance (speed first, memory second): ⚠️ Large validated wins on the target shapes, but one possibly-critical regression window: the membership lane has no driving-side gate (blocking, above). A second, non-blocking window is inherited — both annotation lanes are pipeline breakers, and the new one adds a base sweep of up to 20M rows that the arena lane did not have, so a small LIMIT over a large driving side over-reads.

/// bound the standalone build within [`MEMBERSHIP_JOIN_MAX_BUILD`].
/// Returns the key vars in left-schema order (load-bearing for column
/// lookup at open), or `None` to keep the nested-loop join.
fn membership_join_key_vars(

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.

Blocking — CRITICAL (performance regression). membership_join_key_vars gates the new lane on the build side only. It has no driving-side gate, so a query with a handful of driving rows now drains up to 250,000 build rows where it previously did a handful of scan probes.

Mechanism: the function receives left_schema but not left, so left.estimated_rows() — available at the call site on line 2612, and the exact signal the sibling lane uses — never enters the decision. MembershipJoinOperator::build_key_set then performs one unseeded full drain of the right triple on the first fully-bound row, bounded only by MEMBERSHIP_JOIN_MAX_BUILD = 250_000 (:2685).

Concrete failing input: { ?a :knows ?b . ?b :knows ?a } (a mutual-relationship / triangle shape, common in both Cypher and SPARQL) where the first triple is selective and yields three rows. The (s-bound, const p, const o) carve-out at :2703-2712 does not catch this — the object is Term::Var, so the guard's condition is false and the lane is admitted. The estimate for a const predicate with both ends unbound is the property's flake count, so any :knows extension under 250k rows qualifies. Result: a full drain of the entire :knows extension to answer three rows, against roughly three per-row scan re-opens before this PR.

This is the asymmetry that makes it look like an oversight rather than a judgement call: the annotation hash lane added in the same PR gates on precisely this signal at default_graph_source.rs:203-205 (child.estimated_rows().is_none_or(|n| n >= HASH_ANNOTATION_MIN_DRIVING_ROWS)), and optional.rs:120-126 in this same diff names "defeating an early LIMIT" as a reason not to buffer speculatively. The membership lane should inherit the same discipline.

Suggested fix — thread the driving side into the gate and mirror the sibling's threshold:

// call site, ~:2601
if bounds.is_none() && inline_ops.is_empty() {
    if let Some(key_vars) =
        membership_join_key_vars(&left_schema, tp, planning, hash_planner, left.estimated_rows())
    { … }
}

// in membership_join_key_vars, alongside the history check
// A small driving side is cheaper on the nested loop's per-row probes than
// on a one-shot drain of the whole build side.
if driving_rows.is_some_and(|n| n < MEMBERSHIP_JOIN_MIN_DRIVING) {
    return None;
}

An unknown estimate should take the hash lane, matching HASH_ANNOTATION_MIN_DRIVING_ROWS's treatment of None — an unbounded stream is exactly what the drain protects against.

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.

Fixed in 3934e10. membership_join_key_vars now takes left.estimated_rows() and declines below MEMBERSHIP_JOIN_MIN_DRIVING = 256, mirroring HASH_ANNOTATION_MIN_DRIVING_ROWS including its treatment of None as large. Your { ?a :knows ?b . ?b :knows ?a } case is now a unit test (membership_lane_declines_small_driving_side) alongside admit-on-large, admit-on-unknown, and the build ceiling; the small-driving test goes red with the gate removed.

Comment thread fluree-db-query/src/membership_join.rs Outdated
//!
//! When every variable of a join's right triple already appears in the left
//! schema, the "join" is a pure existence filter: in current-state mode a
//! fully-ground triple matches at most once, so each left row is kept or

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.

Optional (correctness question, not an asserted bug). The module's founding premise is that "in current-state mode a fully-ground triple matches at most once, so each left row is kept or dropped." I could not confirm that holds for a multi-graph dataset, where the same ground triple can be present in more than one named graph and the nested-loop join would emit one row per matching graph while the hash set collapses them to one.

What makes this worth asking rather than dismissing: the sibling hash lane explicitly gates on !ctx.is_multi_ledger() (default_graph_source.rs:266), and MembershipJoinOperator has no equivalent gate — nor could it easily, since it is selected in build_scan_or_join at plan time where the execution context is not in hand. If duplicate-per-graph rows are the existing behavior, this lane silently changes cardinality for those queries; if they are not, a one-line comment recording why would save the next reader the same trip.

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.

Good catch — this is a real cardinality bug, not just an unproven premise, and it is fixed in e4b0484.

Measured it rather than reasoned about it: { ?a :knows ?b . ?b :knows ?a } over a graph unioned with itself returns 4 rows through the hash set against the nested loop's 8. Union does not dedupe (as dataset_multiple_default_graphs_no_dedup already documents), so the same ground triple matches once per graph and keep/drop collapses the second match.

Rather than gate on is_multi_ledger() — which would still miss multiple named graphs of a single ledger in the active scope — the operator now checks the active graph count at open() via ctx.active_graphs() and routes every row through its existing exact per-row fallback when more than one graph is in scope. The execution context is in hand there, so no plan-time plumbing was needed. The lane is join-equivalent unconditionally now, and the hash fast path engages only where the premise provably holds. New test: dataset_membership_shape_keeps_per_graph_multiplicity.

&self,
shape: &crate::annotation_edge_probe::AnnotationEdgeShape,
) -> bool {
const BASE_SWEEP_MAX_ROWS: u64 = 20_000_000;

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.

Optional (performance, inherited pattern). BASE_SWEEP_MAX_ROWS = 20_000_000 is a bare constant with no stated derivation, and it is roughly 100× the scale the PR validated against (~190k reified edges over 72k nodes).

Mechanism: the hash lane is a pipeline breaker — next_batch runs probe_all to completion before emitting anything (annotation_edge_probe.rs:1221-1233) — so a query with a small LIMIT over a large driving side pays the entire sweep. The buffering itself matches the pre-existing arena AnnotationEdgeProbeOperator, so it is a consistent extension rather than a new anti-pattern, but the hash lane adds the base-edge sweep on top, and that sweep is what the 20M ceiling governs. PlanningContext (temporal_mode.rs:59-73) carries no limit, so a LIMIT-aware gate would need real plumbing — this is a design note, not a one-liner.

There is also a sharp edge inside the sweep: keep_all (annotation_edge_probe.rs:931, 957) disables the driving-subject filter entirely if any single driving row leaves the subject unbound, so one such row flips the sweep from "filtered to the driving subjects" to "every base edge in the graph." Correct, but a cliff a reader would not expect from the gate names.

Suggested: record the derivation of 20M in docs/design/edge-annotations.md next to the lane description (it is the one number a future tuner will want and cannot recover), and say explicitly there that both annotation lanes are pipeline breakers so the LIMIT interaction is documented rather than discovered.

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.

Documented in a166086. docs/design/edge-annotations.md gains a "Buffering and the sweep ceiling" subsection recording that 20M is a backstop ~100x the validated scale rather than a tuned optimum, what to benchmark to replace it (sweep vs nested loop at 1M/5M/20M), that both annotation probe lanes are pipeline breakers so a small LIMIT over a large driving side pays the whole probe, and the keep_all cliff — one driving row with an unbound subject flips the sweep from subject-filtered to every base edge in the graph. The constant now points at that section.

}

PatternType::FullScan => FULL_SCAN,
PatternType::FullScan => {

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.

Optional (blast radius worth naming). This is the only hunk in the PR that changes behavior for every query language rather than just Cypher, and the PR description frames the whole change set as Cypher work.

Mechanism: ?s ?p <o> (or ?o bound by an earlier pattern) moves from FULL_SCAN (1e12) to DEFAULT_BOUND_OBJECT_SELECTIVITY. SPARQL and JSON-LD compile to the same IR and share this estimator, so their plans move too. The argument in the comment — a reverse OPST probe bounded by the node's in-degree — is right in kind, but in-degree is unbounded in practice: for a hub object the new estimate underestimates by orders of magnitude where the old one overestimated. Neither is correct; the new one is better on average and worse on hubs.

I am not asking for a change — without an OPST-cardinality statistic there is nothing better available, and the W3C suite and the 1,300 fluree-db-query unit tests are green. It is worth a sentence in the PR description so that if a nightly query_hot_bsbm or query_hot_property_path number moves, the next person knows where to look.

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.

Added to the PR description under "Blast radius beyond Cypher" — that the estimator is shared with SPARQL and JSON-LD, that the new estimate under-estimates on hub objects where the old one over-estimated, and that query_hot_bsbm / query_hot_property_path are the first place to look if a nightly number moves. No code change, agreed there is nothing better available without an OPST-cardinality statistic.

Base automatically changed from fix/upsert-staging-new-subject-scan to main July 30, 2026 02:40
bplatz added 3 commits July 29, 2026 23:02
membership_join_key_vars weighed only the build side, so a query with a
handful of driving rows could drain up to MEMBERSHIP_JOIN_MAX_BUILD
(250k) rows to answer them where the nested loop would have done a
handful of seeded probes. The canonical case is a mutual-relationship
shape — { ?a :knows ?b . ?b :knows ?a } — whose second triple has a VAR
object, so the batched-EXISTS carve-out does not catch it, and whose
build estimate is just the :knows extension.

Thread left.estimated_rows() into the gate and decline below
MEMBERSHIP_JOIN_MIN_DRIVING (256), mirroring the sibling annotation
hash lane's HASH_ANNOTATION_MIN_DRIVING_ROWS — including its treatment
of an unknown estimate as large, since an unbounded driving stream is
what the build-once drain protects against.

Four unit tests cover decline-on-small, admit-on-large, admit-on-
unknown, and the build ceiling; the small-driving test goes red with
the gate removed.
The membership rewrite is keep/drop, which is only join-equivalent when
a ground triple matches at most once. That holds over a single graph in
current-state mode, but a multi-graph active scope unions without
deduplicating (see dataset_multiple_default_graphs_no_dedup), so the
same ground triple can match once per graph: the nested loop emits a
row per match where the hash set collapses them to one.

Measured, not assumed — { ?a :knows ?b . ?b :knows ?a } over a graph
unioned with itself returns 4 rows through the hash set against the
nested loop's 8.

Check the active graph count at open() and route every row through the
existing exact per-row fallback when more than one graph is in scope.
The lane is now join-equivalent unconditionally and the hash fast path
engages only where the premise provably holds; single-graph queries
(every measured workload here) are unaffected.
BASE_SWEEP_MAX_ROWS = 20_000_000 was a bare constant ~100x the scale
the lane was validated at, with no stated derivation — the one number a
future tuner needs and cannot recover from the code. Document it as a
backstop rather than a tuned optimum, say what to measure to replace
it, and point the constant at the doc.

Also state plainly that both annotation probe lanes are pipeline
breakers, so a small LIMIT over a large driving side pays the whole
probe, and note the keep_all cliff: one driving row with an unbound
subject flips the sweep from subject-filtered to every base edge in the
graph.
@bplatz

bplatz commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f All four items addressed — thanks especially for the membership-lane pair, both turned out to be real.

  • Driving-side gate (3934e108c): threaded left.estimated_rows() into membership_join_key_vars, declining below 256 to mirror HASH_ANNOTATION_MIN_DRIVING_ROWS (unknown estimate treated as large). Your mutual-:knows case is a unit test now.
  • Multi-graph cardinality (e4b048486): your question had a bug behind it. Measured — that same shape over a graph unioned with itself returns 4 rows through the hash set against the nested loop's 8. The operator checks the active graph count at open() (ctx.active_graphs(), which also catches multiple named graphs of one ledger — broader than is_multi_ledger()) and routes every row through its exact per-row fallback when more than one graph is in scope, so the lane is join-equivalent unconditionally.
  • Sweep ceiling (a166086a0): 20M documented as a backstop ~100x the validated scale, with what to measure to replace it, plus the pipeline-breaker note and the keep_all cliff.
  • Estimator blast radius: new "Blast radius beyond Cypher" section in the PR description naming the shared estimator and the hub-object trade-off.

Validation: fluree-db-query 1,304 unit tests, grp_query 385, grp_query_sparql 296, grp_misc 251, it_query_cypher 231, grp_transact 183; W3C SPARQL 36/36 suites (246 passed, 0 failed); workspace clippy --all-features --all-targets clean. The upsert bench stays a follow-up.

@bplatz
bplatz merged commit 8506b76 into main Jul 30, 2026
14 checks passed
@bplatz
bplatz deleted the perf/cypher-untyped-rel-scan branch July 30, 2026 03:09
aaj3f added a commit that referenced this pull request Jul 31, 2026
…conflict-free review

Single conflict: fluree-db-api/src/lib.rs — convergent cfg-orphan fix.
Both #1566 and the audit side moved build()'s #[cfg(native)] doc block
below with_secret_resolver (kept iceberg-gated). The cfg fix is
byte-identical on both sides; resolved the lone doc-wording hunk to
main's #1566 text, so the merged file equals origin/main's api/lib.rs
(zero diff, no audit feature lost). hash_join.rs, optional.rs, planner.rs
auto-merged (disjoint hunks: audit #1477 fast-path vs main cypher #1553).
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.

2 participants