Skip to main content

ursa_engine/graph/
exec.rs

1//! Executing a graph node.
2//!
3//! [`GraphPlanner`] maps a [`GraphAlgorithmNode`] to a [`GraphAlgorithmExec`]
4//! whose children are the planned edge plans. When it executes, it looks up
5//! the index in the session's [`IndexCache`]; on a miss it reads a child,
6//! its partitions decoded in parallel and handed on in partition order, and
7//! builds the index as the rows arrive. Then it runs the calls and emits one
8//! batch.
9//!
10//! Row order matters to the index: dense node ids are given in first-seen
11//! order. The build of a graph of 65,536 edges or more then renumbers the
12//! nodes by in-degree for locality (#172, `ursa_core::NodeOrder::InDegree`),
13//! keeping each node's first-seen id: component labels, the seeded community kernels and sampled sources
14//! are defined on those, and the order floating-point sums run in follows
15//! both. The child's partitions are read in order, the node asks for no
16//! repartitioning of its input, and the session turns off file-scan work
17//! stealing, so a file's edges arrive in the file's own order on any thread
18//! count, as `ursa-io` reads them for the Python library.
19//!
20//! ## A vertex table
21//!
22//! A graph with a vertex table has its keys as its nodes (#311). Its node has
23//! one more child, the keys ([`GraphAlgorithmNode::vertices`]), which the
24//! build reads first: each key takes the next dense id, in the table's order,
25//! so a node on no edge is a node all the same. The edges are read after,
26//! and an edge whose source or destination is not a key is dropped, as an
27//! inner join of the edges with the vertex table drops it (DuckPGQ's CSR is
28//! built that way). The index counts them ([`GraphIndex::n_dropped`]), for
29//! `describe`, and keeps which rows it kept, so weights read row by row line
30//! up with the kept edges and a path's edges are still the edge table's rows.
31//! The keys' plan is part of the index's cache key: its fingerprint, and the
32//! identity of the files it reads, so a changed vertex table builds afresh.
33//!
34//! ## Weights
35//!
36//! Weights are looked up by edge row, so they must be in the order of the
37//! rows the index was built from. A weighted node reads only its weighted
38//! child (the endpoints and every weight expression, in one pass, evaluating
39//! the weights a batch at a time as it goes), and:
40//!
41//! - on an index-cache miss, builds the index from those same rows, so the
42//!   weights line up by construction;
43//! - on a hit, checks that the rows' endpoints are the index's, row for row
44//!   (an edge plan over a join need not produce its rows in the same order
45//!   twice). If they are not, it reads the child again and builds a private
46//!   index from those rows rather than mis-assign a weight.
47//!
48//! Each distinct weight expression is evaluated once per node, cast to
49//! `Float64`, and checked as `ursa-plan` checks weights (no nulls, no negative
50//! values, with the same messages). Weights that line up with a cached index
51//! are stored on it, keyed by the weighted plan's fingerprint and file
52//! identities, so the next query with the same weights reads no edges at all.
53//! In a database, they are stored with the index on disk too, so a weighted
54//! query over a stored index in a later process reads no edges either.
55
56use std::fmt;
57use std::sync::{Arc, Mutex};
58
59use async_trait::async_trait;
60use datafusion::arrow::array::{new_empty_array, Array, ArrayRef, BooleanArray, Float64Array};
61use datafusion::arrow::buffer::BooleanBuffer;
62use datafusion::arrow::compute::SortOptions;
63use datafusion::arrow::compute::{cast, cast_with_options, concat, CastOptions};
64use datafusion::arrow::compute::{filter, filter_record_batch};
65use datafusion::arrow::datatypes::{DataType, SchemaRef};
66use datafusion::arrow::record_batch::RecordBatch;
67use datafusion::catalog::Session;
68use datafusion::common::config::ConfigOptions;
69use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
70use datafusion::common::ScalarValue;
71use datafusion::datasource::physical_plan::FileScanConfig;
72use datafusion::datasource::source::DataSourceExec;
73use datafusion::error::{DataFusionError, Result};
74use datafusion::execution::context::QueryPlanner;
75use datafusion::execution::TaskContext;
76use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
77use datafusion::logical_expr::{Expr, LogicalPlan, UserDefinedLogicalNode};
78use datafusion::physical_expr::expressions::Column;
79use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
80use datafusion::physical_expr::{LexOrdering, PhysicalSortExpr};
81use datafusion::physical_optimizer::PhysicalOptimizerRule;
82use datafusion::physical_plan::aggregates::AggregateExec;
83use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
84use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
85use datafusion::physical_plan::filter::FilterExec;
86use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricBuilder, MetricsSet};
87use datafusion::physical_plan::repartition::RepartitionExec;
88use datafusion::physical_plan::replace_children_if_necessary;
89use datafusion::physical_plan::sorts::sort::SortExec;
90use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
91use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
92use datafusion::physical_plan::union::{InterleaveExec, UnionExec};
93use datafusion::physical_plan::{
94    DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, Partitioning,
95    PlanProperties, SendableRecordBatchStream, StatisticsArgs, StatisticsContext,
96};
97use datafusion::physical_planner::{DefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner};
98use futures::{FutureExt, TryStreamExt};
99use ursa_core::{EdgeInterner, IdError, IdMap, NodeOrder, RowSource, Topology};
100
101use super::in_order::{read_ahead, InOrder};
102use super::index::{
103    file_identities, fingerprint, portable_in, BuildInfo, BuildSize, FileIdentity, GraphIndex,
104    IndexCache, IndexHeld, Weights,
105};
106use super::kernels;
107use super::node::{
108    weight_column, GraphAlgorithmNode, GraphTraversalNode, Output, WEIGHTED_DESTINATION,
109    WEIGHTED_SOURCE,
110};
111use super::path_search::{self, PathColumns, PathSearchNode, Search};
112use super::schema_metadata::{SchemaMetadataExec, SchemaMetadataNode};
113use super::traversal::{self, Traversal, TraversalParam, TraversalParamType};
114use crate::notices::{NoticeLevel, Notifier};
115
116/// Plans Ursa's graph nodes.
117#[derive(Debug)]
118pub struct GraphPlanner;
119
120#[async_trait]
121impl ExtensionPlanner for GraphPlanner {
122    async fn plan_extension(
123        &self,
124        _planner: &dyn PhysicalPlanner,
125        node: &dyn UserDefinedLogicalNode,
126        logical_inputs: &[&LogicalPlan],
127        physical_inputs: &[Arc<dyn ExecutionPlan>],
128        session_state: &dyn Session,
129        _planning_ctx: &PhysicalPlanningContext,
130    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
131        let unique = |graph: &str, source: &Expr, destination: &Expr| {
132            key_names(session_state, graph, source, destination)
133        };
134        if let Some(node) = node.as_any().downcast_ref::<SchemaMetadataNode>() {
135            return Ok(Some(Arc::new(SchemaMetadataExec::try_new(
136                Arc::clone(&physical_inputs[0]),
137                Arc::new(node.schema().as_arrow().clone()),
138            )?)));
139        }
140        if let Some(node) = node.as_any().downcast_ref::<GraphTraversalNode>() {
141            let unique = unique(&node.graph, &node.source, &node.destination);
142            return plan_traversal(node, logical_inputs, physical_inputs, unique).map(Some);
143        }
144        if let Some(node) = node.as_any().downcast_ref::<PathSearchNode>() {
145            let unique = unique(&node.graph, &node.source, &node.destination);
146            let mut exec = plan_path_search(node, logical_inputs, physical_inputs, unique)?;
147            exec.held = held_index(&exec.shape.edges, &exec.input, session_state).await;
148            return Ok(Some(Arc::new(exec)));
149        }
150        let Some(node) = node.as_any().downcast_ref::<GraphAlgorithmNode>() else {
151            return Ok(None);
152        };
153        let (source, destination) = node.endpoint_indices()?;
154        let mut next = 1;
155        let weighted = match (
156            &node.weighted,
157            logical_inputs.get(next),
158            physical_inputs.get(next),
159        ) {
160            (Some(_), Some(logical), Some(physical)) => {
161                next += 1;
162                Some(weighted_input(logical, physical, node.weights.len())?)
163            }
164            _ => None,
165        };
166        let vertices = vertex_input(
167            node.vertices.is_some(),
168            logical_inputs,
169            physical_inputs,
170            next,
171            unique(&node.graph, &node.source, &node.destination),
172        )?;
173        // A neighbour aggregation's node values are the last input.
174        let values = node
175            .values
176            .as_ref()
177            .and_then(|_| physical_inputs.last().cloned());
178        Ok(Some(Arc::new(GraphAlgorithmExec::new(
179            Shape {
180                edges: Edges {
181                    graph: node.graph.clone(),
182                    endpoints: (source, destination),
183                    id_type: node.id_type.clone(),
184                    fingerprint: fingerprint(logical_inputs[0]),
185                    vertices,
186                },
187                outputs: node.outputs.clone(),
188                per_node: node.per_node,
189                display: node.display_outputs(),
190                schema: Arc::new(node.schema().as_arrow().clone()),
191            },
192            Arc::clone(&physical_inputs[0]),
193            weighted,
194            values,
195        ))))
196    }
197}
198
199/// The vertex table whose keys are the nodes of `graph`'s edges from
200/// `source` to `destination` (the endpoint columns of a graph node), when
201/// they are one vertex table's: its keys must then identify one row each
202/// (#411). `None` for the keys of two vertex tables (a `GRAPH_TABLE` search
203/// over an edge table between two of them), which may share values.
204fn key_names(
205    session: &dyn Session,
206    graph: &str,
207    source: &Expr,
208    destination: &Expr,
209) -> Option<KeyNames> {
210    let graph = session
211        .config()
212        .get_extension::<super::GraphRegistry>()?
213        .get(graph)?;
214    let (Expr::Column(source), Expr::Column(destination)) = (source, destination) else {
215        return None;
216    };
217    let table = source.relation.as_ref()?;
218    let edges = graph.edge_tables.iter().find(|e| {
219        &e.table == table && e.source == source.name && e.destination == destination.name
220    })?;
221    let from = graph.endpoint_vertex(edges, true)?;
222    let to = graph.endpoint_vertex(edges, false)?;
223    (from.name == to.name).then(|| KeyNames {
224        table: from.name.clone(),
225        key: from.key.clone(),
226    })
227}
228
229/// The vertex keys input at `at`, if the node has one; `unique` as
230/// [`VertexInput::unique`].
231fn vertex_input(
232    has: bool,
233    logical_inputs: &[&LogicalPlan],
234    physical_inputs: &[Arc<dyn ExecutionPlan>],
235    at: usize,
236    unique: Option<KeyNames>,
237) -> Result<Option<VertexInput>> {
238    if !has {
239        return Ok(None);
240    }
241    match (logical_inputs.get(at), physical_inputs.get(at)) {
242        (Some(logical), Some(physical)) => Ok(Some(VertexInput {
243            plan: Arc::clone(physical),
244            fingerprint: fingerprint(logical),
245            unique,
246        })),
247        _ => Err(DataFusionError::Internal(
248            "a graph node's vertex keys were not planned".to_string(),
249        )),
250    }
251}
252
253/// The weighted edge plan `physical` (planned from `logical`), with
254/// `n_weights` weight columns.
255fn weighted_input(
256    logical: &LogicalPlan,
257    physical: &Arc<dyn ExecutionPlan>,
258    n_weights: usize,
259) -> Result<WeightedInput> {
260    let schema = logical.schema();
261    let column = |name: &str| schema.index_of_column_by_name(None, name);
262    let missing =
263        |name: &str| DataFusionError::Internal(format!("the weighted edge plan has no {name}"));
264    let weights = (0..n_weights)
265        .map(|i| {
266            let name = weight_column(i);
267            column(&name).ok_or_else(|| missing(&name))
268        })
269        .collect::<Result<Vec<_>>>()?;
270    Ok(WeightedInput {
271        plan: Arc::clone(physical),
272        source: column(WEIGHTED_SOURCE).ok_or_else(|| missing(WEIGHTED_SOURCE))?,
273        destination: column(WEIGHTED_DESTINATION).ok_or_else(|| missing(WEIGHTED_DESTINATION))?,
274        weights,
275        fingerprint: fingerprint(logical),
276    })
277}
278
279/// The exec of a traversal node.
280fn plan_traversal(
281    node: &GraphTraversalNode,
282    logical_inputs: &[&LogicalPlan],
283    physical_inputs: &[Arc<dyn ExecutionPlan>],
284    unique: Option<KeyNames>,
285) -> Result<Arc<dyn ExecutionPlan>> {
286    let expected = 1
287        + usize::from(node.weighted.is_some())
288        + usize::from(node.vertices.is_some())
289        + node.nodes.len();
290    if logical_inputs.len() != expected || physical_inputs.len() != expected {
291        return Err(DataFusionError::Internal(format!(
292            "GraphTraversal has {expected} inputs; planned {}",
293            physical_inputs.len()
294        )));
295    }
296    let (source, destination) = node.endpoint_indices()?;
297    let mut next = 1;
298    let weighted = match node.weighted {
299        Some(_) => {
300            next += 1;
301            Some(weighted_input(logical_inputs[1], &physical_inputs[1], 1)?)
302        }
303        None => None,
304    };
305    let vertices = vertex_input(
306        node.vertices.is_some(),
307        logical_inputs,
308        physical_inputs,
309        next,
310        unique,
311    )?;
312    next += usize::from(vertices.is_some());
313    Ok(Arc::new(GraphTraversalExec::new(
314        TraversalShape {
315            edges: Edges {
316                graph: node.graph.clone(),
317                endpoints: (source, destination),
318                id_type: node.id_type.clone(),
319                fingerprint: fingerprint(logical_inputs[0]),
320                vertices,
321            },
322            traversal: node.traversal,
323            from_query: node.from_query.clone(),
324            display: node.display_call(),
325            schema: Arc::new(node.schema().as_arrow().clone()),
326        },
327        Arc::clone(&physical_inputs[0]),
328        weighted,
329        physical_inputs[next..].to_vec(),
330    )))
331}
332
333/// Where the session keeps the index of the edges `input` reads, if it
334/// does: then running the node reads none of its edge or vertex inputs.
335async fn held_index(
336    shape: &Edges,
337    input: &Arc<dyn ExecutionPlan>,
338    session: &dyn Session,
339) -> Option<IndexHeld> {
340    let context = session.task_ctx();
341    let cache = context.session_config().get_extension::<IndexCache>()?;
342    let key = index_key(shape, input, &context).await.ok()??;
343    cache.holds(context.session_config(), &key)
344}
345
346fn plan_path_search(
347    node: &PathSearchNode,
348    logical_inputs: &[&LogicalPlan],
349    physical_inputs: &[Arc<dyn ExecutionPlan>],
350    unique: Option<KeyNames>,
351) -> Result<PathSearchExec> {
352    let expected = 2 + usize::from(node.vertices.is_some()) + usize::from(node.targets.is_some());
353    if physical_inputs.len() != expected || logical_inputs.len() != expected {
354        return Err(DataFusionError::Internal(format!(
355            "PathSearch has {expected} inputs; planned {}",
356            physical_inputs.len()
357        )));
358    }
359    let vertices = vertex_input(
360        node.vertices.is_some(),
361        logical_inputs,
362        physical_inputs,
363        1,
364        unique,
365    )?;
366    let starts = 1 + usize::from(vertices.is_some());
367    Ok(PathSearchExec::new(
368        PathShape {
369            edges: Edges {
370                graph: node.graph.clone(),
371                endpoints: node.endpoint_indices()?,
372                id_type: node.id_type.clone(),
373                fingerprint: fingerprint(logical_inputs[0]),
374                vertices,
375            },
376            search: node.search,
377            columns: node.columns,
378            known_only: node.known_only,
379            schema: Arc::new(node.schema().as_arrow().clone()),
380        },
381        Arc::clone(&physical_inputs[0]),
382        Arc::clone(&physical_inputs[starts]),
383        node.targets
384            .as_ref()
385            .map(|_| Arc::clone(&physical_inputs[starts + 1])),
386    ))
387}
388
389#[derive(Debug, Clone)]
390struct PathShape {
391    edges: Edges,
392    search: Search,
393    columns: PathColumns,
394    known_only: bool,
395    schema: SchemaRef,
396}
397
398/// Builds or fetches a graph index from its first child's edge rows, reads
399/// the start nodes its next child produces (and the targets its last, if it
400/// has them), and searches paths from them (see [`super::path_search`]).
401/// `EXPLAIN ANALYZE` shows how many path prefixes it extended (`expanded`).
402/// When the session held the index as the node was planned, `EXPLAIN` says
403/// so (`index=stored, sources: 2 files, not read`, #351): once the plan is
404/// optimized, its edge and vertex inputs, which do not run, are no longer
405/// its children, so `EXPLAIN` does not draw them (#384, N48). They are kept,
406/// optimized, to build the index from should the session no longer hold it
407/// when the node runs.
408#[derive(Debug)]
409pub struct PathSearchExec {
410    shape: PathShape,
411    input: Arc<dyn ExecutionPlan>,
412    starts: Arc<dyn ExecutionPlan>,
413    targets: Option<Arc<dyn ExecutionPlan>>,
414    /// Where the session kept the index when the node was planned.
415    held: Option<IndexHeld>,
416    /// Whether the edge and vertex inputs are left out of the children: set
417    /// by [`CollapseHeldInputs`] when the index is `held`.
418    collapsed: bool,
419    properties: Arc<PlanProperties>,
420    metrics: ExecutionPlanMetricsSet,
421}
422
423impl PathSearchExec {
424    fn new(
425        shape: PathShape,
426        input: Arc<dyn ExecutionPlan>,
427        starts: Arc<dyn ExecutionPlan>,
428        targets: Option<Arc<dyn ExecutionPlan>>,
429    ) -> Self {
430        let properties = Arc::new(PlanProperties::new(
431            EquivalenceProperties::new(Arc::clone(&shape.schema)),
432            Partitioning::UnknownPartitioning(1),
433            EmissionType::Final,
434            Boundedness::Bounded,
435        ));
436        Self {
437            shape,
438            input,
439            starts,
440            targets,
441            held: None,
442            collapsed: false,
443            properties,
444            metrics: ExecutionPlanMetricsSet::new(),
445        }
446    }
447
448    /// This node with its edge and vertex inputs left out of its children.
449    fn collapse(&self) -> Self {
450        let mut exec = Self::new(
451            self.shape.clone(),
452            Arc::clone(&self.input),
453            Arc::clone(&self.starts),
454            self.targets.clone(),
455        );
456        exec.held = self.held;
457        exec.collapsed = true;
458        exec
459    }
460
461    /// What the index is built from, for `EXPLAIN`: `2 files`, `1 file and
462    /// 1 other source`.
463    fn sources(&self) -> String {
464        let mut files = Vec::new();
465        let mut others = 0usize;
466        let plans =
467            std::iter::once(&self.input).chain(self.shape.edges.vertices.as_ref().map(|v| &v.plan));
468        for plan in plans {
469            let _ =
470                plan.apply(|node| {
471                    match node
472                        .downcast_ref::<DataSourceExec>()
473                        .and_then(|exec| exec.data_source().downcast_ref::<FileScanConfig>())
474                    {
475                        Some(config) => files.extend(config.file_groups.iter().flat_map(|g| {
476                            g.files().iter().map(|f| f.object_meta.location.clone())
477                        })),
478                        None if node.children().is_empty() => others += 1,
479                        None => {}
480                    }
481                    Ok(TreeNodeRecursion::Continue)
482                });
483        }
484        files.sort();
485        files.dedup();
486        let plural = |n: usize, what: &str| format!("{n} {what}{}", if n == 1 { "" } else { "s" });
487        match (files.len(), others) {
488            (0, 0) => "none".to_string(),
489            (f, 0) => plural(f, "file"),
490            (0, o) => plural(o, "source"),
491            (f, o) => format!("{} and {}", plural(f, "file"), plural(o, "other source")),
492        }
493    }
494}
495
496impl DisplayAs for PathSearchExec {
497    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
498        write!(
499            f,
500            "PathSearchExec: graph={}, search={}{}",
501            self.shape.edges.graph,
502            self.shape.search,
503            if self.targets.is_some() {
504                ", targets"
505            } else {
506                ""
507            }
508        )?;
509        if let Some(held) = self.held {
510            write!(f, ", index={held}, sources: {}, not read", self.sources())?;
511        }
512        Ok(())
513    }
514}
515
516impl ExecutionPlan for PathSearchExec {
517    fn name(&self) -> &str {
518        "PathSearchExec"
519    }
520
521    fn properties(&self) -> &Arc<PlanProperties> {
522        &self.properties
523    }
524
525    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
526        let mut children = Vec::new();
527        if !self.collapsed {
528            children.push(&self.input);
529            children.extend(self.shape.edges.vertices.as_ref().map(|v| &v.plan));
530        }
531        children.push(&self.starts);
532        children.extend(self.targets.as_ref());
533        children
534    }
535
536    fn metrics(&self) -> Option<MetricsSet> {
537        Some(self.metrics.clone_inner())
538    }
539
540    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
541        vec![false; self.children().len()]
542    }
543
544    fn apply_expressions(
545        &self,
546        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
547    ) -> Result<TreeNodeRecursion> {
548        Ok(TreeNodeRecursion::Continue)
549    }
550
551    fn with_new_children(
552        self: Arc<Self>,
553        children: Vec<Arc<dyn ExecutionPlan>>,
554    ) -> Result<Arc<dyn ExecutionPlan>> {
555        let expected = self.children().len();
556        if children.len() != expected {
557            return Err(DataFusionError::Internal(format!(
558                "PathSearchExec has {expected} children; got {}",
559                children.len()
560            )));
561        }
562        let mut children = children.into_iter();
563        let mut shape = self.shape.clone();
564        let input = if self.collapsed {
565            Arc::clone(&self.input)
566        } else {
567            let input = children.next().expect("checked above");
568            shape.edges.vertices = shape.edges.vertices.map(|v| VertexInput {
569                plan: children.next().expect("checked above"),
570                ..v
571            });
572            input
573        };
574        let starts = children.next().expect("checked above");
575        let targets = self.targets.as_ref().and_then(|_| children.next());
576        let mut exec = Self::new(shape, input, starts, targets);
577        exec.held = self.held;
578        exec.collapsed = self.collapsed;
579        Ok(Arc::new(exec))
580    }
581
582    fn execute(
583        &self,
584        partition: usize,
585        context: Arc<TaskContext>,
586    ) -> Result<SendableRecordBatchStream> {
587        if partition != 0 {
588            return Err(DataFusionError::Internal(format!(
589                "PathSearchExec has one partition; asked for {partition}"
590            )));
591        }
592        let shape = self.shape.clone();
593        let input = Arc::clone(&self.input);
594        let starts = Arc::clone(&self.starts);
595        let targets = self.targets.clone();
596        let schema = Arc::clone(&shape.schema);
597        let expanded = MetricBuilder::new(&self.metrics).counter("expanded", partition);
598        let max_paths = crate::options::max_paths(context.session_config());
599        let notifier = crate::notices::Notifier::of(context.session_config());
600        let run = async move {
601            let index = unweighted_index(&shape.edges, input, &context).await?;
602            if let Some(notice) =
603                path_search::floor_notice(&shape.search, index.topology.n_nodes(), max_paths)
604            {
605                notifier.say(crate::notices::NoticeLevel::On, || notice);
606            }
607            let starts = search_keys(&starts, "start nodes", &shape, &context).await?;
608            let targets = match &targets {
609                Some(t) => Some(search_keys(t, "target nodes", &shape, &context).await?),
610                None => None,
611            };
612            let out_schema = Arc::clone(&shape.schema);
613            let (batches, n) = crate::run_blocking(move || {
614                path_search::run(
615                    &index.topology,
616                    &index.ids,
617                    &|e| index.edge_row(e),
618                    &shape.search,
619                    &starts,
620                    targets.as_ref(),
621                    shape.known_only,
622                    shape.columns,
623                    out_schema,
624                    max_paths,
625                )
626            })
627            .await
628            .map_err(|e| DataFusionError::Execution(format!("a path search failed: {e}")))??;
629            expanded.add(n);
630            Ok::<_, DataFusionError>(futures::stream::iter(batches.into_iter().map(Ok)))
631        };
632        Ok(Box::pin(RecordBatchStreamAdapter::new(
633            schema,
634            futures::stream::once(run).try_flatten(),
635        )))
636    }
637}
638
639/// The one column of keys `plan` gives (a search's `what`: its start or
640/// target nodes), cast to the graph's node id type.
641async fn search_keys(
642    plan: &Arc<dyn ExecutionPlan>,
643    what: &str,
644    shape: &PathShape,
645    context: &Arc<TaskContext>,
646) -> Result<ArrayRef> {
647    let batches = drain(plan, &[0], context).await?;
648    let id_type = &shape.edges.id_type;
649    let mut columns = Vec::with_capacity(batches.len());
650    for batch in &batches {
651        columns.push(cast(batch[0].as_ref(), id_type).map_err(|_| {
652            DataFusionError::Plan(format!(
653                "in GRAPH_TABLE: the {what}' keys ({}) cannot be read as graph '{}''s node ids ({id_type})",
654                batch[0].data_type(),
655                shape.edges.graph
656            ))
657        })?);
658    }
659    Ok(if columns.is_empty() {
660        new_empty_array(id_type)
661    } else {
662        let refs: Vec<&dyn Array> = columns.iter().map(|c| c.as_ref()).collect();
663        concat(&refs)?
664    })
665}
666
667/// A query planner whose physical planner knows Ursa's graph nodes.
668#[derive(Debug)]
669pub struct UrsaQueryPlanner;
670
671#[async_trait]
672impl QueryPlanner for UrsaQueryPlanner {
673    async fn create_physical_plan(
674        &self,
675        logical_plan: &LogicalPlan,
676        session_state: &dyn Session,
677    ) -> Result<Arc<dyn ExecutionPlan>> {
678        DefaultPhysicalPlanner::with_extension_planners(vec![Arc::new(GraphPlanner)])
679            .create_physical_plan(logical_plan, session_state)
680            .await
681    }
682}
683
684/// A graph node's edge input: where its endpoints are, and how its index is
685/// cached.
686#[derive(Debug, Clone)]
687struct Edges {
688    graph: String,
689    /// The source and destination columns of the first input.
690    endpoints: (usize, usize),
691    id_type: DataType,
692    /// The edge plan's fingerprint, or `None` if it cannot be cached.
693    fingerprint: Option<String>,
694    /// The graph's vertex keys, if it has a vertex table.
695    vertices: Option<VertexInput>,
696}
697
698/// A graph node's vertex keys: a plan of one column (see the module docs).
699#[derive(Debug, Clone)]
700struct VertexInput {
701    plan: Arc<dyn ExecutionPlan>,
702    /// The keys' plan's fingerprint, or `None` if it cannot be cached.
703    fingerprint: Option<String>,
704    /// The vertex table the keys are of, when they are one table's: a build
705    /// then refuses a key that repeats or is NULL (#411; see
706    /// [`super::vertex_keys`]).
707    unique: Option<KeyNames>,
708}
709
710/// A vertex table and its key, as a refusal of its keys names them.
711#[derive(Debug, Clone)]
712struct KeyNames {
713    table: String,
714    key: String,
715}
716
717/// The node set `interner` was given is fixed: refuse it if `unique` names
718/// its vertex table and a key repeats or is NULL.
719fn close_keys(
720    interner: &mut EdgeInterner,
721    unique: Option<&KeyNames>,
722    graph: &str,
723    id_type: &DataType,
724) -> Result<()> {
725    if let Some(names) = unique {
726        let rows = interner.key_rows();
727        if !rows.is_unique() {
728            return Err(super::vertex_keys::key_error(
729                graph,
730                &names.table,
731                &names.key,
732                rows,
733                *id_type == DataType::Utf8,
734            ));
735        }
736    }
737    interner.close_nodes();
738    Ok(())
739}
740
741/// What a [`GraphAlgorithmExec`] computes, besides its children.
742#[derive(Debug, Clone)]
743struct Shape {
744    edges: Edges,
745    outputs: Vec<Output>,
746    per_node: bool,
747    /// The outputs as `EXPLAIN` shows them.
748    display: String,
749    schema: SchemaRef,
750}
751
752/// The weighted edge plan, and where its columns are.
753#[derive(Debug, Clone)]
754struct WeightedInput {
755    plan: Arc<dyn ExecutionPlan>,
756    source: usize,
757    destination: usize,
758    /// One column per weight expression, in the node's order.
759    weights: Vec<usize>,
760    /// The weighted plan's fingerprint, or `None` if it cannot be cached.
761    fingerprint: Option<String>,
762}
763
764/// Builds or fetches a graph index from its child's edge rows, and runs
765/// graph functions over it.
766#[derive(Debug)]
767pub struct GraphAlgorithmExec {
768    shape: Shape,
769    input: Arc<dyn ExecutionPlan>,
770    weighted: Option<WeightedInput>,
771    /// A neighbour aggregation's node values: node ids, then values.
772    values: Option<Arc<dyn ExecutionPlan>>,
773    properties: Arc<PlanProperties>,
774}
775
776impl GraphAlgorithmExec {
777    fn new(
778        shape: Shape,
779        input: Arc<dyn ExecutionPlan>,
780        weighted: Option<WeightedInput>,
781        values: Option<Arc<dyn ExecutionPlan>>,
782    ) -> Self {
783        let properties = Arc::new(PlanProperties::new(
784            EquivalenceProperties::new(Arc::clone(&shape.schema)),
785            Partitioning::UnknownPartitioning(1),
786            EmissionType::Final,
787            Boundedness::Bounded,
788        ));
789        Self {
790            shape,
791            input,
792            weighted,
793            values,
794            properties,
795        }
796    }
797}
798
799impl DisplayAs for GraphAlgorithmExec {
800    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
801        write!(
802            f,
803            "GraphAlgorithmExec: graph={}, outputs=[{}]",
804            self.shape.edges.graph, self.shape.display
805        )
806    }
807}
808
809impl ExecutionPlan for GraphAlgorithmExec {
810    fn name(&self) -> &str {
811        "GraphAlgorithmExec"
812    }
813
814    fn properties(&self) -> &Arc<PlanProperties> {
815        &self.properties
816    }
817
818    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
819        let mut children = vec![&self.input];
820        children.extend(self.weighted.as_ref().map(|w| &w.plan));
821        children.extend(self.shape.edges.vertices.as_ref().map(|v| &v.plan));
822        children.extend(self.values.as_ref());
823        children
824    }
825
826    /// The edges are read partition by partition in order; splitting them
827    /// further would only scramble that order.
828    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
829        vec![false; self.children().len()]
830    }
831
832    fn apply_expressions(
833        &self,
834        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
835    ) -> Result<TreeNodeRecursion> {
836        Ok(TreeNodeRecursion::Continue)
837    }
838
839    fn with_new_children(
840        self: Arc<Self>,
841        children: Vec<Arc<dyn ExecutionPlan>>,
842    ) -> Result<Arc<dyn ExecutionPlan>> {
843        let expected = self.children().len();
844        if children.len() != expected {
845            return Err(DataFusionError::Internal(format!(
846                "GraphAlgorithmExec has {expected} children; got {}",
847                children.len()
848            )));
849        }
850        let mut children = children.into_iter();
851        let input = children.next().expect("checked above");
852        let weighted = self.weighted.clone().map(|w| WeightedInput {
853            plan: children.next().expect("checked above"),
854            ..w
855        });
856        let mut shape = self.shape.clone();
857        shape.edges.vertices = shape.edges.vertices.map(|v| VertexInput {
858            plan: children.next().expect("checked above"),
859            ..v
860        });
861        let values = self
862            .values
863            .as_ref()
864            .map(|_| children.next().expect("checked above"));
865        Ok(Arc::new(Self::new(shape, input, weighted, values)))
866    }
867
868    fn execute(
869        &self,
870        partition: usize,
871        context: Arc<TaskContext>,
872    ) -> Result<SendableRecordBatchStream> {
873        if partition != 0 {
874            return Err(DataFusionError::Internal(format!(
875                "GraphAlgorithmExec has one partition; asked for {partition}"
876            )));
877        }
878        let shape = self.shape.clone();
879        let input = Arc::clone(&self.input);
880        let weighted = self.weighted.clone();
881        let values_plan = self.values.clone();
882        let schema = Arc::clone(&shape.schema);
883        let run = async move {
884            let (index, weights) = verified_index(&shape.edges, input, weighted, &context).await?;
885            let values = match values_plan {
886                Some(plan) => {
887                    let batches = drain(&plan, &[0, 1], &context).await?;
888                    Some(kernels::node_values(&index, &shape.edges.graph, batches)?)
889                }
890                None => None,
891            };
892            // The kernels are CPU-bound and parallel (rayon): keep them off
893            // the async workers (inline in the browser, which has none).
894            crate::run_blocking(move || {
895                let weights = weights.as_deref().map_or(&[][..], Vec::as_slice);
896                kernels::batch(
897                    &index,
898                    &shape.outputs,
899                    weights,
900                    values.as_ref(),
901                    shape.per_node,
902                    shape.schema,
903                )
904            })
905            .await
906            .map_err(|e| DataFusionError::Execution(format!("a graph kernel failed: {e}")))?
907        };
908        Ok(Box::pin(RecordBatchStreamAdapter::new(
909            schema,
910            futures::stream::once(run),
911        )))
912    }
913}
914
915/// The index (and the weight columns, for a weighted node) for an algorithm
916/// that reads the whole graph, with the checksums of a memory-mapped stored
917/// index checked first (`crate::database::mapped`): the arrays are about to
918/// be read whole anyway, and a result is never computed from damaged ones.
919/// A damaged stored index is dropped and built again from its sources, with
920/// a notice.
921async fn verified_index(
922    edges: &Edges,
923    input: Arc<dyn ExecutionPlan>,
924    weighted: Option<WeightedInput>,
925    context: &Arc<TaskContext>,
926) -> Result<(Arc<GraphIndex>, Option<Weights>)> {
927    let mut damaged = None;
928    loop {
929        let (index, weights) = match weighted.clone() {
930            None => (
931                unweighted_index(edges, Arc::clone(&input), context).await?,
932                None,
933            ),
934            Some(w) => {
935                let (index, weights) =
936                    weighted_index(edges, Arc::clone(&input), w, context).await?;
937                (index, Some(weights))
938            }
939        };
940        let checked = Arc::clone(&index);
941        let verified = crate::run_blocking(move || checked.verify_stored())
942            .await
943            .map_err(|e| DataFusionError::Execution(format!("checking an index failed: {e}")))?;
944        match (verified, damaged) {
945            (Ok(()), _) => return Ok((index, weights)),
946            (Err(why), None) => {
947                if let Some(cache) = context.session_config().get_extension::<IndexCache>() {
948                    cache.record_damaged_load();
949                }
950                Notifier::of(context.session_config()).say(NoticeLevel::On, || {
951                    format!(
952                        "the stored index for {} is damaged ({why}); building it again",
953                        edges.graph
954                    )
955                });
956                damaged = Some(why);
957            }
958            // Built from its sources: not stored, so never damaged.
959            (Err(why), Some(_)) => {
960                return Err(DataFusionError::Execution(format!(
961                    "the index for {} is damaged ({why})",
962                    edges.graph
963                )))
964            }
965        }
966    }
967}
968
969/// What a [`GraphTraversalExec`] computes, besides its children.
970#[derive(Debug, Clone)]
971struct TraversalShape {
972    edges: Edges,
973    traversal: Traversal,
974    /// Whether each node-id input is a subquery (see
975    /// [`GraphTraversalNode::from_query`]).
976    from_query: Vec<bool>,
977    /// The call as `EXPLAIN` shows it.
978    display: String,
979    schema: SchemaRef,
980}
981
982/// Builds or fetches a graph index from its first child's edge rows, reads
983/// the node ids its other children produce, and runs a traversal.
984#[derive(Debug)]
985pub struct GraphTraversalExec {
986    shape: TraversalShape,
987    input: Arc<dyn ExecutionPlan>,
988    weighted: Option<WeightedInput>,
989    /// One plan per node-id parameter, in the spec's order.
990    nodes: Vec<Arc<dyn ExecutionPlan>>,
991    properties: Arc<PlanProperties>,
992}
993
994impl GraphTraversalExec {
995    fn new(
996        shape: TraversalShape,
997        input: Arc<dyn ExecutionPlan>,
998        weighted: Option<WeightedInput>,
999        nodes: Vec<Arc<dyn ExecutionPlan>>,
1000    ) -> Self {
1001        let properties = Arc::new(PlanProperties::new(
1002            EquivalenceProperties::new(Arc::clone(&shape.schema)),
1003            Partitioning::UnknownPartitioning(1),
1004            EmissionType::Final,
1005            Boundedness::Bounded,
1006        ));
1007        Self {
1008            shape,
1009            input,
1010            weighted,
1011            nodes,
1012            properties,
1013        }
1014    }
1015}
1016
1017impl DisplayAs for GraphTraversalExec {
1018    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
1019        write!(
1020            f,
1021            "GraphTraversalExec: graph={}, call={}",
1022            self.shape.edges.graph, self.shape.display
1023        )
1024    }
1025}
1026
1027impl ExecutionPlan for GraphTraversalExec {
1028    fn name(&self) -> &str {
1029        "GraphTraversalExec"
1030    }
1031
1032    fn properties(&self) -> &Arc<PlanProperties> {
1033        &self.properties
1034    }
1035
1036    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
1037        let mut children = vec![&self.input];
1038        children.extend(self.weighted.as_ref().map(|w| &w.plan));
1039        children.extend(self.shape.edges.vertices.as_ref().map(|v| &v.plan));
1040        children.extend(self.nodes.iter());
1041        children
1042    }
1043
1044    /// The edges are read in order (see [`GraphAlgorithmExec`]), and the node
1045    /// ids in the order their query gives them, which sets the order of the
1046    /// rows.
1047    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
1048        vec![false; self.children().len()]
1049    }
1050
1051    fn apply_expressions(
1052        &self,
1053        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
1054    ) -> Result<TreeNodeRecursion> {
1055        Ok(TreeNodeRecursion::Continue)
1056    }
1057
1058    fn with_new_children(
1059        self: Arc<Self>,
1060        children: Vec<Arc<dyn ExecutionPlan>>,
1061    ) -> Result<Arc<dyn ExecutionPlan>> {
1062        let expected = self.children().len();
1063        if children.len() != expected {
1064            return Err(DataFusionError::Internal(format!(
1065                "GraphTraversalExec has {expected} children; got {}",
1066                children.len()
1067            )));
1068        }
1069        let mut children = children.into_iter();
1070        let input = children.next().expect("checked above");
1071        let weighted = self.weighted.clone().map(|w| WeightedInput {
1072            plan: children.next().expect("checked above"),
1073            ..w
1074        });
1075        let mut shape = self.shape.clone();
1076        shape.edges.vertices = shape.edges.vertices.map(|v| VertexInput {
1077            plan: children.next().expect("checked above"),
1078            ..v
1079        });
1080        Ok(Arc::new(Self::new(
1081            shape,
1082            input,
1083            weighted,
1084            children.collect(),
1085        )))
1086    }
1087
1088    fn execute(
1089        &self,
1090        partition: usize,
1091        context: Arc<TaskContext>,
1092    ) -> Result<SendableRecordBatchStream> {
1093        if partition != 0 {
1094            return Err(DataFusionError::Internal(format!(
1095                "GraphTraversalExec has one partition; asked for {partition}"
1096            )));
1097        }
1098        let shape = self.shape.clone();
1099        let input = Arc::clone(&self.input);
1100        let weighted = self.weighted.clone();
1101        let node_plans = self.nodes.clone();
1102        let schema = Arc::clone(&shape.schema);
1103        let run = async move {
1104            let (index, weights) = match weighted {
1105                None => (unweighted_index(&shape.edges, input, &context).await?, None),
1106                Some(w) => {
1107                    let (index, weights) = weighted_index(&shape.edges, input, w, &context).await?;
1108                    (index, Some(weights))
1109                }
1110            };
1111            let spec = shape.traversal.spec();
1112            let mut nodes = Vec::with_capacity(node_plans.len());
1113            for (i, (param, plan)) in spec.node_params().zip(&node_plans).enumerate() {
1114                let batches = drain(plan, &[0], &context).await?;
1115                let from_query = shape.from_query.get(i).copied().unwrap_or(true);
1116                let notifier = Notifier::of(context.session_config());
1117                nodes.push(node_ids(
1118                    &shape, param, &index, batches, from_query, &notifier,
1119                )?);
1120            }
1121            crate::run_blocking(move || {
1122                let weights = weights.as_ref().map(|w| w[0].as_slice());
1123                traversal::batch(
1124                    &index.topology,
1125                    &index.ids,
1126                    &shape.traversal,
1127                    &nodes,
1128                    weights,
1129                    &|e| index.edge_row(e),
1130                    shape.schema,
1131                )
1132            })
1133            .await
1134            .map_err(|e| DataFusionError::Execution(format!("a graph kernel failed: {e}")))?
1135        };
1136        Ok(Box::pin(RecordBatchStreamAdapter::new(
1137            schema,
1138            futures::stream::once(run),
1139        )))
1140    }
1141}
1142
1143/// The ids a node-id input produced, as dense indexes of `index` (`None` for a
1144/// null or an id not in the graph), cast to the graph's id type first.
1145///
1146/// An id that is not a node of the graph (#416): from a literal, an error
1147/// naming up to three of them and their count; from a subquery (`from_query`),
1148/// skipped, and a notice says how many were. `induced_edges` skips them
1149/// always ([`traversal::TraversalSpec::strict_ids`]). A NULL matches no node.
1150fn node_ids(
1151    shape: &TraversalShape,
1152    param: &TraversalParam,
1153    index: &GraphIndex,
1154    batches: Vec<Vec<ArrayRef>>,
1155    from_query: bool,
1156    notifier: &Notifier,
1157) -> Result<Vec<Option<u32>>> {
1158    let (function, name, graph) = (shape.traversal.name(), param.name, &shape.edges.graph);
1159    let id_type = index.ids.user_type();
1160    let options = CastOptions {
1161        safe: false,
1162        ..CastOptions::default()
1163    };
1164    let arrays = batches
1165        .iter()
1166        .map(|b| {
1167            // No float, boolean or date, and a string must be exactly an
1168            // integer on a graph with integer ids (#271).
1169            if let Some(row) = traversal::first_refused_node_id(&b[0], &id_type) {
1170                let got = sql_text(&b[0], row)
1171                    .unwrap_or_else(|| format!("a value of type {}", b[0].data_type()));
1172                return Err(DataFusionError::Execution(traversal::not_node_ids(
1173                    function, param, graph, &id_type, &got,
1174                )));
1175            }
1176            cast_with_options(&b[0], &id_type, &options).map_err(|e| {
1177                let got = first_uncast(&b[0], &id_type).unwrap_or_else(|| {
1178                    crate::user_message(&DataFusionError::ArrowError(Box::new(e), None))
1179                });
1180                DataFusionError::Execution(traversal::not_node_ids(
1181                    function, param, graph, &id_type, &got,
1182                ))
1183            })
1184        })
1185        .collect::<Result<Vec<_>>>()?;
1186    let refs: Vec<&dyn Array> = arrays.iter().map(|a| a.as_ref()).collect();
1187    let ids = match refs.as_slice() {
1188        [] => new_empty_array(&id_type),
1189        _ => concat(&refs)?,
1190    };
1191    if param.ty == TraversalParamType::Node && ids.len() > 1 {
1192        return Err(DataFusionError::Execution(format!(
1193            "{function}({name} =>) must be one node id; its query returned {} rows",
1194            ids.len()
1195        )));
1196    }
1197    let dense = index
1198        .ids
1199        .dense_from_array(ids.as_ref())
1200        .map_err(|e| DataFusionError::Execution(format!("{function}({name} =>): {e}")))?;
1201    let mut missing: Vec<String> = Vec::new();
1202    for (row, d) in dense.iter().enumerate() {
1203        if d.is_none() && ids.is_valid(row) {
1204            let text = sql_text(&ids, row).unwrap_or_else(|| "?".into());
1205            if !missing.contains(&text) {
1206                missing.push(text);
1207            }
1208        }
1209    }
1210    if missing.is_empty() || !shape.traversal.spec().strict_ids {
1211        return Ok(dense);
1212    }
1213    if from_query {
1214        notifier.say(NoticeLevel::On, || {
1215            let ids = match missing.len() {
1216                1 => "1 id from the query that is not a node".to_string(),
1217                n => format!("{n} ids from the query that are not nodes"),
1218            };
1219            format!("{function}({name} =>): skipped {ids} of graph '{graph}'")
1220        });
1221        return Ok(dense);
1222    }
1223    Err(DataFusionError::Execution(not_nodes(
1224        function, name, graph, &missing,
1225    )))
1226}
1227
1228/// "hop(seeds =>): 99 is not a node of graph 'pg'", or for several, the first
1229/// three and the count: "hop(seeds =>): 5 ids are not nodes of graph 'pg':
1230/// 97, 98, 99 and 2 more".
1231fn not_nodes(function: &str, name: &str, graph: &str, missing: &[String]) -> String {
1232    match missing {
1233        [one] => format!("{function}({name} =>): {one} is not a node of graph '{graph}'"),
1234        _ => {
1235            let shown = missing[..missing.len().min(3)].join(", ");
1236            let more = match missing.len() {
1237                n if n > 3 => format!(" and {} more", n - 3),
1238                _ => String::new(),
1239            };
1240            format!(
1241                "{function}({name} =>): {} ids are not nodes of graph '{graph}': {shown}{more}",
1242                missing.len()
1243            )
1244        }
1245    }
1246}
1247
1248/// The first value of `values` that does not cast to `id_type`, as SQL writes
1249/// it (`'Valjean'`, `2.5`), for a message.
1250fn first_uncast(values: &ArrayRef, id_type: &DataType) -> Option<String> {
1251    let lenient = cast(values, id_type).ok()?;
1252    let row = (0..values.len()).find(|&i| values.is_valid(i) && lenient.is_null(i))?;
1253    sql_text(values, row)
1254}
1255
1256/// Row `row` of `values` as SQL writes it (`'Valjean'`, `2.5`).
1257fn sql_text(values: &ArrayRef, row: usize) -> Option<String> {
1258    let mut value = ScalarValue::try_from_array(values, row).ok()?;
1259    while let ScalarValue::Dictionary(_, inner) = value {
1260        value = *inner;
1261    }
1262    Some(match value.try_as_str() {
1263        Some(Some(s)) => format!("'{}'", s.replace('\'', "''")),
1264        _ => value.to_string(),
1265    })
1266}
1267
1268/// Leaves the edge and vertex inputs of a path search over a held index out
1269/// of its children, so `EXPLAIN` does not draw inputs that do not run
1270/// (#384, N48). It runs last, once every other rule has optimized them: they
1271/// still build the index should the session no longer hold it when the node
1272/// runs.
1273#[derive(Debug)]
1274pub struct CollapseHeldInputs;
1275
1276impl PhysicalOptimizerRule for CollapseHeldInputs {
1277    fn optimize(
1278        &self,
1279        plan: Arc<dyn ExecutionPlan>,
1280        _config: &ConfigOptions,
1281    ) -> Result<Arc<dyn ExecutionPlan>> {
1282        plan.transform_up(|node| match node.downcast_ref::<PathSearchExec>() {
1283            Some(exec) if exec.held.is_some() && !exec.collapsed => Ok(Transformed::yes(Arc::new(
1284                exec.collapse(),
1285            )
1286                as Arc<dyn ExecutionPlan>)),
1287            _ => Ok(Transformed::no(node)),
1288        })
1289        .map(|t| t.data)
1290    }
1291
1292    fn name(&self) -> &str {
1293        "collapse_held_inputs"
1294    }
1295
1296    fn schema_check(&self) -> bool {
1297        true
1298    }
1299}
1300
1301/// Keeps a graph node's edge rows in the order the plan produces them, and
1302/// gives them a fixed order where the plan has none.
1303///
1304/// DataFusion's `EnforceDistribution` puts a round-robin repartition under an
1305/// operator that benefits from parallel input, such as the `FilterExec` of a
1306/// view with a `WHERE` (a subgraph) or the `ProjectionExec` that computes a
1307/// weight expression. Draining its partitions in order would then read the
1308/// batches out of file order, changing dense ids (and so labels and float
1309/// summation order) from what `ursa-io` gives the Python library. This rule
1310/// runs after the default rules and removes every round-robin repartition
1311/// below a graph node: a round-robin repartition only adds parallelism, so
1312/// removing it never changes a result.
1313///
1314/// What remains may still not preserve order: a join, an aggregate, a hash
1315/// repartition, a merge of partitions or a `UNION` produces its rows in an
1316/// order that can change between runs and thread counts (#263). Over such a
1317/// plan, the rule sorts the edge rows by `(source, destination)`, and a
1318/// weighted node's rows by their weights after that, so that rows that tie
1319/// are identical in every column the node reads. A traversal's node-id
1320/// inputs over such a plan are sorted by value, and so are a graph's vertex
1321/// keys, which set the order of its nodes. Order-preserving plans
1322/// (scans, views over files, filters, projections) are left as they are,
1323/// in file order. The sort is a `SortExec` under the node, so `EXPLAIN`
1324/// shows it.
1325#[derive(Debug)]
1326pub struct KeepEdgeOrder;
1327
1328impl PhysicalOptimizerRule for KeepEdgeOrder {
1329    fn optimize(
1330        &self,
1331        plan: Arc<dyn ExecutionPlan>,
1332        _config: &ConfigOptions,
1333    ) -> Result<Arc<dyn ExecutionPlan>> {
1334        plan.transform_up(|node| {
1335            // The columns each child is sorted by, if its order is not fixed.
1336            let keys: Vec<Vec<usize>> =
1337                if let Some(exec) = node.downcast_ref::<GraphAlgorithmExec>() {
1338                    let mut keys = vec![endpoint_keys(exec.shape.edges.endpoints)];
1339                    keys.extend(exec.weighted.as_ref().map(weighted_keys));
1340                    keys.extend(exec.shape.edges.vertices.as_ref().map(|_| vec![0]));
1341                    // A neighbour aggregation's values give one value per
1342                    // node whatever their order: no sort.
1343                    keys.extend(exec.values.as_ref().map(|_| vec![]));
1344                    keys
1345                } else if let Some(exec) = node.downcast_ref::<GraphTraversalExec>() {
1346                    let mut keys = vec![endpoint_keys(exec.shape.edges.endpoints)];
1347                    keys.extend(exec.weighted.as_ref().map(weighted_keys));
1348                    keys.extend(exec.shape.edges.vertices.as_ref().map(|_| vec![0]));
1349                    keys.extend(exec.nodes.iter().map(|_| vec![0]));
1350                    keys
1351                } else if let Some(exec) = node.downcast_ref::<PathSearchExec>() {
1352                    if exec.collapsed {
1353                        return Ok(Transformed::no(node)); // its inputs are done
1354                    }
1355                    let mut keys = vec![endpoint_keys(exec.shape.edges.endpoints)];
1356                    keys.extend(exec.shape.edges.vertices.as_ref().map(|_| vec![0]));
1357                    keys.push(vec![0]);
1358                    // The targets are a set: their order does not matter.
1359                    keys.extend(exec.targets.as_ref().map(|_| vec![]));
1360                    keys
1361                } else {
1362                    return Ok(Transformed::no(node));
1363                };
1364            let children = node
1365                .children()
1366                .into_iter()
1367                .zip(keys)
1368                .map(|(child, keys)| {
1369                    let child = without_round_robin(Arc::clone(child))?;
1370                    if preserves_order(&child) {
1371                        Ok(child)
1372                    } else {
1373                        sorted(child, &keys)
1374                    }
1375                })
1376                .collect::<Result<Vec<_>>>()?;
1377            Ok(Transformed::yes(replace_children_if_necessary(
1378                Arc::clone(&node),
1379                children,
1380            )?))
1381        })
1382        .map(|t| t.data)
1383    }
1384
1385    fn name(&self) -> &str {
1386        "keep_edge_order"
1387    }
1388
1389    fn schema_check(&self) -> bool {
1390        true
1391    }
1392}
1393
1394/// `plan` with its round-robin repartitions removed.
1395fn without_round_robin(plan: Arc<dyn ExecutionPlan>) -> Result<Arc<dyn ExecutionPlan>> {
1396    plan.transform_up(|node| {
1397        if let Some(repartition) = node.downcast_ref::<RepartitionExec>() {
1398            if matches!(repartition.partitioning(), Partitioning::RoundRobinBatch(_)) {
1399                return Ok(Transformed::yes(Arc::clone(repartition.input())));
1400            }
1401        }
1402        Ok(Transformed::no(node))
1403    })
1404    .map(|t| t.data)
1405}
1406
1407/// The sort key of an edge input: its source, then its destination.
1408fn endpoint_keys((source, destination): (usize, usize)) -> Vec<usize> {
1409    vec![source, destination]
1410}
1411
1412/// The sort key of a weighted edge input: its endpoints, then every weight,
1413/// so rows that tie are the same in every column the node reads.
1414fn weighted_keys(weighted: &WeightedInput) -> Vec<usize> {
1415    let mut keys = endpoint_keys((weighted.source, weighted.destination));
1416    keys.extend(&weighted.weights);
1417    keys
1418}
1419
1420/// Whether reading `plan`'s partitions in order gives its rows in an order
1421/// that does not depend on the run or the thread count: true unless it has
1422/// a join, an aggregate, a repartition, a merge of partitions or a union. A
1423/// nested graph node emits its rows in a fixed order, whatever its inputs.
1424fn preserves_order(plan: &Arc<dyn ExecutionPlan>) -> bool {
1425    let mut preserves = true;
1426    let _ = plan.apply(|node| {
1427        if node.downcast_ref::<GraphAlgorithmExec>().is_some()
1428            || node.downcast_ref::<GraphTraversalExec>().is_some()
1429            || node.downcast_ref::<PathSearchExec>().is_some()
1430        {
1431            return Ok(TreeNodeRecursion::Jump);
1432        }
1433        let reorders = node.downcast_ref::<RepartitionExec>().is_some()
1434            || node.downcast_ref::<CoalescePartitionsExec>().is_some()
1435            || node.downcast_ref::<AggregateExec>().is_some()
1436            || node.downcast_ref::<UnionExec>().is_some()
1437            || node.downcast_ref::<InterleaveExec>().is_some()
1438            || node.name().contains("Join");
1439        if reorders {
1440            preserves = false;
1441            return Ok(TreeNodeRecursion::Stop);
1442        }
1443        Ok(TreeNodeRecursion::Continue)
1444    });
1445    preserves
1446}
1447
1448/// `plan`'s rows sorted by the columns `keys`, ascending with nulls last,
1449/// as one partition: each partition is sorted, then they are merged.
1450fn sorted(plan: Arc<dyn ExecutionPlan>, keys: &[usize]) -> Result<Arc<dyn ExecutionPlan>> {
1451    let schema = plan.schema();
1452    let exprs = keys.iter().map(|&i| {
1453        PhysicalSortExpr::new(
1454            Arc::new(Column::new(schema.field(i).name(), i)) as Arc<dyn PhysicalExpr>,
1455            SortOptions {
1456                descending: false,
1457                nulls_first: false,
1458            },
1459        )
1460    });
1461    let Some(ordering) = LexOrdering::new(exprs) else {
1462        return Ok(plan);
1463    };
1464    let partitions = plan.output_partitioning().partition_count();
1465    let sort =
1466        Arc::new(SortExec::new(ordering.clone(), plan).with_preserve_partitioning(partitions > 1));
1467    Ok(if partitions > 1 {
1468        Arc::new(SortPreservingMergeExec::new(ordering, sort))
1469    } else {
1470        sort
1471    })
1472}
1473
1474/// The index cache key for the edges `input` reads, if they can be cached:
1475/// with a vertex table, the keys' plan and files too, so a change to the
1476/// vertex table builds the index afresh.
1477async fn index_key(
1478    shape: &Edges,
1479    input: &Arc<dyn ExecutionPlan>,
1480    context: &TaskContext,
1481) -> Result<Option<(String, Vec<FileIdentity>)>> {
1482    let Some(edges) = &shape.fingerprint else {
1483        return Ok(None);
1484    };
1485    let mut files = file_identities(input, context).await?;
1486    let fingerprint = match &shape.vertices {
1487        None => edges.clone(),
1488        Some(VertexInput {
1489            fingerprint: None, ..
1490        }) => return Ok(None),
1491        Some(VertexInput {
1492            plan,
1493            fingerprint: Some(vertices),
1494            unique,
1495        }) => {
1496            files.extend(file_identities(plan, context).await?);
1497            files.sort();
1498            files.dedup();
1499            // An index whose build refused a key that repeats or is NULL
1500            // (#411) says so in its key: one stored before builds checked
1501            // has another key and is built afresh, and a stored index with
1502            // this key shows its vertex table's keys are one row each
1503            // (see `vertex_keys`).
1504            match unique {
1505                Some(_) => format!("{edges}{}{vertices}", super::vertex_keys::UNIQUE_KEYS),
1506                None => format!("{edges}\n-- vertex keys --\n{vertices}"),
1507            }
1508        }
1509    };
1510    Ok(Some((fingerprint, files)))
1511}
1512
1513/// The index of the graph the first algorithm in `plan` runs over, as the
1514/// algorithm itself would find it: the session's cached one, or built (and
1515/// cached) from the plan's edge input. `None` if `plan` runs no algorithm.
1516///
1517/// For a caller that reads the topology and not a kernel's answer: the
1518/// graph view draws a property graph from it (`super::view`, #525).
1519pub(crate) async fn index_under(
1520    plan: &Arc<dyn ExecutionPlan>,
1521    context: &Arc<TaskContext>,
1522) -> Result<Option<Arc<GraphIndex>>> {
1523    let mut found = None;
1524    plan.apply(|node| {
1525        Ok(match node.downcast_ref::<GraphAlgorithmExec>() {
1526            Some(exec) => {
1527                found = Some((exec.shape.edges.clone(), Arc::clone(&exec.input)));
1528                TreeNodeRecursion::Stop
1529            }
1530            None => TreeNodeRecursion::Continue,
1531        })
1532    })?;
1533    match found {
1534        Some((edges, input)) => {
1535            let (index, _) = verified_index(&edges, input, None, context).await?;
1536            Ok(Some(index))
1537        }
1538        None => Ok(None),
1539    }
1540}
1541
1542/// The index, cached or built from the endpoint-only input.
1543async fn unweighted_index(
1544    shape: &Edges,
1545    input: Arc<dyn ExecutionPlan>,
1546    context: &Arc<TaskContext>,
1547) -> Result<Arc<GraphIndex>> {
1548    let build = {
1549        let (shape, input, context) = (shape.clone(), Arc::clone(&input), Arc::clone(context));
1550        async move {
1551            let mut no_weights = WeightReader::new(&[], 0);
1552            build_streamed(&shape, &input, shape.endpoints, &context, &mut no_weights).await
1553        }
1554    };
1555    match context.session_config().get_extension::<IndexCache>() {
1556        Some(cache) => {
1557            let key = index_key(shape, &input, context).await?;
1558            cache
1559                .get_or_build_for(
1560                    context.session_config(),
1561                    key,
1562                    &build_info(shape, &input),
1563                    build.boxed(),
1564                )
1565                .await
1566        }
1567        None => build.await.map(Arc::new),
1568    }
1569}
1570
1571/// The index and the weight columns, for a node that reads weights (see the
1572/// module docs).
1573async fn weighted_index(
1574    shape: &Edges,
1575    input: Arc<dyn ExecutionPlan>,
1576    weighted: WeightedInput,
1577    context: &Arc<TaskContext>,
1578) -> Result<(Arc<GraphIndex>, Weights)> {
1579    let cache = context.session_config().get_extension::<IndexCache>();
1580    let key = match &cache {
1581        Some(_) => index_key(shape, &input, context).await?,
1582        None => None,
1583    };
1584    let weights_key = match &weighted.fingerprint {
1585        Some(f) => Some(format!(
1586            "{}\n{:?}",
1587            portable_in(f, context.session_config()),
1588            file_identities(&weighted.plan, context).await?
1589        )),
1590        None => None,
1591    };
1592    let n_weights = weighted.weights.len();
1593    // Weights already evaluated over the cached index's rows: nothing to read.
1594    if let (Some(cache), Some(key), Some(weights_key)) = (&cache, &key, &weights_key) {
1595        if let Some(index) = cache.get(key) {
1596            if let Some(weights) = known_weights(&index, weights_key, n_weights).await {
1597                return Ok((index, weights));
1598            }
1599        }
1600    }
1601
1602    let (index, weights, shared) = match &cache {
1603        Some(cache) => {
1604            // Weights read by this node's own build, if the cache ran it.
1605            let slot = Arc::new(Mutex::new(None));
1606            let build = {
1607                let (shape, weighted) = (shape.clone(), weighted.clone());
1608                let (context, slot) = (Arc::clone(context), Arc::clone(&slot));
1609                async move {
1610                    let (index, weights) = build_weighted(&shape, &weighted, &context).await?;
1611                    *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(weights);
1612                    Ok(index)
1613                }
1614            };
1615            let index = cache
1616                .get_or_build_for(
1617                    context.session_config(),
1618                    key,
1619                    &build_info(shape, &weighted.plan),
1620                    build.boxed(),
1621                )
1622                .await?;
1623            let built_here = slot.lock().unwrap_or_else(|e| e.into_inner()).take();
1624            // A stored index may have these weights stored with it.
1625            if built_here.is_none() {
1626                if let Some(weights_key) = &weights_key {
1627                    if let Some(weights) = known_weights(&index, weights_key, n_weights).await {
1628                        return Ok((index, weights));
1629                    }
1630                }
1631            }
1632            match built_here {
1633                Some(weights) => (index, weights, true),
1634                None => {
1635                    let mut weights =
1636                        WeightReader::new(&weighted.weights, index.topology.n_edges());
1637                    if read_aligned(&index, &weighted, shape, context, &mut weights).await? {
1638                        (index, weights, true)
1639                    } else {
1640                        // The cached index's rows are in another order: these
1641                        // weights belong to an index of these rows.
1642                        cache.record_build();
1643                        let (private, weights) = build_weighted(shape, &weighted, context).await?;
1644                        (Arc::new(private), weights, false)
1645                    }
1646                }
1647            }
1648        }
1649        None => {
1650            let (index, weights) = build_weighted(shape, &weighted, context).await?;
1651            (Arc::new(index), weights, false)
1652        }
1653    };
1654
1655    let weights: Weights = Arc::new(weights.finish()?.into_iter().map(Arc::new).collect());
1656    if let (true, Some(weights_key)) = (shared, weights_key) {
1657        index.store_weights(weights_key, Arc::clone(&weights));
1658    }
1659    Ok((index, weights))
1660}
1661
1662/// The weights `index` holds under `key` (with `n_weights` columns), in
1663/// memory or stored with it on disk.
1664async fn known_weights(index: &Arc<GraphIndex>, key: &str, n_weights: usize) -> Option<Weights> {
1665    if let Some(weights) = index.weights(key) {
1666        return Some(weights);
1667    }
1668    if !index.has_stored_weights(key) {
1669        return None;
1670    }
1671    let (index, key) = (Arc::clone(index), key.to_string());
1672    // Reading a file is blocking work.
1673    crate::run_blocking(move || index.stored_weights(&key, n_weights))
1674        .await
1675        .ok()
1676        .flatten()
1677}
1678
1679/// Build the index of the weighted rows, reading their weights in the same
1680/// pass, so they line up by construction.
1681async fn build_weighted(
1682    shape: &Edges,
1683    weighted: &WeightedInput,
1684    context: &Arc<TaskContext>,
1685) -> Result<(GraphIndex, WeightReader)> {
1686    let mut weights = WeightReader::new(&weighted.weights, row_hint(&weighted.plan));
1687    let endpoints = (weighted.source, weighted.destination);
1688    let index = build_streamed(shape, &weighted.plan, endpoints, context, &mut weights).await?;
1689    Ok((index, weights))
1690}
1691
1692/// Read the weighted rows once, reading their weights, and say whether
1693/// their endpoints are the rows `index` was built from, row for row. Stops
1694/// at the first row that is not.
1695async fn read_aligned(
1696    index: &GraphIndex,
1697    weighted: &WeightedInput,
1698    shape: &Edges,
1699    context: &Arc<TaskContext>,
1700    weights: &mut WeightReader,
1701) -> Result<bool> {
1702    let id_type = &shape.id_type;
1703    let mut rows = RowCheck::new(index);
1704    let mut batches = InOrder::new(&weighted.plan, context);
1705    while let Some(batch) = batches.next().await {
1706        let mut batch = batch?;
1707        let mut src = cast(batch.column(weighted.source), id_type)?;
1708        let mut dst = cast(batch.column(weighted.destination), id_type)?;
1709        // With a vertex table, the index holds only the edges between
1710        // keys: skip the others, as the build did.
1711        if shape.vertices.is_some() {
1712            let keep = between_nodes(index, &src, &dst)?;
1713            if keep.true_count() < keep.len() {
1714                batch = filter_record_batch(&batch, &keep)?;
1715                src = filter(&src, &keep)?;
1716                dst = filter(&dst, &keep)?;
1717            }
1718        }
1719        if batch.num_rows() == 0 {
1720            continue;
1721        }
1722        if !rows.check(&src, &dst)? {
1723            return Ok(false);
1724        }
1725        weights.push(&batch);
1726    }
1727    Ok(rows.complete())
1728}
1729
1730/// Which edges `src` -> `dst` (of the index's id type) join two nodes of
1731/// `index`.
1732fn between_nodes(index: &GraphIndex, src: &ArrayRef, dst: &ArrayRef) -> Result<BooleanArray> {
1733    let lookup = |a: &ArrayRef| {
1734        index
1735            .ids
1736            .dense_from_array(a.as_ref())
1737            .map_err(|e| DataFusionError::Execution(e.to_string()))
1738    };
1739    let (s, d) = (lookup(src)?, lookup(dst)?);
1740    Ok(s.iter()
1741        .zip(&d)
1742        .map(|(s, d)| Some(s.is_some() && d.is_some()))
1743        .collect())
1744}
1745
1746/// The weight columns of a weighted node's rows, evaluated a batch at a
1747/// time as the rows are read. The first bad weight is reported once every
1748/// row has been read, after any error in building the index from those
1749/// rows, as when the weights were evaluated after the build.
1750struct WeightReader {
1751    columns: Vec<usize>,
1752    values: Vec<Vec<f64>>,
1753    error: Option<DataFusionError>,
1754}
1755
1756impl WeightReader {
1757    /// A reader of the columns `columns`, sized for `rows` rows.
1758    fn new(columns: &[usize], rows: usize) -> Self {
1759        Self {
1760            columns: columns.to_vec(),
1761            values: columns.iter().map(|_| Vec::with_capacity(rows)).collect(),
1762            error: None,
1763        }
1764    }
1765
1766    fn push(&mut self, batch: &RecordBatch) {
1767        if self.error.is_some() {
1768            return;
1769        }
1770        for (&c, values) in self.columns.iter().zip(&mut self.values) {
1771            if let Err(e) = extend_weights(batch.column(c), values) {
1772                self.error = Some(e);
1773                return;
1774            }
1775        }
1776    }
1777
1778    /// Keep only the rows `kept` marks, one bit per row read.
1779    fn keep(&mut self, kept: &BooleanBuffer) {
1780        for values in &mut self.values {
1781            let mut bits = kept.iter();
1782            values.retain(|_| bits.next().unwrap_or(false));
1783        }
1784    }
1785
1786    /// One `f64` per row read, per column, or the first bad weight.
1787    fn finish(self) -> Result<Vec<Vec<f64>>> {
1788        match self.error {
1789            Some(e) => Err(e),
1790            None => Ok(self.values),
1791        }
1792    }
1793}
1794
1795/// Every batch of `input`, partition by partition in order (decoded in
1796/// parallel, see [`InOrder`]), as the columns
1797/// `columns` of each non-empty batch.
1798async fn drain(
1799    input: &Arc<dyn ExecutionPlan>,
1800    columns: &[usize],
1801    context: &Arc<TaskContext>,
1802) -> Result<Vec<Vec<ArrayRef>>> {
1803    let mut out = Vec::new();
1804    let mut batches = InOrder::new(input, context);
1805    while let Some(batch) = batches.next().await {
1806        let batch = batch?;
1807        if batch.num_rows() == 0 {
1808            continue;
1809        }
1810        out.push(
1811            columns
1812                .iter()
1813                .map(|&c| Arc::clone(batch.column(c)))
1814                .collect(),
1815        );
1816    }
1817    Ok(out)
1818}
1819
1820/// Rows the index build interns at a time. A scan's batches are 8,192 rows,
1821/// and `EdgeInterner` resolves known ids in parallel only in larger chunks,
1822/// so the build gathers batches up to this many rows first: what `ursa-io`'s
1823/// scan does for the Python library (its `SCAN_BATCH_ROWS`). A chunk is
1824/// 2 MiB of `Int64` endpoints.
1825const INTERN_ROWS: usize = 1 << 17;
1826
1827/// Endpoint chunks gathered up to [`INTERN_ROWS`] rows, in row order.
1828#[derive(Default)]
1829struct Gather {
1830    src: Vec<ArrayRef>,
1831    dst: Vec<ArrayRef>,
1832    rows: usize,
1833}
1834
1835impl Gather {
1836    /// Add a chunk; once [`INTERN_ROWS`] rows are gathered, take them.
1837    fn push(&mut self, src: ArrayRef, dst: ArrayRef) -> Result<Option<(ArrayRef, ArrayRef)>> {
1838        self.rows += src.len();
1839        self.src.push(src);
1840        self.dst.push(dst);
1841        if self.rows >= INTERN_ROWS {
1842            self.take()
1843        } else {
1844            Ok(None)
1845        }
1846    }
1847
1848    /// The rows gathered so far, as one chunk, if there are any.
1849    fn take(&mut self) -> Result<Option<(ArrayRef, ArrayRef)>> {
1850        self.rows = 0;
1851        let (src, dst) = (std::mem::take(&mut self.src), std::mem::take(&mut self.dst));
1852        Ok(match src.len() {
1853            0 => None,
1854            1 => src.into_iter().zip(dst).next(),
1855            _ => {
1856                let join = |arrays: &[ArrayRef]| {
1857                    let refs: Vec<&dyn Array> = arrays.iter().map(|a| a.as_ref()).collect();
1858                    concat(&refs)
1859                };
1860                Some((join(&src)?, join(&dst)?))
1861            }
1862        })
1863    }
1864}
1865
1866/// The index of everything `interner` was given; an empty graph of
1867/// `id_type` ids if it was given no node and no edge.
1868fn finish_index(mut interner: EdgeInterner, id_type: &DataType, notifier: &Notifier) -> GraphIndex {
1869    let (n_dropped, kept) = (interner.n_dropped(), interner.kept_rows());
1870    let (ids, source, destination) = interner.finish();
1871    if ids.is_empty() {
1872        let (topology, ids) = ursa_io::topology::empty_topology(id_type);
1873        return GraphIndex::new(topology, ids).with_dropped(n_dropped, kept);
1874    }
1875    let (topology, ids) = relabelled(ids, source, destination, notifier);
1876    GraphIndex::new(Arc::new(topology), Arc::new(ids)).with_dropped(n_dropped, kept)
1877}
1878
1879/// Where an index keeps its edges' rows (#170): an index of
1880/// [`RELABEL_MIN_EDGES`] edges or more writes each row's source to an
1881/// anonymous temporary file (4 B an edge, in the system's temporary
1882/// directory, `TMPDIR`), and builds its edge ids from it only when a query
1883/// reads them (a weight, a mask, an edge's row); a query that reads none never
1884/// holds them, 4 B an edge in each direction. The file is unlinked as soon as
1885/// it is created, so it goes with the index, or with the process.
1886///
1887/// A smaller index, a platform without one, or a file that cannot be written
1888/// (no temporary directory, or no room in it: a full disk fails the write,
1889/// and what was written is freed at once) builds the ids with the index, as
1890/// before #170: the query goes on, with a notice for a failed write. Rows
1891/// already in source order need neither: their ids are the identity.
1892fn spill(sources: &[u32], notifier: &Notifier) -> Option<Arc<dyn RowSource>> {
1893    #[cfg(all(unix, not(target_arch = "wasm32")))]
1894    if sources.len() >= RELABEL_MIN_EDGES {
1895        return spill_in(&std::env::temp_dir(), sources, notifier);
1896    }
1897    let _ = (sources, notifier);
1898    None
1899}
1900
1901/// [`spill`], into the directory `dir`.
1902#[cfg(all(unix, not(target_arch = "wasm32")))]
1903fn spill_in(
1904    dir: &std::path::Path,
1905    sources: &[u32],
1906    notifier: &Notifier,
1907) -> Option<Arc<dyn RowSource>> {
1908    match ursa_core::topology::SpilledRows::write_in(dir, sources) {
1909        Ok(rows) => Some(Arc::new(rows)),
1910        Err(e) => {
1911            notifier.say(NoticeLevel::On, || {
1912                format!(
1913                    "could not write the index's edge rows to {} ({e}); \
1914                     its edge ids are kept in memory ({})",
1915                    dir.display(),
1916                    crate::notices::size(4 * sources.len() as u64)
1917                )
1918            });
1919            None
1920        }
1921    }
1922}
1923
1924/// The fewest edges an index relabels its nodes for (#172): a smaller graph's
1925/// arrays fit in cache in any order, so it keeps its first-seen numbering.
1926const RELABEL_MIN_EDGES: usize = 1 << 16;
1927
1928/// The topology of the edges `source -> destination` (dense ids of `ids`),
1929/// its nodes relabelled for locality (#172) when it has
1930/// [`RELABEL_MIN_EDGES`] edges or more, and `ids` renumbered with them.
1931fn relabelled(
1932    ids: IdMap,
1933    source: Vec<u32>,
1934    destination: Vec<u32>,
1935    notifier: &Notifier,
1936) -> (Topology, IdMap) {
1937    let order = match source.len() >= RELABEL_MIN_EDGES {
1938        true => NodeOrder::InDegree,
1939        false => NodeOrder::AsGiven,
1940    };
1941    let topology =
1942        Topology::build_with_rows(ids.len(), source, destination, order, &mut |sources| {
1943            spill(sources, notifier)
1944        });
1945    let ids = match topology.original_ids() {
1946        Some(original) => ids.reordered(original),
1947        None => ids,
1948    };
1949    (topology, ids)
1950}
1951
1952/// The number of rows `plan` will produce, if its statistics say: sizes the
1953/// interner, as `ursa-io`'s scan sizes it from the Parquet metadata.
1954fn row_hint(plan: &Arc<dyn ExecutionPlan>) -> usize {
1955    StatisticsContext::new()
1956        .compute(plan.as_ref(), &StatisticsArgs::new())
1957        .ok()
1958        .and_then(|s| s.num_rows.get_value().copied())
1959        .unwrap_or(0)
1960}
1961
1962/// What a build over `input` is for, as its notices say: the graph, and how
1963/// much it reads, as far as `input`'s statistics know (#351). An exact count
1964/// is the edge rows. A filter the statistics cannot settle (one no file or
1965/// row-group statistics prune) leaves only a guess at the edges, DataFusion's
1966/// default selectivity, which can be off a hundredfold either way: then the
1967/// notice gives the rows the scans read instead, which the statistics do
1968/// know. Otherwise the estimate is of edge rows.
1969fn build_info(shape: &Edges, input: &Arc<dyn ExecutionPlan>) -> BuildInfo {
1970    let rows = plan_rows(input);
1971    let size = match rows {
1972        Some((n, true)) => Some(BuildSize::Edges(n, true)),
1973        _ if filters(input) => scanned_rows(input).map(BuildSize::Reads),
1974        Some((n, false)) => Some(BuildSize::Edges(n, false)),
1975        None => None,
1976    };
1977    BuildInfo {
1978        graph: Some(shape.graph.clone()),
1979        size,
1980    }
1981}
1982
1983/// The rows `plan`'s statistics say it gives, and whether that is exact.
1984fn plan_rows(plan: &Arc<dyn ExecutionPlan>) -> Option<(u64, bool)> {
1985    StatisticsContext::new()
1986        .compute(plan.as_ref(), &StatisticsArgs::new())
1987        .ok()
1988        .and_then(|s| {
1989            let exact = s.num_rows.is_exact().unwrap_or(false);
1990            s.num_rows.get_value().map(|n| (*n as u64, exact))
1991        })
1992}
1993
1994/// Whether `plan` filters rows: a filter node, or a predicate pushed into a
1995/// file scan.
1996fn filters(plan: &Arc<dyn ExecutionPlan>) -> bool {
1997    let mut found = false;
1998    let _ = plan.apply(|node| {
1999        let scan_predicate = node
2000            .downcast_ref::<DataSourceExec>()
2001            .and_then(|exec| exec.data_source().downcast_ref::<FileScanConfig>())
2002            .is_some_and(|config| config.file_source().filter().is_some());
2003        if scan_predicate || node.downcast_ref::<FilterExec>().is_some() {
2004            found = true;
2005            return Ok(TreeNodeRecursion::Stop);
2006        }
2007        Ok(TreeNodeRecursion::Continue)
2008    });
2009    found
2010}
2011
2012/// The rows the scans under `plan` read, if every scan's statistics say:
2013/// the rows of its leaves.
2014fn scanned_rows(plan: &Arc<dyn ExecutionPlan>) -> Option<u64> {
2015    let mut total = Some(0u64);
2016    let _ = plan.apply(|node| {
2017        if node.children().is_empty() {
2018            let leaf = plan_rows(node).map(|(n, _)| n);
2019            total = total.zip(leaf).map(|(a, b)| a + b);
2020        }
2021        Ok(TreeNodeRecursion::Continue)
2022    });
2023    total.filter(|n| *n > 0)
2024}
2025
2026/// What the reader hands an interning thread.
2027enum Chunk {
2028    /// Vertex keys, before any edge.
2029    Nodes(ArrayRef),
2030    /// Every vertex key has been read: the node set is fixed.
2031    NodesDone,
2032    Edges(ArrayRef, ArrayRef),
2033    /// Every row has been read: build the index.
2034    End,
2035}
2036
2037/// Hand one chunk to `interner`, which takes the keys and then the edges in
2038/// turn (the browser's build, see [`build_streamed`]); the index once every
2039/// row has been read.
2040#[cfg(target_arch = "wasm32")]
2041fn take_chunk(
2042    interner: &mut EdgeInterner,
2043    chunk: Chunk,
2044    graph: &str,
2045    id_type: &DataType,
2046    unique: Option<&KeyNames>,
2047) -> Result<Option<GraphIndex>> {
2048    match chunk {
2049        Chunk::Nodes(keys) => interner
2050            .push_nodes(keys.as_ref())
2051            .map_err(|e| build_error(graph, e))?,
2052        Chunk::NodesDone => close_keys(interner, unique, graph, id_type)?,
2053        Chunk::Edges(src, dst) => interner
2054            .push(src.as_ref(), dst.as_ref())
2055            .map_err(|e| build_error(graph, e))?,
2056        Chunk::End => {
2057            let interner = std::mem::replace(interner, EdgeInterner::with_capacity(0));
2058            return Ok(Some(finish_index(interner, id_type, &Notifier::silent())));
2059        }
2060    }
2061    Ok(None)
2062}
2063
2064/// Send the vertex keys `batches` gives, cast to `id_type`, to `tx`, then
2065/// [`Chunk::NodesDone`]. Stops without error if the receiver is gone (it
2066/// stopped on an error of its own).
2067async fn send_keys(
2068    mut batches: InOrder,
2069    id_type: &DataType,
2070    tx: &tokio::sync::mpsc::Sender<Chunk>,
2071) -> Result<()> {
2072    while let Some(batch) = batches.next().await {
2073        let batch = batch?;
2074        if batch.num_rows() == 0 {
2075            continue;
2076        }
2077        let keys = cast(batch.column(0), id_type)?;
2078        if tx.send(Chunk::Nodes(keys)).await.is_err() {
2079            return Ok(());
2080        }
2081    }
2082    let _ = tx.send(Chunk::NodesDone).await;
2083    Ok(())
2084}
2085
2086/// Send the endpoints of the edge rows `batches` gives to `tx`, gathered
2087/// into chunks of [`INTERN_ROWS`] rows, then [`Chunk::End`]; and read each
2088/// batch's weights into `weights`. Stops without error if the receiver is
2089/// gone (it stopped on an error of its own).
2090async fn send_edges(
2091    mut batches: InOrder,
2092    shape: &Edges,
2093    (source, destination): (usize, usize),
2094    weights: &mut WeightReader,
2095    tx: &tokio::sync::mpsc::Sender<Chunk>,
2096) -> Result<()> {
2097    let mut gather = Gather::default();
2098    while let Some(batch) = batches.next().await {
2099        let batch = batch?;
2100        if batch.num_rows() == 0 {
2101            continue;
2102        }
2103        let src = cast(batch.column(source), &shape.id_type)?;
2104        let dst = cast(batch.column(destination), &shape.id_type)?;
2105        weights.push(&batch);
2106        drop(batch);
2107        if let Some((src, dst)) = gather.push(src, dst)? {
2108            if tx.send(Chunk::Edges(src, dst)).await.is_err() {
2109                return Ok(());
2110            }
2111        }
2112    }
2113    if let Some((src, dst)) = gather.take()? {
2114        if tx.send(Chunk::Edges(src, dst)).await.is_err() {
2115            return Ok(());
2116        }
2117    }
2118    let _ = tx.send(Chunk::End).await;
2119    Ok(())
2120}
2121
2122/// Intern the vertex keys `rx` brings, on a thread of their own, and once the
2123/// last is in, hand the interner, its node set fixed, to the edges' thread
2124/// (`done`; see [`build_streamed`]).
2125#[cfg(not(target_arch = "wasm32"))]
2126fn intern_keys(
2127    mut rx: tokio::sync::mpsc::Receiver<Chunk>,
2128    done: tokio::sync::oneshot::Sender<EdgeInterner>,
2129    hint: usize,
2130    graph: &str,
2131    id_type: &DataType,
2132    unique: Option<&KeyNames>,
2133) -> Result<()> {
2134    let mut interner = EdgeInterner::with_capacity(hint);
2135    while let Some(chunk) = rx.blocking_recv() {
2136        match chunk {
2137            Chunk::Nodes(keys) => interner
2138                .push_nodes(keys.as_ref())
2139                .map_err(|e| build_error(graph, e))?,
2140            Chunk::NodesDone => {
2141                close_keys(&mut interner, unique, graph, id_type)?;
2142                // The edges' thread is gone only if it stopped on an error.
2143                let _ = done.send(interner);
2144                return Ok(());
2145            }
2146            Chunk::Edges(..) | Chunk::End => {
2147                return Err(DataFusionError::Internal(format!(
2148                    "building graph '{graph}': an edge chunk reached the vertex keys"
2149                )))
2150            }
2151        }
2152    }
2153    // The key read stopped before the end: its error is the one reported.
2154    Ok(())
2155}
2156
2157/// The edges' side of a build with a vertex table (see [`build_streamed`]):
2158/// edges interned provisionally until the node set is fixed, then into it.
2159#[cfg(not(target_arch = "wasm32"))]
2160struct EdgeSide {
2161    /// The interner the edges go into once the node set is fixed; from the
2162    /// start without a vertex table.
2163    interner: Option<EdgeInterner>,
2164    /// The edges interned before then ([`EdgeInterner::provisional`]).
2165    provisional: Option<EdgeInterner>,
2166    /// Where the keys' interner comes from, until it has.
2167    nodes: Option<tokio::sync::oneshot::Receiver<EdgeInterner>>,
2168}
2169
2170#[cfg(not(target_arch = "wasm32"))]
2171impl EdgeSide {
2172    fn new(nodes: Option<tokio::sync::oneshot::Receiver<EdgeInterner>>, hint: usize) -> Self {
2173        match nodes {
2174            None => Self {
2175                interner: Some(EdgeInterner::with_capacity(hint)),
2176                provisional: None,
2177                nodes: None,
2178            },
2179            Some(nodes) => Self {
2180                interner: None,
2181                provisional: Some(EdgeInterner::provisional(hint)),
2182                nodes: Some(nodes),
2183            },
2184        }
2185    }
2186
2187    /// Take the node set in if it is fixed (waiting for it, with `wait`),
2188    /// renumbering the edges interned so far into it. `false` if it never
2189    /// will be: the keys' read or interning stopped on an error.
2190    fn take_nodes(&mut self, wait: bool) -> std::result::Result<bool, IdError> {
2191        use tokio::sync::oneshot::error::TryRecvError;
2192        let Some(mut rx) = self.nodes.take() else {
2193            return Ok(true);
2194        };
2195        let mut nodes = match wait {
2196            true => match rx.blocking_recv() {
2197                Ok(nodes) => nodes,
2198                Err(_) => return Ok(false),
2199            },
2200            false => match rx.try_recv() {
2201                Ok(nodes) => nodes,
2202                Err(TryRecvError::Empty) => {
2203                    self.nodes = Some(rx);
2204                    return Ok(true);
2205                }
2206                Err(TryRecvError::Closed) => return Ok(false),
2207            },
2208        };
2209        if let Some(provisional) = self.provisional.take() {
2210            nodes.adopt(provisional)?;
2211        }
2212        self.interner = Some(nodes);
2213        Ok(true)
2214    }
2215
2216    fn push(&mut self, src: &dyn Array, dst: &dyn Array) -> std::result::Result<(), IdError> {
2217        match (&mut self.interner, &mut self.provisional) {
2218            (Some(interner), _) => interner.push(src, dst),
2219            (None, Some(provisional)) => provisional.push(src, dst),
2220            (None, None) => unreachable!("edges interned before the node set, or into it"),
2221        }
2222    }
2223}
2224
2225/// Intern the edges `rx` brings, on a thread of their own (see
2226/// [`build_streamed`]); the index once every row has been read, `None` if a
2227/// read stopped first (its error is the one reported).
2228#[cfg(not(target_arch = "wasm32"))]
2229fn intern_edges(
2230    mut rx: tokio::sync::mpsc::Receiver<Chunk>,
2231    nodes: Option<tokio::sync::oneshot::Receiver<EdgeInterner>>,
2232    hint: usize,
2233    graph: &str,
2234    id_type: &DataType,
2235    notifier: &Notifier,
2236) -> Result<Option<GraphIndex>> {
2237    let error = |e| build_error(graph, e);
2238    let mut side = EdgeSide::new(nodes, hint);
2239    while let Some(chunk) = rx.blocking_recv() {
2240        if !side.take_nodes(false).map_err(error)? {
2241            return Ok(None);
2242        }
2243        match chunk {
2244            Chunk::Edges(src, dst) => side.push(src.as_ref(), dst.as_ref()).map_err(error)?,
2245            Chunk::End => {
2246                if !side.take_nodes(true).map_err(error)? {
2247                    return Ok(None);
2248                }
2249                let interner = side.interner.take().expect("the node set is taken in");
2250                return Ok(Some(finish_index(interner, id_type, notifier)));
2251            }
2252            Chunk::Nodes(_) | Chunk::NodesDone => {
2253                return Err(DataFusionError::Internal(format!(
2254                    "building graph '{graph}': a vertex key chunk reached the edges"
2255                )))
2256            }
2257        }
2258    }
2259    Ok(None)
2260}
2261
2262/// Build the index of the edge rows `input` produces, interning each chunk
2263/// as it is read rather than collecting every endpoint array first, so the
2264/// Arrow input does not accumulate: the build holds the dense endpoints, a
2265/// chunk or two in flight, and what the partitions decoded ahead of their
2266/// turn hold, within the session's read-ahead ([`read_ahead`]). The
2267/// partitions decode in parallel and are interned in partition order
2268/// ([`InOrder`]), and reading (here) and interning (on a blocking thread)
2269/// overlap. The rows are interned in the order [`drain`] would collect them,
2270/// so the index is the one `ursa_io::build_topology_batches` gives over the
2271/// collected rows. A weighted node's weights are read from the same rows
2272/// (`weights`), and with a vertex table kept only for the edges kept (see
2273/// the module docs).
2274///
2275/// A vertex table's keys number the nodes, in the order they are read, and
2276/// an edge between two keys is kept. The keys used to be read and interned
2277/// first, then the edges; now (#385) both are read and interned at once, on
2278/// two threads: the keys into their interner, the edges into a provisional
2279/// one ([`EdgeInterner::provisional`]) until the last key is in. Then the
2280/// edges interned so far are renumbered into the keys' numbering
2281/// ([`EdgeInterner::adopt`]), and the rest go straight into it. The index is
2282/// exactly the one interning the keys first gives, wherever that switch
2283/// falls. The two reads share the read-ahead: a quarter for the keys, the
2284/// rest for the edges. In the browser (wasm32), with one thread, the keys
2285/// are still read first.
2286async fn build_streamed(
2287    shape: &Edges,
2288    input: &Arc<dyn ExecutionPlan>,
2289    endpoints: (usize, usize),
2290    context: &Arc<TaskContext>,
2291    weights: &mut WeightReader,
2292) -> Result<GraphIndex> {
2293    let partitions = input.output_partitioning().partition_count();
2294    let read_ahead = read_ahead(context.session_config(), partitions);
2295    build_streamed_with(shape, input, endpoints, context, weights, read_ahead).await
2296}
2297
2298/// [`build_streamed`], reading the partitions in parallel within
2299/// `read_ahead` bytes (see [`InOrder`]), or one after another with `None`:
2300/// the index is the same either way.
2301async fn build_streamed_with(
2302    shape: &Edges,
2303    input: &Arc<dyn ExecutionPlan>,
2304    endpoints: (usize, usize),
2305    context: &Arc<TaskContext>,
2306    weights: &mut WeightReader,
2307    read_ahead: Option<usize>,
2308) -> Result<GraphIndex> {
2309    let hint = row_hint(input);
2310    let (key_budget, edge_budget) = match (&shape.vertices, read_ahead) {
2311        (Some(_), Some(bytes)) => (Some(bytes / 4), Some(bytes - bytes / 4)),
2312        _ => (read_ahead, read_ahead),
2313    };
2314    let edges = InOrder::with_budget(input, context, edge_budget);
2315
2316    // Native: the keys are read on a task of their own and interned on a
2317    // thread of their own, while the edges are read here and interned on a
2318    // third (see the docs above). The threads are spawned before the reads
2319    // start (`run_blocking` would start one only when awaited).
2320    #[cfg(not(target_arch = "wasm32"))]
2321    let (read, built) = {
2322        use datafusion::common::runtime::SpawnedTask;
2323        let failed = |e: tokio::task::JoinError| {
2324            DataFusionError::Execution(format!("building graph '{}' failed: {e}", shape.graph))
2325        };
2326        let (tx, rx) = tokio::sync::mpsc::channel::<Chunk>(2);
2327        let mut keys = None;
2328        let mut nodes = None;
2329        if let Some(vertices) = &shape.vertices {
2330            let (keys_tx, keys_rx) = tokio::sync::mpsc::channel::<Chunk>(2);
2331            let (done_tx, done_rx) = tokio::sync::oneshot::channel();
2332            nodes = Some(done_rx);
2333            let (graph, id_type) = (shape.graph.clone(), shape.id_type.clone());
2334            let unique = vertices.unique.clone();
2335            let interning = tokio::task::spawn_blocking(move || {
2336                intern_keys(keys_rx, done_tx, hint, &graph, &id_type, unique.as_ref())
2337            });
2338            let batches = InOrder::with_budget(&vertices.plan, context, key_budget);
2339            let id_type = shape.id_type.clone();
2340            let reading =
2341                SpawnedTask::spawn(async move { send_keys(batches, &id_type, &keys_tx).await });
2342            keys = Some((reading, interning));
2343        }
2344        let (graph, id_type) = (shape.graph.clone(), shape.id_type.clone());
2345        let notifier = Notifier::of(context.session_config());
2346        let interning = tokio::task::spawn_blocking(move || {
2347            intern_edges(rx, nodes, hint, &graph, &id_type, &notifier)
2348        });
2349        // The reader owns the sender, so the interner sees the channel close
2350        // when the reader stops, on an error as at the end.
2351        let edges_read = send_edges(edges, shape, endpoints, weights, &tx).await;
2352        drop(tx);
2353        // A key's error comes first, as when the keys were read first.
2354        let keys_done = match keys {
2355            Some((reading, interning)) => {
2356                let read = reading.join().await.map_err(failed)?;
2357                let interned = interning.await.map_err(failed)?;
2358                read.and(interned)
2359            }
2360            None => Ok(()),
2361        };
2362        let built = interning.await.map_err(failed)?;
2363        (keys_done.and(edges_read), built)
2364    };
2365
2366    // The browser (wasm32) has one thread: the interner is a future polled
2367    // alongside the reader, taking each chunk as it is sent, the keys first.
2368    // The channel's bound still keeps at most two chunks in flight, and the
2369    // chunks arrive in the same order, so the index is the same (#278).
2370    #[cfg(target_arch = "wasm32")]
2371    let (read, built) = {
2372        let (tx, mut rx) = tokio::sync::mpsc::channel::<Chunk>(2);
2373        let (graph, id_type) = (shape.graph.clone(), shape.id_type.clone());
2374        let unique = shape.vertices.as_ref().and_then(|v| v.unique.clone());
2375        let interning = async move {
2376            let mut interner = EdgeInterner::with_capacity(hint);
2377            while let Some(chunk) = rx.recv().await {
2378                if let Some(index) =
2379                    take_chunk(&mut interner, chunk, &graph, &id_type, unique.as_ref())?
2380                {
2381                    return Ok(Some(index));
2382                }
2383            }
2384            Ok::<_, DataFusionError>(None)
2385        };
2386        let read = async {
2387            let tx = tx;
2388            if let Some(vertices) = &shape.vertices {
2389                let batches = InOrder::with_budget(&vertices.plan, context, key_budget);
2390                send_keys(batches, &shape.id_type, &tx).await?;
2391            }
2392            send_edges(edges, shape, endpoints, weights, &tx).await
2393        };
2394        futures::join!(read, interning)
2395    };
2396    read?;
2397    let index = built?.ok_or_else(|| {
2398        DataFusionError::Internal(format!(
2399            "building graph '{}' stopped before the last edge",
2400            shape.graph
2401        ))
2402    })?;
2403    if let Some(kept) = index.kept_rows() {
2404        weights.keep(kept);
2405    }
2406    Ok(index)
2407}
2408
2409/// Checks, a chunk at a time, that rows are the edge rows an index was
2410/// built from, in order.
2411struct RowCheck<'a> {
2412    index: &'a GraphIndex,
2413    /// Each row's endpoints as dense ids, from the CSR and its row
2414    /// permutation.
2415    source: Vec<u32>,
2416    destination: Vec<u32>,
2417    /// Rows checked so far.
2418    start: usize,
2419}
2420
2421impl<'a> RowCheck<'a> {
2422    fn new(index: &'a GraphIndex) -> Self {
2423        let topology = &index.topology;
2424        let n = topology.n_edges();
2425        let out = topology.out();
2426        let (mut source, mut destination) = (vec![0u32; n], vec![0u32; n]);
2427        for u in 0..topology.n_nodes() {
2428            let slots = out.offsets[u] as usize..out.offsets[u + 1] as usize;
2429            for slot in slots {
2430                let row = out.edge_ids[slot] as usize;
2431                source[row] = u as u32;
2432                destination[row] = out.targets[slot];
2433            }
2434        }
2435        Self {
2436            index,
2437            source,
2438            destination,
2439            start: 0,
2440        }
2441    }
2442
2443    /// Whether the next rows are `src` → `dst`. Each chunk's ids are
2444    /// compared on their own, so no column of every row's ids is made.
2445    fn check(&mut self, src: &ArrayRef, dst: &ArrayRef) -> Result<bool> {
2446        let rows = self.start..self.start + src.len();
2447        if rows.end > self.source.len() {
2448            return Ok(false);
2449        }
2450        self.start = rows.end;
2451        let ids = &self.index.ids;
2452        let user_type = ids.user_type();
2453        Ok(
2454            ids.gather_user(&self.source[rows.clone()]).as_ref() == cast(src, &user_type)?.as_ref()
2455                && ids.gather_user(&self.destination[rows]).as_ref()
2456                    == cast(dst, &user_type)?.as_ref(),
2457        )
2458    }
2459
2460    /// Whether every row of the index has been checked.
2461    fn complete(&self) -> bool {
2462        self.start == self.source.len()
2463    }
2464}
2465
2466/// Whether `endpoints` are the edge rows `index` was built from, row for row.
2467#[cfg(test)]
2468fn aligned(index: &GraphIndex, endpoints: &[(ArrayRef, ArrayRef)]) -> Result<bool> {
2469    let mut rows = RowCheck::new(index);
2470    for (src, dst) in endpoints {
2471        if !rows.check(src, dst)? {
2472            return Ok(false);
2473        }
2474    }
2475    Ok(rows.complete())
2476}
2477
2478/// A weight expression's values, one `f64` per edge row, checked as
2479/// `ursa-plan`'s `evaluate_weight` checks them, with its messages.
2480#[cfg(test)]
2481fn edge_weights(columns: &[ArrayRef]) -> Result<Vec<f64>> {
2482    let mut out = Vec::with_capacity(columns.iter().map(|c| c.len()).sum());
2483    for column in columns {
2484        extend_weights(column, &mut out)?;
2485    }
2486    Ok(out)
2487}
2488
2489/// Append one chunk of a weight expression's values to `out`, checked as
2490/// `ursa-plan`'s `evaluate_weight` checks them, with its messages.
2491fn extend_weights(column: &ArrayRef, out: &mut Vec<f64>) -> Result<()> {
2492    let column = cast(column, &DataType::Float64)?;
2493    let column = column
2494        .as_any()
2495        .downcast_ref::<Float64Array>()
2496        .expect("cast to Float64 yields Float64Array");
2497    if column.null_count() > 0 {
2498        return Err(DataFusionError::Execution(
2499            "weight expression produced a null value; weights must be non-null".into(),
2500        ));
2501    }
2502    let values = column.values();
2503    if let Some(&w) = values.iter().find(|&&w| w < 0.0) {
2504        return Err(DataFusionError::Execution(format!(
2505            "weight expression produced a negative value ({w}); weights must be \
2506             non-negative"
2507        )));
2508    }
2509    out.extend_from_slice(values);
2510    Ok(())
2511}
2512
2513fn build_error(graph: &str, e: IdError) -> DataFusionError {
2514    DataFusionError::Execution(match e {
2515        IdError::Null => format!(
2516            "graph '{graph}': an edge has a null source or destination; filter those rows out \
2517             of the edge table (for example, with a view that keeps rows WHERE both are NOT NULL)"
2518        ),
2519        other => format!("graph '{graph}': {other}"),
2520    })
2521}
2522
2523#[cfg(test)]
2524mod tests {
2525    use super::*;
2526    use crate::graph::in_order::MAX_READ_AHEAD;
2527    use datafusion::arrow::array::{Int64Array, StringArray};
2528
2529    fn index(src: &dyn Array, dst: &dyn Array) -> GraphIndex {
2530        let (topology, ids) = ursa_io::build_topology_batches(&[(src, dst)]).unwrap();
2531        GraphIndex::new(topology, ids)
2532    }
2533
2534    fn ints(v: &[i64]) -> ArrayRef {
2535        Arc::new(Int64Array::from(v.to_vec()))
2536    }
2537
2538    #[test]
2539    fn weights_line_up_only_with_the_rows_the_index_was_built_from() {
2540        let (src, dst) = (ints(&[10, 20, 10, 30]), ints(&[20, 30, 30, 10]));
2541        let built = index(src.as_ref(), dst.as_ref());
2542        // The same rows, in two batches: aligned.
2543        let split = vec![
2544            (src.slice(0, 1), dst.slice(0, 1)),
2545            (src.slice(1, 3), dst.slice(1, 3)),
2546        ];
2547        assert!(aligned(&built, &split).unwrap());
2548        // The same edge set in another order: not.
2549        let swapped = vec![(ints(&[20, 10, 10, 30]), ints(&[30, 20, 30, 10]))];
2550        assert!(!aligned(&built, &swapped).unwrap());
2551        // Fewer rows: not.
2552        assert!(!aligned(&built, &split[1..]).unwrap());
2553
2554        let names = |v: &[&str]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
2555        let (s, d) = (names(&["a", "b"]), names(&["b", "c"]));
2556        let built = index(s.as_ref(), d.as_ref());
2557        assert!(aligned(&built, &[(Arc::clone(&s), Arc::clone(&d))]).unwrap());
2558        assert!(!aligned(&built, &[(d, s)]).unwrap());
2559    }
2560
2561    /// The bytes a database stores `index` as.
2562    fn stored_bytes(index: &GraphIndex) -> Vec<u8> {
2563        let key = crate::database::IndexKey::new("edges".into(), Vec::new());
2564        let encoded =
2565            crate::database::index_file::Encoded::new(&key, &index.topology, &index.ids).unwrap();
2566        let mut bytes = Vec::new();
2567        encoded.write_to(&mut bytes).unwrap();
2568        bytes
2569    }
2570
2571    /// A session over a Parquet file of many row groups, split into several
2572    /// partitions, and the plan of its edges behind a filter no statistics
2573    /// prune.
2574    async fn filtered_edges() -> (tempfile::TempDir, Arc<dyn ExecutionPlan>, Arc<TaskContext>) {
2575        use datafusion::prelude::SessionConfig;
2576        let dir = tempfile::tempdir().unwrap();
2577        let mut config = SessionConfig::new().with_target_partitions(8);
2578        config.options_mut().optimizer.repartition_file_min_size = 1;
2579        let ctx = crate::new_session_with_config(config);
2580        let file = dir.path().join("edges.parquet");
2581        let sql = [
2582            "SET datafusion.execution.parquet.max_row_group_size = 4096".to_string(),
2583            // Ids scattered over the rows, so first-seen order numbers them
2584            // differently from sorted order.
2585            format!(
2586                "COPY (SELECT (value * 7919) % 50021 AS s, (value * 104729 + 13) % 50021 AS d \
2587                 FROM generate_series(0, 299999)) TO '{}'",
2588                file.display()
2589            ),
2590        ];
2591        for sql in sql {
2592            ctx.sql(&sql).await.unwrap().collect().await.unwrap();
2593        }
2594        let plan = ctx
2595            .sql(&format!(
2596                "SELECT s, d FROM '{}' WHERE s % 7 <> 3",
2597                file.display()
2598            ))
2599            .await
2600            .unwrap()
2601            .create_physical_plan()
2602            .await
2603            .unwrap();
2604        (dir, plan, ctx.task_ctx())
2605    }
2606
2607    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
2608    async fn an_index_built_from_partitions_read_in_parallel_is_the_serial_one() {
2609        let (_dir, plan, context) = filtered_edges().await;
2610        let partitions = plan.output_partitioning().partition_count();
2611        assert!(partitions > 1, "{partitions} partition(s)");
2612        let shape = Edges {
2613            graph: "g".into(),
2614            endpoints: (0, 1),
2615            id_type: DataType::Int64,
2616            fingerprint: None,
2617            vertices: None,
2618        };
2619        let build = |read_ahead| {
2620            let (shape, plan, context) = (shape.clone(), Arc::clone(&plan), Arc::clone(&context));
2621            async move {
2622                let mut no_weights = WeightReader::new(&[], 0);
2623                build_streamed_with(&shape, &plan, (0, 1), &context, &mut no_weights, read_ahead)
2624                    .await
2625                    .unwrap()
2626            }
2627        };
2628        let serial = build(None).await;
2629        assert!(serial.topology.n_edges() > 200_000);
2630        // The serial build is the one over the rows collected in order.
2631        let rows = drain(&plan, &[0, 1], &context).await.unwrap();
2632        let rows: Vec<(&dyn Array, &dyn Array)> = rows
2633            .iter()
2634            .map(|c| (c[0].as_ref(), c[1].as_ref()))
2635            .collect();
2636        let (ids, s, d) = IdMap::from_edge_batches(&rows).unwrap();
2637        let (topology, ids) = relabelled(ids, s, d, &Notifier::silent());
2638        let collected = GraphIndex::new(Arc::new(topology), Arc::new(ids));
2639        let expected = stored_bytes(&serial);
2640        assert_eq!(stored_bytes(&collected), expected);
2641        // In parallel, with room to read ahead and with none: the same node
2642        // numbering, the same CSR, the same stored bytes.
2643        for read_ahead in [Some(MAX_READ_AHEAD), Some(1)] {
2644            let parallel = build(read_ahead).await;
2645            assert_eq!(
2646                parallel.ids.user_id_array().as_ref(),
2647                serial.ids.user_id_array().as_ref(),
2648                "node numbering, read ahead {read_ahead:?}"
2649            );
2650            assert_eq!(
2651                stored_bytes(&parallel),
2652                expected,
2653                "read ahead {read_ahead:?}"
2654            );
2655        }
2656    }
2657
2658    /// The plan of a vertex table of `keys` keys written as `file` (by its
2659    /// extension: CSV, gzipped CSV or Parquet of many row groups), read in
2660    /// several partitions where the format splits.
2661    async fn vertex_keys(dir: &std::path::Path, file: &str) -> Arc<dyn ExecutionPlan> {
2662        use datafusion::prelude::SessionConfig;
2663        let mut config = SessionConfig::new().with_target_partitions(8);
2664        config.options_mut().optimizer.repartition_file_min_size = 1;
2665        let ctx = crate::new_session_with_config(config);
2666        let path = dir.join(file);
2667        // Keys scattered over a range wider than the edges' ids, so some keys
2668        // are on no edge and some edges have an endpoint that is no key.
2669        let keys = "SELECT (value * 31337) % 60013 AS id FROM generate_series(0, 45000)";
2670        let copy = match file {
2671            f if f.ends_with(".csv.gz") => format!(
2672                "COPY ({keys}) TO '{}' STORED AS CSV OPTIONS ('format.compression' 'gzip')",
2673                path.display()
2674            ),
2675            f if f.ends_with(".csv") => {
2676                format!("COPY ({keys}) TO '{}' STORED AS CSV", path.display())
2677            }
2678            _ => format!("COPY ({keys}) TO '{}'", path.display()),
2679        };
2680        for sql in [
2681            "SET datafusion.execution.parquet.max_row_group_size = 2048".to_string(),
2682            copy,
2683        ] {
2684            ctx.sql(&sql).await.unwrap().collect().await.unwrap();
2685        }
2686        ctx.sql(&format!("SELECT id FROM '{}'", path.display()))
2687            .await
2688            .unwrap()
2689            .create_physical_plan()
2690            .await
2691            .unwrap()
2692    }
2693
2694    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
2695    async fn keys_and_edges_interned_at_once_build_the_index_keys_first_did() {
2696        let (dir, plan, context) = filtered_edges().await;
2697        for file in ["keys.csv", "keys.csv.gz", "keys.parquet"] {
2698            let vertices = vertex_keys(dir.path(), file).await;
2699            let shape = Edges {
2700                graph: "g".into(),
2701                endpoints: (0, 1),
2702                id_type: DataType::Int64,
2703                fingerprint: None,
2704                vertices: Some(VertexInput {
2705                    plan: vertices,
2706                    fingerprint: None,
2707                    unique: None,
2708                }),
2709            };
2710            let build = |read_ahead| {
2711                let (shape, plan, context) =
2712                    (shape.clone(), Arc::clone(&plan), Arc::clone(&context));
2713                async move {
2714                    let mut no_weights = WeightReader::new(&[], 0);
2715                    build_streamed_with(
2716                        &shape,
2717                        &plan,
2718                        (0, 1),
2719                        &context,
2720                        &mut no_weights,
2721                        read_ahead,
2722                    )
2723                    .await
2724                    .unwrap()
2725                }
2726            };
2727            // The index as the build made it before #385: every key interned,
2728            // then every edge, in the order a serial read gives them.
2729            let mut interner = EdgeInterner::with_capacity(0);
2730            for keys in drain(&shape.vertices.as_ref().unwrap().plan, &[0], &context)
2731                .await
2732                .unwrap()
2733            {
2734                let keys = cast(&keys[0], &DataType::Int64).unwrap();
2735                interner.push_nodes(keys.as_ref()).unwrap();
2736            }
2737            interner.close_nodes();
2738            for edges in drain(&plan, &[0, 1], &context).await.unwrap() {
2739                interner.push(edges[0].as_ref(), edges[1].as_ref()).unwrap();
2740            }
2741            let before = finish_index(interner, &DataType::Int64, &Notifier::silent());
2742            assert!(before.ids.len() > 45_000, "{file}: {}", before.ids.len());
2743            assert!(before.n_dropped() > 0, "{file}");
2744            assert!(before.topology.n_edges() > 100_000, "{file}");
2745            let expected = stored_bytes(&before);
2746            // The keys and the edges read and interned at once: serially, in
2747            // parallel with room to read ahead, with little, and with none.
2748            // Wherever the edges switch from provisional interning to the
2749            // keys' numbering, the same node numbering, the same edges kept
2750            // and the same stored bytes.
2751            for _ in 0..3 {
2752                for read_ahead in [None, Some(MAX_READ_AHEAD), Some(1 << 20), Some(1), Some(0)] {
2753                    let built = build(read_ahead).await;
2754                    assert_eq!(
2755                        built.ids.user_id_array().as_ref(),
2756                        before.ids.user_id_array().as_ref(),
2757                        "{file}: node numbering, read ahead {read_ahead:?}"
2758                    );
2759                    assert_eq!(
2760                        (built.n_dropped(), built.kept_rows()),
2761                        (before.n_dropped(), before.kept_rows()),
2762                        "{file}: edges kept, read ahead {read_ahead:?}"
2763                    );
2764                    assert_eq!(
2765                        stored_bytes(&built),
2766                        expected,
2767                        "{file}: read ahead {read_ahead:?}"
2768                    );
2769                }
2770            }
2771        }
2772    }
2773
2774    #[cfg(unix)]
2775    #[test]
2776    fn an_index_whose_rows_cannot_be_spilled_keeps_its_ids_with_a_notice() {
2777        let said = Arc::new(Mutex::new(Vec::<String>::new()));
2778        let sink = Arc::clone(&said);
2779        let notifier = Notifier::new(
2780            Arc::new(move |s: &str| sink.lock().unwrap().push(s.to_string())),
2781            NoticeLevel::On,
2782        );
2783        let missing = std::env::temp_dir().join("ursa-no-such-dir-170-engine");
2784        assert!(spill_in(&missing, &[2, 1, 0], &notifier).is_none());
2785        let said = said.lock().unwrap().clone();
2786        assert_eq!(said.len(), 1, "{said:?}");
2787        assert!(said[0].starts_with("could not write the index's edge rows to "));
2788        assert!(
2789            said[0].ends_with("its edge ids are kept in memory (12 B)"),
2790            "{said:?}"
2791        );
2792        // A writable directory spills, and says nothing.
2793        let dir = tempfile::tempdir().unwrap();
2794        let quiet = Notifier::silent();
2795        let rows = spill_in(dir.path(), &[2, 1, 0], &quiet).expect("spilled");
2796        assert_eq!(rows.sources(), vec![2, 1, 0]);
2797        // The file is unlinked as soon as it is written.
2798        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
2799    }
2800
2801    #[test]
2802    fn weights_are_checked_as_ursa_plan_checks_them() {
2803        let ok = edge_weights(&[ints(&[1, 2]), ints(&[0])]).unwrap();
2804        assert_eq!(ok, vec![1.0, 2.0, 0.0]);
2805        let negative = edge_weights(&[ints(&[1, -1])]).unwrap_err();
2806        assert_eq!(
2807            crate::user_message(&negative),
2808            "weight expression produced a negative value (-1); weights must be non-negative"
2809        );
2810        let null: ArrayRef = Arc::new(Int64Array::from(vec![Some(1), None]));
2811        assert_eq!(
2812            crate::user_message(&edge_weights(&[null]).unwrap_err()),
2813            "weight expression produced a null value; weights must be non-null"
2814        );
2815    }
2816}