1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! The match sink's projection: a following `RETURN`/`WITH` the last pattern
//! of a `MATCH` evaluates per path, keeping only the projected row. Split
//! from `project.rs` (the order family's precedent): the sink is the
//! projection's sibling concern — it decides whether the clause can finish in
//! the walk at all — while the ordinary `RETURN`/`WITH` is the merge paths and
//! `project_rows` in `project.rs`, the plan in `classification.rs`, and the
//! landing container, the DISTINCT pass and the tail in `post_merge.rs`.
use std::collections::{BTreeMap, HashSet};
use relate_core::{Result, Value};
use relate_ir::Clause;
use crate::eval::{eval, expr_within, is_agg_expr};
use crate::overlay::ExecGraph;
use crate::row::{Row, RowNames};
use super::classification::pages_eagerly;
use super::expr_safety::{cannot_fail_on, cannot_fail_over_node, id_call_variable};
use super::order::{parked_values, OrderKeys};
use super::scope::{
is_star_item, projection_collides_with_internal_names, projection_names,
projection_repeats_output_name, ProjectionFields,
};
/// A following `RETURN`/`WITH` the match sink can evaluate per path.
///
/// Eager `SKIP`/`LIMIT` (no `ORDER BY`, `DISTINCT`, or `WITH` filter) stays
/// on the ordinary projection so a later row's error is not raised (CIP-27).
pub(crate) struct SinkProjection<'a> {
fields: ProjectionFields<'a>,
/// The clause's `ORDER BY` keys, parked per row by
/// [`finish_match_row`]. The sink declines an explicit `GROUP BY` and an
/// aggregate item, so it only ever sees the implicit-grouping decision.
order: OrderKeys<'a>,
names: RowNames,
/// Whether every order key reads only the incoming row's bindings: none
/// names a projected column, so a key evaluated against the incoming row
/// answers what the projected scope would (a verbatim key's item is the
/// same expression, evaluated on the same incoming row). Decided once
/// here; with it the window path keys a candidate before projecting it.
keys_read_incoming: bool,
/// The variable the clause orders by, ascending, as its one key
/// `id(var)` — the order an id-ascending scan of `var` already
/// delivers, so a full window can stop it.
ascending_id_of: Option<relate_names::SmallName>,
}
impl<'a> SinkProjection<'a> {
pub(crate) fn fields(&self) -> &ProjectionFields<'a> {
&self.fields
}
fn new(graph: &ExecGraph<'_>, fields: ProjectionFields<'a>) -> Self {
let items = fields.items;
let order_items = fields.order;
// The sink declines a `*` item and any repeated resolved name, so the
// filtered name list aligns with `items` index for index and the
// output schema opens with the items' columns in that order.
let mut names = projection_names(items);
debug_assert_eq!(names.len(), items.len());
let order = OrderKeys::new(graph, order_items, items, false);
for index in 0..order.len() {
names.push(order.name(index).to_string());
}
let item_names = projection_names(items);
let keys_read_incoming = !order.is_empty()
&& order.exprs().all(|expr| {
let mut vars = HashSet::new();
relate_ir::expr_vars(expr, &mut vars);
vars.iter().all(|var| !item_names.contains(var))
});
// Only when every item and the key read nothing but that node (or a
// literal): the scan stops reading rows past the page, so an
// expression that could raise on one of them must keep the full scan.
let ascending_id_of = match order_items {
[key] if key.ascending && keys_read_incoming => id_call_variable(&key.expr)
.filter(|var| {
items
.iter()
.all(|item| cannot_fail_over_node(&item.expr, var))
})
.cloned(),
_ => None,
};
Self {
fields,
order,
names: RowNames::new(&names),
keys_read_incoming,
ascending_id_of,
}
}
/// Whether the clause's whole order is `id(var)` ascending.
pub(crate) fn orders_ascending_by_id_of(&self, var: &relate_names::SmallName) -> bool {
self.ascending_id_of.as_ref() == Some(var)
}
/// Whether a window may key `row` before projecting it: the keys read
/// the incoming row alone, and every item and key is an expression whose
/// evaluation cannot fail on this row ([`cannot_fail_on`]), so a row the
/// window rejects raises exactly what projecting it first would have
/// raised: nothing.
pub(crate) fn keys_before_projection(&self, graph: &ExecGraph<'_>, row: &Row) -> bool {
self.keys_read_incoming
&& self
.fields
.items
.iter()
.all(|item| cannot_fail_on(&item.expr, row, graph))
&& self
.order
.exprs()
.all(|expr| cannot_fail_on(expr, row, graph))
}
/// Write the order keys' values for `row` into `out`, evaluated against
/// the incoming bindings: the sort's parked columns in key order, without
/// the projected scope row [`finish_match_row`] builds for them.
pub(crate) fn fill_key_values(
&self,
graph: &ExecGraph<'_>,
row: &Row,
params: &BTreeMap<String, Value>,
out: &mut Vec<Value>,
) -> Result<()> {
for expr in self.order.exprs() {
out.push(eval(graph, row, expr, params)?);
}
Ok(())
}
/// The projected output row for `row` with its already-computed `keys`
/// parked after the items: what [`finish_match_row`] returns, built only
/// for a row the window kept.
pub(crate) fn row_with_keys(
&self,
graph: &ExecGraph<'_>,
row: &Row,
keys: Vec<Value>,
params: &BTreeMap<String, Value>,
) -> Result<Row> {
let mut values = Vec::with_capacity(self.names.names().len());
for item in self.fields.items {
values.push(eval(graph, row, &item.expr, params)?);
}
values.extend(keys);
Ok(Row::from_names(&self.names, values))
}
/// The projected items' columns: the output schema's leading
/// `items.len()` names, in item order — the split [`Self::new`] builds.
fn item_names(&self) -> &[String] {
&self.names.names()[..self.fields.items.len()]
}
}
/// The projection a `MATCH` may finish in its sink, when the next clause
/// is a non-aggregate `RETURN` or `WITH`.
pub(crate) fn sinkable_projection<'c>(
graph: &ExecGraph<'_>,
clause: &'c Clause,
) -> Option<SinkProjection<'c>> {
let fields = ProjectionFields::from_clause(clause)?;
let ProjectionFields {
items,
group_by,
order,
where_clause,
..
} = fields;
if group_by.is_some()
|| items
.iter()
.any(|item| is_star_item(item) || is_agg_expr(&item.expr))
// The `__` namespace reservation: an alias the sink would park
// beside cannot be told apart from engine-internal state, so the
// sink declines and the ordinary projection keeps the column.
|| projection_collides_with_internal_names(items)
// Two items may resolve to one output name even though the
// front-end's conflict check (which compares verbatim names) passed
// them — writing them over one row would collapse them. Decline.
|| projection_repeats_output_name(items)
// ADR-0453: an aggregating subclause (ORDER BY key or WHERE
// predicate) recomputes over a group — the sink parks keys per
// incoming row, so it declines and the aggregation path answers.
|| order.iter().any(|o| is_agg_expr(&o.expr))
|| where_clause.is_some_and(is_agg_expr)
{
return None;
}
// A `WITH` filter runs later, on the projected row. When it names a
// variable the projection does not produce, the ordinary path has to
// keep that binding (pre-projection scope).
if let Some(predicate) = where_clause {
let produced: HashSet<String> = projection_names(items).into_iter().collect();
if !expr_within(predicate, &produced) {
return None;
}
}
// The decline chain above has already rejected every aggregating form
// (an explicit `GROUP BY`, any aggregate item or subclause) and every
// `*` item, so only `pages_eagerly`'s paging half is left to ask.
if pages_eagerly(&fields) {
return None;
}
Some(SinkProjection::new(graph, fields))
}
/// Evaluate `projection` against `row` and keep only those values, plus the
/// order keys the later sort reads. `row` itself is not retained.
pub(crate) fn finish_match_row(
graph: &ExecGraph<'_>,
row: &Row,
projection: &SinkProjection<'_>,
params: &BTreeMap<String, Value>,
) -> Result<Row> {
// Each item evaluated once against the incoming row. The result
// columns are the projection's precomputed names, so the row's schema
// is an `Arc` clone. The buffer is reserved to that column count:
// `collect::<Result<Vec<_>>>()` reports a size hint of 0, and the
// first push of a `Value` then allocates four slots. A one-column
// expand kept the spare three, which the ledger does not charge.
let mut values = Vec::with_capacity(projection.names.names().len());
for item in projection.fields.items {
values.push(eval(graph, row, &item.expr, params)?);
}
// `ORDER BY` keys read the projected row: the incoming bindings with
// each item's value written over its output name. Without a key there
// is no scope row to build — the parked values follow the items, and
// the output schema already carries their columns.
if !projection.order.is_empty() {
// shortcut: the scope schema depends on the incoming row's, so this
// path still appends (and interns) per row; cache a per-sink scope
// schema if ORDER BY lands on a hot expansion.
let mut scope = row.clone();
for (name, value) in projection.item_names().iter().zip(&values) {
scope.insert(name.clone(), value.clone());
}
let parked = parked_values(&projection.order, &scope, |expr, scope| {
eval(graph, scope, expr, params)
})?;
values.extend(parked);
}
Ok(Row::from_names(&projection.names, values))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use relate_front::parse_and_lower;
use relate_ir::Query;
use crate::exec::test_support::exec_cypher;
use crate::graph::Graph;
use crate::row::interned_schema_calls;
use super::*;
/// The sink projection a lone `RETURN` clause yields — the shape the
/// match sink finishes each row with.
fn projection_of(query: &Query) -> SinkProjection<'_> {
let g = Graph::default();
sinkable_projection(&ExecGraph::read(&g), &query.parts[0].clauses[0])
.expect("the RETURN clause is sinkable")
}
/// A row binding `n` to a map with the given properties.
fn row_with_n(props: &[(&str, Value)]) -> Row {
let map = props
.iter()
.map(|(key, value)| ((*key).to_string(), value.clone()))
.collect();
let mut row = Row::new();
row.insert("n".to_string(), Value::Map(Arc::new(map)));
row
}
fn finish(cypher: &str, row: &Row) -> Row {
let query = parse_and_lower(cypher).unwrap();
let projection = projection_of(&query);
let graph = Graph::default();
let view = ExecGraph::read(&graph);
finish_match_row(&view, row, &projection, &BTreeMap::new()).unwrap()
}
fn text(s: &str) -> Value {
Value::String(Arc::from(s))
}
#[test]
fn every_item_evaluates_against_the_incoming_row() {
// The output column `age` already exists on the incoming row; the
// item must read the incoming `n.age`, never the column it writes.
let mut row = row_with_n(&[("age", Value::Int(3))]);
row.insert("age".to_string(), Value::Int(99));
let row = finish("RETURN n.age + 1 AS age, n.age AS other", &row);
assert_eq!(row.values(), [Value::Int(4), Value::Int(3)]);
}
#[test]
fn an_alias_shadows_the_incoming_binding_of_that_name() {
let row = finish("RETURN n.name AS n", &row_with_n(&[("name", text("x"))]));
assert_eq!(row.values(), [text("x")]);
assert_eq!(row.get("n"), Some(&text("x")));
}
#[test]
fn an_order_key_reads_bindings_outside_the_projection() {
// `n` is not a projected column, so the key needs the scope row.
let row = finish(
"RETURN n.name AS name ORDER BY n.age",
&row_with_n(&[("name", text("x")), ("age", Value::Int(7))]),
);
assert_eq!(row.values(), [text("x"), Value::Int(7)]);
assert_eq!(row.get("__ord0"), Some(&Value::Int(7)));
}
#[test]
fn an_order_key_naming_a_projected_column_reads_that_column() {
// `age` is a bare variable naming a projected column, so the key is
// alias-scoped: it reads the projected value, not the item.
let row = finish(
"RETURN n.age AS age ORDER BY age",
&row_with_n(&[("age", Value::Int(3))]),
);
assert_eq!(row.values(), [Value::Int(3), Value::Int(3)]);
assert_eq!(row.get("__ord0"), Some(&Value::Int(3)));
}
#[test]
fn a_verbatim_order_key_reads_the_projected_column() {
// `ORDER BY n.age` is verbatim the item, so the implicit-grouping
// resolution answers it from that item's column.
let row = finish(
"RETURN n.age AS k ORDER BY n.age",
&row_with_n(&[("age", Value::Int(3))]),
);
assert_eq!(row.values(), [Value::Int(3), Value::Int(3)]);
}
/// Finish `cypher`'s sink row `times` times, asserting every result,
/// and report how many schemas those runs interned.
fn interning_rows(cypher: &str, times: usize) -> usize {
let query = parse_and_lower(cypher).unwrap();
let projection = projection_of(&query);
let graph = Graph::default();
let view = ExecGraph::read(&graph);
let row = row_with_n(&[("a", Value::Int(1)), ("b", Value::Int(2))]);
let before = interned_schema_calls();
for _ in 0..times {
let out = finish_match_row(&view, &row, &projection, &BTreeMap::new()).unwrap();
assert_eq!(out.values(), [Value::Int(1), Value::Int(2)]);
}
interned_schema_calls() - before
}
/// A one-column keyless row reserves one slot. The value buffer must
/// not take the four-slot first allocation of an unhinted collect.
#[test]
fn a_keyless_one_column_row_reserves_its_column_count() {
let row = finish("RETURN n.a AS a", &row_with_n(&[("a", Value::Int(1))]));
assert_eq!(row.values().len(), 1);
assert_eq!(row.values_capacity(), 1);
let wide = finish(
"RETURN n.a AS a, n.b AS b",
&row_with_n(&[("a", Value::Int(1)), ("b", Value::Int(2))]),
);
assert_eq!(wide.values_capacity(), 2);
}
/// An ordered row reserves the projected columns plus the parked key.
#[test]
fn an_ordered_projection_row_reserves_its_columns_and_key() {
let row = finish(
"RETURN n.a AS a ORDER BY n.b",
&row_with_n(&[("a", Value::Int(1)), ("b", Value::Int(2))]),
);
assert_eq!(row.values().len(), 2);
assert_eq!(row.values_capacity(), 2);
}
/// The projection path's output schema is the sink's, built once: a row
/// finished a thousand times must not intern a schema even once. (The
/// previous per-row `insert` into a cloned input row interned one per
/// new-name item — two per row for this query.)
#[test]
fn a_keyless_projection_row_interns_no_schema() {
assert_eq!(
interning_rows("RETURN n.a AS a, n.b AS b", 1_000),
0,
"a keyless projection row interns a schema per row"
);
}
/// The `ORDER BY` path builds a scope row whose schema extends the
/// incoming row's. The schema's append-link cache (REL8-2242) serves
/// every row after the first, so a thousand rows intern the schema
/// at most once — it was once per row per new-name item.
#[test]
fn an_ordered_projection_row_interns_its_scope_schema_once() {
let interned = interning_rows("RETURN n.a AS a ORDER BY n.b", 1_000);
assert!(
interned <= 1,
"the ordered scope row's schema is served by the append link, interned {interned}"
);
}
/// `n.name` and `` n.`name` `` are two distinct columns — Neo4j
/// (probed live 2026.10) names an unaliased property access by its
/// verbatim source text, so the two spellings never share one output
/// name: the projection is a plain two-column projection (sinkable
/// like any other), and the end-to-end answer carries both columns
/// with their verbatim names. Only an exact-text duplicate conflicts,
/// and the front-end's ColumnNameConflict check rejects that before
/// the sink ever sees it — so the old decline premise ("one resolved
/// column name twice") no longer arises from the grammar.
#[test]
fn two_spellings_of_one_property_are_two_columns() {
let query = parse_and_lower("RETURN n.name, n.`name`").unwrap();
let g = Graph::default();
assert!(
sinkable_projection(&ExecGraph::read(&g), &query.parts[0].clauses[0]).is_some(),
"two verbatim names are two columns: an ordinary sinkable projection"
);
// The end-to-end answer keeps both columns, verbatim names
// included — the Neo4j parity pin for the naming rule.
let graph = Graph::default();
graph.begin_write().unwrap();
graph
.create_node(
vec!["A".to_string()],
BTreeMap::from([("name".to_string(), text("x"))]),
)
.unwrap();
graph.commit_write();
let result = exec_cypher(&graph, "MATCH (n:A) RETURN n.name, n.`name`");
assert_eq!(result.columns, ["n.name", "n.`name`"]);
assert_eq!(result.rows.len(), 1);
}
}