relate-executor 1.5.0

In-memory graph and Cypher physical executor
Documentation
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
//! The frontier family's cost gate (ADR-0473's `engages()` gate extended
//! to the frontier, ADR-0478): whether the per-(node, state) frontier
//! beats the per-row DFS for one bounded quantified clause.
//!
//! The decision is a break-even between two measured unit costs, not a
//! ratio threshold: the DFS pays per *trail* it enumerates, the frontier
//! per distinct *(seed, endpoint) pair* it reports plus per adjacency
//! *probe* it issues. The inputs are estimates from the planner's stats:
//!
//! - **trails** — the first hop fans out over the start label's mean
//!   degree on the side the hop leaves it by (out, in, or both for an
//!   undirected hop), every later hop over the size-biased excess degree
//!   `sum(d^2) / sum(d) - 1` of the rel types it crosses (a trail arrives
//!   at a node in proportion to its degree); a later undirected hop sees
//!   each rel from both ends, so it counts twice (the histograms keep no
//!   in-degree moments, so a later hop is priced on out-degree alone). Summed over every hop count
//!   up to the bound, since the DFS enumerates the shorter trails too.
//!   The excess-degree model overestimates actual trails; it does not
//!   underestimate them, so a short bound that the model prices cheap is
//!   cheap.
//! - **pairs** — at most the trails, and at most seeds x the target's
//!   endpoint population.
//! - **probes** — at most the trails, and at most seeds x the
//!   adjacency entries of the first hop's rel types.
//!
//! An unbounded quantifier engages on shape alone (the DFS terminates
//! only at its rel-count cap). Statistics that cannot price the hops (no
//! histogram) keep the DFS.

use std::collections::BTreeMap;

use relate_core::{NodeId, Value};
use relate_ir::{Direction, Expr, NodePattern, PatternElement, RelPattern};
use relate_planner::{endpoint_estimate, seed_rows, DegreeMoments, PatternStats};

use crate::graph::Graph;
use crate::row::Row;

/// The DFS's measured cost per enumerated trail, in nanoseconds.
const WALKER_NS_PER_TRAIL: f64 = 1490.0;
/// The frontier's measured cost per distinct (seed, endpoint) pair.
const FRONTIER_NS_PER_PAIR: f64 = 2240.0;
/// The frontier's measured cost per adjacency probe.
const FRONTIER_NS_PER_PROBE: f64 = 65.0;

/// The estimate's hop ceiling: a bounded quantifier whose maximum
/// expansion passes it has a multiplicity saturated beyond pricing (a
/// degree tail chained per hop), so the estimate engages rather than
/// underestimates it.
pub(super) const MAX_ESTIMATE_HOPS: usize = 1024;

/// Maximum seed count for which the cost gate probes actual O(1) adjacency
/// lengths on the resolved seeds instead of relying on the label's global
/// mean degree (which underestimates hub seeds by orders of magnitude).
const ACTUAL_SEED_DEGREE_CAP: usize = 16;

/// What the DFS would enumerate and what the frontier would pay for it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct CostEstimate {
    /// Trails the DFS enumerates, over every hop count up to the bound.
    pub(super) trails: f64,
    /// Distinct (seed, endpoint) pairs the frontier reports.
    pub(super) pairs: f64,
    /// Adjacency probes the frontier issues.
    pub(super) probes: f64,
}

impl CostEstimate {
    /// Whether the frontier's priced work undercuts the DFS's.
    pub(super) fn frontier_wins(self) -> bool {
        WALKER_NS_PER_TRAIL * self.trails
            > FRONTIER_NS_PER_PAIR * self.pairs + FRONTIER_NS_PER_PROBE * self.probes
    }
}

/// The frontier family's cost gate — see the module doc. An unbounded
/// spine engages on shape alone, so the caller skips the gate for one
/// (it has no maximum hop count to price). `population` is
/// the store's node-id span, the ceiling on any endpoint count (an
/// unlabeled target's estimate is the ladder's rank sentinel, an ordering
/// fact no path count can reach).
#[allow(clippy::too_many_arguments)]
pub(super) fn frontier_engages(
    graph: &Graph,
    rows: &[Row],
    stats: &dyn PatternStats,
    conjuncts: &[Expr],
    start: &NodePattern,
    target: &NodePattern,
    elements: &[PatternElement],
    params: &BTreeMap<String, Value>,
) -> bool {
    let Some(hops) = expand_max_hops(elements) else {
        // The expansion passed the estimate's hop ceiling.
        return true;
    };
    let population =
        u128::try_from(graph.next_node_id()).expect("node ids are allocator-issued upward from 0");
    let unbound = |_: &str| false;
    let seeds = seed_rows(endpoint_estimate(start, &unbound, conjuncts.iter(), stats));
    let endpoints =
        seed_rows(endpoint_estimate(target, &unbound, conjuncts.iter(), stats)).min(population);
    let first_hop = probe_actual_first_hop_edges(graph, rows, start, &hops, seeds, params)
        .or_else(|| first_hop_level(stats, population, seeds, start, &hops));
    let Some(first_hop) = first_hop else {
        return false;
    };
    estimate_from_level(stats, first_hop.seeds, endpoints, &hops, first_hop.trails)
        .is_some_and(CostEstimate::frontier_wins)
}

struct FirstHop {
    seeds: u128,
    trails: f64,
}

/// Probe the exact seed count and first-hop edge count for a small set of
/// resolved seeds (either pre-bound in `rows` or resolved via an indexed
/// literal equality on `start.properties`). Returns `None` if seeds are not
/// cheaply resolvable or exceed [`ACTUAL_SEED_DEGREE_CAP`], letting the caller
/// fall back to the label's global mean degree.
fn probe_actual_first_hop_edges(
    graph: &Graph,
    rows: &[Row],
    start: &NodePattern,
    hops: &Expansion<'_>,
    estimated_seeds: u128,
    params: &BTreeMap<String, Value>,
) -> Option<FirstHop> {
    let &first_idx = hops.sequence.first()?;
    let first = hops.distinct[first_idx];
    let start_bound = start
        .variable
        .as_ref()
        .is_some_and(|var| rows.first().and_then(|r| r.get_name(var)).is_some());
    let seed_ids: Vec<NodeId> = if start_bound {
        if rows.len() > ACTUAL_SEED_DEGREE_CAP {
            return None;
        }
        let var = start.variable.as_ref()?;
        rows.iter()
            .filter_map(|row| match row.get_name(var) {
                Some(Value::Node(n)) => Some(n.id),
                _ => None,
            })
            .collect()
    } else if rows.len() == 1 && estimated_seeds <= ACTUAL_SEED_DEGREE_CAP as u128 {
        probe_indexed_literal_seeds(graph, start, params)?
    } else {
        return None;
    };
    if seed_ids.is_empty() {
        return None;
    }
    let rel_types = graph.rel_types_of(first, |name, token| {
        token.id_or_else(|| graph.rel_type_id(name))
    });
    let total_edges: usize = seed_ids
        .iter()
        .map(|&id| graph.typed_adj_len(id, first.direction, &rel_types))
        .sum();
    Some(FirstHop {
        seeds: seed_ids.len() as u128,
        trails: total_edges as f64,
    })
}

fn probe_indexed_literal_seeds(
    graph: &Graph,
    start: &NodePattern,
    params: &BTreeMap<String, Value>,
) -> Option<Vec<NodeId>> {
    let Expr::Map(pairs) = start.properties.as_ref()? else {
        return None;
    };
    if start.labels.is_empty() {
        return None;
    }
    let labels: Vec<String> = start.label_names().map(|n| n.to_string()).collect();
    let ts = graph.commit_ts();
    for (key, expr) in pairs {
        let Some(val) = expr.seek_value(params).filter(|v| !v.is_null()) else {
            continue;
        };
        if let Some(ids) =
            graph.lookup_equality_upto(&labels, key, &[val], ts, ACTUAL_SEED_DEGREE_CAP + 1)
        {
            if ids.len() <= ACTUAL_SEED_DEGREE_CAP {
                return Some(ids);
            }
        }
    }
    None
}

/// The cost estimate of `hops` (every quantifier expanded to its maximum
/// count) from `seeds` start rows, `None` when the statistics keep no
/// degree histogram, or (for an incoming or undirected first hop) no pair
/// counts, to price them with.
#[cfg(test)]
pub(super) fn estimate(
    stats: &dyn PatternStats,
    population: u128,
    seeds: u128,
    endpoints: u128,
    start: &NodePattern,
    hops: &Expansion<'_>,
) -> Option<CostEstimate> {
    let first_hop = first_hop_level(stats, population, seeds, start, hops)?;
    estimate_from_level(stats, first_hop.seeds, endpoints, hops, first_hop.trails)
}

fn first_hop_level(
    stats: &dyn PatternStats,
    population: u128,
    seeds: u128,
    start: &NodePattern,
    hops: &Expansion<'_>,
) -> Option<FirstHop> {
    let (&first_idx, _) = hops.sequence.split_first()?;
    let first = hops.distinct[first_idx];
    let start_population = start
        .labels
        .iter()
        .filter_map(|label| stats.label_rows(label))
        .min()
        .map_or(population, u128::from);
    let first_degrees = first_hop_degree_sum(stats, start, first)?;
    let trails = seeds as f64 * mean_degree(first_degrees, start_population);
    Some(FirstHop { seeds, trails })
}

fn estimate_from_level(
    stats: &dyn PatternStats,
    seeds: u128,
    endpoints: u128,
    hops: &Expansion<'_>,
    level: f64,
) -> Option<CostEstimate> {
    let (&first, rest) = hops.sequence.split_first()?;
    let first = hops.distinct[first];
    let seeds = seeds as f64;
    let mut level = level;
    let mut trails = level;
    // A quantifier repeats the same rels up to 1024 times, and each
    // degree-moments consult scans the histograms: price each distinct
    // rel once, so a crafted pattern costs consults in proportion to its
    // size, never to its expanded hop count.
    let mut fanouts: Vec<Option<f64>> = vec![None; hops.distinct.len()];
    for &index in rest {
        let fanout = match fanouts[index] {
            Some(fanout) => fanout,
            None => {
                let rel = hops.distinct[index];
                let landing = stats.degree_moments(&[], &rel.types)?;
                let fanout = excess_degree(landing) * sides(rel);
                fanouts[index] = Some(fanout);
                fanout
            }
        };
        level *= fanout;
        trails += level;
    }
    let adjacency = stats.degree_moments(&[], &first.types)?.sum as f64 * sides(first);
    let max_pairs = seeds * endpoints as f64;
    let pairs = if max_pairs <= 0.0 || trails <= 0.0 {
        0.0
    } else {
        // Balls-into-bins occupancy: expected distinct (seed, endpoint) pairs
        // when `trails` arrivals land across `max_pairs` possible pairs.
        // Matches `trails` when trails << max_pairs (trees/forests) and
        // captures collision saturation as trails approaches max_pairs.
        let ratio = trails / max_pairs;
        let floor = 1.0_f64.min(trails).min(max_pairs);
        (max_pairs * -(-ratio).exp_m1()).max(floor).min(trails)
    };
    Some(CostEstimate {
        trails,
        pairs,
        probes: trails.min(seeds * adjacency),
    })
}

/// The sum of the degrees the first hop leaves the start label by: the
/// out-degree sum for an outgoing hop, the in-degree sum for an incoming
/// one, both for an undirected hop (it reads every rel from either end).
/// The histograms are out-degree only, so a label whose rels all point
/// at it (a co-change `File`) has a zero out sum: the in side comes from
/// the pair counts ([`PatternStats::in_degree_sum`]). `None` when either
/// needed side is unpriceable.
fn first_hop_degree_sum(
    stats: &dyn PatternStats,
    start: &NodePattern,
    first: &RelPattern,
) -> Option<u128> {
    let out = || {
        stats
            .degree_moments(&start.labels, &first.types)
            .map(|moments| moments.sum)
    };
    let inbound = || stats.in_degree_sum(&start.labels, &first.types);
    match first.direction {
        Direction::Outgoing => out(),
        Direction::Incoming => inbound(),
        Direction::Both => Some(out()?.saturating_add(inbound()?)),
    }
}

/// How many times a hop sees each rel: an undirected hop reads it from
/// both endpoints.
fn sides(rel: &RelPattern) -> f64 {
    match rel.direction {
        Direction::Both => 2.0,
        Direction::Outgoing | Direction::Incoming => 1.0,
    }
}

/// The mean degree — `degree_sum` over `nodes` nodes (zero for none).
pub(super) fn mean_degree(degree_sum: u128, nodes: u128) -> f64 {
    if nodes == 0 {
        return 0.0;
    }
    degree_sum as f64 / nodes as f64
}

/// The size-biased excess degree `sum(d^2) / sum(d) - 1` a trail finds at
/// the node it just arrived at (zero when no node has an edge).
pub(super) fn excess_degree(moments: DegreeMoments) -> f64 {
    if moments.sum == 0 {
        return 0.0;
    }
    (moments.sum_sq as f64 / moments.sum as f64 - 1.0).max(0.0)
}

/// The hops of a pattern with every quantifier expanded to its maximum
/// count: the DFS's path multiplicity. `distinct` holds each rel the
/// pattern spells once; `sequence` lists, in hop order, an index into it
/// per hop, so a repetition repeats an index, never a rel, and
/// [`estimate`] prices per `distinct` entry without comparing rels.
#[derive(Debug, Default)]
pub(super) struct Expansion<'a> {
    distinct: Vec<&'a RelPattern>,
    sequence: Vec<usize>,
}

impl<'a> Expansion<'a> {
    /// One hop per listed rel, each priced on its own.
    #[cfg(test)]
    pub(super) fn chain(rels: &[&'a RelPattern]) -> Self {
        Expansion {
            distinct: rels.to_vec(),
            sequence: (0..rels.len()).collect(),
        }
    }

    /// `count` hops over the one `rel`, as a quantifier expands.
    #[cfg(test)]
    pub(super) fn repeat(rel: &'a RelPattern, count: usize) -> Self {
        Expansion {
            distinct: vec![rel],
            sequence: vec![0; count],
        }
    }

    /// The expanded hop count.
    #[cfg(test)]
    pub(super) fn hops(&self) -> usize {
        self.sequence.len()
    }

    /// The ceiling's one comparison: `Some(())` when `extra` more hops
    /// stay within [`MAX_ESTIMATE_HOPS`].
    fn reserve(&self, extra: usize) -> Option<()> {
        if self.sequence.len().checked_add(extra)? > MAX_ESTIMATE_HOPS {
            return None;
        }
        Some(())
    }

    /// Append one hop's distinct index, under the ceiling.
    fn push(&mut self, index: usize) -> Option<()> {
        self.reserve(1)?;
        self.sequence.push(index);
        Some(())
    }

    /// Register one rel the pattern spells: its distinct index, then the
    /// hop — the registry and the ceiling keep one owner.
    fn push_rel(&mut self, rel: &'a RelPattern) -> Option<()> {
        let index = self.distinct.len();
        self.push(index)?;
        self.distinct.push(rel);
        Some(())
    }

    /// Repeat the quantifier body the recursion left at `start..` `times`
    /// in total, in place: the ceiling is checked once for the whole
    /// repetition, and `extend_from_within` re-reads the one copy already
    /// there instead of a split-off buffer.
    fn repeat_from(&mut self, start: usize, times: u32) -> Option<()> {
        let end = self.sequence.len();
        let times = times as usize;
        if times == 0 {
            self.sequence.truncate(start);
            return Some(());
        }
        self.reserve((end - start).checked_mul(times - 1)?)?;
        for _ in 1..times {
            self.sequence.extend_from_within(start..end);
        }
        Some(())
    }
}

/// The rels of `elements` with every quantifier expanded to its maximum
/// count — the trail estimate's input for the DFS's path multiplicity.
/// `None` when the expansion cannot be priced — it passes
/// [`MAX_ESTIMATE_HOPS`] (the multiplicity is saturated) or a quantifier
/// is unbounded — and the caller engages rather than underestimates it.
pub(super) fn expand_max_hops(elements: &[PatternElement]) -> Option<Expansion<'_>> {
    let mut hops = Expansion::default();
    expand_into(elements, &mut hops)?;
    Some(hops)
}

fn expand_into<'a>(elements: &'a [PatternElement], hops: &mut Expansion<'a>) -> Option<()> {
    for element in elements {
        match element {
            // Only the rels matter to the estimate: nodes carry no
            // fanout of their own.
            PatternElement::Node(_) => {}
            PatternElement::Relationship(rel) => hops.push_rel(rel)?,
            PatternElement::Quantified(qpp) => {
                let max = qpp.max?;
                // The body expands once; a body with no rel adds no
                // hops, and every repetition of one that does grows the
                // spine, so the ceiling bounds the repetition.
                let start = hops.sequence.len();
                expand_into(&qpp.elements, hops)?;
                hops.repeat_from(start, max)?;
            }
        }
    }
    Some(())
}