Skip to main content

ursa_engine/graph/
traversal.rs

1//! The traversals in SQL: `hop`, `shortest_path`, `random_walk` and
2//! `induced_edges`.
3//!
4//! A traversal returns rows of its own (reached pairs, path edges, walk
5//! steps), not one row per node, and some of its parameters are sets of node
6//! ids rather than literals. So the traversals are not in
7//! `ursa_core::catalog`, whose specs, [`ursa_core::catalog::Call`]s and
8//! [`ursa_core::catalog::Evaluator`] describe per-node columns and one-row
9//! statistics; they are specified here, with the same names, defaults, checks
10//! and output columns as the Python library's `ur.hop(edges, n,
11//! direction).from_(seeds)`, `ur.shortest_path(edges, source, target, weight,
12//! direction)` and `ur.random_walk(edges, start, steps, walks_per_node,
13//! seed)` (`python/ursa/_graph.py`, `ursa-plan`'s `result.rs`), with SQL's
14//! own names where #415 gave every role one name ([`PYTHON_NAMES`]): SQL's
15//! `steps` and `seeds` are Python's `n` and `start`, SQL's `random_seed` is
16//! `random_walk`'s `seed`, and SQL's `id` and `step` columns are
17//! `random_walk`'s `node` and `shortest_path`'s `hop`. The parity fixture
18//! records the Python signatures and outputs, and `tests/parity.rs` holds
19//! these specs to them through that table.
20//!
21//! The literal parameters use the catalog's [`ParamType`]s and are checked by
22//! the catalog's rules (a count is a non-negative integer below 2^32, a seed a
23//! non-negative integer or NULL, a direction one of the listed names). The
24//! node-id parameters are planned by the relation planner as child plans of
25//! the traversal node (see `relation`), and their values are cast to the
26//! graph's id type: literals as they are planned, a subquery's values when
27//! the node runs ([`not_node_ids`] words the error for both).
28//!
29//! The kernels are `ursa_core::algo`'s, called exactly as `ursa-plan` calls
30//! them, so the rows are the Python library's, in the same order. One
31//! deliberate difference: SQL's `hop` names its columns `(seed, id,
32//! distance)`, where Python's `EdgeFrame` has `(src, dst)` and no distance
33//! (#328); the parity test compares `seed` and `id` with `src` and `dst`.
34//!
35//! A literal node id that names no node of the graph is an error (#416):
36//! `hop(seeds =>): 99 is not a node of graph 'pg'`. Ids from a subquery are
37//! the data's, so one that is not a node is skipped, and a notice says how
38//! many were ([`TraversalSpec::strict_ids`]; `induced_edges`, whose node set
39//! may name anything, skips them always).
40//!
41//! `induced_edges` (#432) is SQL's own: the Python library has no function
42//! for the edges among a node set ([`TraversalSpec::python`] is false), so
43//! the parity test leaves it out and `tests/traversals.rs` holds it to the
44//! join it stands for.
45
46use std::sync::Arc;
47
48use datafusion::arrow::array::{Array, ArrayRef, AsArray, Float64Array, Int64Array};
49use datafusion::arrow::compute::cast;
50use datafusion::arrow::datatypes::{DataType, Field, Schema};
51use datafusion::arrow::record_batch::RecordBatch;
52use datafusion::error::{DataFusionError, Result};
53use ursa_core::algo::{
54    induced_edges, k_hop_distances_masked, random_walk_masked, shortest_path_masked,
55    shortest_path_weighted_with_cost_masked,
56};
57use ursa_core::catalog::{
58    direction_name, parse_direction, Expected, ParamType, Value, ALL_DIRECTIONS,
59};
60use ursa_core::{Direction, IdMap, Topology};
61
62use super::functions::{
63    direction_arg, expected_text, plan, sql_value, takes, unknown_param_text, Given, Literal,
64};
65use super::provenance;
66
67/// What a traversal parameter takes.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum TraversalParamType {
70    /// Node ids: a list literal (`[0, 1]`), a scalar subquery returning one
71    /// column (`(SELECT id FROM ...)`), or one id.
72    Nodes,
73    /// One node id: a literal or a scalar subquery returning at most one row.
74    Node,
75    /// A literal or a weight expression, as a catalog function's parameter.
76    Param(ParamType),
77}
78
79/// One parameter of a traversal, besides the graph.
80#[derive(Debug, Clone, Copy)]
81pub struct TraversalParam {
82    pub name: &'static str,
83    pub ty: TraversalParamType,
84    /// The value when the argument is not given; `None` if it must be given.
85    pub default: Option<Value>,
86    /// One line on what it does.
87    pub doc: &'static str,
88}
89
90impl TraversalParam {
91    /// Whether the parameter is a node id or a set of them.
92    pub fn takes_nodes(&self) -> bool {
93        matches!(
94            self.ty,
95            TraversalParamType::Nodes | TraversalParamType::Node
96        )
97    }
98
99    /// Whether the parameter can take an argument shaped `given`: node ids
100    /// are a list (for several), a query, an id or an expression.
101    pub fn takes(&self, given: Given) -> bool {
102        match self.ty {
103            TraversalParamType::Nodes => given != Given::Number && given != Given::Boolean,
104            TraversalParamType::Node => {
105                !matches!(given, Given::Number | Given::Boolean | Given::List)
106            }
107            TraversalParamType::Param(ty) => takes(self.name, ty, given),
108        }
109    }
110
111    /// Whether the parameter is the weight expression.
112    pub fn is_weight(&self) -> bool {
113        self.ty == TraversalParamType::Param(ParamType::Weight)
114    }
115
116    /// The parameter as a signature shows it: its default, or a placeholder
117    /// for a required one.
118    pub fn shown_default(&self) -> String {
119        match (self.default, self.ty) {
120            (Some(v), _) => sql_value(&v),
121            (None, TraversalParamType::Nodes) => "[<id>, ...]".to_string(),
122            (None, TraversalParamType::Node) => "<id>".to_string(),
123            (None, TraversalParamType::Param(_)) => "<integer>".to_string(),
124        }
125    }
126}
127
128/// The type of a traversal's output column.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum OutputType {
131    /// A node id, of the graph's id type (`Int64` or `Utf8`).
132    Id,
133    Int64,
134    Float64,
135}
136
137impl OutputType {
138    pub fn data_type(&self, id_type: &DataType) -> DataType {
139        match self {
140            OutputType::Id => id_type.clone(),
141            OutputType::Int64 => DataType::Int64,
142            OutputType::Float64 => DataType::Float64,
143        }
144    }
145}
146
147/// One output column of a traversal. None is nullable.
148#[derive(Debug, Clone, Copy)]
149pub struct TraversalOutput {
150    pub name: &'static str,
151    pub ty: OutputType,
152    /// What the column is, as its field's `ursa.role` says (see
153    /// [`super::provenance`]); `None` for a column with no role.
154    pub role: Option<&'static str>,
155}
156
157/// One traversal.
158#[derive(Debug)]
159pub struct TraversalSpec {
160    pub name: &'static str,
161    /// One line on what it returns.
162    pub summary: &'static str,
163    /// The NetworkX call it matches, as `docs/semantics.md` pins it.
164    pub networkx: Option<&'static str>,
165    /// The parameters besides the graph, in SQL's order: the node ids first.
166    pub params: &'static [TraversalParam],
167    pub outputs: &'static [TraversalOutput],
168    /// Whether the Python library has the traversal, with the same
169    /// parameters and rows: the parity test holds those to it.
170    pub python: bool,
171    /// Whether a literal node id that is not a node of the graph is an error
172    /// (#416). Ids from a subquery are skipped either way, with a notice.
173    pub strict_ids: bool,
174}
175
176/// The names SQL gives a traversal's parameters and columns where the Python
177/// library's differ (#415): `(function, SQL name, Python name)`.
178pub const PYTHON_NAMES: &[(&str, &str, &str)] = &[
179    ("hop", "steps", "n"),
180    ("random_walk", "seeds", "start"),
181    ("random_walk", "random_seed", "seed"),
182    ("random_walk", "id", "node"),
183    ("shortest_path", "step", "hop"),
184];
185
186impl TraversalSpec {
187    /// The parameter called `name`.
188    pub fn param(&self, name: &str) -> Option<&'static TraversalParam> {
189        let params: &'static [TraversalParam] = self.params;
190        params.iter().find(|p| p.name == name)
191    }
192
193    /// The parameters that take node ids, in order: each is one child plan of
194    /// the traversal node.
195    pub fn node_params(&self) -> impl Iterator<Item = &'static TraversalParam> {
196        let params: &'static [TraversalParam] = self.params;
197        params.iter().filter(|p| p.takes_nodes())
198    }
199
200    /// The directions the traversal accepts; empty for one without a
201    /// `direction` parameter.
202    pub fn directions(&self) -> &'static [&'static str] {
203        self.params
204            .iter()
205            .find_map(|p| match p.ty {
206                TraversalParamType::Param(ParamType::Direction(d)) => Some(d),
207                _ => None,
208            })
209            .unwrap_or(&[])
210    }
211
212    /// Whether the traversal takes a `weight`.
213    pub fn weighted(&self) -> bool {
214        self.params.iter().any(TraversalParam::is_weight)
215    }
216
217    /// The output schema over `graph`, whose node ids are `id_type` and
218    /// whose nodes are the keys of the vertex table `vertices` (its element
219    /// name), if it has one, and whose edges are the edge table `edges`.
220    /// Each field says what it is ([`super::provenance`]): a node key
221    /// carries the vertex table as its label, an edge row the edge table.
222    pub fn schema(
223        &self,
224        graph: &str,
225        vertices: Option<&str>,
226        edges: &str,
227        id_type: &DataType,
228    ) -> Schema {
229        Schema::new(
230            self.outputs
231                .iter()
232                .map(|o| {
233                    let field = Field::new(o.name, o.ty.data_type(id_type), false);
234                    let label = match (o.ty, o.role) {
235                        (OutputType::Id, _) => vertices,
236                        (_, Some(provenance::ROLE_EDGE)) => Some(edges),
237                        _ => None,
238                    };
239                    match o.role {
240                        Some(role) => provenance::field(field, role, graph, label),
241                        None => field,
242                    }
243                })
244                .collect::<Vec<_>>(),
245        )
246    }
247
248    /// `hop(<graph>, seeds => [<id>, ...], steps => 1, direction => 'out')`: the
249    /// call with every parameter at its default, for messages.
250    pub fn signature(&self) -> String {
251        let mut parts = vec!["<graph>".to_string()];
252        parts.extend(
253            self.params
254                .iter()
255                .map(|p| format!("{} => {}", p.name, p.shown_default())),
256        );
257        format!("{}({})", self.name, parts.join(", "))
258    }
259}
260
261const fn param(
262    name: &'static str,
263    ty: TraversalParamType,
264    default: Option<Value>,
265    doc: &'static str,
266) -> TraversalParam {
267    TraversalParam {
268        name,
269        ty,
270        default,
271        doc,
272    }
273}
274
275const fn out(name: &'static str, ty: OutputType, role: Option<&'static str>) -> TraversalOutput {
276    TraversalOutput { name, ty, role }
277}
278
279const DIRECTION: TraversalParam = param(
280    "direction",
281    TraversalParamType::Param(ParamType::Direction(ALL_DIRECTIONS)),
282    Some(Value::Str("out")),
283    "Follow out-edges, in-edges, or both (the undirected view).",
284);
285
286/// Every traversal, in the Python API's order.
287pub static TRAVERSALS: &[TraversalSpec] = &[
288    TraversalSpec {
289        name: "hop",
290        summary: "The nodes within steps of each seed: one (seed, id, distance) row per seed \
291                  and node reached, distance the fewest steps from the seed to it. A seed is not \
292                  its own row; a repeated seed repeats its rows. The rows come in no particular \
293                  order; use ORDER BY for one.",
294        networkx: Some(
295            "nx.single_source_shortest_path_length(G, seed, cutoff=steps), the seed left out \
296             (in: on G.reverse(); both: on U)",
297        ),
298        params: &[
299            param(
300                "seeds",
301                TraversalParamType::Nodes,
302                None,
303                "The nodes to start from: a list, a query of one column, or one id.",
304            ),
305            param(
306                "steps",
307                TraversalParamType::Param(ParamType::Count),
308                Some(Value::UInt(1)),
309                "How many steps to take.",
310            ),
311            DIRECTION,
312        ],
313        outputs: &[
314            out("seed", OutputType::Id, Some(provenance::ROLE_SEED)),
315            out("id", OutputType::Id, Some(provenance::ROLE_NODE)),
316            out(
317                "distance",
318                OutputType::Int64,
319                Some(provenance::ROLE_DISTANCE),
320            ),
321        ],
322        python: true,
323        strict_ids: true,
324    },
325    TraversalSpec {
326        name: "shortest_path",
327        summary: "One shortest path from source to target: one row per edge, in order, with its \
328                  0-based position (step) and the cost from source to its end. No path, no \
329                  rows; nor when source is target, as a path of no edges has no edge rows (to \
330                  ask whether a path exists, use GRAPH_TABLE and path_length(p)).",
331        networkx: Some(
332            "nx.shortest_path(G, source, target) (weighted: nx.dijkstra_path(G, source, target, \
333             weight=...))",
334        ),
335        params: &[
336            param(
337                "source",
338                TraversalParamType::Node,
339                None,
340                "The node the path starts at: an id, or a query of one value.",
341            ),
342            param(
343                "target",
344                TraversalParamType::Node,
345                None,
346                "The node the path ends at: an id, or a query of one value.",
347            ),
348            param(
349                "weight",
350                TraversalParamType::Param(ParamType::Weight),
351                Some(Value::Null),
352                "A non-negative weight per edge for the least-cost path; null is the fewest \
353                 edges.",
354            ),
355            DIRECTION,
356        ],
357        outputs: &[
358            out("src", OutputType::Id, Some(provenance::ROLE_SRC)),
359            out("dst", OutputType::Id, Some(provenance::ROLE_DST)),
360            out("step", OutputType::Int64, Some(provenance::ROLE_STEP)),
361            out("cost", OutputType::Float64, None),
362        ],
363        python: true,
364        strict_ids: true,
365    },
366    TraversalSpec {
367        name: "random_walk",
368        summary: "Random walks along out-edges from each seed: one (walk_id, step, id) row per \
369                  step. A walk stops early at a node with no out-edges.",
370        networkx: None,
371        params: &[
372            param(
373                "seeds",
374                TraversalParamType::Nodes,
375                None,
376                "The nodes to start walks at: a list, a query of one column, or one id.",
377            ),
378            param(
379                "steps",
380                TraversalParamType::Param(ParamType::Count),
381                None,
382                "How many steps each walk takes at most.",
383            ),
384            param(
385                "walks_per_node",
386                TraversalParamType::Param(ParamType::Count),
387                Some(Value::UInt(1)),
388                "How many walks start at each seed.",
389            ),
390            param(
391                "random_seed",
392                TraversalParamType::Param(ParamType::Seed),
393                Some(Value::Null),
394                "Seed for the deterministic random stream; null is a fixed default.",
395            ),
396        ],
397        outputs: &[
398            out("walk_id", OutputType::Int64, Some(provenance::ROLE_WALK)),
399            out("step", OutputType::Int64, Some(provenance::ROLE_STEP)),
400            out("id", OutputType::Id, Some(provenance::ROLE_NODE)),
401        ],
402        python: true,
403        strict_ids: true,
404    },
405    TraversalSpec {
406        name: "induced_edges",
407        summary: "The graph's edges whose two ends are both in nodes: one (src, dst, edge) row \
408                  per edge, in the direction the graph stores it, edge its row in the edge \
409                  table. Read from the index, in time proportional to the nodes' degrees. \
410                  Parallel edges are separate rows; rows are ordered by edge.",
411        networkx: Some("G.subgraph(nodes).edges()"),
412        params: &[param(
413            "nodes",
414            TraversalParamType::Nodes,
415            None,
416            "The nodes whose edges to return: a list, a query of one column, or one id.",
417        )],
418        outputs: &[
419            out("src", OutputType::Id, Some(provenance::ROLE_SRC)),
420            out("dst", OutputType::Id, Some(provenance::ROLE_DST)),
421            out("edge", OutputType::Int64, Some(provenance::ROLE_EDGE)),
422        ],
423        python: false,
424        strict_ids: false,
425    },
426];
427
428/// The traversal called `name`.
429pub fn lookup(name: &str) -> Option<&'static TraversalSpec> {
430    TRAVERSALS.iter().find(|t| t.name == name)
431}
432
433/// A validated traversal call: which traversal, with every literal parameter
434/// set. Its node ids and weight are the node's child plans.
435#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
436pub enum Traversal {
437    Hop {
438        steps: u32,
439        direction: Direction,
440    },
441    ShortestPath {
442        direction: Direction,
443    },
444    RandomWalk {
445        steps: u32,
446        walks_per_node: u32,
447        random_seed: Option<u64>,
448    },
449    InducedEdges,
450}
451
452impl Traversal {
453    pub fn spec(&self) -> &'static TraversalSpec {
454        let name = match self {
455            Traversal::Hop { .. } => "hop",
456            Traversal::ShortestPath { .. } => "shortest_path",
457            Traversal::RandomWalk { .. } => "random_walk",
458            Traversal::InducedEdges => "induced_edges",
459        };
460        lookup(name).expect("every traversal has a spec")
461    }
462
463    pub fn name(&self) -> &'static str {
464        self.spec().name
465    }
466
467    /// The literal parameter `name`'s value.
468    fn value(&self, name: &str) -> Option<Value> {
469        let seed = |s: Option<u64>| s.map_or(Value::Null, Value::UInt);
470        Some(match (self, name) {
471            (Traversal::Hop { steps, .. }, "steps")
472            | (Traversal::RandomWalk { steps, .. }, "steps") => Value::UInt(u64::from(*steps)),
473            (Traversal::Hop { direction, .. }, "direction")
474            | (Traversal::ShortestPath { direction }, "direction") => {
475                Value::Str(direction_name(*direction))
476            }
477            (Traversal::RandomWalk { walks_per_node, .. }, "walks_per_node") => {
478                Value::UInt(u64::from(*walks_per_node))
479            }
480            (Traversal::RandomWalk { random_seed, .. }, "random_seed") => seed(*random_seed),
481            _ => return None,
482        })
483    }
484
485    /// The call as SQL would spell it, for `EXPLAIN`: the node arguments and
486    /// the weight as written, then every literal parameter.
487    pub fn display(&self, nodes: &[String], weight: Option<&str>) -> String {
488        let mut nodes = nodes.iter();
489        let parts: Vec<String> = self
490            .spec()
491            .params
492            .iter()
493            .filter_map(|p| {
494                if p.takes_nodes() {
495                    return nodes.next().map(|n| format!("{} => {n}", p.name));
496                }
497                if p.is_weight() {
498                    return weight.map(|w| format!("{} => {w}", p.name));
499                }
500                self.value(p.name)
501                    .map(|v| format!("{} => {}", p.name, sql_value(&v)))
502            })
503            .collect();
504        format!("{}({})", self.name(), parts.join(", "))
505    }
506}
507
508/// "hop() has no parameter 'n'; did you mean 'steps'? ...": `given` is the
509/// argument's shape, if known, so the suggestion can take it (#415).
510pub fn unknown_param(spec: &TraversalSpec, name: &str, given: Option<Given>) -> DataFusionError {
511    let takers: Vec<Box<dyn Fn(Given) -> bool>> = spec
512        .params
513        .iter()
514        .map(|p| Box::new(move |g| p.takes(g)) as Box<dyn Fn(Given) -> bool>)
515        .collect();
516    let entries: Vec<(&str, &dyn Fn(Given) -> bool)> = spec
517        .params
518        .iter()
519        .zip(&takers)
520        .map(|(p, t)| (p.name, t.as_ref()))
521        .collect();
522    plan(unknown_param_text(spec.name, name, given, &entries))
523}
524
525/// "random_walk() needs 'steps': random_walk(<graph>, ...)".
526pub fn missing_param(spec: &TraversalSpec, param: &TraversalParam) -> DataFusionError {
527    plan(format!(
528        "{}() needs '{}': {}",
529        spec.name,
530        param.name,
531        spec.signature()
532    ))
533}
534
535/// "hop(seeds =>) must be node ids of graph 'karate', which are integers; got
536/// 'a'": a node-id argument that is not of the graph's id type and does not
537/// cast to it. `got` is the offending value as SQL writes it, or its type.
538pub fn not_node_ids(
539    function: &str,
540    param: &TraversalParam,
541    graph: &str,
542    id_type: &DataType,
543    got: &str,
544) -> String {
545    let (integer, string) = match param.ty {
546        TraversalParamType::Node => (
547            "a node id of graph '{graph}', which is an integer",
548            "a node id of graph '{graph}', which is a string",
549        ),
550        _ => (
551            "node ids of graph '{graph}', which are integers",
552            "node ids of graph '{graph}', which are strings",
553        ),
554    };
555    let expected = match id_type {
556        DataType::Int64 => integer,
557        _ => string,
558    }
559    .replace("{graph}", graph);
560    format!(
561        "{function}({} =>) must be {expected}; got {got}",
562        param.name
563    )
564}
565
566/// Whether values of type `from` may be node ids of a graph whose ids have
567/// type `id_type` (#271).
568///
569/// A node id is an integer or a string, whatever the graph's id type: on a
570/// graph with integer ids a string must then parse exactly as an integer
571/// (`'7'`, checked when the value is cast), and on a graph with string ids an
572/// integer becomes its decimal string, which loses nothing. Every other type
573/// is refused, even where Arrow would cast it: a float (`1.5`, or `2.0`), a
574/// boolean or a date as a seed is almost certainly a mistake, and casting it
575/// would quietly pick a node. NULL is accepted; it matches no node.
576pub fn is_node_id_type(from: &DataType, id_type: &DataType) -> bool {
577    debug_assert!(matches!(id_type, DataType::Int64 | DataType::Utf8));
578    match from {
579        DataType::Null | DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => true,
580        DataType::Dictionary(_, values) => is_node_id_type(values, id_type),
581        t => t.is_integer(),
582    }
583}
584
585/// Whether `text` is exactly an integer, as a string seed on a graph with
586/// integer ids must be (#271): digits, after an optional sign. Arrow's cast
587/// also takes surrounding whitespace (`' 1'`); a seed does not.
588pub fn is_integer_text(text: &str) -> bool {
589    let digits = text.strip_prefix(['-', '+']).unwrap_or(text);
590    !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
591}
592
593/// The row of the first value in `values` that the node-id rule (#271)
594/// refuses before any cast: any non-null value of a type node ids may not
595/// have, or a string that is not exactly an integer on a graph with integer
596/// ids. `None` when every value passes (it may still fail the cast: an integer
597/// string out of range).
598pub fn first_refused_node_id(values: &ArrayRef, id_type: &DataType) -> Option<usize> {
599    let valid = |i: &usize| values.is_valid(*i);
600    if !is_node_id_type(values.data_type(), id_type) {
601        return (0..values.len()).find(valid);
602    }
603    if id_type != &DataType::Int64 || values.data_type().is_integer() {
604        return None;
605    }
606    let text = cast(values, &DataType::Utf8).ok()?;
607    let text = text.as_string::<i32>();
608    (0..text.len()).find(|i| valid(i) && !is_integer_text(text.value(*i)))
609}
610
611/// Check one literal against a parameter, by the catalog's rules.
612fn check(spec: &TraversalSpec, name: &str, ty: ParamType, literal: &Literal) -> Result<Value> {
613    let expected = |want: Expected| {
614        plan(format!(
615            "{}({name} =>) must be {}; got {literal}",
616            spec.name,
617            expected_text(want)
618        ))
619    };
620    let int = || match literal {
621        Literal::Number(n) => n.parse::<i128>().ok(),
622        _ => None,
623    };
624    match ty {
625        ParamType::Count => match int() {
626            Some(i) if (0..=i128::from(u32::MAX)).contains(&i) => Ok(Value::UInt(i as u64)),
627            _ => Err(expected(Expected::Count)),
628        },
629        ParamType::Seed => match (literal, int()) {
630            (Literal::Null, _) => Ok(Value::Null),
631            (_, Some(i)) if (0..=i128::from(u64::MAX)).contains(&i) => Ok(Value::UInt(i as u64)),
632            _ => Err(expected(Expected::Seed)),
633        },
634        ParamType::Direction(choices) => match literal {
635            Literal::String(s) => {
636                // In any case (#415).
637                let s = direction_arg(spec.name, name, s)?;
638                match choices.iter().find(|c| **c == s.as_str()) {
639                    Some(c) => Ok(Value::Str(c)),
640                    None => {
641                        let options: Vec<String> =
642                            choices.iter().map(|o| format!("'{o}'")).collect();
643                        Err(plan(format!(
644                            "{}({name} => {literal}) is not supported; use one of {}",
645                            spec.name,
646                            options.join(", ")
647                        )))
648                    }
649                }
650            }
651            _ => {
652                let options: Vec<String> = choices.iter().map(|o| format!("'{o}'")).collect();
653                Err(plan(format!(
654                    "{}({name} => {literal}) is not supported; use one of {}",
655                    spec.name,
656                    options.join(", ")
657                )))
658            }
659        },
660        other => Err(DataFusionError::Internal(format!(
661            "{}({name}): no check for a parameter of type {other:?}",
662            spec.name
663        ))),
664    }
665}
666
667/// Resolve a traversal's literal arguments (names normalized and known, none
668/// repeated; node ids and the weight already taken out by the caller) to a
669/// [`Traversal`].
670pub fn resolve(spec: &'static TraversalSpec, literals: &[(String, Literal)]) -> Result<Traversal> {
671    let mut values: Vec<(&'static str, Value)> = Vec::new();
672    for p in spec.params {
673        let TraversalParamType::Param(ty) = p.ty else {
674            continue;
675        };
676        if ty == ParamType::Weight {
677            continue;
678        }
679        let value = match literals.iter().find(|(n, _)| n == p.name) {
680            Some((_, literal)) => check(spec, p.name, ty, literal)?,
681            None => p.default.ok_or_else(|| missing_param(spec, p))?,
682        };
683        values.push((p.name, value));
684    }
685    let get = |name: &str| {
686        values
687            .iter()
688            .find(|(n, _)| *n == name)
689            .map(|(_, v)| *v)
690            .expect("every literal parameter has a value")
691    };
692    let count = |name: &str| match get(name) {
693        Value::UInt(u) => u as u32,
694        other => unreachable!("a count is checked: {other:?}"),
695    };
696    let seed = |name: &str| match get(name) {
697        Value::UInt(u) => Some(u),
698        _ => None,
699    };
700    let direction = |name: &str| match get(name) {
701        Value::Str(s) => parse_direction(s).expect("a direction is checked"),
702        other => unreachable!("a direction is checked: {other:?}"),
703    };
704    Ok(match spec.name {
705        "hop" => Traversal::Hop {
706            steps: count("steps"),
707            direction: direction("direction"),
708        },
709        "shortest_path" => Traversal::ShortestPath {
710            direction: direction("direction"),
711        },
712        "random_walk" => Traversal::RandomWalk {
713            steps: count("steps"),
714            walks_per_node: count("walks_per_node"),
715            random_seed: seed("random_seed"),
716        },
717        "induced_edges" => Traversal::InducedEdges,
718        other => unreachable!("no traversal {other}"),
719    })
720}
721
722/// Run `traversal` over a graph. `nodes` holds, per node parameter in order,
723/// its ids as dense indexes (`None` for an id not in the graph or a null);
724/// `weights` is one `f64` per edge row for a weighted shortest path;
725/// `edge_row` gives the edge table's row of an edge of the index (see
726/// `GraphIndex::edge_row`).
727pub fn batch(
728    topology: &Topology,
729    ids: &IdMap,
730    traversal: &Traversal,
731    nodes: &[Vec<Option<u32>>],
732    weights: Option<&[f64]>,
733    edge_row: &dyn Fn(u32) -> u64,
734    schema: Arc<Schema>,
735) -> Result<RecordBatch> {
736    // An id not in the graph reaches nothing (#225), as in ursa-plan.
737    let known = |i: usize| -> Vec<u32> { nodes[i].iter().flatten().copied().collect() };
738    let columns: Vec<ArrayRef> = match *traversal {
739        Traversal::Hop { steps, direction } => {
740            let (seed, reached, distance) =
741                k_hop_distances_masked(topology, None, &known(0), steps, direction);
742            let distance: Vec<i64> = distance.into_iter().map(i64::from).collect();
743            vec![
744                ids.gather_user(&seed),
745                ids.gather_user(&reached),
746                Arc::new(Int64Array::from(distance)),
747            ]
748        }
749        Traversal::ShortestPath { direction } => {
750            let one = |i: usize| nodes[i].first().copied().flatten();
751            let route = match (one(0), one(1)) {
752                (Some(source), Some(target)) => match weights {
753                    Some(w) => shortest_path_weighted_with_cost_masked(
754                        topology, None, w, source, target, direction,
755                    )
756                    .map(|(path, costs)| (path, Some(costs))),
757                    None => shortest_path_masked(topology, None, source, target, direction)
758                        .map(|path| (path, None)),
759                },
760                _ => None,
761            };
762            let (mut src, mut dst, mut step, mut cost) = (vec![], vec![], vec![], vec![]);
763            if let Some((path, costs)) = route {
764                for (i, pair) in path.windows(2).enumerate() {
765                    src.push(pair[0]);
766                    dst.push(pair[1]);
767                    step.push(i as i64);
768                    // The cost to this edge's end: the settled distance when
769                    // weighted, the edge count otherwise.
770                    cost.push(match &costs {
771                        Some(c) => c[i + 1],
772                        None => (i + 1) as f64,
773                    });
774                }
775            }
776            vec![
777                ids.gather_user(&src),
778                ids.gather_user(&dst),
779                Arc::new(Int64Array::from(step)),
780                Arc::new(Float64Array::from(cost)),
781            ]
782        }
783        Traversal::RandomWalk {
784            steps,
785            walks_per_node,
786            random_seed,
787        } => {
788            let walks = random_walk_masked(
789                topology,
790                None,
791                &known(0),
792                steps,
793                walks_per_node,
794                random_seed,
795            );
796            vec![
797                Arc::new(Int64Array::from(walks.walk_id)),
798                Arc::new(Int64Array::from(walks.step)),
799                ids.gather_user(&walks.node),
800            ]
801        }
802        Traversal::InducedEdges => {
803            // An id not in the graph is on no edge (#225), as for `hop`.
804            let edges = induced_edges(topology, &known(0));
805            let rows: Vec<i64> = edges.edge.iter().map(|&e| edge_row(e) as i64).collect();
806            vec![
807                ids.gather_user(&edges.src),
808                ids.gather_user(&edges.dst),
809                Arc::new(Int64Array::from(rows)),
810            ]
811        }
812    };
813    RecordBatch::try_new(schema, columns)
814        .map_err(|e| DataFusionError::ArrowError(Box::new(e), None))
815}
816
817#[cfg(test)]
818mod tests {
819    use super::*;
820
821    #[test]
822    fn node_id_rule() {
823        for ok in ["0", "7", "-3", "+12", "9223372036854775808"] {
824            assert!(is_integer_text(ok), "{ok}");
825        }
826        for refused in ["", "-", "1.5", "2.0", " 1", "1 ", "1e3", "0x10", "one"] {
827            assert!(!is_integer_text(refused), "{refused}");
828        }
829        for id_type in [DataType::Int64, DataType::Utf8] {
830            for ok in [
831                DataType::Null,
832                DataType::Int8,
833                DataType::UInt64,
834                DataType::Utf8View,
835            ] {
836                assert!(is_node_id_type(&ok, &id_type), "{ok}");
837            }
838            for refused in [DataType::Float64, DataType::Boolean, DataType::Date32] {
839                assert!(!is_node_id_type(&refused, &id_type), "{refused}");
840            }
841        }
842        let strings: ArrayRef = Arc::new(datafusion::arrow::array::StringArray::from(vec![
843            Some("1"),
844            None,
845            Some("2.0"),
846        ]));
847        assert_eq!(first_refused_node_id(&strings, &DataType::Int64), Some(2));
848        assert_eq!(first_refused_node_id(&strings, &DataType::Utf8), None);
849        let floats: ArrayRef = Arc::new(Float64Array::from(vec![None, Some(1.0)]));
850        assert_eq!(first_refused_node_id(&floats, &DataType::Int64), Some(1));
851    }
852
853    fn call(name: &str, args: &[(&str, Literal)]) -> Result<Traversal> {
854        let args: Vec<(String, Literal)> = args
855            .iter()
856            .map(|(n, v)| (n.to_string(), v.clone()))
857            .collect();
858        resolve(lookup(name).unwrap(), &args)
859    }
860
861    fn num(n: &str) -> Literal {
862        Literal::Number(n.into())
863    }
864
865    fn message(r: Result<Traversal>) -> String {
866        crate::user_message(&r.unwrap_err())
867    }
868
869    #[test]
870    fn defaults_match_python() {
871        assert_eq!(
872            call("hop", &[]).unwrap(),
873            Traversal::Hop {
874                steps: 1,
875                direction: Direction::Out
876            }
877        );
878        assert_eq!(
879            call("shortest_path", &[]).unwrap(),
880            Traversal::ShortestPath {
881                direction: Direction::Out
882            }
883        );
884        assert_eq!(
885            call("random_walk", &[("steps", num("4"))]).unwrap(),
886            Traversal::RandomWalk {
887                steps: 4,
888                walks_per_node: 1,
889                random_seed: None
890            }
891        );
892    }
893
894    #[test]
895    fn explains_bad_arguments() {
896        assert_eq!(
897            message(call("hop", &[("steps", num("-1"))])),
898            "hop(steps =>) must be a non-negative integer below 2^32; got -1"
899        );
900        assert_eq!(
901            message(call("hop", &[("steps", num("1.5"))])),
902            "hop(steps =>) must be a non-negative integer below 2^32; got 1.5"
903        );
904        assert_eq!(
905            message(call("hop", &[("direction", Literal::String("up".into()))])),
906            "hop(direction => 'up') is not supported; use one of 'out', 'in', 'both'"
907        );
908        assert_eq!(
909            message(call("random_walk", &[])),
910            "random_walk() needs 'steps': random_walk(<graph>, seeds => [<id>, ...], steps => \
911             <integer>, walks_per_node => 1, random_seed => NULL)"
912        );
913        assert_eq!(
914            message(call(
915                "random_walk",
916                &[
917                    ("steps", num("2")),
918                    ("random_seed", Literal::String("x".into()))
919                ]
920            )),
921            "random_walk(random_seed =>) must be a non-negative integer or NULL; got 'x'"
922        );
923        assert_eq!(
924            message(call(
925                "hop",
926                &[("direction", Literal::String("UNDIRECTED".into()))]
927            )),
928            "hop(direction => 'UNDIRECTED') is not supported; use 'both', which reads every \
929             edge both ways (the undirected view)"
930        );
931        assert_eq!(
932            call("hop", &[("direction", Literal::String("Both".into()))]).unwrap(),
933            Traversal::Hop {
934                steps: 1,
935                direction: Direction::Both
936            }
937        );
938    }
939
940    /// #415: the names others use point to Ursa's, and a suggestion can take
941    /// the value given.
942    #[test]
943    fn suggests_the_name_to_use() {
944        let hint = |function: &str, name: &str, given: Given| {
945            crate::user_message(&unknown_param(lookup(function).unwrap(), name, Some(given)))
946        };
947        for (function, name, given, want) in [
948            ("hop", "n", Given::Integer, "steps"),
949            ("hop", "max_hops", Given::Integer, "steps"),
950            ("hop", "depth", Given::Integer, "steps"),
951            ("hop", "k", Given::Integer, "steps"),
952            ("hop", "start", Given::List, "seeds"),
953            ("hop", "stepz", Given::Integer, "steps"),
954            ("random_walk", "start", Given::List, "seeds"),
955            ("random_walk", "n", Given::Integer, "steps"),
956            ("random_walk", "seed", Given::Integer, "random_seed"),
957            // A list is node ids, never a random seed (the near miss #415
958            // found).
959            ("random_walk", "seed", Given::List, "seeds"),
960            ("random_walk", "sed", Given::List, "seeds"),
961            ("shortest_path", "src", Given::Integer, "source"),
962            ("shortest_path", "dst", Given::Integer, "target"),
963        ] {
964            let message = hint(function, name, given);
965            assert!(
966                message.contains(&format!("did you mean '{want}'?")),
967                "{function}({name}): {message}"
968            );
969        }
970        assert_eq!(
971            hint("hop", "n", Given::Integer),
972            "hop() has no parameter 'n'; did you mean 'steps'? Its parameters are: seeds, \
973             steps, direction"
974        );
975        // Nothing that can take a string is close to 'steps'.
976        assert_eq!(
977            hint("random_walk", "stepz", Given::String),
978            "random_walk() has no parameter 'stepz'. Its parameters are: seeds, steps, \
979             walks_per_node, random_seed"
980        );
981    }
982
983    /// Every SQL name that differs from the Python library's is listed, so
984    /// the parity test can map it.
985    #[test]
986    fn python_names_are_sql_names() {
987        for (function, sql, _) in PYTHON_NAMES {
988            let spec = lookup(function).unwrap();
989            assert!(
990                spec.param(sql).is_some() || spec.outputs.iter().any(|o| o.name == *sql),
991                "{function} has no {sql}"
992            );
993        }
994    }
995
996    #[test]
997    fn signatures_show_defaults() {
998        assert_eq!(
999            lookup("hop").unwrap().signature(),
1000            "hop(<graph>, seeds => [<id>, ...], steps => 1, direction => 'out')"
1001        );
1002        assert_eq!(
1003            lookup("shortest_path").unwrap().signature(),
1004            "shortest_path(<graph>, source => <id>, target => <id>, weight => NULL, direction \
1005             => 'out')"
1006        );
1007    }
1008
1009    #[test]
1010    fn explain_spells_the_call() {
1011        let hop = call("hop", &[("steps", num("2"))]).unwrap();
1012        assert_eq!(
1013            hop.display(&["[0]".into()], None),
1014            "hop(seeds => [0], steps => 2, direction => 'out')"
1015        );
1016        let path = call("shortest_path", &[]).unwrap();
1017        assert_eq!(
1018            path.display(&["0".into(), "33".into()], Some("weight")),
1019            "shortest_path(source => 0, target => 33, weight => weight, direction => 'out')"
1020        );
1021    }
1022}