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
//! Far-node index prefilters. Built only when the candidate set is no larger
//! than the relationship frontier already walked.
use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;
use relate_core::{NodeId, Value};
use relate_ir::{NodePattern, PathPattern};
use relate_names::SmallName;
use crate::overlay::{intersect_ids, ExecGraph};
use crate::pattern_walk::PatternMapRole;
use crate::row::Row;
use super::pushdown::Residual;
use super::semi_mask::SemiMask;
use crate::pattern_walk::{leaf_seek, pattern_props, Seek, ServedIds};
/// One far node's probe, from the cardinality decision through the built set.
enum Probe {
/// An index-served seek matched nothing. The path cannot match.
Empty,
/// A text or spatial seek, or a dirty write overlay. Build on first use.
Unpriced,
/// Counted cost. `seen` is neighbors reached before the set exists.
Pending { cost: usize, seen: usize },
/// `None` means the seeks were considered and none is index-served.
/// `Some` holds the served intersection, ascending and deduplicated
/// (every serve's contract, kept by the LABS-803 sorted-slice fold)
/// — the reject probe binary-searches it.
Ready(Option<Vec<NodeId>>),
}
struct FarNodeSeeks {
labels: Vec<String>,
seeks: Vec<Seek>,
state: RefCell<Probe>,
}
/// Far-node index prefilters, built only when they are no larger than the
/// relationship frontier about to be walked.
pub(crate) struct FarProbe {
nodes: HashMap<String, FarNodeSeeks>,
/// A prefilter set exists. Neighbor rejection stays off the probe state
/// until then: borrowing it on every neighbor regressed Q22 by about 18%
/// when no set was installed. Written only from [`Self::materialize`].
filtering: Cell<bool>,
/// Optional SemiMask SIP prefilter on a shared join variable.
semi_mask: Option<(SmallName, Rc<SemiMask>)>,
}
#[cfg(test)]
thread_local! {
static FAR_RANGE_MATERIALIZATIONS: Cell<u64> = const { Cell::new(0) };
/// Equality (`=` / `IN`) seeks the probe built a served set for.
static FAR_EQUALITY_MATERIALIZATIONS: Cell<u64> = const { Cell::new(0) };
/// The far-node index's rejections: one per candidate the prefilter
/// refused, bumped by the admission path ([`super::expand`]).
static FAR_NODE_INDEX_REJECTS: Cell<u64> = const { Cell::new(0) };
}
#[cfg(test)]
pub(super) fn count_far_node_reject() {
FAR_NODE_INDEX_REJECTS.with(|count| count.set(count.get() + 1));
}
#[cfg(test)]
pub(super) fn take_far_range_materializations() -> u64 {
FAR_RANGE_MATERIALIZATIONS.with(|count| count.replace(0))
}
#[cfg(test)]
pub(super) fn take_far_equality_materializations() -> u64 {
FAR_EQUALITY_MATERIALIZATIONS.with(|count| count.replace(0))
}
#[cfg(test)]
pub(super) fn take_far_node_index_rejects() -> u64 {
FAR_NODE_INDEX_REJECTS.with(|count| count.replace(0))
}
impl FarProbe {
pub(crate) fn prepare(
graph: &ExecGraph<'_>,
path: &PathPattern,
row: &Row,
params: &BTreeMap<String, Value>,
residual: &Residual<'_>,
) -> Self {
let mut nodes = HashMap::new();
let overlay_dirty = graph.overlay_changes_node_membership();
for node in path.nodes.iter().skip(1) {
let Some(var) = node.variable.as_ref() else {
continue;
};
if var.with_str(|text| row.contains_key(text)) {
continue;
}
// Text render, once: the prefilter's tables and the servability
// check are String-keyed.
let labels: Vec<String> = node.label_names().map(|label| label.to_string()).collect();
let seeks = far_node_seeks(graph, node, &labels, var, row, params, residual);
if seeks.is_empty() {
continue;
}
let state = initial_probe(graph, &labels, &seeks, overlay_dirty);
nodes.insert(
var.to_string(),
FarNodeSeeks {
labels,
seeks,
state: RefCell::new(state),
},
);
}
Self {
nodes,
filtering: Cell::new(false),
semi_mask: None,
}
}
/// Install a SemiMask SIP filter on a shared join variable.
pub(crate) fn install_semi_mask(&mut self, var: SmallName, mask: Rc<SemiMask>) {
self.semi_mask = Some((var, mask));
}
/// A mandatory far node is index-proven empty, so the path matches nothing.
pub(crate) fn blocks_path(&self) -> bool {
self.nodes
.values()
.any(|node| matches!(*node.state.borrow(), Probe::Empty))
}
/// `true` when this expansion's decision depends on the relationship frontier.
pub(crate) fn needs_frontier(&self, var: &str) -> bool {
let Some(node) = self.nodes.get(var) else {
return false;
};
matches!(*node.state.borrow(), Probe::Pending { .. })
}
/// Install this variable's prefilter for the expansion about to start.
/// `frontier` is [`usize::MAX`] for a variable-length walk, which does not
/// have a one-hop bound. `false` means the destination cannot match.
pub(crate) fn admit(&self, graph: &ExecGraph<'_>, var: &str, frontier: usize) -> bool {
let Some(node) = self.nodes.get(var) else {
return true;
};
// Copy the phase out so materialize can borrow the state mutably.
let step = match *node.state.borrow() {
Probe::Ready(_) => return true,
Probe::Empty => return false,
Probe::Unpriced => None,
Probe::Pending { cost, seen } => Some((cost, seen)),
};
let Some((cost, seen)) = step else {
self.materialize(graph, var);
return true;
};
// One hub can be smaller than the estimate while the expansions
// already walked are not. The set is built once that total catches
// the estimate, then reused.
if frontier >= cost || seen.saturating_add(frontier) >= cost {
self.materialize(graph, var);
} else {
*node.state.borrow_mut() = Probe::Pending {
cost,
seen: seen.saturating_add(frontier),
};
}
true
}
pub(crate) fn rejects(&self, var: &str, id: NodeId) -> bool {
if let Some((mask_var, mask)) = &self.semi_mask {
if mask_var.with_str(|text| text == var) && !mask.contains(id) {
return true;
}
}
if !self.filtering.get() {
return false;
}
let Some(node) = self.nodes.get(var) else {
return false;
};
match &*node.state.borrow() {
// The served set is ascending (every serve's contract), so
// the per-neighbor rejection is a binary search — no hash
// set materialization (LABS-803).
Probe::Ready(Some(ids)) => ids.binary_search(&id).is_err(),
Probe::Ready(None) | Probe::Empty | Probe::Unpriced | Probe::Pending { .. } => false,
}
}
fn materialize(&self, graph: &ExecGraph<'_>, var: &str) {
let Some(node) = self.nodes.get(var) else {
return;
};
// The served answers compose through the funnel's own fold —
// `ServedIds::folded` over the ascending-list intersection, the
// same spelling the OR-union pass accumulates with; the
// exactness tag is discarded on install (`into_ids`), the probe
// filters by membership only.
let mut served: Option<ServedIds> = None;
for seek in &node.seeks {
let Some(answer) = seek.serve(graph, &node.labels, None) else {
continue;
};
#[cfg(test)]
match seek {
Seek::Range(_, crate::graph::RangeSeek::Cmp { .. }) => {
FAR_RANGE_MATERIALIZATIONS.with(|count| count.set(count.get() + 1));
}
Seek::Range(_, crate::graph::RangeSeek::Eq(_) | crate::graph::RangeSeek::In(_)) => {
FAR_EQUALITY_MATERIALIZATIONS.with(|count| count.set(count.get() + 1));
}
_ => {}
}
served = Some(match served.take() {
None => answer,
Some(previous) => previous.folded(answer, intersect_ids),
});
}
if served.is_some() {
self.filtering.set(true);
}
*node.state.borrow_mut() = Probe::Ready(served.map(ServedIds::into_ids));
}
}
fn initial_probe(
graph: &ExecGraph<'_>,
labels: &[String],
seeks: &[Seek],
overlay_dirty: bool,
) -> Probe {
if overlay_dirty {
return Probe::Unpriced;
}
let mut largest = 0usize;
for seek in seeks {
match seek.cardinality(graph, labels) {
Some(0) => return Probe::Empty,
Some(n) => largest = largest.max(n),
// An equality seek served from the lazy postings has no count
// without building its pair (ADR-0614 §6). Its bucket is a
// subset of the label's ids, so the label count prices it: the
// probe then waits for the frontier like any counted seek
// instead of building whole buckets for a handful of neighbors
// on every input row.
None => {
if let Some(bound) = equality_upper_bound(graph, labels, seek) {
largest = largest.max(bound);
}
}
}
}
// A counted seek is at least one id: zero returned `Empty` above.
if largest > 0 {
Probe::Pending {
cost: largest,
seen: 0,
}
} else {
Probe::Unpriced
}
}
/// An upper bound on the ids an equality (`=` / `IN`) seek can return on a
/// labelled node: the smallest live count among its labels (each bucket is
/// a subset of every one of its labels' ids). `None` for any other seek, an
/// unlabelled node, or a count of zero — the count is a plan-time estimate
/// (ADR-0218), never proof of emptiness, so it only ever prices the probe.
fn equality_upper_bound(graph: &ExecGraph<'_>, labels: &[String], seek: &Seek) -> Option<usize> {
if !matches!(
seek,
Seek::Range(
_,
crate::graph::RangeSeek::Eq(_) | crate::graph::RangeSeek::In(_)
)
) {
return None;
}
labels
.iter()
.map(|label| graph.label_count(label))
.min()
.filter(|count| *count > 0)
.map(|count| usize::try_from(count).unwrap_or(usize::MAX))
}
fn far_node_seeks(
graph: &ExecGraph<'_>,
node: &NodePattern,
labels: &[String],
var: &SmallName,
row: &Row,
params: &BTreeMap<String, Value>,
residual: &Residual<'_>,
) -> Vec<Seek> {
let label_seekable = node.has_static_labels();
let mut seeks = Vec::new();
if label_seekable {
// The probe is lenient by design: a malformed property map just
// means no property seeks (the main funnel's typed error policy
// lives in pattern_props itself). The property-map seeks skip
// `Seek::servable` deliberately: they mirror the funnel's
// property-map lookup (`scan_ids`' label/property arm), which
// ADR-0493's crossover never gates — the crossover prices a
// WHERE window against the label scan it replaces, and the
// pattern map is that scan's own lookup. The label criterion is
// the enclosing `if`.
if let Ok(properties) = pattern_props(
graph,
row,
node.properties.as_ref(),
PatternMapRole::Match,
params,
) {
for (key, value) in properties {
seeks.push(Seek::Range(key, crate::graph::RangeSeek::Eq(value)));
}
}
}
for conjunct in residual.conjuncts {
let Some(seek) = leaf_seek(var, conjunct, graph, row, params) else {
continue;
};
if !seek.servable(graph, labels, label_seekable) {
continue;
}
seeks.push(seek);
}
seeks
}