delta-funnel 0.1.2

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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
//! Sequential multi-output SQL Server write orchestration.
//!
//! This module keeps the multi-output workflow layer separate from the
//! one-output sink. The MVP runs outputs sequentially, stops on the first
//! failure, and marks later outputs as skipped without invoking their lazy batch
//! stream factories.

use std::{fmt, future::Future, pin::Pin};

use arrow_schema::SchemaRef;
use async_trait::async_trait;
use datafusion::arrow::record_batch::RecordBatch;
use futures_util::Stream;
use tracing::Instrument;

use crate::{
    DeltaFunnelError, PhaseTimingReport, ReportReasonCode, RowCount, ValidationOptions,
    ValidationStatus, observability, report::PhaseTimer, support::sanitize_text_for_display,
};

use super::{
    LoadMode, MssqlBatchShapingReport, MssqlConnectionSource, MssqlConnectionSummary,
    MssqlSchemaPlanOptions, MssqlTargetSummary, MssqlTargetTable, MssqlWriteFailureContext,
    MssqlWriteOptions, MssqlWriteReport, ResolvedMssqlTarget, default_mssql_write_options,
    write_output_batches_to_mssql_with_validation_options,
};

const OUTPUT_STREAM_SETUP_PHASE: &str = "output_stream_setup";
const SQL_WRITE_PHASE: &str = "sql_write";
const VALIDATION_PHASE: &str = "validation";

/// Lazy stream produced only when a SQL Server output is attempted.
pub type MssqlOutputBatchStream =
    Pin<Box<dyn Stream<Item = Result<RecordBatch, DeltaFunnelError>> + Send>>;

/// Fallible future that constructs a direct batch stream for one attempted output.
pub type MssqlOutputBatchStreamFuture =
    Pin<Box<dyn Future<Output = Result<MssqlOutputBatchStream, DeltaFunnelError>> + Send>>;

/// Async factory that constructs a direct batch stream for one attempted output.
pub type MssqlOutputBatchStreamFactory = Box<dyn FnOnce() -> MssqlOutputBatchStreamFuture + Send>;

/// One deferred SQL Server output write job.
///
/// The job owns an already resolved SQL Server target plus a lazy batch stream
/// factory. The workflow awaits the factory only after the output becomes the
/// next attempted output. Skipped jobs keep their stream factories uncalled, so
/// skipped outputs do not start source reads, DataFusion execution, stream
/// setup, SQL connections, lifecycle preparation, writer initialization, or
/// batch polling through this API.
pub struct MssqlOutputWriteJob {
    output_schema: SchemaRef,
    resolved_target: ResolvedMssqlTarget,
    schema_options: MssqlSchemaPlanOptions,
    batches: MssqlOutputBatchStreamFactory,
    write_options: MssqlWriteOptions,
    validation_options: ValidationOptions,
    phase_timings: Vec<PhaseTimingReport>,
}

impl MssqlOutputWriteJob {
    /// Creates a deferred SQL Server output write job.
    pub fn new<F, Fut, S>(
        output_schema: SchemaRef,
        resolved_target: ResolvedMssqlTarget,
        schema_options: MssqlSchemaPlanOptions,
        batches: F,
        write_options: MssqlWriteOptions,
        validation_options: ValidationOptions,
    ) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = Result<S, DeltaFunnelError>> + Send + 'static,
        S: Stream<Item = Result<RecordBatch, DeltaFunnelError>> + Send + 'static,
    {
        Self {
            output_schema,
            resolved_target,
            schema_options,
            batches: Box::new(move || {
                Box::pin(async move {
                    let stream = batches().await?;
                    Ok(Box::pin(stream) as MssqlOutputBatchStream)
                })
            }),
            write_options,
            validation_options,
            phase_timings: Vec::new(),
        }
    }

    /// Adds phase timings that completed before this deferred write job runs.
    #[must_use]
    pub fn with_phase_timings(mut self, phase_timings: Vec<PhaseTimingReport>) -> Self {
        self.phase_timings = phase_timings;
        self
    }

    /// Creates a deferred SQL Server output write job using default write options.
    pub fn with_default_write_options<F, Fut, S>(
        output_schema: SchemaRef,
        resolved_target: ResolvedMssqlTarget,
        schema_options: MssqlSchemaPlanOptions,
        batches: F,
    ) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = Result<S, DeltaFunnelError>> + Send + 'static,
        S: Stream<Item = Result<RecordBatch, DeltaFunnelError>> + Send + 'static,
    {
        Self::new(
            output_schema,
            resolved_target,
            schema_options,
            batches,
            default_mssql_write_options(),
            ValidationOptions::default(),
        )
    }

    /// Returns the selected output name.
    #[must_use]
    pub fn output_name(&self) -> &str {
        self.resolved_target.output_name()
    }

    /// Returns a redacted target summary for reports.
    #[must_use]
    pub fn target_summary(&self) -> MssqlTargetSummary {
        self.resolved_target.summary()
    }

    /// Returns phase timings that completed before this deferred write job runs.
    #[must_use]
    pub fn phase_timings(&self) -> &[PhaseTimingReport] {
        &self.phase_timings
    }

    fn into_parts(
        self,
    ) -> (
        SchemaRef,
        ResolvedMssqlTarget,
        MssqlSchemaPlanOptions,
        MssqlOutputBatchStreamFactory,
        MssqlWriteOptions,
        ValidationOptions,
        Vec<PhaseTimingReport>,
    ) {
        (
            self.output_schema,
            self.resolved_target,
            self.schema_options,
            self.batches,
            self.write_options,
            self.validation_options,
            self.phase_timings,
        )
    }
}

/// SQL Server multi-output workflow options.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MssqlWorkflowWriteOptions {
    max_parallel_outputs: usize,
}

impl Default for MssqlWorkflowWriteOptions {
    fn default() -> Self {
        Self {
            max_parallel_outputs: 1,
        }
    }
}

impl MssqlWorkflowWriteOptions {
    /// Creates default sequential workflow options.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            max_parallel_outputs: 1,
        }
    }

    /// Sets the requested maximum number of parallel output writers.
    ///
    /// The current MVP supports only `1`. Values greater than `1` are rejected
    /// explicitly so callers do not mistake the workflow for a parallel writer
    /// pool or cross-output transaction boundary.
    #[must_use]
    pub const fn with_max_parallel_outputs(mut self, max_parallel_outputs: usize) -> Self {
        self.max_parallel_outputs = max_parallel_outputs;
        self
    }

    /// Returns the requested maximum number of parallel output writers.
    #[must_use]
    pub const fn max_parallel_outputs(&self) -> usize {
        self.max_parallel_outputs
    }

    /// Validates workflow write options before any output write side effects.
    ///
    /// # Errors
    ///
    /// Returns [`DeltaFunnelError::MssqlWorkflowPlanning`] when no output
    /// writer is allowed or when parallel output writers are requested. The
    /// current MVP is intentionally single-writer so callers cannot mistake
    /// this workflow for a parallel writer pool or cross-output transaction.
    pub fn validate(&self) -> Result<(), DeltaFunnelError> {
        match self.max_parallel_outputs() {
            1 => Ok(()),
            0 => Err(DeltaFunnelError::MssqlWorkflowPlanning {
                message: "max_parallel_outputs must be at least 1".to_owned(),
            }),
            max_parallel_outputs => Err(DeltaFunnelError::MssqlWorkflowPlanning {
                message: format!(
                    "parallel MSSQL output writers are not supported; requested {max_parallel_outputs}"
                ),
            }),
        }
    }
}

/// Structured report for a multi-output SQL Server write workflow.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MssqlWorkflowWriteReport {
    outputs: Vec<MssqlOutputWriteStatus>,
}

impl MssqlWorkflowWriteReport {
    fn new(outputs: Vec<MssqlOutputWriteStatus>) -> Self {
        Self { outputs }
    }

    /// Returns the number of selected outputs represented by this report.
    #[must_use]
    pub fn len(&self) -> usize {
        self.outputs.len()
    }

    /// Returns whether this report contains no selected outputs.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.outputs.is_empty()
    }

    /// Returns per-output statuses in caller-provided order.
    #[must_use]
    pub fn outputs(&self) -> &[MssqlOutputWriteStatus] {
        &self.outputs
    }

    /// Returns whether every selected output completed successfully.
    #[must_use]
    pub fn all_succeeded(&self) -> bool {
        self.outputs
            .iter()
            .all(MssqlOutputWriteStatus::is_succeeded)
    }

    /// Returns the number of outputs that completed successfully.
    #[must_use]
    pub fn succeeded_count(&self) -> usize {
        self.outputs
            .iter()
            .filter(|status| status.is_succeeded())
            .count()
    }

    /// Returns the number of outputs that failed.
    #[must_use]
    pub fn failed_count(&self) -> usize {
        self.outputs
            .iter()
            .filter(|status| status.is_failed())
            .count()
    }

    /// Returns the number of outputs skipped after a previous output failed.
    #[must_use]
    pub fn skipped_count(&self) -> usize {
        self.outputs
            .iter()
            .filter(|status| status.is_skipped())
            .count()
    }
}

impl fmt::Display for MssqlWorkflowWriteReport {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let succeeded = self.succeeded_count();
        let failed = self.failed_count();
        let skipped = self.skipped_count();

        write!(
            formatter,
            "MSSQL workflow write report: {succeeded} succeeded, {failed} failed, {skipped} skipped"
        )
    }
}

/// Final write status for one selected SQL Server output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MssqlOutputWriteStatus {
    /// The output completed successfully.
    Succeeded(MssqlWriteReport),
    /// The output was the first attempted output to fail.
    Failed(MssqlWriteFailureReport),
    /// The output was not attempted because an earlier output failed.
    Skipped(MssqlWriteSkippedReport),
}

impl MssqlOutputWriteStatus {
    /// Returns the selected output name for this status.
    #[must_use]
    pub fn output_name(&self) -> &str {
        match self {
            Self::Succeeded(report) => report.output_name(),
            Self::Failed(report) => report.output_name(),
            Self::Skipped(report) => report.output_name(),
        }
    }

    /// Returns the effective SQL Server target table for this status.
    #[must_use]
    pub fn target_table(&self) -> &MssqlTargetTable {
        match self {
            Self::Succeeded(report) => report.target_table(),
            Self::Failed(report) => report.target().table(),
            Self::Skipped(report) => report.target().table(),
        }
    }

    /// Returns the requested lifecycle mode for this output.
    #[must_use]
    pub fn load_mode(&self) -> LoadMode {
        match self {
            Self::Succeeded(report) => report.load_mode(),
            Self::Failed(report) => report.target().load_mode(),
            Self::Skipped(report) => report.target().load_mode(),
        }
    }

    /// Returns where the effective connection came from.
    #[must_use]
    pub fn connection_source(&self) -> MssqlConnectionSource {
        match self {
            Self::Succeeded(report) => report.connection_source(),
            Self::Failed(report) => report.target().connection_source(),
            Self::Skipped(report) => report.target().connection_source(),
        }
    }

    /// Returns the redacted effective connection summary.
    #[must_use]
    pub fn connection(&self) -> &MssqlConnectionSummary {
        match self {
            Self::Succeeded(report) => report.connection(),
            Self::Failed(report) => report.target().connection(),
            Self::Skipped(report) => report.target().connection(),
        }
    }

    /// Returns query output row evidence for this output.
    #[must_use]
    pub fn output_row_count(&self) -> RowCount {
        match self {
            Self::Succeeded(report) => report.output_row_count(),
            Self::Failed(report) => report.output_row_count(),
            Self::Skipped(report) => report.output_row_count(),
        }
    }

    /// Returns target-side row count evidence for this output.
    #[must_use]
    pub fn target_row_count(&self) -> RowCount {
        match self {
            Self::Succeeded(report) => report.target_row_count(),
            Self::Failed(report) => report.target_row_count(),
            Self::Skipped(report) => report.target_row_count(),
        }
    }

    /// Returns target-side validation status for this output.
    #[must_use]
    pub fn validation_status(&self) -> ValidationStatus {
        match self {
            Self::Succeeded(report) => report.validation_status(),
            Self::Failed(report) => report.validation_status(),
            Self::Skipped(report) => report.validation_status(),
        }
    }

    /// Returns batch-shaping counters for this output.
    #[must_use]
    pub fn batch_shaping(&self) -> MssqlBatchShapingReport {
        match self {
            Self::Succeeded(report) => report.batch_shaping(),
            Self::Failed(report) => report.batch_shaping(),
            Self::Skipped(report) => report.batch_shaping(),
        }
    }

    /// Returns workflow phase timing reports for this output when available.
    #[must_use]
    pub fn phase_timings(&self) -> &[PhaseTimingReport] {
        match self {
            Self::Succeeded(report) => report.phase_timings(),
            Self::Failed(report) => report.phase_timings(),
            Self::Skipped(report) => report.phase_timings(),
        }
    }

    /// Returns whether this output succeeded.
    #[must_use]
    pub const fn is_succeeded(&self) -> bool {
        matches!(self, Self::Succeeded(_))
    }

    /// Returns whether this output failed.
    #[must_use]
    pub const fn is_failed(&self) -> bool {
        matches!(self, Self::Failed(_))
    }

    /// Returns whether this output was skipped before any work was attempted.
    #[must_use]
    pub const fn is_skipped(&self) -> bool {
        matches!(self, Self::Skipped(_))
    }
}

/// Structured report for the first failed SQL Server output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MssqlWriteFailureReport {
    target: MssqlTargetSummary,
    error: String,
    context: Option<Box<MssqlWriteFailureContext>>,
    output_row_count: RowCount,
    target_row_count: RowCount,
    validation_status: ValidationStatus,
    batch_shaping: MssqlBatchShapingReport,
    phase_timings: Vec<PhaseTimingReport>,
}

impl MssqlWriteFailureReport {
    fn from_error(
        target: MssqlTargetSummary,
        error: DeltaFunnelError,
        phase_timings: Vec<PhaseTimingReport>,
    ) -> Self {
        let context = failure_context(&error).cloned().map(Box::new);
        let phase_timings = merged_failure_phase_timings(phase_timings, context.as_deref());
        let output_row_count = context.as_deref().map_or(
            RowCount::unavailable(),
            MssqlWriteFailureContext::output_row_count,
        );
        let target_row_count = context.as_deref().map_or(
            RowCount::unavailable(),
            MssqlWriteFailureContext::target_row_count,
        );
        let validation_status = context.as_deref().map_or(
            ValidationStatus::skipped(ReportReasonCode::FailureBeforeValidation),
            MssqlWriteFailureContext::validation_status,
        );
        let batch_shaping = context.as_deref().map_or_else(
            || MssqlBatchShapingReport::not_started(ReportReasonCode::NotExecuted),
            MssqlWriteFailureContext::batch_shaping,
        );
        Self {
            target,
            error: sanitize_text_for_display(&error.to_string()),
            context,
            output_row_count,
            target_row_count,
            validation_status,
            batch_shaping,
            phase_timings,
        }
    }

    /// Returns the redacted target summary for the failed output.
    #[must_use]
    pub const fn target(&self) -> &MssqlTargetSummary {
        &self.target
    }

    /// Returns the selected output name.
    #[must_use]
    pub fn output_name(&self) -> &str {
        self.target.output_name()
    }

    /// Returns the sanitized error message for the failed output.
    #[must_use]
    pub fn error(&self) -> &str {
        &self.error
    }

    /// Returns phase-aware write failure context when the one-output sink
    /// provided it.
    #[must_use]
    pub fn context(&self) -> Option<&MssqlWriteFailureContext> {
        self.context.as_deref()
    }

    /// Returns query output row evidence known at failure time.
    #[must_use]
    pub const fn output_row_count(&self) -> RowCount {
        self.output_row_count
    }

    /// Returns target-side row count evidence known at failure time.
    #[must_use]
    pub const fn target_row_count(&self) -> RowCount {
        self.target_row_count
    }

    /// Returns target-side validation status known at failure time.
    #[must_use]
    pub const fn validation_status(&self) -> ValidationStatus {
        self.validation_status
    }

    /// Returns batch-shaping counters known at failure time.
    #[must_use]
    pub const fn batch_shaping(&self) -> MssqlBatchShapingReport {
        self.batch_shaping
    }

    /// Returns workflow phase timing reports for this failed output.
    #[must_use]
    pub fn phase_timings(&self) -> &[PhaseTimingReport] {
        &self.phase_timings
    }
}

fn merged_failure_phase_timings(
    mut phase_timings: Vec<PhaseTimingReport>,
    context: Option<&MssqlWriteFailureContext>,
) -> Vec<PhaseTimingReport> {
    let Some(context) = context else {
        return phase_timings;
    };

    for timing in context.phase_timings() {
        if let Some(existing) = phase_timings
            .iter_mut()
            .find(|existing| existing.phase_name() == timing.phase_name())
        {
            *existing = timing.clone();
        } else {
            phase_timings.push(timing.clone());
        }
    }

    phase_timings
}

/// Structured report for a skipped SQL Server output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MssqlWriteSkippedReport {
    target: MssqlTargetSummary,
    reason: MssqlWriteSkippedReason,
    output_row_count: RowCount,
    target_row_count: RowCount,
    validation_status: ValidationStatus,
    batch_shaping: MssqlBatchShapingReport,
    phase_timings: Vec<PhaseTimingReport>,
}

impl MssqlWriteSkippedReport {
    fn previous_output_failed(
        target: MssqlTargetSummary,
        failed_output_name: String,
        phase_timings: Vec<PhaseTimingReport>,
    ) -> Self {
        Self {
            target,
            reason: MssqlWriteSkippedReason::PreviousOutputFailed { failed_output_name },
            output_row_count: RowCount::unavailable(),
            target_row_count: RowCount::unavailable(),
            validation_status: ValidationStatus::skipped(ReportReasonCode::PriorFailure),
            batch_shaping: MssqlBatchShapingReport::skipped(ReportReasonCode::PriorFailure),
            phase_timings: skipped_after_prior_failure_phase_timings(phase_timings),
        }
    }

    /// Returns the redacted target summary for the skipped output.
    #[must_use]
    pub const fn target(&self) -> &MssqlTargetSummary {
        &self.target
    }

    /// Returns the selected output name.
    #[must_use]
    pub fn output_name(&self) -> &str {
        self.target.output_name()
    }

    /// Returns why this output was skipped before any work was attempted.
    #[must_use]
    pub const fn reason(&self) -> &MssqlWriteSkippedReason {
        &self.reason
    }

    /// Returns query output row evidence for this skipped output.
    #[must_use]
    pub const fn output_row_count(&self) -> RowCount {
        self.output_row_count
    }

    /// Returns target-side row count evidence for this skipped output.
    #[must_use]
    pub const fn target_row_count(&self) -> RowCount {
        self.target_row_count
    }

    /// Returns target-side validation status for this skipped output.
    #[must_use]
    pub const fn validation_status(&self) -> ValidationStatus {
        self.validation_status
    }

    /// Returns batch-shaping counters for this skipped output.
    #[must_use]
    pub const fn batch_shaping(&self) -> MssqlBatchShapingReport {
        self.batch_shaping
    }

    /// Returns workflow phase timing reports for this skipped output.
    #[must_use]
    pub fn phase_timings(&self) -> &[PhaseTimingReport] {
        &self.phase_timings
    }
}

/// Reason one selected SQL Server output was skipped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MssqlWriteSkippedReason {
    /// A previous output failed and the MVP stops on first failure.
    PreviousOutputFailed {
        /// Output name of the first failed output.
        failed_output_name: String,
    },
}

/// Writes multiple SQL Server outputs sequentially.
///
/// This workflow calls the public one-output sink once per attempted output,
/// in caller-provided order. It stops on the first failed output and marks all
/// later outputs as skipped without invoking their lazy batch stream factories.
/// The report is per-output and does not imply all-or-nothing transaction
/// behavior across outputs, target tables, or SQL Server connections.
pub async fn write_mssql_outputs_to_mssql(
    jobs: impl IntoIterator<Item = MssqlOutputWriteJob>,
    options: MssqlWorkflowWriteOptions,
) -> Result<MssqlWorkflowWriteReport, DeltaFunnelError> {
    write_mssql_outputs_with_writer(jobs, options, MssqlPublicOneOutputWriter).await
}

#[async_trait]
pub(crate) trait MssqlWorkflowOutputWriter: Send {
    async fn write_output(
        &mut self,
        output_schema: SchemaRef,
        resolved_target: ResolvedMssqlTarget,
        schema_options: MssqlSchemaPlanOptions,
        batches: MssqlOutputBatchStream,
        write_options: MssqlWriteOptions,
        validation_options: ValidationOptions,
    ) -> Result<MssqlWriteReport, DeltaFunnelError>;
}

struct MssqlPublicOneOutputWriter;

#[async_trait]
impl MssqlWorkflowOutputWriter for MssqlPublicOneOutputWriter {
    async fn write_output(
        &mut self,
        output_schema: SchemaRef,
        resolved_target: ResolvedMssqlTarget,
        schema_options: MssqlSchemaPlanOptions,
        batches: MssqlOutputBatchStream,
        write_options: MssqlWriteOptions,
        validation_options: ValidationOptions,
    ) -> Result<MssqlWriteReport, DeltaFunnelError> {
        write_output_batches_to_mssql_with_validation_options(
            output_schema.as_ref(),
            resolved_target,
            schema_options,
            batches,
            write_options,
            validation_options,
        )
        .await
    }
}

pub(crate) async fn write_mssql_outputs_with_writer<W>(
    jobs: impl IntoIterator<Item = MssqlOutputWriteJob>,
    options: MssqlWorkflowWriteOptions,
    mut writer: W,
) -> Result<MssqlWorkflowWriteReport, DeltaFunnelError>
where
    W: MssqlWorkflowOutputWriter,
{
    ensure_sequential_options(options)?;

    let mut statuses = Vec::new();
    let mut failed_output_name = None::<String>;

    for job in jobs {
        if let Some(failed_output_name) = failed_output_name.as_ref() {
            statuses.push(skipped_output_status_with_tracing(
                job.target_summary(),
                failed_output_name.clone(),
                job.phase_timings().to_vec(),
            ));
            continue;
        }

        let status = write_mssql_output_job_with_tracing(job, &mut writer).await;
        if let MssqlOutputWriteStatus::Failed(failure) = &status {
            failed_output_name = Some(failure.output_name().to_owned());
        }
        statuses.push(status);
    }

    Ok(MssqlWorkflowWriteReport::new(statuses))
}

fn skipped_output_status_with_tracing(
    target: MssqlTargetSummary,
    failed_output_name: String,
    planned_phase_timings: Vec<PhaseTimingReport>,
) -> MssqlOutputWriteStatus {
    let output_span =
        observability::output_span(target.output_name(), target.table(), target.load_mode());
    output_span.in_scope(|| {
        let skipped = skipped_output_status(target, failed_output_name, planned_phase_timings);
        observability::output_skipped(
            skipped.output_name(),
            skipped.target().table(),
            skipped.target().load_mode(),
            "prior_failure",
        );
        MssqlOutputWriteStatus::Skipped(skipped)
    })
}

fn skipped_output_status(
    target: MssqlTargetSummary,
    failed_output_name: String,
    planned_phase_timings: Vec<PhaseTimingReport>,
) -> MssqlWriteSkippedReport {
    MssqlWriteSkippedReport::previous_output_failed(
        target,
        failed_output_name,
        planned_phase_timings,
    )
}

async fn write_mssql_output_job_with_tracing<W>(
    job: MssqlOutputWriteJob,
    writer: &mut W,
) -> MssqlOutputWriteStatus
where
    W: MssqlWorkflowOutputWriter,
{
    let target = job.target_summary();
    let output_span =
        observability::output_span(target.output_name(), target.table(), target.load_mode());

    async move {
        observability::output_started(target.output_name(), target.table(), target.load_mode());
        let status = write_mssql_output_job(job, writer).await;
        match &status {
            MssqlOutputWriteStatus::Succeeded(report) => {
                observability::output_completed(
                    report.output_name(),
                    report.target_table(),
                    report.load_mode(),
                );
            }
            MssqlOutputWriteStatus::Failed(failure) => {
                observability::output_failed(
                    failure.output_name(),
                    failure.target().table(),
                    failure.target().load_mode(),
                    failure.error(),
                );
            }
            MssqlOutputWriteStatus::Skipped(_) => {}
        }
        status
    }
    .instrument(output_span)
    .await
}

async fn write_mssql_output_job<W>(
    job: MssqlOutputWriteJob,
    writer: &mut W,
) -> MssqlOutputWriteStatus
where
    W: MssqlWorkflowOutputWriter,
{
    let target = job.target_summary();
    let (
        output_schema,
        resolved_target,
        schema_options,
        batches,
        write_options,
        validation_options,
        planned_phase_timings,
    ) = job.into_parts();
    let stream_setup_timer = PhaseTimer::start(OUTPUT_STREAM_SETUP_PHASE);
    let (batches, stream_setup_timing) = match batches().await {
        Ok(batches) => (batches, stream_setup_timer.completed()),
        Err(error) => {
            let failure = MssqlWriteFailureReport::from_error(
                target,
                error,
                stream_setup_failure_phase_timings(
                    planned_phase_timings,
                    stream_setup_timer.failed(),
                ),
            );
            return MssqlOutputWriteStatus::Failed(failure);
        }
    };

    let write_timer = PhaseTimer::start(SQL_WRITE_PHASE);
    match writer
        .write_output(
            output_schema,
            resolved_target,
            schema_options,
            batches,
            write_options,
            validation_options,
        )
        .await
    {
        Ok(report) => {
            let report = report.with_phase_timings(output_write_phase_timings(
                planned_phase_timings,
                stream_setup_timing,
                write_timer.completed(),
            ));
            MssqlOutputWriteStatus::Succeeded(report)
        }
        Err(error) => {
            let failure = MssqlWriteFailureReport::from_error(
                target,
                error,
                output_write_failure_phase_timings(
                    planned_phase_timings,
                    stream_setup_timing,
                    write_timer.failed(),
                ),
            );
            MssqlOutputWriteStatus::Failed(failure)
        }
    }
}

fn ensure_sequential_options(options: MssqlWorkflowWriteOptions) -> Result<(), DeltaFunnelError> {
    options.validate()
}

fn failure_context(error: &DeltaFunnelError) -> Option<&MssqlWriteFailureContext> {
    match error {
        DeltaFunnelError::MssqlWritePhase { context, .. }
        | DeltaFunnelError::MssqlBatchSchemaValidation { context, .. } => Some(context.as_ref()),
        _ => None,
    }
}

fn output_write_phase_timings(
    mut phase_timings: Vec<PhaseTimingReport>,
    stream_setup_timing: PhaseTimingReport,
    write_timing: PhaseTimingReport,
) -> Vec<PhaseTimingReport> {
    phase_timings.extend([stream_setup_timing, write_timing]);
    phase_timings
}

fn output_write_failure_phase_timings(
    mut phase_timings: Vec<PhaseTimingReport>,
    stream_setup_timing: PhaseTimingReport,
    write_timing: PhaseTimingReport,
) -> Vec<PhaseTimingReport> {
    phase_timings.extend([
        stream_setup_timing,
        write_timing,
        PhaseTimingReport::not_started(VALIDATION_PHASE, ReportReasonCode::FailureBeforeValidation),
    ]);
    phase_timings
}

fn stream_setup_failure_phase_timings(
    mut phase_timings: Vec<PhaseTimingReport>,
    stream_setup_timing: PhaseTimingReport,
) -> Vec<PhaseTimingReport> {
    phase_timings.extend([
        stream_setup_timing,
        PhaseTimingReport::not_started(SQL_WRITE_PHASE, ReportReasonCode::NotExecuted),
        PhaseTimingReport::not_started(VALIDATION_PHASE, ReportReasonCode::FailureBeforeValidation),
    ]);
    phase_timings
}

fn skipped_after_prior_failure_phase_timings(
    mut phase_timings: Vec<PhaseTimingReport>,
) -> Vec<PhaseTimingReport> {
    phase_timings.extend([
        PhaseTimingReport::skipped(OUTPUT_STREAM_SETUP_PHASE, ReportReasonCode::PriorFailure),
        PhaseTimingReport::skipped(SQL_WRITE_PHASE, ReportReasonCode::PriorFailure),
        PhaseTimingReport::skipped(VALIDATION_PHASE, ReportReasonCode::PriorFailure),
    ]);
    phase_timings
}

#[cfg(test)]
mod tests {
    use std::collections::VecDeque;
    use std::sync::{Arc, Mutex, MutexGuard};
    use std::time::Duration;

    use arrow_schema::{DataType, Field, Schema};
    use async_trait::async_trait;
    use futures_util::{StreamExt, stream};

    use super::*;
    use crate::{
        LoadMode, MssqlConnectionConfig, MssqlTargetCleanupStatus, MssqlTargetConfig,
        MssqlTargetOutputPlan, MssqlTargetResolutionContext, MssqlTargetTable, MssqlWritePhase,
        PhaseStatus, PhaseTimingReport, ValidationStatus, plan_mssql_target_for_output,
        report::sql_server::MssqlWriteReportMetrics,
    };

    const PLANNED_PHASE: &str = "planned_phase";

    #[derive(Default)]
    struct FakeWorkflowWriter {
        outcomes: VecDeque<Result<MssqlWriteReport, DeltaFunnelError>>,
        attempted_outputs: Arc<Mutex<Vec<String>>>,
    }

    #[derive(Default)]
    struct StreamPollingWorkflowWriter {
        attempted_outputs: Arc<Mutex<Vec<String>>>,
    }

    impl FakeWorkflowWriter {
        fn new(outcomes: Vec<Result<MssqlWriteReport, DeltaFunnelError>>) -> Self {
            Self {
                outcomes: outcomes.into(),
                attempted_outputs: Arc::new(Mutex::new(Vec::new())),
            }
        }

        fn attempted_outputs(&self) -> Arc<Mutex<Vec<String>>> {
            Arc::clone(&self.attempted_outputs)
        }
    }

    impl StreamPollingWorkflowWriter {
        fn attempted_outputs(&self) -> Arc<Mutex<Vec<String>>> {
            Arc::clone(&self.attempted_outputs)
        }
    }

    #[async_trait]
    impl MssqlWorkflowOutputWriter for FakeWorkflowWriter {
        async fn write_output(
            &mut self,
            _output_schema: SchemaRef,
            resolved_target: ResolvedMssqlTarget,
            _schema_options: MssqlSchemaPlanOptions,
            _batches: MssqlOutputBatchStream,
            _write_options: MssqlWriteOptions,
            _validation_options: ValidationOptions,
        ) -> Result<MssqlWriteReport, DeltaFunnelError> {
            self.attempted_outputs
                .lock()
                .map_err(|_| test_error("attempted output lock poisoned"))?
                .push(resolved_target.output_name().to_owned());

            self.outcomes
                .pop_front()
                .ok_or_else(|| test_error("missing fake writer outcome"))?
        }
    }

    #[async_trait]
    impl MssqlWorkflowOutputWriter for StreamPollingWorkflowWriter {
        async fn write_output(
            &mut self,
            _output_schema: SchemaRef,
            resolved_target: ResolvedMssqlTarget,
            _schema_options: MssqlSchemaPlanOptions,
            mut batches: MssqlOutputBatchStream,
            _write_options: MssqlWriteOptions,
            _validation_options: ValidationOptions,
        ) -> Result<MssqlWriteReport, DeltaFunnelError> {
            self.attempted_outputs
                .lock()
                .map_err(|_| test_error("attempted output lock poisoned"))?
                .push(resolved_target.output_name().to_owned());

            match batches.next().await {
                Some(Ok(_batch)) => Err(test_error("expected stream polling error")),
                Some(Err(error)) => Err(error),
                None => Err(test_error("expected at least one stream item")),
            }
        }
    }

    #[tokio::test]
    async fn empty_workflow_report_has_zero_counts() -> Result<(), DeltaFunnelError> {
        let writer = FakeWorkflowWriter::default();

        let report = write_mssql_outputs_with_writer(
            Vec::new(),
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        assert!(report.is_empty());
        assert_eq!(report.len(), 0);
        assert_eq!(report.outputs(), []);
        assert!(report.all_succeeded());
        assert_eq!(report.succeeded_count(), 0);
        assert_eq!(report.failed_count(), 0);
        assert_eq!(report.skipped_count(), 0);
        assert_eq!(
            report.to_string(),
            "MSSQL workflow write report: 0 succeeded, 0 failed, 0 skipped"
        );

        Ok(())
    }

    #[tokio::test]
    async fn two_successful_outputs_produce_two_success_statuses() -> Result<(), DeltaFunnelError> {
        let first = output_plan("first", LoadMode::AppendExisting)?;
        let second = output_plan("second", LoadMode::AppendExisting)?;
        let first_report =
            write_report(&first, 2, 1, false, MssqlTargetCleanupStatus::NotApplicable);
        let second_report = write_report(
            &second,
            3,
            2,
            false,
            MssqlTargetCleanupStatus::NotApplicable,
        );
        let writer = FakeWorkflowWriter::new(vec![Ok(first_report), Ok(second_report)]);
        let attempted = writer.attempted_outputs();

        let report = write_mssql_outputs_with_writer(
            vec![job(first)?, job(second)?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        assert_eq!(report.outputs().len(), 2);
        assert!(report.all_succeeded());
        assert_status_output(report.outputs(), 0, "first")?;
        assert_status_output(report.outputs(), 1, "second")?;
        assert_eq!(report.outputs()[0].output_row_count(), RowCount::exact(2));
        assert_batch_shaping(
            report.outputs()[0].batch_shaping(),
            PhaseStatus::completed(),
            1,
            2,
            1,
            2,
        );
        assert_eq!(report.outputs()[1].output_row_count(), RowCount::exact(3));
        assert_batch_shaping(
            report.outputs()[1].batch_shaping(),
            PhaseStatus::completed(),
            2,
            3,
            2,
            3,
        );
        assert_phase_timing(
            &report.outputs()[0],
            PLANNED_PHASE,
            PhaseStatus::completed(),
        )?;
        assert_phase_timing(
            &report.outputs()[0],
            OUTPUT_STREAM_SETUP_PHASE,
            PhaseStatus::completed(),
        )?;
        assert_phase_timing(
            &report.outputs()[0],
            SQL_WRITE_PHASE,
            PhaseStatus::completed(),
        )?;
        assert_eq!(
            locked(&attempted)?.as_slice(),
            ["first".to_owned(), "second".to_owned()]
        );

        Ok(())
    }

    #[tokio::test]
    async fn first_success_remains_successful_when_second_output_fails()
    -> Result<(), DeltaFunnelError> {
        let first = output_plan("first", LoadMode::AppendExisting)?;
        let second = output_plan("second", LoadMode::AppendExisting)?;
        let first_report =
            write_report(&first, 2, 1, false, MssqlTargetCleanupStatus::NotApplicable);
        let failure_context = MssqlWriteFailureContext::from_output_plan(
            &second,
            MssqlWritePhase::WriteBatch,
            1,
            1,
            0,
            true,
            MssqlTargetCleanupStatus::NotApplicable,
        )
        .with_phase_timings(vec![
            PhaseTimingReport::completed("prepare_target_lifecycle", Duration::from_micros(10)),
            PhaseTimingReport::failed("write_batch", Duration::from_micros(20)),
            PhaseTimingReport::not_started(
                VALIDATION_PHASE,
                ReportReasonCode::FailureBeforeValidation,
            ),
        ]);
        let failure = phase_error_with_context(failure_context, "write failed");
        let writer = FakeWorkflowWriter::new(vec![Ok(first_report), Err(failure)]);

        let report = write_mssql_outputs_with_writer(
            vec![job(first)?, job(second)?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        let [first_status, second_status] = report.outputs() else {
            return Err(test_error("expected two output statuses"));
        };
        assert!(matches!(first_status, MssqlOutputWriteStatus::Succeeded(_)));
        let MssqlOutputWriteStatus::Failed(failure) = second_status else {
            return Err(test_error("expected second output to fail"));
        };
        assert_eq!(failure.output_name(), "second");
        let context = failure
            .context()
            .ok_or_else(|| test_error("expected write failure context"))?;
        assert_eq!(context.phase(), MssqlWritePhase::WriteBatch);
        assert!(context.partial_write_possible());
        assert_eq!(context.stats().rows_written(), 1);
        assert_eq!(context.stats().batches_written(), 1);
        assert_phase_timing(
            second_status,
            OUTPUT_STREAM_SETUP_PHASE,
            PhaseStatus::completed(),
        )?;
        assert_phase_timing(second_status, SQL_WRITE_PHASE, PhaseStatus::failed())?;
        assert_phase_timing(second_status, "write_batch", PhaseStatus::failed())?;
        assert_phase_timing(
            second_status,
            VALIDATION_PHASE,
            PhaseStatus::not_started(ReportReasonCode::FailureBeforeValidation),
        )?;
        assert_eq!(
            second_status
                .phase_timings()
                .iter()
                .filter(|timing| timing.phase_name() == VALIDATION_PHASE)
                .count(),
            1
        );

        Ok(())
    }

    #[tokio::test]
    async fn batch_schema_validation_failure_preserves_failure_context()
    -> Result<(), DeltaFunnelError> {
        let output = output_plan("schema_failure", LoadMode::AppendExisting)?;
        let context = MssqlWriteFailureContext::from_output_plan(
            &output,
            MssqlWritePhase::ValidateBatchSchema,
            0,
            0,
            0,
            false,
            MssqlTargetCleanupStatus::NotApplicable,
        );
        let failure = DeltaFunnelError::MssqlBatchSchemaValidation {
            context: Box::new(context),
            source: arrow_tiberius::Error::BackendUnavailable {
                backend: arrow_tiberius::WriteBackend::DirectRawBulk,
                reason: "schema mismatch".to_owned(),
            },
        };
        let writer = FakeWorkflowWriter::new(vec![Err(failure)]);

        let report = write_mssql_outputs_with_writer(
            vec![job(output)?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        let [MssqlOutputWriteStatus::Failed(failure)] = report.outputs() else {
            return Err(test_error("expected failed output status"));
        };
        let context = failure
            .context()
            .ok_or_else(|| test_error("expected schema validation context"))?;
        assert_eq!(failure.output_name(), "schema_failure");
        assert_eq!(context.phase(), MssqlWritePhase::ValidateBatchSchema);
        assert!(!context.partial_write_possible());
        assert_eq!(context.stats().rows_written(), 0);

        Ok(())
    }

    #[tokio::test]
    async fn first_failure_marks_later_outputs_skipped_without_attempting_them()
    -> Result<(), DeltaFunnelError> {
        let first = output_plan("first", LoadMode::AppendExisting)?;
        let second = output_plan("second", LoadMode::AppendExisting)?;
        let third = output_plan("third", LoadMode::AppendExisting)?;
        let failure = phase_error(
            &first,
            MssqlWritePhase::Connect,
            0,
            0,
            false,
            MssqlTargetCleanupStatus::NotApplicable,
            "connect failed",
        );
        let writer = FakeWorkflowWriter::new(vec![Err(failure)]);
        let attempted = writer.attempted_outputs();

        let report = write_mssql_outputs_with_writer(
            vec![job(first)?, job(second)?, job(third)?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        assert_eq!(locked(&attempted)?.as_slice(), ["first".to_owned()]);
        let [failed, skipped_second, skipped_third] = report.outputs() else {
            return Err(test_error("expected three output statuses"));
        };
        assert_eq!(report.len(), 3);
        assert_eq!(report.succeeded_count(), 0);
        assert_eq!(report.failed_count(), 1);
        assert_eq!(report.skipped_count(), 2);
        assert!(matches!(failed, MssqlOutputWriteStatus::Failed(_)));
        assert_eq!(failed.output_row_count(), RowCount::partial(0));
        assert_batch_shaping(failed.batch_shaping(), PhaseStatus::failed(), 0, 0, 0, 0);
        assert_phase_timing(failed, OUTPUT_STREAM_SETUP_PHASE, PhaseStatus::completed())?;
        assert_phase_timing(failed, SQL_WRITE_PHASE, PhaseStatus::failed())?;
        assert_skipped_after(skipped_second, "second", "first")?;
        assert_skipped_after(skipped_third, "third", "first")?;

        Ok(())
    }

    #[tokio::test]
    async fn output_status_accessors_cover_success_failure_and_skipped_variants()
    -> Result<(), DeltaFunnelError> {
        let first = output_plan("first", LoadMode::AppendExisting)?;
        let second = output_plan("second", LoadMode::CreateAndLoad)?;
        let third = output_plan("third", LoadMode::AppendExisting)?;
        let first_report =
            write_report(&first, 2, 1, false, MssqlTargetCleanupStatus::NotApplicable);
        let failure = phase_error(
            &second,
            MssqlWritePhase::InitializeWriter,
            0,
            0,
            false,
            MssqlTargetCleanupStatus::NotAttempted,
            "writer init failed",
        );
        let writer = FakeWorkflowWriter::new(vec![Ok(first_report), Err(failure)]);

        let report = write_mssql_outputs_with_writer(
            vec![job(first)?, job(second)?, job(third)?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        let [success, failed, skipped] = report.outputs() else {
            return Err(test_error("expected three output statuses"));
        };
        assert!(success.is_succeeded());
        assert_eq!(success.output_name(), "first");
        assert_eq!(success.target_table().table(), "first_orders");
        assert_eq!(success.load_mode(), LoadMode::AppendExisting);
        assert_eq!(
            success.connection().display_label(),
            Some("test connection")
        );
        assert_eq!(success.target_row_count(), RowCount::unavailable());
        assert_eq!(
            success.validation_status(),
            ValidationStatus::skipped(ReportReasonCode::NotExecuted)
        );

        assert!(failed.is_failed());
        assert_eq!(failed.output_name(), "second");
        assert_eq!(failed.target_table().table(), "second_orders");
        assert_eq!(failed.load_mode(), LoadMode::CreateAndLoad);
        assert_eq!(failed.connection().display_label(), Some("test connection"));
        assert_eq!(failed.target_row_count(), RowCount::unavailable());
        assert_eq!(
            failed.validation_status(),
            ValidationStatus::skipped(ReportReasonCode::NotExecuted)
        );

        assert!(skipped.is_skipped());
        assert_eq!(skipped.output_name(), "third");
        assert_eq!(skipped.target_table().table(), "third_orders");
        assert_eq!(skipped.load_mode(), LoadMode::AppendExisting);
        assert_eq!(
            skipped.connection().display_label(),
            Some("test connection")
        );
        assert_eq!(skipped.target_row_count(), RowCount::unavailable());
        assert_eq!(
            skipped.validation_status(),
            ValidationStatus::skipped(ReportReasonCode::PriorFailure)
        );

        Ok(())
    }

    #[tokio::test]
    async fn failed_output_status_exposes_validation_evidence() -> Result<(), DeltaFunnelError> {
        let output = output_plan("validation_failed", LoadMode::CreateAndLoad)?;
        let metrics = MssqlWriteReportMetrics::new(
            RowCount::exact(3),
            MssqlBatchShapingReport::completed(1, 3, 1, 3),
            3,
            1,
            0,
            false,
            MssqlTargetCleanupStatus::Succeeded,
        )
        .with_target_validation(RowCount::exact(4), ValidationStatus::failed())
        .with_phase_timings(vec![PhaseTimingReport::failed(
            VALIDATION_PHASE,
            Duration::from_micros(5),
        )]);
        let failure = phase_error_with_context(
            MssqlWriteFailureContext::from_output_plan_with_metrics(
                &output,
                MssqlWritePhase::Validation,
                metrics,
            ),
            "target row count did not match exact output rows",
        );
        let writer = FakeWorkflowWriter::new(vec![Err(failure)]);

        let report = write_mssql_outputs_with_writer(
            vec![job(output)?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        let [status] = report.outputs() else {
            return Err(test_error("expected one output status"));
        };
        let MssqlOutputWriteStatus::Failed(failure) = status else {
            return Err(test_error("expected failed output status"));
        };
        assert_eq!(failure.target_row_count(), RowCount::exact(4));
        assert_eq!(failure.validation_status(), ValidationStatus::failed());
        assert_eq!(status.target_row_count(), RowCount::exact(4));
        assert_eq!(status.validation_status(), ValidationStatus::failed());
        assert_phase_timing(status, VALIDATION_PHASE, PhaseStatus::failed())?;
        Ok(())
    }

    #[tokio::test]
    async fn skipped_output_stream_factories_are_not_invoked() -> Result<(), DeltaFunnelError> {
        let first = output_plan("first", LoadMode::AppendExisting)?;
        let second = output_plan("second", LoadMode::AppendExisting)?;
        let factory_calls = Arc::new(Mutex::new(Vec::new()));
        let failure = phase_error(
            &first,
            MssqlWritePhase::Connect,
            0,
            0,
            false,
            MssqlTargetCleanupStatus::NotApplicable,
            "connect failed",
        );
        let writer = FakeWorkflowWriter::new(vec![Err(failure)]);

        let report = write_mssql_outputs_with_writer(
            vec![
                counted_job(first, Arc::clone(&factory_calls))?,
                counted_job(second, Arc::clone(&factory_calls))?,
            ],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        assert_eq!(locked(&factory_calls)?.as_slice(), ["first".to_owned()]);
        assert_eq!(report.outputs().len(), 2);
        assert!(report.outputs()[1].is_skipped());

        Ok(())
    }

    #[tokio::test]
    async fn skipped_outputs_do_not_reach_one_output_writer() -> Result<(), DeltaFunnelError> {
        let first = output_plan("first", LoadMode::AppendExisting)?;
        let second = output_plan("second", LoadMode::AppendExisting)?;
        let failure = phase_error(
            &first,
            MssqlWritePhase::PrepareTargetLifecycle,
            0,
            0,
            false,
            MssqlTargetCleanupStatus::NotApplicable,
            "prepare failed",
        );
        let writer = FakeWorkflowWriter::new(vec![Err(failure)]);
        let attempted = writer.attempted_outputs();

        let report = write_mssql_outputs_with_writer(
            vec![job(first)?, job(second)?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        assert_eq!(locked(&attempted)?.as_slice(), ["first".to_owned()]);
        assert!(report.outputs()[1].is_skipped());

        Ok(())
    }

    #[tokio::test]
    async fn stream_factory_setup_failure_fails_output_before_writer_and_skips_later_factories()
    -> Result<(), DeltaFunnelError> {
        let first = output_plan("first", LoadMode::AppendExisting)?;
        let second = output_plan("second", LoadMode::AppendExisting)?;
        let third = output_plan("third", LoadMode::AppendExisting)?;
        let first_report =
            write_report(&first, 1, 1, false, MssqlTargetCleanupStatus::NotApplicable);
        let factory_calls = Arc::new(Mutex::new(Vec::new()));
        let writer = FakeWorkflowWriter::new(vec![Ok(first_report)]);
        let attempted = writer.attempted_outputs();

        let report = write_mssql_outputs_with_writer(
            vec![
                counted_job(first, Arc::clone(&factory_calls))?,
                failing_factory_job(
                    second,
                    Arc::clone(&factory_calls),
                    "stream setup failed before SQL writer",
                )?,
                counted_job(third, Arc::clone(&factory_calls))?,
            ],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        assert_eq!(
            locked(&factory_calls)?.as_slice(),
            ["first".to_owned(), "second".to_owned()]
        );
        assert_eq!(locked(&attempted)?.as_slice(), ["first".to_owned()]);
        let [first_status, second_status, third_status] = report.outputs() else {
            return Err(test_error("expected three output statuses"));
        };
        assert!(first_status.is_succeeded());
        let MssqlOutputWriteStatus::Failed(failure) = second_status else {
            return Err(test_error("expected second output to fail"));
        };
        assert_eq!(failure.output_name(), "second");
        assert!(failure.context().is_none());
        assert_eq!(failure.output_row_count(), RowCount::unavailable());
        assert_batch_shaping(
            failure.batch_shaping(),
            PhaseStatus::not_started(ReportReasonCode::NotExecuted),
            0,
            0,
            0,
            0,
        );
        assert_phase_timing(second_status, PLANNED_PHASE, PhaseStatus::completed())?;
        assert_phase_timing(
            second_status,
            OUTPUT_STREAM_SETUP_PHASE,
            PhaseStatus::failed(),
        )?;
        assert_phase_timing(
            second_status,
            SQL_WRITE_PHASE,
            PhaseStatus::not_started(ReportReasonCode::NotExecuted),
        )?;
        assert_phase_timing(
            second_status,
            VALIDATION_PHASE,
            PhaseStatus::not_started(ReportReasonCode::FailureBeforeValidation),
        )?;
        assert!(
            failure
                .error()
                .contains("stream setup failed before SQL writer")
        );
        assert_skipped_after(third_status, "third", "second")?;

        Ok(())
    }

    #[tokio::test]
    async fn stream_polling_failure_after_setup_reaches_writer_boundary()
    -> Result<(), DeltaFunnelError> {
        let output = output_plan("poll_failure", LoadMode::AppendExisting)?;
        let factory_calls = Arc::new(Mutex::new(Vec::new()));
        let writer = StreamPollingWorkflowWriter::default();
        let attempted = writer.attempted_outputs();

        let report = write_mssql_outputs_with_writer(
            vec![polling_error_job(output, Arc::clone(&factory_calls))?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        assert_eq!(
            locked(&factory_calls)?.as_slice(),
            ["poll_failure".to_owned()]
        );
        assert_eq!(locked(&attempted)?.as_slice(), ["poll_failure".to_owned()]);
        let [MssqlOutputWriteStatus::Failed(failure)] = report.outputs() else {
            return Err(test_error("expected failed output status"));
        };
        assert_eq!(failure.output_name(), "poll_failure");
        assert!(failure.error().contains("stream failed during polling"));
        assert!(failure.context().is_none());
        assert_eq!(failure.output_row_count(), RowCount::unavailable());
        assert_batch_shaping(
            failure.batch_shaping(),
            PhaseStatus::not_started(ReportReasonCode::NotExecuted),
            0,
            0,
            0,
            0,
        );
        assert_phase_timing(
            &report.outputs()[0],
            OUTPUT_STREAM_SETUP_PHASE,
            PhaseStatus::completed(),
        )?;
        assert_phase_timing(&report.outputs()[0], SQL_WRITE_PHASE, PhaseStatus::failed())?;

        Ok(())
    }

    #[tokio::test]
    async fn failed_create_and_load_cleanup_status_is_preserved() -> Result<(), DeltaFunnelError> {
        let output = output_plan("created", LoadMode::CreateAndLoad)?;
        let failure = phase_error(
            &output,
            MssqlWritePhase::Finalize,
            2,
            1,
            false,
            MssqlTargetCleanupStatus::Succeeded,
            "finalize failed",
        );
        let writer = FakeWorkflowWriter::new(vec![Err(failure)]);

        let report = write_mssql_outputs_with_writer(
            vec![job(output)?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        let [MssqlOutputWriteStatus::Failed(failure)] = report.outputs() else {
            return Err(test_error("expected failed output status"));
        };
        let context = failure
            .context()
            .ok_or_else(|| test_error("expected write failure context"))?;
        assert_eq!(context.cleanup(), MssqlTargetCleanupStatus::Succeeded);
        assert_eq!(context.stats().rows_written(), 2);
        assert_eq!(context.stats().batches_written(), 1);

        Ok(())
    }

    #[tokio::test]
    async fn parallel_writer_configuration_is_rejected() -> Result<(), DeltaFunnelError> {
        let output = output_plan("first", LoadMode::AppendExisting)?;
        let writer = FakeWorkflowWriter::new(vec![Ok(write_report(
            &output,
            1,
            1,
            false,
            MssqlTargetCleanupStatus::NotApplicable,
        ))]);

        let error = write_mssql_outputs_with_writer(
            vec![job(output)?],
            MssqlWorkflowWriteOptions::new().with_max_parallel_outputs(2),
            writer,
        )
        .await;
        let Err(error) = error else {
            return Err(test_error("parallel writer config should be rejected"));
        };

        assert!(error.to_string().contains("parallel MSSQL output writers"));

        Ok(())
    }

    #[tokio::test]
    async fn zero_parallel_writer_configuration_is_rejected_before_attempting_outputs()
    -> Result<(), DeltaFunnelError> {
        let output = output_plan("first", LoadMode::AppendExisting)?;
        let writer = FakeWorkflowWriter::new(vec![Ok(write_report(
            &output,
            1,
            1,
            false,
            MssqlTargetCleanupStatus::NotApplicable,
        ))]);
        let attempted = writer.attempted_outputs();

        let error = write_mssql_outputs_with_writer(
            vec![job(output)?],
            MssqlWorkflowWriteOptions::new().with_max_parallel_outputs(0),
            writer,
        )
        .await;
        let Err(error) = error else {
            return Err(test_error("zero writer config should be rejected"));
        };

        assert!(error.to_string().contains("must be at least 1"));
        assert!(locked(&attempted)?.is_empty());

        Ok(())
    }

    #[tokio::test]
    async fn workflow_report_debug_and_display_redact_connection_credentials()
    -> Result<(), DeltaFunnelError> {
        let output = output_plan("first", LoadMode::AppendExisting)?;
        let report = write_report(
            &output,
            1,
            1,
            false,
            MssqlTargetCleanupStatus::NotApplicable,
        );
        let writer = FakeWorkflowWriter::new(vec![Ok(report)]);

        let report = write_mssql_outputs_with_writer(
            vec![job(output)?],
            MssqlWorkflowWriteOptions::default(),
            writer,
        )
        .await?;

        let debug = format!("{report:?}");
        let display = report.to_string();
        assert!(!debug.contains("secret"));
        assert!(!display.contains("secret"));
        assert!(display.contains("1 succeeded"));
        assert!(!display.to_lowercase().contains("transaction"));

        Ok(())
    }

    fn job(output_plan: MssqlTargetOutputPlan) -> Result<MssqlOutputWriteJob, DeltaFunnelError> {
        counted_job(output_plan, Arc::new(Mutex::new(Vec::new())))
    }

    fn counted_job(
        output_plan: MssqlTargetOutputPlan,
        factory_calls: Arc<Mutex<Vec<String>>>,
    ) -> Result<MssqlOutputWriteJob, DeltaFunnelError> {
        let output_name = output_plan.output_name().to_owned();
        Ok(MssqlOutputWriteJob::with_default_write_options(
            output_schema(),
            resolved_target(output_plan)?,
            MssqlSchemaPlanOptions::default(),
            move || {
                if let Ok(mut calls) = factory_calls.lock() {
                    calls.push(output_name);
                }
                async { Ok(stream::empty()) }
            },
        )
        .with_phase_timings(planned_phase_timings()))
    }

    fn failing_factory_job(
        output_plan: MssqlTargetOutputPlan,
        factory_calls: Arc<Mutex<Vec<String>>>,
        message: &'static str,
    ) -> Result<MssqlOutputWriteJob, DeltaFunnelError> {
        let output_name = output_plan.output_name().to_owned();
        Ok(MssqlOutputWriteJob::with_default_write_options(
            output_schema(),
            resolved_target(output_plan)?,
            MssqlSchemaPlanOptions::default(),
            move || {
                if let Ok(mut calls) = factory_calls.lock() {
                    calls.push(output_name);
                }
                async move {
                    Err::<stream::Empty<Result<RecordBatch, DeltaFunnelError>>, DeltaFunnelError>(
                        test_error(message),
                    )
                }
            },
        )
        .with_phase_timings(planned_phase_timings()))
    }

    fn polling_error_job(
        output_plan: MssqlTargetOutputPlan,
        factory_calls: Arc<Mutex<Vec<String>>>,
    ) -> Result<MssqlOutputWriteJob, DeltaFunnelError> {
        let output_name = output_plan.output_name().to_owned();
        Ok(MssqlOutputWriteJob::with_default_write_options(
            output_schema(),
            resolved_target(output_plan)?,
            MssqlSchemaPlanOptions::default(),
            move || {
                if let Ok(mut calls) = factory_calls.lock() {
                    calls.push(output_name);
                }
                async {
                    Ok(stream::iter(vec![Err(
                        DeltaFunnelError::MssqlWorkflowPlanning {
                            message: "stream failed during polling".to_owned(),
                        },
                    )]))
                }
            },
        )
        .with_phase_timings(planned_phase_timings()))
    }

    fn planned_phase_timings() -> Vec<PhaseTimingReport> {
        vec![PhaseTimingReport::completed(
            PLANNED_PHASE,
            Duration::from_micros(1),
        )]
    }

    fn resolved_target(
        output_plan: MssqlTargetOutputPlan,
    ) -> Result<ResolvedMssqlTarget, DeltaFunnelError> {
        let connection = secret_connection()?;

        MssqlTargetConfig::new(output_plan.target_table().clone())
            .with_load_mode(output_plan.load_mode())
            .resolve(MssqlTargetResolutionContext {
                output_name: Some(output_plan.output_name()),
                default_connection: Some(&connection),
            })
    }

    fn output_plan(
        output_name: &str,
        load_mode: LoadMode,
    ) -> Result<MssqlTargetOutputPlan, DeltaFunnelError> {
        let connection = secret_connection()?;
        let target = MssqlTargetConfig::new(MssqlTargetTable::new(
            "dbo",
            format!("{output_name}_orders"),
        )?)
        .with_load_mode(load_mode);
        plan_mssql_target_for_output(
            output_schema(),
            output_name,
            &target,
            Some(&connection),
            MssqlSchemaPlanOptions::default(),
        )
    }

    fn output_schema() -> SchemaRef {
        Arc::new(Schema::new(vec![Field::new(
            "order_id",
            DataType::Int64,
            false,
        )]))
    }

    fn secret_connection() -> Result<MssqlConnectionConfig, DeltaFunnelError> {
        Ok(MssqlConnectionConfig::new(
            "server=tcp:example.invalid,1433;user id=sa;password=secret",
        )?
        .with_display_label("test connection"))
    }

    fn write_report(
        output_plan: &MssqlTargetOutputPlan,
        rows_written: u64,
        batches_written: u64,
        partial_write_possible: bool,
        cleanup: MssqlTargetCleanupStatus,
    ) -> MssqlWriteReport {
        MssqlWriteReport::from_output_plan(
            output_plan,
            rows_written,
            batches_written,
            0,
            partial_write_possible,
            cleanup,
        )
    }

    fn phase_error(
        output_plan: &MssqlTargetOutputPlan,
        phase: MssqlWritePhase,
        rows_written: u64,
        batches_written: u64,
        partial_write_possible: bool,
        cleanup: MssqlTargetCleanupStatus,
        message: &str,
    ) -> DeltaFunnelError {
        phase_error_with_context(
            MssqlWriteFailureContext::from_output_plan(
                output_plan,
                phase,
                rows_written,
                batches_written,
                0,
                partial_write_possible,
                cleanup,
            ),
            message,
        )
    }

    fn phase_error_with_context(
        context: MssqlWriteFailureContext,
        message: &str,
    ) -> DeltaFunnelError {
        DeltaFunnelError::MssqlWritePhase {
            context: Box::new(context),
            message: message.to_owned(),
        }
    }

    fn assert_status_output(
        statuses: &[MssqlOutputWriteStatus],
        index: usize,
        expected_output_name: &str,
    ) -> Result<(), DeltaFunnelError> {
        match statuses.get(index) {
            Some(MssqlOutputWriteStatus::Succeeded(report)) => {
                assert_eq!(report.output_name(), expected_output_name);
                Ok(())
            }
            Some(other) => Err(test_error(format!(
                "expected success at index {index}, got {other:?}"
            ))),
            None => Err(test_error(format!("missing status at index {index}"))),
        }
    }

    fn assert_skipped_after(
        status: &MssqlOutputWriteStatus,
        expected_output_name: &str,
        expected_failed_output_name: &str,
    ) -> Result<(), DeltaFunnelError> {
        let MssqlOutputWriteStatus::Skipped(skipped) = status else {
            return Err(test_error(format!(
                "expected skipped status, got {status:?}"
            )));
        };
        assert_eq!(skipped.output_name(), expected_output_name);
        assert_eq!(
            skipped.reason(),
            &MssqlWriteSkippedReason::PreviousOutputFailed {
                failed_output_name: expected_failed_output_name.to_owned()
            }
        );
        assert_eq!(status.output_row_count(), RowCount::unavailable());
        assert_batch_shaping(
            status.batch_shaping(),
            PhaseStatus::skipped(ReportReasonCode::PriorFailure),
            0,
            0,
            0,
            0,
        );
        assert_phase_timing(status, PLANNED_PHASE, PhaseStatus::completed())?;
        assert_phase_timing(
            status,
            OUTPUT_STREAM_SETUP_PHASE,
            PhaseStatus::skipped(ReportReasonCode::PriorFailure),
        )?;
        assert_phase_timing(
            status,
            SQL_WRITE_PHASE,
            PhaseStatus::skipped(ReportReasonCode::PriorFailure),
        )?;
        assert_phase_timing(
            status,
            VALIDATION_PHASE,
            PhaseStatus::skipped(ReportReasonCode::PriorFailure),
        )?;
        Ok(())
    }

    fn assert_phase_timing(
        status: &MssqlOutputWriteStatus,
        phase_name: &str,
        expected_status: PhaseStatus,
    ) -> Result<(), DeltaFunnelError> {
        let timing = status
            .phase_timings()
            .iter()
            .find(|timing| timing.phase_name() == phase_name)
            .ok_or_else(|| test_error(format!("missing phase timing {phase_name}")))?;

        assert_eq!(timing.status(), expected_status);
        if expected_status.is_completed() || expected_status.is_failed() {
            assert!(timing.elapsed_micros().is_some());
        } else {
            assert_eq!(timing.elapsed_micros(), None);
        }
        Ok(())
    }

    fn assert_batch_shaping(
        report: MssqlBatchShapingReport,
        expected_status: PhaseStatus,
        expected_input_batches: u64,
        expected_input_rows: u64,
        expected_output_batches: u64,
        expected_output_rows: u64,
    ) {
        assert_eq!(report.status(), expected_status);
        assert_eq!(report.input_batches(), expected_input_batches);
        assert_eq!(report.input_rows(), expected_input_rows);
        assert_eq!(report.output_batches(), expected_output_batches);
        assert_eq!(report.output_rows(), expected_output_rows);
    }

    fn locked<T>(mutex: &Mutex<T>) -> Result<MutexGuard<'_, T>, DeltaFunnelError> {
        mutex.lock().map_err(|_| test_error("mutex lock poisoned"))
    }

    fn test_error(message: impl Into<String>) -> DeltaFunnelError {
        DeltaFunnelError::MssqlWorkflowPlanning {
            message: message.into(),
        }
    }
}