Repository navigation
feat: Gate hydration SPOT crawl by projection predicates - #1260
Merged
Merged
Conversation
added 5 commits
May 29, 2026 15:51
Adds an optional forward-predicate allow-list to RangeOptions and threads
it through binary_range_eq_v3 so that per-subject SPOT scans driven by
hydration (the `select: {"?x": ["ex:a", "ex:b"]}` projection path) skip
discarded predicates BEFORE the row's subject re-resolve, predicate IRI
lookup, object decode, and dict-touch fuel charge.
Previously, hydration paid the dict-touch + decode cost for every flake on
the subject, then dropped the unselected predicates at the JSON projection
step. The work and fuel were independent of the projection's field count.
With this change, narrow Explicit projections cost proportionally less
work and fuel; Wildcard projections still take the legacy
decode-everything path with zero overhead from the new filter.
The row loop also reuses the bound match_val.s subject Sid instead of
calling resolve_subject_sid per row, dropping one redundant dict touch
per scanned base row on the indexed path.
Also applied to the overlay_only_flakes fallback for parity on
novelty-only subjects.
Documents the new behaviour: an Explicit projection
(`select: {"?x": ["@id", "ex:a", "ex:b"]}`) hands the range provider a
predicate allow-list so the per-subject SPOT crawl skips dict touches
and decode work on non-listed predicates. Wildcards keep the legacy
decode-everything path.
When a projection's Explicit level lists exactly one forward predicate, hydration routes through RangeMatch::subject_predicate instead of RangeMatch::subject + predicate_filter. Same number of cursor descents and same INDEX_TOUCH fuel, but the cursor's leaflet key-range narrows to the (s, p) prefix — skipping the per-row binary_search against the filter and the in-batch scan over the subject's other predicate rows. K >= 2 stays on SPOT(s,*,*) + predicate_filter because two cursor descents would each pay their own INDEX_TOUCH and beat the single-scan baseline. Pattern repeats recursively through nested hydrations: each ref-with- sub-spec dispatches through the same format_subject path, so nested single-predicate selections (chain walks) all take the K=1 fast path naturally.
Two correctness/perf gaps surfaced by review. (1) Novelty-only predicates were silently dropped on the K>=2 path. predicate_filter_p_ids was built from store.sid_to_p_id resolutions only, so an overlay assert on a selected predicate that has no persisted p_id yet (novelty-only) — surviving the overlay translator's Sid filter and landing in the cursor stream under an ephemeral p_id assigned by translate_one_flake_v3_pub — failed the row-loop's persisted-id gate and got discarded. Fix: after overlay translation, walk ephemeral_p_id_to_sid and extend the allow-set with every ephemeral p_id whose mapped Sid is in opts.predicate_filter. (2) Explicit projections with no forward Property items (e.g. `["@id"]` or reverse-only) still opened the SPOT cursor, paying one INDEX_TOUCH (0.010 fuel) per leaflet batch returned even though the row loop dropped every row. Fix: short-circuit in format_subject — when predicate_filter_for_level returns Some(empty), use Vec::new() directly. `@id` and reverse properties are emitted by the dedicated paths further down in format_subject. Tests: - novelty_only_predicate_survives_k_ge_2_gate: seed+reindex base, insert ex:noveltyPred without reindex, project ["ex:p1", "ex:noveltyPred"], assert both come back. - id_only_projection_skips_forward_cursor: project ["@id"] only, assert just @id is emitted and fuel is measurably lower than K=1. All 8 hydration tests pass; 11 existing novelty-adjacent tests still pass; clippy/fmt clean.
Move the `mod tests` block to the bottom of `fluree-db-memory/src/store.rs`. The SPARQL result parsing helpers (`parse_memories_from_sparql_results`, `iri_to_kind`, etc.) were defined after the test module, which trips `clippy::items_after_test_module` under `-D warnings`. Pure relocation, no behavior change.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Hydration / graph-crawl SELECT projections now hand the range provider a forward-predicate allow-list so the per-subject SPOT scan skips object decode, subject resolve, predicate IRI lookup, and dict-touch fuel charges on rows whose predicate isn't in the projection. For Explicit projections (
select: {"?x": ["ex:a", "ex:b", …]}) this turns the projection's field count into a real cost lever — both work and fuel scale with selected predicates rather than the subject's total predicate count. Wildcard projections (["*"]) take the unchanged decode-everything path. K=1 projections get a further narrow-scan fast path viaRangeMatch::subject_predicate.Why
Before this change,
fetch_subject_propertiesissued a singleSPOT(s,*,*)range per subject. The row loop inbinary_range_eq_v3materialized every flake — subject Sid resolve, persisted predicate IRI lookup, eager object decode (one dict touch per dict-backed value), datatype + lang resolution — before the caller's projection got to drop the predicates it didn't want. Two queries against the same WHERE clause but different projections (9 fields vs 4) consumed identical tracked fuel because all the per-row charges had already fired. More importantly, the per-row dict reads happened whether or not the projection cared about the value — real I/O and cache pressure spent on objects the formatter would throw away.This PR moves the projection filter down into the range provider so unselected predicates are dropped before any of that work happens. The savings on a typical narrow projection are a handful of dict touches per subject, which multiply across rows; on fat subjects with narrow projections the effect compounds.
What scales now
0.001), subject-resolve, object-decode, dict-touch (0.010)0.010each)SPOT(s,p,*).Propertyitems (e.g.["@id"], reverse-only)INDEX_TOUCHHow
RangeOptions::predicate_filterNew optional field carrying the projection's forward-predicate Sids:
Nonepreserves the legacy decode-everything path with zero overhead.Arc<[Sid]>so the same allow-list is shared cheaply across the N per-subject range calls a single hydration emits.binary_range_eq_v3row loopThe row loop hoists a
binary_searchagainst a sortedVec<u32>of persistedp_ids above every per-row resolve / decode:Also reuses the caller-supplied
match_val.sinstead of callingresolve_subject_sidper row — one fewer dict touch per scanned base row on the indexed path (every hydration call already has the subject Sid in hand).Overlay translator filter
The overlay translator's
includeclosure now filters by Sid match before callingtranslate_one_flake_v3_pub, so overlay asserts/retracts on non-selected predicates never enter the merge stream. Novelty-only predicates (no persistedp_idyet) are honored: after overlay translation surfaces ephemeralp_ids viaephemeral_p_id_to_sid, the row-loop's allow-set is extended with any ephemeralp_idwhose mapped Sid is in the caller's filter. Without that extension, an overlay assert on a selected novelty-only predicate would survive the Sid filter, land in the cursor stream under an ephemeralp_id, and get silently dropped by the gate.overlay_only_flakesfallbackSame predicate filter applied to the novelty-only fast path (subject/predicate/object Sid unresolvable in the persisted dict, or no branch manifest for this order). Keeps parity between indexed and overlay-only subjects.
Hydration formatter dispatch
format_subjectderives the allow-list from each level'sNestedSelectSpecand picks the cheapest path:["@id"]or reverse-only): skip the forward fetch entirely. Saves oneINDEX_TOUCHper surveyed subject;@idis derived from the subject Sid by the caller, reverse properties go through the dedicated POST scan further down.SPOT(s, p, *)viaRangeMatch::subject_predicate— narrows the cursor's leaflet key-range to the(s, p)prefix. SameINDEX_TOUCHcount for small subjects, strictly fewer for subjects whose flakes span multiple leaflet batches. Also skips the row-loopbinary_search.SPOT(s, *, *)+predicate_filter— one cursor descent, drops non-listed rows before decode/dict-touch. Two probes would each pay their ownINDEX_TOUCHand beat the single-scan baseline; one batched scan + cheap row-loop gate wins.The same pattern repeats recursively through nested hydrations — every
format_subjectcall (for ref-expansions, reverse properties, etc.) re-derives the filter from its own level's spec.Tests
New
fluree-db-api/tests/it_hydration_predicate_gating.rs(8 tests):narrow_projection_costs_less_fuel_than_widewildcard_projection_matches_full_explicit_projection["*"]and the 8-predicate Explicit list cost within 0.030 fuel — wildcard isn't accidentally opting into the filtersingle_predicate_projection_uses_sp_pair_pathSPOT(s,p,*)(correctness contract); K=1 fuel ≤ K=2 fuelnarrow_projection_emits_only_selected_keys@idoverlay_retract_on_selected_predicate_is_honoredoverlay_retract_on_unselected_predicate_does_not_leaknovelty_only_predicate_survives_k_ge_2_gatep_id) survives the K≥2 gate via the ephemeral-p_id extensionid_only_projection_skips_forward_cursor["@id"]) emits just@idand costs measurably less than K=1 — proves the cursor is skippedDocs
docs/query/tracking-and-fuel.mdgets a new Graph-crawl projection: materialization fuel scales with selected predicates subsection that:Side commit
chore: silence clippy items_after_test_module in memory store— pure relocation influree-db-memory/src/store.rs: the SPARQL result parsing helpers were defined aftermod tests, which tripsclippy::items_after_test_moduleunder-D warnings. Moves themod testsblock to the bottom of the file. No behavior change. Surfaced during this PR's CI parity check; unrelated to the feature but needed for the workspace clippy gate to pass.Breaking changes
None at the wire layer. New
RangeOptions::predicate_filter: Option<Arc<[Sid]>>field is optional; existing callers (every range caller outside hydration) leave itNoneand observe identical behavior. Hydration formatter'sfetch_subject_propertiesgained apredicate_filterparameter — only used internally byformat_subject.Future work (not in this PR)
format_subjectis awaited serially per row (seehydration.rs:368-389). Row-level fanout viaFuturesUnorderedor a boundedJoinSet(mirroring the multi-query dispatcher) would parallelize independent row expansions; the shared result cache would need to move toArc<DashMap>(sharded locking matches the access pattern). Fuel/policy already use atomic counters and would survive parallel tasks unchanged.SPOT(s,p,*)probes when the savings beat the extraINDEX_TOUCHcost. Not worth pursuing until query telemetry shows fat-subject hydration is a real bottleneck.