diff --git a/Cargo.lock b/Cargo.lock index ef08d63a..25ab3a67 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -99,6 +99,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "arc-swap" version = "1.9.3" @@ -1697,6 +1706,7 @@ dependencies = [ "log", "object_store 0.13.2", "parquet", + "recursive", "sqlparser", "tokio", "uuid", @@ -1891,6 +1901,7 @@ dependencies = [ "datafusion-physical-expr-common", "indexmap 2.14.2", "itertools 0.14.0", + "recursive", "serde_json", "sqlparser", ] @@ -2066,6 +2077,7 @@ dependencies = [ "indexmap 2.14.2", "itertools 0.14.0", "log", + "recursive", "regex", "regex-syntax", ] @@ -2088,6 +2100,7 @@ dependencies = [ "itertools 0.14.0", "parking_lot", "petgraph", + "recursive", "tokio", ] @@ -2139,6 +2152,7 @@ dependencies = [ "datafusion-physical-plan", "datafusion-pruning", "itertools 0.14.0", + "recursive", ] [[package]] @@ -2218,6 +2232,7 @@ dependencies = [ "datafusion-functions-nested", "indexmap 2.14.2", "log", + "recursive", "regex", "sqlparser", ] @@ -3952,6 +3967,7 @@ dependencies = [ "nom 7.1.3", "object_store 0.14.2", "rayon", + "recursive", "serde", "serde_json", "snafu 0.8.9", @@ -4967,6 +4983,15 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "object_store" version = "0.13.2" @@ -5782,6 +5807,16 @@ dependencies = [ "prost", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quick-xml" version = "0.41.0" @@ -6024,6 +6059,26 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "recursive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0786a43debb760f491b1bc0269fe5e84155353c67482b9e60d0cfb596054b43e" +dependencies = [ + "recursive-proc-macro-impl", + "stacker", +] + +[[package]] +name = "recursive-proc-macro-impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "redb" version = "3.1.3" @@ -7017,6 +7072,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c6d1b651dc4edf07eead2a0c6c78016ce971bc2c10da5266861b13f25e7cec" dependencies = [ "log", + "recursive", "sqlparser_derive", ] @@ -7037,6 +7093,19 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "static_assertions" version = "1.1.0" diff --git a/crates/lance-csr-benches/benches/graph_execution.rs b/crates/lance-csr-benches/benches/graph_execution.rs index d9807f82..3268629a 100644 --- a/crates/lance-csr-benches/benches/graph_execution.rs +++ b/crates/lance-csr-benches/benches/graph_execution.rs @@ -452,6 +452,7 @@ criterion_group!( bench_cypher_execution, bench_query_templates, bench_comprehension_counts, - grouped_two_hop::bench_grouped_two_hop + grouped_two_hop::bench_grouped_two_hop, + grouped_two_hop::bench_seeded_trail ); criterion_main!(benches); diff --git a/crates/lance-csr-benches/benches/grouped_two_hop/mod.rs b/crates/lance-csr-benches/benches/grouped_two_hop/mod.rs index 7617d4b2..842087a1 100644 --- a/crates/lance-csr-benches/benches/grouped_two_hop/mod.rs +++ b/crates/lance-csr-benches/benches/grouped_two_hop/mod.rs @@ -118,3 +118,49 @@ pub fn bench_grouped_two_hop(c: &mut Criterion) { } group.finish(); } + +/// Keep the per-seed workload fixed while unrelated nodes and edges grow. +pub fn bench_seeded_trail(c: &mut Criterion) { + let rt = tokio::runtime::Runtime::new().unwrap(); + let config = GraphConfig::builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + .unwrap(); + let query = "MATCH (:N {id:0})-[:R*1..2]-(f:N)-[:R]-(g:N) RETURN count(*)"; + let mut group = c.benchmark_group("seeded_trail"); + for size in [10_000_i64, 100_000] { + let nodes = batch(&[("id", (0..size).collect())]); + let edges = batch(&[ + ("src", (0..size).flat_map(|i| [i, i]).collect()), + ( + "dst", + (0..size) + .flat_map(|i| [(i + 1) % size, (i + 2) % size]) + .collect(), + ), + ]); + for (mode, csr) in [("csr", true), ("joins", false)] { + let sources = HashMap::from([ + ("N".into(), EngineSource::Arrow(nodes.clone())), + ("R".into(), EngineSource::Arrow(edges.clone())), + ]); + let engine = rt + .block_on(CypherEngine::new(config.clone(), sources, csr)) + .unwrap(); + let execute = || rt.block_on(engine.execute(query, HashMap::new())).unwrap(); + let result = execute(); + // Four choices on the first hop, three on each following hop. + let count = result + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(count.value(0), 4 * 3 + 4 * 3 * 3); + group.bench_function(BenchmarkId::new(mode, size), |b| { + b.iter(|| black_box(execute())) + }); + } + } + group.finish(); +} diff --git a/crates/lance-csr-node/Cargo.lock b/crates/lance-csr-node/Cargo.lock index 1780c576..47a0f677 100644 --- a/crates/lance-csr-node/Cargo.lock +++ b/crates/lance-csr-node/Cargo.lock @@ -87,6 +87,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "arc-swap" version = "1.9.3" @@ -1598,6 +1607,7 @@ dependencies = [ "log", "object_store 0.13.2", "parquet", + "recursive", "sqlparser", "tokio", "uuid", @@ -1792,6 +1802,7 @@ dependencies = [ "datafusion-physical-expr-common", "indexmap 2.14.2", "itertools 0.14.0", + "recursive", "serde_json", "sqlparser", ] @@ -1967,6 +1978,7 @@ dependencies = [ "indexmap 2.14.2", "itertools 0.14.0", "log", + "recursive", "regex", "regex-syntax", ] @@ -1989,6 +2001,7 @@ dependencies = [ "itertools 0.14.0", "parking_lot", "petgraph", + "recursive", "tokio", ] @@ -2040,6 +2053,7 @@ dependencies = [ "datafusion-physical-plan", "datafusion-pruning", "itertools 0.14.0", + "recursive", ] [[package]] @@ -2119,6 +2133,7 @@ dependencies = [ "datafusion-functions-nested", "indexmap 2.14.2", "log", + "recursive", "regex", "sqlparser", ] @@ -3832,6 +3847,7 @@ dependencies = [ "nom 7.1.3", "object_store 0.14.2", "rayon", + "recursive", "serde", "serde_json", "snafu 0.8.9", @@ -4926,6 +4942,15 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "object_store" version = "0.13.2" @@ -5707,6 +5732,16 @@ dependencies = [ "prost", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quick-xml" version = "0.41.0" @@ -5949,6 +5984,26 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "recursive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0786a43debb760f491b1bc0269fe5e84155353c67482b9e60d0cfb596054b43e" +dependencies = [ + "recursive-proc-macro-impl", + "stacker", +] + +[[package]] +name = "recursive-proc-macro-impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "redb" version = "3.1.3" @@ -6942,6 +6997,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c6d1b651dc4edf07eead2a0c6c78016ce971bc2c10da5266861b13f25e7cec" dependencies = [ "log", + "recursive", "sqlparser_derive", ] @@ -6962,6 +7018,19 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "static_assertions" version = "1.1.0" diff --git a/crates/lance-csr-python/Cargo.lock b/crates/lance-csr-python/Cargo.lock index e5568932..074a3670 100644 --- a/crates/lance-csr-python/Cargo.lock +++ b/crates/lance-csr-python/Cargo.lock @@ -87,6 +87,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "arc-swap" version = "1.9.3" @@ -1602,6 +1611,7 @@ dependencies = [ "log", "object_store 0.13.2", "parquet", + "recursive", "sqlparser", "tokio", "uuid", @@ -1796,6 +1806,7 @@ dependencies = [ "datafusion-physical-expr-common", "indexmap 2.14.2", "itertools 0.14.0", + "recursive", "serde_json", "sqlparser", ] @@ -1971,6 +1982,7 @@ dependencies = [ "indexmap 2.14.2", "itertools 0.14.0", "log", + "recursive", "regex", "regex-syntax", ] @@ -1993,6 +2005,7 @@ dependencies = [ "itertools 0.14.0", "parking_lot", "petgraph", + "recursive", "tokio", ] @@ -2044,6 +2057,7 @@ dependencies = [ "datafusion-physical-plan", "datafusion-pruning", "itertools 0.14.0", + "recursive", ] [[package]] @@ -2123,6 +2137,7 @@ dependencies = [ "datafusion-functions-nested", "indexmap 2.14.2", "log", + "recursive", "regex", "sqlparser", ] @@ -3836,6 +3851,7 @@ dependencies = [ "nom 7.1.3", "object_store 0.14.2", "rayon", + "recursive", "serde", "serde_json", "snafu 0.8.9", @@ -4853,6 +4869,15 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "object_store" version = "0.13.2" @@ -5634,6 +5659,16 @@ dependencies = [ "prost", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "pyo3" version = "0.28.3" @@ -5934,6 +5969,26 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "recursive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0786a43debb760f491b1bc0269fe5e84155353c67482b9e60d0cfb596054b43e" +dependencies = [ + "recursive-proc-macro-impl", + "stacker", +] + +[[package]] +name = "recursive-proc-macro-impl" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "redb" version = "3.1.3" @@ -6927,6 +6982,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c6d1b651dc4edf07eead2a0c6c78016ce971bc2c10da5266861b13f25e7cec" dependencies = [ "log", + "recursive", "sqlparser_derive", ] @@ -6947,6 +7003,19 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "static_assertions" version = "1.1.0" diff --git a/crates/lance-csr/Cargo.toml b/crates/lance-csr/Cargo.toml index 43751b28..e4a3ac1a 100644 --- a/crates/lance-csr/Cargo.toml +++ b/crates/lance-csr/Cargo.toml @@ -28,8 +28,11 @@ datafusion = { version = "54.0.0", default-features = false, features = [ "datetime_expressions", "string_expressions", "parquet", + # Separate long trail segments can produce deeply nested join plans. + "recursive_protection", ] } datafusion-common = "54.0.0" +recursive = "0.1.1" datafusion-expr = "54.0.0" datafusion-sql = "54.0.0" datafusion-functions-aggregate = "54.0.0" diff --git a/crates/lance-csr/src/ast.rs b/crates/lance-csr/src/ast.rs index aa1f43e4..d0d9a1dc 100644 --- a/crates/lance-csr/src/ast.rs +++ b/crates/lance-csr/src/ast.rs @@ -318,6 +318,40 @@ pub struct PathPattern { pub shortest: Option, } +impl RelationshipPattern { + /// The hop range of one segment: a single hop without a length. + pub(crate) fn hop_range(&self) -> [u32; 2] { + match &self.length { + None => [1, 1], + Some(length) => [ + length.min.unwrap_or(1), + length.max.unwrap_or(crate::MAX_VARIABLE_LENGTH_HOPS), + ], + } + } +} + +impl PathPattern { + /// A variable-length segment can revisit an edge used by another segment of this path. + pub(crate) fn needs_trail_across_segments(&self) -> bool { + self.variable.is_none() + && self.shortest.is_none() + && self.segments.iter().enumerate().any(|(i, segment)| { + segment.relationship.length.is_some() + && self.segments.iter().enumerate().any(|(j, other)| { + i != j + && segment.relationship.types.iter().any(|kind| { + other + .relationship + .types + .iter() + .any(|t| t.eq_ignore_ascii_case(kind)) + }) + }) + }) + } +} + /// How a shortest-path pattern matches, and the path variable it binds. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ShortestPathSpec { diff --git a/crates/lance-csr/src/csr_expand.rs b/crates/lance-csr/src/csr_expand.rs index ad7f1cfb..24eca04a 100644 --- a/crates/lance-csr/src/csr_expand.rs +++ b/crates/lance-csr/src/csr_expand.rs @@ -64,9 +64,11 @@ use lance::dataset::{Dataset, ProjectionRequest}; mod node_lookup; mod path_exists; +mod trail_walk; use lance_table::format::Fragment; pub use node_lookup::NodeLookupNode; pub use path_exists::{Hop, PathExistsNode}; +pub(crate) use trail_walk::{Tie, TrailCursor, TrailWalk, TrailWalkNode, WalkSegmentSpec}; /// Yield after bounded CPU work without requiring a particular async runtime. pub(crate) async fn cooperative_yield() { @@ -303,9 +305,19 @@ impl Adjacency { /// row is read from a `_rowaddr` column when the stream has one (a Lance scan); /// otherwise rows are numbered by their position in the stream. pub async fn build( + stream: impl futures::Stream> + Unpin, + from: &str, + to: &str, + ) -> Result { + Self::build_with_address_column(stream, from, to, Some(ROW_ADDR)).await + } + + /// Use stream positions for in-memory input, even if a user column is named `_rowaddr`. + pub(crate) async fn build_with_address_column( mut stream: impl futures::Stream> + Unpin, from: &str, to: &str, + address_column: Option<&str>, ) -> Result { let mut edges: Vec<(i64, u64, u64)> = Vec::new(); let mut position = 0u64; @@ -313,8 +325,8 @@ impl Adjacency { let batch = batch.map_err(|e| exec_error(format!("Failed to read edges: {}", e)))?; let from_col = int64_column(&batch, from)?; let to_col = int64_column(&batch, to)?; - let addresses = batch - .column_by_name(ROW_ADDR) + let addresses = address_column + .and_then(|name| batch.column_by_name(name)) .map(|c| c.as_primitive::().clone()); for i in 0..batch.num_rows() { if from_col.is_null(i) || to_col.is_null(i) { @@ -2508,7 +2520,8 @@ struct BatchExpansion { bound: Option, row: usize, position: NeighborPosition, - walk: Option, + /// Current source row and its reusable trail cursor. + walk: Option<(usize, TrailCursor)>, /// Record each output row's edge row, for a relationship-column fetch. edge_rows: bool, /// Passing edge rows of the relationship filter, once built: others are skipped. @@ -2692,6 +2705,9 @@ impl BatchExpansion { batch_size: usize, ) -> ExpandedRows { let mut chunk = ExpandedRows::default(); + let walk = graph.walk(); + let limit = batch_size.max(1); + let mut ends = Vec::new(); let mut source_work = 0_usize; while self.row < self.keys.len() { source_work += 1; @@ -2701,34 +2717,42 @@ impl BatchExpansion { let i = self.row; if self.keys.is_valid(i) && self.bound.as_ref().is_none_or(|b| b.is_valid(i)) { let key = self.keys.value(i); - let walk = self + let required = self.bound.as_ref().map(|b| b.value(i)); + let (source, cursor) = self .walk - .get_or_insert_with(|| crate::csr_traversal::TraversalCursor::new(graph, key)); - let mut candidates = 0usize; - while let Some(neighbor) = walk.next(graph).await { - candidates += 1; - if candidates.is_multiple_of(1024) { - cooperative_yield().await; - } - if self.bound.as_ref().is_some_and(|b| b.value(i) != neighbor) { - continue; + .get_or_insert_with(|| (i, TrailCursor::new(walk, key))); + if *source != i { + cursor.restart(walk, key); + *source = i; + } + loop { + // A group never exceeds the room left, so no end has to be carried over. + if !cursor + .next_group(walk, &[], limit - chunk.rows.len(), &mut ends) + .await + { + break; } - if let Some(target) = target { - let Some(position) = target.rows.position(neighbor) else { + for &neighbor in &ends { + if required.is_some_and(|r| r != neighbor) { continue; - }; - chunk.target_positions.push(position); + } + if let Some(target) = target { + let Some(position) = target.rows.position(neighbor) else { + continue; + }; + chunk.target_positions.push(position); + } + chunk.rows.push(i as u32); + chunk.key_values.push(key); + chunk.neighbor_values.push(neighbor); } - chunk.rows.push(i as u32); - chunk.key_values.push(key); - chunk.neighbor_values.push(neighbor); - if chunk.rows.len() == batch_size.max(1) { + if chunk.rows.len() == limit { return chunk; } } } self.row += 1; - self.walk = None; } chunk } @@ -3288,6 +3312,9 @@ impl ExtensionPlanner for CsrExtensionPlanner { if let Some(node) = node.as_any().downcast_ref::() { return Ok(Some(path_exists::plan_path_exists(node, physical_inputs))); } + if let Some(node) = node.as_any().downcast_ref::() { + return Ok(Some(trail_walk::plan_trail_walk(node, physical_inputs))); + } if node.as_any().is::() { // Not lowered by `CountCsrDegrees`: run the aggregate it wraps. return Ok(Some(physical_inputs[0].clone())); @@ -3587,6 +3614,7 @@ fn prune_unused_columns(plan: LogicalPlan) -> datafusion::common::Result, diff --git a/crates/lance-csr/src/csr_expand/trail_walk.rs b/crates/lance-csr/src/csr_expand/trail_walk.rs new file mode 100644 index 00000000..2f89706b --- /dev/null +++ b/crates/lance-csr/src/csr_expand/trail_walk.rs @@ -0,0 +1,1007 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The lance-csr Authors + +//! A pattern of several relationship segments, walked on the CSR from each input row. +//! +//! Cypher never walks a relationship twice in one match. Separate expand operators share +//! only node ids, so in `(a)-[:R*1..2]-(f)-[:R]-(g)` the hop after `f` cannot tell which +//! edges the variable-length segment walked. This node walks every segment of the pattern +//! in one depth-first search seeded at the row's start node. The stack holds the edges +//! walked so far, each identified by its relationship type and stored edge row, so an +//! edge is used once across all segments, parallel edges stay distinct, and the work +//! follows the paths from that start node: no edge inventory is built. It appends the id +//! of each segment's end node that is not already known. + +use super::*; +use crate::ast::RelationshipDirection; + +/// A segment end that must equal a value known before the walk reaches it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) enum Tie { + /// The bound input column with this index in [`TrailWalkNode`]'s `bound` list. + Input(usize), + /// An earlier boundary of the pattern: 0 is the start node, `k` the end of segment + /// `k - 1`. + Boundary(usize), +} + +/// One segment of the pattern, as the planner describes it. +pub(crate) struct WalkSegmentSpec<'a> { + pub types: &'a [String], + pub direction: &'a RelationshipDirection, + pub end_label: &'a str, + pub min: u32, + pub max: u32, + pub tie: Option, +} + +impl WalkSegmentSpec<'_> { + /// Which alternatives occur on a schema path from start to end within this range. + /// Track the set of types reaching each label at each depth, without enumerating paths. + fn participating_types( + &self, + config: &crate::config::GraphConfig, + start: &str, + ) -> Option> { + let mut steps = Vec::new(); + for (i, name) in self.types.iter().enumerate() { + let mapping = config.get_relationship_mapping(name)?; + let src = mapping.source_label.as_deref()?.to_ascii_lowercase(); + let dst = mapping.target_label.as_deref()?.to_ascii_lowercase(); + if *self.direction != RelationshipDirection::Incoming { + steps.push((src.clone(), dst.clone(), i)); + } + if *self.direction == RelationshipDirection::Incoming + || (*self.direction == RelationshipDirection::Undirected && src != dst) + { + steps.push((dst, src, i)); + } + } + let start = start.to_ascii_lowercase(); + let end = self.end_label.to_ascii_lowercase(); + let mut frontier = HashMap::from([(start.as_str(), HashSet::new())]); + let mut used = HashSet::new(); + for depth in 1..=self.max { + let mut next = HashMap::<&str, HashSet>::new(); + for (from, to, i) in &steps { + if let Some(history) = frontier.get(from.as_str()) { + let reached = next.entry(to).or_default(); + reached.extend(history.iter().copied()); + reached.insert(*i); + } + } + if depth >= self.min { + if let Some(types) = next.get(end.as_str()) { + used.extend(types); + } + } + if next.is_empty() { + break; + } + frontier = next; + } + Some(used) + } +} + +#[derive(Debug)] +struct WalkStep { + from: usize, + to: usize, + /// Index of the relationship type across the whole pattern: with the edge row, it + /// identifies the edge, whichever segment walks it. + rel: usize, + neighbors: Neighbors, +} + +#[derive(Debug)] +struct WalkSegment { + steps: Vec, + end: usize, + min: u32, + max: u32, + tie: Option, +} + +#[derive(Debug)] +pub(crate) struct TrailWalk { + segments: Vec, + /// Node index per label: every node a hop reaches must have a row, as the joins + /// drop dangling edges at every hop. + nodes: Vec>, + labels: Vec, + start: usize, +} + +impl TrailWalk { + /// `None` when a type has no CSR for its direction or a label has no node index. + pub(crate) fn new( + config: &crate::config::GraphConfig, + catalog: &AdjacencyCatalog, + start_label: &str, + specs: &[WalkSegmentSpec], + ) -> Option { + let mut labels: Vec = Vec::new(); + let mut nodes = Vec::new(); + let mut label = |name: &str| -> Option { + if let Some(index) = labels.iter().position(|l| l.eq_ignore_ascii_case(name)) { + return Some(index); + } + nodes.push(catalog.nodes(name)?.clone()); + labels.push(name.to_owned()); + Some(labels.len() - 1) + }; + let mut types: Vec = Vec::new(); + let start = label(start_label)?; + let mut segments = Vec::with_capacity(specs.len()); + let mut segment_start = start_label; + for spec in specs { + let end = label(spec.end_label)?; + let participating = if spec.types.len() > 1 { + Some(spec.participating_types(config, segment_start)?) + } else { + None + }; + segment_start = spec.end_label; + let mut steps = Vec::new(); + for (i, name) in spec.types.iter().enumerate() { + if participating + .as_ref() + .is_some_and(|types| !types.contains(&i)) + { + continue; + } + let mapping = config.get_relationship_mapping(name)?; + let kind = &mapping.relationship_type; + let rel = match types.iter().position(|t| t.eq_ignore_ascii_case(kind)) { + Some(rel) => rel, + None => { + types.push(kind.clone()); + types.len() - 1 + } + }; + let (from, to) = ( + label(mapping.source_label.as_deref()?)?, + label(mapping.target_label.as_deref()?)?, + ); + let get = |outgoing| catalog.get(name, outgoing).cloned(); + let step = |from, to, neighbors| WalkStep { + from, + to, + rel, + neighbors, + }; + match spec.direction { + RelationshipDirection::Outgoing => { + steps.push(step(from, to, Neighbors::directed(get(true)?))) + } + RelationshipDirection::Incoming => { + steps.push(step(to, from, Neighbors::directed(get(false)?))) + } + RelationshipDirection::Undirected if from == to => steps.push(step( + from, + to, + Neighbors::undirected(get(true)?, get(false)?), + )), + RelationshipDirection::Undirected => { + steps.push(step(from, to, Neighbors::directed(get(true)?))); + steps.push(step(to, from, Neighbors::directed(get(false)?))); + } + } + } + segments.push(WalkSegment { + steps, + end, + min: spec.min, + max: spec.max, + tie: spec.tie, + }); + } + Some(Self { + segments, + nodes, + labels, + start, + }) + } + + /// One participating adjacency for the single-segment expansion operator. + pub(crate) fn first_neighbors(&self) -> Option<&Neighbors> { + Some(&self.segments.first()?.steps.first()?.neighbors) + } + + /// Node index of the label at the end of `segment`. + pub(crate) fn end_rows(&self, segment: usize) -> &Arc { + &self.nodes[self.segments[segment].end] + } + + /// The segments whose end id the node outputs: those not tied to a known value. + fn outputs(&self) -> impl Iterator + '_ { + (0..self.segments.len()).filter(|&s| self.segments[s].tie.is_none()) + } + + fn describe(&self) -> String { + let segments: Vec = self + .segments + .iter() + .map(|s| format!("{}..{}->{}", s.min, s.max, self.labels[s.end])) + .collect(); + format!( + "from {}, segments=[{}]", + self.labels[self.start], + segments.join(", ") + ) + } +} + +struct Frame { + segment: usize, + /// Hops walked in `segment` so far. + depth: u32, + label: usize, + key: i64, + step: usize, + position: NeighborPosition, + emit: bool, + /// The edge this frame was reached by, as (type index, edge row). + edge: Option<(usize, u64)>, +} + +impl Frame { + fn new(segment: usize, depth: u32, label: usize, key: i64, edge: Option<(usize, u64)>) -> Self { + Self { + segment, + depth, + label, + key, + step: 0, + position: NeighborPosition::default(), + emit: true, + edge, + } + } +} + +/// A resumable walk from one start node. One frame per hop: a segment's end starts the +/// next segment with a frame of depth 0 at the same node, so the stack also holds every +/// boundary reached so far. A one-segment walk is the variable-length expand's walker. +pub(crate) struct TrailCursor { + stack: Vec, + /// Start id and completed segment ends on the current branch. + boundaries: Vec, + work_since_yield: usize, +} + +impl TrailCursor { + pub(crate) fn new(walk: &TrailWalk, key: i64) -> Self { + Self { + stack: vec![Frame::new(0, 0, walk.start, key, None)], + boundaries: vec![key], + work_since_yield: 0, + } + } + + /// A new source row can reuse the previous row's frame and boundary buffers. + pub(crate) fn restart(&mut self, walk: &TrailWalk, key: i64) { + self.stack.clear(); + self.stack.push(Frame::new(0, 0, walk.start, key, None)); + self.boundaries.clear(); + self.boundaries.push(key); + } + + /// Frames on the stack: one per hop of the current branch, plus one per boundary. + #[cfg(test)] + pub(crate) fn depth(&self) -> usize { + self.stack.len() + } + + fn bound_end(&self, tie: Option, bound: &[i64]) -> Option { + match tie? { + Tie::Input(i) => Some(bound[i]), + Tie::Boundary(k) => Some(self.boundaries[k]), + } + } + + /// Emit final endpoints with the same preceding boundaries as a group. Read a + /// contiguous run of final-hop candidates without rebuilding its CSR iterator or + /// pushing a stack frame for every row. At most `limit` ends per group. + pub(crate) async fn next_group( + &mut self, + walk: &TrailWalk, + bound: &[i64], + limit: usize, + ends: &mut Vec, + ) -> bool { + ends.clear(); + // A single segment has no intermediate boundaries. Its ends at different + // depths can share a batch, including on a shallow graph with a large bound. + let single = walk.segments.len() == 1; + loop { + if self.work_since_yield >= 1024 { + if !ends.is_empty() { + return true; + } + cooperative_yield().await; + self.work_since_yield = 0; + } + self.work_since_yield += 1; + let Some(top) = self.stack.len().checked_sub(1) else { + return !ends.is_empty(); + }; + let (s, depth, label, key, emit) = { + let frame = &mut self.stack[top]; + let emit = std::mem::replace(&mut frame.emit, false); + (frame.segment, frame.depth, frame.label, frame.key, emit) + }; + let segment = &walk.segments[s]; + if emit + && depth >= segment.min + && label == segment.end + && self.bound_end(segment.tie, bound).is_none_or(|v| v == key) + { + if s + 1 == walk.segments.len() { + ends.push(key); + if !single || ends.len() == limit { + return true; + } + } else { + self.boundaries.push(key); + self.stack.push(Frame::new(s + 1, 0, label, key, None)); + continue; + } + } + if depth == segment.max || self.stack[top].step == segment.steps.len() { + if depth == 0 { + self.boundaries.pop(); + } + self.stack.pop(); + continue; + } + let final_hop = s + 1 == walk.segments.len() && depth + 1 == segment.max; + let tied = self.bound_end(segment.tie, bound); + let (frame, ancestors) = self.stack.split_last_mut().expect("nonempty stack"); + let step = &segment.steps[frame.step]; + if final_hop { + let chunk = (limit - ends.len()).min(256); + let mut visited = 0; + if step.from == label && step.to == segment.end { + for candidate in step + .neighbors + .candidates_from::(key, &mut frame.position) + .take(chunk) + { + visited += 1; + let Some((next, row)) = candidate else { + continue; + }; + let next = next as i64; + let edge = Some((step.rel, row)); + if frame.edge != edge + && !ancestors.iter().any(|f| f.edge == edge) + && tied.is_none_or(|v| v == next) + && walk.nodes[step.to].position(next).is_some() + { + ends.push(next); + } + } + } + if visited < chunk { + frame.step += 1; + frame.position = NeighborPosition::default(); + } + self.work_since_yield += visited; + if ends.len() == limit || (!single && !ends.is_empty()) { + return true; + } + continue; + } + let next = if step.from == label { + step.neighbors + .candidates_from::(key, &mut frame.position) + .next() + } else { + None + }; + let (neighbor, edge) = match next { + Some(Some((neighbor, row))) => (neighbor as i64, (step.rel, row)), + // A tombstone or a suppressed self-loop: counted as work, nothing to visit. + Some(None) => continue, + None => { + frame.step += 1; + frame.position = NeighborPosition::default(); + continue; + } + }; + if walk.nodes[step.to].position(neighbor).is_none() + || self.stack.iter().any(|f| f.edge == Some(edge)) + { + continue; + } + self.stack + .push(Frame::new(s, depth + 1, step.to, neighbor, Some(edge))); + } + } +} + +/// `input` plus the end node id of each segment of a pattern whose end is not tied to a +/// known value, one row per match. +#[derive(Clone)] +pub(crate) struct TrailWalkNode { + input: LogicalPlan, + /// Input column holding the start node id. + start: String, + /// Input columns that segment ends tied by [`Tie::Input`] must equal. + bound: Vec, + walk: Arc, + schema: DFSchemaRef, +} + +impl TrailWalkNode { + /// `outputs` names one column per untied segment end, in segment order. + pub(crate) fn try_new( + input: LogicalPlan, + start: String, + bound: Vec, + walk: Arc, + outputs: Vec, + ) -> Result { + if outputs.len() != walk.outputs().count() { + return Err(plan_error( + "TrailWalk needs one output column per untied segment end".to_string(), + )); + } + let added = DFSchema::try_from(Schema::new(outputs)) + .map_err(|e| plan_error(format!("TrailWalk schema: {}", e)))?; + let schema = input + .schema() + .join(&added) + .map_err(|e| plan_error(format!("TrailWalk schema: {}", e)))?; + Ok(Self { + input, + start, + bound, + walk, + schema: Arc::new(schema), + }) + } + + fn added_columns(&self) -> impl Iterator { + let width = self.input.schema().fields().len(); + self.schema.fields()[width..].iter().map(|f| f.name()) + } + + fn describe(&self) -> String { + let ends: Vec<&String> = self.added_columns().collect(); + let mut text = format!("start={}, {}", self.start, self.walk.describe()); + if !ends.is_empty() { + text.push_str(&format!( + ", ends=[{}]", + ends.iter() + .map(|s| s.as_str()) + .collect::>() + .join(", ") + )); + } + if !self.bound.is_empty() { + text.push_str(&format!(", match=[{}]", self.bound.join(", "))); + } + text + } +} + +// Logical nodes must be comparable; the walk compares by identity. +impl PartialEq for TrailWalkNode { + fn eq(&self, other: &Self) -> bool { + self.input == other.input + && self.start == other.start + && self.bound == other.bound + && Arc::ptr_eq(&self.walk, &other.walk) + && self.schema == other.schema + } +} +impl Eq for TrailWalkNode {} +impl Hash for TrailWalkNode { + fn hash(&self, state: &mut H) { + self.input.hash(state); + self.start.hash(state); + self.bound.hash(state); + Arc::as_ptr(&self.walk).hash(state); + } +} +impl PartialOrd for TrailWalkNode { + fn partial_cmp(&self, other: &Self) -> Option { + (&self.start, &self.bound) + .partial_cmp(&(&other.start, &other.bound)) + .filter(|order| *order != Ordering::Equal || self == other) + } +} + +// DataFusion formats every extension node while planning it; printing the input plan +// here would make that quadratic in the plan's depth. +impl std::fmt::Debug for TrailWalkNode { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + UserDefinedLogicalNodeCore::fmt_for_explain(self, f) + } +} + +impl UserDefinedLogicalNodeCore for TrailWalkNode { + fn name(&self) -> &str { + "TrailWalk" + } + + fn inputs(&self) -> Vec<&LogicalPlan> { + vec![&self.input] + } + + fn schema(&self) -> &DFSchemaRef { + &self.schema + } + + fn expressions(&self) -> Vec { + vec![] + } + + /// Filters on the end ids this node creates must stay above it. + fn prevent_predicate_push_down_columns(&self) -> HashSet { + self.added_columns().cloned().collect() + } + + /// The input only needs the requested input columns, the start and the bound ends. + fn necessary_children_exprs(&self, output_columns: &[usize]) -> Option>> { + let schema = self.input.schema(); + let width = schema.fields().len(); + let mut needed: Vec = output_columns + .iter() + .copied() + .filter(|&i| i < width) + .collect(); + for column in std::iter::once(&self.start).chain(&self.bound) { + needed.push(schema.index_of_column_by_name(None, column)?); + } + needed.sort_unstable(); + needed.dedup(); + Some(vec![needed]) + } + + fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TrailWalk: {}", self.describe()) + } + + fn with_exprs_and_inputs( + &self, + _exprs: Vec, + inputs: Vec, + ) -> datafusion::common::Result { + let input = inputs.into_iter().next().ok_or_else(|| { + datafusion::common::internal_datafusion_err!("TrailWalk has one input") + })?; + let width = self.input.schema().fields().len(); + let outputs = self.schema.fields()[width..] + .iter() + .map(|f| f.as_ref().clone()) + .collect(); + Self::try_new( + input, + self.start.clone(), + self.bound.clone(), + self.walk.clone(), + outputs, + ) + .map_err(|e| datafusion::common::DataFusionError::Plan(e.to_string())) + } +} + +/// One input batch being walked, and where its walk paused. +struct WalkBatch { + batch: RecordBatch, + starts: Int64Array, + bound: Vec, + row: usize, + cursor: Option, +} + +impl WalkBatch { + fn try_new( + batch: RecordBatch, + start: usize, + bound: &[usize], + ) -> datafusion::common::Result { + let ints = |i: usize| { + cast(batch.column(i), &DataType::Int64).map(|a| a.as_primitive::().clone()) + }; + let starts = ints(start)?; + let bound = bound + .iter() + .map(|&i| ints(i)) + .collect::, _>>()?; + Ok(Self { + batch, + starts, + bound, + row: 0, + cursor: None, + }) + } + + /// Up to `batch_size` matches: their input rows, and per output column the end ids. + async fn next_chunk( + &mut self, + walk: &TrailWalk, + batch_size: usize, + ) -> (Vec, Vec>) { + let outputs: Vec = walk.outputs().collect(); + let mut rows = Vec::new(); + let mut columns = vec![Vec::new(); outputs.len()]; + let mut ends = Vec::new(); + let mut bound = vec![0_i64; self.bound.len()]; + let mut visited = 0_usize; + while self.row < self.starts.len() { + let i = self.row; + // A null start or bound end matches nothing. + if self.starts.is_valid(i) && self.bound.iter().all(|b| b.is_valid(i)) { + for (slot, values) in bound.iter_mut().zip(&self.bound) { + *slot = values.value(i); + } + let key = self.starts.value(i); + let cursor = self + .cursor + .get_or_insert_with(|| TrailCursor::new(walk, key)); + while cursor + .next_group(walk, &bound, batch_size.max(1) - rows.len(), &mut ends) + .await + { + rows.resize(rows.len() + ends.len(), i as u32); + for (column, &s) in columns.iter_mut().zip(&outputs) { + if s + 1 == walk.segments.len() { + column.extend_from_slice(&ends); + } else { + column.resize(rows.len(), cursor.boundaries[s + 1]); + } + } + if rows.len() == batch_size.max(1) { + return (rows, columns); + } + } + } + self.row += 1; + self.cursor = None; + visited += 1; + if visited.is_multiple_of(1024) { + cooperative_yield().await; + } + } + (rows, columns) + } + + fn materialize( + &self, + rows: Vec, + ends: Vec>, + schema: &SchemaRef, + ) -> datafusion::common::Result { + let indices = UInt32Array::from(rows); + let mut columns: Vec = self + .batch + .columns() + .iter() + .map(|c| take(c.as_ref(), &indices, None)) + .collect::>()?; + let width = columns.len(); + for (i, values) in ends.into_iter().enumerate() { + columns.push(cast( + &Int64Array::from(values), + schema.field(width + i).data_type(), + )?); + } + Ok(RecordBatch::try_new(schema.clone(), columns)?) + } +} + +/// Executes [`TrailWalkNode`], one bounded chunk of matches at a time. +#[derive(Debug)] +pub struct TrailWalkExec { + /// Per-partition metrics for `EXPLAIN ANALYZE`. + metrics: datafusion::physical_plan::metrics::ExecutionPlanMetricsSet, + input: Arc, + start: String, + bound: Vec, + walk: Arc, + description: String, + schema: SchemaRef, + properties: Arc, +} + +impl TrailWalkExec { + fn new(node: &TrailWalkNode, input: Arc) -> Self { + let schema: SchemaRef = Arc::new(node.schema.as_arrow().clone()); + Self { + metrics: Default::default(), + properties: Self::properties_for(&schema, &input), + input, + start: node.start.clone(), + bound: node.bound.clone(), + walk: node.walk.clone(), + description: node.describe(), + schema, + } + } + + fn properties_for(schema: &SchemaRef, input: &Arc) -> Arc { + Arc::new(PlanProperties::new( + EquivalenceProperties::new(schema.clone()), + Partitioning::UnknownPartitioning(input.output_partitioning().partition_count()), + EmissionType::Incremental, + Boundedness::Bounded, + )) + } +} + +impl DisplayAs for TrailWalkExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TrailWalkExec: {}", self.description) + } +} + +impl ExecutionPlan for TrailWalkExec { + fn name(&self) -> &str { + "TrailWalkExec" + } + + fn metrics(&self) -> Option { + Some(self.metrics.clone_inner()) + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> datafusion::common::Result> { + let input = children.into_iter().next().ok_or_else(|| { + datafusion::common::internal_datafusion_err!("TrailWalkExec has one child") + })?; + Ok(Arc::new(Self { + metrics: Default::default(), + properties: Self::properties_for(&self.schema, &input), + input, + start: self.start.clone(), + bound: self.bound.clone(), + walk: self.walk.clone(), + description: self.description.clone(), + schema: self.schema.clone(), + })) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> datafusion::common::Result { + let (input, input_time) = + crate::exec_metrics::time_input(self.input.execute(partition, context.clone())?); + // Resolve by name at execution time, so later column pruning cannot shift them. + let start = input.schema().index_of(&self.start)?; + let bound = self + .bound + .iter() + .map(|c| input.schema().index_of(c)) + .collect::, _>>()?; + let batch_size = context.session_config().batch_size(); + let (walk, schema) = (self.walk.clone(), self.schema.clone()); + let stream = futures::stream::try_unfold( + (input, None::), + move |(mut input, mut pending)| { + let (walk, schema, bound) = (walk.clone(), schema.clone(), bound.clone()); + async move { + loop { + if pending.is_none() { + let Some(batch) = input.next().await else { + return Ok(None); + }; + pending = Some(WalkBatch::try_new(batch?, start, &bound)?); + } + let walking = pending.as_mut().expect("input batch just set"); + let (rows, ends) = walking.next_chunk(&walk, batch_size).await; + if rows.is_empty() { + pending = None; + continue; + } + let batch = walking.materialize(rows, ends, &schema)?; + return Ok(Some((batch, (input, pending)))); + } + } + }, + ); + let output: SendableRecordBatchStream = + Box::pin(RecordBatchStreamAdapter::new(self.schema.clone(), stream)); + Ok(crate::exec_metrics::measure( + output, + &self.metrics, + partition, + input_time, + )) + } +} + +pub(super) fn plan_trail_walk( + node: &TrailWalkNode, + physical_inputs: &[Arc], +) -> Arc { + Arc::new(TrailWalkExec::new(node, physical_inputs[0].clone())) +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow::datatypes::{DataType, Field, Schema}; + + /// Nodes 1, 2, 3 of label N; R edges 1->2 twice (parallel) and 2->3. + async fn graph() -> (crate::config::GraphConfig, AdjacencyCatalog) { + let config = crate::config::GraphConfig::builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + .unwrap(); + let mut catalog = AdjacencyCatalog::default(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int64Array::from(vec![1, 2, 3]))]).unwrap(); + catalog.insert_nodes( + "N", + Arc::new(NodeRows::from_batch(batch, "id").unwrap().unwrap()), + ); + let schema = Arc::new(Schema::new(vec![ + Field::new("src", DataType::Int64, false), + Field::new("dst", DataType::Int64, false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1, 1, 2])), + Arc::new(Int64Array::from(vec![2, 2, 3])), + ], + ) + .unwrap(); + for (outgoing, from, to) in [(true, "src", "dst"), (false, "dst", "src")] { + let stream = Box::pin(RecordBatchStreamAdapter::new( + schema.clone(), + futures::stream::iter([Ok(batch.clone())]), + )); + catalog.insert( + "R", + outgoing, + Arc::new(Adjacency::build(stream, from, to).await.unwrap()), + ); + } + (config, catalog) + } + + async fn matches(walk: &TrailWalk, start: i64, bound: &[i64]) -> Vec> { + let mut cursor = TrailCursor::new(walk, start); + let mut ends = Vec::new(); + let mut out = Vec::new(); + while cursor.next_group(walk, bound, 2, &mut ends).await { + for end in &ends { + let mut row = cursor.boundaries[1..].to_vec(); + row.push(*end); + out.push(row); + } + } + out.sort(); + out + } + + fn segment<'a>( + types: &'a [String], + direction: &'a RelationshipDirection, + [min, max]: [u32; 2], + tie: Option, + ) -> WalkSegmentSpec<'a> { + WalkSegmentSpec { + types, + direction, + end_label: "N", + min, + max, + tie, + } + } + + #[tokio::test] + async fn segments_share_one_set_of_walked_edges() { + let (config, catalog) = graph().await; + let r = ["R".to_string()]; + let undirected = RelationshipDirection::Undirected; + // (1)-[:R*1..2]-(f)-[:R]-(g): the hop after f never reuses an edge of the trail. + let walk = TrailWalk::new( + &config, + &catalog, + "N", + &[ + segment(&r, &undirected, [1, 2], None), + segment(&r, &undirected, [1, 1], None), + ], + ) + .unwrap(); + assert_eq!( + matches(&walk, 1, &[]).await, + vec![vec![2, 1], vec![2, 1], vec![2, 3], vec![2, 3]] + ); + } + + #[tokio::test] + async fn mixed_directions_and_zero_length_segments() { + let (config, catalog) = graph().await; + let r = ["R".to_string()]; + let (out, inc) = ( + RelationshipDirection::Outgoing, + RelationshipDirection::Incoming, + ); + // (1)-[:R*0..1]->(f)<-[:R]-(g): from 2 the incoming hop takes the other parallel edge. + let walk = TrailWalk::new( + &config, + &catalog, + "N", + &[ + segment(&r, &out, [0, 1], None), + segment(&r, &inc, [1, 1], None), + ], + ) + .unwrap(); + assert_eq!(matches(&walk, 1, &[]).await, vec![vec![2, 1], vec![2, 1]]); + } + + #[tokio::test] + async fn ties_to_bound_inputs_and_earlier_boundaries() { + let (config, catalog) = graph().await; + let r = ["R".to_string()]; + let undirected = RelationshipDirection::Undirected; + // (a)-[:R*1..2]-(f)-[:R]-(a): back to the start over the other parallel edge. + let walk = TrailWalk::new( + &config, + &catalog, + "N", + &[ + segment(&r, &undirected, [1, 2], None), + segment(&r, &undirected, [1, 1], Some(Tie::Boundary(0))), + ], + ) + .unwrap(); + assert_eq!(matches(&walk, 1, &[]).await, vec![vec![2, 1], vec![2, 1]]); + // The same pattern with the end bound by an input column. + let walk = TrailWalk::new( + &config, + &catalog, + "N", + &[ + segment(&r, &undirected, [1, 2], None), + segment(&r, &undirected, [1, 1], Some(Tie::Input(0))), + ], + ) + .unwrap(); + assert_eq!(matches(&walk, 1, &[3]).await, vec![vec![2, 3], vec![2, 3]]); + assert!(matches(&walk, 1, &[2]).await.is_empty()); + } + + #[tokio::test] + async fn missing_index_declines_the_walk() { + let (config, catalog) = graph().await; + let r = ["R".to_string()]; + let out = RelationshipDirection::Outgoing; + let specs = [WalkSegmentSpec { + types: &r, + direction: &out, + end_label: "Missing", + min: 1, + max: 1, + tie: None, + }]; + assert!(TrailWalk::new(&config, &catalog, "N", &specs).is_none()); + } +} diff --git a/crates/lance-csr/src/csr_traversal.rs b/crates/lance-csr/src/csr_traversal.rs index 5fc8cd78..e9724003 100644 --- a/crates/lance-csr/src/csr_traversal.rs +++ b/crates/lance-csr/src/csr_traversal.rs @@ -2,31 +2,19 @@ // SPDX-FileCopyrightText: Copyright The Lance Authors //! Resumable variable-length walks over immutable, typed CSR snapshots. - -use std::sync::Arc; +//! +//! A variable-length expand is a one-segment [`TrailWalk`]: the same depth-first search, +//! edge identity, last-hop batching and cooperative yields as a multi-segment pattern. use crate::ast::RelationshipDirection; use crate::config::GraphConfig; -use crate::csr_expand::{ - cooperative_yield, AdjacencyCatalog, NeighborPosition, Neighbors, NodeRows, -}; - -#[derive(Debug)] -struct Step { - from: usize, - to: usize, - adjacency: Neighbors, -} +use crate::csr_expand::{AdjacencyCatalog, TrailWalk, WalkSegmentSpec}; #[derive(Debug)] pub(crate) struct Traversal { - steps: Vec, - nodes: Vec>, - start: usize, - target: usize, + walk: TrailWalk, pub min_hops: u32, pub max_hops: u32, - undirected: bool, } impl Traversal { @@ -42,163 +30,47 @@ impl Traversal { min_hops: u32, max_hops: u32, ) -> Option { - let mut labels: Vec = Vec::new(); - let mut nodes = Vec::new(); - let mut label = |name: &str| -> Option { - if let Some(index) = labels.iter().position(|l| l.eq_ignore_ascii_case(name)) { - return Some(index); - } - nodes.push(catalog.nodes(name)?.clone()); - labels.push(name.to_owned()); - Some(labels.len() - 1) - }; - let (start, target) = (label(source_label)?, label(target_label)?); - let mut steps = Vec::new(); - for name in types { - let mapping = config.get_relationship_mapping(name)?; - let (from, to) = ( - label(mapping.source_label.as_deref()?)?, - label(mapping.target_label.as_deref()?)?, - ); - match direction { - RelationshipDirection::Outgoing => steps.push(Step { - from, - to, - adjacency: Neighbors::directed(catalog.get(name, true)?.clone()), - }), - RelationshipDirection::Incoming => steps.push(Step { - from: to, - to: from, - adjacency: Neighbors::directed(catalog.get(name, false)?.clone()), - }), - RelationshipDirection::Undirected if from == to => steps.push(Step { - from, - to, - adjacency: Neighbors::undirected( - catalog.get(name, true)?.clone(), - catalog.get(name, false)?.clone(), - ), - }), - RelationshipDirection::Undirected => { - steps.push(Step { - from, - to, - adjacency: Neighbors::directed(catalog.get(name, true)?.clone()), - }); - steps.push(Step { - from: to, - to: from, - adjacency: Neighbors::directed(catalog.get(name, false)?.clone()), - }); - } - } + if types.is_empty() { + return None; } - (!steps.is_empty()).then_some(Self { - steps, - nodes, - start, - target, + let segment = WalkSegmentSpec { + types, + direction, + end_label: target_label, + min: min_hops, + max: max_hops, + tie: None, + }; + let walk = TrailWalk::new(config, catalog, source_label, &[segment])?; + Some(Self { + walk, min_hops, max_hops, - undirected: *direction == RelationshipDirection::Undirected, }) } -} - -struct Frame { - label: usize, - key: i64, - step: usize, - position: NeighborPosition, - emit: bool, -} - -impl Frame { - fn new(label: usize, key: i64) -> Self { - Self { - label, - key, - step: 0, - position: NeighborPosition::default(), - emit: true, - } - } -} - -pub(crate) struct TraversalCursor { - stack: Vec, -} - -impl TraversalCursor { - pub fn new(graph: &Traversal, key: i64) -> Self { - Self { - stack: vec![Frame::new(graph.start, key)], - } - } - /// Keep one frame per hop, and cooperate even when candidate edges produce no rows. - pub async fn next(&mut self, graph: &Traversal) -> Option { - let mut work = 0; - while !self.stack.is_empty() { - if work == 1024 { - cooperative_yield().await; - work = 0; - } - work += 1; - let depth = self.stack.len() as u32 - 1; - let frame = self.stack.last_mut().expect("nonempty stack"); - if frame.emit { - frame.emit = false; - if depth >= graph.min_hops && frame.label == graph.target { - return Some(frame.key); - } - } - if depth == graph.max_hops || frame.step == graph.steps.len() { - self.stack.pop(); - continue; - } - let step = &graph.steps[frame.step]; - let next = (step.from == frame.label) - .then(|| { - step.adjacency - .candidates_from::(frame.key, &mut frame.position) - .next() - }) - .flatten(); - let key = match next { - Some(Some((key, _))) => key as i64, - Some(None) => continue, - None => { - frame.step += 1; - frame.position = NeighborPosition::default(); - continue; - } - }; - if graph.nodes[step.to].position(key).is_none() { - continue; - } - // Preserve the existing undirected immediate-backtracking rule, using typed ids. - // shortcut: full relationship uniqueness needs edge row ids, as on the join path. - if graph.undirected - && self.stack.len() >= 2 - && self.stack[self.stack.len() - 2].label == step.to - && self.stack[self.stack.len() - 2].key == key - { - continue; - } - self.stack.push(Frame::new(step.to, key)); - } - None + pub(crate) fn walk(&self) -> &TrailWalk { + &self.walk } } #[cfg(test)] mod tests { use super::*; - use crate::csr_expand::Adjacency; + use crate::csr_expand::{Adjacency, NodeRows, TrailCursor}; use arrow::array::{Int64Array, RecordBatch}; use arrow::datatypes::{DataType, Field, Schema}; use datafusion::physical_plan::stream::RecordBatchStreamAdapter; + use std::sync::Arc; + + /// The next end, one at a time. + async fn next(cursor: &mut TrailCursor, graph: &Traversal) -> Option { + let mut ends = Vec::new(); + cursor + .next_group(graph.walk(), &[], 1, &mut ends) + .await + .then(|| ends[0]) + } async fn graph() -> (GraphConfig, AdjacencyCatalog) { let config = GraphConfig::builder() @@ -263,16 +135,38 @@ mod tests { 3, ) .unwrap(); - let mut cursor = TraversalCursor::new(&walk, 1); + let mut cursor = TrailCursor::new(walk.walk(), 1); let mut out = Vec::new(); - while let Some(key) = cursor.next(&walk).await { + while let Some(key) = next(&mut cursor, &walk).await { out.push(key); - assert!(cursor.stack.len() <= 4); + assert!(cursor.depth() <= 4); } out.sort(); // Tag 1 and Class 1 are different nodes; no extra zero-hop Class 1 result. assert_eq!(out, vec![1, 1, 2, 2, 3, 3]); - assert!(cursor.stack.is_empty()); + assert_eq!(cursor.depth(), 0); + } + + #[tokio::test] + async fn last_hop_groups_ends_up_to_the_limit() { + let (config, catalog) = graph().await; + // Tag 1 has two parallel hasType edges to Class 1: one group, two ends. + let walk = Traversal::new( + &config, + &catalog, + &["hasType".into()], + &RelationshipDirection::Outgoing, + "Tag", + "Class", + 1, + 1, + ) + .unwrap(); + let mut cursor = TrailCursor::new(walk.walk(), 1); + let mut ends = Vec::new(); + assert!(cursor.next_group(walk.walk(), &[], 8, &mut ends).await); + assert_eq!(ends, vec![1, 1]); + assert!(!cursor.next_group(walk.walk(), &[], 8, &mut ends).await); } #[tokio::test] @@ -315,18 +209,18 @@ mod tests { 1, ) .unwrap(); - let mut cursor = TraversalCursor::new(&walk, 1); - let mut next = Box::pin(cursor.next(&walk)); - assert!(futures::poll!(next.as_mut()).is_pending()); - drop(next); - assert_eq!(cursor.next(&walk).await, Some(1)); - assert_eq!(cursor.next(&walk).await, None); + let mut cursor = TrailCursor::new(walk.walk(), 1); + let mut pending = Box::pin(next(&mut cursor, &walk)); + assert!(futures::poll!(pending.as_mut()).is_pending()); + drop(pending); + assert_eq!(next(&mut cursor, &walk).await, Some(1)); + assert_eq!(next(&mut cursor, &walk).await, None); } #[tokio::test] - async fn zero_hop_is_identity_and_depth_bound_survives_cycles() { + async fn batches_intermediate_ends_and_resumes_at_the_next_depth() { let (config, catalog) = graph().await; - let walk = Traversal::new( + let graph = Traversal::new( &config, &catalog, &["isSubclass".into()], @@ -337,19 +231,49 @@ mod tests { 20, ) .unwrap(); - let mut cursor = TraversalCursor::new(&walk, 1); - for depth in 0..=20 { - assert_eq!(cursor.next(&walk).await, Some(1 + depth % 3)); - assert_eq!(cursor.stack.len(), depth as usize + 1); - } - assert_eq!(cursor.next(&walk).await, None); - let zero = Traversal { - max_hops: 0, - ..walk + let walk = graph.walk(); + let mut cursor = TrailCursor::new(walk, 1); + let mut ends = Vec::new(); + assert!(cursor.next_group(walk, &[], 2, &mut ends).await); + assert_eq!(ends, [1, 2]); + assert!(cursor.next_group(walk, &[], 2, &mut ends).await); + assert_eq!(ends, [3, 1]); + assert!(!cursor.next_group(walk, &[], 2, &mut ends).await); + cursor.restart(walk, 2); + assert!(cursor.next_group(walk, &[], 2, &mut ends).await); + assert_eq!(ends, [2, 3]); + assert!(cursor.next_group(walk, &[], 2, &mut ends).await); + assert_eq!(ends, [1, 2]); + assert!(!cursor.next_group(walk, &[], 2, &mut ends).await); + } + + #[tokio::test] + async fn zero_hop_is_identity_and_a_cycle_can_only_be_traversed_once() { + let (config, catalog) = graph().await; + let subclass = |max_hops| { + Traversal::new( + &config, + &catalog, + &["isSubclass".into()], + &RelationshipDirection::Outgoing, + "Class", + "Class", + 0, + max_hops, + ) + .unwrap() }; - let mut cursor = TraversalCursor::new(&zero, 2); - assert_eq!(cursor.next(&zero).await, Some(2)); - assert_eq!(cursor.next(&zero).await, None); + let walk = subclass(20); + let mut cursor = TrailCursor::new(walk.walk(), 1); + for depth in 0..=3 { + assert_eq!(next(&mut cursor, &walk).await, Some(1 + depth % 3)); + assert_eq!(cursor.depth(), depth as usize + 1); + } + assert_eq!(next(&mut cursor, &walk).await, None); + let zero = subclass(0); + let mut cursor = TrailCursor::new(zero.walk(), 2); + assert_eq!(next(&mut cursor, &zero).await, Some(2)); + assert_eq!(next(&mut cursor, &zero).await, None); } #[tokio::test] @@ -371,10 +295,17 @@ mod tests { 2, ) .unwrap(); - let mut cursor = TraversalCursor::new(&walk, 1); - let mut next = Box::pin(cursor.next(&walk)); - assert!(futures::poll!(&mut next).is_pending()); - drop(next); - assert!(cursor.stack.len() <= 3); + let mut cursor = TrailCursor::new(walk.walk(), 1); + let mut pending = Box::pin(next(&mut cursor, &walk)); + assert!(futures::poll!(&mut pending).is_pending()); + drop(pending); + assert!(cursor.depth() <= 3); + } + + #[tokio::test] + async fn untyped_walk_declines() { + let (config, catalog) = graph().await; + let direction = RelationshipDirection::Outgoing; + assert!(Traversal::new(&config, &catalog, &[], &direction, "Tag", "Class", 1, 2).is_none()); } } diff --git a/crates/lance-csr/src/datafusion_planner/analysis.rs b/crates/lance-csr/src/datafusion_planner/analysis.rs index f2bf6abd..4a06c369 100644 --- a/crates/lance-csr/src/datafusion_planner/analysis.rs +++ b/crates/lance-csr/src/datafusion_planner/analysis.rs @@ -196,8 +196,6 @@ fn analyze_operator( relationship_types, direction, relationship_variable, - min_length, - max_length, .. } => { // Recursively analyze input first @@ -209,40 +207,26 @@ fn analyze_operator( ); analysis.var_to_label.insert(target_variable.clone(), label); - // For variable-length paths, register multiple instances (one per hop) - // We need to register instances for all possible hop counts - if let Some(rel_type) = relationship_types.first() { - let max_hops = max_length.unwrap_or(crate::MAX_VARIABLE_LENGTH_HOPS); - let min_hops = min_length.unwrap_or(1).max(1); - - // Register instances for each hop count we'll generate - for hop_count in min_hops..=max_hops { - for _ in 0..hop_count { - let instance_id = rel_counter - .entry(rel_type.clone()) - .and_modify(|c| *c += 1) - .or_insert(1); - - // Use relationship variable if provided, otherwise use type_instanceId - let alias = if let Some(rel_var) = relationship_variable { - format!("{}_{}", rel_var, instance_id) - } else { - format!("{}_{}", rel_type.to_lowercase(), instance_id) - }; - - analysis.relationship_instances.push(RelationshipInstance { - id: *instance_id, - rel_type: rel_type.clone(), - source_var: source_variable.clone(), - target_var: target_variable.clone(), - direction: direction.clone(), - alias, - }); - } - } - - analysis.required_datasets.insert(rel_type.clone()); + // Both the CSR operator and the join fallback consume one instance per segment. + // The fallback's per-hop columns are local to each branch. + if let Some(kind) = relationship_types.first() { + let id = rel_counter.entry(kind.clone()).or_default(); + *id += 1; + let name = relationship_variable + .clone() + .unwrap_or_else(|| kind.to_lowercase()); + analysis.relationship_instances.push(RelationshipInstance { + id: *id, + rel_type: kind.clone(), + source_var: source_variable.clone(), + target_var: target_variable.clone(), + direction: direction.clone(), + alias: format!("{name}_{id}"), + }); } + analysis + .required_datasets + .extend(relationship_types.iter().cloned()); } LogicalOperator::Filter { input, .. } | LogicalOperator::Project { input, .. } @@ -441,7 +425,7 @@ mod tests { #[test] fn test_varlength_expand_analysis_registers_instances() { - // Test that analysis phase correctly registers multiple relationship instances + // Internal hop aliases are private to the segment. let scan_a = LogicalOperator::ScanByLabel { variable: "a".to_string(), label: "Person".to_string(), @@ -475,18 +459,14 @@ mod tests { let _planner = crate::datafusion_planner::DataFusionPlanner::new(cfg); let analysis = analyze(&vlexpand).unwrap(); - // For *1..2, should register 1 + 2 = 3 instances + // One public instance regardless of the number of internal hops. let knows_instances: Vec<_> = analysis .relationship_instances .iter() .filter(|r| r.rel_type == "KNOWS") .collect(); - assert_eq!( - knows_instances.len(), - 3, - "Expected 3 KNOWS instances (1 for 1-hop + 2 for 2-hop)" - ); + assert_eq!(knows_instances.len(), 1); } #[test] diff --git a/crates/lance-csr/src/datafusion_planner/builder/expand_ops.rs b/crates/lance-csr/src/datafusion_planner/builder/expand_ops.rs index fed8c2fc..a6321d2e 100644 --- a/crates/lance-csr/src/datafusion_planner/builder/expand_ops.rs +++ b/crates/lance-csr/src/datafusion_planner/builder/expand_ops.rs @@ -193,6 +193,7 @@ impl DataFusionPlanner { relationship_properties, rel_map, direction, + None, )?; // Join source node with relationship @@ -714,216 +715,47 @@ impl DataFusionPlanner { } else { None }; - if let Some(plan) = csr_plan { - let projection: Vec<_> = plan - .schema() - .fields() - .iter() - .filter(|f| expected_columns.contains(f.name().as_str())) - .map(|f| col(f.name())) - .collect(); - return LogicalPlanBuilder::from(plan) - .project(projection) - .and_then(|p| p.build()) - .map_err(|e| self.plan_error("Failed to project variable-length CSR", e)); - } - - // Generate a plan for each hop count and UNION them - let mut plans = Vec::new(); - - for hop_count in min_hops..=max_hops { - let mut plan = self.build_fixed_length_path( - ctx, - input_plan.clone(), - source_variable, - target_variable, - relationship_types, - direction, - hop_count, - relationship_properties, - target_properties, - )?; - - // Project only source and target columns to ensure consistent schema for UNION - // This removes intermediate node columns that vary by hop count - // Use the pre-computed expected column set derived from actual node schemas - let projection: Vec = plan - .schema() - .fields() - .iter() - .filter(|f| expected_columns.contains(f.name().as_str())) - .map(|f| col(f.name())) - .collect(); - - plan = LogicalPlanBuilder::from(plan) - .project(projection) - .map_err(|e| crate::error::GraphError::PlanError { - message: format!("Failed to project for UNION: {}", e), - location: snafu::Location::new(file!(), line!(), column!()), - })? - .build() - .map_err(|e| crate::error::GraphError::PlanError { - message: format!("Failed to build projection: {}", e), - location: snafu::Location::new(file!(), line!(), column!()), + let plan = match csr_plan { + Some(plan) => plan, + None => { + let (start_label, _) = self.get_target_node_mapping(ctx, source_variable)?; + let (end_label, _) = self.get_target_node_mapping(ctx, target_variable)?; + let first = relationship_types.first().ok_or_else(|| { + crate::error::GraphError::internal("a variable-length relationship type") })?; - - plans.push(plan); - } - - // UNION all plans together - if plans.len() == 1 { - plans - .into_iter() - .next() - .ok_or_else(|| crate::error::GraphError::internal("one plan")) - } else { - // Build UNION of all plans - let mut union_plan = plans[0].clone(); - for plan in plans.into_iter().skip(1) { - union_plan = LogicalPlanBuilder::from(union_plan) - .union(plan) - .map_err(|e| crate::error::GraphError::PlanError { - message: format!("Failed to UNION variable-length paths: {}", e), - location: snafu::Location::new(file!(), line!(), column!()), - })? - .build() - .map_err(|e| crate::error::GraphError::PlanError { - message: format!("Failed to build UNION plan: {}", e), - location: snafu::Location::new(file!(), line!(), column!()), - })?; - } - Ok(union_plan) - } - } - - /// Build a fixed-length path of N hops - /// - /// For hop_count=3: (a)-[:KNOWS]->(temp1)-[:KNOWS]->(temp2)-[:KNOWS]->(b) - #[allow(clippy::too_many_arguments)] - pub(crate) fn build_fixed_length_path( - &self, - ctx: &mut PlanningContext, - input_plan: LogicalPlan, - source_variable: &str, - target_variable: &str, - relationship_types: &[String], - direction: &RelationshipDirection, - hop_count: u32, - relationship_properties: &HashMap, - target_properties: &HashMap, - ) -> Result { - if hop_count == 0 { - let (source_label, source_map) = self.get_target_node_mapping(ctx, source_variable)?; - let (target_label, target_map) = self.get_target_node_mapping(ctx, target_variable)?; - let source = col(qualify_column(source_variable, &source_map.id_field)); - let target = qualify_column(target_variable, &target_map.id_field); - let same_label = source_label.eq_ignore_ascii_case(&target_label); - let mut builder = LogicalPlanBuilder::from(input_plan); - if builder - .schema() - .field_with_unqualified_name(&target) - .is_ok() - { - if !target_properties.is_empty() { - return Err(crate::error::GraphError::PlanError { - message: format!("Property filters on reused variable '{target_variable}' are not yet supported"), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - builder = builder - .filter( - source - .eq(col(&target)) - .and(datafusion::logical_expr::lit(same_label)), - ) - .map_err(|e| self.plan_error("Failed to filter zero-hop identity", e))?; - } else { - let target_source = - self.get_catalog()? - .node_source(&target_label) - .ok_or_else(|| crate::error::GraphError::PlanError { - message: format!("No node source for {target_label}"), - location: snafu::Location::new(file!(), line!(), column!()), - })?; - let scan = self.build_target_scan( - target_source, - &target_label, - target_variable, + ctx.next_relationship_instance(first)?; + let segment = super::trail_joins::ChainSegment { + types: relationship_types, + direction, + range: [min_hops, max_hops], + properties: relationship_properties, + end: target_variable, + end_label: &end_label, + }; + self.build_trail_chain( + &input_plan, + [source_variable, &start_label], + &[segment], target_properties, - )?; - builder = builder - .join_on( - scan, - datafusion::logical_expr::JoinType::Inner, - [source - .eq(col(&target)) - .and(datafusion::logical_expr::lit(same_label))], + )? + .ok_or_else(|| { + crate::error::GraphError::internal( + "a single trail segment has no further fallback", ) - .map_err(|e| self.plan_error("Failed to join zero-hop identity", e))?; + })? } - return builder - .build() - .map_err(|e| self.plan_error("Failed to build zero-hop identity", e)); - } - let mut current_plan = input_plan; - let mut current_source = source_variable.to_string(); - let mut path_nodes = vec![current_source.clone()]; - - for hop_index in 0..hop_count { - let is_last_hop = hop_index == hop_count - 1; - - // Target variable: use actual target on last hop, temp variable otherwise - let current_target = if is_last_hop { - target_variable.to_string() - } else { - format!("_temp_{}_{}", source_variable, hop_index + 1) - }; - - // Build the expansion on top of current plan - // Apply target properties only on the last hop - let props_to_apply = if is_last_hop { - target_properties - } else { - &HashMap::new() - }; - - current_plan = self.build_expand_on_plan( - ctx, - current_plan, - ¤t_source, - ¤t_target, - relationship_types, - direction, - relationship_properties, - props_to_apply, - )?; - - // Move to next hop - path_nodes.push(current_target.clone()); - current_source = current_target; - } - - if *direction != RelationshipDirection::Undirected { - return Ok(current_plan); - } - // Cypher never reuses a relationship within a path, but an undirected hop can walk - // straight back over the edge it just took (u-v-u). Rule that out by requiring each - // node to differ from the one two hops earlier. - // shortcut: exact only while no two distinct edges join the same pair of nodes (and - // for paths of at most 3 hops); upgrade by carrying edge row ids through the hops. - let mut builder = LogicalPlanBuilder::from(current_plan); - for pair in path_nodes.windows(3) { - let id = |var: &str| -> Result<_> { - let (_, node_map) = self.get_target_node_mapping(ctx, var)?; - Ok(col(qualify_column(var, &node_map.id_field))) - }; - builder = builder - .filter(id(&pair[0])?.not_eq(id(&pair[2])?)) - .map_err(|e| self.plan_error("Failed to filter backtracking hops", e))?; - } - builder - .build() - .map_err(|e| self.plan_error("Failed to build undirected path", e)) + }; + let projection: Vec<_> = plan + .schema() + .fields() + .iter() + .filter(|f| expected_columns.contains(f.name().as_str())) + .map(|f| col(f.name())) + .collect(); + LogicalPlanBuilder::from(plan) + .project(projection) + .and_then(|p| p.build()) + .map_err(|e| self.plan_error("Failed to project variable-length paths", e)) } #[allow(clippy::too_many_arguments)] @@ -939,7 +771,7 @@ impl DataFusionPlanner { max_hops: u32, target_properties: &HashMap, ) -> Result> { - use crate::csr_expand::{CsrExpandNode, Neighbors}; + use crate::csr_expand::CsrExpandNode; use datafusion::logical_expr::Extension; if max_hops == 0 { return Ok(None); @@ -971,16 +803,10 @@ impl DataFusionPlanner { { return Ok(None); } - let get = |forward: bool| { - catalog - .get(rel_type, forward) - .cloned() - .ok_or_else(|| crate::error::GraphError::internal("validated traversal")) - }; - let adjacency = match direction { - RelationshipDirection::Outgoing => Neighbors::directed(get(true)?), - RelationshipDirection::Incoming => Neighbors::directed(get(false)?), - RelationshipDirection::Undirected => Neighbors::undirected(get(true)?, get(false)?), + // An unreachable type may be written first and have no index. The traversal + // already selected its participating CSR steps. Joins also handle an identity-only plan. + let Some(adjacency) = walk.walk().first_neighbors().cloned() else { + return Ok(None); }; let cat = self.get_catalog()?; let target = target_properties @@ -1037,46 +863,6 @@ impl DataFusionPlanner { ) .map(Some) } - - /// Build a single-hop expansion on top of an existing plan (one hop of a - /// variable-length path). Uses the same planning as a single hop, so a hop gets - /// the CSR expansion whenever a plain `(a)-[:R]->(b)` would. - #[allow(clippy::too_many_arguments)] - pub(crate) fn build_expand_on_plan( - &self, - ctx: &mut PlanningContext, - input_plan: LogicalPlan, - source_variable: &str, - target_variable: &str, - relationship_types: &[String], - direction: &RelationshipDirection, - relationship_properties: &HashMap, - target_properties: &HashMap, - ) -> Result { - if relationship_types.is_empty() { - return Err(crate::error::GraphError::InvalidPattern { - message: "Expand requires at least one relationship type".to_string(), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - // Fail on a missing mapping or catalog here: `expand_plan` passes the input - // through in those cases, which would silently drop the hop. - self.get_relationship_mapping(&relationship_types[0])?; - self.get_catalog()?; - let (target_label, _) = self.get_target_node_mapping(ctx, target_variable)?; - self.expand_plan( - ctx, - input_plan, - source_variable, - target_variable, - &target_label, - relationship_types, - direction, - None, - relationship_properties, - target_properties, - ) - } } #[cfg(test)] @@ -1260,6 +1046,53 @@ mod tests { assert!(s.contains("Join(")); } + #[test] + fn test_varlength_expand_unlabeled_type_zero_hop_target_filter() { + // MATCH (a:Person)-[:KNOWS*0..2]->(b:Person {name: 'Bob'}) with KNOWS mapped + // without endpoint labels: a chain of one segment still plans every length, + // the zero-hop identity included, and filters the target on each branch. + let vlexpand = LogicalOperator::VariableLengthExpand { + input: Box::new(person_scan("a")), + source_variable: "a".into(), + target_variable: "b".into(), + target_label: "Person".to_string(), + relationship_types: vec!["KNOWS".into()], + direction: crate::ast::RelationshipDirection::Outgoing, + relationship_variable: None, + min_length: Some(0), + max_length: Some(2), + properties: Default::default(), + target_properties: HashMap::from([( + "name".to_string(), + PropertyValue::String("Bob".into()), + )]), + }; + let project = LogicalOperator::Project { + input: Box::new(vlexpand), + projections: vec![ProjectionItem { + expression: ValueExpression::Property(PropertyRef { + variable: "b".into(), + property: "name".into(), + }), + alias: None, + }], + }; + let cfg = crate::config::GraphConfig::builder() + .node_table("Person", "id") + .with_relationship_mapping(crate::config::RelationshipMapping::new( + "KNOWS", + "src_person_id", + "dst_person_id", + )) + .build() + .unwrap(); + let planner = DataFusionPlanner::with_catalog(cfg, make_catalog()); + let s = format!("{:?}", planner.plan(&project).unwrap()); + // Zero, one and two hops: three branches, each filtering its target scan. + assert!(s.contains("Union"), "{s}"); + assert!(s.matches("Bob").count() >= 3, "{s}"); + } + #[test] fn test_varlength_expand_default_min() { // MATCH (a:Person)-[:KNOWS*..3]->(b:Person) - min defaults to 1 diff --git a/crates/lance-csr/src/datafusion_planner/builder/mod.rs b/crates/lance-csr/src/datafusion_planner/builder/mod.rs index 7e9fa59d..923191bb 100644 --- a/crates/lance-csr/src/datafusion_planner/builder/mod.rs +++ b/crates/lance-csr/src/datafusion_planner/builder/mod.rs @@ -22,6 +22,7 @@ mod expand_ops; mod helpers; mod join_builder; mod path_ops; +mod trail_joins; use super::DataFusionPlanner; use crate::error::Result; 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 49422a3e..2f6fa8f8 100644 --- a/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs +++ b/crates/lance-csr/src/datafusion_planner/builder/path_ops.rs @@ -1,19 +1,265 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The lance-csr Authors -use crate::ast::RelationshipDirection; -use crate::ast::{BooleanExpression, PathPattern}; +use super::trail_joins::ChainSegment; +use crate::ast::{ + BooleanExpression, NodePattern, PathPattern, PropertyValue, RelationshipDirection, +}; use crate::case_insensitive::qualify_column; -use crate::csr_expand::{AdjacencyCatalog, Neighbors}; +use crate::csr_expand::{ + AdjacencyCatalog, Neighbors, Tie, TrailWalk, TrailWalkNode, WalkSegmentSpec, +}; 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, CsrHop, CsrRoute, PathMatchNode, PathSpec, Step}; -use datafusion::logical_expr::{Extension, LogicalPlan, LogicalPlanBuilder}; +use datafusion::common::Column; +use datafusion::logical_expr::{col, Expr, Extension, LogicalPlan, LogicalPlanBuilder}; +use std::collections::HashMap; use std::sync::Arc; impl DataFusionPlanner { + /// A path without a path variable whose variable-length segment shares a relationship + /// type with another segment (`(a)-[:R*1..2]-(f)-[:R]-(g)`). The segments must not + /// share an edge, so they are planned as one trail instead of separate expansions: a + /// CSR walk seeded at each start row ([`TrailWalkNode`]) when every type and label is + /// indexed and no segment filters relationship properties, otherwise one chain of + /// joins per combination of segment lengths ([`Self::build_trail_chain`]). Either way + /// the work follows the rows' start nodes; no edge inventory is built. + /// + /// If the combined chain would be too wide, plan each segment independently. + fn build_overlapping_trail( + &self, + ctx: &PlanningContext, + input: &LogicalPlan, + path: &PathPattern, + ) -> Result { + let segments = &path.segments; + let resolve = |node: &NodePattern| -> Option<(String, String)> { + let variable = node.variable.clone()?; + let label = ctx + .analysis + .var_to_label + .get(&variable) + .or_else(|| node.labels.first())? + .clone(); + self.config.get_node_mapping(&label)?; + Some((variable, label)) + }; + let (start, start_label) = resolve(&path.start_node) + .ok_or_else(|| GraphError::internal("a resolved trail start"))?; + let mut ends = Vec::with_capacity(segments.len()); + for segment in segments { + let [min, max] = segment.relationship.hop_range(); + if min > max || max > crate::MAX_VARIABLE_LENGTH_HOPS { + return Err(GraphError::UnsupportedFeature { + feature: format!("invalid trail range {min}..{max}; variable-length paths allow at most {} hops", crate::MAX_VARIABLE_LENGTH_HOPS), + location: snafu::Location::new(file!(), line!(), column!()), + }); + } + ends.push( + resolve(&segment.end_node) + .ok_or_else(|| GraphError::internal("a resolved trail boundary"))?, + ); + } + let start_map = self + .config + .get_node_mapping(&start_label) + .ok_or_else(|| GraphError::internal("a resolved start label"))?; + let start_key = qualify_column(&start, &start_map.id_field); + input + .schema() + .field_with_unqualified_name(&start_key) + .map_err(|e| self.plan_error("Missing trail start key", e))?; + let input = self.filter_node_properties( + input.clone(), + &start, + &start_label, + &path.start_node.properties, + )?; + let walked = self.try_build_trail_walk(&input, [&start, &start_label], path, &ends)?; + let mut plan = match walked { + Some(plan) => plan, + None => { + let chain: Vec = segments + .iter() + .zip(&ends) + .map(|(segment, (end, end_label))| ChainSegment { + types: &segment.relationship.types, + direction: &segment.relationship.direction, + range: segment.relationship.hop_range(), + properties: &segment.relationship.properties, + end, + end_label, + }) + .collect(); + self.build_trail_chain(&input, [&start, &start_label], &chain, &HashMap::new())? + .ok_or_else(|| { + GraphError::internal("shared trail exceeds the planned branch budget") + })? + } + }; + for (segment, (end, label)) in segments.iter().zip(&ends) { + plan = self.filter_node_properties(plan, end, label, &segment.end_node.properties)?; + } + Ok(plan) + } + + /// The CSR walk of [`Self::build_overlapping_trail`], with each new boundary node's + /// other columns looked up through its node index (and dropped when unused). `None` + /// when a type, direction or label has no index, a segment filters relationship + /// properties, or a start or bound column is not an integer id. + fn try_build_trail_walk( + &self, + input: &LogicalPlan, + [start, start_label]: [&str; 2], + path: &PathPattern, + ends: &[(String, String)], + ) -> Result> { + let Some(catalog) = &self.adjacency else { + return Ok(None); + }; + if path + .segments + .iter() + .any(|s| !s.relationship.properties.is_empty()) + { + return Ok(None); + } + let schema = input.schema(); + let id_column = |name: &str| { + schema + .field_with_unqualified_name(name) + .ok() + .map(|f| crate::csr_expand::is_supported_id_type(f.data_type())) + }; + let node_map = |label: &str| { + self.config + .get_node_mapping(label) + .ok_or_else(|| GraphError::internal("a resolved boundary label")) + }; + let start_key = qualify_column(start, &node_map(start_label)?.id_field); + if id_column(&start_key) != Some(true) { + return Ok(None); + } + // Boundary k is the start for k = 0, else the end of segment k - 1. + let mut boundaries = vec![start.to_lowercase()]; + let mut bound = Vec::new(); + let mut specs = Vec::with_capacity(path.segments.len()); + let mut outputs = Vec::new(); + for (s, (segment, (end, label))) in path.segments.iter().zip(ends).enumerate() { + let key = qualify_column(end, &node_map(label)?.id_field); + let tie = if let Some(k) = boundaries.iter().position(|b| *b == end.to_lowercase()) { + Some(Tie::Boundary(k)) + } else { + match id_column(&key) { + Some(true) => { + bound.push(key.clone()); + Some(Tie::Input(bound.len() - 1)) + } + Some(false) => return Ok(None), + None => None, + } + }; + if tie.is_none() { + outputs.push((s, end.as_str(), label.as_str(), key)); + } + boundaries.push(end.to_lowercase()); + let [min, max] = segment.relationship.hop_range(); + specs.push(WalkSegmentSpec { + types: &segment.relationship.types, + direction: &segment.relationship.direction, + end_label: label, + min, + max, + tie, + }); + } + let Some(walk) = TrailWalk::new(&self.config, catalog, start_label, &specs) else { + return Ok(None); + }; + let walk = Arc::new(walk); + let cat = self.get_catalog()?; + let mut fields = Vec::with_capacity(outputs.len()); + for (_, _, label, key) in &outputs { + let id = &node_map(label)?.id_field; + let source = cat + .node_source(label) + .ok_or_else(|| GraphError::internal("an indexed boundary label's table"))?; + let schema = source.schema(); + let field = schema + .fields() + .iter() + .find(|f| f.name().eq_ignore_ascii_case(id)) + .ok_or_else(|| GraphError::internal("a boundary node's id column"))?; + fields.push(field.as_ref().clone().with_name(key).with_nullable(true)); + } + let node = TrailWalkNode::try_new(input.clone(), start_key, bound, walk.clone(), fields)?; + let mut plan = LogicalPlan::Extension(Extension { + node: Arc::new(node), + }); + for (s, end, label, key) in outputs { + let id = &node_map(label)?.id_field; + let rows = walk.end_rows(s).clone(); + let wanted: Vec<(String, String)> = rows + .schema() + .fields() + .iter() + .filter(|f| !f.name().eq_ignore_ascii_case(id)) + .map(|f| (qualify_column(end, f.name()), f.name().clone())) + .collect(); + if wanted.is_empty() { + continue; + } + let lookup = crate::csr_expand::NodeLookupNode::try_new( + plan, + key, + end.to_lowercase(), + rows, + &wanted, + )?; + plan = LogicalPlan::Extension(Extension { + node: Arc::new(lookup), + }); + } + Ok(Some(plan)) + } + + /// `plan` keeping the rows whose node `variable` has the inline property values. + fn filter_node_properties( + &self, + plan: LogicalPlan, + variable: &str, + label: &str, + properties: &HashMap, + ) -> Result { + let schema = self.get_catalog()?.node_source(label).map(|s| s.schema()); + let Some(predicate) = properties + .iter() + .map(|(key, value)| { + let field = schema + .as_ref() + .and_then(|s| { + s.fields() + .iter() + .find(|f| f.name().eq_ignore_ascii_case(key)) + }) + .map_or(key.as_str(), |f| f.name().as_str()); + let value = self + .unresolved_value_expr(&crate::ast::ValueExpression::Literal(value.clone())); + col(Column::new_unqualified(qualify_column(variable, field))).eq(value) + }) + .reduce(Expr::and) + else { + return Ok(plan); + }; + LogicalPlanBuilder::from(plan) + .filter(predicate) + .and_then(|b| b.build()) + .map_err(|e| self.plan_error("Failed to filter path node properties", e)) + } + pub(crate) fn build_path_match( &self, ctx: &mut PlanningContext, @@ -28,6 +274,9 @@ impl DataFusionPlanner { }; let catalog = self.get_catalog()?; let input = self.build_operator(ctx, input)?; + if !node_values && path.needs_trail_across_segments() { + return self.build_overlapping_trail(ctx, &input, path); + } let mut node_labels = Vec::::new(); let mut edge_labels = Vec::::new(); for segment in &path.segments { @@ -292,3 +541,167 @@ fn csr_route( .collect::>>()?; Some(CsrRoute { steps }) } + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::Arc; + + use arrow_array::{Array, Int64Array, RecordBatch}; + use arrow_schema::{DataType, Field, Schema}; + + use crate::{CypherEngine, EngineSource, GraphConfig}; + + fn ints(columns: &[(&str, Vec)]) -> RecordBatch { + let fields: Vec = columns + .iter() + .map(|(name, _)| Field::new(*name, DataType::Int64, false)) + .collect(); + let arrays = columns + .iter() + .map(|(_, values)| Arc::new(Int64Array::from(values.clone())) as _) + .collect(); + RecordBatch::try_new(Arc::new(Schema::new(fields)), arrays).unwrap() + } + + /// Nodes 1, 2, 3; `R` edges 1->2 twice (parallel, so distinct) and 2->3. + async fn engine(use_csr: bool) -> CypherEngine { + let config = GraphConfig::builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + .unwrap(); + let sources = HashMap::from([ + ( + "N".to_string(), + EngineSource::Arrow(ints(&[("id", vec![1, 2, 3])])), + ), + ( + "R".to_string(), + EngineSource::Arrow(ints(&[("src", vec![1, 1, 2]), ("dst", vec![2, 2, 3])])), + ), + ]); + CypherEngine::new(config, sources, use_csr).await.unwrap() + } + + async fn rows(engine: &CypherEngine, query: &str) -> Vec> { + let batch = engine.execute(query, HashMap::new()).await.unwrap(); + let columns: Vec<&Int64Array> = batch + .columns() + .iter() + .map(|c| c.as_any().downcast_ref::().unwrap()) + .collect(); + let mut out: Vec> = (0..batch.num_rows()) + .map(|i| columns.iter().map(|c| c.value(i)).collect()) + .collect(); + out.sort(); + out + } + + /// The rows of `query` with and without the CSR, which must agree. Neither plan may + /// build the edge inventory; the CSR plan walks the pattern from each start row. + async fn trail(query: &str) -> Vec> { + let mut results = Vec::new(); + for use_csr in [false, true] { + let engine = engine(use_csr).await; + let plan = engine.explain(query, HashMap::new()).await.unwrap(); + assert!(!plan.contains("PathMatchExec"), "{query}: {plan}"); + assert_eq!(plan.contains("TrailWalkExec"), use_csr, "{query}: {plan}"); + results.push(rows(&engine, query).await); + } + assert_eq!(results[0], results[1], "{query}"); + results.remove(0) + } + + #[tokio::test] + async fn hop_after_a_trail_of_its_type_keeps_the_edges_apart() { + // From 2 the last hop returns to 1 over the parallel edge the trail did not take. + let query = "MATCH (:N {id: 1})-[:R*1..2]-(f:N)-[:R]-(g:N)"; + assert_eq!( + trail(&format!("{query} RETURN f.id, g.id")).await, + vec![vec![2, 1], vec![2, 1], vec![2, 3], vec![2, 3]] + ); + assert_eq!( + trail(&format!("{query} RETURN count(*)")).await, + vec![vec![4]] + ); + } + + #[tokio::test] + async fn segments_in_different_directions_and_of_zero_length() { + let query = "MATCH (:N {id: 1})-[:R*0..1]->(f:N)<-[:R]-(g:N) RETURN f.id, g.id"; + assert_eq!(trail(query).await, vec![vec![2, 1], vec![2, 1]]); + let query = "MATCH (:N {id: 3})<-[:R]-(f:N)<-[:R*1..2]-(g:N) RETURN f.id, g.id"; + assert_eq!(trail(query).await, vec![vec![2, 1], vec![2, 1]]); + } + + #[tokio::test] + async fn segment_ends_bound_in_the_pattern_or_by_earlier_rows() { + let query = "MATCH (a:N {id: 1})-[:R*1..2]-(f:N)-[:R]-(a) RETURN f.id"; + assert_eq!(trail(query).await, vec![vec![2], vec![2]]); + let query = "MATCH (g:N {id: 3}) \ + MATCH (:N {id: 1})-[:R*1..2]-(f:N)-[:R]-(g) RETURN f.id, g.id"; + assert_eq!(trail(query).await, vec![vec![2, 3], vec![2, 3]]); + let query = "MATCH (:N {id: 1})-[:R*1..2]-(f:N {id: 2})-[:R]-(g:N) RETURN g.id"; + assert_eq!(trail(query).await, vec![vec![1], vec![1], vec![3], vec![3]]); + } + + #[tokio::test] + async fn catalog_without_row_ids_preserves_edge_identity_across_filters_and_directions() { + use datafusion::prelude::SessionContext; + let ctx = SessionContext::new(); + ctx.register_batch("n", ints(&[("id", vec![1, 2])])) + .unwrap(); + ctx.register_batch( + "r", + ints(&[ + ("src", vec![1, 1]), + ("dst", vec![2, 2]), + ("color", vec![0, 1]), + ]), + ) + .unwrap(); + let cfg = GraphConfig::builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + .unwrap(); + for (steps, expected) in [ + ("-[:R*1..1 {color:0}]->(:N)<-[:R {color:1}]-", 1), + ("-[:R*1..1 {color:0}]-(:N)<-[:R {color:0}]-", 0), + ("-[:R*1..1 {color:0}]->(:N)-[:R]-", 1), + ] { + let q = format!("MATCH (:N {{id:1}}){steps}(x:N) RETURN x.id"); + let rows = crate::CypherQuery::new(&q) + .unwrap() + .with_config(cfg.clone()) + .execute_with_context(ctx.clone()) + .await + .unwrap(); + assert_eq!(rows.num_rows(), expected, "{q}"); + } + } + + #[tokio::test] + async fn residual_shapes_use_separate_expansions() { + // A relationship variable on a segment. + let named = "MATCH (:N {id: 1})-[:R*1..2]-(f:N)-[r:R]-(g:N) RETURN f.id, g.id"; + // Without the CSR, 10 × 10 segment lengths exceed the joins' branch limit. + let long = "MATCH (:N {id: 1})-[:R*1..10]-(f:N)-[:R*1..10]-(g:N) RETURN f.id, g.id"; + for use_csr in [false, true] { + let engine = engine(use_csr).await; + for (query, shared) in [(named, false), (long, use_csr)] { + let plan = engine.explain(query, HashMap::new()).await.unwrap(); + assert!(!plan.contains("PathMatchExec"), "{query}: {plan}"); + assert_eq!(plan.contains("TrailWalkExec"), shared, "{query}: {plan}"); + let expected = if shared { + vec![vec![2, 1], vec![2, 1], vec![2, 3], vec![2, 3]] + } else { + // Separate MATCH clauses give each segment its own edge history. + rows(&engine, &query.replace("(f:N)-", "(f:N) MATCH (f)-")).await + }; + assert_eq!(rows(&engine, query).await, expected, "{query}"); + } + } + } +} diff --git a/crates/lance-csr/src/datafusion_planner/builder/trail_joins.rs b/crates/lance-csr/src/datafusion_planner/builder/trail_joins.rs new file mode 100644 index 00000000..9561229c --- /dev/null +++ b/crates/lance-csr/src/datafusion_planner/builder/trail_joins.rs @@ -0,0 +1,447 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The lance-csr Authors + +//! Relational fallback for variable-length segments: one variable-length relationship, or a +//! chain of segments that must not share an edge, unrolled into one branch of joins per +//! combination of hop sequences. The stored endpoints and an occurrence number among +//! parallel edges distinguish a hop from earlier hops of the same type. + +use crate::ast::{PropertyValue, RelationshipDirection}; +use crate::case_insensitive::qualify_column; +use crate::datafusion_planner::analysis::RelationshipInstance; +use crate::datafusion_planner::join_ops::{SourceJoinParams, TargetJoinParams}; +use crate::datafusion_planner::scan_ops::TrailIdentity; +use crate::datafusion_planner::DataFusionPlanner; +use crate::error::{GraphError, Result}; +use crate::pattern_alternatives::{segment_sequences, Enumerated, TrailStep}; +use datafusion::common::Column; +use datafusion::logical_expr::{col, lit, Expr, LogicalPlan, LogicalPlanBuilder}; +use std::collections::HashMap; + +/// One segment of a pattern planned as a single trail: its relationships, hop range and +/// the boundary node at its end. +pub(super) struct ChainSegment<'a> { + pub types: &'a [String], + pub direction: &'a RelationshipDirection, + pub range: [u32; 2], + pub properties: &'a HashMap, + pub end: &'a str, + pub end_label: &'a str, +} + +use crate::pattern_alternatives::MAX_BRANCHES as MAX_CHAIN_BRANCHES; + +fn rank_column(alias: &str) -> String { + format!("#trail rank {alias}") +} + +impl DataFusionPlanner { + fn missing_table(&self, name: &str) -> GraphError { + GraphError::ConfigError { + message: format!("No mapping or table source found for '{name}'"), + location: snafu::Location::new(file!(), line!(), column!()), + } + } + + /// One join branch per combination of hop sequences. Every hop in a branch + /// shares its type's edge history. An oversized multi-segment pattern falls back + /// to ordinary expansions, whose individual joins keep their own history. + pub(super) fn build_trail_chain( + &self, + input: &LogicalPlan, + [start, start_label]: [&str; 2], + segments: &[ChainSegment], + end_properties: &HashMap, + ) -> Result> { + let single = segments.len() == 1; + let mut options = Vec::with_capacity(segments.len()); + let mut from = start_label; + let mut branches = 1; + for segment in segments { + // A single-segment alternation counts only positive lengths toward its cap. + let identity = + single && segment.range[0] == 0 && from.eq_ignore_ascii_case(segment.end_label); + let enumerated = segment_sequences( + &self.config, + segment.types, + segment.direction, + segment.range, + [&[from], &[segment.end_label]], + MAX_CHAIN_BRANCHES / branches + usize::from(identity), + single, + )?; + let sequences = match enumerated { + Enumerated::Found(sequences) => sequences, + Enumerated::OverBudget if single => return Err(crate::pattern_alternatives::too_many()), + Enumerated::Unlabeled(kind) if single => return Err(GraphError::PlanError { + message: format!("relationship type '{kind}' needs endpoint labels for alternation in a variable-length pattern"), + location: snafu::Location::new(file!(), line!(), column!()), + }), + _ => return Ok(None), + }; + if sequences.is_empty() { + if single + && segment.types.len() > 1 + && segment.range[0] > 0 + && *segment.direction != RelationshipDirection::Undirected + { + return Err(GraphError::PlanError { + message: "no sequence of relationship types in the variable-length pattern chains its endpoint labels".into(), + location: snafu::Location::new(file!(), line!(), column!()), + }); + } + return self.trail_no_match(input, start, segments).map(Some); + } + branches *= sequences.len(); + options.push(sequences); + from = segment.end_label; + } + // Internal columns are projected away before the union, but must not collide + // with incoming columns or boundary variables meanwhile. + let names: Vec = segments.iter().map(|s| s.end.to_lowercase()).collect(); + let prefix = (0..) + .map(|n| format!("_trail{n}_chain_")) + .find(|name| { + !names.iter().any(|v| v.starts_with(name.as_str())) + && !input.schema().fields().iter().any(|f| { + f.name().starts_with(name.as_str()) + || f.name().starts_with(&rank_column(name)) + }) + }) + .expect("an unused prefix"); + let projection = self.chain_projection(input, start, segments)?; + let no_properties = HashMap::new(); + let mut choice = vec![0_usize; segments.len()]; + let mut plans = Vec::with_capacity(branches); + loop { + let seqs: Vec<&Vec> = options + .iter() + .zip(&choice) + .map(|(sequences, &i)| &sequences[i]) + .collect(); + let mut counts = HashMap::::new(); + for step in seqs.iter().flat_map(|seq| seq.iter()) { + *counts.entry(step.kind.to_lowercase()).or_default() += 1; + } + let mut plan = input.clone(); + let mut previous = start.to_string(); + let mut from = start_label; + let mut walked = HashMap::>::new(); + let mut hop = 0_usize; + for (s, (segment, seq)) in segments.iter().zip(&seqs).enumerate() { + let end_properties = if s + 1 == segments.len() { + end_properties + } else { + &no_properties + }; + if seq.is_empty() { + plan = self.trail_identity( + plan, + [&previous, segment.end], + segment.end_label, + end_properties, + )?; + } + for (i, step) in seq.iter().enumerate() { + let last = i + 1 == seq.len(); + let next = if last { + segment.end.to_string() + } else { + format!("{prefix}n{hop}") + }; + let kind = step.kind.to_lowercase(); + let repeated = counts.get(&kind).is_some_and(|&n| n > 1); + let history = repeated.then(|| walked.entry(kind).or_default()); + let instance = RelationshipInstance { + id: hop + 1, + rel_type: step.kind.clone(), + source_var: previous.clone(), + target_var: next.clone(), + direction: step.direction.clone(), + alias: format!("{prefix}r{hop}"), + }; + plan = self.build_trail_hop( + plan, + [&previous, &next], + [from, &step.to], + &instance, + segments, + segment.properties, + if last { end_properties } else { &no_properties }, + history, + )?; + previous = next; + from = &step.to; + hop += 1; + } + previous = segment.end.to_string(); + from = segment.end_label; + } + plans.push( + LogicalPlanBuilder::from(plan) + .project(projection.clone()) + .and_then(|b| b.build()) + .map_err(|e| self.plan_error("Failed to project a trail branch", e))?, + ); + // The next combination of segment lengths, last segment fastest. + let Some(s) = (0..choice.len()) + .rev() + .find(|&s| choice[s] + 1 < options[s].len()) + else { + break; + }; + choice[s] += 1; + choice[s + 1..].iter_mut().for_each(|c| *c = 0); + } + if plans.len() == 1 { + return Ok(plans.pop()); + } + // A flat union keeps the optimizer's recursion depth independent of the branch count. + let union = datafusion::logical_expr::Union::try_new_with_loose_types( + plans.into_iter().map(std::sync::Arc::new).collect(), + ) + .map_err(|e| self.plan_error("Failed to union trail branches", e))?; + Ok(Some(LogicalPlan::Union(union))) + } + + /// No rows, with the normal boundary columns, when a segment cannot reach its end label. + fn trail_no_match( + &self, + input: &LogicalPlan, + start: &str, + segments: &[ChainSegment], + ) -> Result { + let mut builder = LogicalPlanBuilder::from(input.clone()); + for segment in segments { + let map = self + .config + .get_node_mapping(segment.end_label) + .ok_or_else(|| self.missing_table(segment.end_label))?; + let key = qualify_column(segment.end, &map.id_field); + if builder.schema().field_with_unqualified_name(&key).is_ok() { + continue; + } + let source = self + .get_catalog()? + .node_source(segment.end_label) + .ok_or_else(|| self.missing_table(segment.end_label))?; + let scan = + self.build_target_scan(source, segment.end_label, segment.end, &HashMap::new())?; + builder = builder + .join_on( + scan, + datafusion::logical_expr::JoinType::Inner, + [lit(false)], + ) + .map_err(|e| self.plan_error("Failed to join path endpoints", e))?; + } + let projection = self.chain_projection(input, start, segments)?; + builder + .filter(lit(false)) + .and_then(|b| b.project(projection)) + .and_then(|b| b.build()) + .map_err(|e| self.plan_error("Failed to build path endpoints", e)) + } + + /// `input`'s columns, then the node columns of each boundary not already bound. + fn chain_projection( + &self, + input: &LogicalPlan, + start: &str, + segments: &[ChainSegment], + ) -> Result> { + let mut projection: Vec = input + .schema() + .iter() + .map(|(qualifier, field)| Expr::Column(Column::from((qualifier, field.as_ref())))) + .collect(); + let mut seen = vec![start.to_lowercase()]; + for segment in segments { + let end = segment.end.to_lowercase(); + if seen.contains(&end) { + continue; + } + seen.push(end); + let map = self + .config + .get_node_mapping(segment.end_label) + .ok_or_else(|| self.missing_table(segment.end_label))?; + if input + .schema() + .field_with_unqualified_name(&qualify_column(segment.end, &map.id_field)) + .is_ok() + { + continue; + } + let source = self + .get_catalog()? + .node_source(segment.end_label) + .ok_or_else(|| self.missing_table(segment.end_label))?; + projection.extend(source.schema().fields().iter().map(|f| { + Expr::Column(Column::new_unqualified(qualify_column( + segment.end, + f.name(), + ))) + })); + } + Ok(projection) + } + + /// A zero-length segment: its end is the node it starts from. `properties` filter the + /// end when it is joined here, as a target join does; a bound end cannot take them. + fn trail_identity( + &self, + plan: LogicalPlan, + [previous, end]: [&str; 2], + label: &str, + properties: &HashMap, + ) -> Result { + let map = self + .config + .get_node_mapping(label) + .ok_or_else(|| self.missing_table(label))?; + let (from, to) = ( + qualify_column(previous, &map.id_field), + qualify_column(end, &map.id_field), + ); + let builder = LogicalPlanBuilder::from(plan); + let bound = previous.eq_ignore_ascii_case(end) + || builder.schema().field_with_unqualified_name(&to).is_ok(); + if bound && !properties.is_empty() { + return Err(GraphError::PlanError { + message: format!( + "Property filters on reused variable '{end}' are not yet supported" + ), + location: snafu::Location::new(file!(), line!(), column!()), + }); + } + if previous.eq_ignore_ascii_case(end) { + return builder + .build() + .map_err(|e| self.plan_error("Failed to bind a zero-length segment", e)); + } + let builder = if bound { + builder.filter(col(Column::new_unqualified(from)).eq(col(Column::new_unqualified(to)))) + } else { + let source = self + .get_catalog()? + .node_source(label) + .ok_or_else(|| self.missing_table(label))?; + let scan = self.build_target_scan(source, label, end, properties)?; + builder.join( + scan, + datafusion::logical_expr::JoinType::Inner, + (vec![from], vec![to]), + None, + ) + }; + builder + .and_then(|b| b.build()) + .map_err(|e| self.plan_error("Failed to bind a zero-length segment", e)) + } + + /// One hop of a path of several hops, joined to its relationship scan. Cypher never + /// walks an edge twice in a path, so rows where this hop walked an edge an earlier hop + /// (`walked`) walked are removed, before the target join. + #[allow(clippy::too_many_arguments)] + fn build_trail_hop( + &self, + left_plan: LogicalPlan, + [source_variable, target_variable]: [&str; 2], + [source_label, target_label]: [&str; 2], + instance: &RelationshipInstance, + segments: &[ChainSegment], + relationship_properties: &HashMap, + target_properties: &HashMap, + walked: Option<&mut Vec>, + ) -> Result { + let direction = &instance.direction; + let rel_map = self.get_relationship_mapping(&instance.rel_type)?; + let cat = self.get_catalog()?; + let identity_source = if walked.is_some() { + cat.relationship_occurrence_source(&instance.rel_type)? + } else { + None + }; + let (rel_source, stored) = match identity_source { + Some((source, id)) => (source, Some(id)), + None => ( + cat.relationship_source(&instance.rel_type) + .ok_or_else(|| self.missing_table(&instance.rel_type))?, + None, + ), + }; + let node_mapping = |label: &str| { + self.config + .get_node_mapping(label) + .ok_or_else(|| self.missing_table(label)) + }; + let source_map = node_mapping(source_label)?; + let target_map = node_mapping(target_label)?; + let rank = walked.as_ref().map(|_| rank_column(&instance.alias)); + let rel_scan = self.build_relationship_scan( + instance, + rel_source, + relationship_properties, + rel_map, + direction, + rank.as_deref().map(|output| TrailIdentity { + output, + stored: stored.as_deref(), + filter_fields: if stored.is_none() { + let mut names: Vec = segments + .iter() + .filter(|s| { + s.types + .iter() + .any(|t| t.eq_ignore_ascii_case(&instance.rel_type)) + }) + .flat_map(|s| s.properties.keys().map(|k| k.to_ascii_lowercase())) + .collect(); + names.sort_unstable(); + names.dedup(); + names + } else { + Vec::new() + }, + }), + )?; + let mut builder = self.join_source_to_relationship( + left_plan, + rel_scan, + &SourceJoinParams { + source_variable, + rel_qualifier: &instance.alias, + node_id_field: &source_map.id_field, + rel_map, + direction, + }, + )?; + if let Some(walked) = walked { + let edge = col(Column::new_unqualified(rank_column(&instance.alias))); + if let Some(repeated) = walked + .iter() + .map(|prior| edge.clone().eq(prior.clone())) + .reduce(Expr::or) + { + builder = builder + .filter(!repeated) + .map_err(|e| self.plan_error("Failed to filter repeated relationships", e))?; + } + walked.push(edge); + } + self.join_relationship_to_target( + builder, + cat, + &TargetJoinParams { + target_variable, + target_label, + rel_qualifier: &instance.alias, + node_map: target_map, + rel_map, + direction, + target_properties, + }, + ) + } +} diff --git a/crates/lance-csr/src/datafusion_planner/mod.rs b/crates/lance-csr/src/datafusion_planner/mod.rs index bfbb5107..535bb96d 100644 --- a/crates/lance-csr/src/datafusion_planner/mod.rs +++ b/crates/lance-csr/src/datafusion_planner/mod.rs @@ -111,6 +111,30 @@ mod tests { use crate::logical_plan::LogicalOperator; use test_fixtures::{make_catalog, person_config, person_knows_config, person_scan}; + #[test] + fn catalog_without_stored_edge_ids_numbers_parallel_edges() { + let planner = DataFusionPlanner::with_catalog(person_knows_config(), make_catalog()); + let expand = LogicalOperator::VariableLengthExpand { + input: Box::new(person_scan("a")), + source_variable: "a".into(), + target_variable: "b".into(), + target_label: "Person".into(), + relationship_types: vec!["KNOWS".into()], + direction: RelationshipDirection::Undirected, + relationship_variable: None, + min_length: Some(2), + max_length: Some(2), + properties: Default::default(), + target_properties: Default::default(), + }; + let plan = planner.plan(&expand).unwrap(); + assert!(plan + .display_indent() + .to_string() + .to_lowercase() + .contains("row_number")); + } + #[test] fn test_filter_preserves_error_context() { // Test that filter errors include helpful context diff --git a/crates/lance-csr/src/datafusion_planner/scan_ops.rs b/crates/lance-csr/src/datafusion_planner/scan_ops.rs index 271d471d..b0c1564c 100644 --- a/crates/lance-csr/src/datafusion_planner/scan_ops.rs +++ b/crates/lance-csr/src/datafusion_planner/scan_ops.rs @@ -11,10 +11,20 @@ use crate::case_insensitive::qualify_column; use crate::config::RelationshipMapping; use crate::error::Result; use datafusion::common::Column; -use datafusion::logical_expr::{col, BinaryExpr, Expr, LogicalPlan, LogicalPlanBuilder, Operator}; +use datafusion::functions_window::expr_fn::row_number; +use datafusion::logical_expr::{ + col, BinaryExpr, Expr, ExprFunctionExt, LogicalPlan, LogicalPlanBuilder, Operator, +}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; +/// An internal output column identifying the edge walked by this hop. +pub(super) struct TrailIdentity<'a> { + pub output: &'a str, + pub stored: Option<&'a str>, + pub filter_fields: Vec, +} + /// Bind a property filter to its physical field spelling before scan aliasing. pub(super) fn source_column(schema: &arrow_schema::Schema, name: &str) -> Expr { let physical = schema @@ -120,14 +130,18 @@ impl DataFusionPlanner { .map_err(|e| self.plan_error("Failed to build scan plan", e)) } - /// Build a qualified relationship scan with property filters - pub(crate) fn build_relationship_scan( + /// Build a qualified relationship scan with property filters. + /// + /// Carry the stored occurrence through filtering and reversal. A custom provider + /// without addresses numbers rows within the original, directed endpoint pair. + pub(super) fn build_relationship_scan( &self, rel_instance: &RelationshipInstance, rel_source: Arc, relationship_properties: &HashMap, rel_map: &RelationshipMapping, direction: &RelationshipDirection, + identity: Option>, ) -> Result { let rel_schema = rel_source.schema(); let normalized_rel_type = rel_instance.rel_type.to_lowercase(); @@ -139,6 +153,54 @@ impl DataFusionPlanner { ) })?; + let occurrence = match &identity { + Some(id) if id.stored.is_none() => { + let name = (0..) + .map(|i| format!("#trail occurrence {i}")) + .find(|name| rel_schema.field_with_name(name).is_err()) + .expect("an unused occurrence column"); + let (src, dst) = Self::endpoint_columns(&rel_schema, rel_map)?; + let (src, dst) = ( + source_column(&rel_schema, &src), + source_column(&rel_schema, &dst), + ); + // Equal keys are interchangeable only when all these hops' predicates + // treat the rows alike. Give both scans the same order before filtering. + let mut number = row_number().partition_by(vec![src.clone(), dst.clone()]); + if !id.filter_fields.is_empty() { + let order = id + .filter_fields + .iter() + .map(|f| source_column(&rel_schema, f).sort(true, false)) + .collect(); + number = number.order_by(order); + } + let rank = number + .build() + .map_err(|e| self.plan_error("Failed to number parallel edges", e))? + .alias(&name); + let mut fields: Vec = rel_schema + .fields() + .iter() + .map(|f| source_column(&rel_schema, f.name())) + .collect(); + let key = datafusion::functions::core::expr_fn::named_struct(vec![ + datafusion::logical_expr::lit("src"), + src, + datafusion::logical_expr::lit("dst"), + dst, + datafusion::logical_expr::lit("ordinal"), + col(Column::new_unqualified(&name)), + ]); + fields.push(key.alias(&name)); + rel_builder = rel_builder + .window(vec![rank]) + .and_then(|b| b.project(fields)) + .map_err(|e| self.plan_error("Failed to identify parallel edges", e))?; + Some(name) + } + _ => None, + }; // Apply relationship property filters (e.g., -[r {since: 2020}]->) for (k, v) in relationship_properties.iter() { let lit_expr = @@ -156,25 +218,54 @@ impl DataFusionPlanner { })?; } - rel_builder = self.with_reversed_edges(rel_builder, &rel_schema, rel_map, direction)?; + let scan_schema = rel_builder.schema().inner().clone(); + rel_builder = self.with_reversed_edges(rel_builder, &scan_schema, rel_map, direction)?; // Use unique alias from rel_instance to avoid column conflicts - let rel_qualified_exprs: Vec = rel_schema + let rel_qualified_exprs: Vec = scan_schema .fields() .iter() .map(|field| { + if let Some(id) = &identity { + if id.stored.or(occurrence.as_deref()) == Some(field.name().as_str()) { + return col(Column::new_unqualified(field.name())).alias(id.output); + } + } let qualified_name = qualify_column(&rel_instance.alias, field.name()); col(Column::new_unqualified(field.name())).alias(&qualified_name) }) .collect(); - rel_builder + rel_builder = rel_builder .project(rel_qualified_exprs) - .map_err(|e| self.plan_error("Failed to project relationship columns", e))? + .map_err(|e| self.plan_error("Failed to project relationship columns", e))?; + rel_builder .build() .map_err(|e| self.plan_error("Failed to build relationship scan", e)) } + /// The physical names of a relationship's source and target id columns. + fn endpoint_columns( + rel_schema: &arrow_schema::SchemaRef, + rel_map: &RelationshipMapping, + ) -> Result<(String, String)> { + let field = |name: &str| { + rel_schema + .fields() + .iter() + .find(|f| f.name().eq_ignore_ascii_case(name)) + .map(|f| f.name().clone()) + .ok_or_else(|| crate::error::GraphError::PlanError { + message: format!("Relationship column '{}' not found", name), + location: snafu::Location::new(file!(), line!(), column!()), + }) + }; + Ok(( + field(&rel_map.source_id_field)?, + field(&rel_map.target_id_field)?, + )) + } + /// For an undirected pattern, append a reversed copy of every edge (source and /// target swapped) to the relationship scan. The joins then treat an undirected /// pattern exactly like an outgoing one, and each edge matches from both ends, @@ -191,21 +282,7 @@ impl DataFusionPlanner { if *direction != RelationshipDirection::Undirected { return Ok(builder); } - let field = |name: &str| { - rel_schema - .fields() - .iter() - .find(|f| f.name().eq_ignore_ascii_case(name)) - .map(|f| f.name().clone()) - .ok_or_else(|| crate::error::GraphError::PlanError { - message: format!("Relationship column '{}' not found", name), - location: snafu::Location::new(file!(), line!(), column!()), - }) - }; - let (src, dst) = ( - field(&rel_map.source_id_field)?, - field(&rel_map.target_id_field)?, - ); + let (src, dst) = Self::endpoint_columns(rel_schema, rel_map)?; let swapped: Vec = rel_schema .fields() .iter() diff --git a/crates/lance-csr/src/engine.rs b/crates/lance-csr/src/engine.rs index 5854214a..6beaf0b3 100644 --- a/crates/lance-csr/src/engine.rs +++ b/crates/lance-csr/src/engine.rs @@ -112,6 +112,59 @@ impl EngineSource { }) } + /// Like [`Self::table_provider`], plus one `UInt64` column identifying each stored row, + /// returned with its name. Built only on request. + /// + /// Lance: the physical `_rowaddr` (unique per live row, fixed for the pinned version). + /// Arrow: the original row ordinal, assigned before `memtable_partitions` slices the + /// batch, under a hidden name that no user column uses. + pub(crate) fn occurrence_table_provider( + &self, + name: &str, + ) -> Result<(Arc, String)> { + match self { + Self::Lance { dataset, .. } => Ok(( + Arc::new(LanceTableProvider::new(dataset.clone(), false, true)), + "_rowaddr".to_string(), + )), + Self::Arrow(batch) => { + let schema = batch.schema(); + let mut column = "__lance_csr_edge_ordinal".to_string(); + while schema + .fields() + .iter() + .any(|f| f.name().eq_ignore_ascii_case(&column)) + { + column.push('_'); + } + let mut fields: Vec = + schema.fields().iter().cloned().collect(); + fields.push(Arc::new(arrow_schema::Field::new( + &column, + arrow_schema::DataType::UInt64, + false, + ))); + let mut columns = batch.columns().to_vec(); + columns.push(Arc::new(arrow_array::UInt64Array::from_iter_values( + 0..batch.num_rows() as u64, + ))); + let numbered = RecordBatch::try_new( + Arc::new(arrow_schema::Schema::new_with_metadata( + fields, + schema.metadata().clone(), + )), + columns, + ) + .map_err(|e| exec_error(format!("Failed to number edges of {}: {}", name, e)))?; + let table = MemTable::try_new(numbered.schema(), memtable_partitions(&numbered)) + .map_err(|e| { + exec_error(format!("Failed to create MemTable for {}: {}", name, e)) + })?; + Ok((Arc::new(table), column)) + } + } + } + /// Pinned Lance version, or `None` for Arrow input. pub fn lance_version(&self) -> Option { match self { @@ -705,6 +758,10 @@ async fn build_engine_state( let mut catalog = InMemoryCatalog::new(); for (name, provider) in providers { + let engine_source = config + .get_relationship_mapping(&name) + .and_then(|_| sources.get(&name)) + .cloned(); // Re-register with join-key statistics, so plans see them; see `key_statistics`. let provider: Arc = match key_stats.get(&name) { Some(entry) => Arc::new(KeyStatisticsProvider::new(provider, entry.distinct.clone())), @@ -721,6 +778,13 @@ async fn build_engine_state( catalog = catalog .with_node_source(&name, table_source.clone()) .with_relationship_source(&name, table_source); + if let Some(source) = engine_source { + catalog = catalog.with_relationship_engine_source( + &name, + source, + key_stats.get(&name).map(|entry| entry.distinct.clone()), + ); + } } Ok(EngineState { sources, @@ -1021,8 +1085,24 @@ async fn build_csr_entries( let started = std::time::Instant::now(); // Two projected scans of the endpoint columns, one per direction. let scan = || source.edge_stream(src.name(), dst.name()); - let outgoing = Adjacency::build(scan().await?, src.name(), dst.name()).await?; - let incoming = Adjacency::build(scan().await?, dst.name(), src.name()).await?; + let address_column = match source { + EngineSource::Lance { .. } => Some("_rowaddr"), + EngineSource::Arrow(_) => None, + }; + let outgoing = Adjacency::build_with_address_column( + scan().await?, + src.name(), + dst.name(), + address_column, + ) + .await?; + let incoming = Adjacency::build_with_address_column( + scan().await?, + dst.name(), + src.name(), + address_column, + ) + .await?; let build_ms = started.elapsed().as_secs_f64() * 1e3; let mut store_error = None; if let (PersistCsr::LoadAndStore, EngineSource::Lance { dataset, .. }) = diff --git a/crates/lance-csr/src/logical_plan.rs b/crates/lance-csr/src/logical_plan.rs index a1391ebb..c264a564 100644 --- a/crates/lance-csr/src/logical_plan.rs +++ b/crates/lance-csr/src/logical_plan.rs @@ -315,16 +315,90 @@ impl<'a> LogicalPlanner<'a> { self } - fn retain_variable_alternation(&self, patterns: &[GraphPattern]) -> bool { + /// Decide at graph planning time so a residual shape keeps its ordinary expansions, + /// with the same relationship aliases, projections and input scope as any other MATCH. + fn can_plan_shared_trail(&self, path: &PathPattern) -> bool { + use crate::csr_expand::{TrailWalk, WalkSegmentSpec}; + use crate::pattern_alternatives::{segment_sequences, Enumerated, MAX_BRANCHES}; + + if self.wildcard_relationships || !path.needs_trail_across_segments() { + return false; + } + let label = |node: &NodePattern| { + let label = node + .variable + .as_ref() + .and_then(|v| self.variables.get(v)) + .or_else(|| (node.labels.len() == 1).then(|| &node.labels[0]))?; + self.config + .get_node_mapping(label) + .map(|mapping| mapping.label.as_str()) + }; + let Some(start) = label(&path.start_node) else { + return false; + }; + let mut specs = Vec::with_capacity(path.segments.len()); + for segment in &path.segments { + let rel = &segment.relationship; + let Some(end_label) = label(&segment.end_node) else { + return false; + }; + if rel.variable.is_some() || rel.types.is_empty() { + return false; + } + let [min, max] = rel.hop_range(); + if min > max || max > crate::MAX_VARIABLE_LENGTH_HOPS { + return false; + } + specs.push(WalkSegmentSpec { + types: &rel.types, + direction: &rel.direction, + end_label, + min, + max, + tie: None, + }); + } + // Check actual typed sequences: a long heterogeneous range can still have only one branch. + let mut budget = MAX_BRANCHES; + let mut from = start; + for spec in &specs { + match segment_sequences( + self.config, + spec.types, + spec.direction, + [spec.min, spec.max], + [&[from], &[spec.end_label]], + budget, + false, + ) { + Ok(Enumerated::Found(sequences)) if sequences.is_empty() => return true, + Ok(Enumerated::Found(sequences)) => budget /= sequences.len(), + _ => { + return self.adjacency.is_some_and(|catalog| { + path.segments + .iter() + .all(|s| s.relationship.properties.is_empty()) + && TrailWalk::new(self.config, catalog, start, &specs).is_some() + }) + } + } + from = spec.end_label; + } + true + } + + fn retain_variable_alternation( + &self, + patterns: &[GraphPattern], + bounded_undirected: bool, + ) -> bool { if patterns .iter() .all(|p| matches!(p, GraphPattern::Path(path) if path.variable.is_some())) { return true; } - let Some(catalog) = self.adjacency else { - return false; - }; let labels = |n: &NodePattern| -> Vec { n.variable .as_ref() @@ -348,34 +422,46 @@ impl<'a> LogicalPlanner<'a> { return true; } if rel.variable.is_some() - || !rel.properties.is_empty() - || rel.direction == RelationshipDirection::Undirected + || (rel.direction == RelationshipDirection::Undirected + && (!bounded_undirected || !rel.properties.is_empty())) || (range.min == Some(1) && range.max == Some(1)) { return false; } let (starts, ends) = (labels(start), labels(&segment.end_node)); - let (Some(start), Some(end)) = (starts.first(), ends.first()) else { + let (Some(first), Some(last)) = (starts.first(), ends.first()) else { return false; }; - if starts - .iter() - .chain(&ends) - .any(|l| catalog.nodes(l).is_none()) - { - return false; - } - crate::csr_traversal::Traversal::new( - self.config, - catalog, - &rel.types, - &rel.direction, - start, - end, - 0, - 0, - ) - .is_some() + let [min, max] = rel.hop_range(); + let csr = max <= crate::MAX_VARIABLE_LENGTH_HOPS + && rel.properties.is_empty() + && self.adjacency.is_some_and(|catalog| { + starts + .iter() + .chain(&ends) + .all(|l| catalog.nodes(l).is_some()) + && crate::csr_traversal::Traversal::new( + self.config, + catalog, + &rel.types, + &rel.direction, + first, + last, + min, + max, + ) + .is_some() + }); + // Without the CSR walk, the planner joins the valid type sequences itself + // when both ends have one label (otherwise the unroller handles the segment). + csr || (rel.direction != RelationshipDirection::Undirected + && starts.len() == 1 + && ends.len() == 1 + && rel.types.iter().all(|t| { + self.config + .get_relationship_mapping(t) + .is_some_and(|m| m.source_label.is_some() && m.target_label.is_some()) + })) }) }) } @@ -923,9 +1009,41 @@ impl<'a> LogicalPlanner<'a> { ), ..match_clause.clone() }; - let inventory_alternation = match_clause.is_bounded_undirected_alternation(); + if let Some(branches) = crate::pattern_alternatives::trail_label_branches( + &inferred.patterns, + self.config, + &self.variables, + )? { + return self.plan_match_branches(base, branches, filter); + } + if let [GraphPattern::Path(path)] = inferred.patterns.as_slice() { + if path.needs_trail_across_segments() { + let last = &path.segments.last().expect("overlapping segments").end_node; + let bound = |n: &NodePattern| { + n.variable + .as_ref() + .is_some_and(|v| self.variables.contains_key(v)) + }; + let reverse = !bound(&path.start_node) + && (bound(last) + || crate::pattern_order::prefer_trail_end( + &path.start_node, + last, + filter, + self.config, + )); + let reversed = reverse.then(|| Self::reversed_path(path)); + let oriented = reversed.as_ref().unwrap_or(path); + if self.can_plan_shared_trail(oriented) { + return self.plan_inventory_path(base, oriented, None); + } + } + } + let bounded_undirected = match_clause.is_bounded_undirected_alternation(); let match_clause = &inferred; - let retain_variable = self.retain_variable_alternation(&match_clause.patterns); + let retain_variable = + self.retain_variable_alternation(&match_clause.patterns, bounded_undirected); + let inventory_alternation = bounded_undirected && !retain_variable; if !inventory_alternation && crate::pattern_alternatives::needs_expansion( &match_clause.patterns, @@ -1007,6 +1125,11 @@ impl<'a> LogicalPlanner<'a> { path.variable = Some(format!("_path_value_{}", self.variables.len())); plan = Some(self.plan_inventory_path(plan, &path, None)?); } + GraphPattern::Path(path) + if patterns.len() > 1 && self.can_plan_shared_trail(path) => + { + plan = Some(self.plan_inventory_path(plan, path, None)?); + } GraphPattern::Path(path) => plan = Some(self.plan_path(plan, path)?), } } @@ -1041,6 +1164,11 @@ impl<'a> LogicalPlanner<'a> { // Whether each variable seen in this clause was variable-length. let mut seen: HashMap = HashMap::new(); for rel in relationships(&mut patterns) { + if rel.length.is_some() && rel.types.len() > 1 { + let mut unique = HashSet::new(); + rel.types + .retain(|kind| unique.insert(kind.to_ascii_lowercase())); + } let Some(var) = rel.variable.as_ref() else { continue; }; @@ -1099,6 +1227,7 @@ impl<'a> LogicalPlanner<'a> { } // The path operator already keeps the edges of one path apart, by edge row. let path_operator = path.variable.is_some() + || (patterns.len() > 1 && self.can_plan_shared_trail(path)) || (self.rich_paths && path .segments diff --git a/crates/lance-csr/src/pattern_alternatives.rs b/crates/lance-csr/src/pattern_alternatives.rs index 8b2132f1..51bf755c 100644 --- a/crates/lance-csr/src/pattern_alternatives.rs +++ b/crates/lance-csr/src/pattern_alternatives.rs @@ -29,7 +29,7 @@ use crate::config::GraphConfig; use crate::error::{GraphError, Result}; /// Branch limit, so a pattern full of alternatives can't explode the plan. -const MAX_BRANCHES: usize = 64; +pub(crate) const MAX_BRANCHES: usize = 64; fn zero_hop(rel: &RelationshipPattern) -> bool { rel.length @@ -105,6 +105,14 @@ pub fn infer_labels( if rel.types.is_empty() { continue; } + // For directed alternation the label-pair planner also considers zero + // hops. A positive hop's endpoint cannot constrain those identity rows. + if rel.types.len() > 1 + && rel.direction != RelationshipDirection::Undirected + && rel.length.as_ref().is_some_and(|r| r.min == Some(0)) + { + continue; + } // (left side, right side) as written. let (left, right) = match rel.direction { RelationshipDirection::Outgoing => { @@ -404,6 +412,124 @@ pub fn expand( Ok(branches) } +/// Resolve ambiguous boundary labels before planning a directed variable-length segment. +/// Each label pair keeps one whole segment, including its relationship-uniqueness check. +pub(crate) fn trail_label_branches( + patterns: &[GraphPattern], + config: &GraphConfig, + bound: &HashMap, +) -> Result>>> { + let labels = |node: &NodePattern| { + if node.labels.is_empty() { + node.variable + .as_ref() + .and_then(|v| bound.get(v)) + .cloned() + .into_iter() + .collect() + } else { + node.labels.clone() + } + }; + for (p, pattern) in patterns.iter().enumerate() { + let GraphPattern::Path(path) = pattern else { + continue; + }; + for (i, segment) in path.segments.iter().enumerate() { + let rel = &segment.relationship; + let Some(range) = &rel.length else { + continue; + }; + if rel.types.len() < 2 + || rel.direction == RelationshipDirection::Undirected + || rel.variable.is_some() + || path.shortest.is_some() + { + continue; + } + let left = if i == 0 { + &path.start_node + } else { + &path.segments[i - 1].end_node + }; + let (starts, ends) = (labels(left), labels(&segment.end_node)); + if starts.len() == 1 && ends.len() == 1 { + continue; + } + let fits = |labels: &[String], name: &str| { + labels.is_empty() || labels.iter().any(|l| l.eq_ignore_ascii_case(name)) + }; + let mut steps = Vec::new(); + for kind in &rel.types { + let map = config.get_relationship_mapping(kind); + let Some((a, b)) = + map.and_then(|m| m.source_label.as_deref().zip(m.target_label.as_deref())) + else { + return Ok(None); // Let the unroller report the missing mapping. + }; + steps.push(if rel.direction == RelationshipDirection::Incoming { + (b, a) + } else { + (a, b) + }); + } + // Only the reachable label pairs matter here. Several type sequences for the + // same pair share one branch and one used-edge history during execution. + let mut frontier: std::collections::BTreeSet<_> = config + .iter_node_mappings() + .map(|(_, n)| n.label.as_str()) + .filter(|l| fits(&starts, l)) + .map(|l| (l, l)) + .collect(); + let mut pairs = std::collections::BTreeSet::new(); + let same_node = left.variable.is_some() && left.variable == segment.end_node.variable; + let max = range.max.unwrap_or(crate::MAX_VARIABLE_LENGTH_HOPS); + if max > crate::MAX_VARIABLE_LENGTH_HOPS { + return Ok(None); + } + for depth in 0..=max { + if depth >= range.min.unwrap_or(1) { + pairs.extend(frontier.iter().copied().filter(|(from, to)| { + fits(&ends, to) && (!same_node || from.eq_ignore_ascii_case(to)) + })); + } + if depth < max { + frontier = frontier + .iter() + .flat_map(|&(start, at)| { + steps + .iter() + .filter(move |(from, _)| at.eq_ignore_ascii_case(from)) + .map(move |&(_, to)| (start, to)) + }) + .collect(); + } + } + if pairs.len() > MAX_BRANCHES { + return Err(too_many()); + } + let mut branches = Vec::new(); + for (start, end) in pairs { + let mut path = path.clone(); + let left = if i == 0 { + &mut path.start_node + } else { + &mut path.segments[i - 1].end_node + }; + left.labels = vec![start.to_string()]; + path.segments[i].end_node.labels = vec![end.to_string()]; + let mut branch = patterns.to_vec(); + branch[p] = GraphPattern::Path(path); + branches.push(branch); + } + if !branches.is_empty() { + return Ok(Some(branches)); + } + } + } + Ok(None) +} + /// The first variable-length segment with several types, replaced by each fixed-length path /// it can match: per hop count in its range, every sequence of types whose endpoint labels /// chain from the segment's start node to its end node. `None` when there is no such @@ -428,28 +554,8 @@ fn unroll_variable_length_alternation( return Ok(None); }; let rel = &path.segments[i].relationship; - if rel.variable.is_some() || rel.direction == RelationshipDirection::Undirected { - return Err(unsupported( - "relationship-type alternation in an undirected or named variable-length pattern", - )); - } - let mut ends = Vec::with_capacity(rel.types.len()); - for t in &rel.types { - let m = config.get_relationship_mapping(t); - let (Some(src), Some(dst)) = ( - m.and_then(|m| m.source_label.clone()), - m.and_then(|m| m.target_label.clone()), - ) else { - return Err(plan_error(format!( - "relationship type '{t}' needs endpoint labels (GraphConfig rel_table's \ - from_table and to_table) for alternation in a variable-length pattern" - ))); - }; - // Labels in traversal order: the segment is read from its left node. - ends.push(match rel.direction { - RelationshipDirection::Incoming => (t.clone(), dst, src), - _ => (t.clone(), src, dst), - }); + if rel.variable.is_some() { + return Err(unsupported(UNSUPPORTED_ALTERNATION)); } let node_labels = |node: &NodePattern| -> Vec { match node.variable.as_ref().and_then(|v| bound.get(v)) { @@ -462,56 +568,19 @@ fn unroll_variable_length_alternation( } else { &path.segments[i - 1].end_node }; - let (starts, finishes) = (node_labels(left), node_labels(&path.segments[i].end_node)); - let fits = |labels: &[String], label: &str| { - labels.is_empty() || labels.iter().any(|l| l.eq_ignore_ascii_case(label)) - }; let range = rel .length .as_ref() .ok_or_else(|| GraphError::internal("a variable-length segment"))?; let min = range.min.unwrap_or(1); - let max = range.max.unwrap_or(crate::MAX_VARIABLE_LENGTH_HOPS); - if max > crate::MAX_VARIABLE_LENGTH_HOPS { - return Err(unsupported(&format!( - "variable-length paths longer than {} hops", - crate::MAX_VARIABLE_LENGTH_HOPS - ))); - } - // Depth-first over (type, label after the hop) sequences. - let mut sequences: Vec> = Vec::new(); - let mut stack: Vec> = vec![vec![]]; - while let Some(prefix) = stack.pop() { - let hops = prefix.len() as u32; - let at = prefix.last().map(|(_, label)| label.clone()); - if hops >= min && at.as_deref().is_some_and(|l| fits(&finishes, l)) { - sequences.push(prefix.clone()); - if sequences.len() > MAX_BRANCHES { - return Err(too_many()); - } - } - if hops == max { - continue; - } - for (t, from, to) in &ends { - let chains = match &at { - None => fits(&starts, from), - Some(label) => label.eq_ignore_ascii_case(from), - }; - if chains { - let mut next = prefix.clone(); - next.push((t.clone(), to.clone())); - stack.push(next); - } - } - } - if sequences.is_empty() && min != 0 { - return Err(plan_error( - "no sequence of relationship types in the variable-length pattern chains its \ - endpoint labels" - .into(), - )); - } + let sequences = alternation_sequences( + &rel.types, + &rel.direction, + range, + &node_labels(left), + &node_labels(&path.segments[i].end_node), + config, + )?; let mut variants = Vec::new(); if min == 0 { let mut identity = path.clone(); @@ -554,7 +623,193 @@ fn unroll_variable_length_alternation( Ok(Some(variants)) } -fn too_many() -> GraphError { +#[derive(Clone)] +pub(crate) struct TrailStep { + pub kind: String, + pub to: String, + pub direction: RelationshipDirection, +} + +/// Hop sequences, or why they were not enumerated. +pub(crate) enum Enumerated { + Found(Vec>), + /// More sequences than the budget allows. + OverBudget, + /// This relationship type has no endpoint labels to choose the types that may follow. + Unlabeled(String), +} + +/// Enumerate oriented sequences, keeping only prefixes which can reach a permitted +/// finish in the remaining hops. The cap applies to viable branches, including on +/// graphs where many type combinations lead to a dead end. +pub(crate) fn segment_sequences( + config: &GraphConfig, + types: &[String], + direction: &RelationshipDirection, + [min, max]: [u32; 2], + [starts, finishes]: [&[&str]; 2], + budget: usize, + allow_unmapped: bool, +) -> Result { + use RelationshipDirection::{Incoming, Outgoing, Undirected}; + let fits = |names: &[&str], label: &str| { + names.is_empty() || names.iter().any(|n| n.eq_ignore_ascii_case(label)) + }; + let mut steps = Vec::new(); + for kind in types { + let mapping = config + .get_relationship_mapping(kind) + .ok_or_else(|| plan_error(format!("No mapping found for relationship type: {kind}")))?; + let Some((src, dst)) = mapping + .source_label + .as_deref() + .zip(mapping.target_label.as_deref()) + else { + let (true, [_], [start], [end]) = (allow_unmapped, types, starts, finishes) else { + return Ok(Enumerated::Unlabeled(kind.clone())); + }; + // Without configured endpoints, intermediate nodes use the starting table. + let mut sequences = Vec::new(); + for depth in min..=max { + if depth == 0 && !start.eq_ignore_ascii_case(end) { + continue; + } + let step = TrailStep { + kind: kind.clone(), + to: (*start).into(), + direction: direction.clone(), + }; + let mut path = vec![step; depth as usize]; + if let Some(last) = path.last_mut() { + last.to = (*end).into(); + } + sequences.push(path); + } + return Ok(Enumerated::Found(sequences)); + }; + match direction { + Outgoing => steps.push((src, dst, kind, Outgoing)), + Incoming => steps.push((dst, src, kind, Incoming)), + Undirected if src.eq_ignore_ascii_case(dst) => steps.push((src, dst, kind, Undirected)), + Undirected => { + steps.push((src, dst, kind, Outgoing)); + steps.push((dst, src, kind, Incoming)); + } + } + } + let mut viable = vec![Vec::<&str>::new(); max as usize + 1]; + let accepts = |label: &str, depth: u32| depth >= min && fits(finishes, label); + for depth in (0..max as usize).rev() { + for &(from, to, _, _) in &steps { + if (accepts(to, depth as u32 + 1) + || viable[depth + 1] + .iter() + .any(|label| label.eq_ignore_ascii_case(to))) + && !viable[depth].contains(&from) + { + viable[depth].push(from); + } + } + } + let mut sequences = Vec::new(); + if min == 0 && starts.iter().any(|s| fits(finishes, s)) { + sequences.push(Vec::new()); + } + let mut pending: Vec> = vec![Vec::new()]; + while let Some(prefix) = pending.pop() { + let depth = prefix.len() as u32; + if let Some(last) = prefix.last() { + if accepts(&last.to, depth) { + if sequences.len() == budget { + return Ok(Enumerated::OverBudget); + } + sequences.push(prefix.clone()); + } + } + if depth == max { + continue; + } + for (from, to, kind, walk) in &steps { + let starts_here = prefix.last().map_or_else( + || fits(starts, from), + |last| last.to.eq_ignore_ascii_case(from), + ); + // Mapping labels are case-insensitive even when two tables were configured + // using different spellings of the same endpoint. + if starts_here + && (accepts(to, depth + 1) + || viable[depth as usize + 1] + .iter() + .any(|label| label.eq_ignore_ascii_case(to))) + { + let mut next = prefix.clone(); + next.push(TrailStep { + kind: (*kind).clone(), + to: (*to).into(), + direction: walk.clone(), + }); + pending.push(next); + } + } + } + Ok(Enumerated::Found(sequences)) +} + +const UNSUPPORTED_ALTERNATION: &str = + "relationship-type alternation in an undirected or named variable-length pattern"; + +/// The valid hop sequences of a directed variable-length segment with several types, as +/// (type, label reached) per hop in traversal order, from a node labelled one of `starts` +/// to one labelled one of `finishes` (any label when empty). Each type's endpoint labels +/// must chain from the label before it. Zero hops are not a sequence: callers add that +/// identity themselves. Every type needs endpoint labels, since they decide which types +/// may follow. +pub(crate) fn alternation_sequences( + types: &[String], + direction: &RelationshipDirection, + range: &crate::ast::LengthRange, + starts: &[String], + finishes: &[String], + config: &GraphConfig, +) -> Result>> { + if *direction == RelationshipDirection::Undirected { + return Err(unsupported(UNSUPPORTED_ALTERNATION)); + } + let min = range.min.unwrap_or(1); + let max = range.max.unwrap_or(crate::MAX_VARIABLE_LENGTH_HOPS); + if max > crate::MAX_VARIABLE_LENGTH_HOPS { + return Err(unsupported(&format!( + "variable-length paths longer than {} hops", + crate::MAX_VARIABLE_LENGTH_HOPS + ))); + } + let starts: Vec<_> = starts.iter().map(String::as_str).collect(); + let finishes: Vec<_> = finishes.iter().map(String::as_str).collect(); + let options = segment_sequences( + config, + types, + direction, + [min.max(1), max], + [&starts, &finishes], + MAX_BRANCHES, + false, + )?; + let sequences = match options { + Enumerated::Found(paths) => paths.into_iter().map(|steps| steps.into_iter().map(|s| (s.kind, s.to)).collect()).collect::>(), + Enumerated::OverBudget => return Err(too_many()), + Enumerated::Unlabeled(kind) => return Err(plan_error(format!("relationship type '{kind}' needs endpoint labels (GraphConfig rel_table's from_table and to_table) for alternation in a variable-length pattern"))), + }; + if sequences.is_empty() && min != 0 { + return Err(plan_error( + "no sequence of relationship types in the variable-length pattern chains its \ + endpoint labels" + .into(), + )); + } + Ok(sequences) +} + +pub(crate) fn too_many() -> GraphError { plan_error(format!( "pattern has more than {MAX_BRANCHES} combinations of relationship types and labels" )) diff --git a/crates/lance-csr/src/pattern_order.rs b/crates/lance-csr/src/pattern_order.rs index c8f8018e..94dc19cb 100644 --- a/crates/lance-csr/src/pattern_order.rs +++ b/crates/lance-csr/src/pattern_order.rs @@ -56,21 +56,7 @@ pub(crate) fn reorder_patterns( let mut scores: HashMap<&str, Selectivity> = HashMap::new(); for node in &graph.nodes { - let id_field = node - .labels - .first() - .and_then(|label| config.get_node_mapping(label)) - .map(|m| m.id_field.as_str()); - let inline = node.properties.keys().map(|property| match id_field { - Some(id) if id.eq_ignore_ascii_case(property) => Selectivity::IdEquality, - _ => Selectivity::Equality, - }); - let filtered = filter - .into_iter() - .flat_map(conjuncts) - .filter_map(|conjunct| score_conjunct(conjunct, name(node), id_field)); - let best = inline.chain(filtered).max().unwrap_or(Selectivity::None); - scores.insert(name(node), best); + scores.insert(name(node), node_selectivity(node, filter, config)); } // Ties keep the earliest node in the text, so equal scores never reorder. @@ -92,6 +78,37 @@ pub(crate) fn reorder_patterns( Some(graph.traverse_from(start)) } +fn node_selectivity( + node: &NodePattern, + filter: Option<&BooleanExpression>, + config: &GraphConfig, +) -> Selectivity { + let id = node + .labels + .first() + .and_then(|label| config.get_node_mapping(label)) + .map(|m| m.id_field.as_str()); + let inline = node.properties.keys().map(|key| match id { + Some(id) if id.eq_ignore_ascii_case(key) => Selectivity::IdEquality, + _ => Selectivity::Equality, + }); + let filtered = filter + .into_iter() + .flat_map(conjuncts) + .filter_map(|expr| score_conjunct(expr, node.variable.as_deref()?, id)); + inline.chain(filtered).max().unwrap_or(Selectivity::None) +} + +/// Compare the two ends of an undivided trail using the same predicate scores as fixed hops. +pub(crate) fn prefer_trail_end( + start: &NodePattern, + end: &NodePattern, + filter: Option<&BooleanExpression>, + config: &GraphConfig, +) -> bool { + node_selectivity(end, filter, config) > node_selectivity(start, filter, config) +} + /// A graph node's variable; [`PatternGraph`] names every node, anonymous ones included. fn name(node: &NodePattern) -> &str { node.variable diff --git a/crates/lance-csr/src/query.rs b/crates/lance-csr/src/query.rs index be31aae7..98bd1930 100644 --- a/crates/lance-csr/src/query.rs +++ b/crates/lance-csr/src/query.rs @@ -998,6 +998,17 @@ impl CypherQuery { catalog = catalog .with_node_source(name, table_source.clone()) .with_relationship_source(name, table_source); + if self + .require_config()? + .get_relationship_mapping(name) + .is_some() + { + catalog = catalog.with_relationship_engine_source( + name, + crate::engine::EngineSource::Arrow(normalized_batch), + None, + ); + } } Ok((catalog, ctx)) @@ -1049,7 +1060,7 @@ impl CypherQuery { .build(), )); let mut catalog = InMemoryCatalog::new(); - let mut providers: HashMap> = HashMap::new(); + let mut providers = HashMap::new(); for table_name in required_tables { let mut request = DescribeTableRequest::new(); @@ -1110,11 +1121,16 @@ impl CypherQuery { })?; // Store provider with normalized (lowercase) key for consistent lookup - providers.insert(normalized_table_name.clone(), provider); + let has_physical_address = !dataset + .schema() + .fields + .iter() + .any(|field| field.name.eq_ignore_ascii_case("_rowaddr")); + providers.insert(normalized_table_name, (provider, has_physical_address)); } for (label, _) in config.iter_node_mappings() { - let provider = providers + let (provider, _) = providers .get(label) .ok_or_else(|| GraphError::ConfigError { message: format!( @@ -1129,18 +1145,25 @@ impl CypherQuery { } for (rel_type, _) in config.iter_relationship_mappings() { - let provider = providers - .get(rel_type) - .ok_or_else(|| GraphError::ConfigError { - message: format!( - "Namespace did not resolve dataset for relationship type '{}'", - rel_type - ), - location: snafu::Location::new(file!(), line!(), column!()), - })?; + let (provider, has_physical_address) = + providers + .get(rel_type) + .ok_or_else(|| GraphError::ConfigError { + message: format!( + "Namespace did not resolve dataset for relationship type '{}'", + rel_type + ), + location: snafu::Location::new(file!(), line!(), column!()), + })?; let table_source = Arc::new(DefaultTableSource::new(provider.clone())); - catalog = catalog.with_relationship_source(rel_type, table_source); + catalog = catalog.with_relationship_source(rel_type, table_source.clone()); + if *has_physical_address { + catalog = catalog.with_relationship_occurrence_table( + rel_type, + (table_source, "_rowaddr".into()), + ); + } } Ok((catalog, ctx)) diff --git a/crates/lance-csr/src/shortest_path.rs b/crates/lance-csr/src/shortest_path.rs index 8e79f0ad..f46b01e8 100644 --- a/crates/lance-csr/src/shortest_path.rs +++ b/crates/lance-csr/src/shortest_path.rs @@ -403,7 +403,7 @@ async fn build_adjacency( let (edges, context) = (edges.clone(), context.clone()); async move { let stream = edges.execute(0, context)?; - Adjacency::build(stream, &from, &to) + Adjacency::build_with_address_column(stream, &from, &to, None) .await .map(Arc::new) .map_err(|e| datafusion::common::DataFusionError::External(Box::new(e))) diff --git a/crates/lance-csr/src/source_catalog.rs b/crates/lance-csr/src/source_catalog.rs index 1961d4a7..d22dcddc 100644 --- a/crates/lance-csr/src/source_catalog.rs +++ b/crates/lance-csr/src/source_catalog.rs @@ -4,21 +4,49 @@ //! Context-free source catalog for DataFusion logical planning. use std::collections::HashMap; -use std::sync::Arc; +use std::sync::{Arc, Mutex, PoisonError}; use arrow_schema::{Schema, SchemaRef}; +use datafusion::datasource::DefaultTableSource; use datafusion::logical_expr::TableSource; +use crate::engine::EngineSource; +use crate::error::Result; + +/// A relationship table with an extra occurrence ID column, and the name of that column. +pub type RelationshipOccurrenceTable = (Arc, String); + /// A minimal catalog to resolve node labels and relationship types to logical table sources. pub trait GraphSourceCatalog: Send + Sync { fn node_source(&self, label: &str) -> Option>; fn relationship_source(&self, rel_type: &str) -> Option>; + + /// An alternate source for `rel_type` with one extra `UInt64` column that identifies each + /// stored edge occurrence (unique and stable within the pinned snapshot), plus that + /// column's name. `None` (the default) means the catalog cannot supply one, and callers + /// fall back to numbering parallel edges with a window. + fn relationship_occurrence_source( + &self, + _rel_type: &str, + ) -> Result> { + Ok(None) + } +} + +/// A relationship's engine source, with its occurrence-id table built on first use. +enum OccurrenceSource { + Engine { + source: EngineSource, + distinct: Option>, + }, + Ready(RelationshipOccurrenceTable), } /// A simple in-memory catalog useful for tests and bootstrap wiring. pub struct InMemoryCatalog { node_sources: HashMap>, rel_sources: HashMap>, + occurrence_sources: HashMap>, } impl InMemoryCatalog { @@ -26,17 +54,55 @@ impl InMemoryCatalog { Self { node_sources: HashMap::new(), rel_sources: HashMap::new(), + occurrence_sources: HashMap::new(), } } + /// Retain the engine source behind a relationship so `relationship_occurrence_source` + /// can build its occurrence-id table lazily. Nothing is built here. + pub(crate) fn with_relationship_engine_source( + mut self, + rel_type: impl Into, + source: EngineSource, + distinct: Option>, + ) -> Self { + if matches!(&source, EngineSource::Lance { .. }) + && source + .schema() + .fields() + .iter() + .any(|f| f.name().eq_ignore_ascii_case("_rowaddr")) + { + return self; + } + self.occurrence_sources.insert( + rel_type.into().to_lowercase(), + Mutex::new(OccurrenceSource::Engine { source, distinct }), + ); + self + } + + /// A namespace Lance scan already exposes its snapshot-local physical row address. + pub(crate) fn with_relationship_occurrence_table( + mut self, + rel_type: &str, + table: RelationshipOccurrenceTable, + ) -> Self { + self.occurrence_sources.insert( + rel_type.to_lowercase(), + Mutex::new(OccurrenceSource::Ready(table)), + ); + self + } + pub fn with_node_source( mut self, label: impl Into, source: Arc, ) -> Self { // Normalize key to lowercase for case-insensitive lookup - self.node_sources - .insert(label.into().to_lowercase(), source); + let label = label.into().to_lowercase(); + self.node_sources.insert(label, source); self } @@ -46,8 +112,9 @@ impl InMemoryCatalog { source: Arc, ) -> Self { // Normalize key to lowercase for case-insensitive lookup - self.rel_sources - .insert(rel_type.into().to_lowercase(), source); + let key = rel_type.into().to_lowercase(); + self.occurrence_sources.remove(&key); + self.rel_sources.insert(key, source); self } } @@ -72,6 +139,35 @@ impl GraphSourceCatalog for InMemoryCatalog { fn relationship_source(&self, rel_type: &str) -> Option> { self.rel_sources.get(&rel_type.to_lowercase()).cloned() } + + /// Built once per relationship for this catalog (one pinned snapshot; `checkout_latest()` + /// builds a new catalog). The lock is held while building, so concurrent queries share one build. + fn relationship_occurrence_source( + &self, + rel_type: &str, + ) -> Result> { + let Some(entry) = self.occurrence_sources.get(&rel_type.to_lowercase()) else { + return Ok(None); + }; + let mut entry = entry.lock().unwrap_or_else(PoisonError::into_inner); + match &*entry { + OccurrenceSource::Ready(table) => Ok(Some(table.clone())), + OccurrenceSource::Engine { source, distinct } => { + let (provider, column) = source.occurrence_table_provider(rel_type)?; + let provider = match distinct { + Some(counts) => Arc::new(crate::key_statistics::KeyStatisticsProvider::new( + provider, + counts.clone(), + )), + None => provider, + }; + let table: RelationshipOccurrenceTable = + (Arc::new(DefaultTableSource::new(provider)), column); + *entry = OccurrenceSource::Ready(table.clone()); + Ok(Some(table)) + } + } + } } /// A trivial logical table source with a fixed schema. diff --git a/docs/csr.md b/docs/csr.md index 3956ff6f..c1c7f9b0 100644 --- a/docs/csr.md +++ b/docs/csr.md @@ -193,8 +193,8 @@ hops. A node's label and key travel together, so the same integer key in two lab The iterative path needs CSR indexes for every traversed type and direction, node indexes for every intermediate label, and resolved labels for the endpoints. Unsupported index shapes retain the join fallback. The 20-hop maximum still applies. `*0..` includes a zero-hop identity match when both labels and -keys agree. Undirected paths keep the existing rule that rejects immediate backtracking; neither execution -path enforces full relationship uniqueness on longer cycles. +keys agree. Each cursor records the relationship type and stored edge row used to reach it. +The walk skips an edge already on the current trail and can return to a node along a different edge. Traversal state grows with the hop limit, not the number of pending paths. Resident graph indexes, input batches, fetched target properties and downstream operators still contribute to query memory. Branching diff --git a/docs/cypher.md b/docs/cypher.md index 6c6d1e66..8120893b 100644 --- a/docs/cypher.md +++ b/docs/cypher.md @@ -367,7 +367,11 @@ RETURN length(p), nodes(p) alternative-branch bound still applies. - **Variable length** defaults to a minimum of 1 and a maximum of 20 hops; a maximum above 20 is rejected. `*0..` also matches the source itself, once per input row; `*0..0` matches only that identity. The start - and end must have the same label and key for a zero-hop match. Eligible CSR paths use one iterative + and end must have the same label and key for a zero-hop match. Each stored relationship can occur + once per variable-length segment, in either direction. A path can revisit a node using a different + relationship. For example, two parallel edges between nodes 1 and 2 give two distinct two-hop + trails from 1 back to 1. Earlier versions could drop these valid trails or count extra rows + by reusing an edge in a cycle. Eligible CSR paths use one iterative expansion for the whole range; the join fallback uses one branch per length. A property map on a variable-length relationship, such as `[:KNOWS*1..3 {since: 2020}]`, must hold for every relationship on the path; a zero-hop match has none to check. Such a path uses the join fallback. @@ -382,15 +386,23 @@ RETURN length(p), nodes(p) 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 - relationship can occur only once per trail, so parallel edges can yield repeated endpoints. + direction at each hop. Its endpoints need known labels and integer keys. This form also works in `OPTIONAL MATCH`. -- **Unnamed single-type undirected variable-length paths** skip immediate backtracking (`a-b-a`). - **Relationship uniqueness**: within one `MATCH`, two single-hop relationships of the same type never bind the same edge, whether they are named or anonymous, in one pattern or in comma-separated parts. `(a)-[:KNOWS]->(b)<-[:KNOWS]-(c)` therefore never matches `c = a`. Separate `MATCH` clauses may bind the same edge again. Edges are compared by their endpoints, so two parallel edges between the same nodes - count as one. Variable-length and untyped relationships are not checked, except inside a named path. + count as one for this single-hop check. A named path tracks edge occurrences across its segments. + An unnamed path also tracks occurrences across segments that share a type when the relationship + patterns are anonymous and typed, their boundary labels resolve, and a shared walk or bounded + join chain can execute the pattern. Node IDs duplicated elsewhere in the graph do not affect this + rule. Patterns with a relationship variable, unresolved boundaries, or more than 64 join branches + without a suitable CSR walk use the ordinary expansions and can reuse an edge between segments. + A shared trail keeps its edge history within that path, including when another pattern + appears after a comma. Separate paths in the same clause do not share that history. + For example, in `(p)-[:KNOWS*1..2]-(f)-[:KNOWS]-(g)` the last hop must use a + friendship that the path from `p` to `f` has not used. Two paths reaching the same + `f` can have different choices for that hop. - **`count(r)` on a relationship** counts the rows where `r` matched, so an unmatched `OPTIONAL MATCH` counts zero. `count(DISTINCT r)` compares all of `r`'s columns: parallel edges with identical properties count once. @@ -408,8 +420,7 @@ RETURN length(p), nodes(p) duplicate node sequences that use different parallel edges. A single source-target pair searches from both ends when reverse adjacency is available. Several targets for the same source in an input batch share one forward search, and those forward searches run together, up to 64 sources at a time. -- **Named paths** (`p = (a)-[:R]->(b)`) retain the ordered node and relationship records. Named - variable-length paths use each relationship at most once, including self-loops and parallel edges. +- **Named paths** (`p = (a)-[:R]->(b)`) retain the ordered node and relationship records. Use `relationships(p)` for variable-length relationship lists; binding a relationship variable inside a named variable-length segment is not supported. diff --git a/docs/internals/index.md b/docs/internals/index.md index 7ab8c237..24fac21e 100644 --- a/docs/internals/index.md +++ b/docs/internals/index.md @@ -116,7 +116,7 @@ All paths are under | `csr_store.rs` | CSR files stored with `persist_csr` | lance-csr | | `exec_metrics.rs` | The wrapper that records each operator's metrics for `explain(..., analyze=True)` | lance-csr | | `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 | +| `csr_expand/trail_walk.rs`, `csr_traversal.rs` | Shared CSR trail cursor and its single-segment traversal adapter | 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 CSR walk and the edge inventory), Arrow path values | lance-csr | | `apply.rs` | `ApplyNode` and `ApplyExec` for CALL subqueries | lance-csr | diff --git a/docs/internals/operators.md b/docs/internals/operators.md index 2fa1cc11..20b56dff 100644 --- a/docs/internals/operators.md +++ b/docs/internals/operators.md @@ -305,9 +305,10 @@ collide with identity metadata. When an untyped match combines branches, the pla 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 tracks edge -occurrences during traversal, on whichever route the segment takes. +An unnamed, bounded undirected segment with several types uses iterative `CsrExpandExec` +when the engine has the CSR and node indexes it needs. Otherwise `PathMatchExec` emits boundary +columns and skips building the Arrow path value for each trail. Both operators identify each edge +by its type and occurrence, including when a trail traverses it in reverse. 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 @@ -318,6 +319,31 @@ expression in the plan references it. The node then shows as `PathMatchExec: end 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. +### Trails across segments of an unnamed path + +For an unnamed path such as `(p)-[:KNOWS*1..2]-(f)-[:KNOWS]-(g)`, the final hop +must know which edge occurrences the first segment used. With compatible CSR and node +indexes, the planner can start at a bound or more selective endpoint even when it is +written last. `TrailWalkExec` starts at each input row and carries the relationship type and +stored edge row through every segment. It emits the node IDs at segment boundaries, +so the query can return both `f` and `g`. Node properties can be fetched by ID when used. +Without the indexes, the planner can join one branch per combination of hop lengths, +checking each hop against earlier occurrences of its type. An edge used in reverse +still has the same identity. + +The join chain uses Lance row addresses or original Arrow row ordinals to recognize +an edge appearing twice. For an Arrow table the engine builds the ordinal column on its +first use and shares it within that snapshot. A custom catalog without occurrence IDs +numbers parallel rows within each pair of stored endpoints before filtering or reversing a +hop. It orders the rows by the properties tested on that type so that each scan distinguishes +the same parallel occurrences. + +Planning the shared walk or join chain depends only on the pattern and the indexes, never on the +data: it requires no scan for duplicate node IDs or comparison of unrelated property types. A +relationship variable, unresolved boundary label, or more than 64 join branches without +a suitable CSR walk leaves the segments to ordinary expansion. Those expansions track +edge use within each variable-length segment and can reuse an edge across a boundary. + Path property values are logical expressions, so cached plans bind them before physical planning. 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. diff --git a/python/python/lance_csr/cypher.py b/python/python/lance_csr/cypher.py index 2fc2da7a..dc4f8593 100644 --- a/python/python/lance_csr/cypher.py +++ b/python/python/lance_csr/cypher.py @@ -83,7 +83,9 @@ class CypherEngine: not read here. use_csr : bool Build the experimental [CSR index](csr.md) for relationship types with integer - endpoints, and node indexes for labels with unique integer keys. + endpoints, and node indexes for labels with unique integer keys. With either + setting, each hop of a variable-length segment uses a different stored + relationship. Parallel relationships between the same nodes count separately. target_partitions : int or None Keyword-only. A target from 1 to 1024 for DataFusion query partitioning; `None` keeps DataFusion's default. `checkout_latest` preserves it. It is not a thread diff --git a/python/python/tests/test_engine_alternation.py b/python/python/tests/test_engine_alternation.py index f7e4527f..f33976ed 100644 --- a/python/python/tests/test_engine_alternation.py +++ b/python/python/tests/test_engine_alternation.py @@ -10,7 +10,7 @@ import lance import pyarrow as pa import pytest -from lance_csr import CypherEngine, GraphConfig +from lance_csr import CypherEngine, CypherQuery, DirNamespace, GraphConfig, SqlEngine RELS = { "postHasCreator": ("Post", "Person", [10, 11], [1, 2]), @@ -164,7 +164,8 @@ def test_undirected_bounded_alternation(datasets, use_csr): assert rows(engine.execute(query)) == expected assert rows(engine.execute(f"MATCH pth = {path} RETURN q.id, q.score")) == expected physical = engine.explain(query).split("physical_plan", 1)[1] - assert physical.count("PathMatchExec: endpoints") == 1 + operator = "CsrExpandExec" if use_csr else "PathMatchExec: endpoints" + assert physical.count(operator) == 1 assert "UnionExec" not in physical # The application carries its starting nodes through UNWIND and collects endpoints. @@ -209,6 +210,182 @@ def test_undirected_alternation_bound_start_label(binding): engine.execute(f"MATCH (s:X {{id: 1}}) {path}") +@pytest.mark.parametrize("use_csr", [False, True]) +@pytest.mark.parametrize( + ("edges", "pattern", "expected"), + [ + ([(1, 2), (1, 2)], "-[:{}*1..2]-", [1, 1, 2, 2]), + ([(1, 1)], "-[:{}*1..2]->", [1]), + ([(1, 1)], "-[:{}*1..2]-", [1]), + ([(1, 2), (2, 1)], "-[:{}*1..4]->", [1, 2]), + ([(1, 2), (2, 3), (3, 1)], "-[:{}*4..4]-", []), + ([(1, 2), (2, 1), (1, 2)], "<-[:{}*3..3]-", []), + ([(1, 2), (2, 1), (1, 2)], "-[:{}*3..3]->", [2, 2]), + ], + ids=[ + "parallel", + "self-loop", + "undirected-loop", + "cycle", + "triangle", + "incoming", + "distinct-parallel", + ], +) +def test_each_relationship_is_used_once_per_trail(use_csr, edges, pattern, expected): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("A", "N", "N", "src", "dst") + .rel_table("B", "N", "N", "src", "dst") + .build() + ) + src, dst = zip(*edges) + a = pa.table({"src": src, "dst": dst}) + tables = {"N": pa.table({"id": [1, 2, 3]}), "A": a, "B": a.slice(0, 0)} + engine = CypherEngine(cfg, tables, use_csr=use_csr) + for types in ("A", "A|B", "A|a"): + for binding in ("", "p = "): + path = f"{binding}(s:N {{id: 1}}){pattern.format(types)}(q:N)" + assert ( + sorted( + engine.execute(f"MATCH {path} RETURN q.id").column(0).to_pylist() + ) + == expected + ), path + + +@pytest.mark.parametrize("use_csr", [False, True]) +def test_trails_keep_typed_endpoints_separate(use_csr): + cfg = ( + GraphConfig.builder() + .node_table("X", "id") + .node_table("Y", "id") + .rel_table("A", "X", "Y", "src", "dst") + .rel_table("B", "Y", "X", "src", "dst") + .build() + ) + engine = CypherEngine( + cfg, + { + "X": pa.table({"id": [1, 2]}), + "Y": pa.table({"id": [1, 2]}), + "A": pa.table({"src": [1, 1, 2], "dst": [2, 2, 2]}), + "B": pa.table({"src": [2], "dst": [1]}), + }, + use_csr=use_csr, + ) + for binding in ("", "p = "): + for pattern, label, expected in [ + ("-[:A*1..3]->", "X", []), + ("-[:A*1..3]->", "Y", [2, 2]), + ("-[:A*2..2]-", "X", [1, 1, 2, 2]), + ("-[:A|B*3..3]->", "Y", [2, 2]), + ]: + path = f"{binding}(s:X {{id: 1}}){pattern}(q:{label})" + assert ( + sorted( + engine.execute(f"MATCH {path} RETURN q.id").column(0).to_pylist() + ) + == expected + ) + + for endpoint in ("q", "q:X:Y"): + query = f"MATCH (s:X {{id:1}})-[:A|B*3..3]->({endpoint}) RETURN q.id" + assert rows(engine.execute(query)) == [(2,), (2,)] + + +@pytest.mark.parametrize("use_csr", [False, True]) +def test_trail_boundaries_and_carried_scalars(use_csr): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("A", "N", "N", "src", "dst") + .rel_table("B", "N", "N", "src", "dst") + .build() + ) + a = pa.table({"src": [1, 2, 1], "dst": [2, 1, 2], "_edge_rank": [1, 2, 3]}) + engine = CypherEngine( + cfg, + {"N": pa.table({"id": [1, 2]}), "A": a, "B": a.slice(0, 0)}, + use_csr=use_csr, + ) + for binding in ("", "p = "): + path = f"{binding}(s:N {{id: 1}})-[:A*2..2]->(:N)-[:A]->(q:N)" + assert rows(engine.execute(f"MATCH {path} RETURN q.id")) == [(2,), (2,)] + # A new MATCH can use the same edges again. A scalar supplied by WITH survives both. + query = ( + "WITH 99 AS __trail_rank_0 MATCH (s:N {id:1})-[:A|B*3..3]->(q:N) " + "MATCH (q)-[:A|B*2..2]->(b:N) RETURN __trail_rank_0, b.id" + ) + assert rows(engine.execute(query)) == [(99, 2)] * 4 + query = "MATCH (s:N {id:1})-[:A*1..3 {_edge_rank: 1}]-(q:N) RETURN q.id" + assert rows(engine.execute(query)) == [(2,)] + + +def test_terminal_batches_resume_across_high_degree_and_missing_nodes(): + # Unmatched endpoints span multiple yield intervals before the first row. + missing = list(range(3000, 5500)) + endpoints = list(range(2, 1091)) + dst = missing + endpoints + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("A", "N", "N", "src", "dst") + .build() + ) + engine = CypherEngine( + cfg, + { + "N": pa.table({"id": [0, 1, *endpoints]}), + "A": pa.table({"src": [0, *([1] * len(dst))], "dst": [1, *dst]}), + }, + use_csr=True, + ) + query = "MATCH (s:N {id:0})-[:A*2..2]->(q:N) RETURN q.id" + assert "CsrExpandExec" in engine.explain(query) + result = engine.execute(query) + assert sorted(result.column(0).to_pylist()) == endpoints + + +def test_trail_join_uses_stored_rows_across_lance_versions(tmp_path): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("A", "N", "N", "src", "dst") + .build() + ) + path = tmp_path / "edges.lance" + a = pa.table( + { + "src": [1, 1, 1], + "dst": [2, 2, 2], + "n": [1, 2, 3], + "__lance_csr_edge_ordinal": [0, 0, 0], + } + ) + dataset = lance.write_dataset(a, path, max_rows_per_file=2) + dataset.delete("n = 2") + nodes = pa.table({"id": [1, 2]}) + query = "MATCH (s:N {id:1})-[:A*2..2]-(q:N) RETURN q.id" + for source in (a.filter(pa.array([True, False, True])), lance.dataset(path)): + engine = CypherEngine(cfg, {"N": nodes, "A": source}, use_csr=False) + assert rows(engine.execute(query)) == [(1,), (1,)] + assert "WindowAggExec" not in engine.explain(query) + lance.write_dataset(a.slice(0, 1), path, mode="append") + assert rows(engine.execute(query)) == [(1,), (1,)] + engine.checkout_latest() + assert rows(engine.execute(query)) == [(1,)] * 6 + + # A user column that would collide with Lance's hidden physical address + # selects the generic window-based fallback. Its values are all identical. + colliding = a.append_column("_ROWADDR", pa.array([0, 0, 0])) + fallback = lance.write_dataset(colliding, tmp_path / "custom.lance") + engine = CypherEngine(cfg, {"N": nodes, "A": fallback}, use_csr=False) + assert "WindowAggExec" in engine.explain(query) + assert rows(engine.execute(query)) == [(1,)] * 6 + + def test_undirected_alternation_parallel_edges_and_zero_hops(): cfg = ( GraphConfig.builder() @@ -318,3 +495,258 @@ def check_page(edge): assert len(edges) == 12 for row in edges: check_page(row["r"]) + + +@pytest.mark.parametrize("dtype", [pa.uint64(), pa.int32()]) +def test_arrow_csr_ignores_user_rowaddr_for_edge_identity(dtype): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + ) + data = { + "N": pa.table({"id": [1, 2, 3]}), + "R": pa.table( + {"src": [1, 2], "dst": [2, 3], "_rowaddr": pa.array([0, 0], dtype)} + ), + } + engine = CypherEngine(cfg, data, use_csr=True) + query = "MATCH (:N {id:1})-[:R*2..2]->(b:N) RETURN b.id" + assert rows(engine.execute(query)) == [(3,)] + + +@pytest.mark.parametrize("use_csr", [False, True]) +def test_overlapping_trail_with_conflicting_node_property_types(use_csr): + cfg = ( + GraphConfig.builder() + .node_table("X", "id") + .node_table("Y", "id") + .rel_table("R", "X", "Y", "src", "dst") + .build() + ) + data = { + "X": pa.table({"id": pa.array([1, 2], pa.int32())}), + "Y": pa.table({"id": pa.array([10], pa.int64())}), + "R": pa.table({"src": pa.array([1, 2], pa.int32()), "dst": [10, 10]}), + } + engine = CypherEngine(cfg, data, use_csr=use_csr) + query = "MATCH (:X {id:1})-[:R*1..1]->(:Y)<-[:R]-(q:X) RETURN q.id" + assert rows(engine.execute(query)) == [(2,)] + + +@pytest.mark.parametrize("use_csr", [False, True]) +def test_overlapping_trail_with_duplicate_node_keys(use_csr): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + ) + engine = CypherEngine( + cfg, + { + "N": pa.table({"id": [1, 2, 3, 4, 4]}), + "R": pa.table({"src": [1, 2], "dst": [2, 3]}), + }, + use_csr=use_csr, + ) + query = "MATCH (a:N {id:1})-[:R*1..1]->(b:N)-[:R]->(c:N) RETURN c.id" + assert rows(engine.execute(query)) == [(3,)] + + +@pytest.mark.parametrize("use_csr", [False, True]) +def test_unrelated_duplicate_cannot_enable_edge_reuse(use_csr): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + ) + data = { + "N": pa.table({"id": [1, 2, 9, 9]}), + "R": pa.table({"src": [1], "dst": [2]}), + } + engine = CypherEngine(cfg, data, use_csr=use_csr) + query = "MATCH (a:N {id:1})-[:R*1..1]-(b:N)-[:R]-(c:N) RETURN c.id" + assert rows(engine.execute(query)) == [] + assert rows(engine.execute(query.replace("MATCH ", "MATCH (:N {id:2}), "))) == [] + + +def test_unreachable_alternative_cannot_disable_indexed_trail(): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .node_table("C", "id") + .rel_table("R", "N", "N", "src", "dst") + .rel_table("T", "N", "N", "src", "dst") + .rel_table("S", "C", "C", "src", "dst") + .build() + ) + for ids in ([9], [9, 9], ["nine", "nine"]): + engine = CypherEngine( + cfg, + { + "N": pa.table({"id": [1, 2]}), + "C": pa.table({"id": ids}), + "R": pa.table({"src": [1], "dst": [1]}), + "T": pa.table({"src": [2], "dst": [2]}), + "S": pa.table({"src": [ids[0]], "dst": [ids[0]]}), + }, + use_csr=True, + ) + prefix = "MATCH (:N {id:1})-[:S|R|T*1..6]->(b:N)" + assert "CsrExpandExec" in engine.explain(prefix + " RETURN b.id") + assert "TrailWalkExec" in engine.explain(prefix + "-[:R]->(c:N) RETURN c.id") + assert rows(engine.execute(prefix + " RETURN b.id")) == [(1,)] + assert rows(engine.execute(prefix + "-[:R]->(c:N) RETURN c.id")) == [] + + +@pytest.mark.parametrize("use_csr", [False, True]) +@pytest.mark.parametrize("end", ["Tag", "C"]) +def test_alternating_trail_that_closes_on_its_start(use_csr, end): + cfg = ( + GraphConfig.builder() + .node_table("Tag", "id") + .node_table("C", "id") + .rel_table("H", "Tag", "C", "src", "dst") + .rel_table("S", "C", end, "src", "dst") + .build() + ) + engine = CypherEngine( + cfg, + { + "Tag": pa.table({"id": [1]}), + "C": pa.table({"id": [2]}), + "H": pa.table({"src": [1], "dst": [2]}), + "S": pa.table({"src": [2], "dst": [1 if end == "Tag" else 2]}), + }, + use_csr=use_csr, + ) + cycles = [(1,), (2,)] if end == "Tag" else [(2,)] + for low, expected in [(1, cycles), (0, sorted(cycles + [(1,), (2,)]))]: + q = f"MATCH (a)-[:H|S*{low}..2]->(a) RETURN a.id" + assert rows(engine.execute(q)) == expected + + +@pytest.mark.parametrize("use_csr", [False, True]) +def test_repeated_type_in_trail_alternation(use_csr): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + ) + data = { + "N": pa.table({"id": [1, 2, 3]}), + "R": pa.table({"src": [1, 1, 2], "dst": [2, 2, 3]}), + } + engine = CypherEngine(cfg, data, use_csr=use_csr) + for tail in [" RETURN b.id", "-[:R]-(c:N) RETURN b.id, c.id"]: + pattern = "MATCH (:N {id:1})-[:R*1..2]->(b:N)" + expected = rows(engine.execute(pattern + tail)) + assert rows(engine.execute(pattern.replace(":R*", ":R|r*") + tail)) == expected + + +@pytest.mark.parametrize("on_disk", [False, True]) +def test_overlapping_trail_one_shot_and_graph_table(on_disk, tmp_path): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + ) + data = { + "N": pa.table({"id": [1, 2, 3, 3]}), + "R": pa.table({"src": [1], "dst": [2]}), + } + if on_disk: + data = { + name: lance.write_dataset(table, tmp_path / f"{name}.lance") + for name, table in data.items() + } + pattern = "MATCH (:N {id:1})-[:R*1..1]->(:N)<-[:R]-(q:N)" + # The same stored edge cannot be used for the return hop. + query = CypherQuery(pattern + " RETURN q.id").with_config(cfg) + assert rows(query.execute(data)) == [] + if on_disk: + assert rows(query.execute_with_namespace(DirNamespace(str(tmp_path)))) == [] + sql = f"SELECT * FROM GRAPH_TABLE ({pattern} COLUMNS (q.id AS id))" + engine = SqlEngine(data, cfg, use_csr=False) + assert rows(engine.execute(sql)) == [] + assert rows(engine.execute(sql)) == [] + + +def test_unrelated_duplicate_in_new_snapshot_preserves_trail(tmp_path): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .build() + ) + nodes = lance.write_dataset(pa.table({"id": [1, 2, 3]}), tmp_path / "nodes") + edges = pa.table({"src": [1], "dst": [2]}) + engine = CypherEngine(cfg, {"N": nodes, "R": edges}, use_csr=False) + query = "MATCH (:N {id:1})-[:R*1..1]->(:N)<-[:R]-(q:N) RETURN q.id" + assert rows(engine.execute(query)) == [] + lance.write_dataset(pa.table({"id": [3]}), tmp_path / "nodes", mode="append") + assert rows(engine.execute(query)) == [] + engine.checkout_latest() + assert rows(engine.execute(query)) == [] + + +@pytest.mark.parametrize("use_csr", [False, True]) +def test_overlapping_trail_with_unrelated_endpoint_label(use_csr): + cfg = ( + GraphConfig.builder() + .node_table("X", "id") + .node_table("Y", "id") + .node_table("Z", "id") + .rel_table("R", "X", "Y", "src", "dst") + .build() + ) + tables = { + "X": pa.table({"id": [1]}), + "Y": pa.table({"id": [2]}), + # The numerical ID also occurs in X, but R is only mapped from X to Y. + "Z": pa.table({"id": [1]}), + "R": pa.table({"src": [1], "dst": [2]}), + } + engine = CypherEngine(cfg, tables, use_csr=use_csr) + query = "MATCH (:Z)-[:R*1..1]->(:Y)<-[:R]-(q:X) RETURN q.id" + assert rows(engine.execute(query)) == [] + + +@pytest.mark.parametrize("use_csr", [True, False]) +@pytest.mark.parametrize("types", ["R", "R|S"]) +def test_trail_followed_by_same_type_hop_uses_local_expansion(use_csr, types): + cfg = ( + GraphConfig.builder() + .node_table("N", "id") + .rel_table("R", "N", "N", "src", "dst") + .rel_table("S", "N", "N", "src", "dst") + .build() + ) + # The parallel edges are distinct. At the middle node the next hop must + # remember which one reached it, including when returning to node 1. + engine = CypherEngine( + cfg, + { + "S": pa.table({"src": [3], "dst": [1]}), + "N": pa.table({"id": [1, 2, 3, 4]}), + "R": pa.table({"src": [1, 1, 2, 3], "dst": [2, 2, 3, 4]}), + }, + use_csr=use_csr, + ) + query = f"MATCH (:N {{id:1}})-[:{types}*1..2]-(f:N)-[:R]-(g:N) RETURN f.id, g.id" + expected = [(2, 1), (2, 1), (2, 3), (2, 3), (3, 4), (3, 4)] + if types == "R|S": + # The S row can be followed by R even when both have the same row ordinal. + expected += [(3, 2), (3, 4), (2, 1), (2, 1)] + assert rows(engine.execute(query)) == sorted(expected) + assert "PathMatchExec" not in engine.explain(query) + + reverse = f"MATCH (g:N)-[:R]-(f:N)-[:{types}*1..2]-(p:N {{id:1}}) RETURN f.id, g.id" + assert rows(engine.execute(reverse)) == sorted(expected) + if use_csr: + assert "TrailWalkExec: start=p__id" in engine.explain(reverse) diff --git a/python/python/tests/test_engine_csr_delta.py b/python/python/tests/test_engine_csr_delta.py index 345b2228..395e9411 100644 --- a/python/python/tests/test_engine_csr_delta.py +++ b/python/python/tests/test_engine_csr_delta.py @@ -31,6 +31,7 @@ # Relationship columns are taken by edge row, so rows must stay aligned. "MATCH (a:Person)-[r:KNOWS]->(b:Person) RETURN a.id, b.id, r.since", "MATCH (a:Person)<-[r:KNOWS]-(b:Person) WHERE a.id < 10 RETURN a.id, r.since", + "MATCH (s:Person {id:2})-[:KNOWS*2..3]-(q:Person) RETURN q.id", ] diff --git a/python/python/tests/test_engine_csr_persist.py b/python/python/tests/test_engine_csr_persist.py index d73dca61..c6b280e2 100644 --- a/python/python/tests/test_engine_csr_persist.py +++ b/python/python/tests/test_engine_csr_persist.py @@ -29,6 +29,7 @@ "MATCH (a:Person)<-[:KNOWS]-(b:Person) RETURN a.id, b.name", "MATCH (a:Person)-[:KNOWS]->(b:Person)-[:KNOWS]->(c:Person) RETURN count(*) AS n", "MATCH (a:Person)-[r:KNOWS]->(b:Person) RETURN a.id, b.id, r.since", + "MATCH (s:Person {id:2})-[:KNOWS*2..3]-(q:Person) RETURN q.id", ] diff --git a/python/python/tests/test_path_csr_walk.py b/python/python/tests/test_path_csr_walk.py index 293c556c..76222d3f 100644 --- a/python/python/tests/test_path_csr_walk.py +++ b/python/python/tests/test_path_csr_walk.py @@ -95,7 +95,9 @@ def test_csr_walk_matches_edge_inventory(tmp_path, lazy): csr = CypherEngine(CONFIG, data, use_csr=True) inventory = CypherEngine(CONFIG, data) for query in QUERIES: - assert "csr walk" in csr.explain(query), query + # An unnamed multi-type segment takes iterative CsrExpand instead. + route = "csr walk" if query.startswith("MATCH p =") else "CsrExpandExec" + assert route in csr.explain(query), query assert rows(csr, query) == rows(inventory, query), query