diff --git a/crates/lance-csr/src/csr_expand.rs b/crates/lance-csr/src/csr_expand.rs index 06980bf..ad7f1cf 100644 --- a/crates/lance-csr/src/csr_expand.rs +++ b/crates/lance-csr/src/csr_expand.rs @@ -84,7 +84,7 @@ pub(crate) async fn cooperative_yield() { } /// Lance's row-address column (`lance_core::ROW_ADDR`, not re-exported by `lance`). -const ROW_ADDR: &str = "_rowaddr"; +pub(crate) const ROW_ADDR: &str = "_rowaddr"; use crate::case_insensitive::qualify_column; @@ -1212,7 +1212,73 @@ impl EdgeRows { matches!(self.data, TableData::Memory(_)) } - async fn take(&self, rows: &[u64], columns: &[usize]) -> Result> { + pub(crate) fn schema(&self) -> &SchemaRef { + &self.schema + } + + /// Every row, with a [`ROW_ADDR`] column holding the position [`Adjacency`] stores + /// for it (row address on Lance, row index in memory), so a full read and a CSR walk + /// name each edge the same way. + pub(crate) async fn read_all(&self) -> Result { + let (batch, addresses): (RecordBatch, ArrayRef) = match &self.data { + TableData::Memory(batch) => ( + batch.clone(), + Arc::new(arrow::array::UInt64Array::from_iter_values( + 0..batch.num_rows() as u64, + )), + ), + TableData::Lance(dataset) => { + let scan_error = + |e: lance::Error| exec_error(format!("Failed to scan edges: {}", e)); + let mut scanner = dataset.scan(); + scanner.with_row_address(); + let mut stream = scanner.try_into_stream().await.map_err(scan_error)?; + let mut read = Vec::new(); + while let Some(batch) = stream.next().await { + read.push(batch.map_err(scan_error)?); + cooperative_yield().await; + } + let schema = read.first().map_or_else( + || { + let mut fields: Vec = self + .schema + .fields() + .iter() + .map(|f| f.as_ref().clone()) + .collect(); + fields.push(Field::new(ROW_ADDR, DataType::UInt64, true)); + Arc::new(Schema::new(fields)) + }, + |b| b.schema(), + ); + let read = arrow::compute::concat_batches(&schema, &read) + .map_err(|e| exec_error(e.to_string()))?; + let index = read + .schema() + .index_of(ROW_ADDR) + .map_err(|e| exec_error(e.to_string()))?; + let addresses = read.column(index).clone(); + let mut columns = read.columns().to_vec(); + columns.remove(index); + let batch = RecordBatch::try_new(self.schema.clone(), columns) + .map_err(|e| exec_error(e.to_string()))?; + (batch, addresses) + } + }; + let mut fields: Vec = batch + .schema() + .fields() + .iter() + .map(|f| f.as_ref().clone()) + .collect(); + fields.push(Field::new(ROW_ADDR, DataType::UInt64, false)); + let mut columns = batch.columns().to_vec(); + columns.push(addresses); + RecordBatch::try_new(Arc::new(Schema::new(fields)), columns) + .map_err(|e| exec_error(e.to_string())) + } + + pub(crate) async fn take(&self, rows: &[u64], columns: &[usize]) -> Result> { self.data.take(&self.schema, rows, columns, true).await } @@ -1371,12 +1437,64 @@ impl EdgeMask { /// Shared by an operator's partitions: edges expanded before the relationship filter /// ran, and the filter's mask once that count made a full read worthwhile. #[derive(Default)] -struct EdgeFilterState { +pub(crate) struct EdgeFilterState { expanded: std::sync::atomic::AtomicU64, mask: std::sync::OnceLock>, building: futures::lock::Mutex<()>, } +impl EdgeFilterState { + /// Count `checked` more edges and, once the count reaches `mask_after`, read + /// `filter`'s columns whole into a mask. Returns the mask when there is one; the + /// check that crosses the threshold already uses it. + async fn mask_if_due( + &self, + rows: &EdgeRows, + filter: &CompiledFilter, + checked: u64, + mask_after: u64, + ) -> Result>> { + use std::sync::atomic::Ordering::Relaxed; + if self.mask.get().is_none() + && self.expanded.fetch_add(checked, Relaxed) + checked >= mask_after + { + let _building = self.building.lock().await; + if self.mask.get().is_none() { + let _ = self.mask.set(Arc::new(rows.mask(filter).await?)); + } + } + Ok(self.mask.get()) + } + + /// Which of `edge_rows` pass `filter`: the filter columns of just these rows, until + /// [`Self::mask_if_due`] switches to the mask. + pub(crate) async fn keep( + &self, + rows: &EdgeRows, + edge_rows: &[u64], + filter: &CompiledFilter, + mask_after: u64, + ) -> Result> { + let checked = edge_rows.len() as u64; + if let Some(mask) = self.mask_if_due(rows, filter, checked, mask_after).await? { + return Ok(edge_rows.iter().map(|&r| mask.contains(r)).collect()); + } + let columns = rows.take(edge_rows, &filter.columns).await?; + filter.keep(columns).map_err(|e| exec_error(e.to_string())) + } +} + +/// When a named path's [`EdgeFilterState`] switches to a whole-column mask, by the same +/// rule as [`CsrExpandExec`]: never in memory, where each check gathers from loaded +/// arrays; the shared mask only beats scattered Lance reads. +pub(crate) fn mask_after(rows: &EdgeRows, neighbors: &Neighbors) -> u64 { + if rows.in_memory() { + u64::MAX + } else { + (neighbors.num_edges() / EDGE_MASK_FRACTION).max(1) + } +} + impl fmt::Debug for EdgeFilterState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("EdgeFilterState") @@ -1601,7 +1719,7 @@ pub struct TargetLookup { /// A moved target or relationship filter compiled for one query: evaluated on just /// the columns it reads, for the candidate rows of each batch. #[derive(Debug, Clone)] -struct CompiledFilter { +pub(crate) struct CompiledFilter { predicate: Arc, /// Table column indices the predicate reads, ascending (`schema`'s order). columns: Vec, @@ -1611,7 +1729,7 @@ struct CompiledFilter { impl CompiledFilter { /// Compile `filter`, an expression over qualified columns such as `b__name`, /// against `table`'s own columns; `raw` maps each qualified name to its column. - fn new( + pub(crate) fn new( filter: &Expr, raw: &HashMap, table: &Schema, @@ -3037,6 +3155,8 @@ impl ExecutionPlan for CsrExpandExec { if let (Some(edge), Some(compiled)) = (&edge, filter) { // Decide before fetching: a chunk that crosses the threshold is // filtered by the new mask, without its own scattered fetch. + // Same rule as `EdgeFilterState::mask_if_due`, kept inline: awaiting + // that helper here slowed IC12 by 10% and custom query 30 by 6%. use std::sync::atomic::Ordering::Relaxed; let expanded = chunk.rows.len() as u64; if edge_state.expanded.fetch_add(expanded, Relaxed) + expanded >= mask_after @@ -3542,6 +3662,17 @@ fn prune_within( plan.map_children(|child| prune_within(child, used))? .transform_data(|node| { if let LogicalPlan::Extension(ext) = &node { + if let Some(path) = ext + .node + .as_any() + .downcast_ref::() + { + if let Some(pruned) = path.without_unused_path(used)? { + return Ok(Transformed::yes(LogicalPlan::Extension(Extension { + node: Arc::new(pruned), + }))); + } + } if let Some(csr) = ext.node.as_any().downcast_ref::() { if let Some(pruned) = csr.with_target_columns(used) { return Ok(Transformed::yes(LogicalPlan::Extension(Extension { @@ -4807,4 +4938,66 @@ mod tests { }; assert_eq!([1, 2, 3].map(|key| undirected.degree_bound(key)), [3, 2, 1]); } + + #[tokio::test] + async fn edge_filter_keeps_the_same_rows_per_edge_and_by_mask() { + use arrow::array::RecordBatchIterator; + let edges = RecordBatch::try_from_iter([ + ( + "src", + Arc::new(Int64Array::from((0..7).collect::>())) as ArrayRef, + ), + ( + "day", + Arc::new(Int64Array::from(vec![5, 1, 5, 5, 2, 5, 3])) as ArrayRef, + ), + ]) + .unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("edges.lance"); + let reader = RecordBatchIterator::new(vec![Ok(edges.clone())], edges.schema()); + let params = lance::dataset::WriteParams { + max_rows_per_file: 3, + ..Default::default() + }; + let mut dataset = Dataset::write(reader, path.to_str().unwrap(), Some(params)) + .await + .unwrap(); + dataset.delete("src = 3").await.unwrap(); + let state = datafusion::prelude::SessionContext::new().state(); + let filter = Expr::Column(Column::from_name("day")).eq(datafusion::prelude::lit(5_i64)); + // Rows 0, 1, 2 in fragment 0; 4, 5 in fragment 1 (3 deleted); 6 in fragment 2. + let addresses = [0, 1, 2, (1 << 32) | 1, (1 << 32) | 2, 2 << 32]; + let expected = [true, false, true, false, true, false]; + for rows in [ + EdgeRows::from_lance(Arc::new(dataset.clone())), + EdgeRows::from_batch(edges.clone()), + ] { + let compiled = + CompiledFilter::new(&filter, &HashMap::new(), rows.schema(), &state).unwrap(); + let addresses: Vec = if rows.in_memory() { + vec![0, 1, 2, 4, 5, 6] + } else { + addresses.to_vec() + }; + // Per edge: the threshold is never reached. + let lazy = EdgeFilterState::default(); + for (row, keep) in addresses.iter().zip(expected) { + assert_eq!( + lazy.keep(&rows, &[*row], &compiled, u64::MAX) + .await + .unwrap(), + [keep] + ); + } + assert!(lazy.mask.get().is_none()); + // By mask: the first check crosses the threshold. + let masked = EdgeFilterState::default(); + assert_eq!( + masked.keep(&rows, &addresses, &compiled, 1).await.unwrap(), + expected + ); + assert!(masked.mask.get().is_some()); + } + } } diff --git a/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs b/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs index 829a63c..f7cd101 100644 --- a/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs +++ b/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs @@ -2,12 +2,14 @@ // SPDX-FileCopyrightText: Copyright The lance-csr Authors use crate::ast::PathPattern; +use crate::ast::RelationshipDirection; use crate::case_insensitive::qualify_column; +use crate::csr_expand::{AdjacencyCatalog, Neighbors}; use crate::datafusion_planner::{analysis::PlanningContext, DataFusionPlanner}; use crate::error::{GraphError, Result}; use crate::logical_plan::LogicalOperator; use crate::path_inventory::{EdgeSource, NodeSource}; -use crate::path_match::{Binding, PathMatchNode, PathSpec, Step}; +use crate::path_match::{Binding, CsrHop, CsrRoute, PathMatchNode, PathSpec, Step}; use datafusion::logical_expr::{Extension, LogicalPlan, LogicalPlanBuilder}; use std::sync::Arc; @@ -82,6 +84,7 @@ impl DataFusionPlanner { ); } let mut edges = Vec::new(); + let mut edge_plans = Vec::new(); for label in &edge_labels { let mapping = self.get_relationship_mapping(label)?; let source = catalog @@ -115,12 +118,19 @@ impl DataFusionPlanner { source_id: mapping.source_id_field.clone(), target_id: mapping.target_id_field.clone(), schema, + rows: self + .adjacency + .as_ref() + .and_then(|catalog| catalog.edges(label).cloned()), }); - plans.push( - LogicalPlanBuilder::scan(label.to_lowercase(), source, None) - .and_then(|b| b.build()) - .map_err(|e| self.plan_error("Failed to scan path edges", e))?, - ); + // A type with engine rows is read from them, by either route; see `EdgeSource::rows`. + if edges.last().is_some_and(|e| e.rows.is_none()) { + edge_plans.push( + LogicalPlanBuilder::scan(label.to_lowercase(), source, None) + .and_then(|b| b.build()) + .map_err(|e| self.plan_error("Failed to scan path edges", e))?, + ); + } } let mut bindings = Vec::new(); for node in @@ -188,6 +198,14 @@ impl DataFusionPlanner { relationship: rel.variable.clone(), }); } + let csr = self + .adjacency + .as_ref() + .filter(|_| shortest.is_none()) + .and_then(|catalog| csr_route(catalog, &edge_labels, &edges, &steps)); + if csr.is_none() { + plans.extend(edge_plans); + } let variable = match &path.shortest { Some(shortest) => Some( shortest @@ -207,6 +225,7 @@ impl DataFusionPlanner { bindings, steps, shortest, + csr, }, std::sync::Arc::clone(&ctx.path_sources), std::iter::once(&path.start_node.properties) @@ -227,3 +246,47 @@ impl DataFusionPlanner { })) } } + +/// The engine's CSR for every type and direction the steps follow, or `None` if one is +/// missing (the edge inventory then serves the path). +fn csr_route( + catalog: &AdjacencyCatalog, + labels: &[String], + edges: &[EdgeSource], + steps: &[Step], +) -> Option { + if edges.iter().any(|e| e.rows.is_none()) { + return None; + } + let steps = steps + .iter() + .map(|step| { + let mut hops = Vec::new(); + for &kind in &step.types { + let (label, edge) = (&labels[kind], &edges[kind]); + let halves: &[(bool, bool)] = match step.direction { + RelationshipDirection::Outgoing => &[(true, false)], + RelationshipDirection::Incoming => &[(false, false)], + RelationshipDirection::Undirected => &[(true, false), (false, true)], + }; + for &(outgoing, second) in halves { + let (from, to) = if outgoing { + (edge.source_label, edge.target_label) + } else { + (edge.target_label, edge.source_label) + }; + hops.push(CsrHop { + kind, + neighbors: Neighbors::directed(catalog.get(label, outgoing)?.clone()), + from, + to, + reversed: !outgoing, + skip_self_loops: second && from == to, + }); + } + } + Some(hops) + }) + .collect::>>()?; + Some(CsrRoute { steps }) +} diff --git a/crates/lance-csr/src/path_inventory.rs b/crates/lance-csr/src/path_inventory.rs index e8ad859..871fae9 100644 --- a/crates/lance-csr/src/path_inventory.rs +++ b/crates/lance-csr/src/path_inventory.rs @@ -21,7 +21,7 @@ use futures::{lock::Mutex, StreamExt}; /// One source scan per query, shared even by distinct named-path operators. pub(crate) type SourceBatches = Arc>>; -use crate::csr_expand::{cooperative_yield, is_supported_id_type}; +use crate::csr_expand::{cooperative_yield, is_supported_id_type, EdgeRows, ROW_ADDR}; use crate::path_value::{entity_type, struct_array}; #[derive(Debug, Clone)] @@ -39,6 +39,23 @@ pub(crate) struct EdgeSource { pub source_id: String, pub target_id: String, pub schema: Arc, + /// The engine's rows for this type when it has a CSR. Every path route then reads the + /// type from them, so a relationship's identity is the same on all routes. + pub rows: Option>, +} + +/// A relationship's `{label, id}` identity, shared by every path route. +pub(crate) fn relationship_identity(labels: Vec<&str>, ids: Vec) -> StructArray { + StructArray::from(vec![ + ( + Arc::new(Field::new("label", DataType::Utf8, false)), + Arc::new(StringArray::from(labels)) as ArrayRef, + ), + ( + Arc::new(Field::new("id", DataType::Int64, false)), + Arc::new(Int64Array::from(ids)) as ArrayRef, + ), + ]) } pub(crate) fn property_fields<'a>(schemas: impl IntoIterator) -> Result { @@ -81,7 +98,7 @@ pub(crate) fn id_column(batch: &RecordBatch, name: &str) -> Result { .clone()) } -fn properties(batch: &RecordBatch, fields: &Fields) -> Result { +pub(crate) fn properties(batch: &RecordBatch, fields: &Fields) -> Result { let columns = fields .iter() .map(|f| { @@ -116,7 +133,7 @@ pub(crate) struct Inventory { pub node_labels: Vec, pub edge_types: Vec, pub endpoints: Vec>, - pub by_key: HashMap<(usize, i64), u32>, + pub by_key: HashMap<(usize, i64), u32, ahash::RandomState>, pub neighbors: Vec>, } @@ -128,21 +145,47 @@ impl Inventory { context: Arc, sources: &SourceBatches, ) -> Result { - let mut batches = Vec::with_capacity(plans.len()); - let source_keys = node_sources + // Plans scan the node tables, then the relationship tables without engine rows. + let mut batches = Vec::with_capacity(node_sources.len() + edge_sources.len()); + let mut plans = plans.iter(); + let keyed = node_sources .iter() - .map(|s| (false, s.label.to_lowercase())) - .chain(edge_sources.iter().map(|s| (true, s.label.to_lowercase()))); - for (plan, key) in plans.iter().zip(source_keys) { + .map(|s| (false, s.label.to_lowercase(), None)) + .chain( + edge_sources + .iter() + .map(|s| (true, s.label.to_lowercase(), s.rows.as_ref())), + ); + for (edge, label, rows) in keyed { + let key = (edge, label); let mut sources = sources.lock().await; + let plan = if rows.is_none() { + Some(plans.next().ok_or_else(|| { + datafusion::common::DataFusionError::Internal( + "path source without a scan".into(), + ) + })?) + } else { + None + }; if !sources.contains_key(&key) { - let mut stream = plan.execute(0, context.clone())?; - let mut read = Vec::new(); - while let Some(batch) = stream.next().await { - read.push(batch?); - cooperative_yield().await; - } - sources.insert(key.clone(), concat_batches(&plan.schema(), &read)?); + let batch = match (rows, plan) { + (Some(rows), _) => rows + .read_all() + .await + .map_err(|e| datafusion::common::DataFusionError::External(Box::new(e)))?, + (None, Some(plan)) => { + let mut stream = plan.execute(0, context.clone())?; + let mut read = Vec::new(); + while let Some(batch) = stream.next().await { + read.push(batch?); + cooperative_yield().await; + } + concat_batches(&plan.schema(), &read)? + } + (None, None) => unreachable!("a scan or engine rows"), + }; + sources.insert(key.clone(), batch); } batches.push(sources[&key].clone()); } @@ -150,7 +193,7 @@ impl Inventory { let edge_fields = property_fields(edge_sources.iter().map(|s| s.schema.fields()))?; let node_type = entity_type(node_fields.clone(), "node", None); let edge_type = entity_type(edge_fields.clone(), "relationship", Some(&node_type)); - let mut by_key = HashMap::new(); + let mut by_key = HashMap::default(); let mut node_labels = Vec::new(); let mut labels = Vec::new(); let mut ids = Vec::new(); @@ -211,6 +254,10 @@ impl Inventory { let batch = &batches[node_sources.len() + kind]; let sources = id_column(batch, &source.source_id)?; let targets = id_column(batch, &source.target_id)?; + // Engine rows carry the identity the CSR uses; a plain scan numbers its rows. + let row_ids = batch + .column_by_name(ROW_ADDR) + .map(|ids| ids.as_primitive::().clone()); for row in 0..batch.num_rows() { let edge = u32::try_from(endpoints.len()).map_err(|_| { datafusion::common::DataFusionError::Execution( @@ -241,7 +288,11 @@ impl Inventory { } endpoints.push(ends); edge_types.push(kind); - occurrence_ids.push(row as i64); + occurrence_ids.push( + row_ids + .as_ref() + .map_or(row as i64, |ids| ids.value(row) as i64), + ); labels.push(source.label.as_str()); if row % 4096 == 4095 { cooperative_yield().await; @@ -250,16 +301,7 @@ impl Inventory { edge_batches.push(properties(batch, &edge_fields)?); } let edge_properties = concat_batches(&Arc::new(Schema::new(edge_fields)), &edge_batches)?; - let identity = StructArray::from(vec![ - ( - Arc::new(Field::new("label", DataType::Utf8, false)), - Arc::new(StringArray::from(labels)) as ArrayRef, - ), - ( - Arc::new(Field::new("id", DataType::Int64, false)), - Arc::new(Int64Array::from(occurrence_ids)) as ArrayRef, - ), - ]); + let identity = relationship_identity(labels, occurrence_ids); let starts = UInt32Array::from_iter(endpoints.iter().map(|p| p.map(|(a, _)| a))); let ends = UInt32Array::from_iter(endpoints.iter().map(|p| p.map(|(_, b)| b))); let edges = struct_array( diff --git a/crates/lance-csr/src/path_match.rs b/crates/lance-csr/src/path_match.rs index dbf0b9a..de83135 100644 --- a/crates/lance-csr/src/path_match.rs +++ b/crates/lance-csr/src/path_match.rs @@ -1,8 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The lance-csr Authors -//! Rich paths use an immutable edge inventory, resumable trail enumeration, and the -//! existing bidirectional BFS on a bipartite node/edge graph for shortest paths. +//! Rich paths enumerate trails resumably, either by walking the engine's CSR, checking +//! relationship filters only on the edges reached (the approach Kùzu takes for filtered +//! recursive joins), or over an immutable edge inventory. Shortest paths use the existing +//! bidirectional BFS on a bipartite node/edge graph of the inventory. use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; @@ -10,7 +12,9 @@ use std::fmt; use std::hash::{Hash, Hasher}; use std::sync::Arc; -use arrow::array::{Array, ArrayRef, AsArray, BooleanArray, Int64Array, RecordBatch, UInt32Array}; +use arrow::array::{ + Array, ArrayRef, AsArray, BooleanArray, Int64Array, RecordBatch, StructArray, UInt32Array, +}; use arrow::compute::take; use arrow_schema::{Field, Schema, SchemaRef}; use datafusion::common::tree_node::{Transformed, TransformedResult, TreeNodeRecursion}; @@ -28,9 +32,12 @@ use datafusion::physical_plan::{ use futures::{lock::Mutex, StreamExt}; use crate::ast::{PropertyValue, RelationshipDirection}; -use crate::csr_expand::{cooperative_yield, Adjacency, Neighbors}; +use crate::csr_expand::{ + cooperative_yield, mask_after, Adjacency, CompiledFilter, EdgeFilterState, EdgeRows, Neighbors, +}; use crate::path_inventory::{ - id_column, property_fields, EdgeSource, Inventory, NodeSource, SourceBatches, + id_column, properties, property_fields, relationship_identity, EdgeSource, Inventory, + NodeSource, SourceBatches, }; use crate::path_value::{entity_type, path_type, paths_array, PathRows}; @@ -52,7 +59,7 @@ pub(crate) struct Step { pub relationship: Option, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub(crate) struct PathSpec { pub variable: Option, /// Expose typed boundary-node values alongside their property columns. @@ -63,6 +70,40 @@ pub(crate) struct PathSpec { pub steps: Vec, /// Some(all): exactly one shortest-path segment, with both endpoints bound. pub shortest: Option, + /// Walk the engine's CSR instead of building an edge inventory. + pub csr: Option, +} + +/// The engine's CSR for every relationship a trail walk follows. Edges are read +/// only where the walk goes; an edge's identity is its row in the CSR. +#[derive(Debug, Clone)] +pub(crate) struct CsrRoute { + /// Per step, every (type, direction) adjacency the step follows. Each type's rows are + /// its `EdgeSource::rows`. + pub steps: Vec>, +} + +impl PathSpec { + /// The engine rows of relationship type `kind`, which the CSR route requires. + fn rows(&self, kind: usize) -> &EdgeRows { + self.edges[kind] + .rows + .as_deref() + .expect("csr route has engine rows") + } +} + +#[derive(Debug, Clone)] +pub(crate) struct CsrHop { + pub kind: usize, + pub neighbors: Neighbors, + /// Labels of the node a hop leaves and the node it reaches. + pub from: usize, + pub to: usize, + /// The adjacency is keyed by target: the edge runs from `to` to `from`. + pub reversed: bool, + /// The incoming half of an undirected step: the outgoing half already matched self-loops. + pub skip_self_loops: bool, } #[derive(Clone)] @@ -198,6 +239,34 @@ impl PathMatchNode { outputs, }) } + + /// This node without its path value, when no column in `used` reads the path. + pub(crate) fn without_unused_path(&self, used: &HashSet) -> Result> { + let Some(variable) = &self.spec.variable else { + return Ok(None); + }; + if used.contains(&variable.to_lowercase()) { + return Ok(None); + } + // The path value is the last column `try_new` adds. + let kept = self.schema.fields().len() - 1; + let schema = DFSchema::new_with_metadata( + self.schema + .iter() + .take(kept) + .map(|(qualifier, field)| (qualifier.cloned(), Arc::clone(field))) + .collect(), + self.schema.metadata().clone(), + )? + .with_functional_dependencies(self.schema.functional_dependencies().clone())?; + let mut spec = PathSpec::clone(&self.spec); + spec.variable = None; + Ok(Some(Self { + spec: Arc::new(spec), + schema: Arc::new(schema), + ..self.clone() + })) + } } impl PartialEq for PathMatchNode { fn eq(&self, other: &Self) -> bool { @@ -265,6 +334,8 @@ impl UserDefinedLogicalNodeCore for PathMatchNode { self.spec.variable.as_deref().unwrap_or("endpoints"), if self.spec.shortest.is_some() { "shortest edge inventory" + } else if self.spec.csr.is_some() { + "trail csr walk" } else { "trail edge inventory" } @@ -323,7 +394,23 @@ struct Ready { inventory: Inventory, nodes_allowed: Vec, edges_allowed: Vec, + /// Each node's key, by inventory position. + node_keys: Int64Array, shortest: Option<(Neighbors, Neighbors)>, + /// CSR route only: per step and hop, its filter and what that filter has checked. + hops: Vec)>>, + /// CSR route only: the inventory has no edges, so relationship values are built here. + edge_type: arrow_schema::DataType, + edge_fields: arrow_schema::Fields, +} + +/// A step's relationship filter, compiled for one hop's table. +#[derive(Debug, Clone)] +enum HopFilter { + All, + /// The table lacks a filtered property, so no edge has a value equal to it. + None, + Where(CompiledFilter), } struct PathMatchExec { @@ -336,6 +423,8 @@ struct PathMatchExec { schema: SchemaRef, properties: Arc, predicates: Vec>>, + /// CSR route only: per step and hop, its relationship filter. + hop_filters: Vec>, ready: Arc>>>, } @@ -374,6 +463,44 @@ pub(crate) fn plan_path_match( .transpose() }) .collect::>>()?; + let hop_filters = node + .spec + .csr + .iter() + .flat_map(|csr| csr.steps.iter().enumerate()) + .map(|(step, hops)| { + let filters = &node.filters[node.spec.bindings.len() + step]; + hops.iter() + .map(|hop| { + if filters.is_empty() { + return Ok(HopFilter::All); + } + let table = node.spec.rows(hop.kind).schema(); + let mut terms = Vec::new(); + for (key, value) in filters { + let Some(field) = table + .fields() + .iter() + .find(|f| f.name().eq_ignore_ascii_case(key)) + else { + return Ok(HopFilter::None); + }; + terms.push( + Expr::Column(datafusion::common::Column::from_name(field.name())) + .eq(value.clone()), + ); + } + let filter = terms.into_iter().reduce(Expr::and).expect("filtered"); + Ok(HopFilter::Where(CompiledFilter::new( + &filter, + &HashMap::new(), + table, + state, + )?)) + }) + .collect::>>() + }) + .collect::>>()?; let schema = Arc::new(node.schema.as_arrow().clone()); let properties = Arc::new(PlanProperties::new( EquivalenceProperties::new(schema.clone()), @@ -390,6 +517,7 @@ pub(crate) fn plan_path_match( schema, properties, predicates, + hop_filters, ready: Arc::new(Mutex::new(None)), })) } @@ -407,8 +535,13 @@ impl DisplayAs for PathMatchExec { fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { write!( f, - "PathMatchExec: {} edge inventory", - self.spec.variable.as_deref().unwrap_or("endpoints") + "PathMatchExec: {} {}", + self.spec.variable.as_deref().unwrap_or("endpoints"), + if self.spec.csr.is_some() { + "csr walk" + } else { + "edge inventory" + } ) } } @@ -453,6 +586,7 @@ impl ExecutionPlan for PathMatchExec { schema: self.schema.clone(), properties, predicates: self.predicates.clone(), + hop_filters: self.hop_filters.clone(), ready: self.ready.clone(), })) } @@ -463,27 +597,36 @@ impl ExecutionPlan for PathMatchExec { ) -> Result { let (input, input_time) = crate::exec_metrics::time_input(self.inputs[0].execute(partition, context.clone())?); - let (cell, plans, spec, outputs, schema, predicates) = ( + let (cell, plans, spec, outputs, schema, predicates, hop_filters) = ( self.ready.clone(), self.inputs[1..].to_vec(), self.spec.clone(), self.outputs.clone(), self.schema.clone(), self.predicates.clone(), + self.hop_filters.clone(), ); let sources = self.sources.clone(); + let reads_edges = spec.variable.is_some() + || outputs.iter().any(|o| { + matches!( + o, + Output::RelationshipValue { .. } | Output::Relationship { .. } + ) + }); let out_schema = schema.clone(); let batch_size = context.session_config().batch_size(); let stream = futures::stream::try_unfold( (input, None::), move |(mut input, mut pending)| { - let (cell, plans, spec, outputs, schema, predicates, context) = ( + let (cell, plans, spec, outputs, schema, predicates, hop_filters, context) = ( cell.clone(), plans.clone(), spec.clone(), outputs.clone(), schema.clone(), predicates.clone(), + hop_filters.clone(), context.clone(), ); let sources = sources.clone(); @@ -502,6 +645,7 @@ impl ExecutionPlan for PathMatchExec { &spec, &plans, &predicates, + &hop_filters, context.clone(), &sources, ) @@ -513,11 +657,17 @@ impl ExecutionPlan for PathMatchExec { pending = Some(Pending::new(batch, graph, &spec)?); } let p = pending.as_mut().unwrap(); - let (rows, paths) = p.next(&spec, batch_size).await?; + let (rows, mut paths) = p.next(&spec, batch_size).await?; if rows.is_empty() { pending = None; continue; } + let edges = match &spec.csr { + Some(_) if reads_edges => p.csr_edges(&spec, &mut paths).await?, + // Nothing reads relationship records: don't fetch them. + Some(_) => StructArray::new_empty_fields(0, None), + None => p.graph.inventory.edges.clone(), + }; let indices = UInt32Array::from(rows); let mut columns: Vec = p .batch @@ -538,7 +688,7 @@ impl ExecutionPlan for PathMatchExec { let positions = UInt32Array::from_iter_values( paths.iter().map(|p| p.edges[p.boundaries[*step]]), ); - columns.push(take(&p.graph.inventory.edges, &positions, None)?); + columns.push(take(&edges, &positions, None)?); continue; } Output::Node { boundary, property } => ( @@ -548,7 +698,7 @@ impl ExecutionPlan for PathMatchExec { ), ), Output::Relationship { step, property } => ( - p.graph.inventory.edge_properties.column(*property), + edges.column(0).as_struct().column(*property), UInt32Array::from_iter_values( paths.iter().map(|p| p.edges[p.boundaries[*step]]), ), @@ -557,11 +707,7 @@ impl ExecutionPlan for PathMatchExec { columns.push(take(array, &positions, None)?); } if spec.variable.is_some() { - columns.push(paths_array( - &paths, - &p.graph.inventory.nodes, - &p.graph.inventory.edges, - )?); + columns.push(paths_array(&paths, &p.graph.inventory.nodes, &edges)?); } let batch = RecordBatch::try_new(schema, columns)?; return Ok(Some((batch, (input, pending)))); @@ -585,10 +731,37 @@ impl Ready { spec: &PathSpec, plans: &[Arc], predicates: &[Option>], + hop_filters: &[Vec], context: Arc, sources: &SourceBatches, ) -> Result { - let inventory = Inventory::build(&spec.nodes, &spec.edges, plans, context, sources).await?; + // The CSR route reads no relationship table up front: its plans scan only nodes. + let edges = if spec.csr.is_some() { + &[][..] + } else { + &spec.edges + }; + let inventory = Inventory::build(&spec.nodes, edges, plans, context, sources).await?; + let edge_fields = property_fields(spec.edges.iter().map(|s| s.schema.fields()))?; + let node_type = inventory.nodes.data_type().clone(); + let edge_type = entity_type(edge_fields.clone(), "relationship", Some(&node_type)); + // Hops of one step over the same table share a state: the two halves of an + // undirected step then count their checks together and read one mask. + let hops = match &spec.csr { + Some(csr) => csr + .steps + .iter() + .zip(hop_filters) + .map(|(step, filters)| { + let mut states: HashMap> = HashMap::new(); + step.iter() + .zip(filters) + .map(|(hop, f)| (f.clone(), states.entry(hop.kind).or_default().clone())) + .collect() + }) + .collect(), + None => Vec::new(), + }; let mask = |p: &Option>, batch: &RecordBatch| -> Result { match p { @@ -606,6 +779,7 @@ impl Ready { .collect::>>()?; let edges_allowed = predicates[spec.bindings.len()..] .iter() + .filter(|_| spec.csr.is_none()) .map(|p| mask(p, &inventory.edge_properties)) .collect::>>()?; let shortest = if spec.shortest.is_some() { @@ -667,15 +841,134 @@ impl Ready { } else { None }; + let node_keys = inventory + .nodes + .column(1) + .as_struct() + .column(1) + .as_primitive::() + .clone(); Ok(Self { inventory, nodes_allowed, edges_allowed, shortest, + hops, + edge_type, + edge_fields, + node_keys, }) } } +/// An edge a CSR walk can enter: its type, CSR row and inventory endpoints. +#[derive(Clone, Copy)] +struct CsrEdge { + kind: usize, + row: u64, + source: u32, + target: u32, +} + +/// Numbers the CSR edges a batch's walks enter, so a trail can check reuse and paths +/// can refer to edges as the inventory route does. Also keeps each (step, node)'s +/// candidates: trails reach the same node many times, and the list never changes. +#[derive(Default)] +struct CsrEdges { + ids: HashMap<(usize, u64), u32, ahash::RandomState>, + edges: Vec, + candidates: HashMap<(usize, u32), Candidates, ahash::RandomState>, + /// Relationship records built for returned paths, kept for the batch's later output. + records: Vec, + /// Per edge id, its record's (part, offset) in `records`. + record: HashMap, +} + +/// (next node, edge id) pairs a frame can take. +type Candidates = Arc<[(u32, u32)]>; + +impl CsrEdges { + fn id(&mut self, edge: CsrEdge) -> u32 { + *self.ids.entry((edge.kind, edge.row)).or_insert_with(|| { + self.edges.push(edge); + (self.edges.len() - 1) as u32 + }) + } +} + +/// The edges a step can take from `node`, through the engine's CSR, that pass the step's +/// filter and reach a node of the inventory, read once per batch. Filters read only these +/// edges' columns. +async fn csr_candidates( + spec: &PathSpec, + graph: &Ready, + edges: &mut CsrEdges, + stage: usize, + node: u32, +) -> Result { + if let Some(candidates) = edges.candidates.get(&(stage, node)) { + return Ok(candidates.clone()); + } + let csr = spec.csr.as_ref().expect("csr route"); + let key = graph.node_keys.value(node as usize); + let label = graph.inventory.node_labels[node as usize]; + let mut candidates = Vec::new(); + for (hop, (filter, state)) in csr.steps[stage].iter().zip(&graph.hops[stage]) { + if hop.from != label || matches!(filter, HopFilter::None) { + continue; + } + let first = candidates.len(); + let mut position = Default::default(); + for (neighbor, row) in hop + .neighbors + .candidates_from::(key, &mut position) + .flatten() + { + let neighbor = neighbor as i64; + if hop.skip_self_loops && neighbor == key { + continue; + } + let Some(&next) = graph.inventory.by_key.get(&(hop.to, neighbor)) else { + continue; + }; + let (source, target) = if hop.reversed { + (next, node) + } else { + (node, next) + }; + candidates.push(( + next, + CsrEdge { + kind: hop.kind, + row, + source, + target, + }, + )); + } + if let HopFilter::Where(filter) = filter { + let rows = spec.rows(hop.kind); + let edge_rows: Vec = candidates[first..].iter().map(|(_, e)| e.row).collect(); + let keep = state + .keep(rows, &edge_rows, filter, mask_after(rows, &hop.neighbors)) + .await + .map_err(|e| datafusion::common::DataFusionError::External(Box::new(e)))?; + let mut keep = keep.into_iter(); + let mut index = 0; + candidates.retain(|_| { + index += 1; + index <= first || keep.next().unwrap_or(false) + }); + } + } + let candidates: Candidates = candidates + .into_iter() + .map(|(next, edge)| (next, edges.id(edge))) + .collect(); + edges.candidates.insert((stage, node), candidates.clone()); + Ok(candidates) +} + struct Pending { batch: RecordBatch, graph: Arc, @@ -683,6 +976,8 @@ struct Pending { row: usize, walk: Option, shortest: Option, + /// CSR route only: the edges this batch's walks entered. + edges: CsrEdges, } impl Pending { fn new(batch: RecordBatch, graph: Arc, spec: &PathSpec) -> Result { @@ -705,8 +1000,86 @@ impl Pending { row: 0, walk: None, shortest: None, + edges: CsrEdges::default(), }) } + /// Relationship values for the edges of `paths`, read from their tables now. Renumbers + /// each path's edges to their positions in the returned array. + async fn csr_edges(&mut self, spec: &PathSpec, paths: &mut [PathRows]) -> Result { + let used: Vec = paths + .iter_mut() + .flat_map(|p| p.edges.iter_mut()) + .enumerate() + .map(|(position, edge)| std::mem::replace(edge, position as u32)) + .collect(); + // Paths share edges: read and build each edge once per input batch, by type, then + // pick every path's records from those parts. + let mut distinct: Vec = used + .iter() + .copied() + .filter(|id| !self.edges.record.contains_key(id)) + .collect(); + distinct.sort_unstable_by_key(|&id| (self.edges.edges[id as usize].kind, id)); + distinct.dedup(); + let error = |e: crate::error::GraphError| { + datafusion::common::DataFusionError::External(Box::new(e)) + }; + for kind in 0..spec.edges.len() { + let ids: Vec = distinct + .iter() + .copied() + .filter(|&id| self.edges.edges[id as usize].kind == kind) + .collect(); + let edges: Vec = ids + .iter() + .map(|&id| self.edges.edges[id as usize]) + .collect(); + if edges.is_empty() { + continue; + } + let rows = spec.rows(kind); + let edge_rows: Vec = edges.iter().map(|e| e.row).collect(); + let columns: Vec = (0..rows.schema().fields().len()).collect(); + let batch = RecordBatch::try_new( + rows.schema().clone(), + rows.take(&edge_rows, &columns).await.map_err(error)?, + )?; + let ends = + |end: fn(&CsrEdge) -> u32| UInt32Array::from_iter_values(edges.iter().map(end)); + let identity = relationship_identity( + vec![spec.edges[kind].label.as_str(); edges.len()], + edge_rows.iter().map(|&r| r as i64).collect(), + ); + let properties = properties(&batch, &self.graph.edge_fields)?; + let part = self.edges.records.len(); + self.edges.record.extend( + ids.iter() + .enumerate() + .map(|(offset, &id)| (id, (part, offset))), + ); + self.edges + .records + .push(Arc::new(crate::path_value::struct_array( + &self.graph.edge_type, + vec![ + Arc::new(StructArray::from(properties)), + Arc::new(identity), + take(&self.graph.inventory.nodes, &ends(|e| e.source), None)?, + take(&self.graph.inventory.nodes, &ends(|e| e.target), None)?, + ], + ))); + } + if used.is_empty() { + return Ok(arrow::array::new_empty_array(&self.graph.edge_type) + .as_struct() + .clone()); + } + let parts: Vec<&dyn Array> = self.edges.records.iter().map(|a| a.as_ref()).collect(); + let positions: Vec<(usize, usize)> = used.iter().map(|id| self.edges.record[id]).collect(); + Ok(arrow::compute::interleave(&parts, &positions)? + .as_struct() + .clone()) + } fn bound(&self, spec: &PathSpec) -> Option>> { self.keys .iter() @@ -772,7 +1145,11 @@ impl Pending { let path = if let Some(search) = &mut self.shortest { search.next().await } else { - self.walk.as_mut().unwrap().next(spec, &self.graph).await + self.walk + .as_mut() + .unwrap() + .next(spec, &self.graph, &mut self.edges) + .await? }; if let Some(path) = path { rows.push(self.row as u32); @@ -799,6 +1176,8 @@ struct Frame { next: usize, advanced: bool, entered: bool, + /// CSR route only: the edges this frame can take, read when it first needs one. + candidates: Option, } struct Walk { frames: Vec, @@ -815,6 +1194,7 @@ impl Walk { next: 0, advanced: false, entered: false, + candidates: None, }], path: PathRows { nodes: vec![source], @@ -833,7 +1213,12 @@ impl Walk { self.path.boundaries.pop(); } } - async fn next(&mut self, spec: &PathSpec, graph: &Ready) -> Option { + async fn next( + &mut self, + spec: &PathSpec, + graph: &Ready, + edges: &mut CsrEdges, + ) -> Result> { let mut work = 0_usize; while let Some(frame) = self.frames.last_mut() { work += 1; @@ -843,7 +1228,7 @@ impl Walk { if frame.stage == spec.steps.len() { if !frame.advanced { frame.advanced = true; - return Some(self.path.clone()); + return Ok(Some(self.path.clone())); } self.pop(); continue; @@ -869,6 +1254,7 @@ impl Walk { next: 0, advanced: false, entered: false, + candidates: None, }; self.path.boundaries.push(self.path.nodes.len() - 1); self.frames.push(next); @@ -879,38 +1265,58 @@ impl Walk { self.pop(); continue; } - let Some(edge) = graph.inventory.neighbors[frame.node as usize].get(frame.next) else { - self.pop(); - continue; - }; - frame.next += 1; - let direction = match step.direction { - RelationshipDirection::Outgoing => edge.outgoing, - RelationshipDirection::Incoming => !edge.outgoing || edge.node == frame.node, - RelationshipDirection::Undirected => true, + let (edge, node) = if spec.csr.is_some() { + if frame.candidates.is_none() { + frame.candidates = + Some(csr_candidates(spec, graph, edges, frame.stage, frame.node).await?); + } + let candidates = frame.candidates.as_ref().expect("fetched"); + let Some(&(node, edge)) = candidates.get(frame.next) else { + self.pop(); + continue; + }; + frame.next += 1; + if self.path.edges.contains(&edge) { + continue; + } + (edge, node) + } else { + let Some(edge) = graph.inventory.neighbors[frame.node as usize].get(frame.next) + else { + self.pop(); + continue; + }; + frame.next += 1; + let direction = match step.direction { + RelationshipDirection::Outgoing => edge.outgoing, + RelationshipDirection::Incoming => !edge.outgoing || edge.node == frame.node, + RelationshipDirection::Undirected => true, + }; + if !direction + || !step + .types + .contains(&graph.inventory.edge_types[edge.edge as usize]) + || self.path.edges.contains(&edge.edge) + || !allowed(&graph.edges_allowed[frame.stage], edge.edge) + { + continue; + } + (edge.edge, edge.node) }; - if !direction - || !step - .types - .contains(&graph.inventory.edge_types[edge.edge as usize]) - || self.path.edges.contains(&edge.edge) - || !allowed(&graph.edges_allowed[frame.stage], edge.edge) - { - continue; - } let next = Frame { stage: frame.stage, hops: frame.hops + 1, - node: edge.node, + node, next: 0, advanced: false, entered: true, + candidates: None, }; - self.path.nodes.push(edge.node); - self.path.edges.push(edge.edge); + self.path.nodes.push(node); + self.path.edges.push(edge); self.frames.push(next); } - None + Ok(None) } } @@ -1038,6 +1444,7 @@ mod tests { source_id: "src".into(), target_id: "dst".into(), schema: edge_batch.schema(), + rows: None, }], bindings: vec![binding("a"), binding("b")], steps: vec![Step { @@ -1048,6 +1455,7 @@ mod tests { relationship: None, }], shortest, + csr: None, }; let ctx = SessionContext::new(); let mut plans = Vec::new(); @@ -1064,6 +1472,7 @@ mod tests { &spec, &plans, &[None, None, None], + &[], ctx.task_ctx(), &Default::default(), ) @@ -1077,7 +1486,11 @@ mod tests { let (spec, graph) = graph(&[(1, 2), (1, 2), (2, 3), (3, 3)], 20, None).await; let mut walk = Walk::new(0, vec![Some(0), None]); let mut paths = Vec::new(); - while let Some(path) = walk.next(&spec, &graph).await { + while let Some(path) = walk + .next(&spec, &graph, &mut Default::default()) + .await + .unwrap() + { paths.push(path); } assert_eq!(paths.len(), 7); // identity, two one-hop, two two-hop, two with self-loop @@ -1138,8 +1551,13 @@ mod tests { async fn rejected_hub_yields_before_scanning_all_edges() { let (spec, graph) = graph(&(2..100_002).map(|n| (1, n)).collect::>(), 1, None).await; let mut walk = Walk::new(0, vec![Some(0), Some(0)]); - assert!(walk.next(&spec, &graph).await.is_some()); // zero hop - let mut next = Box::pin(walk.next(&spec, &graph)); + assert!(walk + .next(&spec, &graph, &mut Default::default()) + .await + .unwrap() + .is_some()); // zero hop + let mut edges = CsrEdges::default(); + let mut next = Box::pin(walk.next(&spec, &graph, &mut edges)); assert!(futures::poll!(next.as_mut()).is_pending()); drop(next); assert!(walk.frames[0].next > 0 && walk.frames[0].next <= 1024); diff --git a/crates/lance-csr/tests/test_engine.rs b/crates/lance-csr/tests/test_engine.rs index d18949e..dd5def9 100644 --- a/crates/lance-csr/tests/test_engine.rs +++ b/crates/lance-csr/tests/test_engine.rs @@ -497,6 +497,69 @@ async fn named_path_endpoint_labels_ignore_case() { } } +#[tokio::test] +async fn named_paths_build_path_values_only_when_read() { + let cfg = GraphConfig::builder() + .node_table("Person", "id") + .rel_table("KNOWS", "Person", "Person", "src_id", "dst_id") + .build() + .unwrap(); + let edges = [(1, 2), (2, 3), (3, 1), (1, 3), (3, 4), (2, 2)]; + let path = "MATCH p = (a:Person {id: 1})-[:KNOWS*1..3]->(b:Person)"; + // (return clause, whether it reads the path) + let cases = [ + ("RETURN count(*) AS n", false), + ("RETURN count(b.id) AS n", false), + ("WITH b, p RETURN count(b) AS n", false), + ("RETURN count(p) AS n", true), + ("RETURN count(length(p)) AS n", true), + ("RETURN count(nodes(p)) AS n", true), + ("RETURN count(relationships(p)) AS n", true), + ("WITH p AS q RETURN count(q) AS n", true), + ]; + for use_csr in [false, true] { + let engine = CypherEngine::new( + cfg.clone(), + HashMap::from([ + ("Person".into(), EngineSource::Arrow(people())), + ("KNOWS".into(), EngineSource::Arrow(knows(&edges))), + ]), + use_csr, + ) + .await + .unwrap(); + let count = |query: String| { + let engine = &engine; + async move { + let batch = engine.execute(&query, HashMap::new()).await.unwrap(); + let n = batch.column_by_name("n").unwrap(); + n.as_any().downcast_ref::().unwrap().value(0) + } + }; + let expected = count(format!("{path} RETURN count(p) AS n")).await; + assert!(expected > 4, "use_csr={use_csr}"); + for (ret, reads_path) in cases { + let query = format!("{path} {ret}"); + assert_eq!( + count(query.clone()).await, + expected, + "use_csr={use_csr} {query}" + ); + let plan = engine.explain(&query, HashMap::new()).await.unwrap(); + let walk = if use_csr { + "csr walk" + } else { + "edge inventory" + }; + let node = if reads_path { "p" } else { "endpoints" }; + assert!( + plan.contains(&format!("PathMatchExec: {node} {walk}")), + "use_csr={use_csr} {query}\n{plan}" + ); + } + } +} + #[tokio::test] async fn anonymous_patterns_keep_mixed_label_identity_and_query_semantics() { use arrow_array::{cast::AsArray, StructArray}; diff --git a/docs/csr.md b/docs/csr.md index b7918f9..aef4939 100644 --- a/docs/csr.md +++ b/docs/csr.md @@ -153,10 +153,24 @@ conditions above always runs on the CSR, even when a join would be about as fast [when it helps](#when-it-helps). `use_csr` is set once, for the whole engine, because it decides whether the CSR is built at all: with `use_csr=False` every hop is a join. -Named path values and `relationships(path)` use a query-local inventory of actual edge occurrences because -CSR neighbors do not carry edge identity or properties. This also preserves parallel edges when a path -passes through `collect()` and `UNWIND`. The inventory materializes the participating node and relationship -tables; bounded traversal batches do not bound that inventory. See [path values](cypher.md#path-values). +Named path values and `relationships(path)` need each relationship's identity and properties, which a CSR +neighbor list doesn't hold on its own. When every relationship type and direction a named path follows has a +CSR, the path walks it from its start node, as an explicit hop does. Each step reads the neighbors of only the +nodes the walk reaches and checks the step's relationship equalities, from an inline `{since: 2020}` or a +`WHERE all(r IN relationships(p) WHERE r.since = 2020)`, on just those edges. Properties are read only for the +relationships of the paths returned. An edge's identity is its row in the relationship table, so parallel edges +stay distinct, even when a path passes through `collect()` and `UNWIND`. The cost therefore follows the part of +the graph the walk reaches rather than the size of the relationship table. + +This design follows [Kùzu](https://github.com/kuzudb/kuzu), which evaluates relationship predicates inside its +recursive joins over CSR adjacency lists, so a filtered variable-length pattern only extends paths along edges +that pass. + +Shortest paths, and named paths over a relationship type without a CSR, use a query-local inventory of edge +occurrences instead. The inventory reads the participating relationship tables in full, and bounded traversal +batches do not bound it. Where a CSR exists, the inventory names each relationship by the same row the walk uses, +so a named path and a shortest path in one query agree on which relationships are equal. Both routes read the participating node tables in full. See +[path values](cypher.md#path-values). Shortest-path queries within one node label that only read length or node keys keep the CSR route below. Relationships crossing labels use typed identities, even for these queries, to distinguish equal keys from different labels. diff --git a/docs/cypher.md b/docs/cypher.md index f5039a7..d00186f 100644 --- a/docs/cypher.md +++ b/docs/cypher.md @@ -376,7 +376,7 @@ RETURN length(p), nodes(p) once each path is complete. - **Variable-length alternation** follows each relationship type's configured endpoint labels. With suitable CSR and node indexes, a mixed path such as `[:hasType|isSubclassOf*1..3]` stays in one operator. - Named paths also support typed variable-length alternation through their edge inventory. + Named paths also support typed variable-length alternation. A standalone undirected segment with an explicit upper bound and multiple types, such as `MATCH (a:Person)-[:KNOWS|WORKS_WITH*1..3]-(b:Person) RETURN b.id`, can change direction at each hop. Its endpoints need known labels and integer keys. Each stored @@ -440,18 +440,22 @@ Entity records store user properties in `__lance_csr_properties` and `{label, id in `__lance_csr_identity`. Relationship records also carry the node records `__lance_csr_start` and `__lance_csr_end`. These metadata fields are distinct from user properties, even if a property has the same name. `keys(entity)` lists only non-null user properties; `keys(map)` includes null-valued keys. -Prefer the Cypher property and endpoint functions when writing queries. Relationship identities identify actual occurrences within this query's inventory, not persistent +Prefer the Cypher property and endpoint functions when writing queries. Relationship identities identify actual occurrences within this query, not persistent IDs that can be compared across queries or snapshots. Rich paths support the same signed integer and `uint8`/`uint16`/`uint32` keys as the CSR. Mixed labels may share compatible properties; conflicting Arrow property types fail explicitly. Non-null node IDs must be unique within each participating label so relationship endpoints identify one node; duplicate IDs raise an error. Expanding a graph pattern from a mixed-label value remains unsupported. -A path value needs a query-local inventory of the participating node and relationship tables, including -properties. It therefore materializes those tables, even with `use_csr=True`. Traversal output is emitted -in batches and named ordinary paths keep a cursor per hop, but inventory memory grows with the graph. -Rich path queries can reuse a query template. Each execution binds its current parameters and creates -an inventory from its own snapshot. A reader opened before `checkout_latest()` retains the old snapshot. +A path value needs the properties of its nodes, so each execution reads the participating node tables in full. +A query that names a path but never reads it, such as `MATCH p = ... RETURN count(*)`, builds no path +values and, on the CSR walk, reads no relationship properties. +With `use_csr=True`, a named path reads relationships only where its walk goes (see +[the CSR index](csr.md#which-hops-use-it)). Shortest paths, and paths over a relationship type without a CSR, +also read the relationship tables into a query-local inventory, whose memory grows with the graph. +Traversal output is emitted in batches and named ordinary paths keep a cursor per hop. +Rich path queries can reuse a query template. Each execution binds its current parameters and reads +from its own snapshot. A reader opened before `checkout_latest()` retains the old snapshot. Queries asking only for shortest-path length, node keys or path null checks, including homogeneous node-property comprehensions and paths carried through `WITH` aliases, retain the usual CSR execution route when the relationship joins the same node label. Cross-label shortest paths use typed identities even for diff --git a/docs/internals/index.md b/docs/internals/index.md index 198452f..7ab8c23 100644 --- a/docs/internals/index.md +++ b/docs/internals/index.md @@ -118,7 +118,7 @@ All paths are under | `csr_index.rs` | The compact CSR neighbour store | [lance-graph](https://github.com/lance-format/lance-graph); edge rows and their block packing (`PackedU64`) added in lance-csr, unused traversal helpers removed | | `csr_traversal.rs` | Resumable, typed variable-length walks | lance-csr | | `shortest_path.rs` | `ShortestPathNode` and `ShortestPathExec`, bidirectional and batched forward breadth-first search | lance-csr | -| `path_match.rs`, `path_inventory.rs`, `path_value.rs` | Named paths, the edge inventory, Arrow path values | lance-csr | +| `path_match.rs`, `path_inventory.rs`, `path_value.rs` | Named paths (the CSR walk and the edge inventory), Arrow path values | lance-csr | | `apply.rs` | `ApplyNode` and `ApplyExec` for CALL subqueries | lance-csr | | `cross_join_order.rs` | `CrossJoinBuildRows` | lance-csr | | `key_statistics.rs` | `KeyStatisticsProvider` and `KeyStatisticsExec` | lance-csr | diff --git a/docs/internals/operators.md b/docs/internals/operators.md index d679d87..4da6fa5 100644 --- a/docs/internals/operators.md +++ b/docs/internals/operators.md @@ -278,23 +278,52 @@ ProjectionExec: expr=[p__length@6 as length(p)] ## `PathMatch`: named paths with real edge identity CSR neighbours don't carry edge identity or properties, but `MATCH p = ...` with `relationships(p)` needs both, and -parallel edges must stay distinct even through `collect()` and `UNWIND`. `PathMatchExec` builds one immutable, -query-local edge inventory in which an edge's identity is its actual scanned occurrence. It enumerates trails over the -inventory, resuming between output batches, and reuses the bidirectional breadth-first search on a bipartite -node/edge graph for shortest paths. Path values keep properties in a marked child, so user property names can't +parallel edges must stay distinct even through `collect()` and `UNWIND`. `PathMatchExec` has two routes, chosen at +planning time. + +The CSR walk (`PathMatchExec: p csr walk`) is used for trails when the engine has a CSR for every relationship type +and direction the steps follow. The plan scans only the participating node tables, into a node inventory of keys, +labels and properties. The walk enumerates trails depth first from each start node, resuming between output batches. +A frame reads its node's neighbors and their edge rows from the CSR the first time the walk needs them. An undirected +step reads the outgoing and incoming CSR separately, so each edge keeps its stored direction. The step's relationship +equalities are compiled against each relationship table and checked by `EdgeFilterState`, the same rule +`CsrExpandExec` uses: fetch the filter columns of just the edges reached and, on a Lance table, switch to one read of +the whole column once the edges checked pass 1/256 of the relationship's edges. Both halves of an undirected step +share one state, so they count their checks together and read the column once. An edge's identity is its CSR row, +numbered per input batch so a trail can refuse to reuse one. Relationship records (properties, identity, start and +end nodes) are built only for the edges of the paths in an output batch. This follows Kùzu's design, which evaluates +relationship predicates inside recursive joins over CSR adjacency lists, so the work follows the frontier instead of +the relationship table's size. + +Otherwise, for shortest paths or a relationship type without a CSR, `PathMatchExec: p edge inventory` builds one +immutable, query-local edge inventory in which an edge's identity is its actual occurrence. For a relationship type +the engine has a CSR for, the inventory reads the rows the CSR stores, with their CSR rows, so a trail and a shortest +path in the same query name each edge the same way; otherwise the identity is the row's position in the scan. It enumerates +trails over the inventory the same way and reuses the bidirectional breadth-first search on a bipartite node/edge +graph for shortest paths. Path values keep properties in a marked child, so user property names can't collide with identity metadata. When an untyped match combines branches, the planner merges those marked property fields by name before casting each branch to the common schema. This also preserves the node records nested inside a path or a relationship endpoint. See [path values](../cypher.md#path-values). For an unnamed, bounded undirected segment with several types, the same operator emits -boundary columns and skips building the Arrow path value for each trail. It still builds the -inventory of participating tables and tracks edge occurrences during traversal. +boundary columns and skips building the Arrow path value for each trail. It still tracks edge +occurrences during traversal, on whichever route the segment takes. + +A named path whose variable the query never reads runs the same way. Building a path value costs +far more than the walk when a query only counts paths or returns their end nodes: on the LDBC SF1 +graph, the 86K paths of `MATCH p = (a:Person {ID: 1131})-[:knows*1..3]->(b:Person) RETURN count(*)` +made about 100 MB of path values that nothing read. So the `prune_csr_target_columns` optimizer rule, +which already drops unused `CsrExpand` columns, also drops the path column from a `PathMatch` when no +expression in the plan references it. The node then shows as `PathMatchExec: endpoints` and, on the +CSR walk, reads no relationship records unless a relationship variable needs them. Any reference to +the path, such as `length(p)`, `nodes(p)` or `WITH p AS q`, keeps the value. Path property values are logical expressions, so cached plans bind them before physical planning. -The physical operator then builds predicates against the inventory's node and relationship schemas. +The physical operator then builds node predicates against the inventory's node schema, and relationship +predicates against the inventory's relationship schema or, on the CSR walk, each relationship table. The planner adds the equalities of a `WHERE all(r IN relationships(p) WHERE ...)` term to every relationship's property map, so the walk skips failing edges; the `WHERE` itself still runs. -Each execution starts with fresh inventory scans that can share source batches within that execution. +Each execution starts with fresh table scans that can share source batches within that execution. ## `Apply`: correlated CALL subqueries diff --git a/python/python/tests/test_path_csr_walk.py b/python/python/tests/test_path_csr_walk.py new file mode 100644 index 0000000..3754410 --- /dev/null +++ b/python/python/tests/test_path_csr_walk.py @@ -0,0 +1,182 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The lance-csr Authors + +"""Named paths walking the CSR return what the edge inventory returns.""" + +import lance +import numpy as np +import pyarrow as pa +import pytest +from lance_csr import CypherEngine, GraphConfig + +CONFIG = ( + GraphConfig.builder() + .node_table("P", "id") + .node_table("C", "id") + .rel_table("R", "P", "P", "src", "dst") + .rel_table("S", "P", "P", "src", "dst") + .rel_table("L", "P", "C", "src", "dst") + .build() +) + +# Parallel edges (0->1), self-loops (2, 5), a dangling endpoint (42) and C keys that +# collide with P keys. S has `day` but no `w`; L has neither. +PAIRS = [(a, (a * 3 + k) % 8) for a in range(8) for k in range(3)] +PAIRS += [(0, 1), (0, 1), (2, 2), (5, 5), (7, 42)] +DATA = { + "P": pa.table({"id": list(range(8)), "name": [f"p{i}" for i in range(8)]}), + "C": pa.table({"id": [0, 1, 2], "name": ["c0", "c1", "c2"]}), + "R": pa.table( + { + "src": [a for a, _ in PAIRS], + "dst": [b for _, b in PAIRS], + "day": [(a + b) % 3 for a, b in PAIRS], + "w": [float(i) for i in range(len(PAIRS))], + } + ), + "S": pa.table( + {"src": [1, 2, 3, 3, 6], "dst": [2, 3, 1, 3, 0], "day": [0, 1, 0, 2, 0]} + ), + "L": pa.table({"src": [0, 1, 2, 3, 0], "dst": [0, 1, 2, 0, 2]}), +} + +PATH = ( + "RETURN a.id AS a, length(p) AS n, [x IN nodes(p) | x.id] AS ids, " + "[x IN nodes(p) | labels(x)[0]] AS labels, " + "[e IN relationships(p) | e.day] AS days, " + "[e IN relationships(p) | e.w] AS ws, [e IN relationships(p) | keys(e)] AS keys, " + "[e IN relationships(p) | e.src] AS srcs, [e IN relationships(p) | e.dst] AS dsts" +) +QUERIES = [ + f"MATCH p = (a:P)-[:R*1..3]->(b:P) {PATH}", + f"MATCH p = (a:P)<-[:R*1..3]-(b:P) {PATH}", + f"MATCH p = (a:P)-[:R*1..3]-(b:P) {PATH}", + f"MATCH p = (a:P)-[:R|S*0..2]-(b:P) {PATH}", + f"MATCH p = (a:P)-[:R|S*1..3]->(b:P) " + f"WHERE all(e IN relationships(p) WHERE e.day = 0) {PATH}", + f"MATCH p = (a:P)-[:R|S*1..2 {{w: 3.0}}]-(b:P) {PATH}", + f"MATCH p = (a:P)-[:R {{day: 2}}]->(b:P)-[:R {{day: 2}}]->(c:P) {PATH}", + f"MATCH p = (c:C)<-[:L]-(a:P)-[:R*1..2]-(b:P) {PATH}", + f"MATCH p = (a:P)-[:R*2..2]->(a) {PATH}", + "MATCH p = (a:P)-[e:R]->(b:P) RETURN a.id AS a, e.day AS d, e.w AS w, b.id AS b", + "MATCH (a:P)-[:R|S*1..2]-(b:P) RETURN a.id AS a, b.id AS b", +] + + +def rows(engine, query): + return sorted( + repr(sorted(row.items())) for row in engine.execute(query).to_pylist() + ) + + +def lance_tables(tmp_path, tables, deleted): + datasets = { + name: lance.write_dataset(table, tmp_path / name, max_rows_per_file=5) + for name, table in tables.items() + } + for name, predicate in deleted.items(): + datasets[name].delete(predicate) + datasets[name] = lance.dataset(tmp_path / name) + return datasets + + +@pytest.mark.parametrize("lazy", [False, True], ids=["memory", "lance"]) +def test_csr_walk_matches_edge_inventory(tmp_path, lazy): + data = DATA + if lazy: + data = lance_tables( + tmp_path, DATA, {"R": "day = 2 AND src = 3", "S": "src = 6"} + ) + csr = CypherEngine(CONFIG, data, use_csr=True) + inventory = CypherEngine(CONFIG, data) + for query in QUERIES: + assert "csr walk" in csr.explain(query), query + assert rows(csr, query) == rows(inventory, query), query + + +def test_filtered_walk_checks_reached_edges_before_switching_to_a_mask(tmp_path): + # 30,000 edges switch to a whole-column mask after 117 checked: the start node's + # 30 edges are fetched one by one, later frames use the mask. + rng = np.random.default_rng(0) + n, m = 1_000, 30_000 + data = lance_tables( + tmp_path, + { + "P": pa.table({"id": np.arange(n)}), + "R": pa.table( + { + "src": np.repeat(np.arange(n), m // n), + "dst": rng.integers(0, n, m), + "day": rng.integers(0, 10, m), + } + ), + }, + {"R": "dst = 7"}, + ) + config = ( + GraphConfig.builder() + .node_table("P", "id") + .rel_table("R", "P", "P", "src", "dst") + .build() + ) + query = ( + "MATCH p = (a:P {id: 0})-[:R*1..3]->(b:P) " + "WHERE all(e IN relationships(p) WHERE e.day = 3) " + "RETURN [x IN nodes(p) | x.id] AS ids, [e IN relationships(p) | e.day] AS days" + ) + expected = rows(CypherEngine(config, data), query) + assert len(expected) > 3 + assert rows(CypherEngine(config, data, use_csr=True), query) == expected + + +def test_shortest_paths_keep_the_edge_inventory(): + engine = CypherEngine(CONFIG, DATA, use_csr=True) + query = "MATCH p = shortestPath((a:P {id: 0})-[:R*1..3]->(b:P {id: 4})) RETURN p" + assert "csr walk" not in engine.explain(query) + assert "edge inventory" in engine.explain(query) + + +@pytest.mark.parametrize("lazy", [False, True], ids=["memory", "lance"]) +@pytest.mark.parametrize("use_csr", [False, True], ids=["inventory", "csr"]) +def test_trail_and_shortest_path_agree_on_relationship_identity( + tmp_path, lazy, use_csr +): + # A trail walks the CSR and a shortest path uses the inventory: both must name the + # same edge the same way, even when Lance row addresses skip deleted rows. + config = ( + GraphConfig.builder() + .node_table("P", "id") + .rel_table("R", "P", "P", "src", "dst") + .build() + ) + data = { + "P": pa.table({"id": list(range(8))}), + "R": pa.table({"src": list(range(7)), "dst": list(range(1, 8))}), + } + if lazy: + data = lance_tables(tmp_path, data, {"R": "src = 0"}) + engine = CypherEngine(config, data, use_csr=use_csr) + query = ( + "MATCH p = (a:P {id: 4})-[:R]->(b:P {id: 5}) " + "MATCH q = shortestPath((a)-[:R*1..3]->(b)) " + "RETURN relationships(p)[0] = relationships(q)[0] AS same, p = q AS same_path" + ) + assert engine.execute(query).to_pylist() == [{"same": True, "same_path": True}] + + +@pytest.mark.parametrize("use_csr", [False, True], ids=["inventory", "csr"]) +def test_path_values_are_built_only_when_read(use_csr): + engine = CypherEngine(CONFIG, DATA, use_csr=use_csr) + path = "MATCH p = (a:P {id: 0})-[:R*1..3]->(b:P)" + expected = engine.execute(f"{path} RETURN count(p) AS n").to_pylist() + unread = ["count(*)", "count(b.id)", "count(DISTINCT b.id)"] + read = ["count(p)", "sum(length(p))", "count(nodes(p))", "count(relationships(p))"] + for ret, node in [(r, "endpoints") for r in unread] + [(r, "p") for r in read]: + query = f"{path} RETURN {ret} AS n" + assert f"PathMatchExec: {node}" in engine.explain(query), query + for ret in ["count(*)", "count(b.id)"]: + assert engine.execute(f"{path} RETURN {ret} AS n").to_pylist() == expected + ids = f"{path} RETURN b.id AS b, length(p) AS n" + assert rows(engine, f"{path} RETURN b.id AS b") == sorted( + repr([("b", row["b"])]) for row in engine.execute(ids).to_pylist() + )