Skip to main content

ursa_engine/graph/
path_search.rs

1//! Searching paths on the graph index: SQL/PGQ's quantified edges
2//! (`-[e]->{1,3}`, `-[e]->*`), path variables, selectors (`ANY SHORTEST`,
3//! `ALL SHORTEST`, `SHORTEST k`) and path modes (`TRAIL`, `SIMPLE`,
4//! `ACYCLIC`) (#297).
5//!
6//! A fixed-length pattern is planned as joins (see [`super::pattern`]). A
7//! quantified edge is not: it is a [`PathSearchNode`], a relation of paths
8//! that runs a breadth-first search on the edge table's graph index, the
9//! index `hop` and `shortest_path` use, and joins to the nodes at its two
10//! ends like any edge. Its rows are one per path:
11//!
12//! | column        | what                                                  |
13//! |---------------|-------------------------------------------------------|
14//! | `__start`     | the key of the path's first node                      |
15//! | `__end`       | the key of its last node                              |
16//! | `__length`    | its number of edges (`path_length(p)`)                |
17//! | `__vertices`  | its nodes' keys, first to last (`vertices(p)`)        |
18//! | `__edges`     | its edges' rows in the edge table, from 0 (`edges(p)`) |
19//! | `__element_id`| nodes and edges alternating (`element_id(p)`)         |
20//!
21//! The last three are computed only when the query uses them.
22//!
23//! A fixed-length edge next to a bound node is searched too, as one edge
24//! (`{1,1}`) from the nodes already reached (see [`super::pattern`]): each of
25//! its rows is one edge, in edge-row order, so the search's rows are the
26//! join's rows.
27//!
28//! ## Targets
29//!
30//! A search may be given its targets: the keys the last node can have, when
31//! a condition on it alone says so (`b.id = 7`, `b.id IN (…)`). It keeps only
32//! the paths that end at one, and a search with a selector stops as soon as
33//! every target has all its paths: `ANY SHORTEST` from one node to another
34//! looks no further than the target.
35//!
36//! ## Which paths
37//!
38//! The search runs from each start node: every node of the left end's
39//! table that its conditions keep. A path of `n` edges is in the result when
40//! `min <= n <= max` and the path mode allows it. Without a selector, every
41//! such path is (a walk needs an upper bound, or it would be endless). With
42//! one, per pair of first and last node:
43//!
44//! - `ANY SHORTEST` (and `ANY`): one shortest path;
45//! - `SHORTEST k` (and `ANY k`): the `k` shortest paths;
46//! - `ALL SHORTEST`: every path as short as the shortest.
47//!
48//! Among paths of one length, a path comes before another when its first
49//! edge has a lower row in the edge table, or the same first edge and a
50//! lower second, and so on: `ANY SHORTEST` keeps the first. The search finds
51//! paths in that order, so the result does not depend on the run or the
52//! thread count. (An undirected edge is followed either way; a self-loop
53//! once.)
54//!
55//! ## How
56//!
57//! The search is breadth-first over (node, edges so far, up to `min`), so a
58//! shortest path of at least `min` edges is found even when it has to come
59//! back to a node it passed. Under `WALK`, a selector lets it stop extending
60//! a state once it has its `k` paths (or, for `ALL SHORTEST`, the paths as
61//! short as the first): any longer prefix makes a longer or later path. That
62//! holds for the other modes too when the lower bound is 0 or 1, the
63//! selector is `ANY SHORTEST` or `ALL SHORTEST` and the path is not an
64//! undirected `TRAIL`: a shortest walk between two nodes repeats no node, and
65//! one back to its start is a cycle. Otherwise the search lists every path
66//! the mode allows.
67//!
68//! A pruned search keeps its states in a table it tests before anything else
69//! per edge (one bit a state for `ANY SHORTEST`), and reads the adjacency
70//! lists where they lie (#451). From several start nodes, a walker per thread
71//! takes the next start, and the starts' rows are appended in start order: the
72//! rows, their order and the limit's verdict are those of one start after
73//! another (see [`run`]).
74//!
75//! ## The limit
76//!
77//! A search stops with an error once it holds more paths than
78//! `ursa.max_paths` (default [`MAX_PATHS`]; 0 for no limit). What counts
79//! depends on what the search can hold (#384, N50):
80//!
81//! - A pruned search with `ANY SHORTEST` or `SHORTEST k` holds at most `k`
82//!   prefixes per (node, edges so far up to `min`), so its memory is bounded
83//!   by the graph's nodes. It counts the paths it keeps (for `ANY SHORTEST`,
84//!   one per pair of first and last node: the destinations), never fewer
85//!   than `k` per node of the graph, so one start is never refused what
86//!   `hop` would list.
87//! - Every other search counts the prefixes it holds and the paths it keeps:
88//!   a walk's prefixes can grow exponentially with its length.
89
90use std::collections::HashSet;
91use std::fmt;
92use std::hash::{Hash, Hasher};
93use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
94use std::sync::Arc;
95
96use datafusion::arrow::array::{
97    Array, ArrayBuilder, ArrayRef, Int64Array, Int64Builder, ListArray, UInt32Array,
98};
99use datafusion::arrow::buffer::OffsetBuffer;
100use datafusion::arrow::compute::{interleave, take};
101use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
102use datafusion::arrow::record_batch::RecordBatch;
103use datafusion::common::{DFSchema, DFSchemaRef, ScalarValue};
104use datafusion::error::{DataFusionError, Result};
105use datafusion::logical_expr::{Expr, LogicalPlan, UserDefinedLogicalNodeCore};
106use rustc_hash::FxHashMap;
107use ursa_core::{IdMap, Topology};
108
109use super::node::{check_vertices, endpoint_id_type};
110use super::pattern::{Direction, Mode, Quantifier, Selector};
111
112/// The path's first node.
113pub const START: &str = "__start";
114/// Its last node.
115pub const END: &str = "__end";
116/// Its number of edges.
117pub const LENGTH: &str = "__length";
118/// Its nodes, first to last.
119pub const VERTICES: &str = "__vertices";
120/// Its edges' rows in the edge table.
121pub const EDGES: &str = "__edges";
122/// Its nodes and edges, alternating.
123pub const ELEMENTS: &str = "__element_id";
124
125/// The path functions, and the column each reads.
126pub const FUNCTIONS: &[(&str, &str)] = &[
127    ("path_length", LENGTH),
128    ("vertices", VERTICES),
129    ("edges", EDGES),
130    ("element_id", ELEMENTS),
131];
132
133/// The default `ursa.max_paths`: the most paths one search holds before it
134/// stops with an error (see the module docs).
135pub const MAX_PATHS: usize = 10_000_000;
136
137/// Rows per output batch.
138const BATCH_ROWS: usize = 8192;
139
140/// What a search looks for.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd)]
142pub struct Search {
143    pub direction: Direction,
144    pub quantifier: Quantifier,
145    pub selector: Selector,
146    pub mode: Mode,
147}
148
149impl fmt::Display for Search {
150    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
151        match self.selector {
152            Selector::All => {}
153            Selector::Shortest(1) => write!(f, "ANY SHORTEST ")?,
154            Selector::Shortest(k) => write!(f, "SHORTEST {k} ")?,
155            Selector::AllShortest => write!(f, "ALL SHORTEST ")?,
156        }
157        let mode = match self.mode {
158            Mode::Walk => "WALK",
159            Mode::Trail => "TRAIL",
160            Mode::Simple => "SIMPLE",
161            Mode::Acyclic => "ACYCLIC",
162        };
163        let arrow = match self.direction {
164            Direction::Right => "-[]->",
165            Direction::Left => "<-[]-",
166            Direction::Any => "-[]-",
167        };
168        let max = self
169            .quantifier
170            .max
171            .map(|m| m.to_string())
172            .unwrap_or_default();
173        write!(f, "{mode} {arrow}{{{},{max}}}", self.quantifier.min)
174    }
175}
176
177/// Which path columns a node computes besides its ends and length.
178#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd)]
179pub struct PathColumns {
180    pub vertices: bool,
181    pub edges: bool,
182    pub elements: bool,
183}
184
185/// The schema of a search's rows, for node ids of `id_type`.
186pub fn schema(id_type: &DataType, columns: PathColumns) -> Schema {
187    let list = |t: DataType| DataType::List(Arc::new(Field::new_list_field(t, false)));
188    let mut fields = vec![
189        Field::new(START, id_type.clone(), false),
190        Field::new(END, id_type.clone(), false),
191        Field::new(LENGTH, DataType::Int64, false),
192    ];
193    if columns.vertices {
194        fields.push(Field::new(VERTICES, list(id_type.clone()), false));
195    }
196    if columns.edges {
197        fields.push(Field::new(EDGES, list(DataType::Int64), false));
198    }
199    if columns.elements {
200        fields.push(Field::new(ELEMENTS, list(DataType::Int64), false));
201    }
202    Schema::new(fields)
203}
204
205/// A search on a graph's index, as a logical plan node. Its inputs:
206///
207/// 1. the edge table's rows, projected to the endpoints (the plan the index
208///    is built from, as for a traversal);
209/// 2. the start nodes: one column of keys, each once.
210#[derive(Debug, Clone)]
211pub struct PathSearchNode {
212    pub graph: String,
213    pub search: Search,
214    pub columns: PathColumns,
215    pub input: Arc<LogicalPlan>,
216    /// The keys of the vertex tables the edges connect, one column, when they
217    /// have them: the graph's nodes, as an algorithm's (#311).
218    pub vertices: Option<Arc<LogicalPlan>>,
219    pub starts: Arc<LogicalPlan>,
220    /// The keys the paths may end at, one column, if they are known (see the
221    /// module docs).
222    pub targets: Option<Arc<LogicalPlan>>,
223    /// Whether every node the starts can name is a node of the index (the
224    /// start node's table is the one the index's nodes are the keys of): a
225    /// start that is not one is no node, so it has no path, not even the
226    /// path of no edges.
227    pub known_only: bool,
228    pub source: Expr,
229    pub destination: Expr,
230    pub id_type: DataType,
231    schema: DFSchemaRef,
232}
233
234impl PathSearchNode {
235    #[allow(clippy::too_many_arguments)]
236    pub fn try_new(
237        graph: String,
238        search: Search,
239        columns: PathColumns,
240        input: Arc<LogicalPlan>,
241        vertices: Option<Arc<LogicalPlan>>,
242        starts: Arc<LogicalPlan>,
243        targets: Option<Arc<LogicalPlan>>,
244        known_only: bool,
245        source: Expr,
246        destination: Expr,
247    ) -> Result<Self> {
248        let id_type = endpoint_id_type(&graph, &input, &source, &destination)?;
249        check_vertices(&graph, vertices.as_deref())?;
250        if columns.elements && id_type != DataType::Int64 {
251            return Err(DataFusionError::Plan(format!(
252                "in GRAPH_TABLE: element_id(p) lists node keys and edge rows together, so it needs integer node keys; graph '{graph}' has {id_type} keys: use vertices(p) and edges(p)"
253            )));
254        }
255        let schema = Arc::new(DFSchema::try_from(schema(&id_type, columns))?);
256        Ok(Self {
257            graph,
258            search,
259            columns,
260            input,
261            vertices,
262            starts,
263            targets,
264            known_only,
265            source,
266            destination,
267            id_type,
268            schema,
269        })
270    }
271
272    pub(crate) fn endpoint_indices(&self) -> Result<(usize, usize)> {
273        let index = |e: &Expr| -> Result<usize> {
274            match e {
275                Expr::Column(c) => self.input.schema().index_of_column(c),
276                other => Err(DataFusionError::Internal(format!(
277                    "a path search's endpoint must be a column; got {other}"
278                ))),
279            }
280        };
281        Ok((index(&self.source)?, index(&self.destination)?))
282    }
283}
284
285impl PartialEq for PathSearchNode {
286    fn eq(&self, other: &Self) -> bool {
287        self.graph == other.graph
288            && self.search == other.search
289            && self.columns == other.columns
290            && self.input == other.input
291            && self.vertices == other.vertices
292            && self.starts == other.starts
293            && self.targets == other.targets
294            && self.known_only == other.known_only
295            && self.source == other.source
296            && self.destination == other.destination
297    }
298}
299
300impl Eq for PathSearchNode {}
301
302impl Hash for PathSearchNode {
303    fn hash<H: Hasher>(&self, state: &mut H) {
304        self.graph.hash(state);
305        self.search.hash(state);
306        self.columns.hash(state);
307        self.input.hash(state);
308        self.vertices.hash(state);
309        self.starts.hash(state);
310        self.targets.hash(state);
311        self.known_only.hash(state);
312    }
313}
314
315impl PartialOrd for PathSearchNode {
316    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
317        (&self.graph, &self.search, &self.columns)
318            .partial_cmp(&(&other.graph, &other.search, &other.columns))
319            .filter(|o| o.is_ne())
320    }
321}
322
323impl UserDefinedLogicalNodeCore for PathSearchNode {
324    fn name(&self) -> &str {
325        "PathSearch"
326    }
327
328    fn inputs(&self) -> Vec<&LogicalPlan> {
329        let mut inputs = vec![self.input.as_ref()];
330        inputs.extend(self.vertices.as_deref());
331        inputs.push(&self.starts);
332        inputs.extend(self.targets.as_deref());
333        inputs
334    }
335
336    fn schema(&self) -> &DFSchemaRef {
337        &self.schema
338    }
339
340    fn expressions(&self) -> Vec<Expr> {
341        vec![]
342    }
343
344    fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
345        write!(
346            f,
347            "PathSearch: graph={}, search={}{}",
348            self.graph,
349            self.search,
350            if self.targets.is_some() {
351                ", targets"
352            } else {
353                ""
354            }
355        )
356    }
357
358    fn with_exprs_and_inputs(&self, _exprs: Vec<Expr>, inputs: Vec<LogicalPlan>) -> Result<Self> {
359        let expected =
360            2 + usize::from(self.vertices.is_some()) + usize::from(self.targets.is_some());
361        if inputs.len() != expected {
362            return Err(DataFusionError::Internal(format!(
363                "PathSearch has {expected} inputs; got {}",
364                inputs.len()
365            )));
366        }
367        let mut inputs = inputs.into_iter().map(Arc::new);
368        let input = inputs.next().expect("checked above");
369        let vertices = self.vertices.as_ref().and_then(|_| inputs.next());
370        let starts = inputs.next().expect("checked above");
371        let targets = self.targets.as_ref().and_then(|_| inputs.next());
372        Ok(Self {
373            input,
374            vertices,
375            starts,
376            targets,
377            ..self.clone()
378        })
379    }
380
381    /// Every input is read whole: the endpoints, the vertex key, the one
382    /// start column and the one target column.
383    fn necessary_children_exprs(&self, _output_columns: &[usize]) -> Option<Vec<Vec<usize>>> {
384        let (source, destination) = self.endpoint_indices().ok()?;
385        let mut children = vec![vec![source, destination]];
386        if self.vertices.is_some() {
387            children.push(vec![0]);
388        }
389        children.push(vec![0]);
390        if self.targets.is_some() {
391            children.push(vec![0]);
392        }
393        Some(children)
394    }
395
396    /// A filter on the paths cannot move into the edges or the starts.
397    fn prevent_predicate_push_down_columns(&self) -> std::collections::HashSet<String> {
398        self.schema
399            .fields()
400            .iter()
401            .map(|f| f.name().clone())
402            .collect()
403    }
404}
405
406/// One path prefix the search holds: its last node, the entry it extends,
407/// the edge that does, and its length.
408#[derive(Debug, Clone, Copy)]
409struct Entry {
410    node: u32,
411    parent: u32,
412    edge: u32,
413    len: u32,
414}
415
416const ROOT: u32 = u32::MAX;
417
418/// A dense state table may take this many bytes whatever the graph's size
419/// (the 2^26 states of 8 bytes the table was limited to before #451)...
420const DENSE_MIN_BYTES: usize = 512 << 20;
421/// ...or this many per node of the graph, which holds that much per node
422/// already: `ALL SHORTEST` with a `+` quantifier (two states per node) stays
423/// dense at any size.
424const DENSE_BYTES_PER_NODE: usize = 16;
425
426/// The most bytes of state tables a search from many start nodes gives its
427/// parallel walkers together; past it, fewer walkers run.
428#[cfg(not(target_arch = "wasm32"))]
429const PARALLEL_STATES_BYTES: usize = 1 << 30;
430
431/// Per search state, (node, edges so far up to `min`), numbered
432/// `node * width + c`: how many prefixes reached it, and the length of the
433/// first. A pruned search keeps a prefix only if its state accepts it.
434trait States: Send {
435    /// Whether to keep a prefix of `len` edges that reaches state `i`,
436    /// counting it if so.
437    fn accept(&mut self, i: usize, len: u32, selector: Selector) -> bool;
438    /// Count the start's prefix of no edges at state `i`.
439    fn start(&mut self, i: usize);
440    /// Forget every state reached.
441    fn clear(&mut self);
442}
443
444/// The selector's test on a state (prefixes kept, length of the first),
445/// counting the prefix if it passes.
446#[inline(always)]
447fn accept_pair(state: &mut (u32, u32), len: u32, selector: Selector) -> bool {
448    let accept = match selector {
449        Selector::All => true,
450        Selector::Shortest(k) => state.0 < k,
451        Selector::AllShortest => state.0 == 0 || state.1 == len,
452    };
453    if accept {
454        if state.0 == 0 {
455            state.1 = len;
456        }
457        state.0 += 1;
458    }
459    accept
460}
461
462/// No states: a search that is not pruned keeps every prefix its mode
463/// allows.
464struct NoStates;
465
466impl States for NoStates {
467    fn accept(&mut self, _: usize, _: u32, _: Selector) -> bool {
468        true
469    }
470    fn start(&mut self, _: usize) {}
471    fn clear(&mut self) {}
472}
473
474/// `ANY SHORTEST`'s states: one bit each, whether a prefix reached it (it
475/// keeps the first, and the length is never asked). 2 bits a node for a `+`
476/// quantifier, so it is dense at any size.
477struct Bits {
478    words: Vec<u64>,
479    touched: Vec<usize>,
480}
481
482impl States for Bits {
483    #[inline(always)]
484    fn accept(&mut self, i: usize, _: u32, _: Selector) -> bool {
485        let (word, bit) = (&mut self.words[i >> 6], 1u64 << (i & 63));
486        if *word & bit != 0 {
487            return false;
488        }
489        *word |= bit;
490        self.touched.push(i);
491        true
492    }
493
494    fn start(&mut self, i: usize) {
495        self.accept(i, 0, Selector::Shortest(1));
496    }
497
498    fn clear(&mut self) {
499        // Every bit set is in `touched`, so a word with one is cleared whole.
500        if self.touched.len() > self.words.len() {
501            self.words.fill(0);
502        } else {
503            for &i in &self.touched {
504                self.words[i >> 6] = 0;
505            }
506        }
507        self.touched.clear();
508    }
509}
510
511/// The states as a table, for `SHORTEST k` and `ALL SHORTEST`.
512struct Pairs {
513    seen: Vec<(u32, u32)>,
514    touched: Vec<usize>,
515}
516
517impl States for Pairs {
518    #[inline(always)]
519    fn accept(&mut self, i: usize, len: u32, selector: Selector) -> bool {
520        let state = &mut self.seen[i];
521        let first = state.0 == 0;
522        let accept = accept_pair(state, len, selector);
523        if accept && first {
524            self.touched.push(i);
525        }
526        accept
527    }
528
529    fn start(&mut self, i: usize) {
530        if self.seen[i].0 == 0 {
531            self.touched.push(i);
532        }
533        self.seen[i] = (1, 0);
534    }
535
536    fn clear(&mut self) {
537        for i in self.touched.drain(..) {
538            self.seen[i] = (0, 0);
539        }
540    }
541}
542
543/// The states as a map, when a table would be too large.
544struct Sparse(FxHashMap<usize, (u32, u32)>);
545
546impl States for Sparse {
547    #[inline]
548    fn accept(&mut self, i: usize, len: u32, selector: Selector) -> bool {
549        accept_pair(self.0.entry(i).or_insert((0, 0)), len, selector)
550    }
551
552    fn start(&mut self, i: usize) {
553        self.0.insert(i, (1, 0));
554    }
555
556    fn clear(&mut self) {
557        self.0.clear();
558    }
559}
560
561/// Which state table a search uses.
562#[derive(Debug, Clone, Copy, PartialEq, Eq)]
563enum Table {
564    None,
565    Bits,
566    Pairs,
567    Sparse,
568}
569
570impl Table {
571    /// The table for a search over `n_nodes` nodes with `width` states each.
572    fn choose(pruned: bool, selector: Selector, n_nodes: usize, width: usize) -> Self {
573        if !pruned {
574            return Table::None;
575        }
576        let budget = DENSE_MIN_BYTES.max(n_nodes.saturating_mul(DENSE_BYTES_PER_NODE));
577        let states = n_nodes.saturating_mul(width);
578        if selector == Selector::Shortest(1) && states / 8 <= budget {
579            Table::Bits
580        } else if states.saturating_mul(8) <= budget {
581            Table::Pairs
582        } else {
583            Table::Sparse
584        }
585    }
586
587    /// The bytes one walker's table takes once the search has touched it
588    /// all, if they are known.
589    fn bytes(self, states: usize) -> Option<usize> {
590        match self {
591            Table::None => Some(0),
592            Table::Bits => Some(states.div_ceil(64) * 8),
593            Table::Pairs => Some(states * 8),
594            Table::Sparse => None,
595        }
596    }
597}
598
599/// The edges a step can take from `u`, in edge-row order, as (next node,
600/// edge row): the adjacency lists read as they are, and for an undirected
601/// step both merged by edge row as they are read. A self-loop is in both
602/// lists: it is taken once, forward.
603struct Undirected<'a> {
604    forward: (&'a [u32], &'a [u32]),
605    backward: (&'a [u32], &'a [u32]),
606    u: u32,
607    i: usize,
608    j: usize,
609}
610
611impl Iterator for Undirected<'_> {
612    type Item = (u32, u32);
613
614    #[inline]
615    fn next(&mut self) -> Option<(u32, u32)> {
616        let (bw, be) = self.backward;
617        while self.j < bw.len() && bw[self.j] == self.u {
618            self.j += 1;
619        }
620        let (fw, fe) = self.forward;
621        let take_forward = self.j == bw.len() || (self.i < fw.len() && fe[self.i] < be[self.j]);
622        if take_forward {
623            let i = self.i;
624            if i == fw.len() {
625                return None;
626            }
627            self.i += 1;
628            Some((fw[i], fe[i]))
629        } else {
630            let j = self.j;
631            self.j += 1;
632            Some((bw[j], be[j]))
633        }
634    }
635}
636
637/// Whether a prefix ending at entry `at` may take the edge `edge` to `w`
638/// under `mode`.
639fn allowed(entries: &[Entry], at: u32, w: u32, edge: u32, mode: Mode, start: u32) -> bool {
640    let chain = || {
641        let mut i = at;
642        std::iter::from_fn(move || {
643            if i == ROOT {
644                return None;
645            }
646            let e = entries[i as usize];
647            i = e.parent;
648            Some(e)
649        })
650    };
651    match mode {
652        Mode::Walk => true,
653        Mode::Trail => chain().all(|e| e.parent == ROOT || e.edge != edge),
654        Mode::Acyclic => chain().all(|e| e.node != w),
655        Mode::Simple => {
656            let last = entries[at as usize];
657            if last.len > 0 && last.node == start {
658                return false; // closed: it cannot go on
659            }
660            w == start && chain().all(|e| e.node != w || e.parent == ROOT)
661                || chain().all(|e| e.node != w)
662        }
663    }
664}
665
666/// The paths one start node found, in the order found, and what its search
667/// counted for the limit.
668#[derive(Default)]
669struct Found {
670    /// The start's row.
671    row: u32,
672    /// Per path, its last node (an index into [`Rows`]' values) and length.
673    ends: Vec<u32>,
674    lengths: Vec<i64>,
675    /// The paths' nodes, first to last, one after another, when asked.
676    vertices: Vec<u32>,
677    /// The paths' edges' rows in the edge table, when asked.
678    edges: Vec<i64>,
679    /// Prefixes extended.
680    expanded: usize,
681    /// Paths that count toward the limit (the path of no edges of a start
682    /// that is no node does not).
683    kept: usize,
684    /// The most prefixes and paths held at once, where the search checked
685    /// (see [`Walker::extend`]); `None` if it never did.
686    peak: Option<usize>,
687}
688
689/// Collects a search's rows into batches.
690struct Rows<'a> {
691    starts: &'a ArrayRef,
692    columns: PathColumns,
693    schema: SchemaRef,
694    start_rows: Vec<u32>,
695    ends: Vec<u32>,
696    lengths: Vec<i64>,
697    vertex_offsets: Vec<i32>,
698    vertex_values: Vec<u32>,
699    edge_offsets: Vec<i32>,
700    edge_values: Vec<i64>,
701    batches: Vec<RecordBatch>,
702    /// Every node of the index, as user ids. A node is referred to by its
703    /// index in the starts, then these (see [`Rows::gather`]).
704    ids: Option<ArrayRef>,
705}
706
707impl<'a> Rows<'a> {
708    fn new(ids: &'a IdMap, starts: &'a ArrayRef, columns: PathColumns, schema: SchemaRef) -> Self {
709        Self {
710            starts,
711            columns,
712            schema,
713            start_rows: Vec::new(),
714            ends: Vec::new(),
715            lengths: Vec::new(),
716            vertex_offsets: vec![0],
717            vertex_values: Vec::new(),
718            edge_offsets: vec![0],
719            edge_values: Vec::new(),
720            batches: Vec::new(),
721            // The ids array is the index's own (borrowed from a stored
722            // index's file): it is read only where a path ends or passes.
723            ids: (!ids.is_empty()).then(|| ids.user_id_array()),
724        }
725    }
726
727    /// Append one start's paths.
728    fn append(&mut self, found: &Found) -> Result<()> {
729        let vertices = self.columns.vertices || self.columns.elements;
730        let edges = self.columns.edges || self.columns.elements;
731        let (mut v, mut e) = (0, 0);
732        for (&end, &len) in found.ends.iter().zip(&found.lengths) {
733            let len = len as usize;
734            self.start_rows.push(found.row);
735            self.ends.push(end);
736            self.lengths.push(len as i64);
737            if vertices {
738                self.vertex_values
739                    .extend_from_slice(&found.vertices[v..v + len + 1]);
740                v += len + 1;
741                self.vertex_offsets.push(self.vertex_values.len() as i32);
742            }
743            if edges {
744                self.edge_values.extend_from_slice(&found.edges[e..e + len]);
745                e += len;
746                self.edge_offsets.push(self.edge_values.len() as i32);
747            }
748            if self.start_rows.len() >= BATCH_ROWS {
749                self.flush()?;
750            }
751        }
752        Ok(())
753    }
754
755    /// The user ids of `nodes`: indexes into the starts, then into the
756    /// index's ids after them.
757    fn gather(&self, nodes: Vec<u32>) -> Result<ArrayRef> {
758        let n = self.starts.len() as u32;
759        let Some(ids) = &self.ids else {
760            return Ok(take(self.starts.as_ref(), &UInt32Array::from(nodes), None)?);
761        };
762        if nodes.iter().all(|&i| i >= n) {
763            let nodes: Vec<u32> = nodes.into_iter().map(|i| i - n).collect();
764            return Ok(take(ids.as_ref(), &UInt32Array::from(nodes), None)?);
765        }
766        let at: Vec<(usize, usize)> = nodes
767            .into_iter()
768            .map(|i| match i.checked_sub(n) {
769                Some(d) => (1, d as usize),
770                None => (0, i as usize),
771            })
772            .collect();
773        Ok(interleave(&[self.starts.as_ref(), ids.as_ref()], &at)?)
774    }
775
776    fn flush(&mut self) -> Result<()> {
777        if self.start_rows.is_empty() {
778            return Ok(());
779        }
780        let start = take(
781            self.starts.as_ref(),
782            &UInt32Array::from(std::mem::take(&mut self.start_rows)),
783            None,
784        )?;
785        let ends = std::mem::take(&mut self.ends);
786        let end = self.gather(ends)?;
787        let mut columns: Vec<ArrayRef> = vec![
788            start,
789            end,
790            Arc::new(Int64Array::from(std::mem::take(&mut self.lengths))),
791        ];
792        let vertex_offsets = std::mem::replace(&mut self.vertex_offsets, vec![0]);
793        let vertex_values = std::mem::take(&mut self.vertex_values);
794        let vertex_values = self.gather(vertex_values)?;
795        let edge_offsets = std::mem::replace(&mut self.edge_offsets, vec![0]);
796        let edge_values = std::mem::take(&mut self.edge_values);
797        let field = |i: usize| match self.schema.field(i).data_type() {
798            DataType::List(f) => Arc::clone(f),
799            _ => unreachable!("a list column"),
800        };
801        let mut i = 3;
802        if self.columns.vertices {
803            columns.push(Arc::new(ListArray::try_new(
804                field(i),
805                OffsetBuffer::new(vertex_offsets.clone().into()),
806                Arc::clone(&vertex_values),
807                None,
808            )?));
809            i += 1;
810        }
811        if self.columns.edges {
812            columns.push(Arc::new(ListArray::try_new(
813                field(i),
814                OffsetBuffer::new(edge_offsets.clone().into()),
815                Arc::new(Int64Array::from(edge_values.clone())),
816                None,
817            )?));
818            i += 1;
819        }
820        if self.columns.elements {
821            let keys = vertex_values
822                .as_any()
823                .downcast_ref::<Int64Array>()
824                .ok_or_else(|| DataFusionError::Internal("element_id needs Int64 keys".into()))?;
825            let mut values = Int64Builder::with_capacity(keys.len() + edge_values.len());
826            let mut offsets = vec![0i32];
827            for p in 0..vertex_offsets.len() - 1 {
828                let (v0, v1) = (vertex_offsets[p] as usize, vertex_offsets[p + 1] as usize);
829                let e0 = edge_offsets[p] as usize;
830                for k in v0..v1 {
831                    values.append_value(keys.value(k));
832                    if k + 1 < v1 {
833                        values.append_value(edge_values[e0 + (k - v0)]);
834                    }
835                }
836                offsets.push(values.len() as i32);
837            }
838            columns.push(Arc::new(ListArray::try_new(
839                field(i),
840                OffsetBuffer::new(offsets.into()),
841                Arc::new(values.finish()),
842                None,
843            )?));
844        }
845        self.batches
846            .push(RecordBatch::try_new(Arc::clone(&self.schema), columns)?);
847        Ok(())
848    }
849}
850
851/// The targets of a search: the dense nodes its paths may end at, each with
852/// a slot, and the target keys that are no node of the index.
853struct Goals {
854    slots: FxHashMap<u32, u32>,
855    unknown: HashSet<ScalarValue>,
856}
857
858impl Goals {
859    fn new(ids: &IdMap, targets: &ArrayRef) -> Result<Self> {
860        let dense = ids
861            .dense_from_array(targets.as_ref())
862            .map_err(|e| DataFusionError::Execution(format!("in GRAPH_TABLE: {e}")))?;
863        let mut slots = FxHashMap::default();
864        let mut unknown = HashSet::new();
865        for (row, d) in dense.iter().enumerate() {
866            if targets.is_null(row) {
867                continue;
868            }
869            match d {
870                Some(d) => {
871                    let next = slots.len() as u32;
872                    slots.entry(*d).or_insert(next);
873                }
874                None => {
875                    unknown.insert(ScalarValue::try_from_array(targets.as_ref(), row)?);
876                }
877            }
878        }
879        Ok(Self { slots, unknown })
880    }
881}
882
883/// What every walker of one search shares.
884struct Plan<'a> {
885    topology: &'a Topology,
886    edge_row: &'a (dyn Fn(u32) -> u64 + Sync),
887    search: &'a Search,
888    starts: &'a ArrayRef,
889    /// The starts' dense nodes.
890    dense: &'a [Option<u32>],
891    goals: Option<&'a Goals>,
892    known_only: bool,
893    columns: PathColumns,
894    restricted: bool,
895    pruned: bool,
896    /// States per node: `min + 1`.
897    width: usize,
898    /// Whether the search's memory is bounded by the graph's nodes (see the
899    /// module docs): it counts only the paths it keeps.
900    bounded: bool,
901    /// The most prefixes and paths the search may hold (`ursa.max_paths`),
902    /// unless it is `bounded`.
903    cap: Option<usize>,
904    /// The most paths a `bounded` search may keep.
905    kept_limit: Option<usize>,
906    /// Paths a `bounded` search has kept so far, from every start (each
907    /// walker adds its own now and then, and at the end of a start).
908    kept_all: AtomicUsize,
909    /// Set when a search from many start nodes has failed: the others stop.
910    stop: AtomicBool,
911}
912
913/// A `bounded` walker adds the paths it kept to [`Plan::kept_all`] after
914/// this many.
915const KEPT_BATCH: usize = 4096;
916
917/// What one search is doing, from one start node after another.
918struct Walker<'a, T> {
919    plan: &'a Plan<'a>,
920    states: T,
921    entries: Vec<Entry>,
922    /// The paths of the current start.
923    found: Found,
924    /// Its paths kept so far, and those not yet added to `kept_all`.
925    kept: usize,
926    unshared: usize,
927    /// Paths kept by the starts before it (as far as known: see
928    /// [`drive_parallel`]).
929    before: usize,
930    /// Per last node, for a search that lists every path: (paths kept,
931    /// length of the first).
932    targets: FxHashMap<u32, (u32, u32)>,
933    /// Per target slot, for this start: (paths kept, length of the first).
934    slot_paths: Vec<(u32, u32)>,
935    touched: Vec<u32>,
936    reach: Reach,
937    /// Scratch for one path's nodes and edges.
938    nodes: Vec<u32>,
939    edges: Vec<u32>,
940}
941
942/// How far a pruned search with targets has reached them, counting the
943/// prefixes it pushed. A pruned search lists every prefix it pushes to a
944/// target (at `min` edges or more), in the order it pushed them, so once each
945/// target has its `k` (`SHORTEST k`), or its first (`ALL SHORTEST`), no
946/// prefix needs extending any more: for `ALL SHORTEST`, none at the
947/// longest of those lengths or beyond.
948#[derive(Default)]
949struct Reach {
950    /// Per slot, prefixes pushed.
951    pushed: Vec<u32>,
952    touched: Vec<u32>,
953    /// Targets without all their paths yet.
954    unfilled: usize,
955    /// The longest length at which a target was first reached.
956    longest: u32,
957}
958
959impl Reach {
960    fn reset(&mut self, n: usize) {
961        if self.pushed.len() != n {
962            self.pushed = vec![0; n];
963        }
964        for slot in self.touched.drain(..) {
965            self.pushed[slot as usize] = 0;
966        }
967        self.unfilled = n;
968        self.longest = 0;
969    }
970
971    /// Whether a prefix of `len` edges still needs extending.
972    fn extends(&self, len: u32, selector: Selector) -> bool {
973        self.unfilled > 0 || (selector == Selector::AllShortest && len < self.longest)
974    }
975}
976
977impl<'a, T: States> Walker<'a, T> {
978    fn new(plan: &'a Plan<'a>, states: T) -> Self {
979        let slots = plan.goals.map_or(0, |g| g.slots.len());
980        Self {
981            plan,
982            states,
983            entries: Vec::new(),
984            found: Found::default(),
985            kept: 0,
986            unshared: 0,
987            before: 0,
988            targets: FxHashMap::default(),
989            slot_paths: vec![(0, 0); slots],
990            touched: Vec::new(),
991            reach: Reach::default(),
992            nodes: Vec::new(),
993            edges: Vec::new(),
994        }
995    }
996
997    /// Push the prefixes that extend entry `at` by one edge.
998    #[inline]
999    fn extend(&mut self, at: u32, start: u32) -> Result<()> {
1000        let topology = self.plan.topology;
1001        let u = self.entries[at as usize].node;
1002        self.found.expanded += 1;
1003        match self.plan.search.direction {
1004            Direction::Right => {
1005                let a = topology.out();
1006                let steps = a.neighbors(u).iter().copied();
1007                self.extend_with(at, start, steps.zip(a.edge_ids(u).iter().copied()))
1008            }
1009            Direction::Left => {
1010                let a = topology.incoming();
1011                let steps = a.neighbors(u).iter().copied();
1012                self.extend_with(at, start, steps.zip(a.edge_ids(u).iter().copied()))
1013            }
1014            Direction::Any => {
1015                let (out, inc) = (topology.out(), topology.incoming());
1016                let steps = Undirected {
1017                    forward: (out.neighbors(u), out.edge_ids(u)),
1018                    backward: (inc.neighbors(u), inc.edge_ids(u)),
1019                    u,
1020                    i: 0,
1021                    j: 0,
1022                };
1023                self.extend_with(at, start, steps)
1024            }
1025        }
1026    }
1027
1028    /// [`Self::extend`] over the edges `steps` (next node, edge row), in
1029    /// edge-row order.
1030    #[inline(always)]
1031    fn extend_with(
1032        &mut self,
1033        at: u32,
1034        start: u32,
1035        steps: impl Iterator<Item = (u32, u32)>,
1036    ) -> Result<()> {
1037        let plan = self.plan;
1038        let search = plan.search;
1039        let min = search.quantifier.min;
1040        let len = self.entries[at as usize].len + 1;
1041        let c = len.min(min) as usize;
1042        let slots = plan.goals.filter(|_| plan.pruned).map(|g| &g.slots);
1043        let cap = plan.cap.filter(|_| !plan.bounded);
1044        for (w, edge) in steps {
1045            if plan.restricted && !allowed(&self.entries, at, w, edge, search.mode, start) {
1046                continue;
1047            }
1048            // The cheap test first: most edges reach a state already full.
1049            if plan.pruned
1050                && !self
1051                    .states
1052                    .accept(w as usize * plan.width + c, len, search.selector)
1053            {
1054                continue;
1055            }
1056            self.entries.push(Entry {
1057                node: w,
1058                parent: at,
1059                edge,
1060                len,
1061            });
1062            if let Some(slots) = slots {
1063                // A pruned search lists this prefix: a target may have its paths.
1064                let listed = len >= min && !(search.mode == Mode::Acyclic && w == start);
1065                if let (true, Some(&slot)) = (listed, slots.get(&w)) {
1066                    let reach = &mut self.reach;
1067                    let pushed = &mut reach.pushed[slot as usize];
1068                    if *pushed == 0 {
1069                        reach.touched.push(slot);
1070                        reach.longest = reach.longest.max(len);
1071                    }
1072                    *pushed += 1;
1073                    let filled = match search.selector {
1074                        Selector::All => false,
1075                        Selector::Shortest(k) => *pushed == k,
1076                        Selector::AllShortest => *pushed == 1,
1077                    };
1078                    if filled {
1079                        reach.unfilled -= 1;
1080                    }
1081                }
1082            }
1083            if let Some(cap) = cap {
1084                let held = self.entries.len() + self.kept;
1085                self.found.peak = Some(self.found.peak.map_or(held, |p| p.max(held)));
1086                if held + self.before > cap {
1087                    return Err(too_many_paths(cap, search, false));
1088                }
1089            }
1090        }
1091        Ok(())
1092    }
1093
1094    /// Add the paths kept and not yet shared to [`Plan::kept_all`]; an error
1095    /// once every start's together are over the limit.
1096    fn share_kept(&mut self) -> Result<()> {
1097        let plan = self.plan;
1098        let Some(limit) = plan.kept_limit else {
1099            return Ok(());
1100        };
1101        let all = plan.kept_all.fetch_add(self.unshared, Ordering::Relaxed) + self.unshared;
1102        self.unshared = 0;
1103        if all > limit {
1104            return Err(too_many_paths(limit, plan.search, true));
1105        }
1106        Ok(())
1107    }
1108
1109    /// The paths from the start at `row`, given that the starts before it
1110    /// kept `before` paths (or at least that many).
1111    fn search(&mut self, row: usize, before: usize) -> Result<Found> {
1112        let plan = self.plan;
1113        let search = plan.search;
1114        let min = search.quantifier.min;
1115        let max = search.quantifier.max;
1116        let mut found = std::mem::take(&mut self.found);
1117        found.row = row as u32;
1118        found.ends.clear();
1119        found.lengths.clear();
1120        found.vertices.clear();
1121        found.edges.clear();
1122        found.expanded = 0;
1123        found.kept = 0;
1124        found.peak = None;
1125        self.found = found;
1126        if plan.starts.is_null(row) {
1127            return Ok(std::mem::take(&mut self.found));
1128        }
1129        let vertices = plan.columns.vertices || plan.columns.elements;
1130        let edges = plan.columns.edges || plan.columns.elements;
1131        let offset = plan.starts.len() as u32;
1132        let Some(start) = plan.dense[row] else {
1133            // A node with no edges: only the path of no edges.
1134            let ends_at_a_target = match plan.goals {
1135                None => true,
1136                Some(g) => g
1137                    .unknown
1138                    .contains(&ScalarValue::try_from_array(plan.starts.as_ref(), row)?),
1139            };
1140            if min == 0 && !plan.known_only && ends_at_a_target {
1141                let f = &mut self.found;
1142                f.ends.push(row as u32);
1143                f.lengths.push(0);
1144                if vertices {
1145                    f.vertices.push(row as u32);
1146                }
1147            }
1148            return Ok(std::mem::take(&mut self.found));
1149        };
1150        if plan.goals.is_some_and(|g| g.slots.is_empty()) {
1151            return Ok(std::mem::take(&mut self.found)); // no target is a node: no path ends at one
1152        }
1153        self.kept = 0;
1154        self.unshared = 0;
1155        self.before = before;
1156        for slot in self.touched.drain(..) {
1157            self.slot_paths[slot as usize] = (0, 0);
1158        }
1159        self.reach.reset(self.slot_paths.len());
1160        // Targets not yet done, and (ALL SHORTEST) the length past which
1161        // none has another path once every one is found.
1162        let mut remaining = self.slot_paths.len();
1163        let mut longest = 0u32;
1164        let mut stop_after: Option<u32> = None;
1165        self.states.clear();
1166        self.targets.clear();
1167        self.entries.clear();
1168        self.entries.push(Entry {
1169            node: start,
1170            parent: ROOT,
1171            edge: 0,
1172            len: 0,
1173        });
1174        self.states.start(start as usize * plan.width);
1175        let mut head = 0;
1176        'search: while head < self.entries.len() {
1177            if head % 1024 == 1023 && plan.stop.load(Ordering::Relaxed) {
1178                return Err(DataFusionError::Execution("stopped".into()));
1179            }
1180            let at = head as u32;
1181            let entry = self.entries[head];
1182            head += 1;
1183            if stop_after.is_some_and(|len| entry.len > len) {
1184                break;
1185            }
1186            let c = entry.len.min(min);
1187            // The target slot of the entry's node, when the search has targets;
1188            // with targets, a node that is none of them ends no path.
1189            //
1190            // Two plain values rather than one `Option<Option<u32>>`: rustc
1191            // 1.97 at `opt-level` "s" and "z" (the browser engine's build)
1192            // matched `Some(Some(_))` on a `None` here, and indexed out of
1193            // bounds. The browser parity test runs GRAPH_TABLE at "z".
1194            let (slot, ends_here) = match plan.goals {
1195                None => (None, true),
1196                Some(g) => {
1197                    let slot = g.slots.get(&entry.node).copied();
1198                    (slot, slot.is_some())
1199                }
1200            };
1201            if c == min && ends_here {
1202                let keep = if plan.pruned {
1203                    true
1204                } else {
1205                    let t = self.targets.entry(entry.node).or_insert((0, entry.len));
1206                    let keep = match search.selector {
1207                        Selector::All => true,
1208                        Selector::Shortest(k) => t.0 < k,
1209                        Selector::AllShortest => t.1 == entry.len,
1210                    };
1211                    if keep {
1212                        t.0 += 1;
1213                    }
1214                    keep
1215                };
1216                // ACYCLIC: a path back to its start is a cycle.
1217                let closed = search.mode == Mode::Acyclic && entry.len > 0 && entry.node == start;
1218                if keep && !closed {
1219                    self.nodes.clear();
1220                    self.edges.clear();
1221                    let mut i = at;
1222                    while i != ROOT {
1223                        let e = self.entries[i as usize];
1224                        self.nodes.push(offset + e.node);
1225                        if e.parent != ROOT {
1226                            self.edges.push(e.edge);
1227                        }
1228                        i = e.parent;
1229                    }
1230                    let f = &mut self.found;
1231                    f.ends.push(offset + entry.node);
1232                    f.lengths.push(i64::from(entry.len));
1233                    if vertices {
1234                        f.vertices.extend(self.nodes.iter().rev());
1235                    }
1236                    if edges {
1237                        let edge_row = plan.edge_row;
1238                        f.edges
1239                            .extend(self.edges.iter().rev().map(|&e| edge_row(e) as i64));
1240                    }
1241                    f.kept += 1;
1242                    self.kept += 1;
1243                    self.unshared += 1;
1244                    if self.unshared == KEPT_BATCH {
1245                        self.share_kept()?;
1246                    }
1247                    if let Some(slot) = slot {
1248                        let f = &mut self.slot_paths[slot as usize];
1249                        if f.0 == 0 {
1250                            self.touched.push(slot);
1251                            f.1 = entry.len;
1252                        }
1253                        f.0 += 1;
1254                        let done = match search.selector {
1255                            Selector::All => false,
1256                            Selector::Shortest(k) => f.0 == k,
1257                            Selector::AllShortest => f.0 == 1,
1258                        };
1259                        if done {
1260                            remaining -= 1;
1261                            longest = longest.max(f.1);
1262                            if remaining == 0 {
1263                                match search.selector {
1264                                    Selector::AllShortest => stop_after = Some(longest),
1265                                    _ => break 'search,
1266                                }
1267                            }
1268                        }
1269                    }
1270                }
1271            }
1272            if max.is_some_and(|max| entry.len >= max) {
1273                continue;
1274            }
1275            if plan.pruned
1276                && plan.goals.is_some()
1277                && !self.reach.extends(entry.len, search.selector)
1278            {
1279                continue; // every target has its paths among those pushed
1280            }
1281            self.extend(at, start)?;
1282        }
1283        self.share_kept()?;
1284        Ok(std::mem::take(&mut self.found))
1285    }
1286}
1287
1288/// The error of a search that reached `limit` paths, with the remedy that
1289/// fits it: a search with a selector already keeps the fewest paths, so it
1290/// is pointed to `hop` (a `bounded` one says it keeps one path per pair of
1291/// nodes, or `k`); one without a selector to `ANY SHORTEST`. Either may
1292/// raise `ursa.max_paths`.
1293fn too_many_paths(limit: usize, search: &Search, bounded: bool) -> DataFusionError {
1294    const RAISE: &str = "or SET ursa.max_paths to a higher limit (0 for none)";
1295    const HOP: &str = "count the nodes at each distance with hop(…) \
1296                       (SELECT distance, count(*) FROM hop(g, seeds => […], steps => …) GROUP BY 1)";
1297    let remedy = match search.selector {
1298        Selector::All => format!(
1299            "give the quantified edge a lower upper bound, keep fewer paths with ANY SHORTEST, \
1300             {RAISE}"
1301        ),
1302        Selector::Shortest(1) if bounded => {
1303            format!("ANY SHORTEST keeps one path per pair of nodes already; {HOP}, {RAISE}")
1304        }
1305        Selector::Shortest(k) if bounded => {
1306            format!("SHORTEST {k} keeps {k} paths per pair of nodes already; {HOP}, {RAISE}")
1307        }
1308        _ => format!("give the quantified edge a lower upper bound, {HOP}, {RAISE}"),
1309    };
1310    DataFusionError::Execution(format!(
1311        "in GRAPH_TABLE: the path search reached {limit} paths, the limit ursa.max_paths sets; \
1312         {remedy}"
1313    ))
1314}
1315
1316/// The paths kept by the starts committed so far, and the prefixes they
1317/// extended.
1318#[derive(Default)]
1319struct Tally {
1320    kept: usize,
1321    expanded: usize,
1322}
1323
1324impl Tally {
1325    /// Append one start's paths, the next in start order, after checking
1326    /// the limit as a search from one start after another would have:
1327    /// `found` was searched knowing only that the starts before it kept at
1328    /// least as many paths as they did.
1329    fn commit(&mut self, plan: &Plan, rows: &mut Rows, found: &Found) -> Result<()> {
1330        if let (Some(cap), Some(peak)) = (plan.cap.filter(|_| !plan.bounded), found.peak) {
1331            if peak + self.kept > cap {
1332                return Err(too_many_paths(cap, plan.search, false));
1333            }
1334        }
1335        rows.append(found)?;
1336        self.kept += found.kept;
1337        self.expanded += found.expanded;
1338        Ok(())
1339    }
1340}
1341
1342/// Run `search` from each of `starts` (keys of the graph's id type, each
1343/// once) on the index `topology`/`ids`; the rows of [`schema`], and how many
1344/// path prefixes the search extended. `edge_row` gives the edge table's row
1345/// of an edge of the index (see [`super::GraphIndex::edge_row`]). With
1346/// `targets`, only the paths that end at one are kept, and a search with a
1347/// selector stops once every target has its paths (see the module docs).
1348/// With `known_only`, a start that is no node of the index has no path.
1349/// `max_paths` is `ursa.max_paths` (`None` for no limit; see the module
1350/// docs).
1351///
1352/// Many start nodes are searched in parallel, each by a walker of its own,
1353/// and their rows appended in start order: the rows, their order and when
1354/// the limit stops the search are those of one start after another.
1355#[allow(clippy::too_many_arguments)]
1356pub fn run(
1357    topology: &Topology,
1358    ids: &IdMap,
1359    edge_row: &(dyn Fn(u32) -> u64 + Sync),
1360    search: &Search,
1361    starts: &ArrayRef,
1362    targets: Option<&ArrayRef>,
1363    known_only: bool,
1364    columns: PathColumns,
1365    schema: SchemaRef,
1366    max_paths: Option<usize>,
1367) -> Result<(Vec<RecordBatch>, usize)> {
1368    let dense = ids
1369        .dense_from_array(starts.as_ref())
1370        .map_err(|e| DataFusionError::Execution(format!("in GRAPH_TABLE: {e}")))?;
1371    let goals = targets.map(|t| Goals::new(ids, t)).transpose()?;
1372    let mut rows = Rows::new(ids, starts, columns, schema);
1373    let Quantifier { min, .. } = search.quantifier;
1374    let restricted = search.mode != Mode::Walk;
1375    let pruned = !restricted
1376        || (matches!(
1377            search.selector,
1378            Selector::Shortest(1) | Selector::AllShortest
1379        ) && min <= 1
1380            && !(search.mode == Mode::Trail && search.direction == Direction::Any));
1381    // At most `k` prefixes per state: memory bounded by the nodes, and at
1382    // most `k` paths per node from one start.
1383    let bounded = pruned && matches!(search.selector, Selector::Shortest(_));
1384    let kept_limit = match (bounded, max_paths, search.selector) {
1385        (true, Some(cap), Selector::Shortest(k)) => {
1386            Some(cap.max(topology.n_nodes().saturating_mul(k as usize)))
1387        }
1388        _ => None,
1389    };
1390    if search.direction != Direction::Right && dense.iter().any(Option::is_some) {
1391        // Built here, outside the walkers, if it is not yet.
1392        topology.incoming();
1393    }
1394    let n_nodes = topology.n_nodes();
1395    let width = min as usize + 1;
1396    let plan = Plan {
1397        topology,
1398        edge_row,
1399        search,
1400        starts,
1401        dense: &dense,
1402        goals: goals.as_ref(),
1403        known_only,
1404        columns,
1405        restricted,
1406        pruned,
1407        width,
1408        bounded,
1409        cap: max_paths,
1410        kept_limit,
1411        kept_all: AtomicUsize::new(0),
1412        stop: AtomicBool::new(false),
1413    };
1414    let states = n_nodes * width;
1415    let table = Table::choose(pruned, search.selector, n_nodes, width);
1416    let walkers = walkers(&plan, table.bytes(states));
1417    let mut tally = Tally::default();
1418    match table {
1419        Table::None => drive(&plan, &mut rows, &mut tally, walkers, || NoStates)?,
1420        Table::Bits => drive(&plan, &mut rows, &mut tally, walkers, || Bits {
1421            words: vec![0; states.div_ceil(64)],
1422            touched: Vec::new(),
1423        })?,
1424        Table::Pairs => drive(&plan, &mut rows, &mut tally, walkers, || Pairs {
1425            seen: vec![(0, 0); states],
1426            touched: Vec::new(),
1427        })?,
1428        Table::Sparse => drive(&plan, &mut rows, &mut tally, walkers, || {
1429            Sparse(FxHashMap::default())
1430        })?,
1431    }
1432    rows.flush()?;
1433    Ok((rows.batches, tally.expanded))
1434}
1435
1436/// How many walkers search from the starts at once: one per thread, one per
1437/// start at most, and as many as their state tables fit in
1438/// [`PARALLEL_STATES_BYTES`] (one for a sparse table, whose size is not
1439/// known).
1440fn walkers(plan: &Plan, table_bytes: Option<usize>) -> usize {
1441    #[cfg(target_arch = "wasm32")]
1442    {
1443        let _ = (plan, table_bytes);
1444        1
1445    }
1446    #[cfg(not(target_arch = "wasm32"))]
1447    {
1448        let starts = plan.dense.iter().filter(|d| d.is_some()).count();
1449        let fit = match table_bytes {
1450            Some(0) => usize::MAX,
1451            Some(b) => (PARALLEL_STATES_BYTES / b).max(1),
1452            None => 1,
1453        };
1454        rayon::current_num_threads().min(starts).min(fit).max(1)
1455    }
1456}
1457
1458/// Search from every start, with `walkers` walkers, each with the state
1459/// table `states` makes, and append the paths to `rows` in start order.
1460fn drive<T: States>(
1461    plan: &Plan,
1462    rows: &mut Rows,
1463    tally: &mut Tally,
1464    walkers: usize,
1465    states: impl Fn() -> T + Sync,
1466) -> Result<()> {
1467    #[cfg(not(target_arch = "wasm32"))]
1468    if walkers > 1 {
1469        return drive_parallel(plan, rows, tally, walkers, states);
1470    }
1471    let _ = walkers;
1472    let mut walker = Walker::new(plan, states());
1473    for row in 0..plan.dense.len() {
1474        let found = walker.search(row, tally.kept)?;
1475        tally.commit(plan, rows, &found)?;
1476        walker.found = found; // its buffers, for the next start
1477    }
1478    Ok(())
1479}
1480
1481/// [`drive`] on rayon's threads. Each walker takes the next start, searches
1482/// it, and leaves its paths for the start-order commit; whoever finishes the
1483/// start next in order commits it and any after it that are done. A walker
1484/// runs at most `4 × walkers` starts ahead of the commit, so a slow start
1485/// holds back only that many finished ones.
1486///
1487/// A walker searches a start knowing the paths kept by the starts committed
1488/// when it took it, at most as many as the starts before it kept. So when
1489/// it reaches the limit, one start after another would have reached it too,
1490/// by then or before, with the same error; and the commit checks each start
1491/// against the exact count before it, as one after another would.
1492#[cfg(not(target_arch = "wasm32"))]
1493fn drive_parallel<T: States>(
1494    plan: &Plan,
1495    rows: &mut Rows,
1496    tally: &mut Tally,
1497    walkers: usize,
1498    states: impl Fn() -> T + Sync,
1499) -> Result<()> {
1500    use std::collections::BTreeMap;
1501    use std::sync::{Condvar, Mutex, PoisonError};
1502
1503    struct Shared<'r, 'a> {
1504        rows: &'r mut Rows<'a>,
1505        tally: &'r mut Tally,
1506        /// The next start to take, and the next to commit.
1507        next: usize,
1508        commit: usize,
1509        done: BTreeMap<usize, Found>,
1510        error: Option<DataFusionError>,
1511    }
1512    let n = plan.dense.len();
1513    let window = 4 * walkers;
1514    let shared = Mutex::new(Shared {
1515        rows,
1516        tally,
1517        next: 0,
1518        commit: 0,
1519        done: BTreeMap::new(),
1520        error: None,
1521    });
1522    let moved = Condvar::new();
1523    let lock = || shared.lock().unwrap_or_else(PoisonError::into_inner);
1524    rayon::scope(|scope| {
1525        for _ in 0..walkers {
1526            scope.spawn(|_| {
1527                let mut walker = Walker::new(plan, states());
1528                loop {
1529                    let (row, before) = {
1530                        let mut s = lock();
1531                        loop {
1532                            if s.error.is_some() || s.next == n {
1533                                return;
1534                            }
1535                            if s.next < s.commit + window {
1536                                break;
1537                            }
1538                            s = moved.wait(s).unwrap_or_else(PoisonError::into_inner);
1539                        }
1540                        s.next += 1;
1541                        (s.next - 1, s.tally.kept)
1542                    };
1543                    let found = walker.search(row, before);
1544                    let mut s = lock();
1545                    match found {
1546                        Err(e) => {
1547                            if s.error.is_none() && !plan.stop.load(Ordering::Relaxed) {
1548                                s.error = Some(e);
1549                            }
1550                            plan.stop.store(true, Ordering::Relaxed);
1551                        }
1552                        Ok(found) => {
1553                            s.done.insert(row, found);
1554                            let s = &mut *s;
1555                            while s.error.is_none() {
1556                                let Some(found) = s.done.remove(&s.commit) else {
1557                                    break;
1558                                };
1559                                match s.tally.commit(plan, s.rows, &found) {
1560                                    Ok(()) => s.commit += 1,
1561                                    Err(e) => {
1562                                        s.error = Some(e);
1563                                        plan.stop.store(true, Ordering::Relaxed);
1564                                    }
1565                                }
1566                            }
1567                        }
1568                    }
1569                    drop(s);
1570                    moved.notify_all();
1571                }
1572            });
1573        }
1574    });
1575    let shared = shared.into_inner().unwrap_or_else(PoisonError::into_inner);
1576    match shared.error {
1577        Some(e) => Err(e),
1578        None => Ok(()),
1579    }
1580}
1581
1582#[cfg(test)]
1583mod tests {
1584    use datafusion::arrow::array::{AsArray, Int64Array};
1585    use datafusion::arrow::datatypes::Int64Type;
1586
1587    use super::*;
1588
1589    /// The index of edges `(src, dst)`, in row order.
1590    fn index(edges: &[(i64, i64)]) -> (Topology, IdMap) {
1591        let src: ArrayRef = Arc::new(Int64Array::from(
1592            edges.iter().map(|e| e.0).collect::<Vec<_>>(),
1593        ));
1594        let dst: ArrayRef = Arc::new(Int64Array::from(
1595            edges.iter().map(|e| e.1).collect::<Vec<_>>(),
1596        ));
1597        let mut interner = ursa_core::EdgeInterner::with_capacity(edges.len());
1598        interner.push(src.as_ref(), dst.as_ref()).unwrap();
1599        let (ids, s, d) = interner.finish();
1600        (Topology::build(ids.len(), s, d), ids)
1601    }
1602
1603    fn search(
1604        direction: Direction,
1605        min: u32,
1606        max: Option<u32>,
1607        selector: Selector,
1608        mode: Mode,
1609    ) -> Search {
1610        Search {
1611            direction,
1612            quantifier: Quantifier { min, max },
1613            selector,
1614            mode,
1615        }
1616    }
1617
1618    /// Each path as (vertices, edges).
1619    /// A path: its vertices and its edges.
1620    type Path = (Vec<i64>, Vec<i64>);
1621
1622    fn paths(edges: &[(i64, i64)], starts: &[i64], s: Search) -> Vec<Path> {
1623        targeted(edges, starts, None, s).0
1624    }
1625
1626    /// Each path as (vertices, edges), searched toward `targets`, and how
1627    /// many prefixes the search extended.
1628    fn targeted(
1629        edges: &[(i64, i64)],
1630        starts: &[i64],
1631        targets: Option<&[i64]>,
1632        s: Search,
1633    ) -> (Vec<Path>, usize) {
1634        let (topology, ids) = index(edges);
1635        let targets: Option<ArrayRef> =
1636            targets.map(|t| Arc::new(Int64Array::from(t.to_vec())) as ArrayRef);
1637        let columns = PathColumns {
1638            vertices: true,
1639            edges: true,
1640            elements: true,
1641        };
1642        let schema = Arc::new(super::schema(&DataType::Int64, columns));
1643        let starts: ArrayRef = Arc::new(Int64Array::from(starts.to_vec()));
1644        let (batches, expanded) = run(
1645            &topology,
1646            &ids,
1647            &|e| u64::from(e),
1648            &s,
1649            &starts,
1650            targets.as_ref(),
1651            false,
1652            columns,
1653            schema,
1654            Some(MAX_PATHS),
1655        )
1656        .unwrap();
1657        let mut out = Vec::new();
1658        for b in batches {
1659            let v = b.column(3).as_list::<i32>();
1660            let e = b.column(4).as_list::<i32>();
1661            let el = b.column(5).as_list::<i32>();
1662            for r in 0..b.num_rows() {
1663                let vs: Vec<i64> = v.value(r).as_primitive::<Int64Type>().values().to_vec();
1664                let es: Vec<i64> = e.value(r).as_primitive::<Int64Type>().values().to_vec();
1665                let els: Vec<i64> = el.value(r).as_primitive::<Int64Type>().values().to_vec();
1666                assert_eq!(els.len(), vs.len() + es.len());
1667                assert_eq!(
1668                    b.column(2).as_primitive::<Int64Type>().value(r),
1669                    es.len() as i64
1670                );
1671                out.push((vs, es));
1672            }
1673        }
1674        (out, expanded)
1675    }
1676
1677    /// A search toward targets keeps the paths a search without them finds
1678    /// to those targets, in the same order, extending fewer prefixes.
1679    #[test]
1680    fn targets_keep_the_same_paths_and_stop_early() {
1681        // A chain 0 → 1 → … → 9 with a fan out of every node, and shortcuts.
1682        let mut edges: Vec<(i64, i64)> = (0..9).map(|i| (i, i + 1)).collect();
1683        for i in 0..10 {
1684            edges.extend((0..4).map(|j| (i, 100 + 10 * i + j)));
1685        }
1686        edges.extend([(0, 5), (2, 7), (5, 5), (7, 2), (3, 1)]);
1687        let graphs: [&[(i64, i64)]; 2] = [KNOW, &edges];
1688        let mut stopped_early = false;
1689        for edges in graphs {
1690            for direction in [Direction::Right, Direction::Left, Direction::Any] {
1691                for selector in [
1692                    Selector::All,
1693                    Selector::Shortest(1),
1694                    Selector::Shortest(2),
1695                    Selector::AllShortest,
1696                ] {
1697                    for mode in [Mode::Walk, Mode::Trail, Mode::Simple, Mode::Acyclic] {
1698                        for (min, max) in [(0, Some(3)), (1, None), (2, Some(4)), (1, Some(1))] {
1699                            if selector == Selector::All && mode == Mode::Walk && max.is_none() {
1700                                continue;
1701                            }
1702                            let s = search(direction, min, max, selector, mode);
1703                            for (starts, targets) in [
1704                                (&[0][..], &[3][..]),
1705                                (&[0, 4], &[0, 3, 9]),
1706                                (&[1, 2], &[2, 77]),
1707                                (&[3], &[7, 5, 1]),
1708                            ] {
1709                                let (all, n_all) = targeted(edges, starts, None, s);
1710                                let kept: Vec<_> = all
1711                                    .into_iter()
1712                                    .filter(|(v, _)| targets.contains(v.last().unwrap()))
1713                                    .collect();
1714                                let (found, n) = targeted(edges, starts, Some(targets), s);
1715                                assert_eq!(found, kept, "{s} from {starts:?} to {targets:?}");
1716                                assert!(n <= n_all, "{s}");
1717                                stopped_early |= n < n_all;
1718                            }
1719                        }
1720                    }
1721                }
1722            }
1723        }
1724        assert!(stopped_early);
1725    }
1726
1727    // DuckPGQ's test graph: Daniel 0, Tavneet 1, Gabor 2, Peter 3, David 4.
1728    const KNOW: &[(i64, i64)] = &[
1729        (0, 1),
1730        (0, 2),
1731        (0, 3),
1732        (3, 0),
1733        (1, 2),
1734        (1, 3),
1735        (2, 3),
1736        (4, 3),
1737    ];
1738
1739    #[test]
1740    fn any_shortest_takes_the_first_edges_and_can_return_to_the_start() {
1741        let found = paths(
1742            KNOW,
1743            &[4],
1744            search(
1745                Direction::Right,
1746                1,
1747                Some(3),
1748                Selector::Shortest(1),
1749                Mode::Walk,
1750            ),
1751        );
1752        assert_eq!(
1753            found,
1754            vec![
1755                (vec![4, 3], vec![7]),
1756                (vec![4, 3, 0], vec![7, 3]),
1757                (vec![4, 3, 0, 1], vec![7, 3, 0]),
1758                (vec![4, 3, 0, 2], vec![7, 3, 1]),
1759            ]
1760        );
1761        // From 0, a shortest walk of one edge or more back to 0 is 0→3→0.
1762        let found = paths(
1763            KNOW,
1764            &[0],
1765            search(
1766                Direction::Right,
1767                1,
1768                Some(3),
1769                Selector::Shortest(1),
1770                Mode::Walk,
1771            ),
1772        );
1773        assert!(found.contains(&(vec![0, 3, 0], vec![2, 3])));
1774        // ACYCLIC drops it.
1775        let found = paths(
1776            KNOW,
1777            &[0],
1778            search(
1779                Direction::Right,
1780                1,
1781                Some(3),
1782                Selector::Shortest(1),
1783                Mode::Acyclic,
1784            ),
1785        );
1786        assert!(found.iter().all(|(v, _)| v.last() != Some(&0)));
1787    }
1788
1789    #[test]
1790    fn walks_trails_and_counts() {
1791        // Every walk of 1 or 2 edges from Peter: 3→0, then 0→1, 0→2, 0→3.
1792        let found = paths(
1793            KNOW,
1794            &[3],
1795            search(Direction::Right, 1, Some(2), Selector::All, Mode::Walk),
1796        );
1797        assert_eq!(found.len(), 4);
1798        // Without a bound under ACYCLIC: every simple path, finitely many.
1799        let acyclic = paths(
1800            KNOW,
1801            &[3],
1802            search(Direction::Right, 1, None, Selector::All, Mode::Acyclic),
1803        );
1804        assert!(acyclic.iter().all(|(v, _)| {
1805            let mut s = v.clone();
1806            s.sort();
1807            s.dedup();
1808            s.len() == v.len()
1809        }));
1810        // 3→0, 3→0→1, 3→0→2 and 3→0→1→2.
1811        assert_eq!(acyclic.len(), 4);
1812        // SHORTEST 2 from 0 to 3: 0→3 (edge 2), then 0→1→3 (0, 5) before 0→2→3 (1, 6).
1813        let found = paths(
1814            KNOW,
1815            &[0],
1816            search(Direction::Right, 1, None, Selector::Shortest(2), Mode::Walk),
1817        );
1818        let to3: Vec<_> = found.iter().filter(|(v, _)| v.last() == Some(&3)).collect();
1819        assert_eq!(
1820            to3,
1821            vec![&(vec![0, 3], vec![2]), &(vec![0, 1, 3], vec![0, 5])]
1822        );
1823        // ALL SHORTEST from 0 to 3 is the one edge; to 2: 0→2 alone.
1824        let found = paths(
1825            KNOW,
1826            &[1],
1827            search(Direction::Right, 1, None, Selector::AllShortest, Mode::Walk),
1828        );
1829        let to0: Vec<_> = found.iter().filter(|(v, _)| v.last() == Some(&0)).collect();
1830        assert_eq!(to0, vec![&(vec![1, 3, 0], vec![5, 3])]);
1831        let found = paths(
1832            KNOW,
1833            &[4],
1834            search(
1835                Direction::Right,
1836                3,
1837                Some(3),
1838                Selector::AllShortest,
1839                Mode::Walk,
1840            ),
1841        );
1842        let to2: Vec<_> = found.iter().filter(|(v, _)| v.last() == Some(&2)).collect();
1843        assert_eq!(to2, vec![&(vec![4, 3, 0, 2], vec![7, 3, 1])]);
1844    }
1845
1846    #[test]
1847    fn zero_length_undirected_and_trails() {
1848        // A start with no edges has its path of no edges.
1849        let found = paths(
1850            KNOW,
1851            &[9, 0],
1852            search(Direction::Right, 0, Some(0), Selector::All, Mode::Walk),
1853        );
1854        assert_eq!(found, vec![(vec![9], vec![]), (vec![0], vec![])]);
1855        // Undirected, a self-loop is followed once.
1856        let found = paths(
1857            &[(1, 1), (1, 2)],
1858            &[1],
1859            search(Direction::Any, 1, Some(1), Selector::All, Mode::Walk),
1860        );
1861        assert_eq!(found, vec![(vec![1, 1], vec![0]), (vec![1, 2], vec![1])]);
1862        // An undirected trail back to the start cannot reuse its edge: 1-2-1
1863        // takes the two parallel edges.
1864        let found = paths(
1865            &[(1, 2), (2, 1)],
1866            &[1],
1867            search(Direction::Any, 1, Some(2), Selector::All, Mode::Trail),
1868        );
1869        assert_eq!(
1870            found,
1871            vec![
1872                (vec![1, 2], vec![0]),
1873                (vec![1, 2], vec![1]),
1874                (vec![1, 2, 1], vec![0, 1]),
1875                (vec![1, 2, 1], vec![1, 0]),
1876            ]
1877        );
1878        // Left: against the edges.
1879        let found = paths(
1880            KNOW,
1881            &[3],
1882            search(Direction::Left, 1, Some(1), Selector::All, Mode::Walk),
1883        );
1884        assert_eq!(
1885            found,
1886            vec![
1887                (vec![3, 0], vec![2]),
1888                (vec![3, 1], vec![5]),
1889                (vec![3, 2], vec![6]),
1890                (vec![3, 4], vec![7])
1891            ]
1892        );
1893        // SIMPLE: back to the start is allowed, once.
1894        let found = paths(
1895            KNOW,
1896            &[0],
1897            search(Direction::Right, 2, Some(2), Selector::All, Mode::Simple),
1898        );
1899        assert!(found.contains(&(vec![0, 3, 0], vec![2, 3])));
1900    }
1901
1902    /// FNV-1a, 64 bits: a hash that is the same on every platform and run.
1903    struct Fnv(u64);
1904
1905    impl Fnv {
1906        fn new() -> Self {
1907            Fnv(0xcbf2_9ce4_8422_2325)
1908        }
1909
1910        fn bytes(&mut self, b: &[u8]) {
1911            for &x in b {
1912                self.0 ^= u64::from(x);
1913                self.0 = self.0.wrapping_mul(0x0100_0000_01b3);
1914            }
1915        }
1916
1917        fn int(&mut self, v: i64) {
1918            self.bytes(&v.to_le_bytes());
1919        }
1920    }
1921
1922    /// splitmix64.
1923    fn mix(state: &mut u64) -> u64 {
1924        *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
1925        let mut z = *state;
1926        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
1927        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
1928        z ^ (z >> 31)
1929    }
1930
1931    /// `m` R-MAT edges over `2^scale` node slots (the Graph500 quadrants),
1932    /// with node keys spread out (`key * 3 + 1`) so they are not the dense
1933    /// numbers.
1934    fn rmat(m: usize, scale: u32, seed: u64) -> Vec<(i64, i64)> {
1935        let mut st = seed;
1936        let (a, ab, abc) = (0.57, 0.76, 0.95);
1937        (0..m)
1938            .map(|_| {
1939                let (mut s, mut d) = (0i64, 0i64);
1940                for _ in 0..scale {
1941                    let r = (mix(&mut st) >> 11) as f64 / (1u64 << 53) as f64;
1942                    s = s << 1 | i64::from(r >= ab);
1943                    d = d << 1 | i64::from((r >= a && r < ab) || r >= abc);
1944                }
1945                (s * 3 + 1, d * 3 + 1)
1946            })
1947            .collect()
1948    }
1949
1950    /// `m` uniform edges among `n` nodes, with self-loops and parallel edges.
1951    fn uniform(m: usize, n: u64, seed: u64) -> Vec<(i64, i64)> {
1952        let mut st = seed;
1953        (0..m)
1954            .map(|_| ((mix(&mut st) % n) as i64, (mix(&mut st) % n) as i64))
1955            .collect()
1956    }
1957
1958    /// One run of `s`, as a hash of every row in order (start, end, length,
1959    /// vertices, edges, element ids) and how many prefixes it extended, or of
1960    /// its error.
1961    fn pinned(
1962        topology: &Topology,
1963        ids: &IdMap,
1964        s: &Search,
1965        starts: &ArrayRef,
1966        targets: Option<&ArrayRef>,
1967        max_paths: Option<usize>,
1968        hash: &mut Fnv,
1969    ) -> usize {
1970        let columns = PathColumns {
1971            vertices: true,
1972            edges: true,
1973            elements: true,
1974        };
1975        let schema = Arc::new(super::schema(&DataType::Int64, columns));
1976        let edge_row = |e: u32| u64::from(e) * 2 + 5;
1977        let result = run(
1978            topology, ids, &edge_row, s, starts, targets, false, columns, schema, max_paths,
1979        );
1980        match result {
1981            Err(e) => {
1982                hash.bytes(b"error");
1983                hash.bytes(e.to_string().as_bytes());
1984                0
1985            }
1986            Ok((batches, expanded)) => {
1987                let mut n = 0;
1988                for b in &batches {
1989                    for c in 0..3 {
1990                        let col = b.column(c).as_primitive::<Int64Type>();
1991                        hash.int(col.len() as i64);
1992                        col.values().iter().for_each(|&v| hash.int(v));
1993                    }
1994                    for c in 3..6 {
1995                        let list = b.column(c).as_list::<i32>();
1996                        list.offsets().iter().for_each(|&o| hash.int(i64::from(o)));
1997                        let values = list.values().as_primitive::<Int64Type>();
1998                        values.values().iter().for_each(|&v| hash.int(v));
1999                    }
2000                    n += b.num_rows();
2001                }
2002                hash.int(expanded as i64);
2003                n
2004            }
2005        }
2006    }
2007
2008    /// The three state tables keep the same prefixes: the map, used past
2009    /// the dense tables' memory budget, which no graph in these tests
2010    /// reaches, and the bits of `ANY SHORTEST`, against the table.
2011    #[test]
2012    fn state_tables_agree() {
2013        let mut st = 5u64;
2014        for selector in [
2015            Selector::All,
2016            Selector::Shortest(1),
2017            Selector::Shortest(3),
2018            Selector::AllShortest,
2019        ] {
2020            let n = 300;
2021            let mut pairs = Pairs {
2022                seen: vec![(0, 0); n],
2023                touched: Vec::new(),
2024            };
2025            let mut sparse = Sparse(FxHashMap::default());
2026            let mut bits = Bits {
2027                words: vec![0; n.div_ceil(64)],
2028                touched: Vec::new(),
2029            };
2030            for round in 0..20 {
2031                pairs.clear();
2032                sparse.clear();
2033                bits.clear();
2034                let first = (mix(&mut st) % n as u64) as usize;
2035                pairs.start(first);
2036                sparse.start(first);
2037                bits.start(first);
2038                // Rounds that reach a few states, and rounds that reach most.
2039                let steps = if round % 2 == 0 { 40 } else { 3000 };
2040                for _ in 0..steps {
2041                    let i = (mix(&mut st) % n as u64) as usize;
2042                    let len = 1 + (mix(&mut st) % 4) as u32;
2043                    let kept = pairs.accept(i, len, selector);
2044                    assert_eq!(sparse.accept(i, len, selector), kept, "{selector:?}");
2045                    if selector == Selector::Shortest(1) {
2046                        assert_eq!(bits.accept(i, len, selector), kept);
2047                    }
2048                }
2049            }
2050        }
2051    }
2052
2053    /// The rows of path searches over a matrix of graphs, directions,
2054    /// selectors, modes, bounds, start nodes, targets and limits, pinned as
2055    /// one hash per graph: recorded before the search was made faster
2056    /// (#451), so a change that moves a row, changes a path or changes when
2057    /// `ursa.max_paths` refuses a search fails here. The same on one thread
2058    /// and on four.
2059    #[test]
2060    fn rows_and_their_order_are_pinned() {
2061        let mut chain: Vec<(i64, i64)> = (0..9).map(|i| (i, i + 1)).collect();
2062        for i in 0..10 {
2063            chain.extend((0..4).map(|j| (i, 100 + 10 * i + j)));
2064        }
2065        chain.extend([(0, 5), (2, 7), (5, 5), (7, 2), (3, 1)]);
2066        let graphs: Vec<(&str, Vec<(i64, i64)>)> = vec![
2067            ("know", KNOW.to_vec()),
2068            ("chain", chain),
2069            ("uniform", uniform(140, 40, 7)),
2070            ("rmat", rmat(600, 7, 11)),
2071        ];
2072        let quantifiers: &[(u32, Option<u32>)] = &[
2073            (0, Some(0)),
2074            (0, Some(2)),
2075            (1, Some(1)),
2076            (1, Some(3)),
2077            (1, None),
2078            (2, Some(3)),
2079            (3, None),
2080        ];
2081        let expected: &[(&str, u64, usize)] = &[
2082            ("know", 12579871203238691482, 71739),
2083            ("chain", 1410182832036601776, 234240),
2084            ("uniform", 5017031796771702360, 385893),
2085            ("rmat", 9397029938903403620, 276899),
2086        ];
2087        let mut got = Vec::new();
2088        for threads in [1, 4] {
2089            let pool = rayon::ThreadPoolBuilder::new()
2090                .num_threads(threads)
2091                .build()
2092                .unwrap();
2093            for (name, edges) in &graphs {
2094                let (topology, ids) = index(edges);
2095                let mut keys: Vec<i64> = edges.iter().flat_map(|&(s, d)| [s, d]).collect();
2096                keys.sort();
2097                keys.dedup();
2098                let all: ArrayRef = Arc::new(Int64Array::from(keys.clone()));
2099                let one: ArrayRef = Arc::new(Int64Array::from(vec![keys[0]]));
2100                // A few, out of key order, with a null and a key that is no node.
2101                let some: ArrayRef = Arc::new(Int64Array::from(vec![
2102                    Some(keys[keys.len() / 2]),
2103                    None,
2104                    Some(-77),
2105                    Some(keys[0]),
2106                    Some(keys[keys.len() - 1]),
2107                    Some(keys[1]),
2108                ]));
2109                let targets: ArrayRef = Arc::new(Int64Array::from(vec![
2110                    keys[keys.len() / 3],
2111                    keys[0],
2112                    -5,
2113                    keys[keys.len() - 2],
2114                ]));
2115                let mut hash = Fnv::new();
2116                let mut rows = 0;
2117                for direction in [Direction::Right, Direction::Left, Direction::Any] {
2118                    for selector in [
2119                        Selector::All,
2120                        Selector::Shortest(1),
2121                        Selector::Shortest(3),
2122                        Selector::AllShortest,
2123                    ] {
2124                        for mode in [Mode::Walk, Mode::Trail, Mode::Simple, Mode::Acyclic] {
2125                            for &(min, max) in quantifiers {
2126                                if selector == Selector::All && mode == Mode::Walk && max.is_none()
2127                                {
2128                                    continue;
2129                                }
2130                                let s = search(direction, min, max, selector, mode);
2131                                for starts in [&one, &some, &all] {
2132                                    for t in [None, Some(&targets)] {
2133                                        for cap in [Some(300), Some(3_000)] {
2134                                            hash.bytes(s.to_string().as_bytes());
2135                                            rows += pool.install(|| {
2136                                                pinned(
2137                                                    &topology, &ids, &s, starts, t, cap, &mut hash,
2138                                                )
2139                                            });
2140                                        }
2141                                    }
2142                                }
2143                            }
2144                        }
2145                    }
2146                }
2147                got.push((*name, hash.0, rows));
2148            }
2149        }
2150        let (one, four) = got.split_at(graphs.len());
2151        assert_eq!(one, four, "one thread and four differ");
2152        assert_eq!(one, expected, "the pinned rows changed");
2153    }
2154}