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
119 changes: 115 additions & 4 deletions crates/lance-csr/src/logical_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,9 @@ impl<'a> LogicalPlanner<'a> {

/// Convert a Cypher AST to a logical plan
pub fn plan(&mut self, query: &CypherQuery) -> Result<LogicalOperator> {
let mut query = query.clone();
drop_unread_path_variables(&mut query);
let query = &query;
let mut relationships = Vec::new();
query.for_each_query(&mut |scope| {
for clause in scope.all_reading_clauses() {
Expand Down Expand Up @@ -2474,6 +2477,65 @@ impl<'a> LogicalPlanner<'a> {
}
}

/// Unname every named path (`p = ...`) whose variable nothing in its query reads, so it
/// plans as the same pattern unnamed. A path value costs an inventory of the label's
/// nodes, read in full, that `count(*)` or a property return never looks at. Each UNION
/// branch is its own scope. Shortest paths keep their name.
fn drop_unread_path_variables(query: &mut CypherQuery) {
fn paths(query: &mut CypherQuery) -> impl Iterator<Item = &mut PathPattern> {
query
.reading_clauses
.iter_mut()
.chain(&mut query.post_with_reading_clauses)
.chain(
query
.further_with_stages
.iter_mut()
.flat_map(|stage| &mut stage.reading_clauses),
)
.filter_map(|clause| match clause {
ReadingClause::Match(m) => Some(m.patterns.iter_mut()),
ReadingClause::Unwind(_) => None,
})
.flatten()
.filter_map(|pattern| match pattern {
GraphPattern::Path(path) if path.shortest.is_none() => Some(path),
_ => None,
})
}
fn contains(value: &serde_json::Value, name: &str) -> bool {
match value {
serde_json::Value::String(s) => s == name,
serde_json::Value::Array(items) => items.iter().any(|v| contains(v, name)),
serde_json::Value::Object(fields) => fields.values().any(|v| contains(v, name)),
_ => false,
}
}

for branch in &mut query.union_branches {
drop_unread_path_variables(&mut branch.query);
}
let branches = std::mem::take(&mut query.union_branches);
// The scope without its path names: a name still found in it is read somewhere. A
// string that merely equals the name (a literal, a property key) keeps the path named,
// which plans it as before.
let mut bare = query.clone();
let mut named = false;
for path in paths(&mut bare) {
named |= path.variable.take().is_some();
}
if named {
let text = serde_json::to_value(&bare).ok();
for path in paths(query) {
let read = |name: &String| text.as_ref().is_none_or(|t| contains(t, name));
if path.variable.as_ref().is_some_and(|name| !read(name)) {
path.variable = None;
}
}
}
query.union_branches = branches;
}

/// The condition every relationship of the named path `p` must meet for `filter` to
/// hold, from its `all(r IN relationships(p) WHERE x)` and `none(... WHERE x)` conjuncts,
/// with `r.key` written as the variable `key`. The path operator checks it on each edge
Expand Down Expand Up @@ -3700,10 +3762,12 @@ mod tests {
("d", "", " {host_id: 7}", ""),
("d", "", "", " WHERE d.host_id = 7"),
] {
// `count(p)` reads the path, so it stays named.
let query = format!(
"MATCH {}{}{filter} RETURN count(*) AS n",
"MATCH {}{}{filter} RETURN count({}) AS n",
if named { "p = " } else { "" },
pattern.replace("{start}", start).replace("{end}", end),
if named { "p" } else { "*" },
);
let plan = computer_plan(&query);
let (variable, narrowed) = start_scan(&plan);
Expand All @@ -3722,7 +3786,7 @@ mod tests {
let plan = computer_plan(
"MATCH p = (c:Computer)-[:AUTH*1..2]->(d:Computer) \
WHERE c.host_id = 7 AND c.host_id < d.host_id AND (c)-[:AUTH]->(:Computer) \
RETURN count(*) AS n",
RETURN count(p) AS n",
);
fn scan_filter(plan: &LogicalOperator) -> &BooleanExpression {
match plan {
Expand All @@ -3749,14 +3813,61 @@ mod tests {
/// A MATCH after WITH uses the stage's WHERE to choose its start, as the first does.
#[test]
fn match_after_with_uses_its_where_to_choose_the_start() {
for (path, expected) in [("p = ", "reversed: true"), ("", "source_variable: \"d\"")] {
for (path, read, expected) in [
("p = ", "p", "reversed: true"),
("", "*", "source_variable: \"d\""),
] {
let query = format!(
"MATCH (x:Computer {{host_id: 1}}) WITH x \
MATCH {path}(c:Computer)-[:AUTH*1..2]->(d:Computer) WHERE d.host_id = 7 \
RETURN x.host_id, count(*) AS n"
RETURN x.host_id, count({read}) AS n"
);
let plan = format!("{:?}", computer_plan(&query));
assert!(plan.contains(expected), "{query}: {plan}");
}
}

/// A path name nothing reads is dropped, so the path plans as the unnamed pattern;
/// any read of it, in this scope only, keeps the path value.
#[test]
fn unread_path_names_plan_as_the_unnamed_pattern() {
let path = "(c:Computer {host_id: 7})-[:AUTH*1..2]->(d:Computer)";
let unnamed = format!(
"{:?}",
computer_plan(&format!("MATCH {path} RETURN count(*)"))
);
for (query, named) in [
(format!("MATCH p = {path} RETURN count(*)"), false),
(format!("MATCH p = {path} RETURN d.host_id"), false),
(format!("MATCH p = {path} RETURN p"), true),
(format!("MATCH p = {path} WHERE length(p) = 2 RETURN count(*)"), true),
(format!("MATCH p = {path} WITH p RETURN count(*)"), true),
(format!("MATCH p = {path} WITH d MATCH (d)-[:AUTH]->(e:Computer) RETURN count(*)"), false),
// A string equal to the name is taken as a read: the path stays as it was.
(format!("MATCH p = {path} WHERE d.name = 'p' RETURN count(*)"), true),
// Each UNION branch is its own scope.
(
format!("MATCH p = {path} RETURN 1 AS x UNION ALL MATCH p = {path} RETURN length(p) AS x"),
true,
),
] {
let plan = format!("{:?}", computer_plan(&query));
assert_eq!(plan.contains("PathMatch"), named, "{query}: {plan}");
}
let plan = format!(
"{:?}",
computer_plan(&format!("MATCH p = {path} RETURN count(*)"))
);
assert_eq!(plan, unnamed);
// Only the branch that reads its path keeps it.
let union = format!(
"MATCH p = {path} RETURN 1 AS x UNION ALL MATCH p = {path} RETURN length(p) AS x"
);
assert_eq!(
format!("{:?}", computer_plan(&union))
.matches("PathMatch")
.count(),
1
);
}
}
31 changes: 16 additions & 15 deletions crates/lance-csr/tests/test_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -506,16 +506,17 @@ async fn named_paths_build_path_values_only_when_read() {
.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)
// (return clause, the path operator's output: none when the query never names `p`
// again and plans as the unnamed pattern, endpoints when it only carries `p`)
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),
("RETURN count(*) AS n", None),
("RETURN count(b.id) AS n", None),
("WITH b, p RETURN count(b) AS n", Some("endpoints")),
("RETURN count(p) AS n", Some("p")),
("RETURN count(length(p)) AS n", Some("p")),
("RETURN count(nodes(p)) AS n", Some("p")),
("RETURN count(relationships(p)) AS n", Some("p")),
("WITH p AS q RETURN count(q) AS n", Some("p")),
];
for use_csr in [false, true] {
let engine = CypherEngine::new(
Expand All @@ -538,7 +539,7 @@ async fn named_paths_build_path_values_only_when_read() {
};
let expected = count(format!("{path} RETURN count(p) AS n")).await;
assert!(expected > 4, "use_csr={use_csr}");
for (ret, reads_path) in cases {
for (ret, node) in cases {
let query = format!("{path} {ret}");
assert_eq!(
count(query.clone()).await,
Expand All @@ -551,11 +552,11 @@ async fn named_paths_build_path_values_only_when_read() {
} 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}"
);
let found = match node {
Some(node) => plan.contains(&format!("PathMatchExec: {node} {walk}")),
None => !plan.contains("PathMatchExec"),
};
assert!(found, "use_csr={use_csr} {query}\n{plan}");
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions docs/cypher.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,9 @@ print(paths.to_pylist())
- A zero-hop path has one node and an empty relationship list. All path functions return `null` for a `null` path.
- **Cost:** constructing path values reads participating node tables in full. With `use_csr=True`, named trail
paths walk the CSR and read relationship properties only for returned paths; shortest paths and non-CSR
relationship types build a query-local edge inventory whose memory grows with the graph. A named path whose
variable is never read (such as `MATCH p = ... RETURN count(*)`) skips building path values.
relationship types build a query-local edge inventory whose memory grows with the graph. A path whose name
appears nowhere else in its query (such as `MATCH p = ... RETURN count(*)`) is planned as the same pattern without
the name, so it builds no path values and reads no node table in full.

??? info "Arrow struct layout and exact path semantics"

Expand Down
11 changes: 7 additions & 4 deletions docs/internals/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,10 +303,13 @@ Additional planning and schema details:
- **Unnamed undirected segments with several types:** bounded undirected segments with multiple types use
iterative `CsrExpandExec` when CSR and node indexes exist; otherwise `PathMatchExec` emits boundary columns
without building Arrow path values.
- **Skipping unused path values (`PathMatchExec: endpoints`):** building Arrow path structs is expensive when a
query only counts paths or returns endpoints (on LDBC SF1, 86K paths from `[:knows*1..3]` produced ~100 MB of
unused structs). `PruneCsrTargetColumns` drops the path column whenever nothing references `p`, letting the CSR
walk skip relationship records unless a relationship variable needs them.
- **Skipping unused path values:** building Arrow path structs is expensive when a query only counts paths or
returns endpoints (on LDBC SF1, 86K paths from `[:knows*1..3]` produced ~100 MB of unused structs). When the
path's name appears nowhere else in its query (UNION branches are separate), the logical planner drops the name
before planning, so the pattern gets the same plan as when written unnamed, with no `PathMatch` and no node
inventory. A name that is only passed along (`WITH b, p RETURN count(b)`) keeps `PathMatch`, but
`PruneCsrTargetColumns` drops the unread path column (`PathMatchExec: endpoints`), letting the CSR walk skip
relationship records unless a relationship variable needs them.
- **Predicate pushdown and caching:** path property values are logical expressions so cached plan templates bind
fresh parameters per execution. Conjuncts of `all(r IN relationships(p) WHERE ...)` and
`none(r IN relationships(p) WHERE ...)` that read only `r`'s properties, parameters and literals are combined
Expand Down
6 changes: 3 additions & 3 deletions docs/internals/optimizer.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ flowchart LR
The same edges, endpoints, labels and variables are matched, and the full `WHERE` clause still applies above the
match. Only the order of work changes.

A single named path (`p = ...`) or a path with a variable-length segment is not split, so it can only be walked from
one end or the other. The planner walks it from its written end when that end is bound, or when its conditions score
higher than the start's. A named path walked backwards is marked `reversed` in `PathMatch`, which reverses each
A single named path (`p = ...`) whose name the query reads, or a path with a variable-length segment, is not split,
so it can only be walked from one end or the other. The planner walks it from its written end when that end is bound,
or when its conditions score higher than the start's. A named path walked backwards is marked `reversed` in `PathMatch`, which reverses each
path's nodes and relationships before building `p`, so `nodes(p)` and `relationships(p)` keep their written order.
A variable-length segment with a relationship variable (`[r:KNOWS*1..3]`) keeps its written direction, because `r`
is a list in that order. A `MATCH` after `WITH` makes the same choices using its stage's `WHERE`.
Expand Down
14 changes: 11 additions & 3 deletions python/python/tests/test_path_csr_walk.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@
f"MATCH p = (a:P)-[:R {{day: 2}}]->(b:P)-[:R {{day: 2}}]->(c:P) {PATH}",
f"MATCH p = (c:C)<-[:L]-(a:P)-[:R*1..2]-(b:P) {PATH}",
f"MATCH p = (a:P)-[:R*2..2]->(a) {PATH}",
"MATCH p = (a:P)-[e:R]->(b:P) RETURN a.id AS a, e.day AS d, e.w AS w, b.id AS b",
"MATCH p = (a:P)-[e:R]->(b:P) "
"RETURN a.id AS a, e.day AS d, e.w AS w, b.id AS b, length(p) AS n",
"MATCH (a:P)-[:R|S*1..2]-(b:P) RETURN a.id AS a, b.id AS b",
]

Expand Down Expand Up @@ -178,9 +179,16 @@ def test_path_values_are_built_only_when_read(use_csr):
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]:
# A path nothing reads plans as the unnamed pattern, with no path operator.
for ret, node in [(r, None) 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
plan = engine.explain(query)
found = (
"PathMatchExec" not in plan
if node is None
else f"PathMatchExec: {node}" in plan
)
assert found, 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"
Expand Down
80 changes: 80 additions & 0 deletions python/python/tests/test_plan_equivalence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The Lance Authors

"""Equivalent phrasings of a query get the same physical plan.

Where a traversal starts should depend on the query's meaning, not on how it is
written: anchor inline or in WHERE, the pattern written from either end, a path
named or not. Each group below lists phrasings of one query; all of them must give
the same plan and the same answer. Uses the graph from ``test_engine_csr.py``.
"""

import lance
import pytest
from lance_csr import CypherEngine
from test_engine_csr import CONFIG, KNOWS, PEOPLE

PATH = (
"(c:Person{c})-[:KNOWS*1..2]->(d:Person{d})",
"(d:Person{d})<-[:KNOWS*1..2]-(c:Person{c})",
)
TWO_HOPS = (
"(c:Person{c})-[:KNOWS]->(b:Person)-[:KNOWS]->(d:Person{d})",
"(d:Person{d})<-[:KNOWS]-(b:Person)<-[:KNOWS]-(c:Person{c})",
)


def phrasings(pattern: tuple[str, str], anchor: str, ret: str, names=("", "p = ")):
"""`pattern` written forward and backward, the anchor (`c` or `d`) inline and in
WHERE, with each path name."""
slots = {"c": "", "d": ""}
return [
f"MATCH {name}{body} {ret}"
for name in names
for text in pattern
for body in (
text.format(**{**slots, anchor: " {id: 1}"}),
text.format(**slots) + f" WHERE {anchor}.id = 1",
)
]


GROUPS = {
"path from its start": phrasings(PATH, "c", "RETURN count(*) AS n"),
"path from its end": phrasings(PATH, "d", "RETURN count(*) AS n"),
"path returning ends": phrasings(PATH, "c", "RETURN d.id AS id ORDER BY id"),
"two hops": phrasings(TWO_HOPS, "c", "RETURN d.id AS id ORDER BY id", names=("",)),
}


def physical(engine: CypherEngine, query: str) -> str:
plan = engine.explain(query)
plan = plan[plan.index("physical_plan") :]
# The explain table pads every line to its widest one, which differs per query.
return "\n".join(
line.strip(" |") for line in plan.splitlines() if line.strip(" |+-")
)


@pytest.fixture(params=["arrow", "lance"])
def engine(request, tmp_path):
datasets = {"Person": PEOPLE, "KNOWS": KNOWS}
if request.param == "lance":
datasets = {
"Person": lance.write_dataset(PEOPLE, tmp_path / "person.lance"),
"KNOWS": lance.write_dataset(KNOWS, tmp_path / "knows.lance"),
}
return CypherEngine(CONFIG, datasets, use_csr=True)


@pytest.mark.parametrize("group", GROUPS)
def test_equivalent_phrasings_get_one_plan(engine, group):
queries = GROUPS[group]
plans = {}
for query in queries:
plans.setdefault(physical(engine, query), []).append(query)
assert len(plans) == 1, "\n\n".join(
"\n".join(qs) + "\n" + plan for plan, qs in plans.items()
)
answers = {str(engine.execute(query).to_pylist()) for query in queries}
assert len(answers) == 1, answers
Loading