Skip to content

feat: Gate hydration SPOT crawl by projection predicates - #1260

Merged
bplatz merged 5 commits into
mainfrom
feature/hydration-predicate-gating
May 31, 2026
Merged

bplatz merged 5 commits into
mainfrom
feature/hydration-predicate-gating

Conversation

@bplatz

@bplatz bplatz commented May 29, 2026

Copy link
Copy Markdown
Contributor

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 via RangeMatch::subject_predicate.

Why

Before this change, fetch_subject_properties issued a single SPOT(s,*,*) range per subject. The row loop in binary_range_eq_v3 materialized 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

Cost Behavior
Per-flake (0.001), subject-resolve, object-decode, dict-touch (0.010) Scales with the number of selected predicates
Index leaflet touches (0.010 each) Still scales with the cursor's scanned subject range — the filter narrows which rows get materialized, not how many leaflets get read. K=1 gets a narrower cursor key-range via SPOT(s,p,*).
Wildcard projections Unchanged — every flake materialized and charged
Explicit projection with no forward Property items (e.g. ["@id"], reverse-only) Skips the forward SPOT scan entirely — no INDEX_TOUCH

How

RangeOptions::predicate_filter

New optional field carrying the projection's forward-predicate Sids:

pub struct RangeOptions {
    // …existing fields…
    pub predicate_filter: Option<Arc<[Sid]>>,
}

None preserves 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_v3 row loop

The row loop hoists a binary_search against a sorted Vec<u32> of persisted p_ids above every per-row resolve / decode:

let p_id = batch.p_id.get_or(i, 0);

if let Some(allow) = &predicate_filter_p_ids {
    if allow.binary_search(&p_id).is_err() {
        continue;                                    // ← bail BEFORE any dict touch
    }
}

// only survivors reach these:
let s_sid  = match &match_val.s {
    Some(sid) => sid.clone(),                        // reuse bound subject Sid
    None => resolve_sid(s_id, &view)?,
};
let p_sid  = store.resolve_predicate_iri(p_id);
let o_val  = view.decode_value(o_type, o_key, p_id)?;   // ← dict touch fires here
// …datatype, lang, FlakeMeta…

Also reuses the caller-supplied match_val.s instead of calling resolve_subject_sid per 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 include closure now filters by Sid match before calling translate_one_flake_v3_pub, so overlay asserts/retracts on non-selected predicates never enter the merge stream. Novelty-only predicates (no persisted p_id yet) are honored: after overlay translation surfaces ephemeral p_ids via ephemeral_p_id_to_sid, the row-loop's allow-set is extended with any ephemeral p_id whose 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 ephemeral p_id, and get silently dropped by the gate.

overlay_only_flakes fallback

Same 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_subject derives the allow-list from each level's NestedSelectSpec and picks the cheapest path:

let predicate_filter = predicate_filter_for_level(level);
let flakes = match predicate_filter.as_deref() {
    Some([])    => Vec::new(),                                      // K=0: skip cursor
    Some([p])   => self.fetch_subject_predicate_pair(sid, p).await?, // K=1: SPOT(s,p,*)
    _           => self.fetch_subject_properties(sid, predicate_filter).await?,  // K=N or wildcard
};
  • K = 0 (Explicit ["@id"] or reverse-only): skip the forward fetch entirely. Saves one INDEX_TOUCH per surveyed subject; @id is derived from the subject Sid by the caller, reverse properties go through the dedicated POST scan further down.
  • K = 1: SPOT(s, p, *) via RangeMatch::subject_predicate — narrows the cursor's leaflet key-range to the (s, p) prefix. Same INDEX_TOUCH count for small subjects, strictly fewer for subjects whose flakes span multiple leaflet batches. Also skips the row-loop binary_search.
  • K ≥ 2: SPOT(s, *, *) + predicate_filter — one cursor descent, drops non-listed rows before decode/dict-touch. Two probes would each pay their own INDEX_TOUCH and beat the single-scan baseline; one batched scan + cheap row-loop gate wins.

The same pattern repeats recursively through nested hydrations — every format_subject call (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):

Test What it pins
narrow_projection_costs_less_fuel_than_wide Tracked fuel on a 2-of-8 projection ≥ 0.040 less than 8-of-8 — proves dict-touch + per-row gate fires on dropped predicates
wildcard_projection_matches_full_explicit_projection ["*"] and the 8-predicate Explicit list cost within 0.030 fuel — wildcard isn't accidentally opting into the filter
single_predicate_projection_uses_sp_pair_path K=1 routes through SPOT(s,p,*) (correctness contract); K=1 fuel ≤ K=2 fuel
narrow_projection_emits_only_selected_keys JSON output shape: narrow projection only emits selected keys + @id
overlay_retract_on_selected_predicate_is_honored Novelty retract on a selected predicate drops the value (overlay filter doesn't mask the retract)
overlay_retract_on_unselected_predicate_does_not_leak Novelty retract on a non-selected predicate doesn't surface
novelty_only_predicate_survives_k_ge_2_gate Regression: novelty-only selected predicate (no persisted p_id) survives the K≥2 gate via the ephemeral-p_id extension
id_only_projection_skips_forward_cursor K=0 projection (["@id"]) emits just @id and costs measurably less than K=1 — proves the cursor is skipped

Docs

docs/query/tracking-and-fuel.md gets a new Graph-crawl projection: materialization fuel scales with selected predicates subsection that:

  • Names what scales (per-flake, subject-resolve, object-decode, dict-touch) and what doesn't (index leaflet touches still depend on the scanned subject range)
  • Calls out the K=1 narrowed-cursor path and the K=0 skip
  • Documents the wildcard preservation and the overlay filter behavior (including novelty-only predicate handling)

Side commit

chore: silence clippy items_after_test_module in memory store — pure relocation in fluree-db-memory/src/store.rs: the SPARQL result parsing helpers were defined after mod tests, which trips clippy::items_after_test_module under -D warnings. Moves the mod tests block 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 it None and observe identical behavior. Hydration formatter's fetch_subject_properties gained a predicate_filter parameter — only used internally by format_subject.

Future work (not in this PR)

  • Parallelize hydration rows. Today format_subject is awaited serially per row (see hydration.rs:368-389). Row-level fanout via FuturesUnordered or a bounded JoinSet (mirroring the multi-query dispatcher) would parallelize independent row expansions; the shared result cache would need to move to Arc<DashMap> (sharded locking matches the access pattern). Fuel/policy already use atomic counters and would survive parallel tasks unchanged.
  • Per-predicate cardinality stats would enable promoting K=2/K=3 narrow projections on fat subjects to per-predicate SPOT(s,p,*) probes when the savings beat the extra INDEX_TOUCH cost. Not worth pursuing until query telemetry shows fat-subject hydration is a real bottleneck.

Brian Platz 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.
@bplatz
bplatz requested review from aaj3f and zonotope May 29, 2026 20:07
@bplatz
bplatz merged commit 6b4c527 into main May 31, 2026
14 checks passed
@bplatz
bplatz deleted the feature/hydration-predicate-gating 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