1use 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#[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 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
183fn 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
204fn 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
230fn 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
281async 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#[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 held: Option<IndexHeld>,
357 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 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 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
574async 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#[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#[derive(Debug, Clone)]
622struct Edges {
623 graph: String,
624 endpoints: (usize, usize),
626 id_type: DataType,
627 fingerprint: Option<String>,
629 vertices: Option<VertexInput>,
631}
632
633#[derive(Debug, Clone)]
635struct VertexInput {
636 plan: Arc<dyn ExecutionPlan>,
637 fingerprint: Option<String>,
639}
640
641#[derive(Debug, Clone)]
643struct Shape {
644 edges: Edges,
645 outputs: Vec<Output>,
646 per_node: bool,
647 display: String,
649 schema: SchemaRef,
650}
651
652#[derive(Debug, Clone)]
654struct WeightedInput {
655 plan: Arc<dyn ExecutionPlan>,
656 source: usize,
657 destination: usize,
658 weights: Vec<usize>,
660 fingerprint: Option<String>,
662}
663
664#[derive(Debug)]
667pub struct GraphAlgorithmExec {
668 shape: Shape,
669 input: Arc<dyn ExecutionPlan>,
670 weighted: Option<WeightedInput>,
671 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 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 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
815async 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 (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#[derive(Debug, Clone)]
871struct TraversalShape {
872 edges: Edges,
873 traversal: Traversal,
874 display: String,
876 schema: SchemaRef,
877}
878
879#[derive(Debug)]
882pub struct GraphTraversalExec {
883 shape: TraversalShape,
884 input: Arc<dyn ExecutionPlan>,
885 weighted: Option<WeightedInput>,
886 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 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
1035fn 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 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
1088fn 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
1096fn 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#[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#[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 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 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)); }
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 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
1234fn 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
1247fn endpoint_keys((source, destination): (usize, usize)) -> Vec<usize> {
1249 vec![source, destination]
1250}
1251
1252fn 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
1260fn 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
1288fn 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
1314async 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
1344async 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
1373async 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 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 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 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 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
1464async 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 crate::run_blocking(move || index.stored_weights(&key, n_weights))
1476 .await
1477 .ok()
1478 .flatten()
1479}
1480
1481async 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
1494async 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 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
1532fn 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
1548struct WeightReader {
1553 columns: Vec<usize>,
1554 values: Vec<Vec<f64>>,
1555 error: Option<DataFusionError>,
1556}
1557
1558impl WeightReader {
1559 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 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 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
1597async 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
1622const INTERN_ROWS: usize = 1 << 17;
1628
1629#[derive(Default)]
1631struct Gather {
1632 src: Vec<ArrayRef>,
1633 dst: Vec<ArrayRef>,
1634 rows: usize,
1635}
1636
1637impl Gather {
1638 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 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
1668fn 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
1681fn 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
1691fn 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
1712fn 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
1723fn 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
1741fn 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
1755enum Chunk {
1757 Nodes(ArrayRef),
1759 NodesDone,
1761 Edges(ArrayRef, ArrayRef),
1762 End,
1764}
1765
1766#[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
1792async 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
1814async 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#[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 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 Ok(())
1881}
1882
1883#[cfg(not(target_arch = "wasm32"))]
1886struct EdgeSide {
1887 interner: Option<EdgeInterner>,
1890 provisional: Option<EdgeInterner>,
1892 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 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#[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
1987async 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
2023async 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 #[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 let edges_read = send_edges(edges, shape, endpoints, weights, &tx).await;
2073 drop(tx);
2074 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 #[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
2127struct RowCheck<'a> {
2130 index: &'a GraphIndex,
2131 source: Vec<u32>,
2134 destination: Vec<u32>,
2135 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 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 fn complete(&self) -> bool {
2180 self.start == self.source.len()
2181 }
2182}
2183
2184#[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#[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
2207fn 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 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 let swapped = vec![(ints(&[20, 10, 10, 30]), ints(&[30, 20, 30, 10]))];
2268 assert!(!aligned(&built, &swapped).unwrap());
2269 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 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 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 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 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 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(¶llel),
2369 expected,
2370 "read ahead {read_ahead:?}"
2371 );
2372 }
2373 }
2374
2375 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 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 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 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}