delta-funnel 0.1.6

Lightweight, fast Delta Lake to SQL Server loads with DataFusion SQL and native TDS
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
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
//! Shared error pattern for DeltaFunnel.

use crate::BatchPipelinePhase;
use crate::support::{sanitize_text_for_display, sanitize_uri_for_display};

use snafu::Snafu;

/// Phase associated with a Delta scan file read failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeltaScanFileReadPhase {
    /// Parsing the table URI failed.
    TableUriParsing,
    /// Converting provider file metadata into kernel file metadata failed.
    FileMetadataConversion,
    /// Resolving the Delta add-action path against the table root failed.
    FilePathResolution,
    /// Constructing the kernel object-store engine failed.
    ObjectStoreEngineConstruction,
    /// Starting a Parquet read failed.
    ParquetReadSetup,
    /// Reading a Parquet batch failed.
    ParquetBatchRead,
    /// Generating or decoding original row indexes failed.
    RowIndexGeneration,
    /// Evaluating a kernel physical predicate failed.
    PredicateEvaluation,
    /// Converting kernel engine data into Arrow failed.
    ArrowConversion,
    /// Applying a physical-to-logical transform failed.
    TransformApplication,
    /// The selected backend cannot read this file task equivalently.
    UnsupportedReadMode,
    /// A deletion-vector read was rejected because the requested read mode is not safe.
    DeletionVectorPredicateRejection,
    /// Applying a deletion-vector mask failed.
    DeletionVectorMasking,
}

impl std::fmt::Display for DeltaScanFileReadPhase {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::TableUriParsing => "table URI parsing",
            Self::FileMetadataConversion => "file metadata conversion",
            Self::FilePathResolution => "file path resolution",
            Self::ObjectStoreEngineConstruction => "object store engine construction",
            Self::ParquetReadSetup => "Parquet read setup",
            Self::ParquetBatchRead => "Parquet batch read",
            Self::RowIndexGeneration => "row-index generation",
            Self::PredicateEvaluation => "physical predicate evaluation",
            Self::ArrowConversion => "Arrow conversion",
            Self::TransformApplication => "physical-to-logical transform application",
            Self::UnsupportedReadMode => "unsupported read mode",
            Self::DeletionVectorPredicateRejection => "deletion-vector predicate read rejection",
            Self::DeletionVectorMasking => "deletion-vector masking",
        })
    }
}

/// Phase associated with a Delta scan deletion-vector failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeltaScanDeletionVectorPhase {
    /// Parsing the table URI failed.
    TableUriParsing,
    /// Constructing the kernel object-store engine failed.
    ObjectStoreEngineConstruction,
    /// Accessing the preserved deletion-vector descriptor failed.
    DescriptorAccess,
    /// Reading or decoding the deletion-vector payload failed.
    PayloadRead,
    /// The selection vector did not match the physical file row count.
    SelectionVectorLengthMismatch,
    /// The selection vector was consumed after it was closed.
    SelectionVectorExhaustion,
}

impl std::fmt::Display for DeltaScanDeletionVectorPhase {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::TableUriParsing => "table URI parsing",
            Self::ObjectStoreEngineConstruction => "object store engine construction",
            Self::DescriptorAccess => "deletion-vector descriptor access",
            Self::PayloadRead => "deletion-vector payload read",
            Self::SelectionVectorLengthMismatch => "selection-vector length mismatch",
            Self::SelectionVectorExhaustion => "selection-vector exhaustion",
        })
    }
}

/// Error type used by DeltaFunnel APIs.
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum DeltaFunnelError {
    /// Caller configuration is invalid.
    #[snafu(display("configuration error: {message}"))]
    Config {
        /// Sanitized message suitable for logs and Python-facing errors.
        message: String,
    },

    /// A Delta source name is not valid for registration.
    #[snafu(display(
        "invalid Delta source name `{}`: {reason}",
        sanitize_source_name_for_display(name)
    ))]
    InvalidSourceName {
        /// Caller-provided source name.
        name: String,
        /// Sanitized reason for the validation failure.
        reason: &'static str,
    },

    /// Two configured Delta sources use the same registration name.
    #[snafu(display(
        "duplicate Delta source name `{}`",
        sanitize_source_name_for_display(name)
    ))]
    DuplicateSourceName {
        /// Caller-provided duplicate source name.
        name: String,
    },

    /// A Delta source URI is not valid for snapshot loading.
    #[snafu(display("invalid Delta source URI: {reason}"))]
    InvalidSourceUri {
        /// Sanitized reason for the validation failure.
        reason: &'static str,
    },

    /// A Delta source engine could not be constructed.
    #[snafu(display("Delta source engine error: {reason}"))]
    DeltaSourceEngine {
        /// Sanitized reason for the engine construction failure.
        reason: &'static str,
    },

    /// A Delta snapshot could not be loaded.
    #[snafu(display("Delta snapshot load error: {reason}"))]
    DeltaSnapshotLoad {
        /// Sanitized reason for the snapshot load failure.
        reason: String,
    },

    /// A Delta source requires an unsupported reader protocol.
    #[snafu(display(
        "Delta protocol compatibility error for source `{}` at snapshot version {snapshot_version} ({}): {reason}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri)
    ))]
    DeltaProtocolCompatibility {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Resolved Delta snapshot version.
        snapshot_version: u64,
        /// Sanitized reason for the compatibility failure.
        reason: String,
    },

    /// A Delta source schema could not be exposed to the query engine.
    #[snafu(display(
        "Delta source schema error for source `{}` ({}): {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(reason)
    ))]
    DeltaSourceSchema {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Sanitized reason for the schema failure.
        reason: String,
    },

    /// A Delta source could not be registered with DataFusion.
    #[snafu(display(
        "DataFusion registration error for source `{}` ({}): {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(reason)
    ))]
    DataFusionRegistration {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Sanitized reason for the registration failure.
        reason: String,
    },

    /// Lazy SQL-derived table planning or alias registration failed.
    #[snafu(display(
        "SQL table error during {phase}: {}",
        sanitize_reason_for_display(message)
    ))]
    SqlTable {
        /// Session SQL table phase that failed.
        phase: SqlTablePhase,
        /// Sanitized reason for the failure.
        message: String,
    },

    /// A Delta provider scan projection could not be planned.
    #[snafu(display(
        "Delta scan projection error for source `{}` ({}): {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(reason)
    ))]
    DeltaScanProjection {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Sanitized reason for the projection failure.
        reason: String,
    },

    /// A pushed Delta provider scan filter could not be planned safely.
    #[snafu(display(
        "Delta scan filter error for source `{}` ({}): {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(reason)
    ))]
    DeltaScanFilter {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Sanitized reason for the filter failure.
        reason: String,
    },

    /// A Delta kernel scan could not be constructed.
    #[snafu(display(
        "Delta scan construction error for source `{}` ({}): {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(&source.to_string())
    ))]
    DeltaScanConstruction {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Kernel scan construction failure.
        #[snafu(source(from(delta_kernel::Error, Box::new)))]
        source: Box<delta_kernel::Error>,
    },

    /// Delta scan metadata could not be expanded from kernel scan planning.
    #[snafu(display(
        "Delta scan metadata expansion error for source `{}` at snapshot version {snapshot_version} ({}): {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(&source.to_string())
    ))]
    DeltaScanMetadataExpansion {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Resolved Delta snapshot version.
        snapshot_version: u64,
        /// Kernel scan metadata expansion failure.
        #[snafu(source(from(delta_kernel::Error, Box::new)))]
        source: Box<delta_kernel::Error>,
    },

    /// Delta scan metadata could not be converted into provider file tasks.
    #[snafu(display(
        "Delta scan file task planning error for source `{}` at snapshot version {snapshot_version} ({}), file `{}`: {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(path),
        sanitize_reason_for_display(reason)
    ))]
    DeltaScanFileTaskPlanning {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Resolved Delta snapshot version.
        snapshot_version: u64,
        /// Delta add-action path associated with the task planning failure.
        path: String,
        /// Sanitized reason for the task planning failure.
        reason: String,
    },

    /// Delta scan file tasks could not be grouped into provider scan partitions.
    #[snafu(display(
        "Delta scan file task partition planning error for source `{}` at snapshot version {snapshot_version} ({}): {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(reason)
    ))]
    DeltaScanFileTaskPartitionPlanning {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Resolved Delta snapshot version.
        snapshot_version: u64,
        /// Sanitized reason for the partition planning failure.
        reason: String,
    },

    /// A Delta scan data file could not be read through the kernel adapter.
    #[snafu(display(
        "Delta scan file read error for source `{}` at snapshot version {snapshot_version} ({}), file `{}` during {phase}: {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(path),
        sanitize_reason_for_display(&source.to_string())
    ))]
    DeltaScanFileRead {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Resolved Delta snapshot version.
        snapshot_version: u64,
        /// Delta add-action path associated with the read failure.
        path: String,
        /// Read phase associated with the failure.
        phase: DeltaScanFileReadPhase,
        /// Underlying kernel read failure.
        #[snafu(source(from(delta_kernel::Error, Box::new)))]
        source: Box<delta_kernel::Error>,
    },

    /// A Delta scan deletion vector could not be loaded or consumed safely.
    #[snafu(display(
        "Delta scan deletion-vector error for source `{}` at snapshot version {snapshot_version} ({}), file `{}` during {phase}: {}",
        sanitize_source_name_for_display(source_name),
        sanitize_uri_for_display(table_uri),
        sanitize_reason_for_display(path),
        sanitize_reason_for_display(&source.to_string())
    ))]
    DeltaScanDeletionVector {
        /// Caller-provided source name.
        source_name: String,
        /// Sanitized or sanitizable Delta table URI context.
        table_uri: String,
        /// Resolved Delta snapshot version.
        snapshot_version: u64,
        /// Delta add-action path associated with the deletion-vector failure.
        path: String,
        /// Deletion-vector phase associated with the failure.
        phase: DeltaScanDeletionVectorPhase,
        /// Underlying kernel deletion-vector failure.
        #[snafu(source(from(delta_kernel::Error, Box::new)))]
        source: Box<delta_kernel::Error>,
    },

    /// A required dependency contract is unavailable or incompatible.
    #[snafu(display("dependency compatibility error: {message}"))]
    DependencyCompatibility {
        /// Sanitized message suitable for logs and Python-facing errors.
        message: String,
    },

    /// Batch pipeline setup or configuration is invalid.
    #[snafu(display(
        "batch pipeline {phase} error for option `{option}`: {}",
        sanitize_reason_for_display(message)
    ))]
    BatchPipeline {
        /// Batch pipeline phase associated with the failure.
        phase: BatchPipelinePhase,
        /// Stable option name associated with the failure.
        option: &'static str,
        /// Sanitized message suitable for logs and Python-facing errors.
        message: String,
    },

    /// SQL Server target configuration is invalid.
    #[snafu(display(
        "MSSQL target configuration error for option `{option}`: {}",
        sanitize_reason_for_display(message)
    ))]
    MssqlTargetConfig {
        /// Stable option name associated with the failure.
        option: &'static str,
        /// Sanitized message suitable for logs and Python-facing errors.
        message: String,
    },

    /// A SQL Server target could not resolve a connection.
    #[snafu(display(
        "MSSQL target for output `{}` has no effective connection",
        sanitize_text_for_display(output_name)
    ))]
    MissingMssqlConnection {
        /// Selected output name associated with the target.
        output_name: String,
    },

    /// A selected output identity is missing or invalid for SQL Server schema planning.
    #[snafu(display(
        "MSSQL schema planning error for output `{}`: {reason}",
        sanitize_text_for_display(output_name)
    ))]
    InvalidMssqlOutputIdentity {
        /// Selected output name associated with the schema.
        output_name: String,
        /// Stable reason for the validation failure.
        reason: &'static str,
    },

    /// A selected output has duplicate field names before SQL Server planning.
    #[snafu(display(
        "MSSQL schema planning error for output `{}`: duplicate field name `{}` at indexes {first_index} and {duplicate_index}",
        sanitize_text_for_display(output_name),
        sanitize_text_for_display(field_name)
    ))]
    DuplicateMssqlOutputField {
        /// Selected output name associated with the schema.
        output_name: String,
        /// Duplicate output field name.
        field_name: String,
        /// First index where the field name was seen.
        first_index: usize,
        /// Duplicate index where the field name was seen again.
        duplicate_index: usize,
    },

    /// SQL Server schema planning failed with structured arrow-tiberius diagnostics.
    #[snafu(display(
        "MSSQL schema planning error for output `{}`: arrow-tiberius returned {} diagnostic(s)",
        sanitize_text_for_display(output_name),
        diagnostics.len()
    ))]
    MssqlSchemaPlanning {
        /// Selected output name associated with the schema.
        output_name: String,
        /// Structured diagnostics returned by arrow-tiberius.
        diagnostics: arrow_tiberius::DiagnosticSet,
    },

    /// SQL Server schema planning failed before producing diagnostics.
    #[snafu(display(
        "MSSQL schema planning error for output `{}`: {}",
        sanitize_text_for_display(output_name),
        sanitize_reason_for_display(&source.to_string())
    ))]
    MssqlSchemaPlanningFailed {
        /// Selected output name associated with the schema.
        output_name: String,
        /// Underlying arrow-tiberius planning failure.
        source: arrow_tiberius::Error,
    },

    /// SQL Server DDL planning failed because a target identifier was invalid.
    #[snafu(display(
        "MSSQL DDL planning error for output `{}`: {}",
        sanitize_text_for_display(output_name),
        sanitize_reason_for_display(&source.to_string())
    ))]
    MssqlDdlTargetIdentifier {
        /// Selected output name associated with the target.
        output_name: String,
        /// Underlying arrow-tiberius identifier validation failure.
        source: arrow_tiberius::Error,
    },

    /// SQL Server DDL planning failed for a DeltaFunnel-owned lifecycle reason.
    #[snafu(display(
        "MSSQL DDL planning error for output `{}`: {}",
        sanitize_text_for_display(output_name),
        sanitize_reason_for_display(message)
    ))]
    MssqlDdlPlanning {
        /// Selected output name associated with the target.
        output_name: String,
        /// Sanitized reason for the DDL planning failure.
        message: String,
    },

    /// SQL Server lifecycle planning failed for a DeltaFunnel-owned reason.
    #[snafu(display(
        "MSSQL lifecycle planning error for output `{}`: {}",
        sanitize_text_for_display(output_name),
        sanitize_reason_for_display(message)
    ))]
    MssqlLifecyclePlanning {
        /// Selected output name associated with the target.
        output_name: String,
        /// Sanitized reason for the lifecycle planning failure.
        message: String,
    },

    /// SQL Server batch writing failed.
    #[snafu(display(
        "MSSQL write error: {}",
        sanitize_reason_for_display(&source.to_string())
    ))]
    MssqlWrite {
        /// Underlying Arrow-to-TDS or Tiberius writer failure.
        source: arrow_tiberius::Error,
    },

    /// SQL Server write execution failed during a known phase.
    #[snafu(display(
        "MSSQL write error for output `{}` during {}: {}",
        sanitize_text_for_display(context.output_name()),
        context.phase(),
        sanitize_reason_for_display(message)
    ))]
    MssqlWritePhase {
        /// Structured, redacted failure context.
        context: Box<crate::MssqlWriteFailureContext>,
        /// Sanitized reason for the write failure.
        message: String,
    },

    /// SQL Server output batch schema validation failed.
    #[snafu(display(
        "MSSQL write error for output `{}` during {}: {}",
        sanitize_text_for_display(context.output_name()),
        context.phase(),
        sanitize_reason_for_display(&source.to_string())
    ))]
    MssqlBatchSchemaValidation {
        /// Structured, redacted failure context.
        context: Box<crate::MssqlWriteFailureContext>,
        /// Underlying arrow-tiberius schema validation failure.
        source: arrow_tiberius::Error,
    },

    /// SQL Server multi-output workflow planning failed before output writes.
    #[snafu(display(
        "MSSQL workflow planning error: {}",
        sanitize_reason_for_display(message)
    ))]
    MssqlWorkflowPlanning {
        /// Sanitized reason for the workflow planning failure.
        message: String,
    },
}

/// Phase associated with lazy SQL table construction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SqlTablePhase {
    /// Caller SQL text failed local validation.
    ValidateSql,
    /// DataFusion could not produce a lazy logical table.
    PlanSql,
    /// A derived table alias could not be registered in the session catalog.
    RegisterDerivedAlias,
}

impl std::fmt::Display for SqlTablePhase {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Self::ValidateSql => "SQL validation",
            Self::PlanSql => "SQL planning",
            Self::RegisterDerivedAlias => "derived alias registration",
        })
    }
}

fn sanitize_source_name_for_display(name: &str) -> String {
    sanitize_text_for_display(name)
}

fn sanitize_reason_for_display(reason: &str) -> String {
    sanitize_text_for_display(reason)
}

#[cfg(test)]
mod tests {
    use std::error::Error;

    use super::DeltaFunnelError;

    #[test]
    fn config_error_has_sanitized_display() {
        let error = DeltaFunnelError::Config {
            message: "max_concurrent_file_reads_per_scan must be greater than zero".to_owned(),
        };

        assert_eq!(
            error.to_string(),
            "configuration error: max_concurrent_file_reads_per_scan must be greater than zero"
        );
    }

    #[test]
    fn dependency_error_has_sanitized_display() {
        let error = DeltaFunnelError::DependencyCompatibility {
            message: "delta_kernel API smoke test failed".to_owned(),
        };

        assert_eq!(
            error.to_string(),
            "dependency compatibility error: delta_kernel API smoke test failed"
        );
    }

    #[test]
    fn batch_pipeline_error_has_sanitized_display() {
        let error = DeltaFunnelError::BatchPipeline {
            phase: super::BatchPipelinePhase::Configuration,
            option: "output_batch_size",
            message: "must be greater than zero".to_owned(),
        };

        assert_eq!(
            error.to_string(),
            "batch pipeline configuration error for option `output_batch_size`: must be greater than zero"
        );
    }

    #[test]
    fn batch_pipeline_error_display_escapes_control_characters() {
        let error = DeltaFunnelError::BatchPipeline {
            phase: super::BatchPipelinePhase::HandoffSetup,
            option: "consumer_capacity",
            message: "invalid\nvalue\tprovided".to_owned(),
        };

        let display = error.to_string();

        assert!(!display.contains('\n'));
        assert!(!display.contains('\t'));
        assert!(display.contains(r"invalid\nvalue\tprovided"));
    }

    #[test]
    fn mssql_write_error_has_sanitized_display() {
        let error = DeltaFunnelError::MssqlWrite {
            source: arrow_tiberius::Error::BackendUnavailable {
                backend: arrow_tiberius::WriteBackend::DirectRawBulk,
                reason: "not available\nfor test".to_owned(),
            },
        };

        let display = error.to_string();

        assert!(!display.contains('\n'));
        assert!(display.contains(r"not available\nfor test"));
    }

    #[test]
    fn mssql_write_phase_error_has_sanitized_display_and_context() -> Result<(), DeltaFunnelError> {
        let connection = crate::MssqlConnectionConfig::new(
            "server=tcp:sql.example.com;database=warehouse;user=admin;password=secret-token",
        )?
        .with_display_label("warehouse-primary");
        let target_config =
            crate::MssqlTargetConfig::new(crate::MssqlTargetTable::new("dbo", "orders")?);
        let schema = arrow_schema::Schema::new(vec![arrow_schema::Field::new(
            "order_id",
            arrow_schema::DataType::Int64,
            false,
        )]);
        let output_plan = crate::plan_mssql_target_for_output(
            schema,
            "orders_output",
            &target_config,
            Some(&connection),
            arrow_tiberius::PlanOptions::default(),
        )?;
        let context = crate::MssqlWriteFailureContext::from_output_plan(
            &output_plan,
            crate::MssqlWritePhase::WriteBatch,
            42,
            3,
            125,
            true,
            crate::MssqlTargetCleanupStatus::NotApplicable,
        );

        let error = DeltaFunnelError::MssqlWritePhase {
            context: Box::new(context),
            message: "batch failed\nwhile writing".to_owned(),
        };

        let display = error.to_string();

        assert!(display.contains("orders_output"));
        assert!(display.contains("write batch"));
        assert!(!display.contains('\n'));
        assert!(display.contains(r"batch failed\nwhile writing"));
        assert!(!display.contains("secret-token"));
        assert!(!display.contains("server=tcp"));
        let DeltaFunnelError::MssqlWritePhase { context, .. } = error else {
            return Err(DeltaFunnelError::Config {
                message: "expected MssqlWritePhase error".to_owned(),
            });
        };
        assert_eq!(context.phase(), crate::MssqlWritePhase::WriteBatch);
        assert_eq!(context.output_name(), "orders_output");
        assert_eq!(context.stats().rows_written(), 42);
        assert!(context.partial_write_possible());
        Ok(())
    }

    #[test]
    fn mssql_batch_schema_validation_error_has_sanitized_display_and_context()
    -> Result<(), DeltaFunnelError> {
        let connection = crate::MssqlConnectionConfig::new(
            "server=tcp:sql.example.com;database=warehouse;user=admin;password=secret-token",
        )?
        .with_display_label("warehouse-primary");
        let target_config =
            crate::MssqlTargetConfig::new(crate::MssqlTargetTable::new("dbo", "orders")?);
        let schema = arrow_schema::Schema::new(vec![arrow_schema::Field::new(
            "order_id",
            arrow_schema::DataType::Int64,
            false,
        )]);
        let output_plan = crate::plan_mssql_target_for_output(
            schema,
            "orders_output",
            &target_config,
            Some(&connection),
            arrow_tiberius::PlanOptions::default(),
        )?;
        let context = crate::MssqlWriteFailureContext::from_output_plan(
            &output_plan,
            crate::MssqlWritePhase::ValidateBatchSchema,
            0,
            0,
            0,
            false,
            crate::MssqlTargetCleanupStatus::NotApplicable,
        );

        let error = DeltaFunnelError::MssqlBatchSchemaValidation {
            context: Box::new(context),
            source: arrow_tiberius::Error::BackendUnavailable {
                backend: arrow_tiberius::WriteBackend::DirectRawBulk,
                reason: "schema mismatch\nfor test".to_owned(),
            },
        };

        let display = error.to_string();

        assert!(display.contains("orders_output"));
        assert!(display.contains("validate batch schema"));
        assert!(!display.contains('\n'));
        assert!(display.contains(r"schema mismatch\nfor test"));
        assert!(!display.contains("secret-token"));
        assert!(!display.contains("server=tcp"));
        let DeltaFunnelError::MssqlBatchSchemaValidation { context, source } = error else {
            return Err(DeltaFunnelError::Config {
                message: "expected MssqlBatchSchemaValidation error".to_owned(),
            });
        };
        assert_eq!(context.phase(), crate::MssqlWritePhase::ValidateBatchSchema);
        assert_eq!(context.output_name(), "orders_output");
        assert_eq!(context.stats().rows_written(), 0);
        assert!(!context.partial_write_possible());
        assert!(matches!(
            source,
            arrow_tiberius::Error::BackendUnavailable { .. }
        ));
        Ok(())
    }

    #[test]
    fn invalid_source_name_error_has_sanitized_display() {
        let error = DeltaFunnelError::InvalidSourceName {
            name: "orders.latest".to_owned(),
            reason: "source names may contain only ASCII letters, digits, and underscores",
        };

        assert_eq!(
            error.to_string(),
            "invalid Delta source name `orders.latest`: source names may contain only ASCII letters, digits, and underscores"
        );
    }

    #[test]
    fn invalid_source_name_display_escapes_control_characters() {
        let error = DeltaFunnelError::InvalidSourceName {
            name: "orders\nlatest\tname".to_owned(),
            reason: "source names may contain only ASCII letters, digits, and underscores",
        };

        let display = error.to_string();

        assert!(!display.contains('\n'));
        assert!(!display.contains('\t'));
        assert!(display.contains(r"orders\nlatest\tname"));
    }

    #[test]
    fn duplicate_source_name_error_has_sanitized_display() {
        let error = DeltaFunnelError::DuplicateSourceName {
            name: "Orders".to_owned(),
        };

        assert_eq!(error.to_string(), "duplicate Delta source name `Orders`");
    }

    #[test]
    fn invalid_source_uri_error_has_sanitized_display() {
        let error = DeltaFunnelError::InvalidSourceUri {
            reason: "table location could not be parsed or normalized",
        };

        assert_eq!(
            error.to_string(),
            "invalid Delta source URI: table location could not be parsed or normalized"
        );
    }

    #[test]
    fn source_engine_error_has_sanitized_display() {
        let error = DeltaFunnelError::DeltaSourceEngine {
            reason: "object store engine could not be constructed",
        };

        assert_eq!(
            error.to_string(),
            "Delta source engine error: object store engine could not be constructed"
        );
    }

    #[test]
    fn snapshot_load_error_has_sanitized_display() {
        let error = DeltaFunnelError::DeltaSnapshotLoad {
            reason: "snapshot could not be loaded".to_owned(),
        };

        assert_eq!(
            error.to_string(),
            "Delta snapshot load error: snapshot could not be loaded"
        );
    }

    #[test]
    fn protocol_compatibility_error_has_sanitized_display() {
        let error = DeltaFunnelError::DeltaProtocolCompatibility {
            source_name: "orders\nlatest".to_owned(),
            table_uri: "s3://user:password@example.com/table?token=secret".to_owned(),
            snapshot_version: 7,
            reason: "unsupported Delta reader feature `deletionVectors`".to_owned(),
        };

        let display = error.to_string();

        assert!(display.contains(r"orders\nlatest"));
        assert!(display.contains("snapshot version 7"));
        assert!(display.contains("s3://example.com/table"));
        assert!(display.contains("deletionVectors"));
        assert!(!display.contains('\n'));
        assert!(!display.contains("user"));
        assert!(!display.contains("password"));
        assert!(!display.contains("token"));
        assert!(!display.contains("secret"));
    }

    #[test]
    fn source_schema_error_has_sanitized_display() {
        let error = DeltaFunnelError::DeltaSourceSchema {
            source_name: "orders\nlatest".to_owned(),
            table_uri: "s3://user:password@example.com/table?token=secret".to_owned(),
            reason: "field\nname could not be converted".to_owned(),
        };

        let display = error.to_string();

        assert!(display.contains(r"orders\nlatest"));
        assert!(display.contains("s3://example.com/table"));
        assert!(display.contains(r"field\nname"));
        assert!(!display.contains('\n'));
        assert!(!display.contains("user"));
        assert!(!display.contains("password"));
        assert!(!display.contains("token"));
        assert!(!display.contains("secret"));
    }

    #[test]
    fn datafusion_registration_error_has_sanitized_display() {
        let error = DeltaFunnelError::DataFusionRegistration {
            source_name: "orders\nlatest".to_owned(),
            table_uri: "s3://user:password@example.com/table?token=secret".to_owned(),
            reason: "table\nalready exists".to_owned(),
        };

        let display = error.to_string();

        assert!(display.contains(r"orders\nlatest"));
        assert!(display.contains("s3://example.com/table"));
        assert!(display.contains(r"table\nalready exists"));
        assert!(!display.contains('\n'));
        assert!(!display.contains("user"));
        assert!(!display.contains("password"));
        assert!(!display.contains("token"));
        assert!(!display.contains("secret"));
    }

    #[test]
    fn scan_metadata_expansion_error_has_sanitized_display()
    -> Result<(), Box<dyn std::error::Error>> {
        let error = DeltaFunnelError::DeltaScanMetadataExpansion {
            source_name: "orders\nlatest".to_owned(),
            table_uri: "s3://user:password@example.com/table?token=secret".to_owned(),
            snapshot_version: 7,
            source: Box::new(delta_kernel::Error::generic(
                "scan\nmetadata expansion failed",
            )),
        };

        let display = error.to_string();

        assert!(display.contains(r"orders\nlatest"));
        assert!(display.contains("snapshot version 7"));
        assert!(display.contains("s3://example.com/table"));
        assert!(display.contains(r"scan\nmetadata expansion failed"));
        assert!(!display.contains('\n'));
        assert!(!display.contains("user"));
        assert!(!display.contains("password"));
        assert!(!display.contains("token"));
        assert!(!display.contains("secret"));

        let source = Error::source(&error)
            .ok_or("metadata expansion error must preserve its kernel source")?;
        assert!(
            source
                .to_string()
                .contains("scan\nmetadata expansion failed")
        );

        Ok(())
    }

    #[test]
    fn scan_file_task_planning_error_has_sanitized_display() {
        let error = DeltaFunnelError::DeltaScanFileTaskPlanning {
            source_name: "orders\nlatest".to_owned(),
            table_uri: "s3://user:password@example.com/table?token=secret".to_owned(),
            snapshot_version: 7,
            path: "part\n00000.parquet".to_owned(),
            reason: "kernel\nsize was negative".to_owned(),
        };

        let display = error.to_string();

        assert!(display.contains(r"orders\nlatest"));
        assert!(display.contains("snapshot version 7"));
        assert!(display.contains("s3://example.com/table"));
        assert!(display.contains(r"part\n00000.parquet"));
        assert!(display.contains(r"kernel\nsize was negative"));
        assert!(!display.contains('\n'));
        assert!(!display.contains("user"));
        assert!(!display.contains("password"));
        assert!(!display.contains("token"));
        assert!(!display.contains("secret"));
    }

    #[test]
    fn scan_file_task_partition_planning_error_has_sanitized_display() {
        let error = DeltaFunnelError::DeltaScanFileTaskPartitionPlanning {
            source_name: "orders\nlatest".to_owned(),
            table_uri: "s3://user:password@example.com/table?token=secret".to_owned(),
            snapshot_version: 7,
            reason: "target\npartitions was zero".to_owned(),
        };

        let display = error.to_string();

        assert!(display.contains(r"orders\nlatest"));
        assert!(display.contains("snapshot version 7"));
        assert!(display.contains("s3://example.com/table"));
        assert!(display.contains(r"target\npartitions was zero"));
        assert!(!display.contains('\n'));
        assert!(!display.contains("user"));
        assert!(!display.contains("password"));
        assert!(!display.contains("token"));
        assert!(!display.contains("secret"));
    }
}