Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions crates/lance-csr/src/csr_expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3662,6 +3662,17 @@ fn prune_within(
plan.map_children(|child| prune_within(child, used))?
.transform_data(|node| {
if let LogicalPlan::Extension(ext) = &node {
if let Some(path) = ext
.node
.as_any()
.downcast_ref::<crate::path_match::PathMatchNode>()
{
if let Some(pruned) = path.without_unused_path(used)? {
return Ok(Transformed::yes(LogicalPlan::Extension(Extension {
node: Arc::new(pruned),
})));
}
}
if let Some(csr) = ext.node.as_any().downcast_ref::<CsrExpandNode>() {
if let Some(pruned) = csr.with_target_columns(used) {
return Ok(Transformed::yes(LogicalPlan::Extension(Extension {
Expand Down
45 changes: 41 additions & 4 deletions crates/lance-csr/src/path_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub(crate) struct Step {
pub relationship: Option<String>,
}

#[derive(Debug)]
#[derive(Debug, Clone)]
pub(crate) struct PathSpec {
pub variable: Option<String>,
/// Expose typed boundary-node values alongside their property columns.
Expand All @@ -76,7 +76,7 @@ pub(crate) struct PathSpec {

/// The engine's CSR for every relationship a trail walk follows. Edges are read
/// only where the walk goes; an edge's identity is its row in the CSR.
#[derive(Debug)]
#[derive(Debug, Clone)]
pub(crate) struct CsrRoute {
/// Per step, every (type, direction) adjacency the step follows. Each type's rows are
/// its `EdgeSource::rows`.
Expand All @@ -93,7 +93,7 @@ impl PathSpec {
}
}

#[derive(Debug)]
#[derive(Debug, Clone)]
pub(crate) struct CsrHop {
pub kind: usize,
pub neighbors: Neighbors,
Expand Down Expand Up @@ -239,6 +239,34 @@ impl PathMatchNode {
outputs,
})
}

/// This node without its path value, when no column in `used` reads the path.
pub(crate) fn without_unused_path(&self, used: &HashSet<String>) -> Result<Option<Self>> {
let Some(variable) = &self.spec.variable else {
return Ok(None);
};
if used.contains(&variable.to_lowercase()) {
return Ok(None);
}
// The path value is the last column `try_new` adds.
let kept = self.schema.fields().len() - 1;
let schema = DFSchema::new_with_metadata(
self.schema
.iter()
.take(kept)
.map(|(qualifier, field)| (qualifier.cloned(), Arc::clone(field)))
.collect(),
self.schema.metadata().clone(),
)?
.with_functional_dependencies(self.schema.functional_dependencies().clone())?;
let mut spec = PathSpec::clone(&self.spec);
spec.variable = None;
Ok(Some(Self {
spec: Arc::new(spec),
schema: Arc::new(schema),
..self.clone()
}))
}
}
impl PartialEq for PathMatchNode {
fn eq(&self, other: &Self) -> bool {
Expand Down Expand Up @@ -579,6 +607,13 @@ impl ExecutionPlan for PathMatchExec {
self.hop_filters.clone(),
);
let sources = self.sources.clone();
let reads_edges = spec.variable.is_some()
|| outputs.iter().any(|o| {
matches!(
o,
Output::RelationshipValue { .. } | Output::Relationship { .. }
)
});
let out_schema = schema.clone();
let batch_size = context.session_config().batch_size();
let stream = futures::stream::try_unfold(
Expand Down Expand Up @@ -628,7 +663,9 @@ impl ExecutionPlan for PathMatchExec {
continue;
}
let edges = match &spec.csr {
Some(_) => p.csr_edges(&spec, &mut paths).await?,
Some(_) if reads_edges => p.csr_edges(&spec, &mut paths).await?,
// Nothing reads relationship records: don't fetch them.
Some(_) => StructArray::new_empty_fields(0, None),
None => p.graph.inventory.edges.clone(),
};
let indices = UInt32Array::from(rows);
Expand Down
63 changes: 63 additions & 0 deletions crates/lance-csr/tests/test_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,69 @@ async fn named_path_endpoint_labels_ignore_case() {
}
}

#[tokio::test]
async fn named_paths_build_path_values_only_when_read() {
let cfg = GraphConfig::builder()
.node_table("Person", "id")
.rel_table("KNOWS", "Person", "Person", "src_id", "dst_id")
.build()
.unwrap();
let edges = [(1, 2), (2, 3), (3, 1), (1, 3), (3, 4), (2, 2)];
let path = "MATCH p = (a:Person {id: 1})-[:KNOWS*1..3]->(b:Person)";
// (return clause, whether it reads the path)
let cases = [
("RETURN count(*) AS n", false),
("RETURN count(b.id) AS n", false),
("WITH b, p RETURN count(b) AS n", false),
("RETURN count(p) AS n", true),
("RETURN count(length(p)) AS n", true),
("RETURN count(nodes(p)) AS n", true),
("RETURN count(relationships(p)) AS n", true),
("WITH p AS q RETURN count(q) AS n", true),
];
for use_csr in [false, true] {
let engine = CypherEngine::new(
cfg.clone(),
HashMap::from([
("Person".into(), EngineSource::Arrow(people())),
("KNOWS".into(), EngineSource::Arrow(knows(&edges))),
]),
use_csr,
)
.await
.unwrap();
let count = |query: String| {
let engine = &engine;
async move {
let batch = engine.execute(&query, HashMap::new()).await.unwrap();
let n = batch.column_by_name("n").unwrap();
n.as_any().downcast_ref::<Int64Array>().unwrap().value(0)
}
};
let expected = count(format!("{path} RETURN count(p) AS n")).await;
assert!(expected > 4, "use_csr={use_csr}");
for (ret, reads_path) in cases {
let query = format!("{path} {ret}");
assert_eq!(
count(query.clone()).await,
expected,
"use_csr={use_csr} {query}"
);
let plan = engine.explain(&query, HashMap::new()).await.unwrap();
let walk = if use_csr {
"csr walk"
} else {
"edge inventory"
};
let node = if reads_path { "p" } else { "endpoints" };
assert!(
plan.contains(&format!("PathMatchExec: {node} {walk}")),
"use_csr={use_csr} {query}\n{plan}"
);
}
}
}

#[tokio::test]
async fn anonymous_patterns_keep_mixed_label_identity_and_query_semantics() {
use arrow_array::{cast::AsArray, StructArray};
Expand Down
2 changes: 2 additions & 0 deletions docs/cypher.md
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,8 @@ relationship endpoints identify one node; duplicate IDs raise an error. Expandin
a mixed-label value remains unsupported.

A path value needs the properties of its nodes, so each execution reads the participating node tables in full.
A query that names a path but never reads it, such as `MATCH p = ... RETURN count(*)`, builds no path
values and, on the CSR walk, reads no relationship properties.
With `use_csr=True`, a named path reads relationships only where its walk goes (see
[the CSR index](csr.md#which-hops-use-it)). Shortest paths, and paths over a relationship type without a CSR,
also read the relationship tables into a query-local inventory, whose memory grows with the graph.
Expand Down
9 changes: 9 additions & 0 deletions docs/internals/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,15 @@ For an unnamed, bounded undirected segment with several types, the same operator
boundary columns and skips building the Arrow path value for each trail. It still tracks edge
occurrences during traversal, on whichever route the segment takes.

A named path whose variable the query never reads runs the same way. Building a path value costs
far more than the walk when a query only counts paths or returns their end nodes: on the LDBC SF1
graph, the 86K paths of `MATCH p = (a:Person {ID: 1131})-[:knows*1..3]->(b:Person) RETURN count(*)`
made about 100 MB of path values that nothing read. So the `prune_csr_target_columns` optimizer rule,
which already drops unused `CsrExpand` columns, also drops the path column from a `PathMatch` when no
expression in the plan references it. The node then shows as `PathMatchExec: endpoints` and, on the
CSR walk, reads no relationship records unless a relationship variable needs them. Any reference to
the path, such as `length(p)`, `nodes(p)` or `WITH p AS q`, keeps the value.

Path property values are logical expressions, so cached plans bind them before physical planning.
The physical operator then builds 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.
Expand Down
18 changes: 18 additions & 0 deletions python/python/tests/test_path_csr_walk.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,21 @@ def test_trail_and_shortest_path_agree_on_relationship_identity(
"RETURN relationships(p)[0] = relationships(q)[0] AS same, p = q AS same_path"
)
assert engine.execute(query).to_pylist() == [{"same": True, "same_path": True}]


@pytest.mark.parametrize("use_csr", [False, True], ids=["inventory", "csr"])
def test_path_values_are_built_only_when_read(use_csr):
engine = CypherEngine(CONFIG, DATA, use_csr=use_csr)
path = "MATCH p = (a:P {id: 0})-[:R*1..3]->(b:P)"
expected = engine.execute(f"{path} RETURN count(p) AS n").to_pylist()
unread = ["count(*)", "count(b.id)", "count(DISTINCT b.id)"]
read = ["count(p)", "sum(length(p))", "count(nodes(p))", "count(relationships(p))"]
for ret, node in [(r, "endpoints") for r in unread] + [(r, "p") for r in read]:
query = f"{path} RETURN {ret} AS n"
assert f"PathMatchExec: {node}" in engine.explain(query), query
for ret in ["count(*)", "count(b.id)"]:
assert engine.execute(f"{path} RETURN {ret} AS n").to_pylist() == expected
ids = f"{path} RETURN b.id AS b, length(p) AS n"
assert rows(engine, f"{path} RETURN b.id AS b") == sorted(
repr([("b", row["b"])]) for row in engine.execute(ids).to_pylist()
)
Loading