jetro-core 0.5.10

jetro-core: parser, compiler, and VM for the Jetro JSON query language
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
//! Operator IR types: `ReducerSpec`, `SortSpec`, `NumOp`, and related enums.
//! Shared across lowering, execution, and the composed substrate.

use std::sync::Arc;

use crate::builtins::BuiltinMethod;
use crate::parse::ast::Expr;
use crate::plan::demand::{Demand, PullDemand, SinkResultDemand, ValueNeed};
use crate::vm::Program;

use super::NumOp;

/// Specification for a terminal reducer sink (`count`, `sum`, `avg`, `min`, `max`).
#[derive(Debug, Clone)]
pub struct ReducerSpec {
    /// The aggregation operation to perform.
    pub op: ReducerOp,
    /// Optional predicate that gates which rows are counted or aggregated.
    pub predicate: Option<Arc<Program>>,
    /// Optional projection applied to each row before aggregation.
    pub projection: Option<Arc<Program>>,
    /// Source AST for `predicate`, used during IR analysis.
    pub predicate_expr: Option<Arc<Expr>>,
    /// Source AST for `projection`, used during IR analysis.
    pub projection_expr: Option<Arc<Expr>>,
}

/// Specification for predicate terminal sinks (`any`, `all`, `find_index`, `find_one`).
#[derive(Debug, Clone)]
pub struct PredicateSinkSpec {
    /// Terminal operation to perform.
    pub op: PredicateSinkOp,
    /// Predicate evaluated for each row until the terminal can decide.
    pub predicate: Arc<Program>,
}

/// Specification for value-membership terminal sinks (`includes`, `index`, `indices_of`).
#[derive(Debug, Clone)]
pub struct MembershipSinkSpec {
    /// Terminal operation to perform.
    pub op: MembershipSinkOp,
    /// Value compared against each row.
    pub target: MembershipSinkTarget,
    /// Original builtin method used for scalar fallback.
    pub method: BuiltinMethod,
}

/// Target value source for value-membership terminal sinks.
#[derive(Debug, Clone)]
pub enum MembershipSinkTarget {
    /// Literal known during lowering.
    Literal(crate::data::value::Val),
    /// Expression evaluated once before rows are streamed.
    Program(Arc<Program>),
}

/// Specification for arg-extreme terminal sinks (`max_by`, `min_by`).
#[derive(Debug, Clone)]
pub struct ArgExtremeSinkSpec {
    /// When true, keeps the row with the largest key; otherwise keeps the smallest key.
    pub want_max: bool,
    /// Key expression evaluated for each row.
    pub key: Arc<Program>,
}

/// Predicate terminal operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PredicateSinkOp {
    /// Returns true when any row matches the predicate.
    Any,
    /// Returns true when every row matches the predicate.
    All,
    /// Returns the zero-based index of the first matching row, or null.
    FindIndex,
    /// Returns all zero-based indices whose rows match the predicate.
    IndicesWhere,
    /// Returns exactly one matching row, erroring on zero or multiple matches.
    FindOne,
}

/// Value-membership terminal operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MembershipSinkOp {
    /// Returns true when any row equals the target.
    Includes,
    /// Returns the zero-based index of the first matching row, or null.
    Index,
    /// Returns all zero-based indices matching the target.
    IndicesOf,
}

impl PredicateSinkSpec {
    /// Constructs a predicate terminal sink from the builtin method.
    pub(crate) fn from_method(method: BuiltinMethod, predicate: Arc<Program>) -> Option<Self> {
        Some(Self {
            op: match method {
                BuiltinMethod::Any => PredicateSinkOp::Any,
                BuiltinMethod::All => PredicateSinkOp::All,
                BuiltinMethod::FindIndex => PredicateSinkOp::FindIndex,
                BuiltinMethod::IndicesWhere => PredicateSinkOp::IndicesWhere,
                BuiltinMethod::FindOne => PredicateSinkOp::FindOne,
                _ => return None,
            },
            predicate,
        })
    }

    /// Demand placed on the row stream by this terminal predicate sink.
    pub(crate) fn demand(&self) -> Demand {
        // Predicate sinks can short-circuit inside their accumulator, but the shared
        // pull model counts source rows emitted by the stage chain. Treating
        // `any`/`find_index` as `UntilOutput(1)` would stop after one non-matching
        // input row before the predicate sink has produced its scalar result.
        Demand {
            pull: PullDemand::All,
            value: if self.op == PredicateSinkOp::FindOne {
                ValueNeed::Whole
            } else {
                ValueNeed::Predicate
            },
            order: false,
        }
    }

    /// Scalar sink-result demand for accumulator-level short-circuit planning.
    pub(crate) fn sink_result_demand(&self) -> SinkResultDemand {
        match self.op {
            PredicateSinkOp::Any | PredicateSinkOp::FindIndex => SinkResultDemand::UntilMatch,
            PredicateSinkOp::All => SinkResultDemand::UntilFailure,
            PredicateSinkOp::IndicesWhere | PredicateSinkOp::FindOne => SinkResultDemand::None,
        }
    }

    /// Iterates over embedded programs for kernel enumeration.
    pub(crate) fn sink_programs(&self) -> impl Iterator<Item = &Arc<Program>> {
        std::iter::once(&self.predicate)
    }

    /// Returns the sink-kernel index for the predicate.
    pub(crate) fn predicate_kernel_index(&self) -> usize {
        0
    }
}

impl MembershipSinkSpec {
    /// Constructs a membership terminal sink from the builtin method.
    pub(crate) fn from_method(
        method: BuiltinMethod,
        target: MembershipSinkTarget,
    ) -> Option<Self> {
        Some(Self {
            op: match method {
                BuiltinMethod::Includes => MembershipSinkOp::Includes,
                BuiltinMethod::Index => MembershipSinkOp::Index,
                BuiltinMethod::IndicesOf => MembershipSinkOp::IndicesOf,
                _ => return None,
            },
            target,
            method,
        })
    }

    /// Demand placed on the row stream by this terminal membership sink.
    pub(crate) fn demand(&self) -> Demand {
        // `includes` and `index` can stop once their accumulator observes a match,
        // but the pull demand is still over input rows, not over the terminal
        // scalar result. Keep the source conservative and let the sink stop the
        // executor loop when it has enough information.
        Demand {
            pull: PullDemand::All,
            value: ValueNeed::Whole,
            order: false,
        }
    }

    /// Scalar sink-result demand for accumulator-level short-circuit planning.
    pub(crate) fn sink_result_demand(&self) -> SinkResultDemand {
        match self.op {
            MembershipSinkOp::Includes | MembershipSinkOp::Index => SinkResultDemand::UntilMatch,
            MembershipSinkOp::IndicesOf => SinkResultDemand::None,
        }
    }

    /// Iterates over embedded programs for kernel enumeration.
    pub(crate) fn sink_programs(&self) -> impl Iterator<Item = &Arc<Program>> {
        match &self.target {
            MembershipSinkTarget::Literal(_) => None,
            MembershipSinkTarget::Program(program) => Some(program),
        }
        .into_iter()
    }
}

impl ArgExtremeSinkSpec {
    /// Constructs an arg-extreme sink from the terminal builtin method.
    pub(crate) fn from_method(method: BuiltinMethod, key: Arc<Program>) -> Option<Self> {
        Some(Self {
            want_max: match method {
                BuiltinMethod::MaxBy => true,
                BuiltinMethod::MinBy => false,
                _ => return None,
            },
            key,
        })
    }

    /// Demand placed on the row stream by this terminal arg-extreme sink.
    pub(crate) fn demand(&self) -> Demand {
        Demand {
            pull: PullDemand::All,
            value: ValueNeed::Whole,
            order: true,
        }
    }

    /// Iterates over embedded programs for kernel enumeration.
    pub(crate) fn sink_programs(&self) -> impl Iterator<Item = &Arc<Program>> {
        std::iter::once(&self.key)
    }

    /// Returns the sink-kernel index for the key projection.
    pub(crate) fn key_kernel_index(&self) -> usize {
        0
    }
}

/// The kind of reduction a `ReducerSpec` performs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReducerOp {
    /// Counts the number of (predicate-passing) rows.
    Count,
    /// Applies a numeric aggregate (`Sum`, `Avg`, `Min`, `Max`).
    Numeric(NumOp),
}

impl ReducerSpec {
    /// Constructs a plain `Count` reducer with no predicate or projection.
    pub fn count() -> Self {
        Self {
            op: ReducerOp::Count,
            predicate: None,
            projection: None,
            predicate_expr: None,
            projection_expr: None,
        }
    }

    /// Constructs a `Count` reducer gated by a predicate expression.
    pub fn count_with_predicate(
        predicate: Arc<Program>,
        predicate_expr: Option<Arc<Expr>>,
    ) -> Self {
        Self {
            op: ReducerOp::Count,
            predicate: Some(predicate),
            projection: None,
            predicate_expr,
            projection_expr: None,
        }
    }

    /// Constructs a numeric reducer from builtin metadata.
    pub fn numeric(
        method: BuiltinMethod,
        projection: Option<Arc<Program>>,
        projection_expr: Option<Arc<Expr>>,
    ) -> Option<Self> {
        Some(Self {
            op: ReducerOp::Numeric(NumOp::from_builtin_reducer(method.spec().numeric_reducer?)),
            predicate: None,
            projection,
            predicate_expr: None,
            projection_expr,
        })
    }

    /// Returns the `NumOp` for a `Numeric` reducer, or `None` for `Count`.
    pub fn numeric_op(&self) -> Option<NumOp> {
        match self.op {
            ReducerOp::Numeric(op) => Some(op),
            ReducerOp::Count => None,
        }
    }

    /// Iterates over embedded programs (predicate then projection) for kernel enumeration.
    pub(crate) fn sink_programs(&self) -> impl Iterator<Item = &Arc<Program>> {
        self.predicate.iter().chain(self.projection.iter())
    }

    /// Returns the sink-kernel index for the predicate (`0` when present), or `None`.
    pub(crate) fn predicate_kernel_index(&self) -> Option<usize> {
        self.predicate.as_ref().map(|_| 0)
    }

    /// Returns the sink-kernel index for the projection (`1` when a predicate also exists), or `None`.
    pub(crate) fn projection_kernel_index(&self) -> Option<usize> {
        self.projection
            .as_ref()
            .map(|_| usize::from(self.predicate.is_some()))
    }

    /// Returns the `BuiltinMethod` corresponding to this reducer operation.
    pub fn method(&self) -> Option<BuiltinMethod> {
        match self.op {
            ReducerOp::Count => Some(BuiltinMethod::Count),
            ReducerOp::Numeric(op) => Some(op.method()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn empty_program() -> Arc<Program> {
        Arc::new(Program::new(Vec::new(), "<sink-demand-test>"))
    }

    #[test]
    fn terminal_sink_specs_construct_from_methods() {
        let predicate = PredicateSinkSpec::from_method(BuiltinMethod::Any, empty_program())
            .expect("any predicate sink");
        assert_eq!(predicate.op, PredicateSinkOp::Any);
        assert!(PredicateSinkSpec::from_method(BuiltinMethod::Count, empty_program()).is_none());

        let membership = MembershipSinkSpec::from_method(
            BuiltinMethod::IndicesOf,
            MembershipSinkTarget::Literal(crate::data::value::Val::Int(1)),
        )
        .expect("indices_of membership sink");
        assert_eq!(membership.op, MembershipSinkOp::IndicesOf);
        assert!(MembershipSinkSpec::from_method(
            BuiltinMethod::Count,
            MembershipSinkTarget::Literal(crate::data::value::Val::Int(1)),
        )
        .is_none());

        let max_by = ArgExtremeSinkSpec::from_method(BuiltinMethod::MaxBy, empty_program())
            .expect("max_by arg-extreme sink");
        assert!(max_by.want_max);
        let min_by = ArgExtremeSinkSpec::from_method(BuiltinMethod::MinBy, empty_program())
            .expect("min_by arg-extreme sink");
        assert!(!min_by.want_max);
        assert!(ArgExtremeSinkSpec::from_method(BuiltinMethod::Count, empty_program()).is_none());
    }

    #[test]
    fn predicate_sink_demand_matches_terminal_semantics() {
        let any = PredicateSinkSpec {
            op: PredicateSinkOp::Any,
            predicate: empty_program(),
        }
        .demand();
        assert_eq!(any.pull, PullDemand::All);
        assert_eq!(any.value, ValueNeed::Predicate);
        assert!(!any.order);
        assert_eq!(
            PredicateSinkSpec {
                op: PredicateSinkOp::Any,
                predicate: empty_program(),
            }
            .sink_result_demand(),
            SinkResultDemand::UntilMatch
        );
        assert_eq!(
            PredicateSinkSpec {
                op: PredicateSinkOp::All,
                predicate: empty_program(),
            }
            .sink_result_demand(),
            SinkResultDemand::UntilFailure
        );

        let find_one = PredicateSinkSpec {
            op: PredicateSinkOp::FindOne,
            predicate: empty_program(),
        }
        .demand();
        assert_eq!(find_one.pull, PullDemand::All);
        assert_eq!(find_one.value, ValueNeed::Whole);
        assert!(!find_one.order);
    }

    #[test]
    fn membership_and_arg_extreme_demands_match_terminal_semantics() {
        let membership = MembershipSinkSpec {
            op: MembershipSinkOp::Includes,
            target: MembershipSinkTarget::Literal(crate::data::value::Val::Int(1)),
            method: BuiltinMethod::Includes,
        }
        .demand();
        assert_eq!(membership.pull, PullDemand::All);
        assert_eq!(membership.value, ValueNeed::Whole);
        assert!(!membership.order);
        assert_eq!(
            MembershipSinkSpec {
                op: MembershipSinkOp::Includes,
                target: MembershipSinkTarget::Literal(crate::data::value::Val::Int(1)),
                method: BuiltinMethod::Includes,
            }
            .sink_result_demand(),
            SinkResultDemand::UntilMatch
        );

        let arg_extreme = ArgExtremeSinkSpec {
            want_max: true,
            key: empty_program(),
        }
        .demand();
        assert_eq!(arg_extreme.pull, PullDemand::All);
        assert_eq!(arg_extreme.value, ValueNeed::Whole);
        assert!(arg_extreme.order);
    }
}