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//! ## The limit
69//!
70//! A search stops with an error once it holds more paths than
71//! `ursa.max_paths` (default [`MAX_PATHS`]; 0 for no limit). What counts
72//! depends on what the search can hold (#384, N50):
73//!
74//! - A pruned search with `ANY SHORTEST` or `SHORTEST k` holds at most `k`
75//!   prefixes per (node, edges so far up to `min`), so its memory is bounded
76//!   by the graph's nodes. It counts the paths it keeps (for `ANY SHORTEST`,
77//!   one per pair of first and last node: the destinations), never fewer
78//!   than `k` per node of the graph, so one start is never refused what
79//!   `hop` would list.
80//! - Every other search counts the prefixes it holds and the paths it keeps:
81//!   a walk's prefixes can grow exponentially with its length.
82
83use std::collections::{HashMap, HashSet};
84use std::fmt;
85use std::hash::{Hash, Hasher};
86use std::sync::Arc;
87
88use datafusion::arrow::array::{
89    Array, ArrayBuilder, ArrayRef, Int64Array, Int64Builder, ListArray, UInt32Array,
90};
91use datafusion::arrow::buffer::OffsetBuffer;
92use datafusion::arrow::compute::{concat, take};
93use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
94use datafusion::arrow::record_batch::RecordBatch;
95use datafusion::common::{DFSchema, DFSchemaRef, ScalarValue};
96use datafusion::error::{DataFusionError, Result};
97use datafusion::logical_expr::{Expr, LogicalPlan, UserDefinedLogicalNodeCore};
98use ursa_core::{IdMap, Topology};
99
100use super::node::{check_vertices, endpoint_id_type};
101use super::pattern::{Direction, Mode, Quantifier, Selector};
102
103/// The path's first node.
104pub const START: &str = "__start";
105/// Its last node.
106pub const END: &str = "__end";
107/// Its number of edges.
108pub const LENGTH: &str = "__length";
109/// Its nodes, first to last.
110pub const VERTICES: &str = "__vertices";
111/// Its edges' rows in the edge table.
112pub const EDGES: &str = "__edges";
113/// Its nodes and edges, alternating.
114pub const ELEMENTS: &str = "__element_id";
115
116/// The path functions, and the column each reads.
117pub const FUNCTIONS: &[(&str, &str)] = &[
118    ("path_length", LENGTH),
119    ("vertices", VERTICES),
120    ("edges", EDGES),
121    ("element_id", ELEMENTS),
122];
123
124/// The default `ursa.max_paths`: the most paths one search holds before it
125/// stops with an error (see the module docs).
126pub const MAX_PATHS: usize = 10_000_000;
127
128/// Rows per output batch.
129const BATCH_ROWS: usize = 8192;
130
131/// What a search looks for.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd)]
133pub struct Search {
134    pub direction: Direction,
135    pub quantifier: Quantifier,
136    pub selector: Selector,
137    pub mode: Mode,
138}
139
140impl fmt::Display for Search {
141    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
142        match self.selector {
143            Selector::All => {}
144            Selector::Shortest(1) => write!(f, "ANY SHORTEST ")?,
145            Selector::Shortest(k) => write!(f, "SHORTEST {k} ")?,
146            Selector::AllShortest => write!(f, "ALL SHORTEST ")?,
147        }
148        let mode = match self.mode {
149            Mode::Walk => "WALK",
150            Mode::Trail => "TRAIL",
151            Mode::Simple => "SIMPLE",
152            Mode::Acyclic => "ACYCLIC",
153        };
154        let arrow = match self.direction {
155            Direction::Right => "-[]->",
156            Direction::Left => "<-[]-",
157            Direction::Any => "-[]-",
158        };
159        let max = self
160            .quantifier
161            .max
162            .map(|m| m.to_string())
163            .unwrap_or_default();
164        write!(f, "{mode} {arrow}{{{},{max}}}", self.quantifier.min)
165    }
166}
167
168/// Which path columns a node computes besides its ends and length.
169#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd)]
170pub struct PathColumns {
171    pub vertices: bool,
172    pub edges: bool,
173    pub elements: bool,
174}
175
176/// The schema of a search's rows, for node ids of `id_type`.
177pub fn schema(id_type: &DataType, columns: PathColumns) -> Schema {
178    let list = |t: DataType| DataType::List(Arc::new(Field::new_list_field(t, false)));
179    let mut fields = vec![
180        Field::new(START, id_type.clone(), false),
181        Field::new(END, id_type.clone(), false),
182        Field::new(LENGTH, DataType::Int64, false),
183    ];
184    if columns.vertices {
185        fields.push(Field::new(VERTICES, list(id_type.clone()), false));
186    }
187    if columns.edges {
188        fields.push(Field::new(EDGES, list(DataType::Int64), false));
189    }
190    if columns.elements {
191        fields.push(Field::new(ELEMENTS, list(DataType::Int64), false));
192    }
193    Schema::new(fields)
194}
195
196/// A search on a graph's index, as a logical plan node. Its inputs:
197///
198/// 1. the edge table's rows, projected to the endpoints (the plan the index
199///    is built from, as for a traversal);
200/// 2. the start nodes: one column of keys, each once.
201#[derive(Debug, Clone)]
202pub struct PathSearchNode {
203    pub graph: String,
204    pub search: Search,
205    pub columns: PathColumns,
206    pub input: Arc<LogicalPlan>,
207    /// The keys of the vertex tables the edges connect, one column, when they
208    /// have them: the graph's nodes, as an algorithm's (#311).
209    pub vertices: Option<Arc<LogicalPlan>>,
210    pub starts: Arc<LogicalPlan>,
211    /// The keys the paths may end at, one column, if they are known (see the
212    /// module docs).
213    pub targets: Option<Arc<LogicalPlan>>,
214    /// Whether every node the starts can name is a node of the index (the
215    /// start node's table is the one the index's nodes are the keys of): a
216    /// start that is not one is no node, so it has no path, not even the
217    /// path of no edges.
218    pub known_only: bool,
219    pub source: Expr,
220    pub destination: Expr,
221    pub id_type: DataType,
222    schema: DFSchemaRef,
223}
224
225impl PathSearchNode {
226    #[allow(clippy::too_many_arguments)]
227    pub fn try_new(
228        graph: String,
229        search: Search,
230        columns: PathColumns,
231        input: Arc<LogicalPlan>,
232        vertices: Option<Arc<LogicalPlan>>,
233        starts: Arc<LogicalPlan>,
234        targets: Option<Arc<LogicalPlan>>,
235        known_only: bool,
236        source: Expr,
237        destination: Expr,
238    ) -> Result<Self> {
239        let id_type = endpoint_id_type(&graph, &input, &source, &destination)?;
240        check_vertices(&graph, vertices.as_deref())?;
241        if columns.elements && id_type != DataType::Int64 {
242            return Err(DataFusionError::Plan(format!(
243                "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)"
244            )));
245        }
246        let schema = Arc::new(DFSchema::try_from(schema(&id_type, columns))?);
247        Ok(Self {
248            graph,
249            search,
250            columns,
251            input,
252            vertices,
253            starts,
254            targets,
255            known_only,
256            source,
257            destination,
258            id_type,
259            schema,
260        })
261    }
262
263    pub(crate) fn endpoint_indices(&self) -> Result<(usize, usize)> {
264        let index = |e: &Expr| -> Result<usize> {
265            match e {
266                Expr::Column(c) => self.input.schema().index_of_column(c),
267                other => Err(DataFusionError::Internal(format!(
268                    "a path search's endpoint must be a column; got {other}"
269                ))),
270            }
271        };
272        Ok((index(&self.source)?, index(&self.destination)?))
273    }
274}
275
276impl PartialEq for PathSearchNode {
277    fn eq(&self, other: &Self) -> bool {
278        self.graph == other.graph
279            && self.search == other.search
280            && self.columns == other.columns
281            && self.input == other.input
282            && self.vertices == other.vertices
283            && self.starts == other.starts
284            && self.targets == other.targets
285            && self.known_only == other.known_only
286            && self.source == other.source
287            && self.destination == other.destination
288    }
289}
290
291impl Eq for PathSearchNode {}
292
293impl Hash for PathSearchNode {
294    fn hash<H: Hasher>(&self, state: &mut H) {
295        self.graph.hash(state);
296        self.search.hash(state);
297        self.columns.hash(state);
298        self.input.hash(state);
299        self.vertices.hash(state);
300        self.starts.hash(state);
301        self.targets.hash(state);
302        self.known_only.hash(state);
303    }
304}
305
306impl PartialOrd for PathSearchNode {
307    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
308        (&self.graph, &self.search, &self.columns)
309            .partial_cmp(&(&other.graph, &other.search, &other.columns))
310            .filter(|o| o.is_ne())
311    }
312}
313
314impl UserDefinedLogicalNodeCore for PathSearchNode {
315    fn name(&self) -> &str {
316        "PathSearch"
317    }
318
319    fn inputs(&self) -> Vec<&LogicalPlan> {
320        let mut inputs = vec![self.input.as_ref()];
321        inputs.extend(self.vertices.as_deref());
322        inputs.push(&self.starts);
323        inputs.extend(self.targets.as_deref());
324        inputs
325    }
326
327    fn schema(&self) -> &DFSchemaRef {
328        &self.schema
329    }
330
331    fn expressions(&self) -> Vec<Expr> {
332        vec![]
333    }
334
335    fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
336        write!(
337            f,
338            "PathSearch: graph={}, search={}{}",
339            self.graph,
340            self.search,
341            if self.targets.is_some() {
342                ", targets"
343            } else {
344                ""
345            }
346        )
347    }
348
349    fn with_exprs_and_inputs(&self, _exprs: Vec<Expr>, inputs: Vec<LogicalPlan>) -> Result<Self> {
350        let expected =
351            2 + usize::from(self.vertices.is_some()) + usize::from(self.targets.is_some());
352        if inputs.len() != expected {
353            return Err(DataFusionError::Internal(format!(
354                "PathSearch has {expected} inputs; got {}",
355                inputs.len()
356            )));
357        }
358        let mut inputs = inputs.into_iter().map(Arc::new);
359        let input = inputs.next().expect("checked above");
360        let vertices = self.vertices.as_ref().and_then(|_| inputs.next());
361        let starts = inputs.next().expect("checked above");
362        let targets = self.targets.as_ref().and_then(|_| inputs.next());
363        Ok(Self {
364            input,
365            vertices,
366            starts,
367            targets,
368            ..self.clone()
369        })
370    }
371
372    /// Every input is read whole: the endpoints, the vertex key, the one
373    /// start column and the one target column.
374    fn necessary_children_exprs(&self, _output_columns: &[usize]) -> Option<Vec<Vec<usize>>> {
375        let (source, destination) = self.endpoint_indices().ok()?;
376        let mut children = vec![vec![source, destination]];
377        if self.vertices.is_some() {
378            children.push(vec![0]);
379        }
380        children.push(vec![0]);
381        if self.targets.is_some() {
382            children.push(vec![0]);
383        }
384        Some(children)
385    }
386
387    /// A filter on the paths cannot move into the edges or the starts.
388    fn prevent_predicate_push_down_columns(&self) -> std::collections::HashSet<String> {
389        self.schema
390            .fields()
391            .iter()
392            .map(|f| f.name().clone())
393            .collect()
394    }
395}
396
397/// One path prefix the search holds: its last node, the entry it extends,
398/// the edge that does, and its length.
399#[derive(Debug, Clone, Copy)]
400struct Entry {
401    node: u32,
402    parent: u32,
403    edge: u32,
404    len: u32,
405}
406
407const ROOT: u32 = u32::MAX;
408
409/// Per search state, (node, edges so far up to `min`): how many prefixes
410/// reached it, and the length of the first.
411enum States {
412    Dense {
413        seen: Vec<(u32, u32)>,
414        touched: Vec<usize>,
415        width: usize,
416    },
417    Sparse(HashMap<(u32, u32), (u32, u32)>),
418}
419
420impl States {
421    fn new(n_nodes: usize, min: u32) -> Self {
422        let width = min as usize + 1;
423        match n_nodes.checked_mul(width) {
424            Some(n) if n <= 1 << 26 => States::Dense {
425                seen: vec![(0, 0); n],
426                touched: Vec::new(),
427                width,
428            },
429            _ => States::Sparse(HashMap::new()),
430        }
431    }
432
433    fn get(&mut self, node: u32, c: u32) -> &mut (u32, u32) {
434        match self {
435            States::Dense {
436                seen,
437                touched,
438                width,
439            } => {
440                let i = node as usize * *width + c as usize;
441                if seen[i].0 == 0 {
442                    touched.push(i);
443                }
444                &mut seen[i]
445            }
446            States::Sparse(map) => map.entry((node, c)).or_insert((0, 0)),
447        }
448    }
449
450    fn clear(&mut self) {
451        match self {
452            States::Dense { seen, touched, .. } => {
453                for i in touched.drain(..) {
454                    seen[i] = (0, 0);
455                }
456            }
457            States::Sparse(map) => map.clear(),
458        }
459    }
460}
461
462/// The edges a step can take from `u`, in edge-row order, as (next node,
463/// edge row).
464fn steps(topology: &Topology, direction: Direction, u: u32, out: &mut Vec<(u32, u32)>) {
465    out.clear();
466    fn pairs(a: &ursa_core::Adjacency, u: u32) -> impl Iterator<Item = (u32, u32)> + '_ {
467        a.neighbors(u)
468            .iter()
469            .copied()
470            .zip(a.edge_ids(u).iter().copied())
471    }
472    match direction {
473        Direction::Right => out.extend(pairs(topology.out(), u)),
474        Direction::Left => out.extend(pairs(topology.incoming(), u)),
475        Direction::Any => {
476            let forward: Vec<(u32, u32)> = pairs(topology.out(), u).collect();
477            // A self-loop is in both lists: it is taken once, forward.
478            let backward: Vec<(u32, u32)> = pairs(topology.incoming(), u)
479                .filter(|&(w, _)| w != u)
480                .collect();
481            let (mut i, mut j) = (0, 0);
482            while i < forward.len() || j < backward.len() {
483                let take_forward =
484                    j == backward.len() || (i < forward.len() && forward[i].1 < backward[j].1);
485                if take_forward {
486                    out.push(forward[i]);
487                    i += 1;
488                } else {
489                    out.push(backward[j]);
490                    j += 1;
491                }
492            }
493        }
494    }
495}
496
497/// Whether a prefix ending at entry `at` may take the edge `edge` to `w`
498/// under `mode`.
499fn allowed(entries: &[Entry], at: u32, w: u32, edge: u32, mode: Mode, start: u32) -> bool {
500    let chain = || {
501        let mut i = at;
502        std::iter::from_fn(move || {
503            if i == ROOT {
504                return None;
505            }
506            let e = entries[i as usize];
507            i = e.parent;
508            Some(e)
509        })
510    };
511    match mode {
512        Mode::Walk => true,
513        Mode::Trail => chain().all(|e| e.parent == ROOT || e.edge != edge),
514        Mode::Acyclic => chain().all(|e| e.node != w),
515        Mode::Simple => {
516            let last = entries[at as usize];
517            if last.len > 0 && last.node == start {
518                return false; // closed: it cannot go on
519            }
520            w == start && chain().all(|e| e.node != w || e.parent == ROOT)
521                || chain().all(|e| e.node != w)
522        }
523    }
524}
525
526/// Collects a search's rows into batches.
527struct Rows<'a> {
528    starts: &'a ArrayRef,
529    columns: PathColumns,
530    schema: SchemaRef,
531    start_rows: Vec<u32>,
532    ends: Vec<u32>,
533    lengths: Vec<i64>,
534    vertex_offsets: Vec<i32>,
535    vertex_values: Vec<u32>,
536    edge_offsets: Vec<i32>,
537    edge_values: Vec<i64>,
538    batches: Vec<RecordBatch>,
539    /// The starts, then every node of the index, as user ids: what the
540    /// node references index.
541    values: ArrayRef,
542    /// The edge table's row of an edge of the index.
543    edge_row: &'a dyn Fn(u32) -> u64,
544}
545
546impl<'a> Rows<'a> {
547    fn new(
548        ids: &'a IdMap,
549        starts: &'a ArrayRef,
550        columns: PathColumns,
551        schema: SchemaRef,
552        edge_row: &'a dyn Fn(u32) -> u64,
553    ) -> Result<Self> {
554        let values = if ids.is_empty() {
555            Arc::clone(starts)
556        } else {
557            concat(&[starts.as_ref(), ids.user_id_array().as_ref()])?
558        };
559        Ok(Self {
560            starts,
561            columns,
562            schema,
563            start_rows: Vec::new(),
564            ends: Vec::new(),
565            lengths: Vec::new(),
566            vertex_offsets: vec![0],
567            vertex_values: Vec::new(),
568            edge_offsets: vec![0],
569            edge_values: Vec::new(),
570            batches: Vec::new(),
571            values,
572            edge_row,
573        })
574    }
575
576    /// The index into `values` of dense node `d`.
577    fn dense(&self, d: u32) -> u32 {
578        (self.starts.len() as u32) + d
579    }
580
581    /// A path from start row `start`: its nodes (as `values` indexes) and
582    /// edges, first to last.
583    fn push(&mut self, start: u32, nodes: &[u32], edges: &[u32]) -> Result<()> {
584        self.start_rows.push(start);
585        self.ends.push(*nodes.last().expect("a path has a node"));
586        self.lengths.push(edges.len() as i64);
587        if self.columns.vertices || self.columns.elements {
588            self.vertex_values.extend_from_slice(nodes);
589            self.vertex_offsets.push(self.vertex_values.len() as i32);
590        }
591        if self.columns.edges || self.columns.elements {
592            let edge_row = self.edge_row;
593            self.edge_values
594                .extend(edges.iter().map(|&e| edge_row(e) as i64));
595            self.edge_offsets.push(self.edge_values.len() as i32);
596        }
597        if self.start_rows.len() >= BATCH_ROWS {
598            self.flush()?;
599        }
600        Ok(())
601    }
602
603    fn flush(&mut self) -> Result<()> {
604        if self.start_rows.is_empty() {
605            return Ok(());
606        }
607        let start = take(
608            self.starts.as_ref(),
609            &UInt32Array::from(std::mem::take(&mut self.start_rows)),
610            None,
611        )?;
612        let end = take(
613            self.values.as_ref(),
614            &UInt32Array::from(std::mem::take(&mut self.ends)),
615            None,
616        )?;
617        let mut columns: Vec<ArrayRef> = vec![
618            start,
619            end,
620            Arc::new(Int64Array::from(std::mem::take(&mut self.lengths))),
621        ];
622        let vertex_offsets = std::mem::replace(&mut self.vertex_offsets, vec![0]);
623        let vertex_values = take(
624            self.values.as_ref(),
625            &UInt32Array::from(std::mem::take(&mut self.vertex_values)),
626            None,
627        )?;
628        let edge_offsets = std::mem::replace(&mut self.edge_offsets, vec![0]);
629        let edge_values = std::mem::take(&mut self.edge_values);
630        let field = |i: usize| match self.schema.field(i).data_type() {
631            DataType::List(f) => Arc::clone(f),
632            _ => unreachable!("a list column"),
633        };
634        let mut i = 3;
635        if self.columns.vertices {
636            columns.push(Arc::new(ListArray::try_new(
637                field(i),
638                OffsetBuffer::new(vertex_offsets.clone().into()),
639                Arc::clone(&vertex_values),
640                None,
641            )?));
642            i += 1;
643        }
644        if self.columns.edges {
645            columns.push(Arc::new(ListArray::try_new(
646                field(i),
647                OffsetBuffer::new(edge_offsets.clone().into()),
648                Arc::new(Int64Array::from(edge_values.clone())),
649                None,
650            )?));
651            i += 1;
652        }
653        if self.columns.elements {
654            let keys = vertex_values
655                .as_any()
656                .downcast_ref::<Int64Array>()
657                .ok_or_else(|| DataFusionError::Internal("element_id needs Int64 keys".into()))?;
658            let mut values = Int64Builder::with_capacity(keys.len() + edge_values.len());
659            let mut offsets = vec![0i32];
660            for p in 0..vertex_offsets.len() - 1 {
661                let (v0, v1) = (vertex_offsets[p] as usize, vertex_offsets[p + 1] as usize);
662                let e0 = edge_offsets[p] as usize;
663                for k in v0..v1 {
664                    values.append_value(keys.value(k));
665                    if k + 1 < v1 {
666                        values.append_value(edge_values[e0 + (k - v0)]);
667                    }
668                }
669                offsets.push(values.len() as i32);
670            }
671            columns.push(Arc::new(ListArray::try_new(
672                field(i),
673                OffsetBuffer::new(offsets.into()),
674                Arc::new(values.finish()),
675                None,
676            )?));
677        }
678        self.batches
679            .push(RecordBatch::try_new(Arc::clone(&self.schema), columns)?);
680        Ok(())
681    }
682}
683
684/// The targets of a search: the dense nodes its paths may end at, each with
685/// a slot, and the target keys that are no node of the index.
686struct Goals {
687    slots: HashMap<u32, u32>,
688    unknown: HashSet<ScalarValue>,
689}
690
691impl Goals {
692    fn new(ids: &IdMap, targets: &ArrayRef) -> Result<Self> {
693        let dense = ids
694            .dense_from_array(targets.as_ref())
695            .map_err(|e| DataFusionError::Execution(format!("in GRAPH_TABLE: {e}")))?;
696        let mut slots = HashMap::new();
697        let mut unknown = HashSet::new();
698        for (row, d) in dense.iter().enumerate() {
699            if targets.is_null(row) {
700                continue;
701            }
702            match d {
703                Some(d) => {
704                    let next = slots.len() as u32;
705                    slots.entry(*d).or_insert(next);
706                }
707                None => {
708                    unknown.insert(ScalarValue::try_from_array(targets.as_ref(), row)?);
709                }
710            }
711        }
712        Ok(Self { slots, unknown })
713    }
714}
715
716/// What one search is doing, apart from its rows.
717struct Walker<'a> {
718    topology: &'a Topology,
719    search: &'a Search,
720    restricted: bool,
721    pruned: bool,
722    states: States,
723    entries: Vec<Entry>,
724    next: Vec<(u32, u32)>,
725    /// Paths listed so far.
726    total: usize,
727    /// The most prefixes and paths the search may hold (`ursa.max_paths`),
728    /// unless it is `bounded`.
729    cap: Option<usize>,
730    /// Whether the search's memory is bounded by the graph's nodes (see the
731    /// module docs): it counts only the paths it keeps.
732    bounded: bool,
733    /// Prefixes extended so far.
734    expanded: usize,
735    /// The targets' slots, when a pruned search has targets: their paths are
736    /// known once pushed (see [`Reach`]).
737    slots: Option<&'a HashMap<u32, u32>>,
738    reach: Reach,
739}
740
741/// How far a pruned search with targets has reached them, counting the
742/// prefixes it pushed. A pruned search lists every prefix it pushes to a
743/// target (at `min` edges or more), in the order it pushed them, so once each
744/// target has its `k` (`SHORTEST k`), or its first (`ALL SHORTEST`), no
745/// prefix needs extending any more: for `ALL SHORTEST`, none at the
746/// longest of those lengths or beyond.
747#[derive(Default)]
748struct Reach {
749    /// Per slot, prefixes pushed.
750    pushed: Vec<u32>,
751    touched: Vec<u32>,
752    /// Targets without all their paths yet.
753    unfilled: usize,
754    /// The longest length at which a target was first reached.
755    longest: u32,
756}
757
758impl Reach {
759    fn reset(&mut self, n: usize) {
760        if self.pushed.len() != n {
761            self.pushed = vec![0; n];
762        }
763        for slot in self.touched.drain(..) {
764            self.pushed[slot as usize] = 0;
765        }
766        self.unfilled = n;
767        self.longest = 0;
768    }
769
770    /// Whether a prefix of `len` edges still needs extending.
771    fn extends(&self, len: u32, selector: Selector) -> bool {
772        self.unfilled > 0 || (selector == Selector::AllShortest && len < self.longest)
773    }
774}
775
776impl Walker<'_> {
777    /// Push the prefixes that extend entry `at` by one edge.
778    fn extend(&mut self, at: u32, start: u32) -> Result<()> {
779        let entry = self.entries[at as usize];
780        let min = self.search.quantifier.min;
781        self.expanded += 1;
782        steps(
783            self.topology,
784            self.search.direction,
785            entry.node,
786            &mut self.next,
787        );
788        for &(w, edge) in self.next.iter() {
789            if self.restricted && !allowed(&self.entries, at, w, edge, self.search.mode, start) {
790                continue;
791            }
792            let len = entry.len + 1;
793            if self.pruned {
794                let state = self.states.get(w, len.min(min));
795                let accept = match self.search.selector {
796                    Selector::All => true,
797                    Selector::Shortest(k) => state.0 < k,
798                    Selector::AllShortest => state.0 == 0 || state.1 == len,
799                };
800                if !accept {
801                    continue;
802                }
803                if state.0 == 0 {
804                    state.1 = len;
805                }
806                state.0 += 1;
807            }
808            self.entries.push(Entry {
809                node: w,
810                parent: at,
811                edge,
812                len,
813            });
814            // A pruned search lists this prefix: a target may have its paths.
815            let listed = len >= min && !(self.search.mode == Mode::Acyclic && w == start);
816            if let (true, true, Some(&slot)) =
817                (self.pruned, listed, self.slots.and_then(|s| s.get(&w)))
818            {
819                let reach = &mut self.reach;
820                let pushed = &mut reach.pushed[slot as usize];
821                if *pushed == 0 {
822                    reach.touched.push(slot);
823                    reach.longest = reach.longest.max(len);
824                }
825                *pushed += 1;
826                let filled = match self.search.selector {
827                    Selector::All => false,
828                    Selector::Shortest(k) => *pushed == k,
829                    Selector::AllShortest => *pushed == 1,
830                };
831                if filled {
832                    reach.unfilled -= 1;
833                }
834            }
835            if let (false, Some(cap)) = (self.bounded, self.cap) {
836                if self.entries.len() + self.total > cap {
837                    return Err(too_many_paths(cap, self.search, false));
838                }
839            }
840        }
841        Ok(())
842    }
843}
844
845/// The error of a search that reached `limit` paths, with the remedy that
846/// fits it: a search with a selector already keeps the fewest paths, so it
847/// is pointed to `hop` (a `bounded` one says it keeps one path per pair of
848/// nodes, or `k`); one without a selector to `ANY SHORTEST`. Either may
849/// raise `ursa.max_paths`.
850fn too_many_paths(limit: usize, search: &Search, bounded: bool) -> DataFusionError {
851    const RAISE: &str = "or SET ursa.max_paths to a higher limit (0 for none)";
852    const HOP: &str = "count the nodes at each distance with hop(…) \
853                       (SELECT distance, count(*) FROM hop(g, seeds => […], n => …) GROUP BY 1)";
854    let remedy = match search.selector {
855        Selector::All => format!(
856            "give the quantified edge a lower upper bound, keep fewer paths with ANY SHORTEST, \
857             {RAISE}"
858        ),
859        Selector::Shortest(1) if bounded => {
860            format!("ANY SHORTEST keeps one path per pair of nodes already; {HOP}, {RAISE}")
861        }
862        Selector::Shortest(k) if bounded => {
863            format!("SHORTEST {k} keeps {k} paths per pair of nodes already; {HOP}, {RAISE}")
864        }
865        _ => format!("give the quantified edge a lower upper bound, {HOP}, {RAISE}"),
866    };
867    DataFusionError::Execution(format!(
868        "in GRAPH_TABLE: the path search reached {limit} paths, the limit ursa.max_paths sets; \
869         {remedy}"
870    ))
871}
872
873/// Run `search` from each of `starts` (keys of the graph's id type, each
874/// once) on the index `topology`/`ids`; the rows of [`schema`], and how many
875/// path prefixes the search extended. `edge_row` gives the edge table's row
876/// of an edge of the index (see [`super::GraphIndex::edge_row`]). With
877/// `targets`, only the paths that end at one are kept, and a search with a
878/// selector stops once every target has its paths (see the module docs).
879/// With `known_only`, a start that is no node of the index has no path.
880/// `max_paths` is `ursa.max_paths` (`None` for no limit; see the module
881/// docs).
882#[allow(clippy::too_many_arguments)]
883pub fn run(
884    topology: &Topology,
885    ids: &IdMap,
886    edge_row: &dyn Fn(u32) -> u64,
887    search: &Search,
888    starts: &ArrayRef,
889    targets: Option<&ArrayRef>,
890    known_only: bool,
891    columns: PathColumns,
892    schema: SchemaRef,
893    max_paths: Option<usize>,
894) -> Result<(Vec<RecordBatch>, usize)> {
895    let dense = ids
896        .dense_from_array(starts.as_ref())
897        .map_err(|e| DataFusionError::Execution(format!("in GRAPH_TABLE: {e}")))?;
898    let goals = targets.map(|t| Goals::new(ids, t)).transpose()?;
899    let mut rows = Rows::new(ids, starts, columns, schema, edge_row)?;
900    let Quantifier { min, max } = search.quantifier;
901    let restricted = search.mode != Mode::Walk;
902    let pruned = !restricted
903        || (matches!(
904            search.selector,
905            Selector::Shortest(1) | Selector::AllShortest
906        ) && min <= 1
907            && !(search.mode == Mode::Trail && search.direction == Direction::Any));
908    // At most `k` prefixes per state: memory bounded by the nodes, and at
909    // most `k` paths per node from one start.
910    let bounded = pruned && matches!(search.selector, Selector::Shortest(_));
911    let kept_limit = match (bounded, max_paths, search.selector) {
912        (true, Some(cap), Selector::Shortest(k)) => {
913            Some(cap.max(topology.n_nodes().saturating_mul(k as usize)))
914        }
915        _ => None,
916    };
917    let mut walker = Walker {
918        topology,
919        search,
920        restricted,
921        pruned,
922        states: States::new(topology.n_nodes(), min),
923        entries: Vec::new(),
924        next: Vec::new(),
925        total: 0,
926        cap: max_paths,
927        bounded,
928        expanded: 0,
929        slots: goals.as_ref().map(|g| &g.slots),
930        reach: Reach::default(),
931    };
932    // Per last node, for a search that lists every path: (paths kept, length of the first).
933    let mut targets: HashMap<u32, (u32, u32)> = HashMap::new();
934    // Per target slot, for this start: (paths kept, length of the first).
935    let mut found: Vec<(u32, u32)> = vec![(0, 0); goals.as_ref().map_or(0, |g| g.slots.len())];
936    let mut touched: Vec<u32> = Vec::new();
937    let (mut nodes, mut edges) = (Vec::new(), Vec::new());
938    for (row, start) in dense.iter().enumerate() {
939        if starts.is_null(row) {
940            continue;
941        }
942        let Some(start) = *start else {
943            // A node with no edges: only the path of no edges.
944            let ends_at_a_target = match &goals {
945                None => true,
946                Some(g) => g
947                    .unknown
948                    .contains(&ScalarValue::try_from_array(starts.as_ref(), row)?),
949            };
950            if min == 0 && !known_only && ends_at_a_target {
951                rows.push(row as u32, &[row as u32], &[])?;
952            }
953            continue;
954        };
955        let row = row as u32;
956        if goals.as_ref().is_some_and(|g| g.slots.is_empty()) {
957            continue; // no target is a node: no path ends at one
958        }
959        for slot in touched.drain(..) {
960            found[slot as usize] = (0, 0);
961        }
962        walker.reach.reset(found.len());
963        // Targets not yet done, and (ALL SHORTEST) the length past which
964        // none has another path once every one is found.
965        let mut remaining = found.len();
966        let mut longest = 0u32;
967        let mut stop_after: Option<u32> = None;
968        walker.states.clear();
969        targets.clear();
970        walker.entries.clear();
971        walker.entries.push(Entry {
972            node: start,
973            parent: ROOT,
974            edge: 0,
975            len: 0,
976        });
977        *walker.states.get(start, 0) = (1, 0);
978        let mut head = 0;
979        'search: while head < walker.entries.len() {
980            let at = head as u32;
981            let entry = walker.entries[head];
982            head += 1;
983            if stop_after.is_some_and(|len| entry.len > len) {
984                break;
985            }
986            let c = entry.len.min(min);
987            // The target slot of the entry's node, when the search has targets;
988            // with targets, a node that is none of them ends no path.
989            //
990            // Two plain values rather than one `Option<Option<u32>>`: rustc
991            // 1.97 at `opt-level` "s" and "z" (the browser engine's build)
992            // matched `Some(Some(_))` on a `None` here, and indexed `found`
993            // out of bounds. The browser parity test runs GRAPH_TABLE at "z".
994            let (slot, ends_here) = match &goals {
995                None => (None, true),
996                Some(g) => {
997                    let slot = g.slots.get(&entry.node).copied();
998                    (slot, slot.is_some())
999                }
1000            };
1001            if c == min && ends_here {
1002                let keep = if pruned {
1003                    true
1004                } else {
1005                    let t = targets.entry(entry.node).or_insert((0, entry.len));
1006                    let keep = match search.selector {
1007                        Selector::All => true,
1008                        Selector::Shortest(k) => t.0 < k,
1009                        Selector::AllShortest => t.1 == entry.len,
1010                    };
1011                    if keep {
1012                        t.0 += 1;
1013                    }
1014                    keep
1015                };
1016                // ACYCLIC: a path back to its start is a cycle.
1017                let closed = search.mode == Mode::Acyclic && entry.len > 0 && entry.node == start;
1018                if keep && !closed {
1019                    nodes.clear();
1020                    edges.clear();
1021                    let mut i = at;
1022                    while i != ROOT {
1023                        let e = walker.entries[i as usize];
1024                        nodes.push(rows.dense(e.node));
1025                        if e.parent != ROOT {
1026                            edges.push(e.edge);
1027                        }
1028                        i = e.parent;
1029                    }
1030                    nodes.reverse();
1031                    edges.reverse();
1032                    rows.push(row, &nodes, &edges)?;
1033                    walker.total += 1;
1034                    if let Some(limit) = kept_limit.filter(|&l| walker.total > l) {
1035                        return Err(too_many_paths(limit, search, true));
1036                    }
1037                    if let Some(slot) = slot {
1038                        let f = &mut found[slot as usize];
1039                        if f.0 == 0 {
1040                            touched.push(slot);
1041                            f.1 = entry.len;
1042                        }
1043                        f.0 += 1;
1044                        let done = match search.selector {
1045                            Selector::All => false,
1046                            Selector::Shortest(k) => f.0 == k,
1047                            Selector::AllShortest => f.0 == 1,
1048                        };
1049                        if done {
1050                            remaining -= 1;
1051                            longest = longest.max(f.1);
1052                            if remaining == 0 {
1053                                match search.selector {
1054                                    Selector::AllShortest => stop_after = Some(longest),
1055                                    _ => break 'search,
1056                                }
1057                            }
1058                        }
1059                    }
1060                }
1061            }
1062            if max.is_some_and(|max| entry.len >= max) {
1063                continue;
1064            }
1065            if pruned && goals.is_some() && !walker.reach.extends(entry.len, search.selector) {
1066                continue; // every target has its paths among those pushed
1067            }
1068            walker.extend(at, start)?;
1069        }
1070    }
1071    rows.flush()?;
1072    Ok((rows.batches, walker.expanded))
1073}
1074
1075#[cfg(test)]
1076mod tests {
1077    use datafusion::arrow::array::{AsArray, Int64Array};
1078    use datafusion::arrow::datatypes::Int64Type;
1079
1080    use super::*;
1081
1082    /// The index of edges `(src, dst)`, in row order.
1083    fn index(edges: &[(i64, i64)]) -> (Topology, IdMap) {
1084        let src: ArrayRef = Arc::new(Int64Array::from(
1085            edges.iter().map(|e| e.0).collect::<Vec<_>>(),
1086        ));
1087        let dst: ArrayRef = Arc::new(Int64Array::from(
1088            edges.iter().map(|e| e.1).collect::<Vec<_>>(),
1089        ));
1090        let mut interner = ursa_core::EdgeInterner::with_capacity(edges.len());
1091        interner.push(src.as_ref(), dst.as_ref()).unwrap();
1092        let (ids, s, d) = interner.finish();
1093        (Topology::build(ids.len(), s, d), ids)
1094    }
1095
1096    fn search(
1097        direction: Direction,
1098        min: u32,
1099        max: Option<u32>,
1100        selector: Selector,
1101        mode: Mode,
1102    ) -> Search {
1103        Search {
1104            direction,
1105            quantifier: Quantifier { min, max },
1106            selector,
1107            mode,
1108        }
1109    }
1110
1111    /// Each path as (vertices, edges).
1112    /// A path: its vertices and its edges.
1113    type Path = (Vec<i64>, Vec<i64>);
1114
1115    fn paths(edges: &[(i64, i64)], starts: &[i64], s: Search) -> Vec<Path> {
1116        targeted(edges, starts, None, s).0
1117    }
1118
1119    /// Each path as (vertices, edges), searched toward `targets`, and how
1120    /// many prefixes the search extended.
1121    fn targeted(
1122        edges: &[(i64, i64)],
1123        starts: &[i64],
1124        targets: Option<&[i64]>,
1125        s: Search,
1126    ) -> (Vec<Path>, usize) {
1127        let (topology, ids) = index(edges);
1128        let targets: Option<ArrayRef> =
1129            targets.map(|t| Arc::new(Int64Array::from(t.to_vec())) as ArrayRef);
1130        let columns = PathColumns {
1131            vertices: true,
1132            edges: true,
1133            elements: true,
1134        };
1135        let schema = Arc::new(super::schema(&DataType::Int64, columns));
1136        let starts: ArrayRef = Arc::new(Int64Array::from(starts.to_vec()));
1137        let (batches, expanded) = run(
1138            &topology,
1139            &ids,
1140            &|e| u64::from(e),
1141            &s,
1142            &starts,
1143            targets.as_ref(),
1144            false,
1145            columns,
1146            schema,
1147            Some(MAX_PATHS),
1148        )
1149        .unwrap();
1150        let mut out = Vec::new();
1151        for b in batches {
1152            let v = b.column(3).as_list::<i32>();
1153            let e = b.column(4).as_list::<i32>();
1154            let el = b.column(5).as_list::<i32>();
1155            for r in 0..b.num_rows() {
1156                let vs: Vec<i64> = v.value(r).as_primitive::<Int64Type>().values().to_vec();
1157                let es: Vec<i64> = e.value(r).as_primitive::<Int64Type>().values().to_vec();
1158                let els: Vec<i64> = el.value(r).as_primitive::<Int64Type>().values().to_vec();
1159                assert_eq!(els.len(), vs.len() + es.len());
1160                assert_eq!(
1161                    b.column(2).as_primitive::<Int64Type>().value(r),
1162                    es.len() as i64
1163                );
1164                out.push((vs, es));
1165            }
1166        }
1167        (out, expanded)
1168    }
1169
1170    /// A search toward targets keeps the paths a search without them finds
1171    /// to those targets, in the same order, extending fewer prefixes.
1172    #[test]
1173    fn targets_keep_the_same_paths_and_stop_early() {
1174        // A chain 0 → 1 → … → 9 with a fan out of every node, and shortcuts.
1175        let mut edges: Vec<(i64, i64)> = (0..9).map(|i| (i, i + 1)).collect();
1176        for i in 0..10 {
1177            edges.extend((0..4).map(|j| (i, 100 + 10 * i + j)));
1178        }
1179        edges.extend([(0, 5), (2, 7), (5, 5), (7, 2), (3, 1)]);
1180        let graphs: [&[(i64, i64)]; 2] = [KNOW, &edges];
1181        let mut stopped_early = false;
1182        for edges in graphs {
1183            for direction in [Direction::Right, Direction::Left, Direction::Any] {
1184                for selector in [
1185                    Selector::All,
1186                    Selector::Shortest(1),
1187                    Selector::Shortest(2),
1188                    Selector::AllShortest,
1189                ] {
1190                    for mode in [Mode::Walk, Mode::Trail, Mode::Simple, Mode::Acyclic] {
1191                        for (min, max) in [(0, Some(3)), (1, None), (2, Some(4)), (1, Some(1))] {
1192                            if selector == Selector::All && mode == Mode::Walk && max.is_none() {
1193                                continue;
1194                            }
1195                            let s = search(direction, min, max, selector, mode);
1196                            for (starts, targets) in [
1197                                (&[0][..], &[3][..]),
1198                                (&[0, 4], &[0, 3, 9]),
1199                                (&[1, 2], &[2, 77]),
1200                                (&[3], &[7, 5, 1]),
1201                            ] {
1202                                let (all, n_all) = targeted(edges, starts, None, s);
1203                                let kept: Vec<_> = all
1204                                    .into_iter()
1205                                    .filter(|(v, _)| targets.contains(v.last().unwrap()))
1206                                    .collect();
1207                                let (found, n) = targeted(edges, starts, Some(targets), s);
1208                                assert_eq!(found, kept, "{s} from {starts:?} to {targets:?}");
1209                                assert!(n <= n_all, "{s}");
1210                                stopped_early |= n < n_all;
1211                            }
1212                        }
1213                    }
1214                }
1215            }
1216        }
1217        assert!(stopped_early);
1218    }
1219
1220    // DuckPGQ's test graph: Daniel 0, Tavneet 1, Gabor 2, Peter 3, David 4.
1221    const KNOW: &[(i64, i64)] = &[
1222        (0, 1),
1223        (0, 2),
1224        (0, 3),
1225        (3, 0),
1226        (1, 2),
1227        (1, 3),
1228        (2, 3),
1229        (4, 3),
1230    ];
1231
1232    #[test]
1233    fn any_shortest_takes_the_first_edges_and_can_return_to_the_start() {
1234        let found = paths(
1235            KNOW,
1236            &[4],
1237            search(
1238                Direction::Right,
1239                1,
1240                Some(3),
1241                Selector::Shortest(1),
1242                Mode::Walk,
1243            ),
1244        );
1245        assert_eq!(
1246            found,
1247            vec![
1248                (vec![4, 3], vec![7]),
1249                (vec![4, 3, 0], vec![7, 3]),
1250                (vec![4, 3, 0, 1], vec![7, 3, 0]),
1251                (vec![4, 3, 0, 2], vec![7, 3, 1]),
1252            ]
1253        );
1254        // From 0, a shortest walk of one edge or more back to 0 is 0→3→0.
1255        let found = paths(
1256            KNOW,
1257            &[0],
1258            search(
1259                Direction::Right,
1260                1,
1261                Some(3),
1262                Selector::Shortest(1),
1263                Mode::Walk,
1264            ),
1265        );
1266        assert!(found.contains(&(vec![0, 3, 0], vec![2, 3])));
1267        // ACYCLIC drops it.
1268        let found = paths(
1269            KNOW,
1270            &[0],
1271            search(
1272                Direction::Right,
1273                1,
1274                Some(3),
1275                Selector::Shortest(1),
1276                Mode::Acyclic,
1277            ),
1278        );
1279        assert!(found.iter().all(|(v, _)| v.last() != Some(&0)));
1280    }
1281
1282    #[test]
1283    fn walks_trails_and_counts() {
1284        // Every walk of 1 or 2 edges from Peter: 3→0, then 0→1, 0→2, 0→3.
1285        let found = paths(
1286            KNOW,
1287            &[3],
1288            search(Direction::Right, 1, Some(2), Selector::All, Mode::Walk),
1289        );
1290        assert_eq!(found.len(), 4);
1291        // Without a bound under ACYCLIC: every simple path, finitely many.
1292        let acyclic = paths(
1293            KNOW,
1294            &[3],
1295            search(Direction::Right, 1, None, Selector::All, Mode::Acyclic),
1296        );
1297        assert!(acyclic.iter().all(|(v, _)| {
1298            let mut s = v.clone();
1299            s.sort();
1300            s.dedup();
1301            s.len() == v.len()
1302        }));
1303        // 3→0, 3→0→1, 3→0→2 and 3→0→1→2.
1304        assert_eq!(acyclic.len(), 4);
1305        // SHORTEST 2 from 0 to 3: 0→3 (edge 2), then 0→1→3 (0, 5) before 0→2→3 (1, 6).
1306        let found = paths(
1307            KNOW,
1308            &[0],
1309            search(Direction::Right, 1, None, Selector::Shortest(2), Mode::Walk),
1310        );
1311        let to3: Vec<_> = found.iter().filter(|(v, _)| v.last() == Some(&3)).collect();
1312        assert_eq!(
1313            to3,
1314            vec![&(vec![0, 3], vec![2]), &(vec![0, 1, 3], vec![0, 5])]
1315        );
1316        // ALL SHORTEST from 0 to 3 is the one edge; to 2: 0→2 alone.
1317        let found = paths(
1318            KNOW,
1319            &[1],
1320            search(Direction::Right, 1, None, Selector::AllShortest, Mode::Walk),
1321        );
1322        let to0: Vec<_> = found.iter().filter(|(v, _)| v.last() == Some(&0)).collect();
1323        assert_eq!(to0, vec![&(vec![1, 3, 0], vec![5, 3])]);
1324        let found = paths(
1325            KNOW,
1326            &[4],
1327            search(
1328                Direction::Right,
1329                3,
1330                Some(3),
1331                Selector::AllShortest,
1332                Mode::Walk,
1333            ),
1334        );
1335        let to2: Vec<_> = found.iter().filter(|(v, _)| v.last() == Some(&2)).collect();
1336        assert_eq!(to2, vec![&(vec![4, 3, 0, 2], vec![7, 3, 1])]);
1337    }
1338
1339    #[test]
1340    fn zero_length_undirected_and_trails() {
1341        // A start with no edges has its path of no edges.
1342        let found = paths(
1343            KNOW,
1344            &[9, 0],
1345            search(Direction::Right, 0, Some(0), Selector::All, Mode::Walk),
1346        );
1347        assert_eq!(found, vec![(vec![9], vec![]), (vec![0], vec![])]);
1348        // Undirected, a self-loop is followed once.
1349        let found = paths(
1350            &[(1, 1), (1, 2)],
1351            &[1],
1352            search(Direction::Any, 1, Some(1), Selector::All, Mode::Walk),
1353        );
1354        assert_eq!(found, vec![(vec![1, 1], vec![0]), (vec![1, 2], vec![1])]);
1355        // An undirected trail back to the start cannot reuse its edge: 1-2-1
1356        // takes the two parallel edges.
1357        let found = paths(
1358            &[(1, 2), (2, 1)],
1359            &[1],
1360            search(Direction::Any, 1, Some(2), Selector::All, Mode::Trail),
1361        );
1362        assert_eq!(
1363            found,
1364            vec![
1365                (vec![1, 2], vec![0]),
1366                (vec![1, 2], vec![1]),
1367                (vec![1, 2, 1], vec![0, 1]),
1368                (vec![1, 2, 1], vec![1, 0]),
1369            ]
1370        );
1371        // Left: against the edges.
1372        let found = paths(
1373            KNOW,
1374            &[3],
1375            search(Direction::Left, 1, Some(1), Selector::All, Mode::Walk),
1376        );
1377        assert_eq!(
1378            found,
1379            vec![
1380                (vec![3, 0], vec![2]),
1381                (vec![3, 1], vec![5]),
1382                (vec![3, 2], vec![6]),
1383                (vec![3, 4], vec![7])
1384            ]
1385        );
1386        // SIMPLE: back to the start is allowed, once.
1387        let found = paths(
1388            KNOW,
1389            &[0],
1390            search(Direction::Right, 2, Some(2), Selector::All, Mode::Simple),
1391        );
1392        assert!(found.contains(&(vec![0, 3, 0], vec![2, 3])));
1393    }
1394}