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
//! The declared indexes' seek family: the shared drain-scan-intersect-recheck
//! driver ([`Graph::lookup_indexed`]), the text, range and spatial seeks over
//! it, and the posting-length cardinalities the planner prices them with.
//! The pair wiring (build, drain, drop) these read stays in the parent.
use std::collections::{BTreeMap, HashSet};
use relate_core::{NodeId, Value};
use super::index_lookup::RecheckSpec;
use super::index_postings::EqualityRoute;
use super::order::{self, RangeSeek, SpatialSeek};
use super::{intersect_acc, point, text, DrainState};
use crate::graph::*;
impl Graph {
/// The shared seek: drain each indexed label's pair, scan it, intersect
/// across labels, and re-check the snapshot. `scan` returns `None` to
/// decline (the caller scans), as does a pair that vanished between
/// `indexed_labels` and here — a concurrent `DROP INDEX` must not be
/// reported as zero rows.
fn lookup_indexed<St: DrainState>(
&self,
pairs: &CoreMap<(u32, u32), St>,
labels: &[String],
key: &str,
ts: u64,
scan: impl Fn(&St) -> Option<HashSet<NodeId>>,
pred: impl Fn(&Value) -> bool,
) -> Option<Vec<NodeId>> {
let (kid, lids) = self.indexed_labels(labels, key, pairs)?;
let mut acc: Option<HashSet<NodeId>> = None;
for lid in lids {
self.drain_pair(pairs, lid, kid);
let st = pairs.get(&(lid, kid))?;
let next = scan(&st)?;
drop(st);
intersect_acc(&mut acc, next);
}
Some(self.finish_ids(acc.into_iter().flatten(), labels, key, ts, pred))
}
pub(in crate::graph) fn lookup_text_contains(
&self,
labels: &[String],
key: &str,
needle: &str,
ts: u64,
) -> Option<Vec<NodeId>> {
let grams = text::query_grams(needle)?;
self.lookup_indexed(
&self.indexes.gram_pairs,
labels,
key,
ts,
|st| Some(text::intersect_grams(st, &grams)),
|v| v.as_string().is_some_and(|s| s.contains(needle)),
)
}
pub(in crate::graph) fn lookup_text_prefix(
&self,
labels: &[String],
key: &str,
prefix: &str,
ts: u64,
) -> Option<Vec<NodeId>> {
self.lookup_indexed(
&self.indexes.range_pairs,
labels,
key,
ts,
|st| Some(order::prefix_ids(&st.order, prefix)),
|v| v.as_string().is_some_and(|s| s.starts_with(prefix)),
)
}
pub(crate) fn lookup_range_seek(
&self,
labels: &[String],
key: &str,
seek: &RangeSeek,
ts: u64,
) -> Option<Vec<NodeId>> {
match seek {
// The two equality shapes differ only in their values
// slice; the one route decision ([`Self::eq_serve`]) holds
// the declared-then-postings precedence.
RangeSeek::Eq(v) => self.eq_serve(labels, key, std::slice::from_ref(v), ts),
RangeSeek::In(vs) => self.eq_serve(labels, key, vs, ts),
RangeSeek::Cmp { op, bound } => {
order::order_key(bound)?;
let op = *op;
self.lookup_indexed(
&self.indexes.range_pairs,
labels,
key,
ts,
// A stored temporal outside the order-key window is not
// posted; the index cannot answer a comparison then.
|st| {
st.unbounded
.is_empty()
.then(|| order::range_ids(&st.order, op, bound))
},
|v| order::cmp_holds(v, op, bound),
)
}
}
}
/// The `=`/`IN` id seek, one route decision (ADR-0614): the
/// declared postings (ordered, no lazy build) when a declared pair
/// covers the key; the lazy equality postings when the values pass
/// the decline predicate; `None` otherwise — the caller scans.
/// ADR-0665 A/B (measured warm/cold ordering): a declared pair
/// always outranks the attached experimental store; behind the
/// declared arm the store's sorted `(key,row)` side-file preempts a
/// COLD lazy pair (its build was paid at attach, the postings'
/// build is paid at first serve) while a warm pair keeps the
/// engine arm — its probe beats the side-file seek. A decline falls
/// through to the arm.
fn eq_serve(
&self,
labels: &[String],
key: &str,
values: &[Value],
ts: u64,
) -> Option<Vec<NodeId>> {
match self.values_equality_route(labels, key, values) {
EqualityRoute::Declared => self.lookup_range_values(labels, key, values, ts),
EqualityRoute::Postings => {
if !self.postings_pair_ready(labels, key) {
if let Some(ids) = self.prop_store_equality(labels, key, values, ts, None) {
return Some(ids);
}
}
Some(self.equality_postings_values(labels, key, values, ts))
}
EqualityRoute::Scan => self.prop_store_equality(labels, key, values, ts, None),
}
}
/// Upper bound on the ids [`Self::lookup_range_seek`] would collect from
/// the index, counted from posting lengths. `None` when the index cannot
/// serve the predicate. A comparison with unbounded temporal postings
/// declines, matching the id seek. The bound is not snapshot-filtered.
pub(crate) fn range_seek_cardinality(
&self,
labels: &[String],
key: &str,
seek: &RangeSeek,
) -> Option<usize> {
match seek {
// The two equality shapes differ only in their values
// slice; the one route decision
// ([`Self::eq_cardinality`]) holds the declared-only rule.
RangeSeek::Eq(v) => self.eq_cardinality(labels, key, std::slice::from_ref(v)),
RangeSeek::In(vs) => self.eq_cardinality(labels, key, vs),
RangeSeek::Cmp { op, bound } => {
order::order_key(bound)?;
let op = *op;
self.range_pair_cost(labels, key, |st| {
st.unbounded
.is_empty()
.then(|| order::range_count(&st.order, op, bound))
})
}
}
}
/// Work upper bound for one range seek across the indexed labels. `Some(0)`
/// when any label posts nothing, because the label intersection is empty.
fn range_pair_cost(
&self,
labels: &[String],
key: &str,
count: impl Fn(&order::RangeIndex) -> Option<usize>,
) -> Option<usize> {
let (kid, lids) = self.indexed_labels(labels, key, &self.indexes.range_pairs)?;
let mut cost = 0usize;
for lid in lids {
self.drain_pair(&self.indexes.range_pairs, lid, kid);
let st = self.indexes.range_pairs.get(&(lid, kid))?;
let n = count(&st)?;
if n == 0 {
return Some(0);
}
cost = cost.saturating_add(n);
}
Some(cost)
}
/// The `=`/`IN` cardinality: declared posting lengths only — the
/// postings route has no count-without-build (ADR-0614 §6), so it
/// answers `None` exactly as the scan route does and the caller
/// keeps the eager probe.
fn eq_cardinality(&self, labels: &[String], key: &str, values: &[Value]) -> Option<usize> {
match self.values_equality_route(labels, key, values) {
EqualityRoute::Declared => self.range_values_cardinality(labels, key, values),
EqualityRoute::Postings | EqualityRoute::Scan => None,
}
}
/// True when a declared RANGE index covers `(labels, key)` — the
/// single-key form of [`Self::range_serves_equality`]'s map form,
/// the WHERE-form seek's half of the route decision.
pub(crate) fn range_serves_key(&self, labels: &[String], key: &str) -> bool {
self.indexed_labels(labels, key, &self.indexes.range_pairs)
.is_some()
}
fn range_values_cardinality(
&self,
labels: &[String],
key: &str,
values: &[Value],
) -> Option<usize> {
let mut total = 0usize;
let mut served = false;
for value in values {
if GroupKey::for_property_index(value).is_none() {
continue;
}
let n =
self.range_pair_cost(labels, key, |st| Some(order::equality_count(st, value)))?;
served = true;
total = total.saturating_add(n);
}
served.then_some(total)
}
fn lookup_range_values(
&self,
labels: &[String],
key: &str,
values: &[Value],
ts: u64,
) -> Option<Vec<NodeId>> {
let (kid, lids) = self.indexed_labels(labels, key, &self.indexes.range_pairs)?;
let mut matched = HashSet::new();
for v in values {
if GroupKey::for_property_index(v).is_none() {
continue;
}
let mut acc: Option<HashSet<NodeId>> = None;
for lid in &lids {
let ids = self.range_equality_ids(*lid, kid, v)?;
intersect_acc(&mut acc, ids);
}
if let Some(ids) = acc {
matched.extend(ids);
}
}
Some(self.finish_ids(matched, labels, key, ts, |v| {
values.iter().any(|b| v.eq_non_null(b))
}))
}
/// The capped form of the declared equality seek: the matches of
/// `labels` and `props` among the postings of the shortest-posting
/// `(label, property)` pair, stopping at `cap + 1` matches. No id set
/// is built and no posting is read past the stop; each posting read
/// is one node read, counted as examined. Every candidate is checked
/// against the snapshot at `ts` with [`Graph::node_matches`], the
/// predicate the unbounded seek's re-check applies. `None` when a pair
/// vanished (a concurrent `DROP INDEX`): the caller scans instead.
pub(in crate::graph) fn range_equality_upto(
&self,
labels: &[String],
props: &BTreeMap<String, Value>,
ts: u64,
cap: usize,
) -> Option<Vec<NodeId>> {
let mut best: Option<(usize, u32, u32, &Value)> = None;
for (key, value) in props {
if GroupKey::for_property_index(value).is_none() {
return Some(Vec::new());
}
let Some(kid) = self.interner.get_id(key) else {
return Some(Vec::new());
};
for label in labels {
let Some(lid) = self.interner.get_id(label) else {
continue;
};
if !self.indexes.range_pairs.contains_key(&(lid, kid)) {
continue;
}
self.drain_pair(&self.indexes.range_pairs, lid, kid);
let st = self.indexes.range_pairs.get(&(lid, kid))?;
let count = order::equality_count(&st, value);
if best.is_none_or(|(least, ..)| count < least) {
best = Some((count, lid, kid, value));
}
}
}
let (_, lid, kid, value) = best?;
let st = self.indexes.range_pairs.get(&(lid, kid))?;
let spec = RecheckSpec {
labels,
props,
ts,
cap: Some(cap),
};
let mut walk = self.recheck_walk(&spec);
order::equality_each(&st, value, |id| walk.visit(id));
Some(walk.finish())
}
/// The length of [`Self::range_equality_ids`]'s answer, read from the
/// bucket's own length: the planner's per-row start estimate prices
/// an equality with it, and building the id set to count it made that
/// estimate O(bucket) on every input row.
pub(in crate::graph) fn range_equality_count(
&self,
lid: u32,
kid: u32,
value: &Value,
) -> Option<usize> {
self.drain_pair(&self.indexes.range_pairs, lid, kid);
let st = self.indexes.range_pairs.get(&(lid, kid))?;
Some(order::equality_count(&st, value))
}
/// Drain the range pair and read its equality postings. `None` when the
/// pair vanished (a concurrent `DROP INDEX`), so the caller scans
/// instead of reporting zero rows.
pub(in crate::graph) fn range_equality_ids(
&self,
lid: u32,
kid: u32,
value: &Value,
) -> Option<HashSet<NodeId>> {
self.drain_pair(&self.indexes.range_pairs, lid, kid);
let st = self.indexes.range_pairs.get(&(lid, kid))?;
Some(order::equality_ids(&st, value))
}
pub(crate) fn lookup_spatial_seek(
&self,
labels: &[String],
key: &str,
seek: &SpatialSeek,
ts: u64,
) -> Option<Vec<NodeId>> {
self.lookup_indexed(
&self.indexes.point_pairs,
labels,
key,
ts,
|st| Some(point::spatial_ids(st, seek)),
|v| point::spatial_holds(v, seek),
)
}
/// True when every property has a range index on at least one pattern label.
pub(in crate::graph) fn range_serves_equality(
&self,
labels: &[String],
props: &BTreeMap<String, Value>,
) -> bool {
if labels.is_empty() || props.is_empty() {
return false;
}
props.keys().all(|k| {
labels.iter().any(|l| {
self.string_pair_id(l, k)
.is_some_and(|pk| self.indexes.range_pairs.contains_key(&pk))
})
})
}
}