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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! `MATCH` clause driver: the operator ladder that picks how a clause
//! runs (batch chain, contracted kernel, or this module's row loop), the
//! row loop itself, the OPTIONAL-miss null binder, and the per-pattern
//! loop. The
//! predicate-filter policy the row loop consults lives one module down,
//! in `predicates`; the one engine fork each per-path dispatch routes
//! through lives in [`super::one_path`]; the LABS-348 hub join the
//! multi-pattern loop tries at its pattern-0→pattern-1 boundary lives
//! in [`super::hub_join`]. The classic walker's terminal named-path
//! binder ([`super::named_path::bind_named_path`]) lives beside its one
//! caller in `named_path`, so this driver's reads stay strictly downward.
use relate_core::Result;
use relate_ir::{Clause, Expr, MatchMode, PathPattern};
use crate::ctx::ExecCtx;
use crate::eval::candidate_passes;
use crate::frontier_decline::FrontierDeclineReason;
use crate::metrics::KernelRung;
use crate::overlay::ExecGraph;
use crate::row::{Row, RowRung};
use crate::UsedSet;
use super::batch::try_scan_filter_batch;
use super::hub_join::hub_join_answer;
use super::kernels;
use super::kernels::frontier_run::FrontierRows;
use super::one_path::{match_one_path, ResolvedPatterns};
use super::pattern_policies::binds_a_null_in_any;
use super::pattern_policies::{MatchReduce, MatchTail, ReduceSink, RowFold};
use super::pushdown::{flatten_and_owned, match_scope, MatchCap, Residual};
use super::rider::Rider;
use super::sink::{finish_match_row, SinkProjection};
/// The pattern-0→pattern-1 boundary: the second pattern's turn in the loop
/// is where the hub join is tried, with the loop's own pattern-0 rows as
/// side A.
const HUB_JOIN_BOUNDARY: usize = 1;
/// Which operator took one `MATCH` clause down the ladder — the one
/// operator-state vocabulary (LABS-1117). The two facts the dispatcher
/// records project from this single value: [`MatchOperator::BatchChain`]
/// is the ADR-0468 `batched` fact, and [`MatchOperator::Rung`] carries
/// the clause's `KernelRung` (the walker included). The ladder returns
/// it, so a nested evaluation cannot contribute or overwrite one.
#[derive(Clone, Copy)]
pub(crate) enum MatchOperator {
/// ADR-0468 (LABS-359): the batch scan/filter/project chain over
/// `Chunk`.
BatchChain,
/// The traversal rung that served the clause: a contracted kernel
/// (ADR-0473), the frontier rung (ADR-0478), or the per-row walker
/// (every decline's home).
Rung(KernelRung),
}
/// The ladder's two non-row facts, one value the dispatcher carries to the
/// PROFILE tick: the operator that served the clause, and why the frontier
/// family did not (LABS-1437: the plan-time gate or the run-time decline).
/// Like the operator, the decline travels in the return value, so a nested
/// evaluation's ladder run cannot contribute or overwrite the enclosing
/// clause's.
#[derive(Clone, Copy)]
pub(crate) struct LadderFacts {
pub(crate) operator: MatchOperator,
pub(crate) frontier_decline: Option<FrontierDeclineReason>,
}
impl LadderFacts {
/// A clause the per-row walker runs without the ladder (a `SEARCH`
/// `MATCH`): the walker's rung, no frontier decline.
pub(crate) fn walker() -> Self {
LadderFacts {
operator: MatchOperator::Rung(KernelRung::Walker),
frontier_decline: None,
}
}
}
/// What the operator ladder returns: the clause's rows and the
/// [`LadderFacts`] that describe how they were produced.
pub(crate) struct LadderRun {
pub(crate) rows: Vec<Row>,
pub(crate) facts: LadderFacts,
}
/// The clause inputs the operator ladder reads, bundled so the ladder's
/// signature carries one value for the `MATCH` clause itself beside the
/// statement context (the cap, projection, suffix and fold).
#[derive(Clone, Copy)]
pub(crate) struct MatchClauseInputs<'a> {
pub(crate) optional: bool,
pub(crate) match_mode: MatchMode,
pub(crate) patterns: &'a [PathPattern],
pub(crate) where_clause: Option<&'a Expr>,
}
impl MatchOperator {
/// Whether the operator hands the dispatch layer a finished,
/// **uncharged** container (ADR-0463, LABS-1077): the batch chain and
/// the contracted chain/hub-star kernels build the whole container
/// before returning, so the dispatcher charges its rows at the
/// landing — while the walker (`match_clause.rs`) and the frontier
/// rung (`frontier_run.rs`) charge every row at their own emission
/// points and arrive charged. The one spelling of the
/// charge-ownership fact, spelled exhaustively — a later rung fails
/// compilation here until its charge owner is decided, never
/// inheriting a silent default.
pub(crate) fn hands_dispatch_a_finished_container(&self) -> bool {
match self {
MatchOperator::BatchChain
| MatchOperator::Rung(KernelRung::Chain { .. })
| MatchOperator::Rung(KernelRung::HubStar) => true,
// The self-charging rungs: their emission points charge
// every row before it lands, so their containers arrive
// already charged.
MatchOperator::Rung(KernelRung::FrontierNfa)
| MatchOperator::Rung(KernelRung::Walker) => false,
}
}
}
/// Run one `MATCH` clause the folds declined down the operator ladder:
/// the frontier family (ADR-0478) first, then the batch scan/filter/
/// project chain (ADR-0468), then the contracted kernels (ADR-0473),
/// then the per-row walker below — the first operator that takes the
/// clause owns it, and every decline falls through unchanged to the
/// walker. The frontier rung sits first on its own gate: it serves the
/// quantified shapes every rung below structurally declines, and its
/// answer-shape proof reads the statement's suffix (`suffix`) — the
/// capped and distinct-endpoint consumers ride plain caps and sink
/// projections the shared gate below excludes, so it cannot live behind
/// that gate. The two rungs below share one admission gate, computed
/// once: no cap and no sink projection, because a cap's and a sink's
/// semantics live in the walker. The plain limit cap is the gate's one
/// exception: it yields to a specialized operator for exactly the shapes
/// that operator proves, while the distinct and ordered caps never
/// yield. The batch chain takes the cap's want as its halt (LABS-1452):
/// it stops scanning once that many kept rows exist, so a `LIMIT` over a
/// scan reads one batch, not the graph; the contracted kernel takes
/// it as its rows-mode halt (LABS-990, ADR-0524) — the want rides, the
/// kernel's final collection stops at it, and a shape the kernel
/// declines keeps the cap at the walker, whose sink applies it.
pub(crate) fn run_match_operator_ladder(
ctx: ExecCtx<'_>,
mut rows: Vec<Row>,
clause: MatchClauseInputs<'_>,
mut cap: Option<MatchCap<'_>>,
projection: Option<&SinkProjection<'_>>,
suffix: &[Clause],
fold: Option<&dyn RowFold>,
) -> Result<LadderRun> {
let MatchClauseInputs {
optional,
match_mode,
patterns,
where_clause,
} = clause;
// A name an earlier clause bound to null matches nothing in any pattern
// of this clause (REL8-2023 issue 34; `pattern_policies::binds_a_null`),
// so a plain `MATCH` loses such a row here, before any rung — the
// frontier rung runs ahead of the per-row walker, and its own `optional`
// gate keeps the optional form out of every specialized rung, where the
// walker's per-row pad emits the null-extended row.
if !optional {
rows.retain(|row| !binds_a_null_in_any(patterns, row));
}
// The frontier family's rung (ADR-0478): the quantified-path shapes
// with a pair-shaped answer contract — the capped emission, the
// distinct-endpoint answer — over the BFS that collapses the trail
// enumeration. Every decline falls through to the ladder below with
// the cap and projection untouched.
let frontier_decline = match kernels::frontier_run::try_frontier_rows(
ctx,
&rows,
optional,
match_mode,
patterns,
where_clause,
suffix,
projection,
fold,
)? {
FrontierRows::Served(rows) => {
return Ok(LadderRun {
rows,
facts: LadderFacts {
operator: MatchOperator::Rung(KernelRung::FrontierNfa),
frontier_decline: None,
},
})
}
FrontierRows::Declined(reason) => reason,
};
// The one cap classification both rungs below read: the plain cap's
// want, `Some` only for a plain cap. The gate admits the clause on
// it and the kernel rung passes it as the rows mode's halt — one
// read, so the two ends cannot drift (the ordered and distinct caps
// answer `None` and keep the walker with their semantics intact).
let plain_want = cap.as_ref().and_then(MatchCap::plain_want);
let chain_eligible = (cap.is_none() || plain_want.is_some()) && projection.is_none();
// The two finished-container rungs share the gate, and the kernel is
// tried only once the chain declined — one decision, so the second
// rung cannot drift from the first. A plain cap's want rides as the
// chain's halt (LABS-1452) and the kernel's rows-mode halt (LABS-990,
// ADR-0524). A rung that returns a finished container hands its rows
// to the fold (when one rides) right here, so the clause still
// collects nothing.
let finished = if chain_eligible {
match try_scan_filter_batch(
ctx,
&rows,
optional,
match_mode,
patterns,
where_clause,
plain_want,
)? {
Some(rows) => Some((rows, MatchOperator::BatchChain)),
None => kernels::try_match_kernel(
ctx,
&rows,
optional,
match_mode,
patterns,
where_clause,
plain_want,
)?
.map(|(rows, rung)| (rows, MatchOperator::Rung(rung))),
}
} else {
None
};
if let Some((rows, operator)) = finished {
let Some(fold) = fold else {
return Ok(LadderRun {
rows,
facts: LadderFacts {
operator,
frontier_decline,
},
});
};
fold.offer_container(ctx.graph, rows)?;
return Ok(LadderRun {
rows: Vec::new(),
facts: LadderFacts {
operator,
frontier_decline,
},
});
}
// Every rung above declined: the walker is this clause's rung, and
// the ladder's return value carries it (LABS-1117).
Ok(LadderRun {
rows: match_clause(
ctx,
rows,
optional,
match_mode,
patterns,
where_clause,
cap.as_mut(),
projection,
fold,
)?,
facts: LadderFacts {
operator: MatchOperator::Rung(KernelRung::Walker),
frontier_decline,
},
})
}
/// The dispatch layer's finished-container charge (ADR-0463, LABS-781):
/// the one bulk spelling every site that lands a finished container reads
/// — the SEARCH arm (its walker runs are per-candidate, so the
/// clause-level container is only whole — and only chargeable — at this
/// landing, and that arm charges it itself), the dispatcher's ladder arm
/// for the operators whose containers arrive uncharged (the ownership
/// predicate's `true` arms; the walker and the frontier rung charge at
/// their own emission points and arrive charged), and the ladder itself
/// for a rung's container headed to a [`RowFold`] that asks for the charge.
/// The refusal fires at ~the cap with the crossing row's honest figure.
pub(crate) fn charge_finished_container(graph: &ExecGraph<'_>, rows: &[Row]) -> Result<()> {
let mut retained = graph.retain_bytes(0)?;
for row in rows {
retained.add_row(graph, row.values())?;
}
Ok(())
}
/// The one charge-then-fold for a fold that asks for a rung container's
/// retention: the container is held whole while it is folded, so the cap
/// sees it first. Every such fold spells its `offer_container` through this
/// helper (the stage chain and both bounded sinks), and a fold that does
/// not ask — the aggregation — keeps the default row-by-row fold.
pub(crate) fn charge_and_fold(
fold: &dyn RowFold,
graph: &ExecGraph<'_>,
rows: Vec<Row>,
) -> Result<()> {
charge_finished_container(graph, &rows)?;
rows.into_iter().try_for_each(|row| fold.offer(graph, row))
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn match_clause(
ctx: ExecCtx<'_>,
rows: Vec<Row>,
optional: bool,
match_mode: MatchMode,
patterns: &[PathPattern],
where_clause: Option<&Expr>,
mut cap: Option<&mut MatchCap<'_>>,
projection: Option<&SinkProjection<'_>>,
fold: Option<&dyn RowFold>,
) -> Result<Vec<Row>> {
let ExecCtx { graph, params, .. } = ctx;
let mut out = Vec::new();
// ADR-0463 (LABS-781, OPLANE_REQ-00345609): the walker's output
// container is a retaining container — each row charges the
// expression budget through the one `add_row` spelling as it
// lands, ahead of the landing. The frontier row rung charges its
// own emission points the same way (frontier_run.rs); the batch
// chain and the contracted kernels hand the dispatch layer a
// finished container, which charges there (see dispatch.rs).
let mut out_retained = graph.retain_bytes(0)?;
let conjuncts = where_clause.map(flatten_and_owned).unwrap_or_default();
// The clause filter runs in the walk's sink — once per row, ahead
// of any cap's count — when the sink projects, and when a cap rides
// a `WHERE`-bearing walk (LABS-853). The placement is the cap
// module's one policy (`sink_filters_clause`), not a local boolean:
// the plain cap's count is exact only because the two ends agree.
let sink_filters =
super::match_cap::sink_filters_clause(projection, cap.as_deref(), where_clause);
// A fold takes the rows after the same checks, so it rides the reduce
// whether or not the sink projects.
let reduce = (sink_filters || fold.is_some()).then_some(MatchReduce {
sink: ReduceSink::select(projection, fold),
patterns,
where_clause,
params,
});
// LABS-801: the patterns' resolved filters, built once per clause
// evaluation, not per row — each pattern carries its tier state too,
// which the shortest-path route shares between rows (its reach cache).
// The graph is read-only for the whole loop.
let resolved = ResolvedPatterns::resolve(graph, patterns, match_mode);
for row in rows {
graph.cancel_tick()?;
if cap.as_ref().is_some_and(|c| c.full()) {
break;
}
let scope = match_scope(graph, &row, patterns);
let residual = Residual {
conjuncts: &conjuncts,
scope: &scope,
};
// A name an earlier clause bound to null matches nothing
// (REL8-2023 issue 34; `pattern_policies::binds_a_null`): the row is
// answered with no match here, at the walker's own per-row entry —
// where a clause-produced row is the only thing in hand — so the
// `OPTIONAL` pad below emits its null-extended row and a plain
// clause drops it. Deliberately not in the per-path fork: an
// enclosing quantification's predicate hands that fork a row that
// already carries its own element names as null placeholders
// (ADR-0335 §5), which are not clause bindings.
let mut matched = if binds_a_null_in_any(patterns, &row) {
Vec::new()
} else {
match_paths(
ctx,
&resolved,
match_mode,
row.clone(),
&residual,
cap.as_deref_mut(),
reduce.as_ref(),
)?
};
// A reduce already applied the inline predicates, the WHERE, and
// any projection in the sink.
if reduce.is_none() {
let mut filtered = Vec::with_capacity(matched.len());
for candidate in matched {
if candidate_passes(graph, patterns, where_clause, &candidate, params)? {
filtered.push(candidate);
}
}
matched = filtered;
}
// Pick the rows first, land them once: the unmatched OPTIONAL
// row (null-bound, projected when the clause carries a
// projection) or the matched rows.
let landing = if matched.is_empty() && optional {
let mut r = row;
bind_pattern_nulls(&mut r, patterns);
vec![match projection {
Some(projection) => finish_match_row(graph, &r, projection, params)?,
None => r,
}]
} else {
matched
};
for landed in landing {
out_retained.add_row(graph, landed.values())?;
out.push(landed);
}
}
Row::share_schemas(&mut out);
Ok(out)
}
pub(crate) fn bind_pattern_nulls(row: &mut Row, patterns: &[PathPattern]) {
// The pattern-bound names, collected through the scope walk's
// callback vocabulary (owned — the callback's reference is
// higher-ranked, so it cannot escape into a borrowed list) into the
// one list the rung build reads.
let mut bound_names: Vec<String> = Vec::new();
for pattern in patterns {
super::scope::for_each_pattern_bound_name(pattern, &mut |name| {
bound_names.push(name.to_string());
});
}
// The null-binding rung: this row's schema plus every pattern-bound
// name it does not already hold, in the canonical bound-name walk's
// order — built through the one per-row rung constructor
// ([`RowRung::past`], its own append accounting, never a hand-built
// row-keys list), stamped with one null per appended name. A name
// the row already binds keeps its value.
let rung = RowRung::past(row, bound_names.iter().map(|name| Some(name.as_str())));
row.stamp_nulls(&rung);
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn match_paths(
ctx: ExecCtx<'_>,
resolved: &ResolvedPatterns<'_>,
match_mode: MatchMode,
row: Row,
residual: &Residual<'_>,
mut cap: Option<&mut MatchCap<'_>>,
reduce: Option<&MatchReduce<'_>>,
) -> Result<Vec<Row>> {
// LABS-348: the base row, kept for the pattern-0→pattern-1
// boundary's hub-join attempt below — the join's shape gate reads
// the incoming row's bindings and its side-B enumeration seeds from
// it. The join is the two-pattern comma join and declines at its
// first check unless `patterns.len() == 2`, so that one width gates
// both this keep-alive clone and the boundary call: a single-pattern
// match (the common shape) and a three-pattern clause pay no clone
// for a join that cannot engage.
let patterns = resolved.paths();
let hub_join = patterns.len() == 2;
let base = hub_join.then(|| row.clone());
let mut current = vec![(row, UsedSet::default())];
let account = relate_core::tokens::workspace_accounting();
let mut batch = relate_core::tokens::WorkspaceCharge::retain_with(|| {
crate::workspace::binding_bytes(¤t)
})?;
let last = patterns.len().saturating_sub(1);
for (pi, (p, filters)) in resolved.iter().enumerate() {
// LABS-348: at the pattern-0→pattern-1 boundary, try the hub
// join — the two-pattern comma join through one shared hub
// intersects at the hub instead of re-expanding pattern 1 for
// every pattern-0 row (the nested loop re-applies the side
// filter per row: the measured adversarial shape paid 25M store
// touches for 250k result rows). `current` here is this loop's
// own pattern-0 output — exactly the plain-side rows the join's
// former private enumeration produced (same base row, same
// fresh used-set, same residual, no cap or reduce riding a
// non-last pattern, the set carried) — so a decline falls
// through to the nested loop below already holding them: the
// old Seeded/DeclinedWithoutSeed handshake is true by
// construction. `base` is Some exactly when `hub_join` holds
// (the guard above), the same fact the join's own first check
// reads.
// The join runs uncapped (a cap rides the nested loop's per-row
// boundary instead) — the third fact of the boundary tuple.
if let (HUB_JOIN_BOUNDARY, Some(base), true) = (pi, base.as_ref(), cap.is_none()) {
if let Some(out) =
hub_join_answer(ctx, patterns, match_mode, base, ¤t, residual, reduce)?
{
return Ok(out);
}
}
let mut next = Vec::new();
let mut next_charge = relate_core::tokens::WorkspaceCharge::empty();
let mut next_meter = crate::workspace::BindingMeter::default();
// Draining `current` keeps its allocation until the loop ends.
// `batch` stays reserved across that overlap and is released when
// `next_charge` replaces it, after `current` has been dropped.
let last_pat = pi == last;
// The tail is pattern-level, not row-level: decided once per
// pattern, here where its values are decided (F-1-11) — the last
// pattern finishes its rows (the reduce when the clause sink
// projects here, the used-rel carry dropped), every earlier
// pattern carries its used-set forward.
let tail = if last_pat {
MatchTail::Finish { reduce }
} else if p.is_shortest_path_function {
MatchTail::Restore
} else {
MatchTail::Carry
};
// The shortest-path function's used-set restore is pattern-level,
// like the tail (F-1-11): only patterns before the last restore
// the entering row's set, so the predicate is decided once per
// pattern and the common case clones nothing per row. The tail
// carries it too (`MatchTail::Restore`), the one spelling of the
// carry-restore-or-drop decision ([`MatchTail::store_row`]'s),
// never a second `!last_pat` encoding kept in hand-in-sync.
let keep_used = matches!(tail, MatchTail::Restore);
// LABS-801: the pattern's rel-type filters arrive resolved with
// it, from the caller's widest loop.
for (r, used) in current {
ctx.graph.cancel_tick()?;
if last_pat && cap.as_ref().is_some_and(|c| c.full()) {
break;
}
let prior_used = keep_used.then(|| used.clone());
let seed_used =
if match_mode == MatchMode::RepeatableElements || p.is_shortest_path_function {
UsedSet::default()
} else {
used
};
let mut matched = {
// The last pattern owns the cap/reduce and finishes its
// rows (the used-rel carry dropped); every earlier pattern
// carries `used` forward. The tail is decided once per
// pattern (see the hoist above); only the cap's reborrow
// is per-row.
let mut rider = if last_pat {
cap.as_deref_mut().map(Rider::Cap)
} else {
None
};
match_one_path(
ctx,
p,
filters,
r,
seed_used,
match_mode,
residual,
rider.as_mut(),
tail,
)?
};
if let Some(prior_used) = &prior_used {
for (_, used) in &mut matched {
*used = prior_used.clone();
}
}
if account {
for (row, used) in &matched {
next_meter.push(row, used.len());
}
next_charge.resize(next_meter.bytes)?;
relate_core::tokens::peak_hold("expand");
}
next.extend(matched);
}
if match_mode == MatchMode::RepeatableElements {
for (_, used) in &mut next {
used.clear();
}
if account {
next_charge.resize_with(|| crate::workspace::binding_bytes(&next))?;
relate_core::tokens::peak_hold("expand");
}
}
current = next;
batch = next_charge;
if current.is_empty() {
return Ok(Vec::new());
}
}
drop(batch);
Ok(current.into_iter().map(|(r, _)| r).collect())
}