substrait-explain 0.9.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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
//! Text-format data structures used by registered advanced extension handlers.
//!
//! These types describe the arguments accepted by custom relation types,
//! enhancements, and optimization hints. Relation extensions can additionally
//! describe output columns.
//!
//! The interface presented to extension handlers is structured rather than
//! textual: handlers read and write values such as [`ExtensionArgs`], [`Expr`],
//! and [`proto::Type`]. `substrait-explain` handles the surrounding
//! parsing/textification. Some values need plan context before they reach a
//! handler; for example, an expression argument like `add($0, $1)` is parsed
//! using [`SimpleExtensions`](crate::extensions::SimpleExtensions) to resolve
//! the text function name to the protobuf function anchor, and formatted by
//! resolving that anchor back to a text name.
//!
//! The extension-facing interface for Substrait objects (e.g. [`proto::Type`])
//! should map directly to Substrait protobuf concepts. Sometimes that means
//! storing the protobuf type directly, as named output columns do with
//! [`proto::Type`]; sometimes it means using a small wrapper, as
//! expression-compatible arguments do with [`Expr`] around
//! [`proto::Expression`].
//!
//! Untyped scalar literals (e.g. `2`, `2.435`, `'string'`) are kept as
//! extension scalar values so text rendering can preserve scalar syntax even in
//! verbose output, while handlers that accept expressions can still widen them
//! into default Substrait literal expressions.

use std::collections::HashSet;
use std::fmt;
use std::slice::Iter as SliceIter;
use std::vec::IntoIter as VecIntoIter;

use indexmap::IndexMap;
use substrait::proto;
use substrait::proto::expression::field_reference::ReferenceType;
use substrait::proto::expression::literal::LiteralType;
use substrait::proto::expression::{RexType, reference_segment};

use super::{Explainable, ExtensionError};
use crate::textify::expressions::Reference;

/// Kind of relation addendum in the text format.
///
/// Addenda are `+`-prefixed lines attached to relations. They are syntax-level
/// constructs, distinct from [`crate::extensions::registry::ExtensionType`],
/// which describes registry namespaces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AddendumKind {
    Enhancement,
    Optimization,
    ExtensionTable,
}

impl AddendumKind {
    pub(crate) fn prefix(self) -> &'static str {
        match self {
            AddendumKind::Enhancement => "Enh",
            AddendumKind::Optimization => "Opt",
            AddendumKind::ExtensionTable => "Ext",
        }
    }
}

/// A Substrait expression carried as an extension argument or output column.
///
/// Boxed because `proto::Expression` is large (multiple `Vec` fields in
/// variants like `ScalarFunction`).
#[derive(Debug, Clone)]
pub struct Expr(Box<proto::Expression>);

impl Expr {
    /// Create a direct field-reference expression (`$N`).
    pub fn field(index: i32) -> Self {
        Reference(index).into()
    }

    /// Borrow the underlying Substrait expression protobuf.
    pub fn as_proto(&self) -> &proto::Expression {
        self.0.as_ref()
    }

    /// Clone the underlying Substrait expression protobuf.
    pub fn to_proto(&self) -> proto::Expression {
        self.as_proto().clone()
    }

    /// If this expression is a direct field reference (`$N`), return it.
    pub fn as_direct_reference(&self) -> Option<i32> {
        let Some(RexType::Selection(field_ref)) = self.as_proto().rex_type.as_ref() else {
            return None;
        };
        let Some(ReferenceType::DirectReference(segment)) = field_ref.reference_type.as_ref()
        else {
            return None;
        };
        let Some(reference_segment::ReferenceType::StructField(field)) =
            segment.reference_type.as_ref()
        else {
            return None;
        };
        if field.child.is_some() {
            return None;
        }
        Some(field.field)
    }
}

impl From<proto::Expression> for Expr {
    fn from(expr: proto::Expression) -> Self {
        Expr(Box::new(expr))
    }
}

impl From<proto::expression::Literal> for Expr {
    fn from(literal: proto::expression::Literal) -> Self {
        proto::Expression {
            rex_type: Some(RexType::Literal(literal)),
        }
        .into()
    }
}

impl From<Reference> for Expr {
    fn from(reference: Reference) -> Self {
        proto::Expression::from(reference).into()
    }
}

impl From<Expr> for proto::Expression {
    fn from(expr: Expr) -> Self {
        *expr.0
    }
}

impl From<i64> for Expr {
    fn from(value: i64) -> Self {
        proto::expression::Literal {
            literal_type: Some(LiteralType::I64(value)),
            nullable: false,
            type_variation_reference: 0,
        }
        .into()
    }
}

impl From<f64> for Expr {
    fn from(value: f64) -> Self {
        proto::expression::Literal {
            literal_type: Some(LiteralType::Fp64(value)),
            nullable: false,
            type_variation_reference: 0,
        }
        .into()
    }
}

impl From<bool> for Expr {
    fn from(value: bool) -> Self {
        proto::expression::Literal {
            literal_type: Some(LiteralType::Boolean(value)),
            nullable: false,
            type_variation_reference: 0,
        }
        .into()
    }
}

impl From<String> for Expr {
    fn from(value: String) -> Self {
        proto::expression::Literal {
            literal_type: Some(LiteralType::String(value)),
            nullable: false,
            type_variation_reference: 0,
        }
        .into()
    }
}

impl From<&str> for Expr {
    fn from(value: &str) -> Self {
        value.to_string().into()
    }
}

/// Represents extension arguments plus optional output columns.
///
/// Named arguments are stored in an [`IndexMap`] whose iteration order
/// determines display order. Extension [`super::Explainable::to_args()`]
/// implementations should insert named arguments in the order they should
/// appear in the text format.
#[derive(Debug, Clone, Default)]
pub struct ExtensionArgs {
    /// Positional arguments.
    pub positional: Vec<ExtensionValue>,
    /// Named arguments, displayed in the order they were inserted
    pub named: IndexMap<String, ExtensionValue>,
    /// Output columns for custom relation types.
    pub output_columns: Vec<ExtensionColumn>,
}

/// [`ArgsAccess`] provides a view of the arguments in the text form of an
/// extension relation or advanced extension.
///
/// Positional arguments are available via [`Self::positional`], named arguments
/// via [`Self::get_named`] or [`Self::expect_named`] which can do type
/// conversion as well, and output columns via [`Self::output_columns`].
///
/// [`ArgsAccess`] tracks which arguments are accessed; when
/// [`Explainable::from_args`] returns, any unaccessed arguments will be raised
/// as [`ExtensionError::InvalidArgument`] errors.
pub struct ArgsAccess<'a> {
    args: &'a ExtensionArgs,
    handled: HashSet<&'a str>,
    positional_handled: bool,
}

impl<'a> ArgsAccess<'a> {
    pub(crate) fn new(args: &'a ExtensionArgs) -> Self {
        Self {
            args,
            handled: HashSet::new(),
            positional_handled: false,
        }
    }

    /// Returns the positional arguments in source order and marks them as handled.
    pub fn positional(&mut self) -> &'a [ExtensionValue] {
        self.positional_handled = true;
        &self.args.positional
    }

    /// Returns the output columns for a custom relation.
    ///
    /// Output columns are not included in the unhandled-argument check.
    pub fn output_columns(&self) -> &'a [ExtensionColumn] {
        &self.args.output_columns
    }

    /// Returns a named argument without converting it, or `None` if it is absent.
    ///
    /// A present argument is marked as handled.
    pub fn get_named_arg(&mut self, name: &str) -> Option<&'a ExtensionValue> {
        match self.args.named.get_key_value(name) {
            Some((k, value)) => {
                self.handled.insert(k);
                Some(value)
            }
            None => None,
        }
    }

    /// Returns a named argument converted to `T`, or `None` if it is absent.
    ///
    /// A present argument is marked as handled.
    pub fn get_named<T>(&mut self, name: &str) -> Result<Option<T>, ExtensionError>
    where
        T: TryFrom<&'a ExtensionValue>,
        T::Error: Into<ExtensionError>,
    {
        self.get_named_arg(name)
            .map(|value| {
                T::try_from(value).map_err(|error| ExtensionError::NamedArgumentConversion {
                    name: name.to_string(),
                    source: Box::new(error.into()),
                })
            })
            .transpose()
    }

    /// Fetch the named argument `name`, with an expected type of
    /// [`TupleValue`], and convert each element to type `T`.
    ///
    /// Returns `Ok(None)` if the argument is absent. Returns an error if the
    /// argument is not a tuple, or if any element of the tuple fails
    /// conversion.
    pub fn get_named_tuple<T>(&mut self, name: &str) -> Result<Option<Vec<T>>, ExtensionError>
    where
        T: TryFrom<&'a ExtensionValue>,
        T::Error: Into<ExtensionError>,
    {
        self.get_named_arg(name)
            .map(|value| {
                let tuple = <&TupleValue>::try_from(value)?;
                tuple
                    .into_iter()
                    .map(|element| T::try_from(element).map_err(Into::into))
                    .collect::<Result<Vec<_>, ExtensionError>>()
            })
            .transpose()
            .map_err(|source| ExtensionError::NamedArgumentConversion {
                name: name.to_string(),
                source: Box::new(source),
            })
    }

    /// Returns a required named argument converted to `T`.
    ///
    /// A present argument is marked as handled.
    pub fn expect_named<T>(&mut self, name: &str) -> Result<T, ExtensionError>
    where
        T: TryFrom<&'a ExtensionValue>,
        T::Error: Into<ExtensionError>,
    {
        self.get_named(name)?
            .ok_or_else(|| ExtensionError::MissingArgument {
                name: name.to_string(),
            })
    }

    /// Rejects arguments that the decoder did not handle.
    pub(crate) fn finish(self) -> Result<(), ExtensionError> {
        if !self.positional_handled && !self.args.positional.is_empty() {
            return Err(ExtensionError::InvalidArgument(format!(
                "Unhandled positional arguments: {}",
                self.args.positional.len()
            )));
        }

        let mut unhandled_args = Vec::new();
        for name in self.args.named.keys() {
            if !self.handled.contains(name.as_str()) {
                unhandled_args.push(name.as_str());
            }
        }

        if unhandled_args.is_empty() {
            Ok(())
        } else {
            // Sort for stable error messages.
            unhandled_args.sort();
            Err(ExtensionError::InvalidArgument(format!(
                "Unknown named arguments: {}",
                unhandled_args.join(", ")
            )))
        }
    }
}

/// A tuple-valued extension argument.
///
/// Tuple values preserve positional order and can be iterated by value or by
/// reference.
#[derive(Debug, Clone)]
pub struct TupleValue(Vec<ExtensionValue>);

impl TupleValue {
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn iter(&self) -> SliceIter<'_, ExtensionValue> {
        self.0.iter()
    }
}

impl<'a> IntoIterator for &'a TupleValue {
    type Item = &'a ExtensionValue;
    type IntoIter = SliceIter<'a, ExtensionValue>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl IntoIterator for TupleValue {
    type Item = ExtensionValue;
    type IntoIter = VecIntoIter<ExtensionValue>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl FromIterator<ExtensionValue> for TupleValue {
    fn from_iter<I: IntoIterator<Item = ExtensionValue>>(iter: I) -> Self {
        TupleValue(iter.into_iter().collect())
    }
}

impl From<Vec<ExtensionValue>> for TupleValue {
    fn from(items: Vec<ExtensionValue>) -> Self {
        TupleValue(items)
    }
}

/// Represents a value in extension arguments.
///
/// These values are the structured form of text-format extension arguments,
/// fully resolved - i.e. any additional context (such as function anchors etc)
/// are part of this struct itself.
#[derive(Debug, Clone)]
pub enum ExtensionValue {
    /// Untyped literals. These are not input or output with types (e.g. `2`,
    /// not `2:i64`), and suitable for protobuf extension fields that are not
    /// substrait types.
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    /// An untyped null literal.
    Null,
    /// A conversion or formatting error preserved for best-effort textification.
    Error(ExtensionError),

    /// Substrait expression value, including typed literals and field references.
    ///
    /// Use `TryFrom<&ExtensionValue> for Expr` when a handler accepts either an
    /// expression or a scalar value widened into an expression.
    Expr(Expr),
    /// Enum value (e.g. &CORE, &Inner) — the string holds the identifier
    /// without the `&` prefix
    Enum(String),
    /// Tuple of values, e.g. (&HASH, &RANGE) or (42, 'hello')
    Tuple(TupleValue),
    // TODO: Consider adding support for types as arguments. May need dedicated
    // syntax (`:typename`, perhaps?), as type names may not be distinguishable
    // from identifiers
}

/// The variant kind of an [`ExtensionValue`], used in diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExtensionValueKind {
    String,
    Integer,
    Float,
    Boolean,
    Null,
    Error,
    Reference,
    Enum,
    Tuple,
    Expression,
}

impl fmt::Display for ExtensionValueKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ExtensionValueKind::String => write!(f, "string"),
            ExtensionValueKind::Integer => write!(f, "integer"),
            ExtensionValueKind::Float => write!(f, "float"),
            ExtensionValueKind::Boolean => write!(f, "boolean"),
            ExtensionValueKind::Null => write!(f, "null"),
            ExtensionValueKind::Error => write!(f, "error"),
            ExtensionValueKind::Reference => write!(f, "reference"),
            ExtensionValueKind::Enum => write!(f, "enum"),
            ExtensionValueKind::Tuple => write!(f, "tuple"),
            ExtensionValueKind::Expression => write!(f, "expression"),
        }
    }
}

impl ExtensionValue {
    /// Return the variant kind of this value for structured diagnostics.
    pub fn kind(&self) -> ExtensionValueKind {
        match self {
            ExtensionValue::String(_) => ExtensionValueKind::String,
            ExtensionValue::Integer(_) => ExtensionValueKind::Integer,
            ExtensionValue::Float(_) => ExtensionValueKind::Float,
            ExtensionValue::Boolean(_) => ExtensionValueKind::Boolean,
            ExtensionValue::Null => ExtensionValueKind::Null,
            ExtensionValue::Error(_) => ExtensionValueKind::Error,
            ExtensionValue::Expr(_) => ExtensionValueKind::Expression,
            ExtensionValue::Enum(_) => ExtensionValueKind::Enum,
            ExtensionValue::Tuple(_) => ExtensionValueKind::Tuple,
        }
    }
}

impl From<ExtensionError> for ExtensionValue {
    fn from(error: ExtensionError) -> Self {
        ExtensionValue::Error(error)
    }
}

impl From<Expr> for ExtensionValue {
    fn from(expr: Expr) -> Self {
        ExtensionValue::Expr(expr)
    }
}

impl From<proto::Expression> for ExtensionValue {
    fn from(expr: proto::Expression) -> Self {
        Expr::from(expr).into()
    }
}

impl From<proto::expression::Literal> for ExtensionValue {
    fn from(literal: proto::expression::Literal) -> Self {
        Expr::from(literal).into()
    }
}

impl From<Reference> for ExtensionValue {
    fn from(reference: Reference) -> Self {
        Expr::from(reference).into()
    }
}

impl From<i64> for ExtensionValue {
    fn from(value: i64) -> Self {
        ExtensionValue::Integer(value)
    }
}

impl From<f64> for ExtensionValue {
    fn from(value: f64) -> Self {
        ExtensionValue::Float(value)
    }
}

impl From<bool> for ExtensionValue {
    fn from(value: bool) -> Self {
        ExtensionValue::Boolean(value)
    }
}

impl From<String> for ExtensionValue {
    fn from(value: String) -> Self {
        ExtensionValue::String(value)
    }
}

impl From<&str> for ExtensionValue {
    fn from(value: &str) -> Self {
        ExtensionValue::String(value.to_string())
    }
}

impl<T> From<Vec<T>> for ExtensionValue
where
    T: Into<ExtensionValue>,
{
    fn from(values: Vec<T>) -> Self {
        ExtensionValue::Tuple(values.into_iter().map(Into::into).collect())
    }
}

impl ExtensionError {
    fn invalid_type(expected: ExtensionValueKind, actual: &ExtensionValue) -> Self {
        match actual {
            ExtensionValue::Error(source) => Self::ArgumentConversion {
                expected,
                source: Box::new(source.clone()),
            },
            _ => Self::InvalidArgumentType {
                expected,
                actual: actual.kind(),
            },
        }
    }
}

impl<'a> TryFrom<&'a ExtensionValue> for &'a str {
    type Error = ExtensionError;

    fn try_from(value: &'a ExtensionValue) -> Result<&'a str, Self::Error> {
        match value {
            ExtensionValue::String(s) => Ok(s),
            v => Err(ExtensionError::invalid_type(ExtensionValueKind::String, v)),
        }
    }
}

impl TryFrom<&ExtensionValue> for String {
    type Error = ExtensionError;

    fn try_from(value: &ExtensionValue) -> Result<String, Self::Error> {
        <&str>::try_from(value).map(ToOwned::to_owned)
    }
}

impl TryFrom<ExtensionValue> for String {
    type Error = ExtensionError;

    fn try_from(value: ExtensionValue) -> Result<String, Self::Error> {
        String::try_from(&value)
    }
}

/// Helper for extracting the identifier from an [`ExtensionValue::Enum`].
pub struct EnumValue(pub String);

impl<'a> TryFrom<&'a ExtensionValue> for EnumValue {
    type Error = ExtensionError;

    fn try_from(value: &'a ExtensionValue) -> Result<EnumValue, Self::Error> {
        match value {
            ExtensionValue::Enum(s) => Ok(EnumValue(s.clone())),
            v => Err(ExtensionError::invalid_type(ExtensionValueKind::Enum, v)),
        }
    }
}

impl<'a> TryFrom<&'a ExtensionValue> for &'a TupleValue {
    type Error = ExtensionError;

    fn try_from(value: &'a ExtensionValue) -> Result<&'a TupleValue, Self::Error> {
        match value {
            ExtensionValue::Tuple(tv) => Ok(tv),
            v => Err(ExtensionError::invalid_type(ExtensionValueKind::Tuple, v)),
        }
    }
}

impl TryFrom<&ExtensionValue> for i64 {
    type Error = ExtensionError;

    fn try_from(value: &ExtensionValue) -> Result<i64, Self::Error> {
        match value {
            ExtensionValue::Integer(i) => Ok(*i),
            v => Err(ExtensionError::invalid_type(ExtensionValueKind::Integer, v)),
        }
    }
}

impl TryFrom<&ExtensionValue> for f64 {
    type Error = ExtensionError;

    fn try_from(value: &ExtensionValue) -> Result<f64, Self::Error> {
        match value {
            ExtensionValue::Float(f) => Ok(*f),
            v => Err(ExtensionError::invalid_type(ExtensionValueKind::Float, v)),
        }
    }
}

impl TryFrom<&ExtensionValue> for bool {
    type Error = ExtensionError;

    fn try_from(value: &ExtensionValue) -> Result<bool, Self::Error> {
        match value {
            ExtensionValue::Boolean(b) => Ok(*b),
            v => Err(ExtensionError::invalid_type(ExtensionValueKind::Boolean, v)),
        }
    }
}

impl TryFrom<&ExtensionValue> for Reference {
    type Error = ExtensionError;

    fn try_from(value: &ExtensionValue) -> Result<Reference, Self::Error> {
        match value {
            ExtensionValue::Expr(expr) => expr
                .as_direct_reference()
                .map(Reference)
                .ok_or_else(|| ExtensionError::invalid_type(ExtensionValueKind::Reference, value)),
            v => Err(ExtensionError::invalid_type(
                ExtensionValueKind::Reference,
                v,
            )),
        }
    }
}

impl TryFrom<&ExtensionValue> for Expr {
    type Error = ExtensionError;

    fn try_from(value: &ExtensionValue) -> Result<Expr, Self::Error> {
        match value {
            ExtensionValue::Expr(e) => Ok(e.clone()),
            // Untyped extension scalars are intentionally expression-compatible:
            // `arg=2` carries no syntax that distinguishes "configuration
            // integer" from "i64 literal expression". Scalar-specific
            // extraction (`i64`, `&str`, `bool`, etc.) still requires the scalar
            // variants, while expression extraction widens them to default
            // non-nullable Substrait literal expressions.
            ExtensionValue::Integer(i) => Ok(Expr::from(*i)),
            ExtensionValue::Float(f) => Ok(Expr::from(*f)),
            ExtensionValue::String(s) => Ok(Expr::from(s.as_str())),
            ExtensionValue::Boolean(b) => Ok(Expr::from(*b)),
            v => Err(ExtensionError::invalid_type(
                ExtensionValueKind::Expression,
                v,
            )),
        }
    }
}

/// Represents an output column specification.
///
/// These values mirror the text-format output column forms. Named columns keep
/// the parsed Substrait type protobuf so handlers can convert directly to
/// relation schemas.
#[derive(Debug, Clone)]
pub enum ExtensionColumn {
    /// Named column with a parsed Substrait type (e.g. `name:i64?`).
    Named {
        /// Column name as it appears in the extension relation output.
        name: String,
        /// Parsed Substrait type for the column.
        ///
        /// This uses the protobuf field name, hence the raw identifier.
        r#type: proto::Type,
    },
    /// Expression-compatible output column, including field references.
    Expr(Expr),
}

impl ExtensionColumn {
    /// Create an expression output column that references an existing input field (`$N`).
    pub fn field(index: i32) -> Self {
        Self::Expr(Expr::field(index))
    }
}

impl ExtensionArgs {
    /// Decodes these arguments as an [`Explainable`] extension value.
    ///
    /// If decoding succeeds, this method rejects any named or positional
    /// arguments the implementation did not access. If decoding fails, it
    /// returns that error without checking for unhandled arguments.
    pub fn parse<T>(&self) -> Result<T, ExtensionError>
    where
        T: Explainable,
    {
        let mut access = ArgsAccess::new(self);
        let value = T::from_args(&mut access)?;
        access.finish()?;
        Ok(value)
    }

    /// Push a positional extension argument.
    pub fn push<T>(&mut self, value: T)
    where
        T: Into<ExtensionValue>,
    {
        self.positional.push(value.into());
    }

    /// Insert a named extension argument, returning any previous value.
    pub fn insert<K, V>(&mut self, name: K, value: V) -> Option<ExtensionValue>
    where
        K: Into<String>,
        V: Into<ExtensionValue>,
    {
        self.named.insert(name.into(), value.into())
    }
}

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

    fn assert_named_invalid_type(
        error: &ExtensionError,
        name: &str,
        expected: ExtensionValueKind,
        actual: ExtensionValueKind,
    ) {
        assert!(
            matches!(
                error,
                ExtensionError::NamedArgumentConversion {
                    name: actual_name,
                    source,
                } if actual_name == name
                    && matches!(
                        source.as_ref(),
                        ExtensionError::InvalidArgumentType {
                            expected: actual_expected,
                            actual: actual_actual,
                        } if *actual_expected == expected && *actual_actual == actual
                    )
            ),
            "unexpected error: {error:?}"
        );
    }

    #[test]
    fn get_named_converts_present_values_and_returns_none_for_missing_values() {
        let mut args = ExtensionArgs::default();
        args.insert("count", 8_i64);
        let mut access = ArgsAccess::new(&args);

        assert_eq!(access.get_named::<i64>("count").unwrap(), Some(8));
        assert_eq!(access.get_named::<i64>("missing").unwrap(), None);
        assert!(access.finish().is_ok());
    }

    #[test]
    fn get_named_contextualizes_conversion_errors() {
        let mut args = ExtensionArgs::default();
        args.insert("count", ExtensionValue::Null);
        let mut access = ArgsAccess::new(&args);

        let error = access
            .get_named::<i64>("count")
            .expect_err("null should not convert to i64");

        assert_eq!(
            error.to_string(),
            "Invalid named argument 'count': Invalid argument: expected integer, got null"
        );
        assert!(access.finish().is_ok());
    }

    #[test]
    fn get_named_tuple_converts_present_values_and_returns_none_for_missing_values() {
        let mut args = ExtensionArgs::default();
        args.insert(
            "names",
            ExtensionValue::Tuple(vec!["first".into(), "second".into()].into()),
        );
        let mut access = ArgsAccess::new(&args);

        assert_eq!(access.get_named_tuple::<String>("missing").unwrap(), None);
        assert_eq!(
            access.get_named_tuple::<String>("names").unwrap(),
            Some(vec!["first".to_string(), "second".to_string()])
        );
        assert!(access.finish().is_ok());
    }

    #[test]
    fn get_named_tuple_contextualizes_invalid_outer_value() {
        let mut args = ExtensionArgs::default();
        args.insert("names", "not a tuple");
        let mut access = ArgsAccess::new(&args);

        let error = access
            .get_named_tuple::<String>("names")
            .expect_err("string should not convert to tuple");

        assert_named_invalid_type(
            &error,
            "names",
            ExtensionValueKind::Tuple,
            ExtensionValueKind::String,
        );
        assert!(access.finish().is_ok());
    }

    #[test]
    fn get_named_tuple_contextualizes_invalid_element() {
        let mut args = ExtensionArgs::default();
        args.insert(
            "names",
            ExtensionValue::Tuple(vec!["first".into(), 2_i64.into()].into()),
        );
        let mut access = ArgsAccess::new(&args);

        let error = access
            .get_named_tuple::<String>("names")
            .expect_err("integer should not convert to string");

        assert_named_invalid_type(
            &error,
            "names",
            ExtensionValueKind::String,
            ExtensionValueKind::Integer,
        );
        assert!(access.finish().is_ok());
    }

    #[test]
    fn vector_encodes_as_tuple() {
        let encoded: ExtensionValue = vec![1_i64, 2_i64].into();
        let tuple = <&TupleValue>::try_from(&encoded).unwrap();
        let values = tuple
            .iter()
            .map(i64::try_from)
            .collect::<Result<Vec<_>, _>>()
            .unwrap();

        assert_eq!(values, vec![1, 2]);
    }

    #[test]
    fn error_value_reports_expected_type_and_source_when_extracted() {
        let value = ExtensionValue::Error(ExtensionError::Custom("bad value".to_string()));

        let error = i64::try_from(&value).expect_err("error value should not convert");

        assert_eq!(
            error.to_string(),
            "Cannot convert argument to integer: bad value"
        );
        assert!(matches!(
            &error,
            ExtensionError::ArgumentConversion {
                expected: ExtensionValueKind::Integer,
                source,
            } if matches!(source.as_ref(), ExtensionError::Custom(message) if message == "bad value")
        ));
    }

    #[test]
    fn expect_named_reports_missing_argument_name() {
        let args = ExtensionArgs::default();
        let mut access = ArgsAccess::new(&args);

        let error = access
            .expect_named::<i64>("count")
            .expect_err("missing argument should fail");

        assert_eq!(error.to_string(), "Missing required argument: count");
        assert!(access.finish().is_ok());
    }
}