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