substrait-explain 0.7.0

Explain Substrait plans as human-readable text.
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! Test that we can roundtrip a plan from text to a Substrait plan and back to
//! text. Many features can be tested this way - in general, if it can survive a
//! round-trip, it's probably correct; it could be stored incorrectly and both
//! parser and formatter handle it the same incorrect way, but that is probably
//! rare, and more likely a reflection of the author's misunderstanding of the
//! Substrait plan format.

mod common;

use common::{assert_roundtrip_canonical, roundtrip_plan};
use substrait_explain::{ParseError, Parser};

#[test]
fn test_simple_plan_roundtrip() {
    let plan = r#"=== Plan
Root[c, d]
  Filter[$0 => $0, $1]
    Project[$1, 42]
      Read[my.table => a:i32, b:string?, c:boolean]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_plan_with_extensions_roundtrip() {
    let plan = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
Functions:
  # 10 @  1: add
  # 11 @  1: multiply

=== Plan
Root[result]
  Project[$0, $1, add($0, $1):i32?]
    Read[table1 => col1:i32?, col2:i32?]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_complex_plan_roundtrip() {
    let plan = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
  @  2: https://github.com/substrait-io/substrait/blob/main/extensions/functions_aggregate.yaml
Functions:
  # 10 @  1: add
  # 11 @  2: sum
  # 12 @  2: count

=== Plan
Root[name, parent, sum, count]
  Project[$0, $3, $1, $2]
    Read[schema.table => name:string?, parent:string?, sum:fp64?, count:fp64?]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_plan_with_verbose_and_simple_output() {
    let simple_plan = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
Functions:
  # 10 @  1: coalesce

=== Plan
Root[name, num]
  Project[$1, coalesce($1, $2):fp64?]
    Read[schema.table => name:string?, num:fp64?, other_num:fp64?, id:i64]"#;

    let verbose_plan = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
Functions:
  # 10 @  1: coalesce

=== Plan
Root[name, num]
  Project[$1, coalesce#10($1, $2):fp64?]
    Read[schema.table => name:string?, num:fp64?, other_num:fp64?, id:i64]"#;

    assert_roundtrip_canonical(simple_plan, verbose_plan);
}

#[test]
fn test_multiple_relations_roundtrip() {
    let plan = r#"=== Plan
Root[name, num, id]
  Project[$0, $1, $2]
    Read[t1 => name:string?, num:fp64, id:i64]

Root[name, num, id]
  Filter[$0 => $0, $1, $2]
    Read[schema.table => name:string?, num:fp64?, id:i64]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_plan_with_fetch_and_sort_roundtrip() {
    let plan = r#"=== Plan
Root[name, num, id]
  Project[$0, $1, $2]
    Read[schema.table => name:string?, num:fp64?, id:i64]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_plan_with_extension_leaf_roundtrip() {
    let plan = r#"=== Plan
Root[name, some_value]
  Project[$0, $1]
    Read[schema.table => name:string?, some_value:fp64?]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_aggregate_relation_roundtrip() {
    let plan = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_aggregate.yaml
Functions:
  # 10 @  1: sum
  # 11 @  1: count

=== Plan
Root[category, total, count]
  Aggregate[$0 => sum($1):fp64?, count($1):i64]
    Read[orders => category:string?, amount:fp64?]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_aggregate_multiple_grouping_sets_roundtrip() {
    let plan = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_aggregate.yaml
Functions:
  # 10 @  1: sum
  # 11 @  1: count

=== Plan
Root[sum, category, count]
  Aggregate[($0, $1), ($0), _ => sum($2):fp64?, $0, count($2):i64]
    Read[orders => category:string?, region:string?, amount:fp64?]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_global_aggregate_relation_roundtrip() {
    let plan = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_aggregate.yaml
Functions:
  # 10 @  1: sum
  # 11 @  1: count

=== Plan
Root[sum, count]
  Aggregate[_ => sum($2):fp64?, count($2):i64]
    Read[orders => category:string?, region:string?, amount:fp64?]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_sort_relation_roundtrip() {
    let plan = r#"=== Plan
Root[a, b]
  Sort[($0, &AscNullsFirst), ($1, &DescNullsLast) => $0, $1]
    Read[table => a:i32, b:string]"#;
    roundtrip_plan(plan);
}

#[test]
fn test_fetch_relation_roundtrip() {
    let plan_both = r#"=== Plan
Root[a, b]
  Fetch[limit=10, offset=5 => $0, $1]
    Read[table => a:i32, b:string]"#;

    let plan_offset_first = r#"=== Plan
Root[a, b]
  Fetch[offset=5, limit=10 => $0, $1]
    Read[table => a:i32, b:string]"#;

    assert_roundtrip_canonical(plan_both, plan_offset_first);

    let plan_limit_only = r#"=== Plan
Root[a, b]
  Fetch[limit=10 => $0, $1]
    Read[table => a:i32, b:string]"#;
    roundtrip_plan(plan_limit_only);

    let plan_offset_only = r#"=== Plan
Root[a, b]
  Fetch[offset=5 => $0, $1]
    Read[table => a:i32, b:string]"#;
    roundtrip_plan(plan_offset_only);

    let plan_empty = r#"=== Plan
Root[a, b]
  Fetch[_ => $0, $1]
    Read[table => a:i32, b:string]"#;
    roundtrip_plan(plan_empty);
}

#[test]
fn test_full_name_zero_arg_type_signature_roundtrip() {
    let plan = r#"=== Extensions
URNs:
  @  1: extension:io.substrait:functions_aggregate_generic
Functions:
  #  1 @  1: count:

=== Plan
Root[n]
  Project[count():i64]
    Read[events => n:i64]"#;
    roundtrip_plan(plan);
}

/// One no-signature `add` registration — base name is unique so the function
/// is written without an anchor or type signature in compact mode.
#[test]
fn test_no_sig_function_unique_no_anchor() {
    let plan = r#"=== Extensions
URNs:
  @  1: urn:substrait:vendor_a
Functions:
  #  1 @  1: add

=== Plan
Root[result]
  Project[$0, $1, add($0, $1):i64]
    Read[t => a:i64, b:i64]"#;
    roundtrip_plan(plan);
}

/// `add` and `add:` share the base name, so `add(…)` (no colon, no anchor)
/// is ambiguous and must be rejected.
#[test]
fn test_ambiguous_base_name_fails() {
    let plan = r#"=== Extensions
URNs:
  @  1: urn:substrait:vendor_a
Functions:
  #  1 @  1: add
  #  2 @  1: add:

=== Plan
Root[result]
  Project[add($0, $1)]
    Read[t => a:i64, b:i64]"#;

    assert!(Parser::parse(plan).is_err());
}

/// `add` (simple) and `add:` (full, zero-argument type signature) registered under the same
/// URN. `add:` is unambiguous so it needs no anchor; `add` requires an anchor
/// because the base name is shared.
#[test]
fn test_no_sig_and_zero_arg_disambiguate_without_anchor() {
    let plan = r#"=== Extensions
URNs:
  @  1: urn:substrait:vendor_a
Functions:
  #  1 @  1: add
  #  2 @  1: add:

=== Plan
Root[result]
  Project[$0, $1, add#1($0, $1):i64, add:($0, $1):i64]
    Read[t => a:i64, b:i64]"#;
    roundtrip_plan(plan);
}

/// `add` (simple) from one URN and `add:` (full, zero-argument type signature) from two different URNs.
/// The compound name `add:` is no longer unique, so all three functions require
/// an anchor in the plan text.
#[test]
fn test_three_add_variants_all_require_anchors() {
    let plan = r#"=== Extensions
URNs:
  @  1: urn:substrait:vendor_a
  @  2: urn:substrait:vendor_b
Functions:
  #  1 @  1: add
  #  2 @  1: add:
  #  3 @  2: add:

=== Plan
Root[result]
  Project[$0, $1, add#1($0, $1):i64, add:#2($0, $1):i64, add:#3($0, $1):i64]
    Read[t => a:i64, b:i64]"#;
    roundtrip_plan(plan);
}

#[test]
fn test_u_prefix_type_in_schema_roundtrip() {
    // Types are declared without u! in the Extensions section. The u! prefix is
    // accepted but ignored in plan references (both "doc:json" and "doc:u!json" resolve
    // to the same type), and output is always the bare name.
    let canonical = r#"=== Extensions
URNs:
  @  1: https://example.com/types
Types:
  #  5 @  1: json

=== Plan
Root[result]
  Project[$0]
    Read[data => doc:json]"#;

    // Plan authored with u! prefix on the type reference round-trips to the canonical form.
    let with_prefix = r#"=== Extensions
URNs:
  @  1: https://example.com/types
Types:
  #  5 @  1: json

=== Plan
Root[result]
  Project[$0]
    Read[data => doc:u!json]"#;

    assert_roundtrip_canonical(canonical, with_prefix);
}

#[test]
fn test_u_prefix_type_in_function_declaration_roundtrip() {
    // The declaration preserves the full compound name including the u!-prefixed signature.
    // The call site uses the compact base name since the function is unique.
    let canonical = r#"=== Extensions
URNs:
  @  1: https://example.com/funcs
Functions:
  #  5 @  1: json_extract_path:u!json_str

=== Plan
Root[result]
  Project[json_extract_path($0, $1):string]
    Read[data => doc:string, path:string]"#;

    // Explicit compound name in the call site resolves to the same canonical output.
    let with_signature = r#"=== Extensions
URNs:
  @  1: https://example.com/funcs
Functions:
  #  5 @  1: json_extract_path:u!json_str

=== Plan
Root[result]
  Project[json_extract_path:u!json_str($0, $1):string]
    Read[data => doc:string, path:string]"#;

    roundtrip_plan(canonical);
    assert_roundtrip_canonical(canonical, with_signature);
}

#[test]
fn test_u_prefix_type_in_cast_roundtrip() {
    // A cast to a u!-prefixed UDT: both "::u!json" and "::json" in the plan resolve to
    // the same type. Canonical output always uses the bare name.
    let canonical = r#"=== Extensions
URNs:
  @  1: https://example.com/types
Types:
  #  5 @  1: json

=== Plan
Root[result]
  Project[($0)::json]
    Read[data => doc:string]"#;

    let with_prefix = r#"=== Extensions
URNs:
  @  1: https://example.com/types
Types:
  #  5 @  1: json

=== Plan
Root[result]
  Project[($0)::u!json]
    Read[data => doc:string]"#;

    roundtrip_plan(canonical);
    assert_roundtrip_canonical(canonical, with_prefix);
}

#[test]
fn test_join_relation_roundtrip() {
    let plan = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_comparison.yaml
Functions:
  # 10 @  1: eq

=== Plan
Root[id, name, amount]
  Join[&Inner, eq($0, $2):boolean => $0, $1, $3]
    Read[users => id:i64, name:string]
    Read[orders => user_id:i64, amount:i32]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_join_relation_semi_types_roundtrip() {
    // Test LeftSemi join - should output only left columns
    let plan_semi = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_comparison.yaml
Functions:
  # 10 @  1: eq

=== Plan
Root[a, b]
  Join[&LeftSemi, eq($0, $2):boolean => $0, $1]
    Read[left_table => a:i32, b:string]
    Read[right_table => c:i32, d:string]"#;
    roundtrip_plan(plan_semi);
}

#[test]
fn test_join_relation_right_mark_roundtrip() {
    // Test RightMark join - should output right columns plus mark column
    // Left: 2 columns, Right: 3 columns, RightMark outputs 4 total: $0, $1, $2, $3
    // We output just the last right column ($2) and the mark ($3)
    let plan_right_mark = r#"=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_comparison.yaml
Functions:
  # 10 @  1: eq

=== Plan
Root[d, mark]
  Join[&RightMark, eq($0, $2):boolean => $2, $3]
    Read[left_table => a:i32, b:string]
    Read[right_table => c:i32, d:string, e:boolean]"#;
    roundtrip_plan(plan_right_mark);
}

#[test]
fn test_unregistered_extension_error() {
    let plan_text = r#"=== Plan
Root[result]
  ExtensionLeaf:UnknownExtension[path='test.parquet' => col1:i32]"#;

    let err = Parser::parse(plan_text).expect_err("parse should fail for unknown extension");
    match err {
        ParseError::UnregisteredExtension { name, context } => {
            assert_eq!(name, "UnknownExtension");
            assert_eq!(context.line_no, 3);
            assert!(
                context.line.contains("ExtensionLeaf:UnknownExtension"),
                "context should include the extension line"
            );
        }
        other => panic!("expected unregistered extension error, got {other:?}"),
    }
}

#[test]
fn test_malformed_input_error_handling() {
    use substrait_explain::Parser;

    // Test malformed input: unclosed bracket in extension relation
    let malformed_plan = r#"=== Plan
Root[result]
  ExtensionLeaf:TestExtension[path='test.parquet', missing_close => col1:i32"#;

    let result = Parser::parse(malformed_plan);

    // Should fail with a clear error
    assert!(
        result.is_err(),
        "Malformed input should result in parse error"
    );

    let error = result.unwrap_err();
    let error_msg = format!("{error}");

    // Verify error contains useful information
    assert!(error_msg.len() > 10, "Error message should be descriptive");

    // Error should reference the problematic line (line 3 where the unclosed bracket is)
    assert!(
        error_msg.contains("3") || error_msg.contains("line"),
        "Error should reference line information: {error_msg}"
    );

    // Malformed input error test passed
}

#[test]
fn test_overloaded_functions_verbose_shows_signature_and_anchor() {
    // A plan where a function has an overloaded compound name. The compact output
    // must include the signature because the base name is not unique, but must
    // omit the anchor because the compound name is unique.
    let simple = r#"=== Extensions
URNs:
  @  1: extension:io.substrait:functions_comparison
Functions:
  #  1 @  1: equal:any_any
  #  2 @  1: equal:str_str

=== Plan
Root[result]
  Project[$0, equal:any_any($0, $1):boolean, equal:str_str($0, $1):boolean]
    Read[t => a:i64, b:i64, c:string]"#;

    // Verbose output always shows signatures and anchors for all functions,
    // including those with unique base names.
    let verbose = r#"=== Extensions
URNs:
  @  1: extension:io.substrait:functions_comparison
Functions:
  #  1 @  1: equal:any_any
  #  2 @  1: equal:str_str

=== Plan
Root[result]
  Project[$0, equal:any_any#1($0, $1):boolean, equal:str_str#2($0, $1):boolean]
    Read[t => a:i64, b:i64, c:string]"#;

    roundtrip_plan(simple);
    assert_roundtrip_canonical(simple, verbose);
}

/// A unique function (only one overload registered) uses the base name in
/// compact mode and the compound name with anchor in verbose mode.
/// Writing the compound name explicitly in input is equivalent to writing
/// just the base name — both produce the same canonical output.
#[test]
fn test_unique_function_compact_omits_signature() {
    // Canonical: base name only, because add:i64_i64 is the only "add"
    let compact = r#"=== Extensions
URNs:
  @  1: extension:io.substrait:functions_arithmetic
Functions:
  #  1 @  1: add:i64_i64

=== Plan
Root[result]
  Project[$0, add($0, $1):i64]
    Read[t => a:i64, b:i64]"#;

    // Explicit compound name in input resolves to the same canonical output
    let compound = r#"=== Extensions
URNs:
  @  1: extension:io.substrait:functions_arithmetic
Functions:
  #  1 @  1: add:i64_i64

=== Plan
Root[result]
  Project[$0, add:i64_i64($0, $1):i64]
    Read[t => a:i64, b:i64]"#;

    // Verbose output always shows the full compound name and anchor
    let verbose = r#"=== Extensions
URNs:
  @  1: extension:io.substrait:functions_arithmetic
Functions:
  #  1 @  1: add:i64_i64

=== Plan
Root[result]
  Project[$0, add:i64_i64#1($0, $1):i64]
    Read[t => a:i64, b:i64]"#;

    assert_roundtrip_canonical(compact, compound);
    assert_roundtrip_canonical(compact, verbose);
}

/// A plan that mixes unique and overloaded functions.  Compact mode shows
/// signatures only where needed.
#[test]
fn test_mixed_unique_and_overloaded_functions() {
    let simple = r#"=== Extensions
URNs:
  @  1: extension:io.substrait:functions_comparison
  @  2: extension:io.substrait:functions_string
Functions:
  #  1 @  1: equal:any_any
  #  2 @  1: equal:str_str
  #  3 @  2: like:str_str

=== Plan
Root[result]
  Project[$0, equal:any_any($0, $1):boolean, equal:str_str($0, $2):boolean, like($0, $2):boolean]
    Read[t => id:i64, score:i64, name:string]"#;

    roundtrip_plan(simple);
}

/// Same compound name registered in two different URNs — the anchor is
/// required to disambiguate in all modes.
#[test]
fn test_same_compound_name_two_urns_requires_anchor() {
    let plan = r#"=== Extensions
URNs:
  @  1: urn:substrait:vendor_a
  @  2: urn:substrait:vendor_b
Functions:
  #  1 @  1: equal:any_any
  #  2 @  2: equal:any_any

=== Plan
Root[result]
  Project[$0, equal:any_any#1($0, $1):boolean, equal:any_any#2($0, $1):boolean]
    Read[t => a:i64, b:i64]"#;

    roundtrip_plan(plan);
}

// === VirtualTable Read tests ===

#[test]
fn test_virtual_read_inline_single_row() {
    let plan = r#"
=== Plan
Root[id, name]
  Read:Virtual[(1, 'alice') => id:i64, name:string]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_virtual_read_inline_multi_row() {
    let plan = r#"
=== Plan
Root[id, name]
  Read:Virtual[(1, 'alice'), (2, 'bob') => id:i64, name:string]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_virtual_read_typed_null_roundtrip() {
    let plan = r#"
=== Plan
Root[id, name]
  Read:Virtual[(1, null:string?), (2, 'bob') => id:i64, name:string?]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_virtual_read_empty() {
    let plan = r#"
=== Plan
Root[id, name]
  Read:Virtual[_ => id:i64, name:string]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_virtual_read_single_column() {
    // Three rows reaches the multi-line threshold, so the canonical output
    // spreads the rows across lines.
    let plan = r#"
=== Plan
Root[id]
  Read:Virtual[
    - (1),
    - (2),
    - (3)
    - => id:i64]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_virtual_read_in_plan_context() {
    // VirtualTable as input to Filter and Project
    let plan = r#"
=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_comparison.yaml
Functions:
  # 10 @  1: gt

=== Plan
Root[name]
  Filter[gt($0, 1):boolean => $0, $1]
    Read:Virtual[
      - (1, 'alice'),
      - (2, 'bob'),
      - (3, 'carol')
      - => id:i64, name:string]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_virtual_read_no_columns() {
    // Degenerate table with zero columns and empty rows.
    let plan = r#"
=== Plan
Root[]
  Read:Virtual[(), () => ]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_virtual_read_invalid_expression_returns_error() {
    // A function call referencing an undeclared extension should produce
    // a parse error, not a panic.
    let plan = r#"
=== Plan
Root[result]
  Read:Virtual[(unknown_func(1)) => result:i64]"#;

    let result = Parser::parse(plan);
    assert!(
        result.is_err(),
        "undeclared function in VirtualTable row should fail"
    );
}

// === Emit / output-field-count propagation tests ===
//
// These exercise the pipeline: child's output_field_count → parent's
// input_field_count → correct emit indices for expressions in Project.
// If any relation type returns the wrong output count, the Project's emit
// mapping will be offset incorrectly and the roundtrip will fail.

#[test]
fn test_emit_read_to_project_with_expression() {
    // Read outputs 2 columns. Project has expression add($0,$1) → emit index should be 2.
    let plan = r#"
=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
Functions:
  # 10 @  1: add

=== Plan
Root[sum]
  Project[add($0, $1):i64]
    Read[t => a:i64, b:i64]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_emit_filter_to_project_with_expression() {
    // Read outputs 3, Filter emits 2 ($0, $1). Project sees 2 inputs.
    let plan = r#"
=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
  @  2: https://github.com/substrait-io/substrait/blob/main/extensions/functions_comparison.yaml
Functions:
  # 10 @  1: add
  # 11 @  2: gt

=== Plan
Root[sum]
  Project[add($0, $1):i64]
    Filter[gt($2, 0):boolean => $0, $1]
      Read[t => a:i64, b:i64, c:i64]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_emit_sort_to_project_with_expression() {
    // Sort is passthrough — its output count should equal its input's.
    let plan = r#"
=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
Functions:
  # 10 @  1: add

=== Plan
Root[sum]
  Project[add($0, $1):i64]
    Sort[($0, &AscNullsFirst) => $0, $1]
      Read[t => a:i64, b:i64]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_emit_fetch_to_project_with_expression() {
    // Fetch is passthrough — its output count should equal its input's.
    let plan = r#"
=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
Functions:
  # 10 @  1: add

=== Plan
Root[sum]
  Project[add($0, $1):i64]
    Fetch[limit=10, offset=0 => $0, $1]
      Read[t => a:i64, b:i64]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_emit_join_to_project_with_expression() {
    // Join: left has 2 cols, right has 2 cols → 4 total. Project sees 4.
    let plan = r#"
=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
  @  2: https://github.com/substrait-io/substrait/blob/main/extensions/functions_comparison.yaml
Functions:
  # 10 @  1: add
  # 11 @  2: eq

=== Plan
Root[sum]
  Project[add($1, $3):i64]
    Join[&Inner, eq($0, $2):boolean => $0, $1, $2, $3]
      Read[users => id:i64, age:i64]
      Read[orders => user_id:i64, amount:i64]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_emit_aggregate_to_project_with_expression() {
    // Aggregate: 1 grouping field + 1 measure = 2 output columns.
    let plan = r#"
=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
  @  2: https://github.com/substrait-io/substrait/blob/main/extensions/functions_aggregate.yaml
Functions:
  # 10 @  1: add
  # 11 @  2: sum

=== Plan
Root[total]
  Project[add($0, $1):i64]
    Aggregate[$0 => $0, sum($1):i64]
      Read[t => category:i64, amount:i64]"#;

    roundtrip_plan(plan);
}

#[test]
fn test_emit_virtual_read_to_project_with_expression() {
    let plan = r#"
=== Extensions
URNs:
  @  1: https://github.com/substrait-io/substrait/blob/main/extensions/functions_arithmetic.yaml
Functions:
  # 10 @  1: add

=== Plan
Root[sum]
  Project[add($0, $1):i64]
    Read:Virtual[(1, 2), (3, 4) => a:i64, b:i64]"#;

    roundtrip_plan(plan);
}