relate-executor 1.0.1

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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! The grouped aggregate's streaming state: what a group keeps instead of
//! its input rows.
//!
//! [`AggSites::discover`] finds every aggregate call an aggregating
//! projection can evaluate (items, `ORDER BY` keys, HAVING) by running the
//! one recursive evaluator in its discovery mode, so the sites are exactly
//! the calls the evaluator reaches. Each site gets one accumulator per
//! group ([`GroupAccs`]): a non-retaining aggregate (`count`, `sum`, `avg`,
//! `min`, `max`, `stDev`, `stDevP`, DISTINCT or not) keeps constant-size state
//! (plus a DISTINCT call's seen-set) and never an operand value; only `collect` and the percentiles retain
//! their operands, charged to the expression budget as a retaining
//! container. The plain percentile calls of one group over the same operand
//! share one `f64` buffer (`pool`) rather than each keeping its own `Value`s.
//! [`GroupAccs::finish`] resolves every site once, and the
//! evaluator reads the results back from the [`FoldedGroup`].

use std::cell::RefCell;
use std::collections::BTreeMap;

use relate_core::{Error, ErrorKind, Result, Value};
use relate_ir::{classify_aggregate, AggregateArity, AggregateKind, Expr};
use relate_names::SmallName;

use crate::distinct_set::DistinctSet;
use crate::eval::{eval, fold_aggregate, needs_numbers, FoldInput, Percentile, StreamFold};
use crate::overlay::{ExecGraph, RetainedTotal};
use crate::row::Row;

use super::eval::{agg_eval, AggScope};
use super::pool::{shareable, OperandPool, SortedPool};

/// One aggregate call, validated: the borrowed pieces every offer and the
/// finish read.
#[derive(Clone, Copy)]
struct Call<'e> {
    kind: AggregateKind,
    name: &'e SmallName,
    operand: &'e Expr,
    /// The percentile argument of a `PercentilePair` call.
    percentile: Option<&'e Expr>,
}

/// One site's per-group state.
enum SiteAcc<'e> {
    CountStar(i64),
    /// A non-retaining aggregate: constant-size state, independent of the
    /// number of rows offered.
    Stream {
        fold: StreamFold,
        call: Call<'e>,
        /// The peak payload bytes of the one value a `min`/`max` keeps,
        /// already charged ([`GroupAccs::settle`]).
        held: u64,
        /// A DISTINCT call's seen-set: an operand folds only when it is
        /// first seen, and is dropped at once; the set's keys are the
        /// only per-distinct-value state.
        seen: Option<DistinctSet>,
    },
    /// `collect` and the percentiles (and their DISTINCT forms): the operands are the
    /// state, charged to the aggregation's running total as they settle.
    Retain {
        vals: Vec<Value>,
        /// How many of `vals` are already charged.
        charged: usize,
        /// A DISTINCT call's seen-set: only first-seen operands reach
        /// `vals`, so the state is proportional to the distinct values.
        seen: Option<DistinctSet>,
        call: Call<'e>,
    },
    /// A plain percentile call: its operands live in the group's shared
    /// [`OperandPool`] at this index, not in the site.
    Pooled {
        pool: usize,
        call: Call<'e>,
        /// The call's percentile argument, resolved when it was pooled.
        percentile: &'e Expr,
    },
    /// A lenient site (one only an `ORDER BY` key or HAVING reads) whose
    /// operand failed to fold: the error is parked here and surfaces when
    /// the site is read. The read's outcome is stated once at the
    /// canonical contract ([`GroupSubclauses::having`], ADR-0458 §7); an
    /// ORDER BY key orders as null.
    Failed(Error),
    /// An arity violation (a backtick-escaped `` `count`() `` bypasses the
    /// parser and front validation): raised when the group resolves, as the
    /// row-retaining fold did, so an empty keyed input still yields no
    /// error.
    Rejected(Error),
}

struct Slot<'e> {
    /// The call's identity: the evaluator asks for its value by this
    /// reference.
    expr: &'e Expr,
    /// Whether only an `ORDER BY` key or HAVING reads this call: a fold
    /// error parks instead of failing the statement (see
    /// [`SiteAcc::Failed`]); the read's outcome is the canonical HAVING
    /// contract ([`GroupSubclauses::having`], ADR-0458 §7).
    lenient: bool,
    acc: SiteAcc<'e>,
}

impl<'e> SiteAcc<'e> {
    /// A fresh group's state from this template site: the same call, an
    /// empty accumulator (a DISTINCT call's seen-set starts empty).
    fn open(&self) -> SiteAcc<'e> {
        match self {
            Self::CountStar(_) => Self::CountStar(0),
            Self::Stream {
                fold,
                call,
                held,
                seen,
            } => Self::Stream {
                fold: fold.clone(),
                call: *call,
                held: *held,
                seen: seen.as_ref().map(|_| DistinctSet::default()),
            },
            Self::Retain { seen, call, .. } => Self::Retain {
                vals: Vec::new(),
                charged: 0,
                seen: seen.as_ref().map(|_| DistinctSet::default()),
                call: *call,
            },
            Self::Pooled {
                pool,
                call,
                percentile,
            } => Self::Pooled {
                pool: *pool,
                call: *call,
                percentile,
            },
            Self::Failed(error) => Self::Failed(error.clone()),
            Self::Rejected(error) => Self::Rejected(error.clone()),
        }
    }
}

/// Whether an operand is admitted: true when there is no seen-set (the
/// call is not DISTINCT) or the value is first seen.
fn admits(seen: &mut Option<DistinctSet>, value: &Value) -> Result<bool> {
    seen.as_mut()
        .map_or(Ok(true), |seen| seen.insert_value(value))
}

impl SiteAcc<'_> {
    /// Offer one input row to this site.
    fn offer(
        &mut self,
        graph: &ExecGraph<'_>,
        row: &Row,
        params: &BTreeMap<String, Value>,
        cypher_version: Option<u32>,
    ) -> Result<()> {
        match self {
            Self::CountStar(n) => *n += 1,
            Self::Stream {
                fold, call, seen, ..
            } => {
                graph.cancel_tick()?;
                let value = eval(graph, row, call.operand, params, cypher_version)?;
                if admits(seen, &value)? {
                    call.name.with_str(|name| fold.offer(value, name))?;
                }
            }
            Self::Retain {
                vals, seen, call, ..
            } => {
                graph.cancel_tick()?;
                let value = eval(graph, row, call.operand, params, cypher_version)?;
                if admits(seen, &value)? {
                    vals.push(value);
                }
            }
            Self::Pooled { .. } | Self::Failed(_) | Self::Rejected(_) => {}
        }
        Ok(())
    }
}

/// The one strict-raises/lenient-parks rule of an offer: a failure on a
/// lenient site (or a pool only lenient sites read) is handed back to be
/// parked, any other failure fails the statement.
fn parked(lenient: bool, offered: Result<()>) -> Result<Option<Error>> {
    match offered {
        Ok(()) => Ok(None),
        Err(error) if lenient => Ok(Some(error)),
        Err(error) => Err(error),
    }
}

/// The aggregate call sites of one aggregating projection, with the
/// accumulator each group starts from.
pub(crate) struct AggSites<'e> {
    template: GroupAccs<'e>,
}

impl<'e> AggSites<'e> {
    /// Discover the sites of an aggregating projection: `items` are the
    /// projection items' aggregate expressions, `lenient` the expressions
    /// only an `ORDER BY` key or HAVING evaluates. A call an item also
    /// reads is strict.
    pub(crate) fn discover(
        graph: &ExecGraph<'_>,
        items: impl IntoIterator<Item = &'e Expr>,
        lenient: impl IntoIterator<Item = &'e Expr>,
        params: &BTreeMap<String, Value>,
        cypher_version: Option<u32>,
    ) -> Result<Self> {
        let mut slots: Vec<Slot<'e>> = Vec::new();
        for (exprs, is_lenient) in [
            (items.into_iter().collect::<Vec<_>>(), false),
            (lenient.into_iter().collect::<Vec<_>>(), true),
        ] {
            let found = RefCell::new(Vec::new());
            for expr in exprs {
                agg_eval(
                    graph,
                    AggScope::discovering(&found),
                    expr,
                    params,
                    cypher_version,
                )?;
            }
            for expr in found.into_inner() {
                if slots.iter().all(|slot| !std::ptr::eq(slot.expr, expr)) {
                    slots.push(Slot {
                        expr,
                        lenient: is_lenient,
                        acc: site_acc(expr)?,
                    });
                }
            }
        }
        let pools = pool_percentiles(&mut slots);
        Ok(Self {
            template: GroupAccs { slots, pools },
        })
    }

    /// A fresh group's accumulators.
    pub(crate) fn open_group(&self) -> GroupAccs<'e> {
        GroupAccs {
            pools: self.template.pools.iter().map(OperandPool::open).collect(),
            slots: self
                .template
                .slots
                .iter()
                .map(|slot| Slot {
                    expr: slot.expr,
                    lenient: slot.lenient,
                    acc: slot.acc.open(),
                })
                .collect(),
        }
    }
}

/// Route every plain percentile call over a shareable operand to one pool
/// per distinct operand expression. A DISTINCT call keeps its own seen-set
/// and values, and `collect` keeps `Value`s: neither is pooled. A pool is
/// lenient only while every site reading it is.
fn pool_percentiles<'e>(slots: &mut [Slot<'e>]) -> Vec<OperandPool<'e>> {
    let mut pools: Vec<OperandPool<'e>> = Vec::new();
    for slot in slots {
        let SiteAcc::Retain {
            seen: None, call, ..
        } = &slot.acc
        else {
            continue;
        };
        let call = *call;
        let Some(percentile) = call.percentile else {
            continue;
        };
        if !shareable(call.operand) {
            continue;
        }
        let index = match pools.iter().position(|pool| pool.reads(call.operand)) {
            Some(index) => {
                pools[index].lenient &= slot.lenient;
                index
            }
            None => {
                pools.push(OperandPool::new(call.operand, slot.lenient));
                pools.len() - 1
            }
        };
        slot.acc = SiteAcc::Pooled {
            pool: index,
            call,
            percentile,
        };
    }
    pools
}

/// Classify one discovered call once: its arity contract, and whether it
/// streams or retains.
fn site_acc(expr: &Expr) -> Result<SiteAcc<'_>> {
    let (name, distinct, args) = match expr {
        Expr::CountStar => return Ok(SiteAcc::CountStar(0)),
        Expr::Function {
            name,
            distinct,
            args,
        } => (name, *distinct, args.as_slice()),
        _ => {
            return Err(Error::internal(
                "an aggregate call site is a count(*) or a function call",
            ))
        }
    };
    let kind = name.with_str(classify_aggregate).ok_or_else(|| {
        Error::internal("discovery records only calls the aggregate classification accepts")
    })?;
    // LABS-276 / ADR-0225/0217: every aggregate's arity contract comes from
    // the kind's row in the single `relate-ir` contracts table. `count` is
    // guarded here too — a backtick-escaped `` `count`() `` bypasses both
    // the parser's keyword path and front validation — and the percentiles
    // keep their own two-argument message.
    let arity = kind.arity();
    if args.len() != arity.required() {
        let rejection = name.with_str(|text| arity.rejection(text, args.len()));
        return Ok(SiteAcc::Rejected(match arity {
            AggregateArity::SingleInput => Error::syntax(rejection),
            AggregateArity::PercentilePair => Error::ty(rejection),
        }));
    }
    let call = Call {
        kind,
        name,
        operand: &args[0],
        percentile: args.get(1),
    };
    // `min`/`max` ignore DISTINCT (the extreme of the distinct values is the
    // extreme of the values), so they need no seen-set; every other
    // streaming DISTINCT call folds an operand when its seen-set admits it.
    let dedups = distinct && !matches!(kind, AggregateKind::Min | AggregateKind::Max);
    Ok(match StreamFold::for_kind(kind) {
        Some(fold) => SiteAcc::Stream {
            fold,
            call,
            held: 0,
            seen: dedups.then(DistinctSet::default),
        },
        None => SiteAcc::Retain {
            vals: Vec::new(),
            charged: 0,
            seen: distinct.then(DistinctSet::default),
            call,
        },
    })
}

/// One group's accumulators, one per site.
pub(crate) struct GroupAccs<'e> {
    slots: Vec<Slot<'e>>,
    /// The group's shared percentile operand buffers, one per distinct
    /// operand expression (see [`pool_percentiles`]).
    pools: Vec<OperandPool<'e>>,
}

impl<'e> GroupAccs<'e> {
    /// The constant footprint of a group's accumulators — what the group
    /// map's retained total grows by when a group lands.
    pub(crate) fn footprint(&self) -> u64 {
        crate::workspace::buffer_bytes_saturating(self.slots.len(), size_of::<Slot<'e>>() as u64)
            .saturating_add(crate::workspace::buffer_bytes_saturating(
                self.pools.len(),
                size_of::<OperandPool<'e>>() as u64,
            ))
    }

    /// Offer one input row to every site. A streaming site evaluates its
    /// operand and folds it into its constant-size state; a retaining site
    /// keeps the value. What a site kept is charged by [`Self::settle`],
    /// once the spent row has let go of its share.
    pub(crate) fn offer(
        &mut self,
        graph: &ExecGraph<'_>,
        row: &Row,
        params: &BTreeMap<String, Value>,
        cypher_version: Option<u32>,
    ) -> Result<()> {
        for index in 0..self.pools.len() {
            let pool = &mut self.pools[index];
            let offered = pool.offer(graph, row, params, cypher_version);
            if let Some(error) = parked(pool.lenient, offered)? {
                // The pool's sites are all lenient: park the failure on each
                // and stop collecting.
                pool.stop();
                for slot in &mut self.slots {
                    if matches!(slot.acc, SiteAcc::Pooled { pool, .. } if pool == index) {
                        slot.acc = SiteAcc::Failed(error.clone());
                    }
                }
            }
        }
        for slot in &mut self.slots {
            let offered = slot.acc.offer(graph, row, params, cypher_version);
            if let Some(error) = parked(slot.lenient, offered)? {
                slot.acc = SiteAcc::Failed(error);
            }
        }
        Ok(())
    }

    /// Charge what the sites kept since the last settle to the
    /// aggregation's one running total: a retaining site's new operand slots
    /// and payloads, and the growth of the payload a `min`/`max` holds. The
    /// caller settles after the spent input row is dropped, so a value
    /// cloned from that row is the sole owner of its payload by now and is
    /// charged in full (a payload still shared with the store or a
    /// parameter adds nothing, as everywhere else). One total for every
    /// group: the groups' retained state is alive together, so it is
    /// bounded together.
    pub(crate) fn settle(
        &mut self,
        graph: &ExecGraph<'_>,
        total: &mut RetainedTotal,
    ) -> Result<()> {
        for pool in &mut self.pools {
            pool.settle(graph, total)?;
        }
        for slot in &mut self.slots {
            match &mut slot.acc {
                SiteAcc::Retain { vals, charged, .. } => {
                    for value in &vals[*charged..] {
                        let slot_bytes = crate::workspace::buffer_growth(
                            *charged,
                            *charged + 1,
                            size_of::<Value>() as u64,
                        );
                        total.add_bytes(graph, slot_bytes)?;
                        total.add_owned(graph, value)?;
                        *charged += 1;
                    }
                }
                SiteAcc::Stream { fold, held, .. } => {
                    if let Some(best) = fold.held_value() {
                        let now = crate::workspace::owned_heap(best);
                        if now > *held {
                            total.add_bytes(graph, now - *held)?;
                            *held = now;
                        }
                    }
                }
                SiteAcc::CountStar(_)
                | SiteAcc::Pooled { .. }
                | SiteAcc::Failed(_)
                | SiteAcc::Rejected(_) => {}
            }
        }
        Ok(())
    }

    /// Resolve every site. `seed` is the group's own first row — a
    /// percentile's second argument is read from it, and an empty group has
    /// no percentile to report.
    pub(crate) fn finish(
        self,
        graph: &ExecGraph<'_>,
        seed: Option<&Row>,
        params: &BTreeMap<String, Value>,
        cypher_version: Option<u32>,
    ) -> FoldedGroup<'e> {
        let pools: Vec<SortedPool> = self.pools.into_iter().map(OperandPool::finish).collect();
        FoldedGroup {
            values: self
                .slots
                .into_iter()
                .map(|slot| {
                    let value = match slot.acc {
                        SiteAcc::CountStar(n) => Ok(Value::Int(n)),
                        SiteAcc::Stream { fold, .. } => fold.finish(),
                        SiteAcc::Retain { vals, call, .. } => {
                            finish_retained(graph, vals, call, seed, params, cypher_version)
                        }
                        SiteAcc::Pooled {
                            pool,
                            call,
                            percentile,
                        } => finish_pooled(
                            graph,
                            &pools[pool],
                            call,
                            percentile,
                            seed,
                            params,
                            cypher_version,
                        ),
                        SiteAcc::Failed(error) | SiteAcc::Rejected(error) => Err(error),
                    };
                    (slot.expr, value)
                })
                .collect(),
        }
    }
}

/// The validated percentile argument of a call. The percentile depends only
/// on the group's first row; an empty group has no row to ask and no
/// percentile to report (`None`).
fn percentile_input(
    graph: &ExecGraph<'_>,
    call: Call<'_>,
    percentile: &Expr,
    seed: Option<&Row>,
    params: &BTreeMap<String, Value>,
    cypher_version: Option<u32>,
) -> Result<Option<Percentile>> {
    let Some(first) = seed else {
        return Ok(None);
    };
    let p = eval(graph, first, percentile, params, cypher_version)?;
    // Two distinct rejections: a non-numeric percentile is the
    // wrong-type class, an out-of-[0, 1] one the NumberOutOfRange
    // kind (ADR-0175's 22N03 mapping).
    let Some(p) = p.as_number() else {
        return Err(Error::invalid_argument_type("percentile must be a number"));
    };
    if !(0.0..=1.0).contains(&p) {
        return Err(Error::argument_value_kind(
            ErrorKind::NumberOutOfRange,
            "percentile",
        ));
    }
    call.name
        .with_str(|text| Percentile::new(call.kind, p, text))
        .map(Some)
}

/// A retaining site's result: the percentile argument is validated first,
/// and the shared per-kind fold finishes the operands (`collect` and
/// the DISTINCT percentiles).
fn finish_retained(
    graph: &ExecGraph<'_>,
    vals: Vec<Value>,
    call: Call<'_>,
    seed: Option<&Row>,
    params: &BTreeMap<String, Value>,
    cypher_version: Option<u32>,
) -> Result<Value> {
    let input = match call.percentile {
        None => FoldInput::Many(call.kind),
        Some(percentile) => {
            match percentile_input(graph, call, percentile, seed, params, cypher_version)? {
                Some(percentile) => FoldInput::Percentile(percentile),
                None => return Ok(Value::Null),
            }
        }
    };
    call.name.with_str(|text| fold_aggregate(input, text, vals))
}

/// A pooled percentile's result: the same order of rejections as the
/// per-site fold (a parked evaluation failure is already a `Failed` site;
/// then the percentile argument, then a non-numeric operand), then the rank
/// in the sample the group sorted once.
fn finish_pooled(
    graph: &ExecGraph<'_>,
    pool: &SortedPool,
    call: Call<'_>,
    percentile: &Expr,
    seed: Option<&Row>,
    params: &BTreeMap<String, Value>,
    cypher_version: Option<u32>,
) -> Result<Value> {
    let Some(percentile) = percentile_input(graph, call, percentile, seed, params, cypher_version)?
    else {
        return Ok(Value::Null);
    };
    if pool.non_numeric {
        return Err(call.name.with_str(needs_numbers));
    }
    Ok(percentile.rank_in_sorted(&pool.vals))
}

/// One group's resolved aggregate calls, read back by the evaluator.
pub(crate) struct FoldedGroup<'e> {
    values: Vec<(&'e Expr, Result<Value>)>,
}

impl FoldedGroup<'_> {
    /// The value of the call at `expr` (by identity).
    pub(crate) fn value(&self, expr: &Expr) -> Result<Value> {
        self.values
            .iter()
            .find(|(site, _)| std::ptr::eq(*site, expr))
            .map(|(_, value)| value.clone())
            .unwrap_or_else(|| {
                Err(Error::internal(
                    "an aggregate call was not discovered before the group resolved",
                ))
            })
    }
}