fv-streams-sql 0.2.0

The SQL front door for FusionVault Streams: a streaming SQL statement parses to a small typed logical plan and lowers to the same topology the TOML frontend produces — one runtime, two front doors. No DataFusion planner, no fork; expressions compile through the value dialect as the steps already do.
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
//! # fv-streams-sql — the SQL front door
//!
//! A streaming SQL statement parses to a **small typed logical plan** ([`plan::Plan`]) and lowers to
//! the *same* [`Topology`] of [`StageDef`]s the TOML frontend produces (whose `steps` are the engine's
//! own JSON vocabulary). One runtime, two front doors: SQL inherits checkpointing, the exchange,
//! exactness and `--join` because it emits the identical steps a hand-written pipeline would.
//!
//! Deliberately **not** DataFusion's `LogicalPlan`/physical layer (design §10): our own IR models
//! streaming (DataFusion's does not), so there is no fork risk, the errors are streaming-aware and
//! ours, and the IR is the seam a future optimiser plugs into. Scalar expressions lower to the value
//! dialect strings the `expression` steps already carry, compiled through `fv-value-datafusion` at
//! build time exactly as the TOML path does.
//!
//! ```
//! let topo = fv_streams_sql::compile(
//!     "INSERT INTO out SELECT auction, price * 0.908 AS eur FROM bids WHERE type = 'bid'",
//! ).unwrap();
//! assert_eq!(topo.stages.len(), 1);
//! ```

use fv_streams_engine::Topology;

mod expr;
mod lower;
mod plan;

pub use plan::Plan;

/// Compile one streaming SQL statement into a [`Topology`]. Datasets (the `FROM`/`INSERT INTO`
/// targets) are referenced by name; their bindings (topic, connector, schema) stay in the pipeline
/// config, exactly as the TOML frontend resolves them. Fails LOUDLY with a streaming-aware message
/// on anything outside the supported subset.
pub fn compile(sql: &str) -> Result<Topology, String> {
    let plan = plan::parse(sql)?;
    let plan = optimize(plan);
    let stages = lower::lower(&plan)?;
    Ok(Topology { stages })
}

/// The optimiser seam: passes over the typed IR (filter pushdown, projection pruning, …) go here —
/// streaming-aware because the IR is. Empty today; the boundary exists so a mature optimiser is
/// additive, on our own IR, never a rewrite (design §10).
fn optimize(plan: Plan) -> Plan {
    plan
}

/// Lower a plan to `StageDef`s without wrapping in a `Topology` — for tests that assert the steps.
#[cfg(test)]
pub(crate) fn compile_stages(sql: &str) -> Result<Vec<fv_streams_engine::StageDef>, String> {
    lower::lower(&optimize(plan::parse(sql)?))
}

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

    #[test]
    fn a_filter_projection_lowers_to_the_same_steps_the_toml_would() {
        let stages =
            compile_stages("INSERT INTO out SELECT auction, price * 0.908 AS eur FROM bids WHERE type = 'bid'")
                .unwrap();
        assert_eq!(stages.len(), 1);
        let s = &stages[0];
        assert_eq!(s.inputs, vec!["bids".to_string()]);
        assert_eq!(s.output, "out");
        assert_eq!(
            s.steps,
            vec![
                json!({"op": "filter", "expression": "(type == 'bid')"}),
                json!({"op": "applyExpression", "column": "eur", "expression": "(price * 0.908)"}),
                json!({"op": "select", "columns": ["auction", "eur"]}),
            ]
        );
    }

    #[test]
    fn select_star_is_a_pass_through_no_steps() {
        let s = &compile_stages("INSERT INTO out SELECT * FROM bids").unwrap()[0];
        assert!(s.steps.is_empty());
        assert_eq!(s.inputs, vec!["bids".to_string()]);
        assert_eq!(s.output, "out");
    }

    #[test]
    fn star_plus_a_computed_column_keeps_all_columns_the_q1_shape() {
        // `SELECT *, <expr> AS name` = keep every column + add one (Nexmark q1) → applyExpression, no select.
        let s = &compile_stages(
            "INSERT INTO out SELECT *, price * 0.908 AS priceEur FROM events WHERE type = 'bid'",
        )
        .unwrap()[0];
        assert_eq!(
            s.steps,
            vec![
                json!({"op": "filter", "expression": "(type == 'bid')"}),
                json!({"op": "applyExpression", "column": "priceEur", "expression": "(price * 0.908)"}),
            ]
        );
        // a bare column with `*` is redundant → a loud error.
        assert!(compile("INSERT INTO o SELECT *, auction FROM b").is_err());
    }

    #[test]
    fn boolean_comparison_and_case_render_in_the_value_dialect() {
        let s = &compile_stages(
            "INSERT INTO out SELECT CASE WHEN price < 100 THEN 1 ELSE 0 END AS band FROM b WHERE a > 1 AND c = 2",
        )
        .unwrap()[0];
        // SQL AND/= → dialect &&/== ; CASE → ternary.
        assert_eq!(s.steps[0], json!({"op": "filter", "expression": "((a > 1) && (c == 2))"}));
        assert_eq!(
            s.steps[1],
            json!({"op": "applyExpression", "column": "band", "expression": "((price < 100) ? 1 : 0)"})
        );
    }

    #[test]
    fn a_bare_rename_and_a_function_call_lower_correctly() {
        let s = &compile_stages("INSERT INTO out SELECT bidder AS who, round(price * 0.9) AS p FROM b").unwrap()[0];
        assert_eq!(s.steps[0], json!({"op": "applyExpression", "column": "who", "expression": "bidder"}));
        assert_eq!(s.steps[1], json!({"op": "applyExpression", "column": "p", "expression": "round((price * 0.9))"}));
        assert_eq!(s.steps[2], json!({"op": "select", "columns": ["who", "p"]}));
    }

    #[test]
    fn the_unsupported_shapes_are_rejected_with_streaming_aware_errors() {
        // a bare SELECT with no sink
        assert!(compile("SELECT * FROM b").unwrap_err().contains("INSERT INTO"));
        // GROUP BY without a window / EMIT
        assert!(compile("INSERT INTO o SELECT count(*) AS n FROM b GROUP BY x")
            .unwrap_err()
            .contains("window"));
        // a comma join (only `JOIN … ON …` is supported)
        assert!(compile("INSERT INTO o SELECT * FROM a, b").is_err());
        // a set operation
        assert!(compile("INSERT INTO o SELECT * FROM a UNION SELECT * FROM b")
            .unwrap_err()
            .contains("UNION"));
        // an unbounded ORDER BY → points at ROW_NUMBER top-N
        assert!(compile("INSERT INTO o SELECT * FROM b ORDER BY price")
            .unwrap_err()
            .contains("ROW_NUMBER"));
    }

    #[test]
    fn a_tumbling_windowed_aggregate_lowers_to_the_windowedaggregate_step() {
        let s = &compile_stages(
            "INSERT INTO out SELECT auction, count(*) AS n, max(price) AS top \
             FROM bids WHERE type = 'bid' GROUP BY auction, TUMBLE(dateTime, INTERVAL '10' SECOND)",
        )
        .unwrap()[0];
        assert_eq!(s.inputs, vec!["bids".to_string()]);
        assert_eq!(s.output, "out");
        assert_eq!(s.steps[0], json!({"op": "filter", "expression": "(type == 'bid')"}));
        assert_eq!(
            s.steps[1],
            json!({
                "op": "windowedAggregate",
                "timeColumn": "dateTime",
                "windowMs": 10000,
                "keyBy": true,
                "groupBy": ["auction"],
                "aggs": [
                    {"op": "count", "column": "", "alias": "n"},
                    {"op": "max", "column": "price", "alias": "top"},
                ],
            })
        );
    }

    #[test]
    fn hop_is_a_sliding_window_and_session_is_a_session_aggregate() {
        let hop = &compile_stages(
            "INSERT INTO o SELECT auction, count(*) AS n FROM b GROUP BY auction, HOP(ts, INTERVAL '2' SECOND, INTERVAL '10' SECOND)",
        )
        .unwrap()[0];
        assert_eq!(
            hop.steps[0],
            json!({"op": "windowedAggregate", "timeColumn": "ts", "windowMs": 10000, "slideMs": 2000,
                   "keyBy": true, "groupBy": ["auction"], "aggs": [{"op": "count", "column": "", "alias": "n"}]})
        );
        let sess = &compile_stages(
            "INSERT INTO o SELECT bidder, sum(price) AS s FROM b GROUP BY bidder, SESSION(ts, INTERVAL '5' SECOND)",
        )
        .unwrap()[0];
        assert_eq!(
            sess.steps[0],
            json!({"op": "sessionAggregate", "timeColumn": "ts", "gapMs": 5000,
                   "keyBy": true, "groupBy": ["bidder"], "aggs": [{"op": "sum", "column": "price", "alias": "s"}]})
        );
    }

    #[test]
    fn emit_changes_makes_it_the_updating_aggregate_q17_shape() {
        // q17: per-auction, per-day, updated as they change.
        let s = &compile_stages(
            "INSERT INTO out SELECT auction, count(*) AS n FROM bids WHERE type = 'bid' \
             GROUP BY auction, TUMBLE(dateTime, INTERVAL '1' DAY) EMIT CHANGES EVERY 5000 ROWS",
        )
        .unwrap()[0];
        assert_eq!(s.steps[0], json!({"op": "filter", "expression": "(type == 'bid')"}));
        assert_eq!(
            s.steps[1],
            json!({
                "op": "windowedAggregate",
                "timeColumn": "dateTime",
                "windowMs": 86_400_000,
                "keyBy": true,
                "groupBy": ["auction"],
                "aggs": [{"op": "count", "column": "", "alias": "n"}],
                "emit": {"everyRows": 5000},
            }),
            "EMIT CHANGES EVERY n ROWS → the emit block the engine's parse_trigger reads"
        );

        // EVERY n MS → the processing-time trigger.
        let ms = &compile_stages(
            "INSERT INTO o SELECT k, count(*) AS n FROM b GROUP BY k, TUMBLE(ts, INTERVAL '10' SECOND) EMIT CHANGES EVERY 500 MS",
        )
        .unwrap()[0];
        assert_eq!(ms.steps[0]["emit"], json!({"everyMs": 500}));
    }

    #[test]
    fn emit_is_rejected_where_it_has_no_meaning_and_needs_a_cadence() {
        // EMIT on a stateless SELECT (no aggregate)
        assert!(compile("INSERT INTO o SELECT * FROM b EMIT CHANGES EVERY 1 ROWS")
            .unwrap_err()
            .contains("windowed"));
        // EMIT CHANGES with no cadence
        assert!(compile("INSERT INTO o SELECT k, count(*) AS n FROM b GROUP BY k, TUMBLE(ts, INTERVAL '1' SECOND) EMIT CHANGES")
            .unwrap_err()
            .to_lowercase()
            .contains("cadence"));
        // EMIT on a session aggregate (the operator that early-fires is the windowed one)
        assert!(compile("INSERT INTO o SELECT k, count(*) AS n FROM b GROUP BY k, SESSION(ts, INTERVAL '5' SECOND) EMIT CHANGES EVERY 1 ROWS")
            .unwrap_err()
            .to_lowercase()
            .contains("session"));
    }

    #[test]
    fn the_word_emit_inside_a_string_literal_is_not_a_trigger() {
        // the quote-aware pre-pass must not strip `emit` when it is data, not a clause.
        let s = &compile_stages("INSERT INTO o SELECT channel FROM b WHERE channel = 'emit changes'").unwrap()[0];
        assert_eq!(s.steps[0], json!({"op": "filter", "expression": "(channel == 'emit changes')"}));
        assert_eq!(s.steps.last().unwrap(), &json!({"op": "select", "columns": ["channel"]}));
    }

    #[test]
    fn count_distinct_and_a_case_argument_become_a_pre_column_the_q15_shape() {
        let s = &compile_stages(
            "INSERT INTO o SELECT auction, count(*) AS total, count(DISTINCT bidder) AS bidders, \
             count(DISTINCT CASE WHEN price < 10000 THEN bidder END) AS r1bidders \
             FROM b GROUP BY auction, TUMBLE(ts, INTERVAL '1' DAY)",
        )
        .unwrap()[0];
        // the CASE argument becomes a synthetic pre-aggregate applyExpression column.
        assert_eq!(
            s.steps[0],
            json!({"op": "applyExpression", "column": "_fv_agg0", "expression": "((price < 10000) ? bidder : null)"})
        );
        assert_eq!(
            s.steps[1],
            json!({
                "op": "windowedAggregate", "timeColumn": "ts", "windowMs": 86_400_000, "keyBy": true,
                "groupBy": ["auction"],
                "aggs": [
                    {"op": "count", "column": "", "alias": "total"},
                    {"op": "countDistinct", "column": "bidder", "alias": "bidders"},
                    {"op": "countDistinct", "column": "_fv_agg0", "alias": "r1bidders"},
                ],
            })
        );
        // DISTINCT is only on count()
        assert!(compile("INSERT INTO o SELECT sum(DISTINCT x) AS s FROM b GROUP BY k, TUMBLE(ts, INTERVAL '1' SECOND)").is_err());
    }

    #[test]
    fn a_post_aggregate_computed_column_lowers_after_the_aggregate_the_q15_day_shape() {
        let s = &compile_stages(
            "INSERT INTO out SELECT count(*) AS total, count(DISTINCT CASE WHEN price < 10000 THEN bidder END) AS r1, \
             substring(epochToIso(windowStart), 0, 10) AS day \
             FROM events WHERE type = 'bid' GROUP BY TUMBLE(dateTime, INTERVAL '1' DAY)",
        )
        .unwrap()[0];
        // order: filter, pre (CASE), windowedAggregate, post (day).
        assert_eq!(s.steps[0], json!({"op": "filter", "expression": "(type == 'bid')"}));
        assert_eq!(s.steps[1], json!({"op": "applyExpression", "column": "_fv_agg0", "expression": "((price < 10000) ? bidder : null)"}));
        assert_eq!(s.steps[2]["op"], "windowedAggregate");
        assert_eq!(s.steps[2]["aggs"][1], json!({"op": "countDistinct", "column": "_fv_agg0", "alias": "r1"}));
        assert_eq!(
            s.steps[3],
            json!({"op": "applyExpression", "column": "day", "expression": "substring(epochToIso(windowStart), 0, 10)"})
        );
    }

    #[test]
    fn a_group_by_without_a_window_is_rejected_with_a_pointer_to_windows_or_emit() {
        let e = compile("INSERT INTO o SELECT auction, count(*) AS n FROM b GROUP BY auction").unwrap_err();
        assert!(e.contains("window") || e.contains("EMIT"), "got: {e}");
        // an interval with an unknown unit is a loud error, not a silent zero.
        assert!(compile("INSERT INTO o SELECT count(*) AS n FROM b GROUP BY TUMBLE(ts, INTERVAL '10' YEAR)").is_err());
    }

    #[test]
    fn a_plain_equi_join_lowers_to_the_5b_lookup_join() {
        let s = &compile_stages(
            "INSERT INTO out SELECT bids.auction, side.value FROM bids JOIN side ON bids.key = side.key",
        )
        .unwrap()[0];
        // inputs[0]=stream, inputs[1]=table (FROM … JOIN …).
        assert_eq!(s.inputs, vec!["bids".to_string(), "side".to_string()]);
        assert_eq!(s.steps[0], json!({"op": "lookupJoin", "joinKey": "key"}));
        assert_eq!(s.steps.last().unwrap(), &json!({"op": "select", "columns": ["auction", "value"]}));
    }

    #[test]
    fn a_join_with_a_time_interval_lowers_to_the_stream_join() {
        let s = &compile_stages(
            "INSERT INTO out SELECT a.x, b.y FROM a JOIN b \
             ON a.k = b.k AND a.ts BETWEEN b.ts - INTERVAL '5' SECOND AND b.ts + INTERVAL '5' SECOND",
        )
        .unwrap()[0];
        assert_eq!(s.inputs, vec!["a".to_string(), "b".to_string()]);
        assert_eq!(
            s.steps[0],
            json!({"op": "streamJoin", "joinKey": "k", "timeColumn": "ts", "windowMs": 5000, "keyBy": true})
        );
    }

    #[test]
    fn row_number_top_n_lowers_to_the_topn_operator() {
        let s = &compile_stages(
            "INSERT INTO out SELECT auction, price FROM ( \
               SELECT auction, price, ROW_NUMBER() OVER (PARTITION BY auction ORDER BY price DESC) AS rn FROM bids \
             ) WHERE rn <= 1",
        )
        .unwrap()[0];
        assert_eq!(s.inputs, vec!["bids".to_string()]);
        assert_eq!(
            s.steps[0],
            json!({"op": "topN", "n": 1, "orderBy": "price", "direction": "desc", "keyBy": true, "groupBy": ["auction"]})
        );
        assert_eq!(s.steps.last().unwrap(), &json!({"op": "select", "columns": ["auction", "price"]}));
        // ORDER BY ASC and n=10 top-N.
        let asc = &compile_stages(
            "INSERT INTO o SELECT k FROM (SELECT k, v, ROW_NUMBER() OVER (PARTITION BY k ORDER BY v) AS rn FROM t) WHERE rn <= 10",
        )
        .unwrap()[0];
        assert_eq!(asc.steps[0]["direction"], "asc");
        assert_eq!(asc.steps[0]["n"], 10);
    }

    #[test]
    fn a_join_key_with_mismatched_column_names_is_a_loud_error() {
        assert!(compile("INSERT INTO o SELECT * FROM a JOIN b ON a.x = b.y")
            .unwrap_err()
            .contains("share a name"));
    }

    #[test]
    fn compile_wraps_the_stages_in_a_topology() {
        let topo = compile("INSERT INTO out SELECT * FROM bids").unwrap();
        assert_eq!(topo.stages.len(), 1);
        assert_eq!(topo.stages[0].output, "out");
    }

    // ── Multi-stage (5c-v): a CTE materialises as its own stage, referenced by name downstream — the
    // SQL equivalent of the TOML `[[transforms]]` DAG. ──

    #[test]
    fn a_cte_computing_a_key_then_a_lookup_join_is_two_stages_the_q13_shape() {
        // q13: enrich bids against a bounded side table on a COMPUTED key (auction % N). The key
        // must exist on the stream before the join → a `WITH` stage, then the join stage.
        let stages = compile_stages(
            "INSERT INTO out \
             WITH bids AS (SELECT *, auction % 30011 AS key FROM events WHERE type = 'bid') \
             SELECT * FROM bids JOIN side ON bids.key = side.key",
        )
        .unwrap();
        assert_eq!(stages.len(), 2, "the CTE is its own stage, then the join");
        // stage 0 = the CTE: filter + the computed key, output under the CTE name.
        assert_eq!(stages[0].output, "bids");
        assert_eq!(stages[0].inputs, vec!["events".to_string()]);
        assert_eq!(
            stages[0].steps,
            vec![
                json!({"op": "filter", "expression": "(type == 'bid')"}),
                json!({"op": "applyExpression", "column": "key", "expression": "(auction % 30011)"}),
            ]
        );
        // stage 1 = the lookup join, reading the CTE and the bounded table.
        assert_eq!(stages[1].output, "out");
        assert_eq!(stages[1].inputs, vec!["bids".to_string(), "side".to_string()]);
        assert_eq!(stages[1].steps, vec![json!({"op": "lookupJoin", "joinKey": "key"})]);
    }

    #[test]
    fn a_windowed_count_cte_then_a_per_window_top_n_is_two_stages_the_q5_shape() {
        // q5 hot items: a sliding windowed count per auction (a CTE), then top-1 per window.
        let stages = compile_stages(
            "INSERT INTO out \
             WITH counts AS ( \
               SELECT auction, count(*) AS n FROM events WHERE type = 'bid' \
               GROUP BY auction, HOP(dateTime, INTERVAL '2' SECOND, INTERVAL '10' SECOND) \
             ) \
             SELECT auction FROM ( \
               SELECT auction, n, ROW_NUMBER() OVER (PARTITION BY windowStart ORDER BY n DESC, auction) AS rn \
               FROM counts \
             ) WHERE rn <= 1",
        )
        .unwrap();
        assert_eq!(stages.len(), 2);
        // stage 0 = the sliding windowed count.
        assert_eq!(stages[0].output, "counts");
        assert_eq!(stages[0].inputs, vec!["events".to_string()]);
        assert_eq!(stages[0].steps[0], json!({"op": "filter", "expression": "(type == 'bid')"}));
        assert_eq!(
            stages[0].steps[1],
            json!({"op": "windowedAggregate", "timeColumn": "dateTime", "windowMs": 10000, "slideMs": 2000,
                   "keyBy": true, "groupBy": ["auction"], "aggs": [{"op": "count", "column": "", "alias": "n"}]})
        );
        // stage 1 = top-1 per window over the counts, projected to the hot auction.
        assert_eq!(stages[1].output, "out");
        assert_eq!(stages[1].inputs, vec!["counts".to_string()]);
        assert_eq!(
            stages[1].steps[0],
            json!({"op": "topN", "n": 1, "orderBy": "n", "direction": "desc", "keyBy": true,
                   "groupBy": ["windowStart"], "tieBy": "auction"})
        );
        assert_eq!(stages[1].steps[1], json!({"op": "select", "columns": ["auction"]}));
    }

    #[test]
    fn a_cte_feeding_an_aggregate_nests_two_aggregates_the_q4_shape() {
        // q4-shaped: a per-auction max in a CTE, then an average over those maxima — an aggregate
        // reading another aggregate's output (two windowed stages).
        let stages = compile_stages(
            "INSERT INTO out \
             WITH perAuction AS ( \
               SELECT category, max(price) AS finalPrice FROM catBids \
               GROUP BY category, TUMBLE(dateTime, INTERVAL '10' SECOND) \
             ) \
             SELECT category, avg(finalPrice) AS avgFinal FROM perAuction \
             GROUP BY category, TUMBLE(windowStart, INTERVAL '10' SECOND)",
        )
        .unwrap();
        assert_eq!(stages.len(), 2);
        assert_eq!(stages[0].output, "perAuction");
        assert_eq!(stages[0].inputs, vec!["catBids".to_string()]);
        assert_eq!(stages[0].steps[0]["op"], "windowedAggregate");
        assert_eq!(stages[0].steps[0]["aggs"], json!([{"op": "max", "column": "price", "alias": "finalPrice"}]));
        assert_eq!(stages[1].output, "out");
        assert_eq!(stages[1].inputs, vec!["perAuction".to_string()]);
        assert_eq!(stages[1].steps[0]["aggs"], json!([{"op": "avg", "column": "finalPrice", "alias": "avgFinal"}]));
    }

    #[test]
    fn a_chain_of_ctes_wires_stage_to_stage_in_dependency_order() {
        // a → b(reads a) → out(reads b): three stages, upstream always before downstream.
        let stages = compile_stages(
            "INSERT INTO out \
             WITH a AS (SELECT bidder, price FROM events WHERE type = 'bid'), \
                  b AS (SELECT bidder, price * 0.9 AS net FROM a WHERE price > 100) \
             SELECT * FROM b",
        )
        .unwrap();
        assert_eq!(stages.iter().map(|s| s.output.as_str()).collect::<Vec<_>>(), vec!["a", "b", "out"]);
        assert_eq!(stages[0].inputs, vec!["events".to_string()]);
        assert_eq!(stages[1].inputs, vec!["a".to_string()]);
        assert_eq!(stages[2].inputs, vec!["b".to_string()]);
    }

    #[test]
    fn a_cte_referenced_twice_is_still_one_stage() {
        // both join sides read the same CTE → the CTE stage is emitted once (dedup by name).
        let stages = compile_stages(
            "INSERT INTO out \
             WITH e AS (SELECT bidder, auction, dateTime FROM events WHERE type = 'bid') \
             SELECT l.bidder FROM e AS l JOIN e AS r \
             ON l.auction = r.auction AND l.dateTime BETWEEN r.dateTime - INTERVAL '5' SECOND AND r.dateTime + INTERVAL '5' SECOND",
        )
        .unwrap();
        // one stage for e, one for the self-interval-join — not two copies of e.
        assert_eq!(stages.iter().filter(|s| s.output == "e").count(), 1);
        assert_eq!(stages.len(), 2);
        assert_eq!(stages[1].inputs, vec!["e".to_string(), "e".to_string()]);
    }

    #[test]
    fn a_trailing_interval_on_a_window_is_the_allowed_lateness() {
        // q4/q5 need a large lateness so no out-of-order bid is dropped from a closed window; the
        // extra INTERVAL beyond the base arity lowers to the engine's `allowedLatenessMs`.
        let hop = &compile_stages(
            "INSERT INTO o SELECT k, count(*) AS n FROM b \
             GROUP BY k, HOP(ts, INTERVAL '2' SECOND, INTERVAL '10' SECOND, INTERVAL '5000' SECOND)",
        )
        .unwrap()[0];
        assert_eq!(hop.steps[0]["allowedLatenessMs"], json!(5_000_000));
        assert_eq!(hop.steps[0]["windowMs"], json!(10_000));
        assert_eq!(hop.steps[0]["slideMs"], json!(2_000));
        let tumble = &compile_stages(
            "INSERT INTO o SELECT k, max(v) AS m FROM b GROUP BY k, TUMBLE(ts, INTERVAL '10' SECOND, INTERVAL '30' SECOND)",
        )
        .unwrap()[0];
        assert_eq!(tumble.steps[0]["allowedLatenessMs"], json!(30_000));
        // no trailing interval → no lateness field (the engine default stands).
        let plain = &compile_stages("INSERT INTO o SELECT k, count(*) AS n FROM b GROUP BY k, TUMBLE(ts, INTERVAL '10' SECOND)").unwrap()[0];
        assert_eq!(plain.steps[0].get("allowedLatenessMs"), None);
        // too many intervals is a loud arity error.
        assert!(compile("INSERT INTO o SELECT k, count(*) AS n FROM b GROUP BY k, TUMBLE(ts, INTERVAL '1' SECOND, INTERVAL '2' SECOND, INTERVAL '3' SECOND)").is_err());
    }

    #[test]
    fn recursive_ctes_are_rejected() {
        assert!(compile(
            "INSERT INTO o WITH RECURSIVE r AS (SELECT * FROM b) SELECT * FROM r"
        )
        .unwrap_err()
        .contains("RECURSIVE"));
    }
}