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