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
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
//! The aggregate site: the typed call shape, its classification (the one
//! construction path of a [`SiteColumn`]), the site's state across every
//! group, and the per-shape finish policy. `columns` keeps the flat table
//! over the sites and the offer/settle/finish orchestration.

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;
use crate::row::Row;
use crate::workspace::buffer_growth;

use super::bill::GroupBill;
use super::pool::{SampleEnding, SortedPool};

/// Groups whose lenient site failed to fold: the error is parked here and
/// surfaces when the site is read. Sparse — empty unless an `ORDER BY` key
/// or HAVING operand failed (see [`GroupSubclauses::where_mode`] for the
/// outcome, ADR-0458 §7).
///
/// [`GroupSubclauses::where_mode`]: super::group::GroupSubclauses
pub(super) type Failed = BTreeMap<usize, Error>;

/// What one parked failure retains: its map entry, the error value and its
/// message. Billed once per site, so K sites parking one operand's error
/// pay K times.
fn parked_error_bytes(error: &Error) -> u64 {
    (size_of::<(usize, Error)>() as u64 + error.to_string().len() as u64)
        .saturating_add(BTREE_ENTRY_OVERHEAD)
}

/// Per-entry bookkeeping of a `BTreeMap` node, a conservative flat figure.
const BTREE_ENTRY_OVERHEAD: u64 = 16;

/// The `PercentilePair` call's payload: the four borrowed pieces one
/// percentile call is, carried whole wherever it goes — the enum's arm or
/// a pooled site's column — so no reader re-splits it into loose fields.
#[derive(Clone, Copy)]
pub(super) struct PercentileCall<'e> {
    pub(super) kind: AggregateKind,
    pub(super) name: &'e SmallName,
    pub(super) operand: &'e Expr,
    pub(super) percentile: &'e Expr,
}

/// One aggregate call, validated: the borrowed pieces every offer and the
/// finish read, in one typed shape — the kind's arity row in the
/// `relate-ir` contracts table decides the arm once, in
/// [`SiteColumn::classify`], so no reader re-derives whether the call carries
/// a percentile argument.
#[derive(Clone, Copy)]
pub(super) enum Call<'e> {
    /// A single-input call: `count`, `sum`, `avg`, `min`, `max`, a
    /// deviation, `collect`.
    Plain {
        kind: AggregateKind,
        name: &'e SmallName,
        operand: &'e Expr,
    },
    /// A `PercentilePair` call: the percentile argument rides in the arm's
    /// payload, non-optional.
    Percentile(PercentileCall<'e>),
}

impl<'e> Call<'e> {
    pub(super) fn name(&self) -> &'e SmallName {
        match self {
            Self::Plain { name, .. } => name,
            Self::Percentile(call) => call.name,
        }
    }

    fn operand(&self) -> &'e Expr {
        match self {
            Self::Plain { operand, .. } => operand,
            Self::Percentile(call) => call.operand,
        }
    }

    /// The percentile argument of a percentile call (`None` for a plain
    /// one) — a discriminant query for the readers that ask, never a
    /// re-derivation of the arity fact.
    pub(super) fn percentile(&self) -> Option<&'e Expr> {
        match self {
            Self::Percentile(call) => Some(call.percentile),
            Self::Plain { .. } => None,
        }
    }
}

/// One group's slot of a streaming site: the fold and the peak payload
/// bytes of the one value a `min`/`max` keeps, already charged. The slot
/// is one value, so what a group pushes and what the column bills per
/// group are the same type.
pub(super) struct StreamSlot {
    pub(super) fold: StreamFold,
    pub(super) held: u64,
}

impl StreamSlot {
    /// A fresh group's slot: the site's template fold, nothing held.
    fn new(template: &StreamFold) -> Self {
        Self {
            fold: template.clone(),
            held: 0,
        }
    }
}

/// One group's slot of a retaining site: the operands and how many of
/// them are already charged.
#[derive(Default)]
pub(super) struct RetainSlot {
    pub(super) vals: Vec<Value>,
    pub(super) charged: usize,
}

/// One aggregate site's state across every group.
pub(super) enum SiteState<'e> {
    CountStar(Vec<i64>),
    /// A non-retaining aggregate: constant-size state per group,
    /// independent of the number of rows offered.
    Stream {
        call: Call<'e>,
        /// The fold a new group starts from.
        template: StreamFold,
        slots: Vec<StreamSlot>,
    },
    /// `collect` and the DISTINCT percentiles: the operands are the state,
    /// charged to the aggregation's running total as they settle.
    Retain {
        call: Call<'e>,
        slots: Vec<RetainSlot>,
    },
    /// A plain percentile call: its operands live in the shared pool
    /// column at this index, not here. The routing in
    /// [`super::columns::AccTable::new`] admits only percentile calls into
    /// this state, so the call rides whole — the plain-call shape has no
    /// spelling here.
    Pooled {
        pool: usize,
        call: PercentileCall<'e>,
    },
    /// An arity violation (a backtick-escaped `` `count`() `` bypasses the
    /// parser and front validation): raised when a group resolves, as the
    /// row-retaining fold did, so an empty keyed input still yields no
    /// error.
    Rejected(Error),
}

/// One aggregate call site: the call's identity (the evaluator asks for its
/// value by this reference), whether only an `ORDER BY` key or HAVING reads
/// it (a fold error parks instead of failing the statement), the groups
/// whose fold already failed, and its state.
pub(super) struct SiteColumn<'e> {
    pub(super) expr: &'e Expr,
    pub(super) lenient: bool,
    pub(super) failed: Failed,
    /// A DISTINCT call's per-group seen-set (`Some` for such a site): an
    /// operand folds only when first seen and is dropped at once. A
    /// property of the site, not of its fold shape — both the streaming
    /// and the retaining shapes keep one.
    pub(super) seen: Option<Vec<DistinctSet>>,
    pub(super) state: SiteState<'e>,
}

/// The operand `call` yields for `row` in `group`, when it is to be folded:
/// `None` for a group whose site already failed (nothing is evaluated any
/// more) and for a DISTINCT call's operand already seen there. The one
/// preamble every streaming and retaining offer shares.
pub(super) fn admitted_operand(
    failed: &Failed,
    seen: &mut Option<Vec<DistinctSet>>,
    group: usize,
    call: &Call<'_>,
    graph: &ExecGraph<'_>,
    row: &Row,
    params: &BTreeMap<String, Value>,
) -> Result<Option<Value>> {
    if failed.contains_key(&group) {
        return Ok(None);
    }
    graph.cancel_tick()?;
    let value = eval(graph, row, call.operand(), params)?;
    let admitted = seen
        .as_mut()
        .map_or(Ok(true), |seen| seen[group].insert_value(&value))?;
    Ok(admitted.then_some(value))
}

impl<'e> SiteColumn<'e> {
    /// Classify one discovered call once — the one construction path, so
    /// the state and the seen-set that must agree with it are built in
    /// one place and the impossible combinations (a seen-set on a pooled
    /// or `count(*)` site, a `min`/`max` site with one) have no spelling.
    ///
    /// LABS-276 / ADR-0225/0217: every aggregate's arity contract comes
    /// from the kind's row in the single `relate-ir` contracts table —
    /// the one place the call's typed shape is decided. `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.
    pub(super) fn classify(expr: &'e Expr, lenient: bool) -> Result<Self> {
        let (name, distinct, args) = match expr {
            Expr::CountStar => {
                return Ok(Self::assemble(
                    expr,
                    lenient,
                    SiteState::CountStar(Vec::new()),
                    None,
                ))
            }
            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")
        })?;
        let arity = kind.arity();
        if args.len() != arity.required() {
            let rejected = SiteState::Rejected(name.with_str(|text| arity.error(text, args.len())));
            return Ok(Self::assemble(expr, lenient, rejected, None));
        }
        let call = match arity {
            AggregateArity::SingleInput => Call::Plain {
                kind,
                name,
                operand: &args[0],
            },
            AggregateArity::PercentilePair => Call::Percentile(PercentileCall {
                kind,
                name,
                operand: &args[0],
                percentile: &args[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);
        let (state, keeps_seen) = match StreamFold::for_kind(kind) {
            Some(template) => (
                SiteState::Stream {
                    call,
                    template,
                    slots: Vec::new(),
                },
                dedups,
            ),
            None => (
                SiteState::Retain {
                    call,
                    slots: Vec::new(),
                },
                distinct,
            ),
        };
        Ok(Self::assemble(
            expr,
            lenient,
            state,
            keeps_seen.then(Vec::new),
        ))
    }

    /// The packer behind [`Self::classify`]: a site is its identity,
    /// lenience, an empty failure map, its state, and the seen-set the
    /// classification agreed on — one place, beside the classification
    /// that decides the pair.
    fn assemble(
        expr: &'e Expr,
        lenient: bool,
        state: SiteState<'e>,
        seen: Option<Vec<DistinctSet>>,
    ) -> Self {
        Self {
            expr,
            lenient,
            failed: Failed::new(),
            seen,
            state,
        }
    }

    /// The call's percentile argument, which the finish reads from the
    /// group's seed.
    pub(super) fn percentile(&self) -> Option<&'e Expr> {
        // Every shape named: a streaming call also carries a `Call`, and
        // answering from it (not from the storage shape) keeps a new shape
        // deciding instead of silently reading as "no".
        match &self.state {
            SiteState::Retain { call, .. } | SiteState::Stream { call, .. } => call.percentile(),
            SiteState::Pooled { call, .. } => Some(call.percentile),
            SiteState::CountStar(_) | SiteState::Rejected(_) => None,
        }
    }

    /// Per-group bytes of this site's column slot.
    pub(super) fn slot_bytes(&self) -> u64 {
        let distinct = self
            .seen
            .as_ref()
            .map_or(0, |_| size_of::<DistinctSet>() as u64);
        match &self.state {
            SiteState::CountStar(_) => size_of::<i64>() as u64,
            SiteState::Stream { .. } => size_of::<StreamSlot>() as u64 + distinct,
            SiteState::Retain { .. } => size_of::<RetainSlot>() as u64 + distinct,
            SiteState::Pooled { .. } | SiteState::Rejected(_) => 0,
        }
    }

    pub(super) fn open_group(&mut self) {
        match &mut self.state {
            SiteState::CountStar(counts) => counts.push(0),
            SiteState::Stream {
                template, slots, ..
            } => slots.push(StreamSlot::new(template)),
            SiteState::Retain { slots, .. } => slots.push(RetainSlot::default()),
            SiteState::Pooled { .. } | SiteState::Rejected(_) => {}
        }
        if let Some(seen) = &mut self.seen {
            seen.push(DistinctSet::default());
        }
    }

    /// Offer one input row to group `group`'s slot.
    pub(super) fn offer(
        &mut self,
        group: usize,
        graph: &ExecGraph<'_>,
        row: &Row,
        params: &BTreeMap<String, Value>,
    ) -> Result<()> {
        let Self {
            failed,
            seen,
            state,
            ..
        } = self;
        match state {
            SiteState::CountStar(counts) => counts[group] += 1,
            SiteState::Stream { call, slots, .. } => {
                if let Some(value) =
                    admitted_operand(failed, seen, group, call, graph, row, params)?
                {
                    call.name()
                        .with_str(|name| slots[group].fold.offer(value, name))?;
                }
            }
            SiteState::Retain { call, slots } => {
                if let Some(value) =
                    admitted_operand(failed, seen, group, call, graph, row, params)?
                {
                    slots[group].vals.push(value);
                }
            }
            SiteState::Pooled { .. } | SiteState::Rejected(_) => {}
        }
        Ok(())
    }

    /// Drop what group `group`'s slot retained: the operands (or the fold)
    /// with their charge cursors, and the DISTINCT seen-set — the same
    /// reset the finish performs while it resolves the slot. A pooled
    /// site holds nothing here (its pool state releases the sample).
    fn release(&mut self, group: usize) {
        let Self { state, seen, .. } = self;
        match state {
            SiteState::Stream {
                template, slots, ..
            } => {
                let _ = take_stream_slot(template, slots, group);
            }
            SiteState::Retain { slots, .. } => {
                let _ = take_retain_slot(slots, group);
            }
            SiteState::CountStar(_) | SiteState::Pooled { .. } | SiteState::Rejected(_) => {}
        }
        reset_seen(seen, group);
    }

    /// A lenient site's operand failed for `group`: bill what the parked
    /// error retains to `total`, release what the slot kept, and park the
    /// error. The failure surfaces when the site is read.
    pub(super) fn park_failure(
        &mut self,
        group: usize,
        error: Error,
        graph: &ExecGraph<'_>,
        bill: &mut GroupBill,
    ) -> Result<()> {
        bill.add(graph, parked_error_bytes(&error))?;
        self.release(group);
        self.failed.insert(group, error);
        Ok(())
    }

    pub(super) fn settle(
        &mut self,
        group: usize,
        graph: &ExecGraph<'_>,
        bill: &mut GroupBill,
    ) -> Result<()> {
        if self.failed.contains_key(&group) {
            return Ok(());
        }
        match &mut self.state {
            SiteState::Retain { slots, .. } => {
                let RetainSlot { vals, charged } = &mut slots[group];
                for value in &vals[*charged..] {
                    let slot_bytes =
                        buffer_growth(*charged, *charged + 1, size_of::<Value>() as u64);
                    bill.add(graph, slot_bytes)?;
                    bill.add(graph, crate::workspace::owned_heap(value))?;
                    *charged += 1;
                }
            }
            SiteState::Stream { slots, .. } => {
                let StreamSlot { fold, held } = &mut slots[group];
                if let Some(best) = fold.held_value() {
                    let now = crate::workspace::owned_heap(best);
                    if now > *held {
                        bill.add(graph, now - *held)?;
                        *held = now;
                    }
                }
            }
            SiteState::CountStar(_) | SiteState::Pooled { .. } | SiteState::Rejected(_) => {}
        }
        Ok(())
    }

    /// Resolve this site for `group`, taking the group's state out.
    pub(super) fn finish(
        &mut self,
        group: usize,
        graph: &ExecGraph<'_>,
        pools: &[SortedPool],
        seed: Option<&Row>,
        params: &BTreeMap<String, Value>,
    ) -> Result<Value> {
        if let Some(error) = self.failed.get(&group) {
            return Err(error.clone());
        }
        // Each retaining shape resolves through the one slot reset its
        // taker performs — the same reset a release performs — so the slot
        // a resolved group leaves behind holds neither its values nor a
        // cursor claiming bytes for them.
        let Self { state, seen, .. } = self;
        let resolved = match state {
            SiteState::CountStar(counts) => Ok(Value::Int(counts[group])),
            SiteState::Stream {
                template, slots, ..
            } => take_stream_slot(template, slots, group).finish(),
            SiteState::Retain { call, slots } => {
                finish_retained(graph, take_retain_slot(slots, group), *call, seed, params)
            }
            SiteState::Pooled { pool, call } => {
                finish_pooled(graph, &pools[*pool], *call, seed, params)
            }
            SiteState::Rejected(error) => Err(error.clone()),
        };
        reset_seen(seen, group);
        resolved
    }
}

/// The DISTINCT seen-set's half of a slot reset: a fresh set in `group`'s
/// place, for the shapes that keep one.
fn reset_seen(seen: &mut Option<Vec<DistinctSet>>, group: usize) {
    if let Some(seen) = seen {
        seen[group] = DistinctSet::default();
    }
}

/// The one stream-slot reset: group `group`'s fold taken out, the site's
/// template back in its place, and the held-payload cursor zeroed with the
/// value it described. One policy for the release a parked failure
/// performs and the resolve a finish takes, so the two cannot disagree.
fn take_stream_slot(template: &StreamFold, slots: &mut [StreamSlot], group: usize) -> StreamFold {
    std::mem::replace(&mut slots[group], StreamSlot::new(template)).fold
}

/// The one retain-slot reset: group `group`'s operands taken out and the
/// charge cursor zeroed with them.
fn take_retain_slot(slots: &mut [RetainSlot], group: usize) -> Vec<Value> {
    std::mem::take(&mut slots[group]).vals
}

/// The validated percentile argument of a percentile 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`).
pub(super) fn percentile_input(
    graph: &ExecGraph<'_>,
    call: PercentileCall<'_>,
    seed: Option<&Row>,
    params: &BTreeMap<String, Value>,
) -> Result<Option<Percentile>> {
    let Some(first) = seed else {
        return Ok(None);
    };
    let p = eval(graph, first, call.percentile, params)?;
    // 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).
pub(super) fn finish_retained(
    graph: &ExecGraph<'_>,
    vals: Vec<Value>,
    call: Call<'_>,
    seed: Option<&Row>,
    params: &BTreeMap<String, Value>,
) -> Result<Value> {
    let input = match call {
        Call::Plain { kind, .. } => FoldInput::Many(kind),
        Call::Percentile(p) => match percentile_input(graph, p, seed, params)? {
            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, read
/// before this; then the percentile argument, then a non-numeric operand),
/// then the rank in the sample the group sorted once.
pub(super) fn finish_pooled(
    graph: &ExecGraph<'_>,
    pool: &SortedPool,
    call: PercentileCall<'_>,
    seed: Option<&Row>,
    params: &BTreeMap<String, Value>,
) -> Result<Value> {
    let Some(percentile) = percentile_input(graph, call, seed, params)? else {
        return Ok(Value::Null);
    };
    // The sample's own ending, matched where it leaves the pool: only a
    // non-numeric operand is this rejection. A parked pool has no ending
    // here — its sites answer with the parked error before this.
    match pool.ending {
        SampleEnding::NonNumeric => return Err(call.name.with_str(needs_numbers)),
        SampleEnding::Open => {}
    }
    percentile.rank_pooled(&pool.vals)
}