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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::error::Error;
use std::fmt::Display;

use bytes::BufMut;
use mz_expr::{EvalError, PartitionId};
use mz_proto::{IntoRustIfSome, ProtoType, RustType, TryFromProtoError};
use mz_repr::{GlobalId, Row};
use proptest_derive::Arbitrary;
use prost::Message;
use serde::{Deserialize, Serialize};
use tracing::warn;

include!(concat!(
    env!("OUT_DIR"),
    "/mz_storage_client.types.errors.rs"
));

/// The underlying data was not decodable in the format we expected: eg.
/// invalid JSON or Avro data that doesn't match a schema.
#[derive(Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub struct DecodeError {
    pub kind: DecodeErrorKind,
    pub raw: Vec<u8>,
}

impl RustType<ProtoDecodeError> for DecodeError {
    fn into_proto(&self) -> ProtoDecodeError {
        ProtoDecodeError {
            kind: Some(RustType::into_proto(&self.kind)),
            raw: Some(self.raw.clone()),
        }
    }

    fn from_proto(proto: ProtoDecodeError) -> Result<Self, TryFromProtoError> {
        let kind = match proto.kind {
            Some(kind) => RustType::from_proto(kind)?,
            None => return Err(TryFromProtoError::missing_field("ProtoDecodeError::kind")),
        };
        let raw = proto.raw.into_rust_if_some("raw")?;
        Ok(Self { kind, raw })
    }
}

impl DecodeError {
    pub fn encode<B>(&self, buf: &mut B)
    where
        B: BufMut,
    {
        self.into_proto()
            .encode(buf)
            .expect("no required fields means no initialization errors")
    }

    pub fn decode(buf: &[u8]) -> Result<Self, String> {
        let proto = ProtoDecodeError::decode(buf).map_err(|err| err.to_string())?;
        proto.into_rust().map_err(|err| err.to_string())
    }
}

impl Display for DecodeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} (original bytes: {:x?})", self.kind, self.raw)
    }
}

#[derive(Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum DecodeErrorKind {
    Text(String),
    Bytes(String),
}

impl RustType<ProtoDecodeErrorKind> for DecodeErrorKind {
    fn into_proto(&self) -> ProtoDecodeErrorKind {
        use proto_decode_error_kind::Kind::*;
        ProtoDecodeErrorKind {
            kind: Some(match self {
                DecodeErrorKind::Text(v) => Text(v.clone()),
                DecodeErrorKind::Bytes(v) => Bytes(v.clone()),
            }),
        }
    }

    fn from_proto(proto: ProtoDecodeErrorKind) -> Result<Self, TryFromProtoError> {
        use proto_decode_error_kind::Kind::*;
        match proto.kind {
            Some(Text(v)) => Ok(DecodeErrorKind::Text(v)),
            Some(Bytes(v)) => Ok(DecodeErrorKind::Bytes(v)),
            None => Err(TryFromProtoError::missing_field("ProtoDecodeError::kind")),
        }
    }
}

impl Display for DecodeErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DecodeErrorKind::Text(e) => write!(f, "Text: {}", e),
            DecodeErrorKind::Bytes(e) => write!(f, "Bytes: {}", e),
        }
    }
}

/// Errors arising during envelope processing.
#[derive(Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, Deserialize, Serialize, PartialEq, Hash)]
pub enum EnvelopeError {
    /// An error arising while processing the Debezium envelope.
    Debezium(String),
    /// An error that can be retracted by a future message using upsert logic.
    Upsert(UpsertError),
    /// Errors corresponding to `ENVELOPE NONE`. Naming this
    /// `None`, though, would have been too confusing.
    Flat(String),
}

impl RustType<ProtoEnvelopeErrorV1> for EnvelopeError {
    fn into_proto(&self) -> ProtoEnvelopeErrorV1 {
        use proto_envelope_error_v1::Kind;
        ProtoEnvelopeErrorV1 {
            kind: Some(match self {
                EnvelopeError::Debezium(text) => Kind::Debezium(text.clone()),
                EnvelopeError::Upsert(rust) => Kind::Upsert(rust.into_proto()),
                EnvelopeError::Flat(text) => Kind::Flat(text.clone()),
            }),
        }
    }

    fn from_proto(proto: ProtoEnvelopeErrorV1) -> Result<Self, TryFromProtoError> {
        use proto_envelope_error_v1::Kind;
        match proto.kind {
            Some(Kind::Debezium(text)) => Ok(Self::Debezium(text)),
            Some(Kind::Upsert(proto)) => {
                let rust = RustType::from_proto(proto)?;
                Ok(Self::Upsert(rust))
            }
            Some(Kind::Flat(text)) => Ok(Self::Flat(text)),
            None => Err(TryFromProtoError::missing_field(
                "ProtoEnvelopeErrorV1::kind",
            )),
        }
    }
}

impl Display for EnvelopeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EnvelopeError::Debezium(err) => write!(f, "Debezium: {err}"),
            EnvelopeError::Upsert(err) => write!(f, "Upsert: {err}"),
            EnvelopeError::Flat(err) => write!(f, "Flat: {err}"),
        }
    }
}

/// An error from a value in an upsert source. The corresponding key is included, allowing
/// us to reconstruct their entry in the upsert map upon restart.
#[derive(Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub struct UpsertValueError {
    /// The underlying error.
    pub inner: DecodeError,
    /// The (good) key associated with the errored value.
    pub for_key: Row,
}

impl RustType<ProtoUpsertValueError> for UpsertValueError {
    fn into_proto(&self) -> ProtoUpsertValueError {
        ProtoUpsertValueError {
            inner: Some(self.inner.into_proto()),
            for_key: Some(self.for_key.into_proto()),
        }
    }

    fn from_proto(proto: ProtoUpsertValueError) -> Result<Self, TryFromProtoError> {
        let inner = match proto.inner {
            Some(inner) => RustType::from_proto(inner)?,
            None => {
                return Err(TryFromProtoError::missing_field(
                    "ProtoUpsertValueError::inner",
                ))
            }
        };
        let for_key = match proto.for_key {
            Some(key) => RustType::from_proto(key)?,
            None => {
                return Err(TryFromProtoError::missing_field(
                    "ProtoUpsertValueError::for_key",
                ))
            }
        };
        Ok(Self { inner, for_key })
    }
}

impl Display for UpsertValueError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let UpsertValueError { inner, for_key } = self;
        write!(f, "{inner}, decoded key: {for_key:?}")
    }
}

/// A source contained a record with a NULL key, which we don't support.
#[derive(
    Arbitrary, Ord, PartialOrd, Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash,
)]
pub struct UpsertNullKeyError {
    partition_id: Option<PartitionId>,
}

impl UpsertNullKeyError {
    pub fn with_partition_id(partition_id: PartitionId) -> Self {
        Self {
            partition_id: Some(partition_id),
        }
    }
}

impl RustType<ProtoUpsertNullKeyError> for UpsertNullKeyError {
    fn into_proto(&self) -> ProtoUpsertNullKeyError {
        ProtoUpsertNullKeyError {
            partition_id: self.partition_id.map(|id| id.into_proto()),
        }
    }

    fn from_proto(proto: ProtoUpsertNullKeyError) -> Result<Self, TryFromProtoError> {
        let partition_id = RustType::from_proto(proto.partition_id)?;
        Ok(Self { partition_id })
    }
}

impl Display for UpsertNullKeyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "record with NULL key in UPSERT source")?;

        if let Some(partition_id) = self.partition_id {
            write!(f, " in partition {}", partition_id)?;
        }

        write!(
            f,
            "; to retract this error, produce a record upstream with a NULL key and NULL value",
        )?;

        Ok(())
    }
}

/// An error that can be retracted by a future message using upsert logic.
#[derive(Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum UpsertError {
    /// Wrapper around a key decoding error.
    /// We use this instead of emitting the underlying `DataflowError::DecodeError` because with only
    /// the underlying error, we can't distinguish between an error with the key and an error
    /// with the value.
    ///
    /// It is necessary to distinguish them because the necessary record to retract them is different.
    /// `(K, <errored V>)` is retracted by `(K, null)`, whereas `(<errored K>, anything)` is retracted by
    /// `("bytes", null)`, where "bytes" is the string that failed to correctly decode as a key.
    KeyDecode(DecodeError),
    /// Wrapper around an error related to the value.
    Value(UpsertValueError),
    NullKey(UpsertNullKeyError),
}

impl RustType<ProtoUpsertError> for UpsertError {
    fn into_proto(&self) -> ProtoUpsertError {
        use proto_upsert_error::Kind;
        ProtoUpsertError {
            kind: Some(match self {
                UpsertError::KeyDecode(err) => Kind::KeyDecode(err.into_proto()),
                UpsertError::Value(err) => Kind::Value(err.into_proto()),
                UpsertError::NullKey(err) => Kind::NullKey(err.into_proto()),
            }),
        }
    }

    fn from_proto(proto: ProtoUpsertError) -> Result<Self, TryFromProtoError> {
        use proto_upsert_error::Kind;
        match proto.kind {
            Some(Kind::KeyDecode(proto)) => {
                let rust = RustType::from_proto(proto)?;
                Ok(Self::KeyDecode(rust))
            }
            Some(Kind::Value(proto)) => {
                let rust = RustType::from_proto(proto)?;
                Ok(Self::Value(rust))
            }
            Some(Kind::NullKey(proto)) => {
                let rust = RustType::from_proto(proto)?;
                Ok(Self::NullKey(rust))
            }
            None => Err(TryFromProtoError::missing_field("ProtoUpsertError::kind")),
        }
    }
}

impl Display for UpsertError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            UpsertError::KeyDecode(err) => write!(f, "Key decode: {err}"),
            UpsertError::Value(err) => write!(f, "Value error: {err}"),
            UpsertError::NullKey(err) => write!(f, "Null key: {err}"),
        }
    }
}

/// Source-wide durable errors; for example, a replication log being meaningless or corrupted.
/// This should _not_ include transient source errors, like connection issues or misconfigurations.
#[derive(Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub struct SourceError {
    pub source_id: GlobalId,
    pub error: SourceErrorDetails,
}

impl SourceError {
    pub fn new(source_id: GlobalId, error: SourceErrorDetails) -> SourceError {
        SourceError { source_id, error }
    }
}

impl RustType<ProtoSourceError> for SourceError {
    fn into_proto(&self) -> ProtoSourceError {
        ProtoSourceError {
            source_id: Some(self.source_id.into_proto()),
            error: Some(self.error.into_proto()),
        }
    }

    fn from_proto(proto: ProtoSourceError) -> Result<Self, TryFromProtoError> {
        Ok(SourceError {
            source_id: proto
                .source_id
                .into_rust_if_some("ProtoSourceError::source_id")?,
            error: proto.error.into_rust_if_some("ProtoSourceError::error")?,
        })
    }
}

impl Display for SourceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: ", self.source_id)?;
        self.error.fmt(f)
    }
}

#[derive(Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum SourceErrorDetails {
    Initialization(String),
    Other(String),
}

impl RustType<ProtoSourceErrorDetails> for SourceErrorDetails {
    fn into_proto(&self) -> ProtoSourceErrorDetails {
        use proto_source_error_details::Kind;
        ProtoSourceErrorDetails {
            kind: Some(match self {
                SourceErrorDetails::Initialization(s) => Kind::Initialization(s.clone()),
                SourceErrorDetails::Other(s) => Kind::Other(s.clone()),
            }),
        }
    }

    fn from_proto(proto: ProtoSourceErrorDetails) -> Result<Self, TryFromProtoError> {
        use proto_source_error_details::Kind;
        match proto.kind {
            Some(kind) => match kind {
                Kind::Initialization(s) => Ok(SourceErrorDetails::Initialization(s)),
                Kind::DeprecatedFileIo(s) | Kind::DeprecatedPersistence(s) => {
                    warn!("Deprecated source error kind: {s}");
                    Ok(SourceErrorDetails::Other(s))
                }
                Kind::Other(s) => Ok(SourceErrorDetails::Other(s)),
            },
            None => Err(TryFromProtoError::missing_field(
                "ProtoSourceErrorDetails::kind",
            )),
        }
    }
}

impl Display for SourceErrorDetails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SourceErrorDetails::Initialization(e) => {
                write!(
                    f,
                    "failed during initialization, must be dropped and recreated: {}",
                    e
                )
            }
            SourceErrorDetails::Other(e) => write!(f, "{}", e),
        }
    }
}

/// An error that's destined to be presented to the user in a differential dataflow collection.
/// For example, a divide by zero will be visible in the error collection for a particular row.
///
/// All of the variants are boxed to minimize the memory size of `DataflowError`. This type is
/// likely to appear in `Result<Row, DataflowError>`s on high-throughput code paths, so keeping its
/// size less than or equal to that of `Row` is important to ensure we are not wasting memory.
#[derive(Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, Deserialize, Serialize, PartialEq, Hash)]
pub enum DataflowError {
    DecodeError(Box<DecodeError>),
    EvalError(Box<EvalError>),
    SourceError(Box<SourceError>),
    EnvelopeError(Box<EnvelopeError>),
}

impl Error for DataflowError {}

mod columnation {
    use std::iter::once;

    use mz_expr::EvalError;
    use mz_repr::adt::range::InvalidRangeError;
    use mz_repr::strconv::ParseError;
    use mz_repr::Row;
    use timely::container::columnation::{Columnation, Region, StableRegion};

    use crate::types::errors::{
        DataflowError, DecodeError, DecodeErrorKind, EnvelopeError, SourceError,
        SourceErrorDetails, UpsertError, UpsertValueError,
    };

    impl Columnation for DataflowError {
        type InnerRegion = DataflowErrorRegion;
    }

    /// A region to store [`DataflowError`].
    #[derive(Default)]
    pub struct DataflowErrorRegion {
        /// Stable location for [`DecodeError`] for inserting into a box.
        decode_error_region: StableRegion<DecodeError>,
        /// Stable location for [`EnvelopeError`] for inserting into a box.
        envelope_error_region: StableRegion<EnvelopeError>,
        /// Stable location for [`EvalError`] for inserting into a box.
        eval_error_region: StableRegion<EvalError>,
        /// Region for storing rows.
        row_region: <Row as Columnation>::InnerRegion,
        /// Stable location for [`SourceError`] for inserting into a box.
        source_error_region: StableRegion<SourceError>,
        /// Region for storing strings.
        string_region: <String as Columnation>::InnerRegion,
        /// Region for storing u8 vectors.
        u8_region: <Vec<u8> as Columnation>::InnerRegion,
    }

    impl DataflowErrorRegion {
        /// Copy a decode error into its region, return an owned object.
        ///
        /// This is unsafe because the returned value must not be dropped.
        unsafe fn copy_decode_error(&mut self, decode_error: &DecodeError) -> DecodeError {
            DecodeError {
                kind: match &decode_error.kind {
                    DecodeErrorKind::Text(string) => {
                        DecodeErrorKind::Text(self.string_region.copy(string))
                    }
                    DecodeErrorKind::Bytes(string) => {
                        DecodeErrorKind::Bytes(self.string_region.copy(string))
                    }
                },
                raw: self.u8_region.copy(&decode_error.raw),
            }
        }
    }

    /// Compile-time assertion that a value is `Copy`.
    fn assert_copy<T: Copy>(_: &T) {}

    impl Region for DataflowErrorRegion {
        type Item = DataflowError;

        unsafe fn copy(&mut self, item: &Self::Item) -> Self::Item {
            // Unsafe Box::from_raw reasoning:
            // Construct a box from a provided value. This is safe because a box is
            // a pointer to a memory address, and the value is stored on the heap.
            // Note that the box must not be dropped.

            // SAFETY: When adding new enum variants, care must be taken that all types containing
            // references are region-allocated, otherwise we'll leak memory.

            // Types that are `Copy` should be asserted using `assert_copy`, or copied, to detect
            // changes that introduce pointers.

            let err = match item {
                DataflowError::DecodeError(err) => {
                    let err = self.copy_decode_error(&*err);
                    let reference = self.decode_error_region.copy_iter(once(err));
                    let boxed = unsafe { Box::from_raw(reference.as_mut_ptr()) };
                    DataflowError::DecodeError(boxed)
                }
                DataflowError::EvalError(err) => {
                    let err: &EvalError = &*err;
                    let err = match err {
                        e @ EvalError::CharacterNotValidForEncoding(x) => {
                            assert_copy(x);
                            e.clone()
                        }
                        e @ EvalError::CharacterTooLargeForEncoding(x) => {
                            assert_copy(x);
                            e.clone()
                        }
                        EvalError::DateBinOutOfRange(string) => {
                            EvalError::DateBinOutOfRange(self.string_region.copy(string))
                        }
                        e @ EvalError::DivisionByZero
                        | e @ EvalError::FloatOverflow
                        | e @ EvalError::FloatUnderflow
                        | e @ EvalError::NumericFieldOverflow
                        | e @ EvalError::MzTimestampStepOverflow
                        | e @ EvalError::TimestampCannotBeNan
                        | e @ EvalError::TimestampOutOfRange
                        | e @ EvalError::NegSqrt
                        | e @ EvalError::NullCharacterNotPermitted
                        | e @ EvalError::UnterminatedLikeEscapeSequence
                        | e @ EvalError::MultipleRowsFromSubquery
                        | e @ EvalError::LikePatternTooLong
                        | e @ EvalError::LikeEscapeTooLong
                        | e @ EvalError::MultidimensionalArrayRemovalNotSupported
                        | e @ EvalError::MultiDimensionalArraySearch
                        | e @ EvalError::ArrayFillWrongArraySubscripts
                        | e @ EvalError::DateOutOfRange
                        | e @ EvalError::CharOutOfRange
                        | e @ EvalError::InvalidBase64Equals
                        | e @ EvalError::InvalidBase64EndSequence
                        | e @ EvalError::InvalidTimezoneInterval
                        | e @ EvalError::InvalidTimezoneConversion
                        | e @ EvalError::LengthTooLarge => e.clone(),
                        EvalError::Unsupported { feature, issue_no } => EvalError::Unsupported {
                            feature: self.string_region.copy(feature),
                            issue_no: *issue_no,
                        },
                        EvalError::Float32OutOfRange(string) => {
                            EvalError::Float32OutOfRange(self.string_region.copy(string))
                        }
                        EvalError::Float64OutOfRange(string) => {
                            EvalError::Float64OutOfRange(self.string_region.copy(string))
                        }
                        EvalError::Int16OutOfRange(string) => {
                            EvalError::Int16OutOfRange(self.string_region.copy(string))
                        }
                        EvalError::Int32OutOfRange(string) => {
                            EvalError::Int32OutOfRange(self.string_region.copy(string))
                        }
                        EvalError::Int64OutOfRange(string) => {
                            EvalError::Int64OutOfRange(self.string_region.copy(string))
                        }
                        EvalError::UInt16OutOfRange(string) => {
                            EvalError::UInt16OutOfRange(self.string_region.copy(string))
                        }
                        EvalError::UInt32OutOfRange(string) => {
                            EvalError::UInt32OutOfRange(self.string_region.copy(string))
                        }
                        EvalError::UInt64OutOfRange(string) => {
                            EvalError::UInt64OutOfRange(self.string_region.copy(string))
                        }
                        EvalError::MzTimestampOutOfRange(string) => {
                            EvalError::MzTimestampOutOfRange(self.string_region.copy(string))
                        }
                        EvalError::OidOutOfRange(string) => {
                            EvalError::OidOutOfRange(self.string_region.copy(string))
                        }
                        EvalError::IntervalOutOfRange(string) => {
                            EvalError::IntervalOutOfRange(self.string_region.copy(string))
                        }
                        e @ EvalError::IndexOutOfRange {
                            provided,
                            valid_end,
                        } => {
                            assert_copy(provided);
                            assert_copy(valid_end);
                            e.clone()
                        }
                        e @ EvalError::InvalidBase64Symbol(c) => {
                            assert_copy(c);
                            e.clone()
                        }
                        EvalError::InvalidTimezone(x) => {
                            EvalError::InvalidTimezone(self.string_region.copy(x))
                        }
                        e @ EvalError::InvalidLayer { max_layer, val } => {
                            assert_copy(max_layer);
                            assert_copy(val);
                            e.clone()
                        }
                        EvalError::InvalidArray(err) => EvalError::InvalidArray(*err),
                        EvalError::InvalidEncodingName(x) => {
                            EvalError::InvalidEncodingName(self.string_region.copy(x))
                        }
                        EvalError::InvalidHashAlgorithm(x) => {
                            EvalError::InvalidHashAlgorithm(self.string_region.copy(x))
                        }
                        EvalError::InvalidByteSequence {
                            byte_sequence,
                            encoding_name,
                        } => EvalError::InvalidByteSequence {
                            byte_sequence: self.string_region.copy(byte_sequence),
                            encoding_name: self.string_region.copy(encoding_name),
                        },
                        EvalError::InvalidJsonbCast { from, to } => EvalError::InvalidJsonbCast {
                            from: self.string_region.copy(from),
                            to: self.string_region.copy(to),
                        },
                        EvalError::InvalidRegex(x) => {
                            EvalError::InvalidRegex(self.string_region.copy(x))
                        }
                        e @ EvalError::InvalidRegexFlag(x) => {
                            assert_copy(x);
                            e.clone()
                        }
                        EvalError::InvalidParameterValue(x) => {
                            EvalError::InvalidParameterValue(self.string_region.copy(x))
                        }
                        EvalError::InvalidDatePart(x) => {
                            EvalError::InvalidDatePart(self.string_region.copy(x))
                        }
                        EvalError::UnknownUnits(x) => {
                            EvalError::UnknownUnits(self.string_region.copy(x))
                        }
                        EvalError::UnsupportedUnits(x, y) => EvalError::UnsupportedUnits(
                            self.string_region.copy(x),
                            self.string_region.copy(y),
                        ),
                        EvalError::Parse(ParseError {
                            kind,
                            type_name,
                            input,
                            details,
                        }) => EvalError::Parse(ParseError {
                            kind: *kind,
                            type_name: self.string_region.copy(type_name),
                            input: self.string_region.copy(input),
                            details: details
                                .as_ref()
                                .map(|details| self.string_region.copy(details)),
                        }),
                        e @ EvalError::ParseHex(x) => {
                            assert_copy(x);
                            e.clone()
                        }
                        EvalError::Internal(x) => EvalError::Internal(self.string_region.copy(x)),
                        EvalError::InfinityOutOfDomain(x) => {
                            EvalError::InfinityOutOfDomain(self.string_region.copy(x))
                        }
                        EvalError::NegativeOutOfDomain(x) => {
                            EvalError::NegativeOutOfDomain(self.string_region.copy(x))
                        }
                        EvalError::ZeroOutOfDomain(x) => {
                            EvalError::ZeroOutOfDomain(self.string_region.copy(x))
                        }
                        EvalError::OutOfDomain(x, y, z) => {
                            assert_copy(x);
                            assert_copy(y);
                            EvalError::OutOfDomain(*x, *y, self.string_region.copy(z))
                        }
                        EvalError::ComplexOutOfRange(x) => {
                            EvalError::ComplexOutOfRange(self.string_region.copy(x))
                        }
                        EvalError::Undefined(x) => EvalError::Undefined(self.string_region.copy(x)),
                        EvalError::StringValueTooLong {
                            target_type,
                            length,
                        } => EvalError::StringValueTooLong {
                            target_type: self.string_region.copy(target_type),
                            length: *length,
                        },
                        e @ EvalError::IncompatibleArrayDimensions { dims } => {
                            assert_copy(dims);
                            e.clone()
                        }
                        EvalError::TypeFromOid(x) => {
                            EvalError::TypeFromOid(self.string_region.copy(x))
                        }
                        EvalError::InvalidRange(x) => {
                            let err = match x {
                                e @ InvalidRangeError::MisorderedRangeBounds
                                | e @ InvalidRangeError::InvalidRangeBoundFlags
                                | e @ InvalidRangeError::DiscontiguousUnion
                                | e @ InvalidRangeError::DiscontiguousDifference
                                | e @ InvalidRangeError::NullRangeBoundFlags => e.clone(),
                                InvalidRangeError::CanonicalizationOverflow(string) => {
                                    InvalidRangeError::CanonicalizationOverflow(
                                        self.string_region.copy(string),
                                    )
                                }
                            };
                            EvalError::InvalidRange(err)
                        }
                        EvalError::InvalidRoleId(x) => {
                            EvalError::InvalidRoleId(self.string_region.copy(x))
                        }
                        EvalError::InvalidPrivileges(x) => {
                            EvalError::InvalidPrivileges(self.string_region.copy(x))
                        }
                        EvalError::LetRecLimitExceeded(x) => {
                            EvalError::LetRecLimitExceeded(self.string_region.copy(x))
                        }
                        EvalError::MustNotBeNull(x) => {
                            EvalError::MustNotBeNull(self.string_region.copy(x))
                        }
                        EvalError::InvalidIdentifier { ident, detail } => {
                            EvalError::InvalidIdentifier {
                                ident: self.string_region.copy(ident),
                                detail: detail
                                    .as_ref()
                                    .map(|detail| self.string_region.copy(detail)),
                            }
                        }
                        e @ EvalError::MaxArraySizeExceeded(x) => {
                            assert_copy(x);
                            e.clone()
                        }
                        EvalError::DateDiffOverflow { unit, a, b } => EvalError::DateDiffOverflow {
                            unit: self.string_region.copy(unit),
                            a: self.string_region.copy(a),
                            b: self.string_region.copy(b),
                        },
                        EvalError::IfNullError(x) => {
                            EvalError::IfNullError(self.string_region.copy(x))
                        }
                    };
                    let reference = self.eval_error_region.copy_iter(once(err));
                    let boxed = unsafe { Box::from_raw(reference.as_mut_ptr()) };
                    DataflowError::EvalError(boxed)
                }
                DataflowError::SourceError(err) => {
                    let err: &SourceError = &*err;
                    let err = SourceError {
                        source_id: err.source_id,
                        error: match &err.error {
                            SourceErrorDetails::Initialization(string) => {
                                SourceErrorDetails::Initialization(self.string_region.copy(string))
                            }
                            SourceErrorDetails::Other(string) => {
                                SourceErrorDetails::Other(self.string_region.copy(string))
                            }
                        },
                    };
                    let reference = self.source_error_region.copy_iter(once(err));
                    let boxed = unsafe { Box::from_raw(reference.as_mut_ptr()) };
                    DataflowError::SourceError(boxed)
                }
                DataflowError::EnvelopeError(err) => {
                    let err: &EnvelopeError = &*err;
                    let err = match err {
                        EnvelopeError::Debezium(string) => {
                            EnvelopeError::Debezium(self.string_region.copy(string))
                        }
                        EnvelopeError::Upsert(err) => {
                            let err = match err {
                                UpsertError::KeyDecode(err) => {
                                    UpsertError::KeyDecode(self.copy_decode_error(err))
                                }
                                UpsertError::Value(err) => UpsertError::Value(UpsertValueError {
                                    inner: self.copy_decode_error(&err.inner),
                                    for_key: self.row_region.copy(&err.for_key),
                                }),
                                UpsertError::NullKey(err) => UpsertError::NullKey(*err),
                            };
                            EnvelopeError::Upsert(err)
                        }
                        EnvelopeError::Flat(string) => {
                            EnvelopeError::Flat(self.string_region.copy(string))
                        }
                    };
                    let reference = self.envelope_error_region.copy_iter(once(err));
                    let boxed = unsafe { Box::from_raw(reference.as_mut_ptr()) };
                    DataflowError::EnvelopeError(boxed)
                }
            };
            // Debug-only check that we're returning an equal object.
            debug_assert_eq!(item, &err);
            err
        }

        fn clear(&mut self) {
            // De-structure `self` to make sure we're clearing all regions.
            let Self {
                decode_error_region,
                envelope_error_region,
                eval_error_region,
                row_region,
                source_error_region,
                string_region,
                u8_region,
            } = self;
            decode_error_region.clear();
            envelope_error_region.clear();
            eval_error_region.clear();
            row_region.clear();
            source_error_region.clear();
            string_region.clear();
            u8_region.clear();
        }

        fn reserve_items<'a, I>(&mut self, items: I)
        where
            Self: 'a,
            I: Iterator<Item = &'a Self::Item> + Clone,
        {
            // Reserve space on all stable regions.
            self.decode_error_region.reserve(
                items
                    .clone()
                    .filter(|x| matches!(x, DataflowError::DecodeError(_)))
                    .count(),
            );
            self.envelope_error_region.reserve(
                items
                    .clone()
                    .filter(|x| matches!(x, DataflowError::EnvelopeError(_)))
                    .count(),
            );
            self.eval_error_region.reserve(
                items
                    .clone()
                    .filter(|x| matches!(x, DataflowError::EvalError(_)))
                    .count(),
            );
            self.source_error_region.reserve(
                items
                    .filter(|x| matches!(x, DataflowError::SourceError(_)))
                    .count(),
            );
        }

        fn reserve_regions<'a, I>(&mut self, regions: I)
        where
            Self: 'a,
            I: Iterator<Item = &'a Self> + Clone,
        {
            // Reserve space on all region allocators.
            self.row_region
                .reserve_regions(regions.clone().map(|r| &r.row_region));
            self.string_region
                .reserve_regions(regions.clone().map(|r| &r.string_region));
            self.u8_region
                .reserve_regions(regions.clone().map(|r| &r.u8_region));
        }

        fn heap_size(&self, mut callback: impl FnMut(usize, usize)) {
            // De-structure `self` to make sure we're counting all regions.
            let Self {
                decode_error_region,
                envelope_error_region,
                eval_error_region,
                row_region,
                source_error_region,
                string_region,
                u8_region,
            } = &self;
            decode_error_region.heap_size(&mut callback);
            envelope_error_region.heap_size(&mut callback);
            eval_error_region.heap_size(&mut callback);
            row_region.heap_size(&mut callback);
            source_error_region.heap_size(&mut callback);
            string_region.heap_size(&mut callback);
            u8_region.heap_size(callback);
        }
    }

    #[cfg(test)]
    mod tests {
        use proptest::prelude::*;
        use timely::container::columnation::TimelyStack;

        use super::*;

        fn columnation_roundtrip<T: Columnation>(item: &T) -> TimelyStack<T> {
            let mut container = TimelyStack::with_capacity(1);
            container.copy(item);
            container
        }

        proptest! {
            #[mz_ore::test]
            // unsupported operation: can't call foreign function `decContextDefault` on OS `linux`
            #[cfg_attr(miri, ignore)]
            fn dataflow_error_roundtrip(expect in any::<DataflowError>()) {
                let actual = columnation_roundtrip(&expect);
                proptest::prop_assert_eq!(&expect, &actual[0])
            }
        }
    }
}

impl RustType<ProtoDataflowError> for DataflowError {
    fn into_proto(&self) -> ProtoDataflowError {
        use proto_dataflow_error::Kind::*;
        ProtoDataflowError {
            kind: Some(match self {
                DataflowError::DecodeError(err) => DecodeError(*err.into_proto()),
                DataflowError::EvalError(err) => EvalError(*err.into_proto()),
                DataflowError::SourceError(err) => SourceError(*err.into_proto()),
                DataflowError::EnvelopeError(err) => EnvelopeErrorV1(*err.into_proto()),
            }),
        }
    }

    fn from_proto(proto: ProtoDataflowError) -> Result<Self, TryFromProtoError> {
        use proto_dataflow_error::Kind::*;
        match proto.kind {
            Some(kind) => match kind {
                DecodeError(err) => Ok(DataflowError::DecodeError(Box::new(err.into_rust()?))),
                EvalError(err) => Ok(DataflowError::EvalError(Box::new(err.into_rust()?))),
                SourceError(err) => Ok(DataflowError::SourceError(Box::new(err.into_rust()?))),
                EnvelopeErrorV1(err) => {
                    Ok(DataflowError::EnvelopeError(Box::new(err.into_rust()?)))
                }
            },
            None => Err(TryFromProtoError::missing_field("ProtoDataflowError::kind")),
        }
    }
}

impl Display for DataflowError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DataflowError::DecodeError(e) => write!(f, "Decode error: {}", e),
            DataflowError::EvalError(e) => write!(
                f,
                "{}{}",
                match **e {
                    EvalError::IfNullError(_) => "",
                    _ => "Evaluation error: ",
                },
                e
            ),
            DataflowError::SourceError(e) => write!(f, "Source error: {}", e),
            DataflowError::EnvelopeError(e) => write!(f, "Envelope error: {}", e),
        }
    }
}

impl From<DecodeError> for DataflowError {
    fn from(e: DecodeError) -> Self {
        Self::DecodeError(Box::new(e))
    }
}

impl From<EvalError> for DataflowError {
    fn from(e: EvalError) -> Self {
        Self::EvalError(Box::new(e))
    }
}

impl From<SourceError> for DataflowError {
    fn from(e: SourceError) -> Self {
        Self::SourceError(Box::new(e))
    }
}

impl From<EnvelopeError> for DataflowError {
    fn from(e: EnvelopeError) -> Self {
        Self::EnvelopeError(Box::new(e))
    }
}

#[cfg(test)]
mod tests {
    use crate::types::errors::DecodeErrorKind;

    use super::DecodeError;

    #[mz_ore::test]
    fn test_decode_error_codec_roundtrip() -> Result<(), String> {
        let original = DecodeError {
            kind: DecodeErrorKind::Text("ciao".to_string()),
            raw: b"oaic".to_vec(),
        };
        let mut encoded = Vec::new();
        original.encode(&mut encoded);
        let decoded = DecodeError::decode(&encoded)?;

        assert_eq!(decoded, original);

        Ok(())
    }
}