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::{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::{InOrder, READ_AHEAD_BYTES};
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::traversal::{self, Traversal, TraversalParam, TraversalParamType};
110
111/// Plans Ursa's graph nodes.
112#[derive(Debug)]
113pub struct GraphPlanner;
114
115#[async_trait]
116impl ExtensionPlanner for GraphPlanner {
117    async fn plan_extension(
118        &self,
119        _planner: &dyn PhysicalPlanner,
120        node: &dyn UserDefinedLogicalNode,
121        logical_inputs: &[&LogicalPlan],
122        physical_inputs: &[Arc<dyn ExecutionPlan>],
123        session_state: &dyn Session,
124        _planning_ctx: &PhysicalPlanningContext,
125    ) -> Result<Option<Arc<dyn ExecutionPlan>>> {
126        if let Some(node) = node.as_any().downcast_ref::<GraphTraversalNode>() {
127            return plan_traversal(node, logical_inputs, physical_inputs).map(Some);
128        }
129        if let Some(node) = node.as_any().downcast_ref::<PathSearchNode>() {
130            let mut exec = plan_path_search(node, logical_inputs, physical_inputs)?;
131            exec.held = held_index(&exec.shape.edges, &exec.input, session_state).await;
132            return Ok(Some(Arc::new(exec)));
133        }
134        let Some(node) = node.as_any().downcast_ref::<GraphAlgorithmNode>() else {
135            return Ok(None);
136        };
137        let (source, destination) = node.endpoint_indices()?;
138        let mut next = 1;
139        let weighted = match (
140            &node.weighted,
141            logical_inputs.get(next),
142            physical_inputs.get(next),
143        ) {
144            (Some(_), Some(logical), Some(physical)) => {
145                next += 1;
146                Some(weighted_input(logical, physical, node.weights.len())?)
147            }
148            _ => None,
149        };
150        let vertices = vertex_input(
151            node.vertices.is_some(),
152            logical_inputs,
153            physical_inputs,
154            next,
155        )?;
156        // A neighbour aggregation's node values are the last input.
157        let values = node
158            .values
159            .as_ref()
160            .and_then(|_| physical_inputs.last().cloned());
161        Ok(Some(Arc::new(GraphAlgorithmExec::new(
162            Shape {
163                edges: Edges {
164                    graph: node.graph.clone(),
165                    endpoints: (source, destination),
166                    id_type: node.id_type.clone(),
167                    fingerprint: fingerprint(logical_inputs[0]),
168                    vertices,
169                },
170                outputs: node.outputs.clone(),
171                per_node: node.per_node,
172                display: node.display_outputs(),
173                schema: Arc::new(node.schema().as_arrow().clone()),
174            },
175            Arc::clone(&physical_inputs[0]),
176            weighted,
177            values,
178        ))))
179    }
180}
181
182/// The vertex keys input at `at`, if the node has one.
183fn vertex_input(
184    has: bool,
185    logical_inputs: &[&LogicalPlan],
186    physical_inputs: &[Arc<dyn ExecutionPlan>],
187    at: usize,
188) -> Result<Option<VertexInput>> {
189    if !has {
190        return Ok(None);
191    }
192    match (logical_inputs.get(at), physical_inputs.get(at)) {
193        (Some(logical), Some(physical)) => Ok(Some(VertexInput {
194            plan: Arc::clone(physical),
195            fingerprint: fingerprint(logical),
196        })),
197        _ => Err(DataFusionError::Internal(
198            "a graph node's vertex keys were not planned".to_string(),
199        )),
200    }
201}
202
203/// The weighted edge plan `physical` (planned from `logical`), with
204/// `n_weights` weight columns.
205fn weighted_input(
206    logical: &LogicalPlan,
207    physical: &Arc<dyn ExecutionPlan>,
208    n_weights: usize,
209) -> Result<WeightedInput> {
210    let schema = logical.schema();
211    let column = |name: &str| schema.index_of_column_by_name(None, name);
212    let missing =
213        |name: &str| DataFusionError::Internal(format!("the weighted edge plan has no {name}"));
214    let weights = (0..n_weights)
215        .map(|i| {
216            let name = weight_column(i);
217            column(&name).ok_or_else(|| missing(&name))
218        })
219        .collect::<Result<Vec<_>>>()?;
220    Ok(WeightedInput {
221        plan: Arc::clone(physical),
222        source: column(WEIGHTED_SOURCE).ok_or_else(|| missing(WEIGHTED_SOURCE))?,
223        destination: column(WEIGHTED_DESTINATION).ok_or_else(|| missing(WEIGHTED_DESTINATION))?,
224        weights,
225        fingerprint: fingerprint(logical),
226    })
227}
228
229/// The exec of a traversal node.
230fn plan_traversal(
231    node: &GraphTraversalNode,
232    logical_inputs: &[&LogicalPlan],
233    physical_inputs: &[Arc<dyn ExecutionPlan>],
234) -> Result<Arc<dyn ExecutionPlan>> {
235    let expected = 1
236        + usize::from(node.weighted.is_some())
237        + usize::from(node.vertices.is_some())
238        + node.nodes.len();
239    if logical_inputs.len() != expected || physical_inputs.len() != expected {
240        return Err(DataFusionError::Internal(format!(
241            "GraphTraversal has {expected} inputs; planned {}",
242            physical_inputs.len()
243        )));
244    }
245    let (source, destination) = node.endpoint_indices()?;
246    let mut next = 1;
247    let weighted = match node.weighted {
248        Some(_) => {
249            next += 1;
250            Some(weighted_input(logical_inputs[1], &physical_inputs[1], 1)?)
251        }
252        None => None,
253    };
254    let vertices = vertex_input(
255        node.vertices.is_some(),
256        logical_inputs,
257        physical_inputs,
258        next,
259    )?;
260    next += usize::from(vertices.is_some());
261    Ok(Arc::new(GraphTraversalExec::new(
262        TraversalShape {
263            edges: Edges {
264                graph: node.graph.clone(),
265                endpoints: (source, destination),
266                id_type: node.id_type.clone(),
267                fingerprint: fingerprint(logical_inputs[0]),
268                vertices,
269            },
270            traversal: node.traversal,
271            display: node.display_call(),
272            schema: Arc::new(node.schema().as_arrow().clone()),
273        },
274        Arc::clone(&physical_inputs[0]),
275        weighted,
276        physical_inputs[next..].to_vec(),
277    )))
278}
279
280/// Where the session keeps the index of the edges `input` reads, if it
281/// does: then running the node reads none of its edge or vertex inputs.
282async fn held_index(
283    shape: &Edges,
284    input: &Arc<dyn ExecutionPlan>,
285    session: &dyn Session,
286) -> Option<IndexHeld> {
287    let context = session.task_ctx();
288    let cache = context.session_config().get_extension::<IndexCache>()?;
289    let key = index_key(shape, input, &context).await.ok()??;
290    cache.holds(context.session_config(), &key)
291}
292
293fn plan_path_search(
294    node: &PathSearchNode,
295    logical_inputs: &[&LogicalPlan],
296    physical_inputs: &[Arc<dyn ExecutionPlan>],
297) -> Result<PathSearchExec> {
298    let expected = 2 + usize::from(node.vertices.is_some()) + usize::from(node.targets.is_some());
299    if physical_inputs.len() != expected || logical_inputs.len() != expected {
300        return Err(DataFusionError::Internal(format!(
301            "PathSearch has {expected} inputs; planned {}",
302            physical_inputs.len()
303        )));
304    }
305    let vertices = vertex_input(node.vertices.is_some(), logical_inputs, physical_inputs, 1)?;
306    let starts = 1 + usize::from(vertices.is_some());
307    Ok(PathSearchExec::new(
308        PathShape {
309            edges: Edges {
310                graph: node.graph.clone(),
311                endpoints: node.endpoint_indices()?,
312                id_type: node.id_type.clone(),
313                fingerprint: fingerprint(logical_inputs[0]),
314                vertices,
315            },
316            search: node.search,
317            columns: node.columns,
318            known_only: node.known_only,
319            schema: Arc::new(node.schema().as_arrow().clone()),
320        },
321        Arc::clone(&physical_inputs[0]),
322        Arc::clone(&physical_inputs[starts]),
323        node.targets
324            .as_ref()
325            .map(|_| Arc::clone(&physical_inputs[starts + 1])),
326    ))
327}
328
329#[derive(Debug, Clone)]
330struct PathShape {
331    edges: Edges,
332    search: Search,
333    columns: PathColumns,
334    known_only: bool,
335    schema: SchemaRef,
336}
337
338/// Builds or fetches a graph index from its first child's edge rows, reads
339/// the start nodes its next child produces (and the targets its last, if it
340/// has them), and searches paths from them (see [`super::path_search`]).
341/// `EXPLAIN ANALYZE` shows how many path prefixes it extended (`expanded`).
342/// When the session held the index as the node was planned, `EXPLAIN` says
343/// so (`index=stored (sources not read)`): its edge and vertex inputs are
344/// drawn, but do not run (#351).
345#[derive(Debug)]
346pub struct PathSearchExec {
347    shape: PathShape,
348    input: Arc<dyn ExecutionPlan>,
349    starts: Arc<dyn ExecutionPlan>,
350    targets: Option<Arc<dyn ExecutionPlan>>,
351    /// Where the session kept the index when the node was planned.
352    held: Option<IndexHeld>,
353    properties: Arc<PlanProperties>,
354    metrics: ExecutionPlanMetricsSet,
355}
356
357impl PathSearchExec {
358    fn new(
359        shape: PathShape,
360        input: Arc<dyn ExecutionPlan>,
361        starts: Arc<dyn ExecutionPlan>,
362        targets: Option<Arc<dyn ExecutionPlan>>,
363    ) -> Self {
364        let properties = Arc::new(PlanProperties::new(
365            EquivalenceProperties::new(Arc::clone(&shape.schema)),
366            Partitioning::UnknownPartitioning(1),
367            EmissionType::Final,
368            Boundedness::Bounded,
369        ));
370        Self {
371            shape,
372            input,
373            starts,
374            targets,
375            held: None,
376            properties,
377            metrics: ExecutionPlanMetricsSet::new(),
378        }
379    }
380}
381
382impl DisplayAs for PathSearchExec {
383    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
384        write!(
385            f,
386            "PathSearchExec: graph={}, search={}{}",
387            self.shape.edges.graph,
388            self.shape.search,
389            if self.targets.is_some() {
390                ", targets"
391            } else {
392                ""
393            }
394        )?;
395        if let Some(held) = self.held {
396            write!(f, ", index={held} (sources not read)")?;
397        }
398        Ok(())
399    }
400}
401
402impl ExecutionPlan for PathSearchExec {
403    fn name(&self) -> &str {
404        "PathSearchExec"
405    }
406
407    fn properties(&self) -> &Arc<PlanProperties> {
408        &self.properties
409    }
410
411    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
412        let mut children = vec![&self.input];
413        children.extend(self.shape.edges.vertices.as_ref().map(|v| &v.plan));
414        children.push(&self.starts);
415        children.extend(self.targets.as_ref());
416        children
417    }
418
419    fn metrics(&self) -> Option<MetricsSet> {
420        Some(self.metrics.clone_inner())
421    }
422
423    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
424        vec![false; self.children().len()]
425    }
426
427    fn apply_expressions(
428        &self,
429        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
430    ) -> Result<TreeNodeRecursion> {
431        Ok(TreeNodeRecursion::Continue)
432    }
433
434    fn with_new_children(
435        self: Arc<Self>,
436        children: Vec<Arc<dyn ExecutionPlan>>,
437    ) -> Result<Arc<dyn ExecutionPlan>> {
438        let expected = self.children().len();
439        if children.len() != expected {
440            return Err(DataFusionError::Internal(format!(
441                "PathSearchExec has {expected} children; got {}",
442                children.len()
443            )));
444        }
445        let mut children = children.into_iter();
446        let input = children.next().expect("checked above");
447        let mut shape = self.shape.clone();
448        shape.edges.vertices = shape.edges.vertices.map(|v| VertexInput {
449            plan: children.next().expect("checked above"),
450            ..v
451        });
452        let starts = children.next().expect("checked above");
453        let targets = self.targets.as_ref().and_then(|_| children.next());
454        let mut exec = Self::new(shape, input, starts, targets);
455        exec.held = self.held;
456        Ok(Arc::new(exec))
457    }
458
459    fn execute(
460        &self,
461        partition: usize,
462        context: Arc<TaskContext>,
463    ) -> Result<SendableRecordBatchStream> {
464        if partition != 0 {
465            return Err(DataFusionError::Internal(format!(
466                "PathSearchExec has one partition; asked for {partition}"
467            )));
468        }
469        let shape = self.shape.clone();
470        let input = Arc::clone(&self.input);
471        let starts = Arc::clone(&self.starts);
472        let targets = self.targets.clone();
473        let schema = Arc::clone(&shape.schema);
474        let expanded = MetricBuilder::new(&self.metrics).counter("expanded", partition);
475        let run = async move {
476            let index = unweighted_index(&shape.edges, input, &context).await?;
477            let starts = search_keys(&starts, "start nodes", &shape, &context).await?;
478            let targets = match &targets {
479                Some(t) => Some(search_keys(t, "target nodes", &shape, &context).await?),
480                None => None,
481            };
482            let out_schema = Arc::clone(&shape.schema);
483            let (batches, n) = crate::run_blocking(move || {
484                path_search::run(
485                    &index.topology,
486                    &index.ids,
487                    &|e| index.edge_row(e),
488                    &shape.search,
489                    &starts,
490                    targets.as_ref(),
491                    shape.known_only,
492                    shape.columns,
493                    out_schema,
494                )
495            })
496            .await
497            .map_err(|e| DataFusionError::Execution(format!("a path search failed: {e}")))??;
498            expanded.add(n);
499            Ok::<_, DataFusionError>(futures::stream::iter(batches.into_iter().map(Ok)))
500        };
501        Ok(Box::pin(RecordBatchStreamAdapter::new(
502            schema,
503            futures::stream::once(run).try_flatten(),
504        )))
505    }
506}
507
508/// The one column of keys `plan` gives (a search's `what`: its start or
509/// target nodes), cast to the graph's node id type.
510async fn search_keys(
511    plan: &Arc<dyn ExecutionPlan>,
512    what: &str,
513    shape: &PathShape,
514    context: &Arc<TaskContext>,
515) -> Result<ArrayRef> {
516    let batches = drain(plan, &[0], context).await?;
517    let id_type = &shape.edges.id_type;
518    let mut columns = Vec::with_capacity(batches.len());
519    for batch in &batches {
520        columns.push(cast(batch[0].as_ref(), id_type).map_err(|_| {
521            DataFusionError::Plan(format!(
522                "in GRAPH_TABLE: the {what}' keys ({}) cannot be read as graph '{}''s node ids ({id_type})",
523                batch[0].data_type(),
524                shape.edges.graph
525            ))
526        })?);
527    }
528    Ok(if columns.is_empty() {
529        new_empty_array(id_type)
530    } else {
531        let refs: Vec<&dyn Array> = columns.iter().map(|c| c.as_ref()).collect();
532        concat(&refs)?
533    })
534}
535
536/// A query planner whose physical planner knows Ursa's graph nodes.
537#[derive(Debug)]
538pub struct UrsaQueryPlanner;
539
540#[async_trait]
541impl QueryPlanner for UrsaQueryPlanner {
542    async fn create_physical_plan(
543        &self,
544        logical_plan: &LogicalPlan,
545        session_state: &dyn Session,
546    ) -> Result<Arc<dyn ExecutionPlan>> {
547        DefaultPhysicalPlanner::with_extension_planners(vec![Arc::new(GraphPlanner)])
548            .create_physical_plan(logical_plan, session_state)
549            .await
550    }
551}
552
553/// A graph node's edge input: where its endpoints are, and how its index is
554/// cached.
555#[derive(Debug, Clone)]
556struct Edges {
557    graph: String,
558    /// The source and destination columns of the first input.
559    endpoints: (usize, usize),
560    id_type: DataType,
561    /// The edge plan's fingerprint, or `None` if it cannot be cached.
562    fingerprint: Option<String>,
563    /// The graph's vertex keys, if it has a vertex table.
564    vertices: Option<VertexInput>,
565}
566
567/// A graph node's vertex keys: a plan of one column (see the module docs).
568#[derive(Debug, Clone)]
569struct VertexInput {
570    plan: Arc<dyn ExecutionPlan>,
571    /// The keys' plan's fingerprint, or `None` if it cannot be cached.
572    fingerprint: Option<String>,
573}
574
575/// What a [`GraphAlgorithmExec`] computes, besides its children.
576#[derive(Debug, Clone)]
577struct Shape {
578    edges: Edges,
579    outputs: Vec<Output>,
580    per_node: bool,
581    /// The outputs as `EXPLAIN` shows them.
582    display: String,
583    schema: SchemaRef,
584}
585
586/// The weighted edge plan, and where its columns are.
587#[derive(Debug, Clone)]
588struct WeightedInput {
589    plan: Arc<dyn ExecutionPlan>,
590    source: usize,
591    destination: usize,
592    /// One column per weight expression, in the node's order.
593    weights: Vec<usize>,
594    /// The weighted plan's fingerprint, or `None` if it cannot be cached.
595    fingerprint: Option<String>,
596}
597
598/// Builds or fetches a graph index from its child's edge rows, and runs
599/// graph functions over it.
600#[derive(Debug)]
601pub struct GraphAlgorithmExec {
602    shape: Shape,
603    input: Arc<dyn ExecutionPlan>,
604    weighted: Option<WeightedInput>,
605    /// A neighbour aggregation's node values: node ids, then values.
606    values: Option<Arc<dyn ExecutionPlan>>,
607    properties: Arc<PlanProperties>,
608}
609
610impl GraphAlgorithmExec {
611    fn new(
612        shape: Shape,
613        input: Arc<dyn ExecutionPlan>,
614        weighted: Option<WeightedInput>,
615        values: Option<Arc<dyn ExecutionPlan>>,
616    ) -> Self {
617        let properties = Arc::new(PlanProperties::new(
618            EquivalenceProperties::new(Arc::clone(&shape.schema)),
619            Partitioning::UnknownPartitioning(1),
620            EmissionType::Final,
621            Boundedness::Bounded,
622        ));
623        Self {
624            shape,
625            input,
626            weighted,
627            values,
628            properties,
629        }
630    }
631}
632
633impl DisplayAs for GraphAlgorithmExec {
634    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
635        write!(
636            f,
637            "GraphAlgorithmExec: graph={}, outputs=[{}]",
638            self.shape.edges.graph, self.shape.display
639        )
640    }
641}
642
643impl ExecutionPlan for GraphAlgorithmExec {
644    fn name(&self) -> &str {
645        "GraphAlgorithmExec"
646    }
647
648    fn properties(&self) -> &Arc<PlanProperties> {
649        &self.properties
650    }
651
652    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
653        let mut children = vec![&self.input];
654        children.extend(self.weighted.as_ref().map(|w| &w.plan));
655        children.extend(self.shape.edges.vertices.as_ref().map(|v| &v.plan));
656        children.extend(self.values.as_ref());
657        children
658    }
659
660    /// The edges are read partition by partition in order; splitting them
661    /// further would only scramble that order.
662    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
663        vec![false; self.children().len()]
664    }
665
666    fn apply_expressions(
667        &self,
668        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
669    ) -> Result<TreeNodeRecursion> {
670        Ok(TreeNodeRecursion::Continue)
671    }
672
673    fn with_new_children(
674        self: Arc<Self>,
675        children: Vec<Arc<dyn ExecutionPlan>>,
676    ) -> Result<Arc<dyn ExecutionPlan>> {
677        let expected = self.children().len();
678        if children.len() != expected {
679            return Err(DataFusionError::Internal(format!(
680                "GraphAlgorithmExec has {expected} children; got {}",
681                children.len()
682            )));
683        }
684        let mut children = children.into_iter();
685        let input = children.next().expect("checked above");
686        let weighted = self.weighted.clone().map(|w| WeightedInput {
687            plan: children.next().expect("checked above"),
688            ..w
689        });
690        let mut shape = self.shape.clone();
691        shape.edges.vertices = shape.edges.vertices.map(|v| VertexInput {
692            plan: children.next().expect("checked above"),
693            ..v
694        });
695        let values = self
696            .values
697            .as_ref()
698            .map(|_| children.next().expect("checked above"));
699        Ok(Arc::new(Self::new(shape, input, weighted, values)))
700    }
701
702    fn execute(
703        &self,
704        partition: usize,
705        context: Arc<TaskContext>,
706    ) -> Result<SendableRecordBatchStream> {
707        if partition != 0 {
708            return Err(DataFusionError::Internal(format!(
709                "GraphAlgorithmExec has one partition; asked for {partition}"
710            )));
711        }
712        let shape = self.shape.clone();
713        let input = Arc::clone(&self.input);
714        let weighted = self.weighted.clone();
715        let values_plan = self.values.clone();
716        let schema = Arc::clone(&shape.schema);
717        let run = async move {
718            let (index, weights) = match weighted {
719                None => (unweighted_index(&shape.edges, input, &context).await?, None),
720                Some(w) => {
721                    let (index, weights) = weighted_index(&shape.edges, input, w, &context).await?;
722                    (index, Some(weights))
723                }
724            };
725            let values = match values_plan {
726                Some(plan) => {
727                    let batches = drain(&plan, &[0, 1], &context).await?;
728                    Some(kernels::node_values(&index, &shape.edges.graph, batches)?)
729                }
730                None => None,
731            };
732            // The kernels are CPU-bound and parallel (rayon): keep them off
733            // the async workers (inline in the browser, which has none).
734            crate::run_blocking(move || {
735                let weights = weights.as_deref().map_or(&[][..], Vec::as_slice);
736                kernels::batch(
737                    &index,
738                    &shape.outputs,
739                    weights,
740                    values.as_ref(),
741                    shape.per_node,
742                    shape.schema,
743                )
744            })
745            .await
746            .map_err(|e| DataFusionError::Execution(format!("a graph kernel failed: {e}")))?
747        };
748        Ok(Box::pin(RecordBatchStreamAdapter::new(
749            schema,
750            futures::stream::once(run),
751        )))
752    }
753}
754
755/// What a [`GraphTraversalExec`] computes, besides its children.
756#[derive(Debug, Clone)]
757struct TraversalShape {
758    edges: Edges,
759    traversal: Traversal,
760    /// The call as `EXPLAIN` shows it.
761    display: String,
762    schema: SchemaRef,
763}
764
765/// Builds or fetches a graph index from its first child's edge rows, reads
766/// the node ids its other children produce, and runs a traversal.
767#[derive(Debug)]
768pub struct GraphTraversalExec {
769    shape: TraversalShape,
770    input: Arc<dyn ExecutionPlan>,
771    weighted: Option<WeightedInput>,
772    /// One plan per node-id parameter, in the spec's order.
773    nodes: Vec<Arc<dyn ExecutionPlan>>,
774    properties: Arc<PlanProperties>,
775}
776
777impl GraphTraversalExec {
778    fn new(
779        shape: TraversalShape,
780        input: Arc<dyn ExecutionPlan>,
781        weighted: Option<WeightedInput>,
782        nodes: Vec<Arc<dyn ExecutionPlan>>,
783    ) -> Self {
784        let properties = Arc::new(PlanProperties::new(
785            EquivalenceProperties::new(Arc::clone(&shape.schema)),
786            Partitioning::UnknownPartitioning(1),
787            EmissionType::Final,
788            Boundedness::Bounded,
789        ));
790        Self {
791            shape,
792            input,
793            weighted,
794            nodes,
795            properties,
796        }
797    }
798}
799
800impl DisplayAs for GraphTraversalExec {
801    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
802        write!(
803            f,
804            "GraphTraversalExec: graph={}, call={}",
805            self.shape.edges.graph, self.shape.display
806        )
807    }
808}
809
810impl ExecutionPlan for GraphTraversalExec {
811    fn name(&self) -> &str {
812        "GraphTraversalExec"
813    }
814
815    fn properties(&self) -> &Arc<PlanProperties> {
816        &self.properties
817    }
818
819    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
820        let mut children = vec![&self.input];
821        children.extend(self.weighted.as_ref().map(|w| &w.plan));
822        children.extend(self.shape.edges.vertices.as_ref().map(|v| &v.plan));
823        children.extend(self.nodes.iter());
824        children
825    }
826
827    /// The edges are read in order (see [`GraphAlgorithmExec`]), and the node
828    /// ids in the order their query gives them, which sets the order of the
829    /// rows.
830    fn benefits_from_input_partitioning(&self) -> Vec<bool> {
831        vec![false; self.children().len()]
832    }
833
834    fn apply_expressions(
835        &self,
836        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
837    ) -> Result<TreeNodeRecursion> {
838        Ok(TreeNodeRecursion::Continue)
839    }
840
841    fn with_new_children(
842        self: Arc<Self>,
843        children: Vec<Arc<dyn ExecutionPlan>>,
844    ) -> Result<Arc<dyn ExecutionPlan>> {
845        let expected = self.children().len();
846        if children.len() != expected {
847            return Err(DataFusionError::Internal(format!(
848                "GraphTraversalExec has {expected} children; got {}",
849                children.len()
850            )));
851        }
852        let mut children = children.into_iter();
853        let input = children.next().expect("checked above");
854        let weighted = self.weighted.clone().map(|w| WeightedInput {
855            plan: children.next().expect("checked above"),
856            ..w
857        });
858        let mut shape = self.shape.clone();
859        shape.edges.vertices = shape.edges.vertices.map(|v| VertexInput {
860            plan: children.next().expect("checked above"),
861            ..v
862        });
863        Ok(Arc::new(Self::new(
864            shape,
865            input,
866            weighted,
867            children.collect(),
868        )))
869    }
870
871    fn execute(
872        &self,
873        partition: usize,
874        context: Arc<TaskContext>,
875    ) -> Result<SendableRecordBatchStream> {
876        if partition != 0 {
877            return Err(DataFusionError::Internal(format!(
878                "GraphTraversalExec has one partition; asked for {partition}"
879            )));
880        }
881        let shape = self.shape.clone();
882        let input = Arc::clone(&self.input);
883        let weighted = self.weighted.clone();
884        let node_plans = self.nodes.clone();
885        let schema = Arc::clone(&shape.schema);
886        let run = async move {
887            let (index, weights) = match weighted {
888                None => (unweighted_index(&shape.edges, input, &context).await?, None),
889                Some(w) => {
890                    let (index, weights) = weighted_index(&shape.edges, input, w, &context).await?;
891                    (index, Some(weights))
892                }
893            };
894            let spec = shape.traversal.spec();
895            let mut nodes = Vec::with_capacity(node_plans.len());
896            for (param, plan) in spec.node_params().zip(&node_plans) {
897                let batches = drain(plan, &[0], &context).await?;
898                nodes.push(node_ids(&shape, param, &index, batches)?);
899            }
900            crate::run_blocking(move || {
901                let weights = weights.as_ref().map(|w| w[0].as_slice());
902                traversal::batch(
903                    &index.topology,
904                    &index.ids,
905                    &shape.traversal,
906                    &nodes,
907                    weights,
908                    shape.schema,
909                )
910            })
911            .await
912            .map_err(|e| DataFusionError::Execution(format!("a graph kernel failed: {e}")))?
913        };
914        Ok(Box::pin(RecordBatchStreamAdapter::new(
915            schema,
916            futures::stream::once(run),
917        )))
918    }
919}
920
921/// The ids a node-id input produced, as dense indexes of `index` (`None` for a
922/// null or an id not in the graph), cast to the graph's id type first.
923fn node_ids(
924    shape: &TraversalShape,
925    param: &TraversalParam,
926    index: &GraphIndex,
927    batches: Vec<Vec<ArrayRef>>,
928) -> Result<Vec<Option<u32>>> {
929    let (function, name, graph) = (shape.traversal.name(), param.name, &shape.edges.graph);
930    let id_type = index.ids.user_type();
931    let options = CastOptions {
932        safe: false,
933        ..CastOptions::default()
934    };
935    let arrays = batches
936        .iter()
937        .map(|b| {
938            // No float, boolean or date, and a string must be exactly an
939            // integer on a graph with integer ids (#271).
940            if let Some(row) = traversal::first_refused_node_id(&b[0], &id_type) {
941                let got = sql_text(&b[0], row)
942                    .unwrap_or_else(|| format!("a value of type {}", b[0].data_type()));
943                return Err(DataFusionError::Execution(traversal::not_node_ids(
944                    function, param, graph, &id_type, &got,
945                )));
946            }
947            cast_with_options(&b[0], &id_type, &options).map_err(|e| {
948                let got = first_uncast(&b[0], &id_type).unwrap_or_else(|| {
949                    crate::user_message(&DataFusionError::ArrowError(Box::new(e), None))
950                });
951                DataFusionError::Execution(traversal::not_node_ids(
952                    function, param, graph, &id_type, &got,
953                ))
954            })
955        })
956        .collect::<Result<Vec<_>>>()?;
957    let refs: Vec<&dyn Array> = arrays.iter().map(|a| a.as_ref()).collect();
958    let ids = match refs.as_slice() {
959        [] => new_empty_array(&id_type),
960        _ => concat(&refs)?,
961    };
962    if param.ty == TraversalParamType::Node && ids.len() > 1 {
963        return Err(DataFusionError::Execution(format!(
964            "{function}({name} =>) must be one node id; its query returned {} rows",
965            ids.len()
966        )));
967    }
968    index
969        .ids
970        .dense_from_array(ids.as_ref())
971        .map_err(|e| DataFusionError::Execution(format!("{function}({name} =>): {e}")))
972}
973
974/// The first value of `values` that does not cast to `id_type`, as SQL writes
975/// it (`'Valjean'`, `2.5`), for a message.
976fn first_uncast(values: &ArrayRef, id_type: &DataType) -> Option<String> {
977    let lenient = cast(values, id_type).ok()?;
978    let row = (0..values.len()).find(|&i| values.is_valid(i) && lenient.is_null(i))?;
979    sql_text(values, row)
980}
981
982/// Row `row` of `values` as SQL writes it (`'Valjean'`, `2.5`).
983fn sql_text(values: &ArrayRef, row: usize) -> Option<String> {
984    let mut value = ScalarValue::try_from_array(values, row).ok()?;
985    while let ScalarValue::Dictionary(_, inner) = value {
986        value = *inner;
987    }
988    Some(match value.try_as_str() {
989        Some(Some(s)) => format!("'{}'", s.replace('\'', "''")),
990        _ => value.to_string(),
991    })
992}
993
994/// Keeps a graph node's edge rows in the order the plan produces them, and
995/// gives them a fixed order where the plan has none.
996///
997/// DataFusion's `EnforceDistribution` puts a round-robin repartition under an
998/// operator that benefits from parallel input, such as the `FilterExec` of a
999/// view with a `WHERE` (a subgraph) or the `ProjectionExec` that computes a
1000/// weight expression. Draining its partitions in order would then read the
1001/// batches out of file order, changing dense ids (and so labels and float
1002/// summation order) from what `ursa-io` gives the Python library. This rule
1003/// runs after the default rules and removes every round-robin repartition
1004/// below a graph node: a round-robin repartition only adds parallelism, so
1005/// removing it never changes a result.
1006///
1007/// What remains may still not preserve order: a join, an aggregate, a hash
1008/// repartition, a merge of partitions or a `UNION` produces its rows in an
1009/// order that can change between runs and thread counts (#263). Over such a
1010/// plan, the rule sorts the edge rows by `(source, destination)`, and a
1011/// weighted node's rows by their weights after that, so that rows that tie
1012/// are identical in every column the node reads. A traversal's node-id
1013/// inputs over such a plan are sorted by value, and so are a graph's vertex
1014/// keys, which set the order of its nodes. Order-preserving plans
1015/// (scans, views over files, filters, projections) are left as they are,
1016/// in file order. The sort is a `SortExec` under the node, so `EXPLAIN`
1017/// shows it.
1018#[derive(Debug)]
1019pub struct KeepEdgeOrder;
1020
1021impl PhysicalOptimizerRule for KeepEdgeOrder {
1022    fn optimize(
1023        &self,
1024        plan: Arc<dyn ExecutionPlan>,
1025        _config: &ConfigOptions,
1026    ) -> Result<Arc<dyn ExecutionPlan>> {
1027        plan.transform_up(|node| {
1028            // The columns each child is sorted by, if its order is not fixed.
1029            let keys: Vec<Vec<usize>> =
1030                if let Some(exec) = node.downcast_ref::<GraphAlgorithmExec>() {
1031                    let mut keys = vec![endpoint_keys(exec.shape.edges.endpoints)];
1032                    keys.extend(exec.weighted.as_ref().map(weighted_keys));
1033                    keys.extend(exec.shape.edges.vertices.as_ref().map(|_| vec![0]));
1034                    // A neighbour aggregation's values give one value per
1035                    // node whatever their order: no sort.
1036                    keys.extend(exec.values.as_ref().map(|_| vec![]));
1037                    keys
1038                } else if let Some(exec) = node.downcast_ref::<GraphTraversalExec>() {
1039                    let mut keys = vec![endpoint_keys(exec.shape.edges.endpoints)];
1040                    keys.extend(exec.weighted.as_ref().map(weighted_keys));
1041                    keys.extend(exec.shape.edges.vertices.as_ref().map(|_| vec![0]));
1042                    keys.extend(exec.nodes.iter().map(|_| vec![0]));
1043                    keys
1044                } else if let Some(exec) = node.downcast_ref::<PathSearchExec>() {
1045                    let mut keys = vec![endpoint_keys(exec.shape.edges.endpoints)];
1046                    keys.extend(exec.shape.edges.vertices.as_ref().map(|_| vec![0]));
1047                    keys.push(vec![0]);
1048                    // The targets are a set: their order does not matter.
1049                    keys.extend(exec.targets.as_ref().map(|_| vec![]));
1050                    keys
1051                } else {
1052                    return Ok(Transformed::no(node));
1053                };
1054            let children = node
1055                .children()
1056                .into_iter()
1057                .zip(keys)
1058                .map(|(child, keys)| {
1059                    let child = without_round_robin(Arc::clone(child))?;
1060                    if preserves_order(&child) {
1061                        Ok(child)
1062                    } else {
1063                        sorted(child, &keys)
1064                    }
1065                })
1066                .collect::<Result<Vec<_>>>()?;
1067            Ok(Transformed::yes(replace_children_if_necessary(
1068                Arc::clone(&node),
1069                children,
1070            )?))
1071        })
1072        .map(|t| t.data)
1073    }
1074
1075    fn name(&self) -> &str {
1076        "keep_edge_order"
1077    }
1078
1079    fn schema_check(&self) -> bool {
1080        true
1081    }
1082}
1083
1084/// `plan` with its round-robin repartitions removed.
1085fn without_round_robin(plan: Arc<dyn ExecutionPlan>) -> Result<Arc<dyn ExecutionPlan>> {
1086    plan.transform_up(|node| {
1087        if let Some(repartition) = node.downcast_ref::<RepartitionExec>() {
1088            if matches!(repartition.partitioning(), Partitioning::RoundRobinBatch(_)) {
1089                return Ok(Transformed::yes(Arc::clone(repartition.input())));
1090            }
1091        }
1092        Ok(Transformed::no(node))
1093    })
1094    .map(|t| t.data)
1095}
1096
1097/// The sort key of an edge input: its source, then its destination.
1098fn endpoint_keys((source, destination): (usize, usize)) -> Vec<usize> {
1099    vec![source, destination]
1100}
1101
1102/// The sort key of a weighted edge input: its endpoints, then every weight,
1103/// so rows that tie are the same in every column the node reads.
1104fn weighted_keys(weighted: &WeightedInput) -> Vec<usize> {
1105    let mut keys = endpoint_keys((weighted.source, weighted.destination));
1106    keys.extend(&weighted.weights);
1107    keys
1108}
1109
1110/// Whether reading `plan`'s partitions in order gives its rows in an order
1111/// that does not depend on the run or the thread count: true unless it has
1112/// a join, an aggregate, a repartition, a merge of partitions or a union. A
1113/// nested graph node emits its rows in a fixed order, whatever its inputs.
1114fn preserves_order(plan: &Arc<dyn ExecutionPlan>) -> bool {
1115    let mut preserves = true;
1116    let _ = plan.apply(|node| {
1117        if node.downcast_ref::<GraphAlgorithmExec>().is_some()
1118            || node.downcast_ref::<GraphTraversalExec>().is_some()
1119            || node.downcast_ref::<PathSearchExec>().is_some()
1120        {
1121            return Ok(TreeNodeRecursion::Jump);
1122        }
1123        let reorders = node.downcast_ref::<RepartitionExec>().is_some()
1124            || node.downcast_ref::<CoalescePartitionsExec>().is_some()
1125            || node.downcast_ref::<AggregateExec>().is_some()
1126            || node.downcast_ref::<UnionExec>().is_some()
1127            || node.downcast_ref::<InterleaveExec>().is_some()
1128            || node.name().contains("Join");
1129        if reorders {
1130            preserves = false;
1131            return Ok(TreeNodeRecursion::Stop);
1132        }
1133        Ok(TreeNodeRecursion::Continue)
1134    });
1135    preserves
1136}
1137
1138/// `plan`'s rows sorted by the columns `keys`, ascending with nulls last,
1139/// as one partition: each partition is sorted, then they are merged.
1140fn sorted(plan: Arc<dyn ExecutionPlan>, keys: &[usize]) -> Result<Arc<dyn ExecutionPlan>> {
1141    let schema = plan.schema();
1142    let exprs = keys.iter().map(|&i| {
1143        PhysicalSortExpr::new(
1144            Arc::new(Column::new(schema.field(i).name(), i)) as Arc<dyn PhysicalExpr>,
1145            SortOptions {
1146                descending: false,
1147                nulls_first: false,
1148            },
1149        )
1150    });
1151    let Some(ordering) = LexOrdering::new(exprs) else {
1152        return Ok(plan);
1153    };
1154    let partitions = plan.output_partitioning().partition_count();
1155    let sort =
1156        Arc::new(SortExec::new(ordering.clone(), plan).with_preserve_partitioning(partitions > 1));
1157    Ok(if partitions > 1 {
1158        Arc::new(SortPreservingMergeExec::new(ordering, sort))
1159    } else {
1160        sort
1161    })
1162}
1163
1164/// The index cache key for the edges `input` reads, if they can be cached:
1165/// with a vertex table, the keys' plan and files too, so a change to the
1166/// vertex table builds the index afresh.
1167async fn index_key(
1168    shape: &Edges,
1169    input: &Arc<dyn ExecutionPlan>,
1170    context: &TaskContext,
1171) -> Result<Option<(String, Vec<FileIdentity>)>> {
1172    let Some(edges) = &shape.fingerprint else {
1173        return Ok(None);
1174    };
1175    let mut files = file_identities(input, context).await?;
1176    let fingerprint = match &shape.vertices {
1177        None => edges.clone(),
1178        Some(VertexInput {
1179            fingerprint: None, ..
1180        }) => return Ok(None),
1181        Some(VertexInput {
1182            plan,
1183            fingerprint: Some(vertices),
1184        }) => {
1185            files.extend(file_identities(plan, context).await?);
1186            files.sort();
1187            files.dedup();
1188            format!("{edges}\n-- vertex keys --\n{vertices}")
1189        }
1190    };
1191    Ok(Some((fingerprint, files)))
1192}
1193
1194/// The index, cached or built from the endpoint-only input.
1195async fn unweighted_index(
1196    shape: &Edges,
1197    input: Arc<dyn ExecutionPlan>,
1198    context: &Arc<TaskContext>,
1199) -> Result<Arc<GraphIndex>> {
1200    let build = {
1201        let (shape, input, context) = (shape.clone(), Arc::clone(&input), Arc::clone(context));
1202        async move {
1203            let mut no_weights = WeightReader::new(&[], 0);
1204            build_streamed(&shape, &input, shape.endpoints, &context, &mut no_weights).await
1205        }
1206    };
1207    match context.session_config().get_extension::<IndexCache>() {
1208        Some(cache) => {
1209            let key = index_key(shape, &input, context).await?;
1210            cache
1211                .get_or_build_for(
1212                    context.session_config(),
1213                    key,
1214                    &build_info(shape, &input),
1215                    build.boxed(),
1216                )
1217                .await
1218        }
1219        None => build.await.map(Arc::new),
1220    }
1221}
1222
1223/// The index and the weight columns, for a node that reads weights (see the
1224/// module docs).
1225async fn weighted_index(
1226    shape: &Edges,
1227    input: Arc<dyn ExecutionPlan>,
1228    weighted: WeightedInput,
1229    context: &Arc<TaskContext>,
1230) -> Result<(Arc<GraphIndex>, Weights)> {
1231    let cache = context.session_config().get_extension::<IndexCache>();
1232    let key = match &cache {
1233        Some(_) => index_key(shape, &input, context).await?,
1234        None => None,
1235    };
1236    let weights_key = match &weighted.fingerprint {
1237        Some(f) => Some(format!(
1238            "{}\n{:?}",
1239            portable_in(f, context.session_config()),
1240            file_identities(&weighted.plan, context).await?
1241        )),
1242        None => None,
1243    };
1244    let n_weights = weighted.weights.len();
1245    // Weights already evaluated over the cached index's rows: nothing to read.
1246    if let (Some(cache), Some(key), Some(weights_key)) = (&cache, &key, &weights_key) {
1247        if let Some(index) = cache.get(key) {
1248            if let Some(weights) = known_weights(&index, weights_key, n_weights).await {
1249                return Ok((index, weights));
1250            }
1251        }
1252    }
1253
1254    let (index, weights, shared) = match &cache {
1255        Some(cache) => {
1256            // Weights read by this node's own build, if the cache ran it.
1257            let slot = Arc::new(Mutex::new(None));
1258            let build = {
1259                let (shape, weighted) = (shape.clone(), weighted.clone());
1260                let (context, slot) = (Arc::clone(context), Arc::clone(&slot));
1261                async move {
1262                    let (index, weights) = build_weighted(&shape, &weighted, &context).await?;
1263                    *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(weights);
1264                    Ok(index)
1265                }
1266            };
1267            let index = cache
1268                .get_or_build_for(
1269                    context.session_config(),
1270                    key,
1271                    &build_info(shape, &weighted.plan),
1272                    build.boxed(),
1273                )
1274                .await?;
1275            let built_here = slot.lock().unwrap_or_else(|e| e.into_inner()).take();
1276            // A stored index may have these weights stored with it.
1277            if built_here.is_none() {
1278                if let Some(weights_key) = &weights_key {
1279                    if let Some(weights) = known_weights(&index, weights_key, n_weights).await {
1280                        return Ok((index, weights));
1281                    }
1282                }
1283            }
1284            match built_here {
1285                Some(weights) => (index, weights, true),
1286                None => {
1287                    let mut weights =
1288                        WeightReader::new(&weighted.weights, index.topology.n_edges());
1289                    if read_aligned(&index, &weighted, shape, context, &mut weights).await? {
1290                        (index, weights, true)
1291                    } else {
1292                        // The cached index's rows are in another order: these
1293                        // weights belong to an index of these rows.
1294                        cache.record_build();
1295                        let (private, weights) = build_weighted(shape, &weighted, context).await?;
1296                        (Arc::new(private), weights, false)
1297                    }
1298                }
1299            }
1300        }
1301        None => {
1302            let (index, weights) = build_weighted(shape, &weighted, context).await?;
1303            (Arc::new(index), weights, false)
1304        }
1305    };
1306
1307    let weights: Weights = Arc::new(weights.finish()?.into_iter().map(Arc::new).collect());
1308    if let (true, Some(weights_key)) = (shared, weights_key) {
1309        index.store_weights(weights_key, Arc::clone(&weights));
1310    }
1311    Ok((index, weights))
1312}
1313
1314/// The weights `index` holds under `key` (with `n_weights` columns), in
1315/// memory or stored with it on disk.
1316async fn known_weights(index: &Arc<GraphIndex>, key: &str, n_weights: usize) -> Option<Weights> {
1317    if let Some(weights) = index.weights(key) {
1318        return Some(weights);
1319    }
1320    if !index.has_stored_weights(key) {
1321        return None;
1322    }
1323    let (index, key) = (Arc::clone(index), key.to_string());
1324    // Reading a file is blocking work.
1325    crate::run_blocking(move || index.stored_weights(&key, n_weights))
1326        .await
1327        .ok()
1328        .flatten()
1329}
1330
1331/// Build the index of the weighted rows, reading their weights in the same
1332/// pass, so they line up by construction.
1333async fn build_weighted(
1334    shape: &Edges,
1335    weighted: &WeightedInput,
1336    context: &Arc<TaskContext>,
1337) -> Result<(GraphIndex, WeightReader)> {
1338    let mut weights = WeightReader::new(&weighted.weights, row_hint(&weighted.plan));
1339    let endpoints = (weighted.source, weighted.destination);
1340    let index = build_streamed(shape, &weighted.plan, endpoints, context, &mut weights).await?;
1341    Ok((index, weights))
1342}
1343
1344/// Read the weighted rows once, reading their weights, and say whether
1345/// their endpoints are the rows `index` was built from, row for row. Stops
1346/// at the first row that is not.
1347async fn read_aligned(
1348    index: &GraphIndex,
1349    weighted: &WeightedInput,
1350    shape: &Edges,
1351    context: &Arc<TaskContext>,
1352    weights: &mut WeightReader,
1353) -> Result<bool> {
1354    let id_type = &shape.id_type;
1355    let mut rows = RowCheck::new(index);
1356    let mut batches = InOrder::new(&weighted.plan, context);
1357    while let Some(batch) = batches.next().await {
1358        let mut batch = batch?;
1359        let mut src = cast(batch.column(weighted.source), id_type)?;
1360        let mut dst = cast(batch.column(weighted.destination), id_type)?;
1361        // With a vertex table, the index holds only the edges between
1362        // keys: skip the others, as the build did.
1363        if shape.vertices.is_some() {
1364            let keep = between_nodes(index, &src, &dst)?;
1365            if keep.true_count() < keep.len() {
1366                batch = filter_record_batch(&batch, &keep)?;
1367                src = filter(&src, &keep)?;
1368                dst = filter(&dst, &keep)?;
1369            }
1370        }
1371        if batch.num_rows() == 0 {
1372            continue;
1373        }
1374        if !rows.check(&src, &dst)? {
1375            return Ok(false);
1376        }
1377        weights.push(&batch);
1378    }
1379    Ok(rows.complete())
1380}
1381
1382/// Which edges `src` -> `dst` (of the index's id type) join two nodes of
1383/// `index`.
1384fn between_nodes(index: &GraphIndex, src: &ArrayRef, dst: &ArrayRef) -> Result<BooleanArray> {
1385    let lookup = |a: &ArrayRef| {
1386        index
1387            .ids
1388            .dense_from_array(a.as_ref())
1389            .map_err(|e| DataFusionError::Execution(e.to_string()))
1390    };
1391    let (s, d) = (lookup(src)?, lookup(dst)?);
1392    Ok(s.iter()
1393        .zip(&d)
1394        .map(|(s, d)| Some(s.is_some() && d.is_some()))
1395        .collect())
1396}
1397
1398/// The weight columns of a weighted node's rows, evaluated a batch at a
1399/// time as the rows are read. The first bad weight is reported once every
1400/// row has been read, after any error in building the index from those
1401/// rows, as when the weights were evaluated after the build.
1402struct WeightReader {
1403    columns: Vec<usize>,
1404    values: Vec<Vec<f64>>,
1405    error: Option<DataFusionError>,
1406}
1407
1408impl WeightReader {
1409    /// A reader of the columns `columns`, sized for `rows` rows.
1410    fn new(columns: &[usize], rows: usize) -> Self {
1411        Self {
1412            columns: columns.to_vec(),
1413            values: columns.iter().map(|_| Vec::with_capacity(rows)).collect(),
1414            error: None,
1415        }
1416    }
1417
1418    fn push(&mut self, batch: &RecordBatch) {
1419        if self.error.is_some() {
1420            return;
1421        }
1422        for (&c, values) in self.columns.iter().zip(&mut self.values) {
1423            if let Err(e) = extend_weights(batch.column(c), values) {
1424                self.error = Some(e);
1425                return;
1426            }
1427        }
1428    }
1429
1430    /// Keep only the rows `kept` marks, one bit per row read.
1431    fn keep(&mut self, kept: &BooleanBuffer) {
1432        for values in &mut self.values {
1433            let mut bits = kept.iter();
1434            values.retain(|_| bits.next().unwrap_or(false));
1435        }
1436    }
1437
1438    /// One `f64` per row read, per column, or the first bad weight.
1439    fn finish(self) -> Result<Vec<Vec<f64>>> {
1440        match self.error {
1441            Some(e) => Err(e),
1442            None => Ok(self.values),
1443        }
1444    }
1445}
1446
1447/// Every batch of `input`, partition by partition in order (decoded in
1448/// parallel, see [`InOrder`]), as the columns
1449/// `columns` of each non-empty batch.
1450async fn drain(
1451    input: &Arc<dyn ExecutionPlan>,
1452    columns: &[usize],
1453    context: &Arc<TaskContext>,
1454) -> Result<Vec<Vec<ArrayRef>>> {
1455    let mut out = Vec::new();
1456    let mut batches = InOrder::new(input, context);
1457    while let Some(batch) = batches.next().await {
1458        let batch = batch?;
1459        if batch.num_rows() == 0 {
1460            continue;
1461        }
1462        out.push(
1463            columns
1464                .iter()
1465                .map(|&c| Arc::clone(batch.column(c)))
1466                .collect(),
1467        );
1468    }
1469    Ok(out)
1470}
1471
1472/// Rows the index build interns at a time. A scan's batches are 8,192 rows,
1473/// and `EdgeInterner` resolves known ids in parallel only in larger chunks,
1474/// so the build gathers batches up to this many rows first: what `ursa-io`'s
1475/// scan does for the Python library (its `SCAN_BATCH_ROWS`). A chunk is
1476/// 2 MiB of `Int64` endpoints.
1477const INTERN_ROWS: usize = 1 << 17;
1478
1479/// Endpoint chunks gathered up to [`INTERN_ROWS`] rows, in row order.
1480#[derive(Default)]
1481struct Gather {
1482    src: Vec<ArrayRef>,
1483    dst: Vec<ArrayRef>,
1484    rows: usize,
1485}
1486
1487impl Gather {
1488    /// Add a chunk; once [`INTERN_ROWS`] rows are gathered, take them.
1489    fn push(&mut self, src: ArrayRef, dst: ArrayRef) -> Result<Option<(ArrayRef, ArrayRef)>> {
1490        self.rows += src.len();
1491        self.src.push(src);
1492        self.dst.push(dst);
1493        if self.rows >= INTERN_ROWS {
1494            self.take()
1495        } else {
1496            Ok(None)
1497        }
1498    }
1499
1500    /// The rows gathered so far, as one chunk, if there are any.
1501    fn take(&mut self) -> Result<Option<(ArrayRef, ArrayRef)>> {
1502        self.rows = 0;
1503        let (src, dst) = (std::mem::take(&mut self.src), std::mem::take(&mut self.dst));
1504        Ok(match src.len() {
1505            0 => None,
1506            1 => src.into_iter().zip(dst).next(),
1507            _ => {
1508                let join = |arrays: &[ArrayRef]| {
1509                    let refs: Vec<&dyn Array> = arrays.iter().map(|a| a.as_ref()).collect();
1510                    concat(&refs)
1511                };
1512                Some((join(&src)?, join(&dst)?))
1513            }
1514        })
1515    }
1516}
1517
1518/// The index of everything `interner` was given; an empty graph of
1519/// `id_type` ids if it was given no node and no edge.
1520fn finish_index(mut interner: EdgeInterner, id_type: &DataType) -> GraphIndex {
1521    let (n_dropped, kept) = (interner.n_dropped(), interner.kept_rows());
1522    let (ids, source, destination) = interner.finish();
1523    if ids.is_empty() {
1524        let (topology, ids) = ursa_io::topology::empty_topology(id_type);
1525        return GraphIndex::new(topology, ids).with_dropped(n_dropped, kept);
1526    }
1527    let topology = Topology::build(ids.len(), source, destination);
1528    GraphIndex::new(Arc::new(topology), Arc::new(ids)).with_dropped(n_dropped, kept)
1529}
1530
1531/// The number of rows `plan` will produce, if its statistics say: sizes the
1532/// interner, as `ursa-io`'s scan sizes it from the Parquet metadata.
1533fn row_hint(plan: &Arc<dyn ExecutionPlan>) -> usize {
1534    StatisticsContext::new()
1535        .compute(plan.as_ref(), &StatisticsArgs::new())
1536        .ok()
1537        .and_then(|s| s.num_rows.get_value().copied())
1538        .unwrap_or(0)
1539}
1540
1541/// What a build over `input` is for, as its notices say: the graph, and how
1542/// much it reads, as far as `input`'s statistics know (#351). An exact count
1543/// is the edge rows. A filter the statistics cannot settle (one no file or
1544/// row-group statistics prune) leaves only a guess at the edges, DataFusion's
1545/// default selectivity, which can be off a hundredfold either way: then the
1546/// notice gives the rows the scans read instead, which the statistics do
1547/// know. Otherwise the estimate is of edge rows.
1548fn build_info(shape: &Edges, input: &Arc<dyn ExecutionPlan>) -> BuildInfo {
1549    let rows = plan_rows(input);
1550    let size = match rows {
1551        Some((n, true)) => Some(BuildSize::Edges(n, true)),
1552        _ if filters(input) => scanned_rows(input).map(BuildSize::Reads),
1553        Some((n, false)) => Some(BuildSize::Edges(n, false)),
1554        None => None,
1555    };
1556    BuildInfo {
1557        graph: Some(shape.graph.clone()),
1558        size,
1559    }
1560}
1561
1562/// The rows `plan`'s statistics say it gives, and whether that is exact.
1563fn plan_rows(plan: &Arc<dyn ExecutionPlan>) -> Option<(u64, bool)> {
1564    StatisticsContext::new()
1565        .compute(plan.as_ref(), &StatisticsArgs::new())
1566        .ok()
1567        .and_then(|s| {
1568            let exact = s.num_rows.is_exact().unwrap_or(false);
1569            s.num_rows.get_value().map(|n| (*n as u64, exact))
1570        })
1571}
1572
1573/// Whether `plan` filters rows: a filter node, or a predicate pushed into a
1574/// file scan.
1575fn filters(plan: &Arc<dyn ExecutionPlan>) -> bool {
1576    let mut found = false;
1577    let _ = plan.apply(|node| {
1578        let scan_predicate = node
1579            .downcast_ref::<DataSourceExec>()
1580            .and_then(|exec| exec.data_source().downcast_ref::<FileScanConfig>())
1581            .is_some_and(|config| config.file_source().filter().is_some());
1582        if scan_predicate || node.downcast_ref::<FilterExec>().is_some() {
1583            found = true;
1584            return Ok(TreeNodeRecursion::Stop);
1585        }
1586        Ok(TreeNodeRecursion::Continue)
1587    });
1588    found
1589}
1590
1591/// The rows the scans under `plan` read, if every scan's statistics say:
1592/// the rows of its leaves.
1593fn scanned_rows(plan: &Arc<dyn ExecutionPlan>) -> Option<u64> {
1594    let mut total = Some(0u64);
1595    let _ = plan.apply(|node| {
1596        if node.children().is_empty() {
1597            let leaf = plan_rows(node).map(|(n, _)| n);
1598            total = total.zip(leaf).map(|(a, b)| a + b);
1599        }
1600        Ok(TreeNodeRecursion::Continue)
1601    });
1602    total.filter(|n| *n > 0)
1603}
1604
1605/// What the reader hands the interning thread.
1606enum Chunk {
1607    /// Vertex keys, before any edge.
1608    Nodes(ArrayRef),
1609    /// Every vertex key has been read: the node set is fixed.
1610    NodesDone,
1611    Edges(ArrayRef, ArrayRef),
1612    /// Every row has been read: build the index.
1613    End,
1614}
1615
1616/// Hand one chunk to `interner` (see [`build_streamed`]); the index once
1617/// every row has been read.
1618fn take_chunk(
1619    interner: &mut EdgeInterner,
1620    chunk: Chunk,
1621    graph: &str,
1622    id_type: &DataType,
1623) -> Result<Option<GraphIndex>> {
1624    match chunk {
1625        Chunk::Nodes(keys) => interner
1626            .push_nodes(keys.as_ref())
1627            .map_err(|e| build_error(graph, e))?,
1628        Chunk::NodesDone => interner.close_nodes(),
1629        Chunk::Edges(src, dst) => interner
1630            .push(src.as_ref(), dst.as_ref())
1631            .map_err(|e| build_error(graph, e))?,
1632        Chunk::End => {
1633            let interner = std::mem::replace(interner, EdgeInterner::with_capacity(0));
1634            return Ok(Some(finish_index(interner, id_type)));
1635        }
1636    }
1637    Ok(None)
1638}
1639
1640/// Build the index of the edge rows `input` produces, interning each chunk
1641/// as it is read rather than collecting every endpoint array first, so the
1642/// Arrow input does not accumulate: the build holds the dense endpoints, a
1643/// chunk or two in flight, and what the partitions decoded ahead of their
1644/// turn hold, within [`READ_AHEAD_BYTES`]. The partitions decode in parallel
1645/// and are interned in partition order ([`InOrder`]), and reading (here) and
1646/// interning (on a blocking thread) overlap. The rows are interned in the
1647/// order [`drain`] would collect them, so the index is the one
1648/// `ursa_io::build_topology_batches` gives over the collected rows. A
1649/// weighted node's weights are read from the same rows (`weights`), and with
1650/// a vertex table kept only for the edges kept (see the module docs), whose
1651/// keys are read first.
1652async fn build_streamed(
1653    shape: &Edges,
1654    input: &Arc<dyn ExecutionPlan>,
1655    endpoints: (usize, usize),
1656    context: &Arc<TaskContext>,
1657    weights: &mut WeightReader,
1658) -> Result<GraphIndex> {
1659    let read_ahead = Some(READ_AHEAD_BYTES);
1660    build_streamed_with(shape, input, endpoints, context, weights, read_ahead).await
1661}
1662
1663/// [`build_streamed`], reading the partitions in parallel within
1664/// `read_ahead` bytes (see [`InOrder`]), or one after another with `None`:
1665/// the index is the same either way.
1666async fn build_streamed_with(
1667    shape: &Edges,
1668    input: &Arc<dyn ExecutionPlan>,
1669    (source, destination): (usize, usize),
1670    context: &Arc<TaskContext>,
1671    weights: &mut WeightReader,
1672    read_ahead: Option<usize>,
1673) -> Result<GraphIndex> {
1674    let (graph, id_type) = (shape.graph.clone(), shape.id_type.clone());
1675    let hint = row_hint(input);
1676    let (tx, mut rx) = tokio::sync::mpsc::channel::<Chunk>(2);
1677
1678    // Native: the interner runs on a blocking thread, so reading and interning
1679    // overlap on two threads. It is spawned here, before the reader starts
1680    // (`run_blocking` would start it only when awaited, after the reader).
1681    #[cfg(not(target_arch = "wasm32"))]
1682    let interning = tokio::task::spawn_blocking(move || -> Result<Option<GraphIndex>> {
1683        let mut interner = EdgeInterner::with_capacity(hint);
1684        while let Some(chunk) = rx.blocking_recv() {
1685            if let Some(index) = take_chunk(&mut interner, chunk, &graph, &id_type)? {
1686                return Ok(Some(index));
1687            }
1688        }
1689        // The reader stopped before the end (its error is the one reported).
1690        Ok(None)
1691    });
1692    // The browser (wasm32) has one thread: the interner is a future polled
1693    // alongside the reader, taking each chunk as it is sent. The channel's
1694    // bound still keeps at most two chunks in flight, and the chunks arrive in
1695    // the same order, so the index is the same (#278).
1696    #[cfg(target_arch = "wasm32")]
1697    let interning = async move {
1698        let mut interner = EdgeInterner::with_capacity(hint);
1699        while let Some(chunk) = rx.recv().await {
1700            if let Some(index) = take_chunk(&mut interner, chunk, &graph, &id_type)? {
1701                return Ok(Some(index));
1702            }
1703        }
1704        Ok::<_, DataFusionError>(None)
1705    };
1706
1707    let read = async {
1708        // The reader owns the sender, so the interner sees the channel close
1709        // when the reader stops, on an error as at the end.
1710        let tx = tx;
1711        if let Some(vertices) = &shape.vertices {
1712            let mut batches = InOrder::with_budget(&vertices.plan, context, read_ahead);
1713            while let Some(batch) = batches.next().await {
1714                let batch = batch?;
1715                if batch.num_rows() == 0 {
1716                    continue;
1717                }
1718                let keys = cast(batch.column(0), &shape.id_type)?;
1719                if tx.send(Chunk::Nodes(keys)).await.is_err() {
1720                    return Ok(());
1721                }
1722            }
1723            if tx.send(Chunk::NodesDone).await.is_err() {
1724                return Ok(());
1725            }
1726        }
1727        let mut gather = Gather::default();
1728        let mut batches = InOrder::with_budget(input, context, read_ahead);
1729        while let Some(batch) = batches.next().await {
1730            let batch = batch?;
1731            if batch.num_rows() == 0 {
1732                continue;
1733            }
1734            let src = cast(batch.column(source), &shape.id_type)?;
1735            let dst = cast(batch.column(destination), &shape.id_type)?;
1736            weights.push(&batch);
1737            drop(batch);
1738            if let Some((src, dst)) = gather.push(src, dst)? {
1739                if tx.send(Chunk::Edges(src, dst)).await.is_err() {
1740                    // The interner stopped on an error: it is reported below.
1741                    return Ok(());
1742                }
1743            }
1744        }
1745        if let Some((src, dst)) = gather.take()? {
1746            if tx.send(Chunk::Edges(src, dst)).await.is_err() {
1747                return Ok(());
1748            }
1749        }
1750        let _ = tx.send(Chunk::End).await;
1751        Ok::<_, DataFusionError>(())
1752    };
1753    #[cfg(not(target_arch = "wasm32"))]
1754    let (read, built) = {
1755        let read = read.await;
1756        let built = interning.await.map_err(|e| {
1757            DataFusionError::Execution(format!("building graph '{}' failed: {e}", shape.graph))
1758        })?;
1759        (read, built)
1760    };
1761    #[cfg(target_arch = "wasm32")]
1762    let (read, built) = futures::join!(read, interning);
1763    read?;
1764    let index = built?.ok_or_else(|| {
1765        DataFusionError::Internal(format!(
1766            "building graph '{}' stopped before the last edge",
1767            shape.graph
1768        ))
1769    })?;
1770    if let Some(kept) = index.kept_rows() {
1771        weights.keep(kept);
1772    }
1773    Ok(index)
1774}
1775
1776/// Checks, a chunk at a time, that rows are the edge rows an index was
1777/// built from, in order.
1778struct RowCheck<'a> {
1779    index: &'a GraphIndex,
1780    /// Each row's endpoints as dense ids, from the CSR and its row
1781    /// permutation.
1782    source: Vec<u32>,
1783    destination: Vec<u32>,
1784    /// Rows checked so far.
1785    start: usize,
1786}
1787
1788impl<'a> RowCheck<'a> {
1789    fn new(index: &'a GraphIndex) -> Self {
1790        let topology = &index.topology;
1791        let n = topology.n_edges();
1792        let out = topology.out();
1793        let (mut source, mut destination) = (vec![0u32; n], vec![0u32; n]);
1794        for u in 0..topology.n_nodes() {
1795            let slots = out.offsets[u] as usize..out.offsets[u + 1] as usize;
1796            for slot in slots {
1797                let row = out.edge_ids[slot] as usize;
1798                source[row] = u as u32;
1799                destination[row] = out.targets[slot];
1800            }
1801        }
1802        Self {
1803            index,
1804            source,
1805            destination,
1806            start: 0,
1807        }
1808    }
1809
1810    /// Whether the next rows are `src` → `dst`. Each chunk's ids are
1811    /// compared on their own, so no column of every row's ids is made.
1812    fn check(&mut self, src: &ArrayRef, dst: &ArrayRef) -> Result<bool> {
1813        let rows = self.start..self.start + src.len();
1814        if rows.end > self.source.len() {
1815            return Ok(false);
1816        }
1817        self.start = rows.end;
1818        let ids = &self.index.ids;
1819        let user_type = ids.user_type();
1820        Ok(
1821            ids.gather_user(&self.source[rows.clone()]).as_ref() == cast(src, &user_type)?.as_ref()
1822                && ids.gather_user(&self.destination[rows]).as_ref()
1823                    == cast(dst, &user_type)?.as_ref(),
1824        )
1825    }
1826
1827    /// Whether every row of the index has been checked.
1828    fn complete(&self) -> bool {
1829        self.start == self.source.len()
1830    }
1831}
1832
1833/// Whether `endpoints` are the edge rows `index` was built from, row for row.
1834#[cfg(test)]
1835fn aligned(index: &GraphIndex, endpoints: &[(ArrayRef, ArrayRef)]) -> Result<bool> {
1836    let mut rows = RowCheck::new(index);
1837    for (src, dst) in endpoints {
1838        if !rows.check(src, dst)? {
1839            return Ok(false);
1840        }
1841    }
1842    Ok(rows.complete())
1843}
1844
1845/// A weight expression's values, one `f64` per edge row, checked as
1846/// `ursa-plan`'s `evaluate_weight` checks them, with its messages.
1847#[cfg(test)]
1848fn edge_weights(columns: &[ArrayRef]) -> Result<Vec<f64>> {
1849    let mut out = Vec::with_capacity(columns.iter().map(|c| c.len()).sum());
1850    for column in columns {
1851        extend_weights(column, &mut out)?;
1852    }
1853    Ok(out)
1854}
1855
1856/// Append one chunk of a weight expression's values to `out`, checked as
1857/// `ursa-plan`'s `evaluate_weight` checks them, with its messages.
1858fn extend_weights(column: &ArrayRef, out: &mut Vec<f64>) -> Result<()> {
1859    let column = cast(column, &DataType::Float64)?;
1860    let column = column
1861        .as_any()
1862        .downcast_ref::<Float64Array>()
1863        .expect("cast to Float64 yields Float64Array");
1864    if column.null_count() > 0 {
1865        return Err(DataFusionError::Execution(
1866            "weight expression produced a null value; weights must be non-null".into(),
1867        ));
1868    }
1869    let values = column.values();
1870    if let Some(&w) = values.iter().find(|&&w| w < 0.0) {
1871        return Err(DataFusionError::Execution(format!(
1872            "weight expression produced a negative value ({w}); weights must be \
1873             non-negative"
1874        )));
1875    }
1876    out.extend_from_slice(values);
1877    Ok(())
1878}
1879
1880fn build_error(graph: &str, e: IdError) -> DataFusionError {
1881    DataFusionError::Execution(match e {
1882        IdError::Null => format!(
1883            "graph '{graph}': an edge has a null source or destination; filter those rows out \
1884             of the edge table (for example, with a view that keeps rows WHERE both are NOT NULL)"
1885        ),
1886        other => format!("graph '{graph}': {other}"),
1887    })
1888}
1889
1890#[cfg(test)]
1891mod tests {
1892    use super::*;
1893    use datafusion::arrow::array::{Int64Array, StringArray};
1894
1895    fn index(src: &dyn Array, dst: &dyn Array) -> GraphIndex {
1896        let (topology, ids) = ursa_io::build_topology_batches(&[(src, dst)]).unwrap();
1897        GraphIndex::new(topology, ids)
1898    }
1899
1900    fn ints(v: &[i64]) -> ArrayRef {
1901        Arc::new(Int64Array::from(v.to_vec()))
1902    }
1903
1904    #[test]
1905    fn weights_line_up_only_with_the_rows_the_index_was_built_from() {
1906        let (src, dst) = (ints(&[10, 20, 10, 30]), ints(&[20, 30, 30, 10]));
1907        let built = index(src.as_ref(), dst.as_ref());
1908        // The same rows, in two batches: aligned.
1909        let split = vec![
1910            (src.slice(0, 1), dst.slice(0, 1)),
1911            (src.slice(1, 3), dst.slice(1, 3)),
1912        ];
1913        assert!(aligned(&built, &split).unwrap());
1914        // The same edge set in another order: not.
1915        let swapped = vec![(ints(&[20, 10, 10, 30]), ints(&[30, 20, 30, 10]))];
1916        assert!(!aligned(&built, &swapped).unwrap());
1917        // Fewer rows: not.
1918        assert!(!aligned(&built, &split[1..]).unwrap());
1919
1920        let names = |v: &[&str]| Arc::new(StringArray::from(v.to_vec())) as ArrayRef;
1921        let (s, d) = (names(&["a", "b"]), names(&["b", "c"]));
1922        let built = index(s.as_ref(), d.as_ref());
1923        assert!(aligned(&built, &[(Arc::clone(&s), Arc::clone(&d))]).unwrap());
1924        assert!(!aligned(&built, &[(d, s)]).unwrap());
1925    }
1926
1927    /// The bytes a database stores `index` as.
1928    fn stored_bytes(index: &GraphIndex) -> Vec<u8> {
1929        let key = crate::database::IndexKey::new("edges".into(), Vec::new());
1930        let encoded =
1931            crate::database::index_file::Encoded::new(&key, &index.topology, &index.ids).unwrap();
1932        let mut bytes = Vec::new();
1933        encoded.write_to(&mut bytes).unwrap();
1934        bytes
1935    }
1936
1937    /// A session over a Parquet file of many row groups, split into several
1938    /// partitions, and the plan of its edges behind a filter no statistics
1939    /// prune.
1940    async fn filtered_edges() -> (tempfile::TempDir, Arc<dyn ExecutionPlan>, Arc<TaskContext>) {
1941        use datafusion::prelude::SessionConfig;
1942        let dir = tempfile::tempdir().unwrap();
1943        let mut config = SessionConfig::new().with_target_partitions(8);
1944        config.options_mut().optimizer.repartition_file_min_size = 1;
1945        let ctx = crate::new_session_with_config(config);
1946        let file = dir.path().join("edges.parquet");
1947        let sql = [
1948            "SET datafusion.execution.parquet.max_row_group_size = 4096".to_string(),
1949            // Ids scattered over the rows, so first-seen order numbers them
1950            // differently from sorted order.
1951            format!(
1952                "COPY (SELECT (value * 7919) % 50021 AS s, (value * 104729 + 13) % 50021 AS d \
1953                 FROM generate_series(0, 299999)) TO '{}'",
1954                file.display()
1955            ),
1956        ];
1957        for sql in sql {
1958            ctx.sql(&sql).await.unwrap().collect().await.unwrap();
1959        }
1960        let plan = ctx
1961            .sql(&format!(
1962                "SELECT s, d FROM '{}' WHERE s % 7 <> 3",
1963                file.display()
1964            ))
1965            .await
1966            .unwrap()
1967            .create_physical_plan()
1968            .await
1969            .unwrap();
1970        (dir, plan, ctx.task_ctx())
1971    }
1972
1973    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1974    async fn an_index_built_from_partitions_read_in_parallel_is_the_serial_one() {
1975        let (_dir, plan, context) = filtered_edges().await;
1976        let partitions = plan.output_partitioning().partition_count();
1977        assert!(partitions > 1, "{partitions} partition(s)");
1978        let shape = Edges {
1979            graph: "g".into(),
1980            endpoints: (0, 1),
1981            id_type: DataType::Int64,
1982            fingerprint: None,
1983            vertices: None,
1984        };
1985        let build = |read_ahead| {
1986            let (shape, plan, context) = (shape.clone(), Arc::clone(&plan), Arc::clone(&context));
1987            async move {
1988                let mut no_weights = WeightReader::new(&[], 0);
1989                build_streamed_with(&shape, &plan, (0, 1), &context, &mut no_weights, read_ahead)
1990                    .await
1991                    .unwrap()
1992            }
1993        };
1994        let serial = build(None).await;
1995        assert!(serial.topology.n_edges() > 200_000);
1996        // The serial build is the one over the rows collected in order.
1997        let rows = drain(&plan, &[0, 1], &context).await.unwrap();
1998        let rows: Vec<(&dyn Array, &dyn Array)> = rows
1999            .iter()
2000            .map(|c| (c[0].as_ref(), c[1].as_ref()))
2001            .collect();
2002        let (topology, ids) = ursa_io::build_topology_batches(&rows).unwrap();
2003        let collected = GraphIndex::new(topology, ids);
2004        let expected = stored_bytes(&serial);
2005        assert_eq!(stored_bytes(&collected), expected);
2006        // In parallel, with room to read ahead and with none: the same node
2007        // numbering, the same CSR, the same stored bytes.
2008        for read_ahead in [Some(READ_AHEAD_BYTES), Some(1)] {
2009            let parallel = build(read_ahead).await;
2010            assert_eq!(
2011                parallel.ids.user_id_array().as_ref(),
2012                serial.ids.user_id_array().as_ref(),
2013                "node numbering, read ahead {read_ahead:?}"
2014            );
2015            assert_eq!(
2016                stored_bytes(&parallel),
2017                expected,
2018                "read ahead {read_ahead:?}"
2019            );
2020        }
2021    }
2022
2023    #[test]
2024    fn weights_are_checked_as_ursa_plan_checks_them() {
2025        let ok = edge_weights(&[ints(&[1, 2]), ints(&[0])]).unwrap();
2026        assert_eq!(ok, vec![1.0, 2.0, 0.0]);
2027        let negative = edge_weights(&[ints(&[1, -1])]).unwrap_err();
2028        assert_eq!(
2029            crate::user_message(&negative),
2030            "weight expression produced a negative value (-1); weights must be non-negative"
2031        );
2032        let null: ArrayRef = Arc::new(Int64Array::from(vec![Some(1), None]));
2033        assert_eq!(
2034            crate::user_message(&edge_weights(&[null]).unwrap_err()),
2035            "weight expression produced a null value; weights must be non-null"
2036        );
2037    }
2038}