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