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