Skip to main content

waratah_compute/
path.rs

1//! Encoded property-path walker (SPARQL 1.1 ALP on interned terms).
2//!
3//! Hops are hexastore scans with a broadcast frontier, not per-term iterators.
4//! Walk state — pairs, seen/frontier sets, targets, identity graphs — is
5//! interned `(start, end, graph)` id triples: each scan page's S/O/G slots are
6//! interned into the query [`TermDict`] exactly once at the page boundary
7//! ([`intern_quad_slots`]), so a high-degree step never holds the full hop list
8//! before LIMIT or the pair budget can stop the walk. Raw encodings survive
9//! only in the wire-facing constants (the hop predicate, a ground graph name,
10//! the negated-property set) and cross OUT to storage for the hop allow-lists,
11//! promoted per frontier chunk ([`promote_terms`]) — the same boundary
12//! discipline the join path's scan absorb uses. `*` / `+` / `?` hash-dedup
13//! (connectivity). `/`, `|`, and `!` keep bag multiplicity (equivalent-pattern
14//! counting). A root `*` / `?` with both ends the same variable emits identity
15//! pairs and does not walk.
16
17use std::collections::{HashMap, HashSet};
18use std::sync::Arc;
19
20use waratah_exec::{TermBatch, TermColumn, TermDict, TermId};
21use waratah_proto::PatternSlot;
22use waratah_stats::PUSHDOWN_TERMS_LIMIT;
23use waratah_storage::{EncodedQuad, EncodedTerm, EncodedTriplePattern, Variable};
24
25use crate::clients::{
26    BlobStoreClient, BroadcastFilter, HexastoreCatalog, HexastoreGeo, HexastoreScan, StringResolve,
27};
28use crate::context::{LogLevel, QueryContext, TraceEvent, epoch_millis_now};
29use crate::dataset::{GraphFilter, compose_graph_constraint};
30use crate::error::ComputeError;
31use crate::plan::{PathEnd, PathOp, PropertyPath, ScanOp};
32use crate::query::QueryEngine;
33use crate::query::caches::QueryCaches;
34use crate::query::pushdown::PushedKeyVals;
35use crate::query::tunables::scan_batch;
36use crate::solutions::EncodedSolutions;
37
38/// Default distinct-pair circuit breaker for bound / one-end walks (8e6).
39pub const PATH_PAIR_BUDGET: u64 = 8_000_000;
40
41/// Default distinct-pair circuit breaker for `*` / `+` with no LIMIT.
42///
43/// Lower than [`PATH_PAIR_BUDGET`]: `*` / `+` can grow toward Θ(V²) (open) or a
44/// huge join-pushed start set. `?` and `LIMIT` still use [`PATH_PAIR_BUDGET`].
45pub const OPEN_STAR_PAIR_BUDGET: u64 = 800_000;
46
47/// Pair of interned terms `(start, end, graph)` produced by a path walk.
48///
49/// Every slot is a query-local [`TermId`] into the walk's shared `TermDict`;
50/// integer equality is term equality because interning is injective
51/// (`EncodedTerm` Eq/Hash is bit-identity).
52type PathPair = (TermId, TermId, TermId);
53
54type PathPairsFuture<'a> = std::pin::Pin<
55    Box<dyn std::future::Future<Output = Result<Vec<PathPair>, ComputeError>> + Send + 'a>,
56>;
57
58/// Per-page interned S/O/G id columns — the output of the absorb boundary.
59type QuadSlotIds = (Vec<TermId>, Vec<TermId>, Vec<TermId>);
60
61/// Intern the S/O/G slots of a scan page under one batched
62/// [`TermDict::intern_columns`] call — a single dict lock acquisition for
63/// all three slot columns.
64///
65/// This is the walk's single absorb boundary: every `EncodedQuad` crosses
66/// here exactly once (the caller may pre-filter the stream — e.g. the
67/// negated-property set drops quads before any slot is interned), so
68/// downstream walk state never holds a raw term and a term crossing between
69/// walk stages is never re-interned (the dict returns the existing id).
70fn intern_quad_slots(
71    dict: &TermDict,
72    quads: impl Iterator<Item = EncodedQuad>,
73) -> Result<QuadSlotIds, ComputeError> {
74    let (lower, upper) = quads.size_hint();
75    let mut subjects = Vec::with_capacity(upper.unwrap_or(lower));
76    let mut objects = Vec::with_capacity(upper.unwrap_or(lower));
77    let mut graphs = Vec::with_capacity(upper.unwrap_or(lower));
78    for quad in quads {
79        subjects.push(quad.subject);
80        objects.push(quad.object);
81        graphs.push(quad.graph_name);
82    }
83    let [subjects, objects, graphs] = dict.intern_columns([subjects, objects, graphs])?;
84    Ok((
85        subjects.into_iter().map(TermId).collect(),
86        objects.into_iter().map(TermId).collect(),
87        graphs.into_iter().map(TermId).collect(),
88    ))
89}
90
91/// Promote interned walk terms back to raw encodings for the scan wire
92/// (broadcast allow-lists). The reverse direction of [`intern_quad_slots`]:
93/// ids crossing OUT to storage cross exactly here, once per frontier chunk.
94///
95/// Every walk id was minted by this same dict (page absorb or the
96/// once-per-walk frontier intern), so a miss is an invariant break — reported
97/// as a query error, never a panic: the walker maps every impossible state to
98/// `ComputeError`.
99fn promote_terms(dict: &TermDict, ids: &[TermId]) -> Result<Arc<[EncodedTerm]>, ComputeError> {
100    let mut slots = vec![None; ids.len()];
101    let raw: Vec<u32> = ids.iter().map(|id| id.0).collect();
102    dict.get_many(&raw, &mut slots);
103    let mut terms: Vec<EncodedTerm> = Vec::with_capacity(ids.len());
104    for (term, id) in slots.into_iter().zip(ids) {
105        let term = term.ok_or_else(|| {
106            ComputeError::Internal(format!(
107                "path-walk term id {id:?} is missing from the walk's own TermDict"
108            ))
109        })?;
110        terms.push(term);
111    }
112    Ok(Arc::from(terms))
113}
114
115/// Intern a walk-frontier term list (bound starts / ends) once, when the walk
116/// is set up — the only other place raw terms enter walk state.
117fn intern_frontier(
118    dict: &TermDict,
119    terms: Option<Vec<EncodedTerm>>,
120) -> Result<Option<Vec<TermId>>, ComputeError> {
121    Ok(match terms {
122        None => None,
123        Some(terms) => Some(
124            dict.intern_column(terms.into_iter().map(Some))?
125                .into_iter()
126                .map(TermId)
127                .collect(),
128        ),
129    })
130}
131
132/// Walk limits: a pair-count circuit breaker plus an optional SPARQL `LIMIT`.
133///
134/// There is **no hop cap**. ALP already stops when no new pairs appear;
135/// memory tracks distinct pairs, which a small-diameter graph can fill in a
136/// handful of hops.
137///
138/// Closed `*` / `+` / `?` (both ends bound) counts SPARQL solutions only for
139/// pairs that hit `targets`. BFS `seen` / `frontier` still hold every reached
140/// pair; that is what `pair_budget` bounds.
141#[derive(Clone)]
142struct WalkCap {
143    pair_budget: u64,
144    max_solutions: Option<u64>,
145    same_term: bool,
146    /// When false, a hop may return more pairs than `pair_budget`; the closure
147    /// records them one at a time and enforces the budget on BFS `seen`.
148    hop_budget: bool,
149    /// Closed walk: interned ids of the other end. `None` means every new pair
150    /// is a SPARQL solution (open / one-end walks).
151    targets: Option<HashSet<TermId>>,
152    /// When true, a pair hits if `start` is in `targets` (walk toward ends).
153    /// When false, a pair hits if `end` is in `targets` (walk from starts).
154    match_start: bool,
155    /// Connectivity closed walks stop once this many candidate pairs exist
156    /// (`|starts|×|ends|`), even without a SPARQL LIMIT.
157    max_closed: Option<u64>,
158    /// Bound graph name when G is ground.
159    graph_name: Option<EncodedTerm>,
160    /// Residual G allow-list or block-list for hops.
161    graph_filter: Option<GraphFilter>,
162    /// Merge-default hop scans unique S/P/O and rewrite G to DefaultGraph.
163    merge_default_graph: bool,
164    /// `PathOp.graph` is `Some`: this walk is inside `GRAPH ?g` / `GRAPH <iri>`.
165    /// Distinguishes Collect / FROM NAMED identities from default-graph merge.
166    in_named_graph: bool,
167    /// Graphs in which a 0-hop `*` / `?` identity is true, interned into the
168    /// walk's dict.
169    ///
170    /// Ground G: that one graph. `GRAPH ?g` with an allow-list: each FROM NAMED
171    /// / pushed IRI (no catalog RPC). Engine Collect: Present catalog IRIs
172    /// (see [`QueryEngine::resolve_identity_graphs`]). Default-graph walks:
173    /// [`EncodedTerm::DefaultGraph`] (its reserved [`TermId::DEFAULT_GRAPH`]
174    /// id) so merge-default hops still join on the sentinel. Hop scans do not
175    /// use this list.
176    identity_graphs: Arc<[TermId]>,
177}
178
179impl WalkCap {
180    /// Adjacency hops must not inherit the output LIMIT: truncating a step's
181    /// edges would under-fill reachable pairs. Used for ALP closure waves,
182    /// both `/` operands, and the first seed of `+` (those pairs are not yet
183    /// SPARQL solutions). `same_term` is a root-output predicate (`?v path ?v`
184    /// / `LIMIT` counts only `start == end`); nested identities are ordinary
185    /// intermediate pairs. `pair_budget` still applies to the hop list: a hub
186    /// operand must error instead of materialising more pairs than the cap.
187    /// Targets are cleared so an inner hop keeps every neighbour, not only
188    /// SPARQL hits.
189    fn adjacency(self) -> Self {
190        Self {
191            max_solutions: None,
192            same_term: false,
193            targets: None,
194            match_start: false,
195            max_closed: None,
196            ..self
197        }
198    }
199
200    /// Walk from `starts`; a pair is a hit when its end is in `ends`.
201    fn closed_forward(mut self, starts: &[TermId], ends: &[TermId]) -> Self {
202        self.targets = Some(ends.iter().copied().collect());
203        self.match_start = false;
204        self.max_closed = Some((starts.len() as u64).saturating_mul(ends.len() as u64));
205        self
206    }
207
208    /// Walk toward `ends`; a pair is a hit when its start is in `starts`.
209    fn closed_backward(mut self, starts: &[TermId], ends: &[TermId]) -> Self {
210        self.targets = Some(starts.iter().copied().collect());
211        self.match_start = true;
212        self.max_closed = Some((starts.len() as u64).saturating_mul(ends.len() as u64));
213        self
214    }
215
216    /// Counting `/` `|` `!`: filter LIMIT to target hits, but do not cap at
217    /// `|starts|×|ends|` (bags may repeat a pair).
218    fn closed_hits_end(mut self, ends: &[TermId]) -> Self {
219        self.targets = Some(ends.iter().copied().collect());
220        self.match_start = false;
221        self.max_closed = None;
222        self
223    }
224
225    fn closed_hits_start(mut self, starts: &[TermId]) -> Self {
226        self.targets = Some(starts.iter().copied().collect());
227        self.match_start = true;
228        self.max_closed = None;
229        self
230    }
231
232    fn over_budget(&self, pair_count: usize) -> bool {
233        (pair_count as u64) > self.pair_budget
234    }
235
236    /// Whether any solution threshold exists — SPARQL `OFFSET+LIMIT` or the
237    /// closed-set bound `|starts|×|ends|`. When false, `enough_solutions`
238    /// can never be true and every solution-counting pass is pure waste;
239    /// per-pair callers must skip it (the O(N²) walk defect: each push
240    /// recounted the whole accumulation to answer a statically-false
241    /// question).
242    fn counts_solutions(&self) -> bool {
243        self.max_solutions.is_some() || self.max_closed.is_some()
244    }
245
246    fn enough_solutions(&self, pairs: &[PathPair]) -> bool {
247        // The count is O(len): only pay it when a threshold exists at all.
248        // Per-pair callers go through `enough_solutions_count` with a
249        // [`SolutionCountMemo`] instead of this full recount.
250        if !self.counts_solutions() {
251            return false;
252        }
253        self.enough_solutions_count(solution_count(self, pairs))
254    }
255
256    /// [`Self::enough_solutions`] over a count the caller already holds:
257    /// the incrementally maintained count on per-pair paths, a fresh
258    /// [`solution_count`] on once-per-segment paths.
259    fn enough_solutions_count(&self, n: u64) -> bool {
260        if let Some(max) = self.max_solutions
261            && n >= max
262        {
263            return true;
264        }
265        if let Some(max) = self.max_closed
266            && n >= max
267        {
268            return true;
269        }
270        false
271    }
272
273    fn pair_is_solution(&self, start: &TermId, end: &TermId) -> bool {
274        if self.same_term && start != end {
275            return false;
276        }
277        match &self.targets {
278            None => true,
279            Some(keys) if self.match_start => keys.contains(start),
280            Some(keys) => keys.contains(end),
281        }
282    }
283}
284
285fn solution_count(cap: &WalkCap, pairs: &[PathPair]) -> u64 {
286    pairs
287        .iter()
288        .filter(|(start, end, _)| cap.pair_is_solution(start, end))
289        .count() as u64
290}
291
292/// Amortized [`solution_count`] over one growing output list, for the
293/// per-pair `enough_solutions` checks: remembers how far the last count
294/// reached and counts only the suffix grown since, so each pair is counted
295/// once per querying cap instead of once per check.
296///
297/// One memo belongs to exactly one (output list, cap) pair. Bidirectional
298/// closed walks share one `out` between their forward and backward caps;
299/// each cap carries its own memo, and the suffix recount keeps both exact
300/// regardless of which cap pushed a given pair — a full recount under a
301/// cap is always the memo's prefix count plus the suffix count.
302/// cap is always the memo's prefix count plus the suffix count.
303///
304/// **List-replacement invariant:** the memo's count is only meaningful
305/// while its list only GROWS. Every site that REPLACES the paired list
306/// (`take_solutions` after a satisfied threshold — `push_budgeted_pair`,
307/// `record_pair_frontier`, `ensure_in_frontier`) calls [`Self::reset`]
308/// immediately; all three return right after, so no memo is read
309/// post-replacement today. Two backstops, not substitutes: `solutions`
310/// self-heals a SHRINKING replacement (recounts from zero), but a
311/// replacement that reorders or dedups at the SAME length would
312/// over-count silently — `take_solutions` provably never does (its
313/// filter-then-take either strictly shrinks or returns the identical
314/// list), and the `debug_assert` in `solutions` trips in debug builds if
315/// a shrinking replacement ever misses its reset.
316#[derive(Default)]
317struct SolutionCountMemo {
318    /// Pairs of the paired list already counted; grows with the list, and
319    /// is zeroed by [`Self::reset`] whenever the list is replaced.
320    counted_len: usize,
321    count: u64,
322}
323
324impl SolutionCountMemo {
325    /// Solutions under `cap` in `out`, counting only what changed.
326    fn solutions(&mut self, cap: &WalkCap, out: &[PathPair]) -> u64 {
327        debug_assert!(
328            self.counted_len <= out.len(),
329            "the paired list shrank without a reset — a take_solutions site lost its reset()",
330        );
331        if self.counted_len > out.len() {
332            // Self-heal (release): a shrinking replacement the reset
333            // missed. The counted prefix is gone — recount from zero.
334            self.counted_len = 0;
335            self.count = 0;
336        }
337        self.count += solution_count(cap, &out[self.counted_len..]);
338        self.counted_len = out.len();
339        self.count
340    }
341
342    /// Drop the remembered count entirely: the paired list was REPLACED
343    /// (a satisfied threshold took its solutions), so both the counted
344    /// prefix and the count may refer to pairs no longer in the list.
345    /// The next `solutions` call recounts from zero.
346    fn reset(&mut self) {
347        self.counted_len = 0;
348        self.count = 0;
349    }
350}
351
352fn take_solutions(pairs: Vec<PathPair>, cap: &WalkCap) -> Vec<PathPair> {
353    let filtered = if cap.targets.is_some() || cap.same_term {
354        pairs
355            .into_iter()
356            .filter(|(start, end, _)| cap.pair_is_solution(start, end))
357            .collect()
358    } else {
359        pairs
360    };
361    match cap.max_solutions {
362        Some(max) => filtered.into_iter().take(max as usize).collect(),
363        None => filtered,
364    }
365}
366
367fn pair_budget_error(cap: &WalkCap, discovered: usize) -> ComputeError {
368    ComputeError::PathPairBudget {
369        budget: cap.pair_budget,
370        discovered: discovered as u64,
371    }
372}
373
374fn ensure_frontier(cap: &WalkCap, n: usize) -> Result<(), ComputeError> {
375    if cap.over_budget(n) {
376        Err(pair_budget_error(cap, n))
377    } else {
378        Ok(())
379    }
380}
381
382fn enforce_budget(cap: &WalkCap, pairs: Vec<PathPair>) -> Result<Vec<PathPair>, ComputeError> {
383    if cap.over_budget(pairs.len()) {
384        Err(pair_budget_error(cap, pairs.len()))
385    } else {
386        Ok(pairs)
387    }
388}
389
390fn absorb_hop_pairs(
391    cap: &WalkCap,
392    acc: &mut Vec<PathPair>,
393    solutions: &mut SolutionCountMemo,
394    page: Vec<PathPair>,
395) -> Result<bool, ComputeError> {
396    // Predicate and NPS hops keep one pair per matching quad (`/` / `|` / `!`
397    // counting). `LIMIT` still applies pair-at-a-time so a large page cannot
398    // overshoot the slice. Distinct-pair collapse belongs on `*` / `+` / `?`.
399    if !cap.hop_budget {
400        acc.extend(page);
401        return Ok(false);
402    }
403    for pair in page {
404        if push_budgeted_pair(cap, acc, solutions, pair)? {
405            return Ok(true);
406        }
407    }
408    Ok(false)
409}
410
411/// Push one pair; error if the live list exceeds `pair_budget`. Stop early when
412/// SPARQL `OFFSET+LIMIT` is already satisfied (root hops / `/` join output).
413/// `solutions` is the caller's [`SolutionCountMemo`] for (this cap, `acc`) —
414/// the amortized stand-in for recounting `acc` on every push.
415fn push_budgeted_pair(
416    cap: &WalkCap,
417    acc: &mut Vec<PathPair>,
418    solutions: &mut SolutionCountMemo,
419    pair: PathPair,
420) -> Result<bool, ComputeError> {
421    acc.push(pair);
422    if cap.over_budget(acc.len()) {
423        return Err(pair_budget_error(cap, acc.len()));
424    }
425    if cap.counts_solutions() && cap.enough_solutions_count(solutions.solutions(cap, acc)) {
426        *acc = take_solutions(std::mem::take(acc), cap);
427        // The list was replaced: the memo's count refers to pre-take pairs.
428        solutions.reset();
429        return Ok(true);
430    }
431    Ok(false)
432}
433
434fn hop_pattern(predicate: Option<&EncodedTerm>, cap: &WalkCap) -> EncodedTriplePattern {
435    // Merge-default walks leave `graph_name` unbound and set `merge_default_graph` on
436    // the hop ScanOp so storage unique's edges and rewrites G to DefaultGraph.
437    EncodedTriplePattern {
438        subject: None,
439        predicate: predicate.cloned(),
440        object: None,
441        graph_name: cap.graph_name.clone(),
442    }
443}
444
445fn finish_output(cap: &WalkCap, pairs: Vec<PathPair>) -> Result<Vec<PathPair>, ComputeError> {
446    // Apply LIMIT before the budget check so a hop that returns more edges than
447    // `pair_budget` can still satisfy a smaller OFFSET+LIMIT without erroring.
448    let pairs = if cap.enough_solutions(&pairs) {
449        take_solutions(pairs, cap)
450    } else {
451        pairs
452    };
453    enforce_budget(cap, pairs)
454}
455
456fn record_pair(
457    cap: &WalkCap,
458    seen: &mut PairSet,
459    out: &mut Vec<PathPair>,
460    frontier: &mut Vec<PathPair>,
461    solutions: &mut SolutionCountMemo,
462    pair: PathPair,
463) -> Result<bool, ComputeError> {
464    record_pair_frontier(cap, seen, out, Some(frontier), solutions, pair)
465}
466
467/// Insert `pair` into BFS `seen`. Hits go to `out` (SPARQL solutions). Non-hits
468/// stay off `out` so `LIMIT` / ASK do not stop at `*` identity. Budget is
469/// `seen.len()`. `frontier` is `None` when the pair is already expanded (probe
470/// hop-0 identities). `solutions` is the caller's [`SolutionCountMemo`] for
471/// (this cap, `out`) — the amortized stand-in for recounting `out` per hit.
472fn record_pair_frontier(
473    cap: &WalkCap,
474    seen: &mut PairSet,
475    out: &mut Vec<PathPair>,
476    frontier: Option<&mut Vec<PathPair>>,
477    solutions: &mut SolutionCountMemo,
478    pair: PathPair,
479) -> Result<bool, ComputeError> {
480    if !seen.insert(pair.0, pair.1, pair.2) {
481        return Ok(false);
482    }
483    if cap.over_budget(seen.len()) {
484        return Err(pair_budget_error(cap, seen.len()));
485    }
486    let hit = cap.pair_is_solution(&pair.0, &pair.1);
487    if hit {
488        out.push(pair);
489        if cap.counts_solutions() && cap.enough_solutions_count(solutions.solutions(cap, out)) {
490            *out = take_solutions(std::mem::take(out), cap);
491            // The list was replaced: the memo's count refers to pre-take pairs.
492            solutions.reset();
493            return Ok(true);
494        }
495    }
496    if let Some(frontier) = frontier {
497        frontier.push(pair);
498    }
499    Ok(false)
500}
501
502#[allow(clippy::too_many_arguments)]
503fn record_with_fringe(
504    cap: &WalkCap,
505    seen: &mut PairSet,
506    out: &mut Vec<PathPair>,
507    frontier: &mut Vec<PathPair>,
508    solutions: &mut SolutionCountMemo,
509    pair: PathPair,
510    fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
511    forward: bool,
512) -> Result<bool, ComputeError> {
513    let graph = pair.2;
514    let start = pair.0;
515    let neighbor = pair.1;
516    let backward_end = pair.1;
517    let backward_neighbor = pair.0;
518    if record_pair(cap, seen, out, frontier, solutions, pair)? {
519        return Ok(true);
520    }
521    let Some(fringe) = fringe else {
522        return Ok(false);
523    };
524    if forward {
525        if let Some(ends) = fringe.get(&(neighbor, graph)) {
526            for end in ends {
527                if record_pair(cap, seen, out, frontier, solutions, (start, *end, graph))? {
528                    return Ok(true);
529                }
530            }
531        }
532    } else if let Some(starts) = fringe.get(&(backward_neighbor, graph)) {
533        for start in starts {
534            if record_pair(
535                cap,
536                seen,
537                out,
538                frontier,
539                solutions,
540                (*start, backward_end, graph),
541            )? {
542                return Ok(true);
543            }
544        }
545    }
546    Ok(false)
547}
548
549/// Incremental core of [`hop_would_be_enough`]: the membership set of
550/// already-known pairs (seeded from `confirmed`) and the running count of
551/// distinct hits. A paged hop feeds each page's pairs in ONCE — instead of
552/// rebuilding the set and recounting the whole accumulation per page, which
553/// cost O(pages × N) with a fresh clone of every term each page.
554struct HopEnough {
555    known: HashSet<(TermId, TermId, TermId)>,
556    count: u64,
557}
558
559impl HopEnough {
560    /// Seed the membership set from `confirmed` and the running count from
561    /// its hits.
562    fn new(cap: &WalkCap, confirmed: &[PathPair]) -> Self {
563        Self {
564            known: confirmed.iter().copied().collect(),
565            count: solution_count(cap, confirmed),
566        }
567    }
568
569    /// Would the NEW pairs of `page` complete the solution set? Only a
570    /// pair that is a hit AND not yet known advances the count;
571    /// threshold-less caps never stop early (the one-shot
572    /// [`hop_would_be_enough`] guards that case before seeding).
573    fn absorb_page(&mut self, cap: &WalkCap, page: &[PathPair]) -> bool {
574        if !cap.counts_solutions() {
575            return false;
576        }
577        for (start, end, graph) in page {
578            if cap.pair_is_solution(start, end) && self.known.insert((*start, *end, *graph)) {
579                self.count += 1;
580                if cap.enough_solutions_count(self.count) {
581                    return true;
582                }
583            }
584        }
585        false
586    }
587}
588
589fn hop_would_be_enough(cap: &WalkCap, confirmed: &[PathPair], hop: &[PathPair]) -> bool {
590    // Would this hop's NEW hits complete the solution set? With no
591    // threshold (`LIMIT` / closed-set bound) the answer is statically
592    // false. Both production callers pass caps built by `closed_forward`
593    // / `closed_backward`, which always set `max_closed`, so this arm is
594    // defensive today — kept so a future threshold-less caller gets the
595    // correct answer without paying for the membership set and counting.
596    if !cap.counts_solutions() {
597        return false;
598    }
599    // Membership by hash set: the former linear `.any()` over the
600    // accumulated confirmed list cost O(confirmed × hop) per call, and
601    // `confirmed.to_vec()` cloned it first. The running count is the
602    // incremental form of `solution_count(cap, confirmed ++ new hits)`
603    // — every pushed pair is a hit by the guard below.
604    HopEnough::new(cap, confirmed).absorb_page(cap, hop)
605}
606
607fn ensure_in_frontier(
608    cap: &WalkCap,
609    seen: &mut PairSet,
610    out: &mut Vec<PathPair>,
611    frontier: &mut Vec<PathPair>,
612    solutions: &mut SolutionCountMemo,
613    pair: PathPair,
614) -> Result<bool, ComputeError> {
615    let new = seen.insert(pair.0, pair.1, pair.2);
616    if new && cap.over_budget(seen.len()) {
617        return Err(pair_budget_error(cap, seen.len()));
618    }
619    if new && cap.pair_is_solution(&pair.0, &pair.1) {
620        out.push(pair);
621        if cap.counts_solutions() && cap.enough_solutions_count(solutions.solutions(cap, out)) {
622            *out = take_solutions(std::mem::take(out), cap);
623            // The list was replaced: the memo's count refers to pre-take pairs.
624            solutions.reset();
625            return Ok(true);
626        }
627    }
628    frontier.push(pair);
629    Ok(false)
630}
631
632#[derive(Clone, Copy)]
633enum ClosureKind {
634    ZeroOrMore,
635    OneOrMore,
636}
637
638impl<H: HexastoreScan + HexastoreCatalog + HexastoreGeo, R: StringResolve + BlobStoreClient>
639    QueryEngine<H, R>
640{
641    /// Evaluate a path leaf, optionally restricted by join-pushed start/end IDs.
642    ///
643    /// `max_solutions` is SPARQL `OFFSET+LIMIT` when the Path is the Slice
644    /// child: the walker may stop once that many output rows exist. It is not
645    /// a hop cap. Exceeding the pair budget is always an error.
646    pub(crate) async fn execute_path(
647        &self,
648        path: &PathOp,
649        ctx: &QueryContext,
650        pushed: Option<&PushedKeyVals>,
651        cache: &mut QueryCaches,
652        max_solutions: Option<u64>,
653    ) -> Result<EncodedSolutions, ComputeError> {
654        crate::query_trace!(ctx, TraceEvent::Path);
655        for (hash, raw) in &path.strings {
656            cache.insert(*hash, raw.clone());
657        }
658        let (starts, ends) = path_frontiers(path, pushed);
659        let pair_budget = if max_solutions.is_none() && path.path.contains_star_or_plus() {
660            self.open_star_pair_budget()
661        } else {
662            self.path_pair_budget()
663        };
664        let mut graph_name = path.graph_name.clone();
665        let mut graph_filter = path.graph_filter.clone();
666        if let Some(variable) = &path.graph
667            && let Some(keys) = pushed
668        {
669            for (name, terms) in keys.iter() {
670                if name == variable {
671                    if let Some(composed) =
672                        compose_graph_constraint(graph_name.as_ref(), graph_filter.as_ref(), terms)
673                    {
674                        let slots = composed.into_slots();
675                        graph_name = slots.0;
676                        graph_filter = slots.1;
677                    }
678                    break;
679                }
680            }
681        }
682        if graph_filter
683            .as_ref()
684            .is_some_and(GraphFilter::is_empty_allow)
685        {
686            return Ok(EncodedSolutions::empty(ctx.term_dict(), path.variables()));
687        }
688        let in_named_graph = path.graph.is_some();
689        let identity_graphs_raw = self
690            .resolve_identity_graphs(
691                ctx,
692                graph_name.as_ref(),
693                graph_filter.as_ref(),
694                in_named_graph,
695                &path.path,
696            )
697            .await?;
698        // Intern the walk's frontier terms ONCE, before any walk state is
699        // built: starts/ends from the plan and pushed keys, and the identity
700        // graphs. Every id the walk later sees descends from these or from
701        // [`intern_quad_slots`] at a hop page boundary — no other raw→id
702        // crossing exists.
703        let dict = ctx.term_dict();
704        let starts = intern_frontier(dict.as_ref(), starts)?;
705        let ends = intern_frontier(dict.as_ref(), ends)?;
706        let identity_graphs: Arc<[TermId]> = Arc::from(
707            dict.intern_column(identity_graphs_raw.iter().cloned().map(Some))?
708                .into_iter()
709                .map(TermId)
710                .collect::<Vec<_>>(),
711        );
712        let cap = WalkCap {
713            pair_budget,
714            max_solutions,
715            same_term: path.subject.is_some()
716                && path.object.is_some()
717                && path.subject.as_ref() == path.object.as_ref(),
718            hop_budget: true,
719            targets: None,
720            match_start: false,
721            max_closed: None,
722            graph_name,
723            graph_filter,
724            merge_default_graph: path.merge_default_graph,
725            in_named_graph,
726            identity_graphs,
727        };
728        // Root `*` / `?` with both ends the same `?v` is zero-length identity.
729        // Nested intermediates use `adjacency()` (no LIMIT, no `same_term`).
730        // Only the root path may skip the walk (`:p/:q*` must not treat `:q*`
731        // as identity).
732        let pairs = if cap.same_term && zero_length_same_term(&path.path) {
733            self.eval_same_term_identities(starts.as_deref(), ends.as_deref(), ctx, cap.clone())
734                .await?
735        } else {
736            match (starts.as_deref(), ends.as_deref()) {
737                (Some(starts), Some(ends)) => {
738                    self.eval_closed_pairs(&path.path, starts, ends, ctx, cap.clone())
739                        .await?
740                }
741                (Some(starts), None) => {
742                    self.eval_from_pairs(&path.path, starts, ctx, cap.clone())
743                        .await?
744                }
745                (None, Some(ends)) => {
746                    self.eval_to_pairs(&path.path, ends, ctx, cap.clone())
747                        .await?
748                }
749                (None, None) => self.eval_open_pairs(&path.path, ctx, cap.clone()).await?,
750            }
751        };
752        solutions_from_pairs(dict, path, take_solutions(pairs, &cap))
753    }
754
755    /// Distinct `(n, n)` for a root same-variable `*` / `?`. Bound terms are
756    /// identities even when missing from the graph; unbound uses `graph_nodes`.
757    async fn eval_same_term_identities(
758        &self,
759        starts: Option<&[TermId]>,
760        ends: Option<&[TermId]>,
761        ctx: &QueryContext,
762        cap: WalkCap,
763    ) -> Result<Vec<PathPair>, ComputeError> {
764        let pairs = match (starts, ends) {
765            (None, None) => self.graph_nodes(ctx, &cap).await?,
766            (Some(starts), Some(ends)) => {
767                let nodes = intersect_terms(starts, ends);
768                self.identity_pairs_for_nodes(nodes, ctx, &cap).await?
769            }
770            (Some(starts), None) => {
771                self.identity_pairs_for_nodes(unique_terms(starts.iter().copied()), ctx, &cap)
772                    .await?
773            }
774            (None, Some(ends)) => {
775                self.identity_pairs_for_nodes(unique_terms(ends.iter().copied()), ctx, &cap)
776                    .await?
777            }
778        };
779        finish_output(&cap, pairs)
780    }
781
782    async fn identity_pairs_for_nodes(
783        &self,
784        nodes: Vec<TermId>,
785        ctx: &QueryContext,
786        cap: &WalkCap,
787    ) -> Result<Vec<PathPair>, ComputeError> {
788        // GRAPH (ground, FROM NAMED allow-list, or Collect catalog) and a
789        // grounded default-graph G: stamp each node in every identity graph,
790        // including empty named graphs that `graph_nodes` never sees.
791        if cap.in_named_graph || cap.graph_name.is_some() {
792            return Ok(identity_pairs(nodes, &cap.identity_graphs));
793        }
794        let all = self.graph_nodes(ctx, cap).await?;
795        Ok(all
796            .into_iter()
797            .filter(|(start, _, _)| nodes.contains(start))
798            .collect())
799    }
800
801    /// Graphs in which a 0-hop `*` / `?` identity is true.
802    ///
803    /// Hop scans still use `graph_name` / `graph_filter` on the RPC. Only the
804    /// invented `(n, n, G)` seeds go through this list. Merge-default hops
805    /// rewrite G to DefaultGraph on storage, so the default-graph sentinel
806    /// matches hop pairs and `/` / ALP join across source graphs.
807    async fn resolve_identity_graphs(
808        &self,
809        ctx: &QueryContext,
810        graph_name: Option<&EncodedTerm>,
811        graph_filter: Option<&GraphFilter>,
812        in_named_graph: bool,
813        path: &PropertyPath,
814    ) -> Result<Arc<[EncodedTerm]>, ComputeError> {
815        if let Some(graph) = graph_name {
816            return Ok(Arc::from([graph.clone()]));
817        }
818        if !in_named_graph {
819            return Ok(Arc::from([EncodedTerm::DefaultGraph]));
820        }
821        if let Some(filter) = graph_filter
822            && !filter.is_exclude()
823        {
824            let graphs: Vec<EncodedTerm> = filter
825                .terms()
826                .iter()
827                .filter(|graph| !matches!(graph, EncodedTerm::DefaultGraph))
828                .cloned()
829                .collect();
830            return Ok(Arc::from(graphs));
831        }
832        if !path_has_zero_length_identity(path) {
833            return Ok(Arc::from([]));
834        }
835        // Not ideal: each Collect `*` / `?` Path leaf lists the catalog by
836        // itself, even though every leaf at this snapshot wants the same
837        // Present named-graph set. The long-term shape is one GRAPH domain
838        // (`PlanNode::NamedGraphs`) pushing `?g` into the path. Until then,
839        // [`QueryContext`] memos the listing so a query with many identity
840        // paths and scan-free GRAPH still pays one ListNamedGraphs RPC.
841        let graphs = self.list_catalog_named_graphs(ctx).await?;
842        let graphs: Vec<EncodedTerm> = match graph_filter {
843            Some(filter) => graphs
844                .into_iter()
845                .filter(|graph| filter.allows(graph))
846                .collect(),
847            None => graphs,
848        };
849        Ok(Arc::from(graphs))
850    }
851
852    fn eval_from_pairs<'a>(
853        &'a self,
854        path: &'a PropertyPath,
855        starts: &'a [TermId],
856        ctx: &'a QueryContext,
857        cap: WalkCap,
858    ) -> PathPairsFuture<'a> {
859        Box::pin(async move {
860            if starts.is_empty() {
861                return Ok(Vec::new());
862            }
863            ensure_frontier(&cap, starts.len())?;
864            match path {
865                PropertyPath::Predicate(predicate) => {
866                    self.hop_from(starts, Some(predicate), None, ctx, &cap)
867                        .await
868                }
869                // Bound starts of `^inner` are bound *ends* of `inner`. Flip each
870                // `(inner-start, inner-end)` so the result stays `(path-start, path-end)`.
871                PropertyPath::Reverse(inner) => finish_output(
872                    &cap,
873                    reverse_pairs(self.eval_to_pairs(inner, starts, ctx, cap.clone()).await?),
874                ),
875                PropertyPath::Sequence(a, b) => {
876                    // `/` middles are not SPARQL solutions: LIMIT on `a` would
877                    // keep a dead-end neighbour and skip a later one that joins
878                    // with `b`. Apply the slice after `sequence_extend`.
879                    let middles = self
880                        .eval_from_pairs(a, starts, ctx, cap.clone().adjacency())
881                        .await?;
882                    self.sequence_extend(middles, b, ctx, cap).await
883                }
884                PropertyPath::Alternative(a, b) => {
885                    let left = self.eval_from_pairs(a, starts, ctx, cap.clone()).await?;
886                    if cap.enough_solutions(&left) {
887                        return Ok(take_solutions(left, &cap));
888                    }
889                    let right = self.eval_from_pairs(b, starts, ctx, cap.clone()).await?;
890                    // SPARQL `|` is UNION: keep both branches' bags.
891                    finish_output(&cap, concat_path_bags(left, right, &cap)?)
892                }
893                PropertyPath::ZeroOrMore(inner) => {
894                    let seed = identity_pairs(starts.iter().cloned(), &cap.identity_graphs);
895                    self.pair_closure(seed, inner, ctx, cap, None).await
896                }
897                PropertyPath::OneOrMore(inner) => {
898                    // First `+` seed is one complete inner walk, not a root
899                    // solution: `LIMIT` / `same_term` apply in `pair_closure`.
900                    let first = self
901                        .eval_from_pairs(inner, starts, ctx, cap.clone().adjacency())
902                        .await?;
903                    self.pair_closure(first, inner, ctx, cap, None).await
904                }
905                PropertyPath::ZeroOrOne(inner) => {
906                    let identity = identity_pairs(starts.iter().cloned(), &cap.identity_graphs);
907                    if cap.enough_solutions(&identity) {
908                        return Ok(take_solutions(identity, &cap));
909                    }
910                    let stepped = self
911                        .eval_from_pairs(inner, starts, ctx, cap.clone())
912                        .await?;
913                    finish_output(&cap, unique_pairs(identity.into_iter().chain(stepped)))
914                }
915                PropertyPath::NegatedPropertySet(forbidden) => {
916                    self.hop_from(starts, None, Some(forbidden), ctx, &cap)
917                        .await
918                }
919            }
920        })
921    }
922
923    fn eval_to_pairs<'a>(
924        &'a self,
925        path: &'a PropertyPath,
926        ends: &'a [TermId],
927        ctx: &'a QueryContext,
928        cap: WalkCap,
929    ) -> PathPairsFuture<'a> {
930        Box::pin(async move {
931            if ends.is_empty() {
932                return Ok(Vec::new());
933            }
934            ensure_frontier(&cap, ends.len())?;
935            match path {
936                PropertyPath::Predicate(predicate) => {
937                    self.hop_to(ends, Some(predicate), None, ctx, &cap).await
938                }
939                // Bound ends of `^inner` are bound *starts* of `inner`. Same pair flip
940                // as `eval_from` / `eval_open` — without it, `?x` on `:bob ^(:knows+) ?x`
941                // would bind `:bob` instead of `:alice`.
942                PropertyPath::Reverse(inner) => finish_output(
943                    &cap,
944                    reverse_pairs(self.eval_from_pairs(inner, ends, ctx, cap.clone()).await?),
945                ),
946                PropertyPath::Sequence(a, b) => {
947                    // Backward `/` evaluates `b` first; LIMIT on either operand
948                    // can drop the only middle that still joins with `a`.
949                    let middles = self
950                        .eval_to_pairs(b, ends, ctx, cap.clone().adjacency())
951                        .await?;
952                    let starts_of_b = unique_terms(middles.iter().map(|(s, _, _)| *s));
953                    let a_pairs = self
954                        .eval_to_pairs(a, &starts_of_b, ctx, cap.clone().adjacency())
955                        .await?;
956                    finish_output(&cap, join_sequence_backward(a_pairs, middles, &cap)?)
957                }
958                PropertyPath::Alternative(a, b) => {
959                    let left = self.eval_to_pairs(a, ends, ctx, cap.clone()).await?;
960                    if cap.enough_solutions(&left) {
961                        return Ok(take_solutions(left, &cap));
962                    }
963                    let right = self.eval_to_pairs(b, ends, ctx, cap.clone()).await?;
964                    // SPARQL `|` is UNION: keep both branches' bags.
965                    finish_output(&cap, concat_path_bags(left, right, &cap)?)
966                }
967                PropertyPath::ZeroOrMore(inner) => {
968                    let seed = identity_pairs(ends.iter().cloned(), &cap.identity_graphs);
969                    self.pair_closure_backward(seed, inner, ctx, cap, None)
970                        .await
971                }
972                PropertyPath::OneOrMore(inner) => {
973                    let first = self
974                        .eval_to_pairs(inner, ends, ctx, cap.clone().adjacency())
975                        .await?;
976                    self.pair_closure_backward(first, inner, ctx, cap, None)
977                        .await
978                }
979                PropertyPath::ZeroOrOne(inner) => {
980                    let identity = identity_pairs(ends.iter().cloned(), &cap.identity_graphs);
981                    if cap.enough_solutions(&identity) {
982                        return Ok(take_solutions(identity, &cap));
983                    }
984                    let stepped = self.eval_to_pairs(inner, ends, ctx, cap.clone()).await?;
985                    finish_output(&cap, unique_pairs(identity.into_iter().chain(stepped)))
986                }
987                PropertyPath::NegatedPropertySet(forbidden) => {
988                    self.hop_to(ends, None, Some(forbidden), ctx, &cap).await
989                }
990            }
991        })
992    }
993
994    fn eval_open_pairs<'a>(
995        &'a self,
996        path: &'a PropertyPath,
997        ctx: &'a QueryContext,
998        cap: WalkCap,
999    ) -> PathPairsFuture<'a> {
1000        Box::pin(async move {
1001            match path {
1002                PropertyPath::Predicate(predicate) => {
1003                    self.hop_open(Some(predicate), None, ctx, &cap).await
1004                }
1005                PropertyPath::Reverse(inner) => finish_output(
1006                    &cap,
1007                    reverse_pairs(self.eval_open_pairs(inner, ctx, cap.clone()).await?),
1008                ),
1009                PropertyPath::Sequence(a, b) => {
1010                    // Same as `eval_from`: do not slice `a` before the `/` join.
1011                    let middles = self
1012                        .eval_open_pairs(a, ctx, cap.clone().adjacency())
1013                        .await?;
1014                    self.sequence_extend(middles, b, ctx, cap).await
1015                }
1016                PropertyPath::Alternative(a, b) => {
1017                    let left = self.eval_open_pairs(a, ctx, cap.clone()).await?;
1018                    if cap.enough_solutions(&left) {
1019                        return Ok(take_solutions(left, &cap));
1020                    }
1021                    let right = self.eval_open_pairs(b, ctx, cap.clone()).await?;
1022                    // SPARQL `|` is UNION: keep both branches' bags.
1023                    finish_output(&cap, concat_path_bags(left, right, &cap)?)
1024                }
1025                PropertyPath::ZeroOrMore(inner) => {
1026                    let seed = self.graph_nodes(ctx, &cap).await?;
1027                    self.pair_closure(seed, inner, ctx, cap, None).await
1028                }
1029                PropertyPath::OneOrMore(inner) => {
1030                    let first = self
1031                        .eval_open_pairs(inner, ctx, cap.clone().adjacency())
1032                        .await?;
1033                    self.pair_closure(first, inner, ctx, cap, None).await
1034                }
1035                PropertyPath::ZeroOrOne(inner) => {
1036                    let identity = self.graph_nodes(ctx, &cap).await?;
1037                    if cap.enough_solutions(&identity) {
1038                        return Ok(take_solutions(identity, &cap));
1039                    }
1040                    let stepped = self.eval_open_pairs(inner, ctx, cap.clone()).await?;
1041                    finish_output(&cap, unique_pairs(identity.into_iter().chain(stepped)))
1042                }
1043                PropertyPath::NegatedPropertySet(forbidden) => {
1044                    self.hop_open(None, Some(forbidden), ctx, &cap).await
1045                }
1046            }
1047        })
1048    }
1049
1050    async fn eval_closed_pairs(
1051        &self,
1052        path: &PropertyPath,
1053        starts: &[TermId],
1054        ends: &[TermId],
1055        ctx: &QueryContext,
1056        cap: WalkCap,
1057    ) -> Result<Vec<PathPair>, ComputeError> {
1058        if starts.is_empty() || ends.is_empty() {
1059            return Ok(Vec::new());
1060        }
1061        // `*` / `?` identity: `:ghost :knows* :ghost` is true with no walk.
1062        // Under `GRAPH ?g` this is one pair per eligible named graph, never
1063        // DefaultGraph.
1064        if starts.len() == 1
1065            && ends.len() == 1
1066            && starts[0] == ends[0]
1067            && matches!(
1068                path,
1069                PropertyPath::ZeroOrMore(_) | PropertyPath::ZeroOrOne(_)
1070            )
1071        {
1072            return Ok(identity_pairs(
1073                std::iter::once(starts[0]),
1074                &cap.identity_graphs,
1075            ));
1076        }
1077        match path {
1078            PropertyPath::Reverse(inner) => Ok(reverse_pairs(
1079                Box::pin(self.eval_closed_pairs(inner, ends, starts, ctx, cap)).await?,
1080            )),
1081            PropertyPath::ZeroOrMore(inner) => {
1082                self.eval_closed_closure(inner, starts, ends, ctx, cap, ClosureKind::ZeroOrMore)
1083                    .await
1084            }
1085            PropertyPath::OneOrMore(inner) => {
1086                self.eval_closed_closure(inner, starts, ends, ctx, cap, ClosureKind::OneOrMore)
1087                    .await
1088            }
1089            PropertyPath::ZeroOrOne(inner) => {
1090                self.eval_closed_question(inner, starts, ends, ctx, cap)
1091                    .await
1092            }
1093            _ => {
1094                // Counting `/` `|` `!` (and a lone predicate): LIMIT counts
1095                // only pairs that hit the other end, but bags are not capped
1096                // at `|starts|×|ends|`.
1097                if starts.len() <= ends.len() {
1098                    self.eval_from_pairs(path, starts, ctx, cap.closed_hits_end(ends))
1099                        .await
1100                } else {
1101                    self.eval_to_pairs(path, ends, ctx, cap.closed_hits_start(starts))
1102                        .await
1103                }
1104            }
1105        }
1106    }
1107
1108    async fn eval_closed_question(
1109        &self,
1110        inner: &PropertyPath,
1111        starts: &[TermId],
1112        ends: &[TermId],
1113        ctx: &QueryContext,
1114        cap: WalkCap,
1115    ) -> Result<Vec<PathPair>, ComputeError> {
1116        let fwd_cap = cap.clone().closed_forward(starts, ends);
1117        let mut seen = PairSet::new();
1118        let mut out = Vec::new();
1119        let mut unused = Vec::new();
1120        // One memo per cap over the shared `out` (bidirectional recording):
1121        // each cap's count stays exact regardless of which cap pushed.
1122        let mut fwd_solutions = SolutionCountMemo::default();
1123        let mut bwd_solutions = SolutionCountMemo::default();
1124        for pair in identity_pairs(intersect_terms(starts, ends), &fwd_cap.identity_graphs) {
1125            if record_pair_frontier(
1126                &fwd_cap,
1127                &mut seen,
1128                &mut out,
1129                None,
1130                &mut fwd_solutions,
1131                pair,
1132            )? {
1133                return Ok(out);
1134            }
1135        }
1136        if starts.len() < ends.len() {
1137            let stepped = self
1138                .eval_from_pairs(inner, starts, ctx, fwd_cap.clone())
1139                .await?;
1140            for pair in stepped {
1141                if record_pair_frontier(
1142                    &fwd_cap,
1143                    &mut seen,
1144                    &mut out,
1145                    Some(&mut unused),
1146                    &mut fwd_solutions,
1147                    pair,
1148                )? {
1149                    return Ok(out);
1150                }
1151            }
1152            return Ok(take_solutions(out, &fwd_cap));
1153        }
1154        if ends.len() < starts.len() {
1155            let bwd_cap = cap.closed_backward(starts, ends);
1156            let stepped = self
1157                .eval_to_pairs(inner, ends, ctx, bwd_cap.clone())
1158                .await?;
1159            for pair in stepped {
1160                if record_pair_frontier(
1161                    &bwd_cap,
1162                    &mut seen,
1163                    &mut out,
1164                    Some(&mut unused),
1165                    &mut bwd_solutions,
1166                    pair,
1167                )? {
1168                    return Ok(out);
1169                }
1170            }
1171            return Ok(take_solutions(out, &bwd_cap));
1172        }
1173        let (fwd, enough) = self
1174            .collect_inner_hop(inner, starts, ctx, &fwd_cap, &out, true)
1175            .await?;
1176        for pair in fwd {
1177            if record_pair_frontier(
1178                &fwd_cap,
1179                &mut seen,
1180                &mut out,
1181                Some(&mut unused),
1182                &mut fwd_solutions,
1183                pair,
1184            )? {
1185                return Ok(out);
1186            }
1187        }
1188        if enough || fwd_cap.enough_solutions(&out) {
1189            return Ok(take_solutions(out, &fwd_cap));
1190        }
1191        let bwd_cap = cap.closed_backward(starts, ends);
1192        let (bwd, _) = self
1193            .collect_inner_hop(inner, ends, ctx, &bwd_cap, &out, false)
1194            .await?;
1195        for pair in bwd {
1196            if record_pair_frontier(
1197                &bwd_cap,
1198                &mut seen,
1199                &mut out,
1200                Some(&mut unused),
1201                &mut bwd_solutions,
1202                pair,
1203            )? {
1204                return Ok(out);
1205            }
1206        }
1207        Ok(take_solutions(out, &fwd_cap))
1208    }
1209
1210    async fn eval_closed_closure(
1211        &self,
1212        inner: &PropertyPath,
1213        starts: &[TermId],
1214        ends: &[TermId],
1215        ctx: &QueryContext,
1216        cap: WalkCap,
1217        kind: ClosureKind,
1218    ) -> Result<Vec<PathPair>, ComputeError> {
1219        if starts.len() < ends.len() {
1220            let fwd_cap = cap.closed_forward(starts, ends);
1221            return self
1222                .closed_walk_from(kind, inner, starts, ctx, fwd_cap, None)
1223                .await;
1224        }
1225        if ends.len() < starts.len() {
1226            let bwd_cap = cap.closed_backward(starts, ends);
1227            return self
1228                .closed_walk_to(kind, inner, ends, ctx, bwd_cap, None)
1229                .await;
1230        }
1231        self.eval_closed_equal_probe(inner, starts, ends, ctx, cap, kind)
1232            .await
1233    }
1234
1235    async fn closed_walk_from(
1236        &self,
1237        kind: ClosureKind,
1238        inner: &PropertyPath,
1239        starts: &[TermId],
1240        ctx: &QueryContext,
1241        cap: WalkCap,
1242        fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
1243    ) -> Result<Vec<PathPair>, ComputeError> {
1244        match kind {
1245            ClosureKind::ZeroOrMore => {
1246                let seed = identity_pairs(starts.iter().cloned(), &cap.identity_graphs);
1247                self.pair_closure(seed, inner, ctx, cap, fringe).await
1248            }
1249            ClosureKind::OneOrMore => {
1250                let first = self
1251                    .eval_from_pairs(inner, starts, ctx, cap.clone().adjacency())
1252                    .await?;
1253                self.pair_closure(first, inner, ctx, cap, fringe).await
1254            }
1255        }
1256    }
1257
1258    async fn closed_walk_to(
1259        &self,
1260        kind: ClosureKind,
1261        inner: &PropertyPath,
1262        ends: &[TermId],
1263        ctx: &QueryContext,
1264        cap: WalkCap,
1265        fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
1266    ) -> Result<Vec<PathPair>, ComputeError> {
1267        match kind {
1268            ClosureKind::ZeroOrMore => {
1269                let seed = identity_pairs(ends.iter().cloned(), &cap.identity_graphs);
1270                self.pair_closure_backward(seed, inner, ctx, cap, fringe)
1271                    .await
1272            }
1273            ClosureKind::OneOrMore => {
1274                let first = self
1275                    .eval_to_pairs(inner, ends, ctx, cap.clone().adjacency())
1276                    .await?;
1277                self.pair_closure_backward(first, inner, ctx, cap, fringe)
1278                    .await
1279            }
1280        }
1281    }
1282
1283    /// Equal-length seed lists: 1-hop both ways, confirm hits and length-2
1284    /// middles, then continue from the smaller unique-neighbour frontier.
1285    async fn eval_closed_equal_probe(
1286        &self,
1287        inner: &PropertyPath,
1288        starts: &[TermId],
1289        ends: &[TermId],
1290        ctx: &QueryContext,
1291        cap: WalkCap,
1292        kind: ClosureKind,
1293    ) -> Result<Vec<PathPair>, ComputeError> {
1294        let fwd_cap = cap.clone().closed_forward(starts, ends);
1295        let bwd_cap = cap.closed_backward(starts, ends);
1296        let mut seen = PairSet::new();
1297        let mut out = Vec::new();
1298        // One memo per cap over the shared `out` (bidirectional recording):
1299        // each cap's count stays exact regardless of which cap pushed.
1300        let mut fwd_solutions = SolutionCountMemo::default();
1301        let mut bwd_solutions = SolutionCountMemo::default();
1302        if matches!(kind, ClosureKind::ZeroOrMore) {
1303            for pair in identity_pairs(intersect_terms(starts, ends), &fwd_cap.identity_graphs) {
1304                if record_pair_frontier(
1305                    &fwd_cap,
1306                    &mut seen,
1307                    &mut out,
1308                    None,
1309                    &mut fwd_solutions,
1310                    pair,
1311                )? {
1312                    return Ok(out);
1313                }
1314            }
1315        }
1316        let (fwd, enough_fwd) = self
1317            .collect_inner_hop(inner, starts, ctx, &fwd_cap, &out, true)
1318            .await?;
1319        for pair in &fwd {
1320            if fwd_cap.pair_is_solution(&pair.0, &pair.1)
1321                && record_pair_frontier(
1322                    &fwd_cap,
1323                    &mut seen,
1324                    &mut out,
1325                    None,
1326                    &mut fwd_solutions,
1327                    *pair,
1328                )?
1329            {
1330                return Ok(out);
1331            }
1332        }
1333        if enough_fwd || fwd_cap.enough_solutions(&out) {
1334            return Ok(take_solutions(out, &fwd_cap));
1335        }
1336        let (bwd, enough_bwd) = self
1337            .collect_inner_hop(inner, ends, ctx, &bwd_cap, &out, false)
1338            .await?;
1339        for pair in &bwd {
1340            if bwd_cap.pair_is_solution(&pair.0, &pair.1)
1341                && record_pair_frontier(
1342                    &bwd_cap,
1343                    &mut seen,
1344                    &mut out,
1345                    None,
1346                    &mut bwd_solutions,
1347                    *pair,
1348                )?
1349            {
1350                return Ok(out);
1351            }
1352        }
1353        if enough_bwd || fwd_cap.enough_solutions(&out) {
1354            return Ok(take_solutions(out, &fwd_cap));
1355        }
1356        for pair in join_sequence_forward(fwd.clone(), bwd.clone(), &fwd_cap)? {
1357            if record_pair_frontier(
1358                &fwd_cap,
1359                &mut seen,
1360                &mut out,
1361                None,
1362                &mut fwd_solutions,
1363                pair,
1364            )? {
1365                return Ok(out);
1366            }
1367        }
1368        if fwd_cap.enough_solutions(&out) {
1369            return Ok(take_solutions(out, &fwd_cap));
1370        }
1371        let fwd_branch = unique_terms(fwd.iter().map(|(_, e, _)| *e)).len();
1372        let bwd_branch = unique_terms(bwd.iter().map(|(s, _, _)| *s)).len();
1373        if fwd.is_empty() && bwd.is_empty() {
1374            return Ok(take_solutions(out, &fwd_cap));
1375        }
1376        if !bwd.is_empty() && (fwd.is_empty() || bwd_branch < fwd_branch) {
1377            let fringe = group_by_end(&fwd);
1378            let mut frontier = Vec::new();
1379            for pair in bwd {
1380                if ensure_in_frontier(
1381                    &bwd_cap,
1382                    &mut seen,
1383                    &mut out,
1384                    &mut frontier,
1385                    &mut bwd_solutions,
1386                    pair,
1387                )? {
1388                    return Ok(out);
1389                }
1390            }
1391            self.expand_closure_waves(
1392                inner,
1393                ctx,
1394                &bwd_cap,
1395                &mut seen,
1396                &mut out,
1397                &mut bwd_solutions,
1398                &mut frontier,
1399                Some(&fringe),
1400                false,
1401            )
1402            .await?;
1403            return Ok(take_solutions(out, &bwd_cap));
1404        }
1405        let fringe = group_by_start(&bwd);
1406        let mut frontier = Vec::new();
1407        for pair in fwd {
1408            if ensure_in_frontier(
1409                &fwd_cap,
1410                &mut seen,
1411                &mut out,
1412                &mut frontier,
1413                &mut fwd_solutions,
1414                pair,
1415            )? {
1416                return Ok(out);
1417            }
1418        }
1419        self.expand_closure_waves(
1420            inner,
1421            ctx,
1422            &fwd_cap,
1423            &mut seen,
1424            &mut out,
1425            &mut fwd_solutions,
1426            &mut frontier,
1427            Some(&fringe),
1428            true,
1429        )
1430        .await?;
1431        Ok(take_solutions(out, &fwd_cap))
1432    }
1433
1434    /// One ALP step from `seeds`. Predicate/NPS pages so a hub can stop on a
1435    /// hit or the pair budget without holding the full neighbourhood.
1436    async fn collect_inner_hop(
1437        &self,
1438        inner: &PropertyPath,
1439        seeds: &[TermId],
1440        ctx: &QueryContext,
1441        closed_cap: &WalkCap,
1442        confirmed: &[PathPair],
1443        from_starts: bool,
1444    ) -> Result<(Vec<PathPair>, bool), ComputeError> {
1445        match inner {
1446            PropertyPath::Predicate(predicate) => {
1447                self.collect_predicate_hop(
1448                    seeds,
1449                    Some(predicate),
1450                    None,
1451                    ctx,
1452                    closed_cap,
1453                    confirmed,
1454                    from_starts,
1455                )
1456                .await
1457            }
1458            PropertyPath::NegatedPropertySet(forbidden) => {
1459                self.collect_predicate_hop(
1460                    seeds,
1461                    None,
1462                    Some(forbidden),
1463                    ctx,
1464                    closed_cap,
1465                    confirmed,
1466                    from_starts,
1467                )
1468                .await
1469            }
1470            _ => {
1471                let pairs = if from_starts {
1472                    self.eval_from_pairs(inner, seeds, ctx, closed_cap.clone().adjacency())
1473                        .await?
1474                } else {
1475                    self.eval_to_pairs(inner, seeds, ctx, closed_cap.clone().adjacency())
1476                        .await?
1477                };
1478                let enough = hop_would_be_enough(closed_cap, confirmed, &pairs);
1479                Ok((pairs, enough))
1480            }
1481        }
1482    }
1483
1484    #[allow(clippy::too_many_arguments)]
1485    async fn collect_predicate_hop(
1486        &self,
1487        seeds: &[TermId],
1488        predicate: Option<&EncodedTerm>,
1489        forbidden: Option<&[EncodedTerm]>,
1490        ctx: &QueryContext,
1491        closed_cap: &WalkCap,
1492        confirmed: &[PathPair],
1493        from_starts: bool,
1494    ) -> Result<(Vec<PathPair>, bool), ComputeError> {
1495        let mut acc = Vec::new();
1496        // Seed the enough-tracker ONCE from `confirmed`; each page then
1497        // contributes only its own pairs. A per-page `hop_would_be_enough`
1498        // rebuilt the membership set and recounted the whole accumulation
1499        // every page (O(pages × N), plus a fresh clone of every term).
1500        let mut enough = HopEnough::new(closed_cap, confirmed);
1501        let slot = if from_starts {
1502            PatternSlot::Subject
1503        } else {
1504            PatternSlot::Object
1505        };
1506        let stop = self
1507            .for_each_hop_pair_page(
1508                hop_pattern(predicate, closed_cap),
1509                slot,
1510                seeds,
1511                forbidden,
1512                ctx,
1513                closed_cap,
1514                |page| {
1515                    let stop = enough.absorb_page(closed_cap, &page);
1516                    acc.extend(page);
1517                    Ok(stop)
1518                },
1519            )
1520            .await?;
1521        Ok((acc, stop))
1522    }
1523
1524    async fn sequence_extend(
1525        &self,
1526        left_pairs: Vec<PathPair>,
1527        right: &PropertyPath,
1528        ctx: &QueryContext,
1529        cap: WalkCap,
1530    ) -> Result<Vec<PathPair>, ComputeError> {
1531        if left_pairs.is_empty() {
1532            return Ok(Vec::new());
1533        }
1534        let middles: Vec<TermId> = unique_terms(left_pairs.iter().map(|(_, m, _)| *m));
1535        let right_pairs = self
1536            .eval_from_pairs(right, &middles, ctx, cap.clone().adjacency())
1537            .await?;
1538        finish_output(&cap, join_sequence_forward(left_pairs, right_pairs, &cap)?)
1539    }
1540
1541    async fn pair_closure(
1542        &self,
1543        seed: Vec<PathPair>,
1544        step: &PropertyPath,
1545        ctx: &QueryContext,
1546        cap: WalkCap,
1547        fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
1548    ) -> Result<Vec<PathPair>, ComputeError> {
1549        let mut seen = PairSet::new();
1550        let mut out = Vec::new();
1551        let mut frontier = Vec::new();
1552        let mut solutions = SolutionCountMemo::default();
1553        for pair in seed {
1554            if record_pair(
1555                &cap,
1556                &mut seen,
1557                &mut out,
1558                &mut frontier,
1559                &mut solutions,
1560                pair,
1561            )? {
1562                return Ok(out);
1563            }
1564        }
1565        self.expand_closure_waves(
1566            step,
1567            ctx,
1568            &cap,
1569            &mut seen,
1570            &mut out,
1571            &mut solutions,
1572            &mut frontier,
1573            fringe,
1574            true,
1575        )
1576        .await?;
1577        Ok(out)
1578    }
1579
1580    async fn pair_closure_backward(
1581        &self,
1582        seed: Vec<PathPair>,
1583        step: &PropertyPath,
1584        ctx: &QueryContext,
1585        cap: WalkCap,
1586        fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
1587    ) -> Result<Vec<PathPair>, ComputeError> {
1588        let mut seen = PairSet::new();
1589        let mut out = Vec::new();
1590        let mut frontier = Vec::new();
1591        let mut solutions = SolutionCountMemo::default();
1592        for pair in seed {
1593            if record_pair(
1594                &cap,
1595                &mut seen,
1596                &mut out,
1597                &mut frontier,
1598                &mut solutions,
1599                pair,
1600            )? {
1601                return Ok(out);
1602            }
1603        }
1604        self.expand_closure_waves(
1605            step,
1606            ctx,
1607            &cap,
1608            &mut seen,
1609            &mut out,
1610            &mut solutions,
1611            &mut frontier,
1612            fringe,
1613            false,
1614        )
1615        .await?;
1616        Ok(out)
1617    }
1618
1619    #[allow(clippy::too_many_arguments)]
1620    async fn expand_closure_waves(
1621        &self,
1622        step: &PropertyPath,
1623        ctx: &QueryContext,
1624        cap: &WalkCap,
1625        seen: &mut PairSet,
1626        out: &mut Vec<PathPair>,
1627        solutions: &mut SolutionCountMemo,
1628        frontier: &mut Vec<PathPair>,
1629        fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
1630        forward: bool,
1631    ) -> Result<(), ComputeError> {
1632        while !frontier.is_empty() {
1633            let mut next = Vec::new();
1634            let stop = if forward {
1635                let middles = unique_terms(frontier.iter().map(|(_, m, _)| *m));
1636                self.expand_from_step(
1637                    step, frontier, &middles, ctx, cap, seen, out, solutions, &mut next, fringe,
1638                )
1639                .await?
1640            } else {
1641                let currents = unique_terms(frontier.iter().map(|(s, _, _)| *s));
1642                self.expand_to_step(
1643                    step, frontier, &currents, ctx, cap, seen, out, solutions, &mut next, fringe,
1644                )
1645                .await?
1646            };
1647            if stop {
1648                return Ok(());
1649            }
1650            *frontier = next;
1651        }
1652        Ok(())
1653    }
1654
1655    /// One closure wave: Predicate/NPS hops fold each scan page into `record_pair`
1656    /// and drop it. Nested paths still materialise the full step, then expand.
1657    #[allow(clippy::too_many_arguments)]
1658    async fn expand_from_step(
1659        &self,
1660        step: &PropertyPath,
1661        frontier: &[PathPair],
1662        middles: &[TermId],
1663        ctx: &QueryContext,
1664        cap: &WalkCap,
1665        seen: &mut PairSet,
1666        out: &mut Vec<PathPair>,
1667        solutions: &mut SolutionCountMemo,
1668        next: &mut Vec<PathPair>,
1669        fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
1670    ) -> Result<bool, ComputeError> {
1671        match step {
1672            PropertyPath::Predicate(predicate) => {
1673                self.expand_from_hop_pages(
1674                    frontier,
1675                    middles,
1676                    Some(predicate),
1677                    None,
1678                    ctx,
1679                    cap,
1680                    seen,
1681                    out,
1682                    solutions,
1683                    next,
1684                    fringe,
1685                )
1686                .await
1687            }
1688            PropertyPath::NegatedPropertySet(forbidden) => {
1689                self.expand_from_hop_pages(
1690                    frontier,
1691                    middles,
1692                    None,
1693                    Some(forbidden),
1694                    ctx,
1695                    cap,
1696                    seen,
1697                    out,
1698                    solutions,
1699                    next,
1700                    fringe,
1701                )
1702                .await
1703            }
1704            _ => {
1705                let stepped = self
1706                    .eval_from_pairs(step, middles, ctx, cap.clone().adjacency())
1707                    .await?;
1708                let by_middle = group_by_start(&stepped);
1709                for (start, middle, graph) in frontier {
1710                    if let Some(ends) = by_middle.get(&(*middle, *graph)) {
1711                        for end in ends {
1712                            let pair = (*start, *end, *graph);
1713                            if record_with_fringe(
1714                                cap, seen, out, next, solutions, pair, fringe, true,
1715                            )? {
1716                                return Ok(true);
1717                            }
1718                        }
1719                    }
1720                }
1721                Ok(false)
1722            }
1723        }
1724    }
1725
1726    #[allow(clippy::too_many_arguments)]
1727    async fn expand_to_step(
1728        &self,
1729        step: &PropertyPath,
1730        frontier: &[PathPair],
1731        currents: &[TermId],
1732        ctx: &QueryContext,
1733        cap: &WalkCap,
1734        seen: &mut PairSet,
1735        out: &mut Vec<PathPair>,
1736        solutions: &mut SolutionCountMemo,
1737        next: &mut Vec<PathPair>,
1738        fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
1739    ) -> Result<bool, ComputeError> {
1740        match step {
1741            PropertyPath::Predicate(predicate) => {
1742                self.expand_to_hop_pages(
1743                    frontier,
1744                    currents,
1745                    Some(predicate),
1746                    None,
1747                    ctx,
1748                    cap,
1749                    seen,
1750                    out,
1751                    solutions,
1752                    next,
1753                    fringe,
1754                )
1755                .await
1756            }
1757            PropertyPath::NegatedPropertySet(forbidden) => {
1758                self.expand_to_hop_pages(
1759                    frontier,
1760                    currents,
1761                    None,
1762                    Some(forbidden),
1763                    ctx,
1764                    cap,
1765                    seen,
1766                    out,
1767                    solutions,
1768                    next,
1769                    fringe,
1770                )
1771                .await
1772            }
1773            _ => {
1774                let stepped = self
1775                    .eval_to_pairs(step, currents, ctx, cap.clone().adjacency())
1776                    .await?;
1777                let by_end = group_by_end(&stepped);
1778                for (current, end, graph) in frontier {
1779                    if let Some(starts) = by_end.get(&(*current, *graph)) {
1780                        for start in starts {
1781                            let pair = (*start, *end, *graph);
1782                            if record_with_fringe(
1783                                cap, seen, out, next, solutions, pair, fringe, false,
1784                            )? {
1785                                return Ok(true);
1786                            }
1787                        }
1788                    }
1789                }
1790                Ok(false)
1791            }
1792        }
1793    }
1794
1795    #[allow(clippy::too_many_arguments)]
1796    async fn expand_from_hop_pages(
1797        &self,
1798        frontier: &[PathPair],
1799        middles: &[TermId],
1800        predicate: Option<&EncodedTerm>,
1801        forbidden: Option<&[EncodedTerm]>,
1802        ctx: &QueryContext,
1803        cap: &WalkCap,
1804        seen: &mut PairSet,
1805        out: &mut Vec<PathPair>,
1806        solutions: &mut SolutionCountMemo,
1807        next: &mut Vec<PathPair>,
1808        fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
1809    ) -> Result<bool, ComputeError> {
1810        // frontier (start, middle) → lookup starts that share this hop subject.
1811        let by_middle = group_by_end(frontier);
1812        self.for_each_hop_pair_page(
1813            hop_pattern(predicate, cap),
1814            PatternSlot::Subject,
1815            middles,
1816            forbidden,
1817            ctx,
1818            cap,
1819            |page| {
1820                for (middle, neighbor, graph) in page {
1821                    if let Some(starts) = by_middle.get(&(middle, graph)) {
1822                        for start in starts {
1823                            if record_with_fringe(
1824                                cap,
1825                                seen,
1826                                out,
1827                                next,
1828                                solutions,
1829                                (*start, neighbor, graph),
1830                                fringe,
1831                                true,
1832                            )? {
1833                                return Ok(true);
1834                            }
1835                        }
1836                    }
1837                }
1838                Ok(false)
1839            },
1840        )
1841        .await
1842    }
1843
1844    #[allow(clippy::too_many_arguments)]
1845    async fn expand_to_hop_pages(
1846        &self,
1847        frontier: &[PathPair],
1848        currents: &[TermId],
1849        predicate: Option<&EncodedTerm>,
1850        forbidden: Option<&[EncodedTerm]>,
1851        ctx: &QueryContext,
1852        cap: &WalkCap,
1853        seen: &mut PairSet,
1854        out: &mut Vec<PathPair>,
1855        solutions: &mut SolutionCountMemo,
1856        next: &mut Vec<PathPair>,
1857        fringe: Option<&HashMap<(TermId, TermId), Vec<TermId>>>,
1858    ) -> Result<bool, ComputeError> {
1859        // frontier (current, end) → lookup ends that share this hop object.
1860        let by_current = group_by_start(frontier);
1861        self.for_each_hop_pair_page(
1862            hop_pattern(predicate, cap),
1863            PatternSlot::Object,
1864            currents,
1865            forbidden,
1866            ctx,
1867            cap,
1868            |page| {
1869                for (neighbor, current, graph) in page {
1870                    if let Some(ends) = by_current.get(&(current, graph)) {
1871                        for end in ends {
1872                            if record_with_fringe(
1873                                cap,
1874                                seen,
1875                                out,
1876                                next,
1877                                solutions,
1878                                (neighbor, *end, graph),
1879                                fringe,
1880                                false,
1881                            )? {
1882                                return Ok(true);
1883                            }
1884                        }
1885                    }
1886                }
1887                Ok(false)
1888            },
1889        )
1890        .await
1891    }
1892
1893    async fn hop_from(
1894        &self,
1895        starts: &[TermId],
1896        predicate: Option<&EncodedTerm>,
1897        forbidden: Option<&[EncodedTerm]>,
1898        ctx: &QueryContext,
1899        cap: &WalkCap,
1900    ) -> Result<Vec<PathPair>, ComputeError> {
1901        let mut acc = Vec::new();
1902        let mut solutions = SolutionCountMemo::default();
1903        self.for_each_hop_pair_page(
1904            hop_pattern(predicate, cap),
1905            PatternSlot::Subject,
1906            starts,
1907            forbidden,
1908            ctx,
1909            cap,
1910            |page| absorb_hop_pairs(cap, &mut acc, &mut solutions, page),
1911        )
1912        .await?;
1913        if cap.hop_budget {
1914            enforce_budget(cap, acc)
1915        } else {
1916            Ok(acc)
1917        }
1918    }
1919
1920    async fn hop_to(
1921        &self,
1922        ends: &[TermId],
1923        predicate: Option<&EncodedTerm>,
1924        forbidden: Option<&[EncodedTerm]>,
1925        ctx: &QueryContext,
1926        cap: &WalkCap,
1927    ) -> Result<Vec<PathPair>, ComputeError> {
1928        let mut acc = Vec::new();
1929        let mut solutions = SolutionCountMemo::default();
1930        self.for_each_hop_pair_page(
1931            hop_pattern(predicate, cap),
1932            PatternSlot::Object,
1933            ends,
1934            forbidden,
1935            ctx,
1936            cap,
1937            |page| absorb_hop_pairs(cap, &mut acc, &mut solutions, page),
1938        )
1939        .await?;
1940        if cap.hop_budget {
1941            enforce_budget(cap, acc)
1942        } else {
1943            Ok(acc)
1944        }
1945    }
1946
1947    async fn hop_open(
1948        &self,
1949        predicate: Option<&EncodedTerm>,
1950        forbidden: Option<&[EncodedTerm]>,
1951        ctx: &QueryContext,
1952        cap: &WalkCap,
1953    ) -> Result<Vec<PathPair>, ComputeError> {
1954        let mut acc = Vec::new();
1955        let mut solutions = SolutionCountMemo::default();
1956        let dict = ctx.term_dict();
1957        self.for_each_scan_page(
1958            hop_pattern(predicate, cap),
1959            None,
1960            cap.graph_filter.as_ref(),
1961            cap.merge_default_graph,
1962            ctx,
1963            |quads| {
1964                absorb_hop_pairs(
1965                    cap,
1966                    &mut acc,
1967                    &mut solutions,
1968                    quads_to_pairs(dict.as_ref(), quads, forbidden)?,
1969                )
1970            },
1971        )
1972        .await?;
1973        if cap.hop_budget {
1974            enforce_budget(cap, acc)
1975        } else {
1976            Ok(acc)
1977        }
1978    }
1979
1980    async fn graph_nodes(
1981        &self,
1982        ctx: &QueryContext,
1983        cap: &WalkCap,
1984    ) -> Result<Vec<PathPair>, ComputeError> {
1985        let scan = ScanOp {
1986            ancestor_push_return_bound: None,
1987            fetch_once: None,
1988            pattern: EncodedTriplePattern {
1989                subject: None,
1990                predicate: None,
1991                object: None,
1992                graph_name: cap.graph_name.clone(),
1993            },
1994            subject: None,
1995            predicate: None,
1996            object: None,
1997            produced_row_count_estimate: 1,
1998            broadcasted: None,
1999            graph: None,
2000            graph_filter: cap.graph_filter.clone(),
2001            grounded: Vec::new(),
2002            merge_default_graph: cap.merge_default_graph,
2003            marks: Vec::new(),
2004            domain_scan: None,
2005            head_scan: None,
2006            head_scan_counts: None,
2007            domain_counts: None,
2008            iri_only: Vec::new(),
2009            eager: Vec::new(),
2010            join_domains: crate::plan::JoinDomainStamps::default(),
2011        };
2012        let batch = scan_batch() as u64;
2013        let dict = ctx.term_dict();
2014        let mut seen = PairSet::new();
2015        let mut out = Vec::new();
2016        let mut start_after: Option<EncodedQuad> = None;
2017        loop {
2018            ctx.check_abort()?;
2019            if let Some(max) = cap.max_solutions
2020                && (out.len() as u64) >= max
2021            {
2022                break;
2023            }
2024            let page_limit = if let Some(max) = cap.max_solutions {
2025                batch.min(max.saturating_sub(out.len() as u64).max(1))
2026            } else {
2027                batch
2028            };
2029            let page_started = std::time::Instant::now();
2030            let page_sent_at = epoch_millis_now();
2031            // Documented transport exception (plan §6 census, stage-2
2032            // audit): path windows page at a fixed `scan_batch()` (≤ the
2033            // unary ceiling) so `fetch_window`'s bounded-stream rule would
2034            // gain nothing, and `scan_page_at` deliberately skips
2035            // query-context tracing — path hops are high-frequency and
2036            // log their own `path-open`/`path-hop` lines instead.
2037            let page = self
2038                .scan_page_at(
2039                    &scan,
2040                    ctx.snapshot(),
2041                    None,
2042                    None,
2043                    page_limit,
2044                    start_after.as_ref(),
2045                    // Paging consumer: the absorb loop resumes from the
2046                    // cursor until the walk's own verdict ends it, so an
2047                    // exact-boundary terminal verdict saves one empty
2048                    // confirm request per hop scan. The verdict is
2049                    // load-bearing here — see the terminal break below;
2050                    // under purchase a short page always carries the
2051                    // terminal verdict (unary EDGE mode stops only at the
2052                    // limit, reporting LIMITED on a full page).
2053                    true,
2054                )
2055                .await?
2056                .0;
2057            let verdict = page.exhausted;
2058            let page = page.rows;
2059            ctx.log(
2060                LogLevel::Debug,
2061                &format!(
2062                    "scan-rpc[path-open] {:?} sent_at={} rows={}",
2063                    page_started.elapsed(),
2064                    page_sent_at,
2065                    page.len()
2066                ),
2067            );
2068            if page.is_empty() {
2069                break;
2070            }
2071            let n = page.len();
2072            start_after = page.last().cloned();
2073            // Absorb boundary: the open-scan page's S/O/G slots are interned
2074            // once here; the identity-pair loop below is pure id arithmetic.
2075            let (subjects, objects, graphs) = intern_quad_slots(dict.as_ref(), page.into_iter())?;
2076            for row in 0..n {
2077                for node in [subjects[row], objects[row]] {
2078                    let pair = (node, node, graphs[row]);
2079                    if seen.insert(node, node, graphs[row]) {
2080                        out.push(pair);
2081                    }
2082                    if let Some(max) = cap.max_solutions {
2083                        if (out.len() as u64) >= max {
2084                            out.truncate(max as usize);
2085                            return Ok(out);
2086                        }
2087                    } else if cap.over_budget(out.len()) {
2088                        return Err(pair_budget_error(cap, out.len()));
2089                    }
2090                }
2091            }
2092            // The walk's own verdict ends the loop: a full page carries
2093            // `Limited` (resume — one more page), a short page carries a
2094            // terminal verdict (the walk ended exactly here — the confirm
2095            // page the old row-count break cost). No row-count fallback:
2096            // under purchase a short page always carries the terminal
2097            // verdict, and the empty-page break above is the defensive
2098            // backstop for a misbehaving transport.
2099            if verdict.is_some_and(waratah_storage::ScanExhaustion::is_terminal) {
2100                break;
2101            }
2102        }
2103        if let Some(max) = cap.max_solutions {
2104            out.truncate(max as usize);
2105        }
2106        Ok(out)
2107    }
2108
2109    /// Page a path hop/open scan. Peak extra RAM is one `SCAN_BATCH` of quads.
2110    /// `visit` returns `true` to stop paging (LIMIT / pair budget already met).
2111    /// Broadcast filters still page: `start_after` resumes inside the matching
2112    /// allow-list term, then continues with later terms.
2113    #[allow(clippy::too_many_arguments)]
2114    async fn for_each_scan_page(
2115        &self,
2116        pattern: EncodedTriplePattern,
2117        filter: Option<&BroadcastFilter>,
2118        graph_filter: Option<&GraphFilter>,
2119        merge_default_graph: bool,
2120        ctx: &QueryContext,
2121        mut visit: impl FnMut(Vec<EncodedQuad>) -> Result<bool, ComputeError> + Send,
2122    ) -> Result<bool, ComputeError> {
2123        let scan = ScanOp {
2124            ancestor_push_return_bound: None,
2125            fetch_once: None,
2126            pattern,
2127            subject: None,
2128            predicate: None,
2129            object: None,
2130            produced_row_count_estimate: 1,
2131            broadcasted: None,
2132            graph: None,
2133            graph_filter: graph_filter.cloned(),
2134            grounded: Vec::new(),
2135            merge_default_graph,
2136            marks: Vec::new(),
2137            domain_scan: None,
2138            head_scan: None,
2139            head_scan_counts: None,
2140            domain_counts: None,
2141            iri_only: Vec::new(),
2142            eager: Vec::new(),
2143            join_domains: crate::plan::JoinDomainStamps::default(),
2144        };
2145        let batch = scan_batch() as u64;
2146        let mut start_after: Option<EncodedQuad> = None;
2147        loop {
2148            // Path hops use `scan_page_at` (no query_trace; documented
2149            // transport exception — see the path-open comment above);
2150            // abort before the RPC.
2151            ctx.check_abort()?;
2152            let page_started = std::time::Instant::now();
2153            let page_sent_at = epoch_millis_now();
2154            let page = self
2155                .scan_page_at(
2156                    &scan,
2157                    ctx.snapshot(),
2158                    filter,
2159                    None,
2160                    batch,
2161                    start_after.as_ref(),
2162                    // Paging consumer: the hop loop resumes from the
2163                    // cursor until the visit closure or the walk's own
2164                    // verdict ends it.
2165                    true,
2166                )
2167                .await?
2168                .0;
2169            let verdict = page.exhausted;
2170            let page = page.rows;
2171            ctx.log(
2172                LogLevel::Debug,
2173                &format!(
2174                    "scan-rpc[path-hop] {:?} sent_at={} rows={}",
2175                    page_started.elapsed(),
2176                    page_sent_at,
2177                    page.len()
2178                ),
2179            );
2180            if page.is_empty() {
2181                return Ok(false);
2182            }
2183            start_after = page.last().cloned();
2184            if visit(page)? {
2185                return Ok(true);
2186            }
2187            if verdict.is_some_and(waratah_storage::ScanExhaustion::is_terminal) {
2188                return Ok(false);
2189            }
2190        }
2191    }
2192
2193    #[allow(clippy::too_many_arguments)]
2194    async fn for_each_hop_pair_page(
2195        &self,
2196        pattern: EncodedTriplePattern,
2197        slot: PatternSlot,
2198        frontier: &[TermId],
2199        forbidden: Option<&[EncodedTerm]>,
2200        ctx: &QueryContext,
2201        cap: &WalkCap,
2202        mut visit: impl FnMut(Vec<PathPair>) -> Result<bool, ComputeError> + Send,
2203    ) -> Result<bool, ComputeError> {
2204        if frontier.is_empty() {
2205            return Ok(false);
2206        }
2207        let dict = ctx.term_dict();
2208        for chunk in frontier.chunks(PUSHDOWN_TERMS_LIMIT as usize) {
2209            // Raw terms cross OUT to storage here, promoted once per chunk —
2210            // the reverse direction of the page absorb in `quads_to_pairs`.
2211            let filter = BroadcastFilter {
2212                slot,
2213                terms: promote_terms(dict.as_ref(), chunk)?,
2214            };
2215            if self
2216                .for_each_scan_page(
2217                    pattern.clone(),
2218                    Some(&filter),
2219                    cap.graph_filter.as_ref(),
2220                    cap.merge_default_graph,
2221                    ctx,
2222                    |quads| visit(quads_to_pairs(dict.as_ref(), quads, forbidden)?),
2223                )
2224                .await?
2225            {
2226                return Ok(true);
2227            }
2228        }
2229        Ok(false)
2230    }
2231}
2232
2233fn path_frontiers(
2234    path: &PathOp,
2235    pushed: Option<&PushedKeyVals>,
2236) -> (Option<Vec<EncodedTerm>>, Option<Vec<EncodedTerm>>) {
2237    let mut starts = path.subject_term.clone().map(|term| vec![term]);
2238    let mut ends = path.object_term.clone().map(|term| vec![term]);
2239    if let Some(keys) = pushed {
2240        for (variable, terms) in keys.iter() {
2241            match path.end_of(variable) {
2242                Some(PathEnd::Start) if starts.is_none() => starts = Some(terms.to_vec()),
2243                Some(PathEnd::End) if ends.is_none() => ends = Some(terms.to_vec()),
2244                Some(PathEnd::Both) => {
2245                    if starts.is_none() {
2246                        starts = Some(terms.to_vec());
2247                    }
2248                    if ends.is_none() {
2249                        ends = Some(terms.to_vec());
2250                    }
2251                }
2252                _ => {}
2253            }
2254        }
2255    }
2256    (starts, ends)
2257}
2258
2259/// `s --^p--> o` iff `o --p--> s`. Bound Reverse walks the inner path from the
2260/// opposite end, so each pair must be flipped to restore path-start / path-end.
2261fn reverse_pairs(pairs: Vec<PathPair>) -> Vec<PathPair> {
2262    pairs.into_iter().map(|(s, o, g)| (o, s, g)).collect()
2263}
2264
2265fn solutions_from_pairs(
2266    dict: Arc<TermDict>,
2267    path: &PathOp,
2268    pairs: Vec<PathPair>,
2269) -> Result<EncodedSolutions, ComputeError> {
2270    let variables = path.variables();
2271    if variables.is_empty() {
2272        return if pairs.is_empty() {
2273            Ok(EncodedSolutions::empty(dict, Vec::new()))
2274        } else {
2275            EncodedSolutions::from_optional_rows(dict, Vec::new(), vec![Vec::new(); 1])
2276        };
2277    }
2278    // Same projection as [`EncodedSolutions::from_scan`]: first occurrence of a
2279    // variable owns the column (subject, then object, then graph). A later slot
2280    // with the same name (`GRAPH ?g { ?g :p+ ?o }`, `?x :p+ ?x`) must equal the
2281    // first or the pair is dropped — never a second column.
2282    let named = [
2283        (path.subject.as_ref(), 0usize),
2284        (path.object.as_ref(), 1),
2285        (path.graph.as_ref(), 2),
2286    ];
2287    let mut columns: Vec<usize> = Vec::new();
2288    let mut repeats: Vec<(usize, usize)> = Vec::new();
2289    let mut seen: Vec<&Variable> = Vec::new();
2290    for (variable, slot) in named {
2291        let Some(variable) = variable else { continue };
2292        match seen.iter().position(|known| *known == variable) {
2293            Some(first) => repeats.push((columns[first], slot)),
2294            None => {
2295                seen.push(variable);
2296                columns.push(slot);
2297            }
2298        }
2299    }
2300    debug_assert_eq!(seen.len(), variables.len());
2301    // The pairs already ARE TermId columns: assemble the output batch by
2302    // column copies — no row materialization, no second full pass re-interning
2303    // every term (the raw-era finish step did both).
2304    let mut id_columns: Vec<Vec<u32>> = (0..seen.len())
2305        .map(|_| Vec::with_capacity(pairs.len()))
2306        .collect();
2307    for (start, end, graph) in pairs {
2308        // Walk pairs carry interned terms by construction (page absorb or the
2309        // once-per-walk frontier intern). An unbound id here means a pair
2310        // producer broke that invariant — unchecked, it would silently emit
2311        // unbound output cells instead of terms.
2312        debug_assert!(
2313            !start.is_unbound() && !end.is_unbound() && !graph.is_unbound(),
2314            "walk pairs must carry interned (bound) term ids"
2315        );
2316        let cells = [start.0, end.0, graph.0];
2317        if repeats.iter().any(|(a, b)| cells[*a] != cells[*b]) {
2318            continue;
2319        }
2320        for (column, slot) in id_columns.iter_mut().zip(&columns) {
2321            column.push(cells[*slot]);
2322        }
2323    }
2324    let batch = TermBatch::try_new(id_columns.into_iter().map(TermColumn::from_ids).collect())?;
2325    Ok(EncodedSolutions::from_batch(dict, variables, batch))
2326}
2327
2328/// Convert a hop page to walk pairs at the absorb boundary. The
2329/// negated-property set filters the raw quads INSIDE the slot-push pass (a
2330/// dropped predicate never interns a term, and no intermediate kept-quads
2331/// vector is materialized), then the surviving S/O/G slots intern once.
2332fn quads_to_pairs(
2333    dict: &TermDict,
2334    quads: Vec<EncodedQuad>,
2335    forbidden: Option<&[EncodedTerm]>,
2336) -> Result<Vec<PathPair>, ComputeError> {
2337    let forbidden_keys: Option<std::collections::HashSet<EncodedTerm>> =
2338        forbidden.map(|ps| ps.iter().cloned().collect());
2339    let (subjects, objects, graphs) = intern_quad_slots(
2340        dict,
2341        quads.into_iter().filter(|quad| {
2342            forbidden_keys
2343                .as_ref()
2344                .is_none_or(|set| !set.contains(&quad.predicate))
2345        }),
2346    )?;
2347    Ok(subjects
2348        .into_iter()
2349        .zip(objects)
2350        .zip(graphs)
2351        .map(|((start, end), graph)| (start, end, graph))
2352        .collect())
2353}
2354
2355fn join_sequence_forward(
2356    left: Vec<PathPair>,
2357    right: Vec<PathPair>,
2358    cap: &WalkCap,
2359) -> Result<Vec<PathPair>, ComputeError> {
2360    let by_middle = group_by_start(&right);
2361    let mut out = Vec::new();
2362    let mut solutions = SolutionCountMemo::default();
2363    for (start, middle, graph) in left {
2364        if let Some(ends) = by_middle.get(&(middle, graph)) {
2365            for end in ends {
2366                if push_budgeted_pair(cap, &mut out, &mut solutions, (start, *end, graph))? {
2367                    return Ok(out);
2368                }
2369            }
2370        }
2371    }
2372    Ok(out)
2373}
2374
2375fn join_sequence_backward(
2376    a_pairs: Vec<PathPair>,
2377    b_pairs: Vec<PathPair>,
2378    cap: &WalkCap,
2379) -> Result<Vec<PathPair>, ComputeError> {
2380    let by_end = group_by_end(&a_pairs);
2381    let mut out = Vec::new();
2382    let mut solutions = SolutionCountMemo::default();
2383    for (middle, end, graph) in b_pairs {
2384        if let Some(starts) = by_end.get(&(middle, graph)) {
2385            for start in starts {
2386                if push_budgeted_pair(cap, &mut out, &mut solutions, (*start, end, graph))? {
2387                    return Ok(out);
2388                }
2389            }
2390        }
2391    }
2392    Ok(out)
2393}
2394
2395/// SPARQL `|` is UNION: append bags, but error as soon as the concat exceeds
2396/// `pair_budget`. `LIMIT` can still stop early via [`push_budgeted_pair`].
2397fn concat_path_bags(
2398    mut left: Vec<PathPair>,
2399    right: Vec<PathPair>,
2400    cap: &WalkCap,
2401) -> Result<Vec<PathPair>, ComputeError> {
2402    if cap.over_budget(left.len()) {
2403        return Err(pair_budget_error(cap, left.len()));
2404    }
2405    if cap.enough_solutions(&left) {
2406        return Ok(take_solutions(left, cap));
2407    }
2408    let mut solutions = SolutionCountMemo::default();
2409    for pair in right {
2410        if push_budgeted_pair(cap, &mut left, &mut solutions, pair)? {
2411            return Ok(left);
2412        }
2413    }
2414    Ok(left)
2415}
2416
2417/// 0-hop `(n, n, g)` for each identity graph. Hop scans are unchanged.
2418fn identity_pairs(nodes: impl IntoIterator<Item = TermId>, graphs: &[TermId]) -> Vec<PathPair> {
2419    let nodes: Vec<TermId> = nodes.into_iter().collect();
2420    let mut out = Vec::with_capacity(nodes.len().saturating_mul(graphs.len()));
2421    for n in nodes {
2422        for g in graphs {
2423            out.push((n, n, *g));
2424        }
2425    }
2426    out
2427}
2428
2429fn group_by_start(pairs: &[PathPair]) -> HashMap<(TermId, TermId), Vec<TermId>> {
2430    let mut map: HashMap<(TermId, TermId), Vec<TermId>> = HashMap::new();
2431    for (start, end, graph) in pairs {
2432        map.entry((*start, *graph)).or_default().push(*end);
2433    }
2434    map
2435}
2436
2437fn group_by_end(pairs: &[PathPair]) -> HashMap<(TermId, TermId), Vec<TermId>> {
2438    let mut map: HashMap<(TermId, TermId), Vec<TermId>> = HashMap::new();
2439    for (start, end, graph) in pairs {
2440        map.entry((*end, *graph)).or_default().push(*start);
2441    }
2442    map
2443}
2444
2445/// Connectivity collapse for `?` (identity ∪ one step). `/` / `|` / `!` must not
2446/// use this: those operators keep bag multiplicity.
2447fn unique_pairs(pairs: impl IntoIterator<Item = PathPair>) -> Vec<PathPair> {
2448    let mut seen = PairSet::new();
2449    let mut out = Vec::new();
2450    for pair in pairs {
2451        if seen.insert(pair.0, pair.1, pair.2) {
2452            out.push(pair);
2453        }
2454    }
2455    out
2456}
2457
2458fn unique_terms(terms: impl IntoIterator<Item = TermId>) -> Vec<TermId> {
2459    let mut set: HashSet<TermId> = HashSet::new();
2460    for term in terms {
2461        set.insert(term);
2462    }
2463    set.into_iter().collect()
2464}
2465
2466fn intersect_terms(starts: &[TermId], ends: &[TermId]) -> Vec<TermId> {
2467    let end_keys: HashSet<TermId> = ends.iter().copied().collect();
2468    unique_terms(
2469        starts
2470            .iter()
2471            .filter(|term| end_keys.contains(*term))
2472            .copied(),
2473    )
2474}
2475
2476fn zero_length_same_term(path: &PropertyPath) -> bool {
2477    matches!(
2478        path,
2479        PropertyPath::ZeroOrMore(_) | PropertyPath::ZeroOrOne(_)
2480    )
2481}
2482
2483/// Nested `*` / `?` still invent identity seeds (then join hops on node+graph).
2484fn path_has_zero_length_identity(path: &PropertyPath) -> bool {
2485    match path {
2486        PropertyPath::ZeroOrMore(_) | PropertyPath::ZeroOrOne(_) => true,
2487        PropertyPath::Reverse(inner) | PropertyPath::OneOrMore(inner) => {
2488            path_has_zero_length_identity(inner)
2489        }
2490        PropertyPath::Sequence(a, b) | PropertyPath::Alternative(a, b) => {
2491            path_has_zero_length_identity(a) || path_has_zero_length_identity(b)
2492        }
2493        PropertyPath::Predicate(_) | PropertyPath::NegatedPropertySet(_) => false,
2494    }
2495}
2496
2497struct PairSet {
2498    inner: HashSet<(TermId, TermId, TermId)>,
2499}
2500
2501impl PairSet {
2502    fn new() -> Self {
2503        Self {
2504            inner: HashSet::new(),
2505        }
2506    }
2507
2508    fn insert(&mut self, start: TermId, end: TermId, graph: TermId) -> bool {
2509        self.inner.insert((start, end, graph))
2510    }
2511
2512    fn len(&self) -> usize {
2513        self.inner.len()
2514    }
2515}
2516
2517#[cfg(test)]
2518mod tests {
2519    use super::*;
2520    use waratah_storage::StrHash;
2521
2522    /// `WalkCap` for the counting tests: thresholds and targets parameterized,
2523    /// everything else at walk-neutral defaults.
2524    fn test_cap(
2525        max_solutions: Option<u64>,
2526        max_closed: Option<u64>,
2527        targets: Option<HashSet<TermId>>,
2528    ) -> WalkCap {
2529        WalkCap {
2530            pair_budget: 1_000_000,
2531            max_solutions,
2532            same_term: false,
2533            targets,
2534            match_start: false,
2535            max_closed,
2536            hop_budget: true,
2537            graph_name: None,
2538            graph_filter: None,
2539            merge_default_graph: false,
2540            in_named_graph: false,
2541            identity_graphs: Arc::from(vec![TermId::DEFAULT_GRAPH]),
2542        }
2543    }
2544
2545    /// One dict per test binary: ids minted by `node` are stable and unique
2546    /// per name, exactly like one query's shared TermDict.
2547    fn dict() -> Arc<TermDict> {
2548        static DICT: std::sync::OnceLock<Arc<TermDict>> = std::sync::OnceLock::new();
2549        DICT.get_or_init(TermDict::new_shared).clone()
2550    }
2551
2552    fn node(name: &str) -> TermId {
2553        dict()
2554            .intern(EncodedTerm::NamedNode {
2555                iri_id: StrHash::new(&format!("http://ex/{name}")),
2556            })
2557            .expect("test dict intern")
2558    }
2559
2560    fn graph() -> TermId {
2561        TermId::DEFAULT_GRAPH
2562    }
2563
2564    #[test]
2565    fn solution_count_memo_matches_a_full_recount() {
2566        // The memo's amortized count must equal a fresh `solution_count`
2567        // over the whole list at EVERY point — including after a
2568        // truncation (a satisfied LIMIT taking its solutions), which
2569        // invalidates the counted prefix and must reset the memo.
2570        let hit = node("hit");
2571        let cap = test_cap(Some(100), None, Some(HashSet::from([hit])));
2572        let mut out: Vec<PathPair> = Vec::new();
2573        let mut memo = SolutionCountMemo::default();
2574        for i in 0..64 {
2575            let end = if i % 3 == 0 {
2576                hit
2577            } else {
2578                node(&format!("n{i}"))
2579            };
2580            out.push((node(&format!("s{i}")), end, graph()));
2581            assert_eq!(memo.solutions(&cap, &out), solution_count(&cap, &out));
2582        }
2583        // Truncation (a satisfied LIMIT took its solutions): the
2584        // truncation sites pair every list replacement with reset(), and
2585        // the memo must recount from zero afterward.
2586        out.truncate(10);
2587        memo.reset();
2588        assert_eq!(memo.solutions(&cap, &out), solution_count(&cap, &out));
2589        for i in 64..96 {
2590            out.push((node(&format!("s{i}")), node(&format!("n{i}")), graph()));
2591            assert_eq!(memo.solutions(&cap, &out), solution_count(&cap, &out));
2592        }
2593    }
2594
2595    #[test]
2596    fn hop_would_be_enough_matches_the_brute_force_verdict() {
2597        // The brute-force reference is the pre-fix shape verbatim: clone
2598        // `confirmed`, linear-scan membership, full recount per new hit.
2599        // The hash-set + running-count rewrite must agree on every
2600        // threshold combination.
2601        fn brute_force(cap: &WalkCap, confirmed: &[PathPair], hop: &[PathPair]) -> bool {
2602            let mut acc = confirmed.to_vec();
2603            for (start, end, graph) in hop {
2604                if cap.pair_is_solution(start, end)
2605                    && !acc
2606                        .iter()
2607                        .any(|(s, e, g)| s == start && e == end && g == graph)
2608                {
2609                    acc.push((*start, *end, *graph));
2610                    if cap.enough_solutions(&acc) {
2611                        return true;
2612                    }
2613                }
2614            }
2615            false
2616        }
2617        let hit = node("hit");
2618        let s = |n: usize| node(&format!("s{n}"));
2619        let confirmed: Vec<PathPair> = (0..6).map(|i| (s(i), hit, graph())).collect();
2620        // Some hop pairs repeat confirmed (start, end) pairs — membership
2621        // must treat them as known — and some hit, some do not.
2622        let hop: Vec<PathPair> = (0..12)
2623            .map(|i| {
2624                let end = if i % 2 == 0 {
2625                    hit
2626                } else {
2627                    node(&format!("h{i}"))
2628                };
2629                (s(i % 6), end, graph())
2630            })
2631            .collect();
2632        for (max_solutions, max_closed) in [
2633            (None, None),
2634            (Some(3), None),
2635            (Some(8), None),
2636            (None, Some(4)),
2637            (Some(50), Some(7)),
2638        ] {
2639            let cap = test_cap(max_solutions, max_closed, Some(HashSet::from([hit])));
2640            assert_eq!(
2641                hop_would_be_enough(&cap, &confirmed, &hop),
2642                brute_force(&cap, &confirmed, &hop),
2643                "verdict mismatch at {max_solutions:?}/{max_closed:?}"
2644            );
2645        }
2646    }
2647
2648    #[test]
2649    fn budgeted_absorb_does_not_recount_the_accumulation() {
2650        // The explorer-app alternation shape: a threshold-less open walk
2651        // (hop_budget, no LIMIT, no closed set, no targets) absorbing
2652        // pages of pairs. The per-pair `enough_solutions` check must cost
2653        // nothing — the pre-fix code recounted the whole accumulation per
2654        // pair, O(N²): at this size that is ~26s of pure counting, and
2655        // the bound below fails it while leaving the amortized check
2656        // (milliseconds) an order of magnitude of headroom.
2657        let cap = test_cap(None, None, None);
2658        let starts: Vec<TermId> = (0..64).map(|i| node(&format!("s{i}"))).collect();
2659        let ends: Vec<TermId> = (0..64).map(|i| node(&format!("o{i}"))).collect();
2660        let mut acc = Vec::new();
2661        let mut solutions = SolutionCountMemo::default();
2662        let started = std::time::Instant::now();
2663        for page in 0..20 {
2664            let batch: Vec<PathPair> = (0..10_000)
2665                .map(|i| (starts[(page * 10_000 + i) % 64], ends[i % 64], graph()))
2666                .collect();
2667            assert!(!absorb_hop_pairs(&cap, &mut acc, &mut solutions, batch).unwrap());
2668        }
2669        assert_eq!(acc.len(), 200_000);
2670        let elapsed = started.elapsed();
2671        assert!(
2672            elapsed < std::time::Duration::from_secs(10),
2673            "amortized absorb took {elapsed:?} — the per-pair recount is back"
2674        );
2675    }
2676
2677    #[test]
2678    fn budgeted_absorb_with_a_threshold_counts_every_pair_once() {
2679        // The threshold-bearing twin of
2680        // `budgeted_absorb_does_not_recount_the_accumulation`: a LIMIT
2681        // above the walk's size keeps every push on the amortized memo
2682        // path (no short-circuit, no truncation), and the EXACT final
2683        // count — every pair is a solution under a target-less cap —
2684        // proves the suffix counting counted each pair exactly once,
2685        // which a wall-clock bound alone cannot distinguish from
2686        // skipping the count entirely.
2687        let cap = test_cap(Some(500_000), None, None);
2688        let starts: Vec<TermId> = (0..64).map(|i| node(&format!("s{i}"))).collect();
2689        let ends: Vec<TermId> = (0..64).map(|i| node(&format!("o{i}"))).collect();
2690        let mut acc = Vec::new();
2691        let mut solutions = SolutionCountMemo::default();
2692        let started = std::time::Instant::now();
2693        for page in 0..20 {
2694            let batch: Vec<PathPair> = (0..10_000)
2695                .map(|i| (starts[(page * 10_000 + i) % 64], ends[i % 64], graph()))
2696                .collect();
2697            assert!(!absorb_hop_pairs(&cap, &mut acc, &mut solutions, batch).unwrap());
2698        }
2699        assert_eq!(acc.len(), 200_000);
2700        // No early stop: the LIMIT sits above the walk's size, so every
2701        // push was counted and the memo's count is exact.
2702        assert_eq!(solutions.solutions(&cap, &acc), 200_000);
2703        let elapsed = started.elapsed();
2704        assert!(
2705            elapsed < std::time::Duration::from_secs(10),
2706            "amortized absorb took {elapsed:?} — the per-pair recount is back"
2707        );
2708    }
2709
2710    #[test]
2711    fn two_memos_over_one_shared_out_each_match_their_own_cap() {
2712        // The bidirectional closed walkers share one `out` between a
2713        // forward cap (hit: end ∈ ends) and a backward cap (hit:
2714        // start ∈ starts). Each cap's memo must equal a fresh recount
2715        // under ITS cap after every push — including pairs pushed while
2716        // only the other cap was querying, which the suffix recount
2717        // picks up on this cap's next query.
2718        let starts = [node("alice"), node("bob")];
2719        let ends = [node("carol"), node("dan")];
2720        let base = test_cap(None, None, None);
2721        let fwd_cap = base.clone().closed_forward(&starts, &ends);
2722        let bwd_cap = base.clone().closed_backward(&starts, &ends);
2723        let mut out: Vec<PathPair> = Vec::new();
2724        let mut fwd = SolutionCountMemo::default();
2725        let mut bwd = SolutionCountMemo::default();
2726        // Mixed pushes: fwd-only hits, bwd-only hits, a both-hits pair,
2727        // and a neither-hits pair.
2728        let pairs = [
2729            (node("x"), node("carol"), graph()),   // fwd hit only
2730            (node("alice"), node("y"), graph()),   // bwd hit only
2731            (node("alice"), node("dan"), graph()), // both
2732            (node("x"), node("y"), graph()),       // neither
2733        ];
2734        for (i, pair) in pairs.into_iter().enumerate() {
2735            out.push(pair);
2736            // Interleave: each memo goes stale while the other queries,
2737            // then must catch up over the whole grown suffix.
2738            if i % 2 == 0 {
2739                assert_eq!(
2740                    bwd.solutions(&bwd_cap, &out),
2741                    solution_count(&bwd_cap, &out)
2742                );
2743            } else {
2744                assert_eq!(
2745                    fwd.solutions(&fwd_cap, &out),
2746                    solution_count(&fwd_cap, &out)
2747                );
2748            }
2749        }
2750        assert_eq!(
2751            fwd.solutions(&fwd_cap, &out),
2752            solution_count(&fwd_cap, &out)
2753        );
2754        assert_eq!(
2755            bwd.solutions(&bwd_cap, &out),
2756            solution_count(&bwd_cap, &out)
2757        );
2758    }
2759
2760    #[test]
2761    fn take_solutions_replacement_resets_the_memo_exactly() {
2762        // The REAL replacement shape at the truncation sites: enough
2763        // fired, `take_solutions` filters by the hit predicate then
2764        // truncates to the limit, and the site calls reset() — the memo
2765        // must then match a fresh recount over the REPLACED list, both
2766        // for a filtering cap (targets) and a non-filtering one.
2767        let hit = node("hit");
2768        // Filtering cap: only pairs ending in :hit count, LIMIT 3.
2769        let cap = test_cap(Some(3), None, Some(HashSet::from([hit])));
2770        let mut out: Vec<PathPair> = Vec::new();
2771        let mut memo = SolutionCountMemo::default();
2772        for i in 0..6 {
2773            let end = if i % 2 == 0 {
2774                hit
2775            } else {
2776                node(&format!("n{i}"))
2777            };
2778            out.push((node(&format!("s{i}")), end, graph()));
2779        }
2780        assert_eq!(memo.solutions(&cap, &out), 3);
2781        let taken = take_solutions(std::mem::take(&mut out), &cap);
2782        memo.reset();
2783        out = taken;
2784        // Filtered to the 3 hits, truncated to 3: the list shrank and the
2785        // memo recounts from zero over the new content.
2786        assert_eq!(out.len(), 3);
2787        assert_eq!(memo.solutions(&cap, &out), solution_count(&cap, &out));
2788        assert_eq!(memo.solutions(&cap, &out), 3);
2789        // Non-filtering cap: `take_solutions` only truncates to the limit.
2790        let plain = test_cap(Some(3), None, None);
2791        let mut plain_out: Vec<PathPair> = (0..5)
2792            .map(|i| (node(&format!("a{i}")), node(&format!("b{i}")), graph()))
2793            .collect();
2794        let mut plain_memo = SolutionCountMemo::default();
2795        assert_eq!(plain_memo.solutions(&plain, &plain_out), 5);
2796        let taken = take_solutions(std::mem::take(&mut plain_out), &plain);
2797        plain_memo.reset();
2798        plain_out = taken;
2799        assert_eq!(plain_out.len(), 3);
2800        assert_eq!(
2801            plain_memo.solutions(&plain, &plain_out),
2802            solution_count(&plain, &plain_out)
2803        );
2804        assert_eq!(plain_memo.solutions(&plain, &plain_out), 3);
2805    }
2806
2807    #[test]
2808    fn paged_hop_enough_matches_the_one_shot_verdict_per_page() {
2809        // The paged tracker `collect_predicate_hop` uses (`HopEnough`
2810        // seeded once, one absorb per page) must fire "enough" on exactly
2811        // the page where the one-shot `hop_would_be_enough` over
2812        // `confirmed` plus ALL pages so far first fires.
2813        let hit = node("hit");
2814        let s = |n: usize| node(&format!("s{n}"));
2815        let confirmed: Vec<PathPair> = (0..3).map(|i| (s(i), hit, graph())).collect();
2816        // Each page carries two fresh hit pairs and one in-page duplicate
2817        // (the membership set must dedup it): 2 new hits per page.
2818        let pages: Vec<Vec<PathPair>> = (0..4)
2819            .map(|p| {
2820                vec![
2821                    (s(10 + p), hit, graph()),
2822                    (s(20 + p), hit, graph()),
2823                    (s(10 + p), hit, graph()),
2824                ]
2825            })
2826            .collect();
2827        // Counts: seed 3, then 5, 7, 9, 11 after pages 0..3 — the four
2828        // thresholds below stop at page 0, page 2, page 1, and never.
2829        for (max_solutions, max_closed) in [
2830            (Some(4), None),
2831            (Some(8), None),
2832            (None, Some(7)),
2833            (Some(100), None),
2834        ] {
2835            let cap = test_cap(max_solutions, max_closed, Some(HashSet::from([hit])));
2836            let mut tracker = HopEnough::new(&cap, &confirmed);
2837            let mut paged_stop_at: Option<usize> = None;
2838            for (page_index, page) in pages.iter().enumerate() {
2839                if tracker.absorb_page(&cap, page) && paged_stop_at.is_none() {
2840                    paged_stop_at = Some(page_index);
2841                }
2842            }
2843            let mut one_shot_stop_at: Option<usize> = None;
2844            let mut rolling = confirmed.clone();
2845            for (page_index, page) in pages.iter().enumerate() {
2846                rolling.extend(page.iter().cloned());
2847                if hop_would_be_enough(&cap, &confirmed, &rolling) && one_shot_stop_at.is_none() {
2848                    one_shot_stop_at = Some(page_index);
2849                }
2850            }
2851            assert_eq!(
2852                paged_stop_at, one_shot_stop_at,
2853                "stop page mismatch at {max_solutions:?}/{max_closed:?}"
2854            );
2855        }
2856    }
2857}