Repository navigation
perf: stop widening scans for a bound subject absent from the base index - #1657
Conversation
`BinaryScanOperator::open` kept the decoded IRI of a bound subject that failed to translate to a persisted `s_id`, switched the scan to PSOT, and re-checked every row of the predicate's partition by resolving its subject IRI. Probing a subject that does not exist therefore cost O(partition size) with a dictionary lookup per row, while the same probe for a subject that does exist is a single dictionary hit. The IRI was never actually looked up. `build_filter_from_snapshot_sids` resolves `Ref::Sid` through `active_snapshot`, but a pattern SID is encoded against `original_snapshot`; where those namespace tables differ the filter either used the wrong IRI or never ran. Probe the store's subject dictionary with the IRI the pattern means before deciding: a hit narrows the filter and drops the per-row comparison, and `Ok(None)` is a conclusive base miss that goes overlay-only — the standard the bound-object `Ref` arm and `generate_upsert_deletions` already apply. An `Err` leaves absence undecidable, so the widened scan stays. This is not an upsert-only path. `join.rs` and `optional.rs` rebind a correlated subject to `Ref::Iri` once per driving row, so every non-batched join or OPTIONAL probe for a missing subject paid it. Measured on one predicate, absent-subject point query: 583us/1.14ms/2.20ms/ 4.55ms at 5k/10k/20k/40k rows — linear — against a flat ~14us when the subject is present. After: ~11us, flat. The regression tests assert flatness in fuel across partition sizes rather than a wall-clock bound, so they are deterministic; both fail on the prior behavior (6.01 vs 41.01 fuel).
…velty `open_overlay_only_fallback` passed `first: None, rhs: None, leftmost: true` to `for_each_overlay_flake`, so `Segment::range` returned the segment's whole id slice and `may_overlap` could prune nothing — every probe walked the graph's entire novelty. The seek machinery already existed and was simply unused; `fast_path_common::collect_resolved_overlay_ops` bounds its walk the same way for predicate-leading orders. Derive bounds from whichever bound terms lead the active index order. Bounds are an optimization only — the per-flake equality checks in the walk stay the correctness backstop — so each one pins only components that lead the sort order and are fixed by an equality match, and lets every trailing component span its full range. `first` is left-exclusive, hence `t: i64::MIN`; `leftmost` must go false whenever it is supplied or the lower bound is ignored. This compounds with the preceding commit: routing conclusive base misses to the overlay sends more probes down this path, so its per-probe cost matters more than it did. Measured, absent-subject probe against unindexed novelty: 24us/29us/65us/ 134us at 5k/10k/20k/40k flakes. After: ~9-10us, flat. The new tests cover all four index orders (verified reached with bounds active) and fail if a bound is too tight on either the subject/predicate or the object axis.
aaj3f
left a comment
There was a problem hiding this comment.
This looks good to me, @bplatz — both fixes land at the right depth (the subject arm now meets the standard the bound-object arm already set, and the overlay walk reuses the existing Segment::range seek machinery instead of growing a parallel mechanism), the PR body names its own judgment call (Ok(None) conclusiveness widening from writes to reads) instead of burying it, and the mutation-checking discipline on the tests is exactly what fuel-shaped assertions need to be trustworthy.
One process point, same as #1655: this PR's base is another PR's branch, so no CI runs here at all — the 11122-test nextest result in the body is local. Just be sure the stack lands bottom-up with a retarget to main so the workspace gates get their pass before this merges.
Adherence to repo commitments:
- Patterns/abstractions: ✔ aligns the subject arm with the bound-object arm's existing conclusive-miss standard; reuses
Segment::rangeseeks per thepredicate_walk_boundsprecedent; below the shared IR, so SPARQL/JSON-LD behave identically. - Performance (speed first, memory second): ✔ strongly positive and measured (linear→flat on two probe classes; correlated joins/OPTIONALs compound the win); present-subject paths untouched; fuel-based regression tests are deterministic guards.
- Testing: ✔ 5/5 passing locally at HEAD, wired via
[[test]], mutation-checked by the author and independently by this review; the novelty-only-subject test pins the one direction where conclusiveness could swallow rows. - Conventions: ✔ thorough multi-line commit bodies,
docs/design/query-execution.mdgains the contract documentation, fmt/clippy clean at HEAD.
Verified locally at branch HEAD: it_absent_subject_scan_narrowing 5/5; my p_max = Sid::min() mutation → exactly the 2 bounded-walk tests fail (then reverted); cargo fmt --all -- --check clean; clippy -p fluree-db-query --all-targets --no-deps clean.
| // an upsert-only path: `join.rs` and `optional.rs` rebind a correlated | ||
| // subject to `Ref::Iri` per driving row, so every non-batched probe for a | ||
| // missing subject paid it. | ||
| if let Some(target_iri) = self.unresolved_bound_subject_iri.clone() { |
There was a problem hiding this comment.
Praise. The three-way split (Ok(Some) narrow / Ok(None) overlay-only / Err keep the widened scan) honors the repo's degrade-to-correct fallback contract exactly — the Err arm keeping the slow-but-correct path is the detail that a hastier version of this fix would have gotten wrong.
| }; | ||
|
|
||
| // Only worth bounding when the order's leading component is pinned; | ||
| // otherwise the range spans everything anyway. |
There was a problem hiding this comment.
Optional, more a question than a suggestion. overlay_walk_bounds returns None whenever the index order's leading component is unpinned — so e.g. a Psot walk with a bound subject and object but unbound predicate still walks all of novelty. I think that's the right scoping (a range spanning the whole leading component prunes nothing at the segment level anyway, so bounding buys little), but if may_overlap prunes per-segment on the full key rather than just the leading component, there might be residual pruning left on the table for the multi-component-bound shapes. Not needed for this PR's target workload — happy to leave it as a note for if a profile ever surfaces it.
| /// predicate's partition. Before the narrowing fix this scaled linearly: the | ||
| /// scan walked every `ex:name` row and resolved its subject IRI. | ||
| #[tokio::test(flavor = "current_thread")] | ||
| async fn absent_subject_probe_cost_is_flat_in_partition_size() { |
There was a problem hiding this comment.
Praise. Asserting flatness in fuel rather than a wall-clock bound is the right determinism trade for CI, and assert_eq!(small, large) (exact equality, not a tolerance) is a satisfyingly strict pin — a single extra index touch per partition row fails it loudly.
`enforce_single_target_reifiers` scans each touched reifier's stored bundle
before deciding whether the transaction would leave it reifying two edges. On
an indexed ledger that scan is not cheap when it misses: a `Sid` neither the
persisted dictionary nor `DictNovelty` can resolve falls through
`binary_range` into `overlay_only_flakes`, which walks the graph's entire
novelty. Freshly minted reifiers are exactly that shape — every anonymous
`{| … |}` and `<< … >>` is one — so a bulk Turtle-star insert paid one
whole-novelty walk per annotation in the file, and the cost was the product of
the two.
A subject absent from both dictionaries provably has no prior bundle, so the
scan can only come back empty. `subjects_with_prior_rows` decides that for
every touched reifier in one pass, with a point probe against the base
dictionary and at most one novelty walk per graph. It reports "undecidable"
rather than "absent" when an already-indexed ledger has no binary store
attached, so a store that failed to load still surfaces through the scan
instead of silently skipping the check. `generate_upsert_deletions` skips
absent subjects for the same reason, and #1657 fixed the same shape in
`binary_scan`.
Measured on a file-backed ledger, indexed and then given unindexed novelty,
inserting 2,000 annotated edges:
novelty flakes before after
20,000 124 ms 52 ms
60,000 270 ms 52 ms
The remaining 52 ms is the insert itself. Isolating the scan, its cost grew
3.04x for 3x the novelty — linear, as expected — and is now gone.
The earlier 9,000-edge figure in the PR body was measured without a binary
store attached, so it never reached this path at all.
`an_indexed_reifier_pointed_at_a_second_edge_is_still_refused` pins the other
half: a reifier that does resolve must still be scanned. Making the skip
unconditional fails it.
Two scan-path costs found while reviewing #1645. Both are performance, not correctness — and both were verified against the code and measured before being fixed.
Stacked on #1655 (
fix/branch-index-root-ledger-id), which is the base branch. Review that one first.1. An absent bound subject widened into a predicate-partition walk
BinaryScanOperator::openkeeps the decoded IRI of a bound subject that fails to translate to a persisteds_id, switches the scan to PSOT, and re-checks every row of the predicate's partition by resolving its subject IRI. Probing a subject that does not exist cost O(partition size) with a dictionary lookup per row; the same probe for a subject that does exist is a single dictionary hit.The root cause is that the IRI was never actually looked up.
build_filter_from_snapshot_sidsresolvesRef::Sidthroughactive_snapshot, but a pattern SID is encoded againstoriginal_snapshot— where those namespace tables differ, the filter either used the wrong IRI or never ran. It is also strictly weaker thansubject_ref_to_s_id, which triesfind_subject_id_by_partsfirst and falls back throughstore.sid_to_iri. The in-file comment claiming the bound-objectRefarm "mirrors the subject path (build_filter_from_snapshot_sids)" is inaccurate — the object arm is stronger, and already treatsOk(None)as a conclusive base miss. That asymmetry is the bug.Now the store's subject dictionary is probed with the IRI the pattern actually means:
Ok(Some)s_id, drop the per-row IRI comparisonOk(None)Err(_)This is not an upsert-only path.
join.rsandoptional.rsrebind a correlated subject toRef::Irionce per driving row, so every non-batched join or OPTIONAL probe for a missing subject paid it. Thestage.rspre-check from #1645 only short-circuits the upsert caller.Absent-subject point query, one predicate:
Linear before (present-subject probe is a flat ~14 µs throughout); flat after.
2. The overlay-only fallback walked all of novelty per probe
open_overlay_only_fallbackpassedfirst: None, rhs: None, leftmost: true, soSegment::rangereturned the whole id slice andmay_overlappruned nothing. Thepartition_pointseek machinery already existed and was simply unused —fast_path_common::collect_resolved_overlay_opsbounds its walk the same way.Bounds are now derived from whichever bound terms lead the active index order. They are an optimization only — the per-flake equality checks stay the correctness backstop — so each pins only components that lead the sort order and are fixed by an equality match, letting every trailing component span its full range.
Absent-subject probe against unindexed novelty: 24/29/65/134 µs at 5k/10k/20k/40k flakes → ~9–10 µs, flat.
The two are coupled: fixing #1 routes more probes into this fallback, so #2's per-probe cost matters more than it did. That is why they ship together.
Correctness notes for review
Ok(None)as conclusive.find_subject_idanswers from the canonical-split namespace plus the EMPTY/OVERFLOW full-IRI fallback. Treating that as conclusive is already load-bearing in the bound-objectRefarm and in the fix: don't fail open when a subject's namespace code is undecodable #1645 upsert skip, so this is not a new assumption — but it does widen its blast radius from writes to all reads. Flagging it as the one judgment call here.PartialEqforFlakeValuemirrorsOrd(both route numerics throughnumeric_cmp), so a flake the callback would match cannot sort outside the bracket.firstis left-exclusive, hencet: i64::MIN;leftmostmust go false whenever it is supplied.Testing
fluree-db-api/tests/it_absent_subject_scan_narrowing.rs, 5 tests. The cost assertions pin flatness in fuel across partition sizes rather than a wall-clock bound, so they are deterministic in CI.Every test was mutation-checked rather than assumed to have teeth:
fuel > 0and passed under mutation — it was rewritten to assert the returned rows, and now catches aOk(None)arm that reports "no rows anywhere".CI parity green:
fmt --check,clippy --all --all-features --all-targets -D warnings, andnextest --workspace --all-featuresat 11122 passed.Docs:
docs/design/query-execution.mdgains a section on bound-term resolution, the conclusive-miss vs undecidable split, and the bounds-are-not-correctness contract.