jetro-core 0.5.12

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
use super::ndjson::{ndjson_writer_path_kind, NdjsonOptions, NdjsonWriterPathKind};
use super::ndjson_frame::NdjsonRowFrame;
use super::ndjson_rows::{ndjson_rows_file_plan, NdjsonRowsFilePlan, NdjsonRowsPlanKind};
use super::stream_types::RowStreamStats;
use crate::{JetroEngine, JetroEngineError};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NdjsonSourceMode {
    Reader,
    File,
}

impl std::fmt::Display for NdjsonSourceMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Reader => "reader",
            Self::File => "file",
        })
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NdjsonSourceCaps {
    pub mode: NdjsonSourceMode,
    pub forward: bool,
    pub reverse: bool,
    pub mmap: bool,
    pub partitionable: bool,
    pub framed_payload: bool,
}

impl NdjsonSourceCaps {
    pub fn for_mode(mode: NdjsonSourceMode, options: NdjsonOptions) -> Self {
        match mode {
            NdjsonSourceMode::Reader => Self::reader(options),
            NdjsonSourceMode::File => Self::file(options),
        }
    }

    pub fn reader(options: NdjsonOptions) -> Self {
        Self {
            mode: NdjsonSourceMode::Reader,
            forward: true,
            reverse: false,
            mmap: false,
            partitionable: false,
            framed_payload: options.row_frame != NdjsonRowFrame::JsonLine,
        }
    }

    pub fn file(options: NdjsonOptions) -> Self {
        Self {
            mode: NdjsonSourceMode::File,
            forward: true,
            reverse: true,
            mmap: true,
            partitionable: true,
            framed_payload: options.row_frame != NdjsonRowFrame::JsonLine,
        }
    }
}

impl std::fmt::Display for NdjsonSourceCaps {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.mode)?;
        if self.reverse {
            f.write_str("+reverse")?;
        }
        if self.mmap {
            f.write_str("+mmap")?;
        }
        if self.partitionable {
            f.write_str("+partitionable")?;
        }
        if self.framed_payload {
            f.write_str("+framed-payload")?;
        }
        Ok(())
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NdjsonRouteKind {
    RowLocal,
    Matches,
    RowsStream,
    RowsFanout,
    RowsSubquery,
    UnsupportedRows,
}

impl std::fmt::Display for NdjsonRouteKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::RowLocal => "row-local",
            Self::Matches => "matches",
            Self::RowsStream => "rows-stream",
            Self::RowsFanout => "rows-fanout",
            Self::RowsSubquery => "rows-subquery",
            Self::UnsupportedRows => "unsupported-rows",
        })
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NdjsonFallbackReason {
    FileBackedRowsRequired,
}

impl std::fmt::Display for NdjsonFallbackReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::FileBackedRowsRequired => "rows plan requires a file-backed NDJSON source",
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NdjsonRouteExplain {
    pub kind: NdjsonRouteKind,
    pub source: NdjsonSourceCaps,
    pub writer_path: Option<NdjsonWriterPathKind>,
    pub rows_plan: Option<NdjsonRowsPlanKind>,
    pub fallback_reason: Option<NdjsonFallbackReason>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct NdjsonExecutionStats {
    pub rows_scanned: usize,
    pub rows_emitted: usize,
    pub rows_filtered: usize,
    pub duplicate_rows: usize,
    pub direct_filter_rows: usize,
    pub fallback_filter_rows: usize,
    pub direct_key_rows: usize,
    pub fallback_key_rows: usize,
    pub direct_project_rows: usize,
    pub fallback_project_rows: usize,
    pub parallel_partitions: usize,
    pub hint_learned_rows: usize,
    pub hint_rejected_rows: usize,
    pub hint_rows: usize,
    pub hint_layout_misses: usize,
    pub hint_disabled: bool,
}

impl From<&RowStreamStats> for NdjsonExecutionStats {
    fn from(stats: &RowStreamStats) -> Self {
        Self {
            rows_scanned: stats.rows_scanned,
            rows_emitted: stats.rows_emitted,
            rows_filtered: stats.rows_filtered,
            duplicate_rows: stats.duplicate_rows,
            direct_filter_rows: stats.direct_filter_rows,
            fallback_filter_rows: stats.fallback_filter_rows,
            direct_key_rows: stats.direct_key_rows,
            fallback_key_rows: stats.fallback_key_rows,
            direct_project_rows: stats.direct_project_rows,
            fallback_project_rows: stats.fallback_project_rows,
            parallel_partitions: stats.parallel_partitions,
            hint_learned_rows: 0,
            hint_rejected_rows: 0,
            hint_rows: 0,
            hint_layout_misses: 0,
            hint_disabled: false,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NdjsonExecutionReport {
    pub route: NdjsonRouteExplain,
    pub stats: NdjsonExecutionStats,
}

impl NdjsonExecutionReport {
    pub fn new(route: NdjsonRouteExplain, stats: NdjsonExecutionStats) -> Self {
        Self { route, stats }
    }

    pub fn emitted_only(route: NdjsonRouteExplain, rows_emitted: usize) -> Self {
        Self {
            route,
            stats: NdjsonExecutionStats {
                rows_emitted,
                ..NdjsonExecutionStats::default()
            },
        }
    }
}

pub(crate) enum NdjsonRoutePlan {
    RowLocal {
        explain: NdjsonRouteExplain,
    },
    Rows {
        explain: NdjsonRouteExplain,
        plan: NdjsonRowsFilePlan,
    },
    Unsupported {
        explain: NdjsonRouteExplain,
    },
}

impl NdjsonRoutePlan {
    pub(crate) fn explain(&self) -> &NdjsonRouteExplain {
        match self {
            Self::RowLocal { explain }
            | Self::Rows { explain, .. }
            | Self::Unsupported { explain } => explain,
        }
    }
}

impl NdjsonRouteExplain {
    pub fn matches(source: NdjsonSourceCaps) -> Self {
        Self {
            kind: NdjsonRouteKind::Matches,
            source,
            writer_path: None,
            rows_plan: None,
            fallback_reason: None,
        }
    }

    pub fn is_rows_route(&self) -> bool {
        self.rows_plan.is_some()
    }

    pub fn is_supported(&self) -> bool {
        self.kind != NdjsonRouteKind::UnsupportedRows
    }

    pub fn unsupported_message(&self) -> Option<String> {
        if self.is_supported() {
            return None;
        }
        Some(
            self.fallback_reason
                .map(|reason| reason.to_string())
                .unwrap_or_else(|| "unsupported $.rows() NDJSON route".to_string()),
        )
    }
}

pub(crate) fn ndjson_route_plan(
    engine: &JetroEngine,
    source: NdjsonSourceMode,
    query: &str,
    options: NdjsonOptions,
) -> Result<NdjsonRoutePlan, JetroEngineError> {
    let source = NdjsonSourceCaps::for_mode(source, options);
    let Some(plan) = ndjson_rows_file_plan(query)? else {
        return Ok(NdjsonRoutePlan::RowLocal {
            explain: NdjsonRouteExplain {
                kind: NdjsonRouteKind::RowLocal,
                source,
                writer_path: ndjson_writer_path_kind(engine, query),
                rows_plan: None,
                fallback_reason: None,
            },
        });
    };

    let rows_plan = plan.kind();
    if plan.requires_file_backed_source() && source.mode == NdjsonSourceMode::Reader {
        return Ok(NdjsonRoutePlan::Unsupported {
            explain: NdjsonRouteExplain {
                kind: NdjsonRouteKind::UnsupportedRows,
                source,
                writer_path: None,
                rows_plan: Some(rows_plan),
                fallback_reason: Some(NdjsonFallbackReason::FileBackedRowsRequired),
            },
        });
    }

    Ok(NdjsonRoutePlan::Rows {
        explain: NdjsonRouteExplain {
            kind: route_kind_for_rows_plan(rows_plan),
            source,
            writer_path: None,
            rows_plan: Some(rows_plan),
            fallback_reason: None,
        },
        plan,
    })
}

pub fn ndjson_explain(
    engine: &JetroEngine,
    source: NdjsonSourceMode,
    query: &str,
    options: NdjsonOptions,
) -> Result<NdjsonRouteExplain, JetroEngineError> {
    Ok(ndjson_route_plan(engine, source, query, options)?
        .explain()
        .clone())
}

fn route_kind_for_rows_plan(plan: NdjsonRowsPlanKind) -> NdjsonRouteKind {
    match plan {
        NdjsonRowsPlanKind::Stream => NdjsonRouteKind::RowsStream,
        NdjsonRowsPlanKind::Fanout => NdjsonRouteKind::RowsFanout,
        NdjsonRowsPlanKind::Subquery => NdjsonRouteKind::RowsSubquery,
    }
}

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

    #[test]
    fn route_explain_reports_row_local_and_rows_modes() {
        let engine = JetroEngine::new();
        let row = ndjson_explain(
            &engine,
            NdjsonSourceMode::Reader,
            "$.name",
            NdjsonOptions::default(),
        )
        .unwrap();
        assert_eq!(row.kind, NdjsonRouteKind::RowLocal);
        assert_eq!(row.writer_path, Some(NdjsonWriterPathKind::ByteExpr));
        assert_eq!(row.source.to_string(), "reader");

        let rows = ndjson_explain(
            &engine,
            NdjsonSourceMode::File,
            "$.rows().take(1)",
            NdjsonOptions::default(),
        )
        .unwrap();
        assert_eq!(rows.kind, NdjsonRouteKind::RowsStream);
        assert_eq!(rows.rows_plan, Some(NdjsonRowsPlanKind::Stream));
        assert_eq!(rows.source.to_string(), "file+reverse+mmap+partitionable");
    }

    #[test]
    fn route_explain_marks_reader_rows_subquery_unsupported() {
        let engine = JetroEngine::new();
        let route = ndjson_explain(
            &engine,
            NdjsonSourceMode::Reader,
            r#"{head: $.rows().take(1)}"#,
            NdjsonOptions::default(),
        )
        .unwrap();
        assert_eq!(route.kind, NdjsonRouteKind::UnsupportedRows);
        assert_eq!(
            route.fallback_reason,
            Some(NdjsonFallbackReason::FileBackedRowsRequired)
        );
        assert_eq!(route.kind.to_string(), "unsupported-rows");
        assert_eq!(
            route.fallback_reason.unwrap().to_string(),
            "rows plan requires a file-backed NDJSON source"
        );
        assert!(!route.is_supported());
        assert_eq!(
            route.unsupported_message().unwrap(),
            "rows plan requires a file-backed NDJSON source"
        );
    }

    #[test]
    fn route_explain_marks_reader_rows_fanout_unsupported() {
        let engine = JetroEngine::new();
        let query = r#"let stream = $.rows(), a = stream.take(1), b = stream.count() in {a, b}"#;

        let reader = ndjson_explain(
            &engine,
            NdjsonSourceMode::Reader,
            query,
            NdjsonOptions::default(),
        )
        .unwrap();
        assert_eq!(reader.kind, NdjsonRouteKind::UnsupportedRows);
        assert_eq!(reader.rows_plan, Some(NdjsonRowsPlanKind::Fanout));
        assert_eq!(
            reader.fallback_reason,
            Some(NdjsonFallbackReason::FileBackedRowsRequired)
        );

        let file = ndjson_explain(
            &engine,
            NdjsonSourceMode::File,
            query,
            NdjsonOptions::default(),
        )
        .unwrap();
        assert_eq!(file.kind, NdjsonRouteKind::RowsFanout);
        assert!(file.is_supported());
        assert!(file.fallback_reason.is_none());
    }

    #[test]
    fn execution_stats_copy_row_stream_counters() {
        let stream = RowStreamStats {
            rows_scanned: 3,
            rows_emitted: 2,
            rows_filtered: 1,
            direct_project_rows: 2,
            parallel_partitions: 4,
            ..RowStreamStats::default()
        };
        let stats = NdjsonExecutionStats::from(&stream);
        assert_eq!(stats.rows_scanned, 3);
        assert_eq!(stats.rows_emitted, 2);
        assert_eq!(stats.rows_filtered, 1);
        assert_eq!(stats.direct_project_rows, 2);
        assert_eq!(stats.parallel_partitions, 4);
    }
}