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
//! The one live-graph [`relate_planner::PatternStats`] implementation (LABS-351): the
//! executor's compound start-element estimate consumes it directly, and
//! the top-level crate's plan-time stats adapter delegates to it, so
//! one implementation answers both consumers.
use std::collections::BTreeMap;
use std::sync::Arc;
use relate_core::Value;
use relate_ir::{BinaryOp, Expr, NodePattern, PathPattern, RelPattern};
use relate_names::{NamedToken, SmallName, Token, TokenResolver};
use relate_planner::{
endpoint_estimate, seed_on_rel_start, walk_cost, Basis, Bound, ContainsCount, DegreeMoments,
KeyStats, Provenance, RowEstimate,
};
use crate::graph::{key_heavy_count, key_value_admitted, Graph};
/// A start's walked row estimate with the trust of the figure it was
/// walked from (ADR-0694's provenance): the rows are what strategies
/// compare, the basis only gates a strategy or breaks a tie between
/// prices that are equal, never overrides a strictly cheaper row count.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct StartEstimate {
pub(crate) rows: u64,
pub(crate) basis: Basis,
}
impl StartEstimate {
/// The one price ordering: fewer rows first, then the more
/// trustworthy basis. Every start choice ranks by it, so no chooser
/// carries its own tie policy.
pub(super) fn key(self) -> (u64, std::cmp::Reverse<Basis>) {
(self.rows, std::cmp::Reverse(self.basis))
}
/// The cheaper of two prices; an equal price keeps the more
/// trustworthy basis (a tie-break, never an override of fewer rows).
pub(super) fn cheaper(self, other: StartEstimate) -> StartEstimate {
if other.key() < self.key() {
other
} else {
self
}
}
}
/// Construction goes through [`GraphStats::new`] (the ADR-0218 one-
/// construction idiom the sibling plan-time stats impls use), so an
/// inline build cannot drift from it.
pub struct GraphStats<'a> {
graph: &'a Graph,
params: &'a BTreeMap<String, Value>,
}
impl<'a> GraphStats<'a> {
/// The one construction: the connection's graph and the statement's
/// parameters.
pub fn new(graph: &'a Graph, params: &'a BTreeMap<String, Value>) -> GraphStats<'a> {
GraphStats { graph, params }
}
/// One element's compound start estimate (LABS-351): the planner's
/// canonical endpoint ladder over this graph's stats, mapped onto
/// the one u64 scale the executor compares. The rank sentinels
/// share the measured scale (`direction_cost` compares them
/// directly); the bare rank — an unlabeled element, an all-node
/// scan — stays the whole-graph sentinel. A sampled `CONTAINS` seed
/// compounds (ADR-0474): its first hop is the degree-scaled output
/// floored at the whole-label scan the unseekable filter pays, the
/// same arithmetic the planner's `direction_cost` runs, so the
/// per-row start selection and the plan-time orientation agree on
/// the anchor (GBL SF0.1 q8: the Forum side's 13,750-row scan floor
/// ties Person's degree-scaled walk and the tie-break's seed
/// comparison — 1,528 Person rows against the floored 13,750 —
/// flips the anchor to Person).
pub(crate) fn estimate<'c>(
&self,
np: &'c NodePattern,
bound: Bound<'_>,
where_conjuncts: impl Iterator<Item = &'c Expr> + Clone,
first_hop: Option<&RelPattern>,
reversed: bool,
) -> StartEstimate {
let estimate = endpoint_estimate(np, bound, where_conjuncts, self);
let basis = estimate.basis();
// Two local facts: the orientation flag is the caller's derived
// one (the forward walker passes false, the backward walker's
// k > 0 pivots pass true — LABS-426), and the walk prices this
// start's first hop only. The model itself — which estimate kind
// gets which walk, and the seed-side derivation — is
// [`walk_cost`]'s and [`seed_on_rel_start`]'s to state.
let rows = walk_cost(
estimate,
first_hop
.into_iter()
.map(|rel| (np, rel, seed_on_rel_start(rel, reversed))),
self,
);
StartEstimate {
rows: rows.min(u64::MAX as u128) as u64,
basis,
}
}
}
/// One element's degree-scaled start estimate with its adjacent first
/// hop — the comparison both start selections run, spelled once
/// (stellar F-1-1/F-1-2/F-1-4): the bound-pivot gate and
/// `cheapest_start` rank candidates with the same numbers. Element 0's
/// first hop is the path's first rel; element k walks `rels[k - 1]`
/// backward. Element 0 is the start node the parsed-pattern invariant
/// guarantees (F-8-4's boundary, stated once here). `choose_start`'s ranker and the hub join's cost gate are
/// its callers, and the hub join's cost gate prices a pair's side B with it.
pub(super) fn element_estimate<'a>(
stats: &GraphStats<'_>,
path: &'a PathPattern,
bound: relate_planner::Bound<'_>,
conjuncts: impl Iterator<Item = &'a relate_ir::Expr> + Clone,
k: usize,
) -> StartEstimate {
// The walk, derived once (round 2, F-2-1: one branch on `k == 0`, not
// three spellings of it): k == 0 is the forward walker (seed
// nodes[0], hop rels[0]); k > 0 is the backward walker's pivot
// candidate — the walk from nodes[k] back through rels[k-1], the
// reversed evaluation of the planned spelling (LABS-426).
// `nodes[k]` exists for every k the callers pass (the parsed-pattern
// invariant: one more node than rels, index 0 the start node).
let np = &path.nodes[k];
let first_hop = path.rels.get(k.saturating_sub(1));
let reversed = k > 0;
stats.estimate(np, bound, conjuncts, first_hop, reversed)
}
impl GraphStats<'_> {
/// The store id of a name beside its planning token (ADR-0541): `Id`
/// answers it, `Absent` answers `None` without a store read, and only
/// `Unresolved` interns by name. `None` means no stored entity
/// carries the name.
fn id_of(&self, name: &SmallName, token: Token) -> Option<u32> {
token.id_or_else(|| name.with_str(|text| self.graph.resolve(text).id()))
}
/// The interned `(label, property)` ids of a value-keyed consult; `None`
/// when either side was never interned.
fn pair_ids(&self, label: &NamedToken, property: &NamedToken) -> Option<(u32, u32)> {
Some((
self.id_of(&label.0, label.1)?,
self.id_of(&property.0, property.1)?,
))
}
/// A declared index's posting length for the equality: its postings
/// are a superset of the live values (ADR-0018: superseded versions
/// stay until the next prune), so an upper bound.
fn index_estimate(&self, lid: u32, kid: u32, value: &Value) -> Option<RowEstimate> {
let rows = self.graph.pattern_equality_rows_by_id(lid, kid, value)?;
Some(RowEstimate {
rows,
provenance: Provenance::UpperBound,
})
}
/// The key's sketches: a heavy value answers with its own count and any
/// other with the admitted values spread over the distinct count. A
/// value the type gate declines (a null, a NaN, long text, a list) is
/// unmeasured: the sketches never saw such a value.
fn sketch_estimate(&self, lid: u32, kid: u32, value: &Value) -> Option<RowEstimate> {
if !key_value_admitted(value) {
return None;
}
let stats = self.graph.key_stats(lid, kid)?;
let rows = stats.equality_rows(
key_heavy_count(&stats, value),
self.graph.label_count_by_id(lid),
);
Some(RowEstimate {
rows,
provenance: stats.provenance,
})
}
/// The one by-name read of a (label, property) pair: the pair as text
/// for the name-keyed store path, or `None` for an `Absent` label (a
/// plan-time fact: the store never interned it) before any store read.
/// The caller picks what an absent label means for its figure.
fn with_label_property<R>(
&self,
(label, label_token): &NamedToken,
property: &NamedToken,
read: impl FnOnce(&str, &str) -> R,
) -> Option<R> {
if *label_token == Token::Absent {
return None;
}
Some(label.with_str(|label_text| {
property
.0
.with_str(|property_text| read(label_text, property_text))
}))
}
/// The interned ids of `rel_types`; a name the store never interned
/// selects nothing, so it drops out (the moments' "selects nothing"
/// contract, not a fabricated id).
fn type_ids(&self, rel_types: &[NamedToken]) -> Vec<u32> {
rel_types
.iter()
.filter_map(|(name, token)| self.id_of(name, *token))
.collect()
}
/// The one per-label scaffold the degree figures share: resolve the
/// type names, price the type selection (`None` when no type is named:
/// every type) over each named label — a label the store never
/// interned selects nothing, so it prices as `T::default()` — or over
/// every label (`None` label id) when no label is named, and keep the
/// smallest per-label figure, the tighter bound on a node carrying all
/// the labels (the `degree_tail` min discipline).
fn min_over_labels<T: Default>(
&self,
labels: &[NamedToken],
rel_types: &[NamedToken],
price: impl Fn(Option<u32>, Option<&[u32]>) -> T,
size: impl Fn(&T) -> u128,
) -> Option<T> {
let type_ids = self.type_ids(rel_types);
let types = (!rel_types.is_empty()).then_some(type_ids.as_slice());
if labels.is_empty() {
return Some(price(None, types));
}
labels
.iter()
.map(|(name, token)| {
self.id_of(name, *token)
.map_or_else(T::default, |id| price(Some(id), types))
})
.min_by_key(size)
}
}
impl relate_planner::PatternStats for GraphStats<'_> {
fn label_rows(&self, (name, token): &NamedToken) -> Option<u64> {
Some(
self.id_of(name, *token)
.map_or(0, |id| self.graph.label_count_by_id(id)),
)
}
fn equality_rows(
&self,
(label, label_token): &NamedToken,
property: &NamedToken,
value: &Expr,
) -> Option<u64> {
let value = value.seek_value(self.params)?;
let lid = self.id_of(label, *label_token)?;
let kid = self.id_of(&property.0, property.1)?;
self.graph.pattern_equality_rows_by_id(lid, kid, &value)
}
/// ADR-0486: the range window's posting-length count, delegated to
/// [`Graph::pattern_range_rows`] — the same `range_seek_cardinality`
/// the executor's own seek cardinality reads, so the ladder's price
/// and the runtime funnel decline together. The bound resolves the
/// `equality_rows` way: literals and parameters only, `None` for
/// anything else (a temporal literal's function call included — the
/// funnel's `eval`-resolved bound is the runtime's, not the
/// plan-time estimate's).
fn range_rows(
&self,
label: &NamedToken,
property: &NamedToken,
op: BinaryOp,
bound: &Expr,
) -> Option<u64> {
let bound = bound.seek_value(self.params)?;
// The one by-name fallback: the range seek's owned forms are
// names, so a resolved label still reads through the name-keyed
// store path; an `Absent` label declines before any store read.
self.with_label_property(label, property, |label_text, property_text| {
self.graph
.pattern_range_rows(label_text, property_text, op, &bound)
})
.flatten()
}
/// LABS-643: the count is always measurable — the TEXT index's exact
/// answer, or without one the sampled estimate
/// ([`Graph::pattern_contains_rows`]) — so only a non-string needle
/// stays unmeasured (`None`, the ladder's fallback). The provenance
/// stays typed in [`ContainsCount`]; the planner compounds the
/// sampled form's scan floor on its one scale (ADR-0474). The sample
/// rides the name-keyed store path like `range_rows`; an `Absent`
/// label is the measurable zero the by-name path answers for a label
/// never interned.
fn contains_rows(
&self,
label: &NamedToken,
property: &NamedToken,
needle: &Expr,
) -> Option<ContainsCount> {
let needle = needle.seek_value(self.params)?;
let Value::String(needle) = needle else {
return None;
};
Some(
self.with_label_property(label, property, |label_text, property_text| {
self.graph
.pattern_contains_rows(label_text, property_text, &needle)
})
.unwrap_or(ContainsCount::SampleScan { rows: 0, scan: 0 }),
)
}
/// The per-key statistics of the `(label, property)` pair, shared with
/// the graph's published entry; `None` while the label's statistics are
/// unbuilt (a consult records the build request, the pump serves it).
fn key_stats(&self, label: &NamedToken, property: &NamedToken) -> Option<Arc<KeyStats>> {
let (lid, kid) = self.pair_ids(label, property)?;
self.graph.key_stats(lid, kid)
}
/// An equality's row estimate with provenance, resolved the
/// `equality_rows` way (literals and parameters only). The sources
/// are ordered here and nowhere else: a declared index's postings
/// first, then the key's sketches.
fn equality_estimate(
&self,
label: &NamedToken,
property: &NamedToken,
value: &Expr,
) -> Option<RowEstimate> {
let value = value.seek_value(self.params)?;
let (lid, kid) = self.pair_ids(label, property)?;
self.index_estimate(lid, kid, &value)
.or_else(|| self.sketch_estimate(lid, kid, &value))
}
fn rel_type_rows(&self, (name, token): &NamedToken) -> Option<u64> {
Some(
self.id_of(name, *token)
.map_or(0, |id| self.graph.pattern_rel_type_rows_by_id(id)),
)
}
/// LABS-351: the live graph's histogram tail (the executor keeps the
/// real one; the null stats default None).
fn degree_tail(&self, label: &NamedToken, rel_type: &NamedToken) -> Option<u64> {
let label_id = self.id_of(&label.0, label.1)?;
let type_id = self.id_of(&rel_type.0, rel_type.1)?;
self.graph.pattern_degree_tail_by_id(label_id, type_id)
}
/// LABS-991: the live histograms' any-label tail.
fn any_degree_tail(&self, rel_type: Option<&SmallName>) -> Option<u64> {
match rel_type {
Some(rel_type) => rel_type.with_str(|text| self.graph.pattern_type_degree_tail(text)),
None => self.graph.pattern_any_degree_tail(),
}
}
/// The live histograms' out-degree moments, bounded per label by
/// [`GraphStats::min_over_labels`].
fn degree_moments(
&self,
labels: &[NamedToken],
rel_types: &[NamedToken],
) -> Option<DegreeMoments> {
self.min_over_labels(
labels,
rel_types,
|label_id, types| self.graph.pattern_degree_moments(label_id, types),
|moments| moments.sum,
)
}
/// The live pair counts' in-degree sum, bounded the same way as
/// [`PatternStats::degree_moments`]: the smallest per-label sum.
fn in_degree_sum(&self, labels: &[NamedToken], rel_types: &[NamedToken]) -> Option<u128> {
self.min_over_labels(
labels,
rel_types,
|label_id, types| self.graph.pattern_in_degree_sum(label_id, types),
|sum| *sum,
)
}
}