delta_kernel 0.25.0

Core crate providing a Delta/Deltalake implementation focused on interoperability with a wide range of query engines.
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
//! Metric event types emitted during Delta Kernel operations.
//!
//! Each [`MetricEvent`] variant wraps a per-event struct that owns its fields, `Display` impl,
//! span name, and the small set of methods the `tracing` layer in [`crate::metrics::reporter`]
//! calls to construct and finalize the event. Per-event code is colocated in a single block
//! per type below.
//!
//! Enums carried in event payloads derive the full strum set (`EnumString`, `Display`,
//! `AsRefStr`, `IntoStaticStr`) with stable serialized names. `IntoStaticStr` in particular
//! lets connectors convert a value to its `&'static str` metric-label string via `.into()`
//! instead of maintaining their own variant-to-string `match`.
//!
//! Event construction is infallible: a malformed span field warns and falls back to a
//! default rather than failing the operation being observed.

use std::fmt;
use std::str::FromStr as _;
use std::sync::Arc;
use std::time::Duration;

use delta_kernel_derive::internal_api;
use strum::{AsRefStr, Display as StrumDisplay, EnumString, IntoStaticStr};
use tracing::field::{Field, Visit};
use tracing::span::Attributes;
use tracing::warn;
use uuid::Uuid;

// ====================================================================
// MetricId
// ====================================================================

/// Unique identifier for a metrics operation.
///
/// Each operation (Snapshot, Transaction, Scan) gets a unique `MetricId` that correlates all
/// events emitted from that operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MetricId(pub(crate) Uuid);

impl MetricId {
    /// Generate a new unique `MetricId`.
    pub fn new() -> Self {
        Self(Uuid::new_v4())
    }

    /// Return the 16 raw bytes of the underlying UUID. Useful for FFI consumers that want to
    /// carry the id without allocating or parsing its string form.
    pub fn as_bytes(&self) -> [u8; 16] {
        *self.0.as_bytes()
    }

    /// Extract the `operation_id` field from span attributes. Returns a nil id if the field is
    /// absent, or warns and returns nil if the value is present but malformed.
    pub(crate) fn from_attrs(attrs: &Attributes<'_>) -> Self {
        #[derive(Default)]
        struct V(Uuid);
        impl Visit for V {
            fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
                if field.name() == "operation_id" {
                    let s = format!("{value:?}");
                    match Uuid::from_str(&s) {
                        Ok(u) => self.0 = u,
                        Err(e) => warn!("Invalid uuid '{s}' on span: {e}. Using default."),
                    }
                }
            }
        }
        let mut v = V::default();
        attrs.record(&mut v);
        Self(v.0)
    }
}

impl Default for MetricId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for MetricId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

// ====================================================================
// MetricEvent
// ====================================================================

/// Metric events emitted during Delta Kernel operations.
#[derive(Debug, Clone)]
pub enum MetricEvent {
    LogSegmentLoadSuccess(LogSegmentLoadSuccess),
    LogSegmentLoadFailure(LogSegmentLoadFailure),
    ProtocolMetadataLoadSuccess(ProtocolMetadataLoadSuccess),
    ProtocolMetadataLoadFailure(ProtocolMetadataLoadFailure),
    SnapshotBuildSuccess(SnapshotBuildSuccess),
    SnapshotBuildFailure(SnapshotBuildFailure),
    TransactionCommitSuccess(TransactionCommitSuccess),
    TransactionCommitFailure(TransactionCommitFailure),
    DomainMetadataLoadSuccess(DomainMetadataLoadSuccess),
    DomainMetadataLoadFailure,
    SetTransactionLoadSuccess(SetTransactionLoadSuccess),
    SetTransactionLoadFailure,
    CrcReadSuccess(CrcReadSuccess),
    CrcReadFailure,
    JsonReadCompleted(JsonReadCompleted),
    ParquetReadCompleted(ParquetReadCompleted),
    ScanMetadataCompleted(ScanMetadataCompleted),
    StorageListCompleted(StorageListCompleted),
    StorageReadCompleted(StorageReadCompleted),
    StorageCopyCompleted(StorageCopyCompleted),
}

impl MetricEvent {
    /// Set the wall-clock duration on lifecycle events.
    pub(crate) fn set_duration_if_applicable(&mut self, d: Duration) {
        match self {
            // Lifecycle success: duration must be set by the tracing layer on span close.
            Self::LogSegmentLoadSuccess(e) => e.set_duration(d),
            Self::ProtocolMetadataLoadSuccess(e) => e.set_duration(d),
            Self::SnapshotBuildSuccess(e) => e.set_duration(d),
            Self::TransactionCommitSuccess(e) => e.set_duration(d),
            Self::DomainMetadataLoadSuccess(e) => e.set_duration(d),
            Self::SetTransactionLoadSuccess(e) => e.set_duration(d),
            Self::CrcReadSuccess(e) => e.set_duration(d),

            // For now, failure events carry no duration; storage/scan events set it at
            // construction; read events have no duration field.
            Self::LogSegmentLoadFailure(_)
            | Self::ProtocolMetadataLoadFailure(_)
            | Self::SnapshotBuildFailure(_)
            | Self::TransactionCommitFailure(_)
            | Self::DomainMetadataLoadFailure
            | Self::SetTransactionLoadFailure
            | Self::CrcReadFailure
            | Self::ScanMetadataCompleted(_)
            | Self::StorageListCompleted(_)
            | Self::StorageReadCompleted(_)
            | Self::StorageCopyCompleted(_)
            | Self::JsonReadCompleted(_)
            | Self::ParquetReadCompleted(_) => {}
        }
    }

    pub(crate) fn record_u64(&mut self, name: &str, value: u64) -> Result<(), &'static str> {
        match self {
            // Variants with u64 fields set during span lifetime.
            Self::LogSegmentLoadSuccess(e) => e.record_u64(name, value),
            Self::SnapshotBuildSuccess(e) => e.record_u64(name, value),
            Self::TransactionCommitSuccess(e) => e.record_u64(name, value),
            Self::DomainMetadataLoadSuccess(e) => e.record_u64(name, value),
            Self::CrcReadSuccess(e) => e.record_u64(name, value),

            // No u64 fields set during span lifetime — a runtime record() on these is a bug.
            Self::ProtocolMetadataLoadSuccess(_) => Err(ProtocolMetadataLoadSuccess::SPAN_NAME),
            Self::SetTransactionLoadSuccess(_) => Err(SetTransactionLoadSuccess::SPAN_NAME),
            Self::ScanMetadataCompleted(_) => Err(ScanMetadataCompleted::SPAN_NAME),
            Self::JsonReadCompleted(_) => Err(JsonReadCompleted::SPAN_NAME),
            Self::ParquetReadCompleted(_) => Err(ParquetReadCompleted::SPAN_NAME),
            Self::StorageListCompleted(_)
            | Self::StorageReadCompleted(_)
            | Self::StorageCopyCompleted(_) => Err(STORAGE_SPAN),

            // Failure events are built at span close, after any runtime records.
            Self::LogSegmentLoadFailure(_) => Err(LogSegmentLoadSuccess::SPAN_NAME),
            Self::ProtocolMetadataLoadFailure(_) => Err(ProtocolMetadataLoadSuccess::SPAN_NAME),
            Self::SnapshotBuildFailure(_) => Err(SnapshotBuildSuccess::SPAN_NAME),
            Self::TransactionCommitFailure(_) => Err(TransactionCommitSuccess::SPAN_NAME),
            Self::DomainMetadataLoadFailure => Err(DomainMetadataLoadSuccess::SPAN_NAME),
            Self::SetTransactionLoadFailure => Err(SetTransactionLoadSuccess::SPAN_NAME),
            Self::CrcReadFailure => Err(CrcReadSuccess::SPAN_NAME),
        }
    }

    pub(crate) fn record_bool(&mut self, name: &str, value: bool) -> Result<(), &'static str> {
        match self {
            // Variants with bool fields set during span lifetime.
            Self::LogSegmentLoadSuccess(e) => e.record_bool(name, value),
            Self::TransactionCommitSuccess(e) => e.record_bool(name, value),
            Self::DomainMetadataLoadSuccess(e) => e.record_bool(name, value),
            Self::SetTransactionLoadSuccess(e) => e.record_bool(name, value),

            // No bool fields set during span lifetime — a runtime record() on these is a bug.
            Self::ProtocolMetadataLoadSuccess(_) => Err(ProtocolMetadataLoadSuccess::SPAN_NAME),
            Self::SnapshotBuildSuccess(_) => Err(SnapshotBuildSuccess::SPAN_NAME),
            Self::CrcReadSuccess(_) => Err(CrcReadSuccess::SPAN_NAME),
            Self::ScanMetadataCompleted(_) => Err(ScanMetadataCompleted::SPAN_NAME),
            Self::JsonReadCompleted(_) => Err(JsonReadCompleted::SPAN_NAME),
            Self::ParquetReadCompleted(_) => Err(ParquetReadCompleted::SPAN_NAME),
            Self::StorageListCompleted(_)
            | Self::StorageReadCompleted(_)
            | Self::StorageCopyCompleted(_) => Err(STORAGE_SPAN),

            // Failure events are built at span close, after any runtime records.
            Self::LogSegmentLoadFailure(_) => Err(LogSegmentLoadSuccess::SPAN_NAME),
            Self::ProtocolMetadataLoadFailure(_) => Err(ProtocolMetadataLoadSuccess::SPAN_NAME),
            Self::SnapshotBuildFailure(_) => Err(SnapshotBuildSuccess::SPAN_NAME),
            Self::TransactionCommitFailure(_) => Err(TransactionCommitSuccess::SPAN_NAME),
            Self::DomainMetadataLoadFailure => Err(DomainMetadataLoadSuccess::SPAN_NAME),
            Self::SetTransactionLoadFailure => Err(SetTransactionLoadSuccess::SPAN_NAME),
            Self::CrcReadFailure => Err(CrcReadSuccess::SPAN_NAME),
        }
    }

    pub(crate) fn record_str(&mut self, name: &str, value: &str) -> Result<(), &'static str> {
        if name == "failure_reason" {
            if let Self::TransactionCommitSuccess(e) = self {
                let operation_id = e.operation_id;
                let table_type = e.table_type;
                let correlation_id = e.correlation_id.take();
                *self = Self::TransactionCommitFailure(TransactionCommitFailure {
                    operation_id,
                    table_type,
                    correlation_id,
                    reason: value.parse().unwrap_or_else(|e| {
                        warn!("Invalid failure_reason '{value}' on span: {e}. Using Error.");
                        CommitFailureReason::Error
                    }),
                });
            }
            return Ok(());
        }
        // Only TransactionCommitSuccess records string fields today. If other events need them,
        // dispatch per-variant like `record_u64`/`record_bool` above instead of this catch-all.
        match self {
            Self::TransactionCommitSuccess(e) => e.record_str(name, value),
            _ => Ok(()),
        }
    }

    /// Maps a lifecycle success event to its failure counterpart when the span errors.
    pub(crate) fn into_failure(self) -> Self {
        match self {
            Self::LogSegmentLoadSuccess(e) => Self::LogSegmentLoadFailure(LogSegmentLoadFailure {
                operation_id: e.operation_id,
                table_type: e.table_type,
                correlation_id: e.correlation_id,
            }),
            Self::ProtocolMetadataLoadSuccess(e) => {
                Self::ProtocolMetadataLoadFailure(ProtocolMetadataLoadFailure {
                    operation_id: e.operation_id,
                    table_type: e.table_type,
                    correlation_id: e.correlation_id,
                })
            }
            Self::SnapshotBuildSuccess(e) => Self::SnapshotBuildFailure(SnapshotBuildFailure {
                operation_id: e.operation_id,
                table_type: e.table_type,
                correlation_id: e.correlation_id,
            }),
            Self::TransactionCommitSuccess(e) => {
                Self::TransactionCommitFailure(TransactionCommitFailure {
                    operation_id: e.operation_id,
                    table_type: e.table_type,
                    correlation_id: e.correlation_id,
                    reason: CommitFailureReason::Error,
                })
            }
            Self::DomainMetadataLoadSuccess(_) => Self::DomainMetadataLoadFailure,
            Self::SetTransactionLoadSuccess(_) => Self::SetTransactionLoadFailure,
            Self::CrcReadSuccess(_) => Self::CrcReadFailure,
            // Events with no failure form pass through unchanged.
            // Note: here we list explicitly so adding a lifecycle event without a failure mapping
            //       fails to compile.
            e @ (Self::LogSegmentLoadFailure(_)
            | Self::ProtocolMetadataLoadFailure(_)
            | Self::SnapshotBuildFailure(_)
            | Self::TransactionCommitFailure(_)
            | Self::DomainMetadataLoadFailure
            | Self::SetTransactionLoadFailure
            | Self::CrcReadFailure
            | Self::JsonReadCompleted(_)
            | Self::ParquetReadCompleted(_)
            | Self::ScanMetadataCompleted(_)
            | Self::StorageListCompleted(_)
            | Self::StorageReadCompleted(_)
            | Self::StorageCopyCompleted(_)) => e,
        }
    }
}

impl fmt::Display for MetricEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::LogSegmentLoadSuccess(e) => e.fmt(f),
            Self::LogSegmentLoadFailure(e) => e.fmt(f),
            Self::ProtocolMetadataLoadSuccess(e) => e.fmt(f),
            Self::ProtocolMetadataLoadFailure(e) => e.fmt(f),
            Self::SnapshotBuildSuccess(e) => e.fmt(f),
            Self::SnapshotBuildFailure(e) => e.fmt(f),
            Self::TransactionCommitSuccess(e) => e.fmt(f),
            Self::TransactionCommitFailure(e) => e.fmt(f),
            Self::DomainMetadataLoadSuccess(e) => e.fmt(f),
            Self::DomainMetadataLoadFailure => f.write_str("DomainMetadataLoadFailure"),
            Self::SetTransactionLoadSuccess(e) => e.fmt(f),
            Self::SetTransactionLoadFailure => f.write_str("SetTransactionLoadFailure"),
            Self::CrcReadSuccess(e) => e.fmt(f),
            Self::CrcReadFailure => f.write_str("CrcReadFailure"),
            Self::JsonReadCompleted(e) => e.fmt(f),
            Self::ParquetReadCompleted(e) => e.fmt(f),
            Self::ScanMetadataCompleted(e) => e.fmt(f),
            Self::StorageListCompleted(e) => e.fmt(f),
            Self::StorageReadCompleted(e) => e.fmt(f),
            Self::StorageCopyCompleted(e) => e.fmt(f),
        }
    }
}

// ====================================================================
// LogSegmentLoad
// ====================================================================
//
// Canonical example for the per-event block pattern. Other events below follow the same
// shape; detailed `///` docs on `from_attrs` and `record_*` live here only.

// Module-scope span name. `#[instrument(name = ...)]` only accepts a bare identifier here,
// not a multi-segment path like `Type::SPAN_NAME`.
pub(crate) const LOG_SEGMENT_LOADED_SPAN: &str = "segment.for_snapshot";

/// A log segment was listed and assembled for a snapshot.
#[derive(Debug, Clone)]
pub struct LogSegmentLoadSuccess {
    // === Set on span creation ===
    pub operation_id: MetricId,
    /// Opaque, caller-supplied id for joining this operation's metric events to the caller's
    /// own request or operation id.
    pub correlation_id: Option<Arc<str>>,
    pub table_type: TableType,

    // === Set during span lifetime ===
    pub num_commit_files: u64,
    pub num_checkpoint_files: u64,
    pub num_compaction_files: u64,
    pub has_latest_crc_file: bool,

    // === Set on span close ===
    pub duration: Duration,
}

impl LogSegmentLoadSuccess {
    pub(crate) const SPAN_NAME: &'static str = LOG_SEGMENT_LOADED_SPAN;

    /// Construction-time channel. Extracts fields bound at span creation via
    /// `#[instrument(fields(X = expr))]` or `tracing::span!(..., X = expr)`.
    pub(crate) fn from_attrs(attrs: &Attributes<'_>) -> Self {
        Self {
            operation_id: MetricId::from_attrs(attrs),
            table_type: TableType::from_catalog_managed(read_is_catalog_managed(attrs)),
            correlation_id: correlation_id_from_attrs(attrs),
            num_commit_files: 0,
            num_checkpoint_files: 0,
            num_compaction_files: 0,
            has_latest_crc_file: false,
            duration: Duration::default(),
        }
    }

    /// Runtime channel. Dispatches a u64 field update from `Span::current().record(name, value)`
    /// to the matching field.
    pub(crate) fn record_u64(&mut self, name: &str, value: u64) -> Result<(), &'static str> {
        match name {
            "num_commit_files" => self.num_commit_files = value,
            "num_checkpoint_files" => self.num_checkpoint_files = value,
            "num_compaction_files" => self.num_compaction_files = value,
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn record_bool(&mut self, name: &str, value: bool) -> Result<(), &'static str> {
        match name {
            "has_latest_crc_file" => self.has_latest_crc_file = value,
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn set_duration(&mut self, d: Duration) {
        self.duration = d;
    }
}

impl fmt::Display for LogSegmentLoadSuccess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            operation_id,
            table_type,
            correlation_id,
            duration,
            num_commit_files,
            num_checkpoint_files,
            num_compaction_files,
            has_latest_crc_file,
        } = self;
        write!(
            f,
            "LogSegmentLoadSuccess(id={operation_id}, table_type={table_type}, \
             correlation_id={correlation_id:?}, \
             duration={duration:?}, commits={num_commit_files}, \
             checkpoints={num_checkpoint_files}, compactions={num_compaction_files}, \
             has_latest_crc={has_latest_crc_file})"
        )
    }
}

/// Listing the log segment for a snapshot failed.
#[derive(Debug, Clone)]
pub struct LogSegmentLoadFailure {
    pub operation_id: MetricId,
    /// Opaque, caller-supplied id for joining this operation's metric events to the caller's
    /// own request or operation id.
    pub correlation_id: Option<Arc<str>>,
    pub table_type: TableType,
}

impl fmt::Display for LogSegmentLoadFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "LogSegmentLoadFailure(id={}, table_type={}, correlation_id={:?})",
            self.operation_id, self.table_type, self.correlation_id
        )
    }
}

// ====================================================================
// ProtocolMetadataLoad
// ====================================================================

pub(crate) const PROTOCOL_METADATA_LOADED_SPAN: &str = "segment.read_metadata";

/// Protocol and metadata actions were read from the log.
#[derive(Debug, Clone)]
pub struct ProtocolMetadataLoadSuccess {
    // === Set on span creation ===
    pub operation_id: MetricId,
    /// Opaque, caller-supplied id for joining this operation's metric events to the caller's
    /// own request or operation id.
    pub correlation_id: Option<Arc<str>>,
    pub table_type: TableType,

    // === Set on span close ===
    pub duration: Duration,
}

impl ProtocolMetadataLoadSuccess {
    pub(crate) const SPAN_NAME: &'static str = PROTOCOL_METADATA_LOADED_SPAN;

    pub(crate) fn from_attrs(attrs: &Attributes<'_>) -> Self {
        Self {
            operation_id: MetricId::from_attrs(attrs),
            table_type: TableType::from_catalog_managed(read_is_catalog_managed(attrs)),
            correlation_id: correlation_id_from_attrs(attrs),
            duration: Duration::default(),
        }
    }

    pub(crate) fn set_duration(&mut self, d: Duration) {
        self.duration = d;
    }
}

impl fmt::Display for ProtocolMetadataLoadSuccess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            operation_id,
            table_type,
            correlation_id,
            duration,
        } = self;
        write!(
            f,
            "ProtocolMetadataLoadSuccess(id={operation_id}, table_type={table_type}, \
             correlation_id={correlation_id:?}, duration={duration:?})"
        )
    }
}

/// Reading protocol and metadata from the log failed.
#[derive(Debug, Clone)]
pub struct ProtocolMetadataLoadFailure {
    pub operation_id: MetricId,
    /// Opaque, caller-supplied id for joining this operation's metric events to the caller's
    /// own request or operation id.
    pub correlation_id: Option<Arc<str>>,
    pub table_type: TableType,
}

impl fmt::Display for ProtocolMetadataLoadFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ProtocolMetadataLoadFailure(id={}, table_type={}, correlation_id={:?})",
            self.operation_id, self.table_type, self.correlation_id
        )
    }
}

// ====================================================================
// SnapshotBuild
// ====================================================================

pub(crate) const SNAPSHOT_COMPLETED_SPAN: &str = "snap.build";

/// A snapshot was built successfully.
#[derive(Debug, Clone)]
pub struct SnapshotBuildSuccess {
    // === Set on span creation ===
    pub operation_id: MetricId,
    /// Opaque, caller-supplied id for joining this operation's metric events to the caller's
    /// own request or operation id.
    pub correlation_id: Option<Arc<str>>,
    pub table_type: TableType,

    // === Set during span lifetime ===
    pub version: u64,

    // === Set on span close ===
    pub duration: Duration,
}

impl SnapshotBuildSuccess {
    pub(crate) const SPAN_NAME: &'static str = SNAPSHOT_COMPLETED_SPAN;

    pub(crate) fn from_attrs(attrs: &Attributes<'_>) -> Self {
        Self {
            operation_id: MetricId::from_attrs(attrs),
            table_type: TableType::from_catalog_managed(read_is_catalog_managed(attrs)),
            correlation_id: correlation_id_from_attrs(attrs),
            version: 0,
            duration: Duration::default(),
        }
    }

    pub(crate) fn record_u64(&mut self, name: &str, value: u64) -> Result<(), &'static str> {
        match name {
            "version" => self.version = value,
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn set_duration(&mut self, d: Duration) {
        self.duration = d;
    }
}

impl fmt::Display for SnapshotBuildSuccess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            operation_id,
            table_type,
            correlation_id,
            version,
            duration,
        } = self;
        write!(
            f,
            "SnapshotBuildSuccess(id={operation_id}, table_type={table_type}, \
             correlation_id={correlation_id:?}, version={version}, duration={duration:?})"
        )
    }
}

// ====================================================================
// SnapshotBuildFailure
// ====================================================================

/// Building a snapshot failed.
#[derive(Debug, Clone)]
pub struct SnapshotBuildFailure {
    pub operation_id: MetricId,
    /// Opaque, caller-supplied id for joining this operation's metric events to the caller's
    /// own request or operation id.
    pub correlation_id: Option<Arc<str>>,
    pub table_type: TableType,
}

impl fmt::Display for SnapshotBuildFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "SnapshotBuildFailure(id={}, table_type={}, correlation_id={:?})",
            self.operation_id, self.table_type, self.correlation_id
        )
    }
}

// ====================================================================
// TransactionCommit
// ====================================================================

pub(crate) const TRANSACTION_COMMIT_SPAN: &str = "txn.commit";

/// A transaction was committed successfully.
#[derive(Debug, Clone)]
pub struct TransactionCommitSuccess {
    // === Set on span creation ===
    pub operation_id: MetricId,
    /// Opaque, caller-supplied id for joining this operation's metric events to the caller's
    /// own request or operation id.
    pub correlation_id: Option<Arc<str>>,
    pub table_type: TableType,
    pub commit_version: u64,

    // === Set during span lifetime ===
    pub num_add_files: u64,
    pub num_remove_files: u64,
    pub num_dv_updates: u64,
    pub add_files_bytes: u64,
    pub remove_files_bytes: u64,
    pub is_blind_append: bool,
    pub data_change: bool,
    pub operation: Option<String>,
    /// Time assembling and validating the commit, before the committer call.
    pub prepare_duration: Duration,
    /// Time in the committer's `commit()` call.
    pub committer_duration: Duration,

    // === Set on span close ===
    pub total_duration: Duration,
}

impl TransactionCommitSuccess {
    pub(crate) const SPAN_NAME: &'static str = TRANSACTION_COMMIT_SPAN;

    pub(crate) fn from_attrs(attrs: &Attributes<'_>) -> Self {
        let mut v = TransactionCommitAttrs::default();
        attrs.record(&mut v);
        Self {
            operation_id: MetricId::from_attrs(attrs),
            table_type: TableType::from_catalog_managed(read_is_catalog_managed(attrs)),
            correlation_id: correlation_id_from_attrs(attrs),
            commit_version: v.commit_version,
            num_add_files: 0,
            num_remove_files: 0,
            num_dv_updates: 0,
            add_files_bytes: 0,
            remove_files_bytes: 0,
            is_blind_append: false,
            data_change: false,
            operation: None,
            prepare_duration: Duration::default(),
            committer_duration: Duration::default(),
            total_duration: Duration::default(),
        }
    }

    pub(crate) fn record_u64(&mut self, name: &str, value: u64) -> Result<(), &'static str> {
        match name {
            "num_add_files" => self.num_add_files = value,
            "num_remove_files" => self.num_remove_files = value,
            "num_dv_updates" => self.num_dv_updates = value,
            "add_files_bytes" => self.add_files_bytes = value,
            "remove_files_bytes" => self.remove_files_bytes = value,
            "prepare_duration_ns" => self.prepare_duration = Duration::from_nanos(value),
            "committer_duration_ns" => self.committer_duration = Duration::from_nanos(value),
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn record_bool(&mut self, name: &str, value: bool) -> Result<(), &'static str> {
        match name {
            "is_blind_append" => self.is_blind_append = value,
            "data_change" => self.data_change = value,
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn record_str(&mut self, name: &str, value: &str) -> Result<(), &'static str> {
        match name {
            "operation" => self.operation = Some(value.to_string()),
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn set_duration(&mut self, d: Duration) {
        self.total_duration = d;
    }
}

impl fmt::Display for TransactionCommitSuccess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            operation_id,
            table_type,
            correlation_id,
            commit_version,
            num_add_files,
            num_remove_files,
            num_dv_updates,
            add_files_bytes,
            remove_files_bytes,
            is_blind_append,
            data_change,
            operation,
            prepare_duration,
            committer_duration,
            total_duration,
        } = self;
        write!(
            f,
            "TransactionCommitSuccess(id={operation_id}, table_type={table_type}, \
             correlation_id={correlation_id:?}, version={commit_version}, \
             total_duration={total_duration:?}, prepare={prepare_duration:?}, committer={committer_duration:?}, \
             add_files={num_add_files}, remove_files={num_remove_files}, dv_updates={num_dv_updates}, \
             add_bytes={add_files_bytes}, remove_bytes={remove_files_bytes}, \
             is_blind_append={is_blind_append}, data_change={data_change}, operation={operation:?})"
        )
    }
}

/// Why a transaction commit did not succeed.
///
/// Serializes to its `snake_case` name for the `failure_reason` span field (e.g.
/// `RetryableIo` -> `"retryable_io"`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, StrumDisplay, AsRefStr, IntoStaticStr)]
#[strum(serialize_all = "snake_case")]
pub enum CommitFailureReason {
    /// The commit conflicted with a concurrently committed version.
    Conflict,
    /// A retryable IO error occurred during the commit.
    RetryableIo,
    /// A terminal (non-retryable) error occurred.
    Error,
}

/// A transaction commit did not succeed; `reason` distinguishes conflict, retryable IO, and
/// terminal errors.
#[derive(Debug, Clone)]
pub struct TransactionCommitFailure {
    pub operation_id: MetricId,
    /// Opaque, caller-supplied id for joining this operation's metric events to the caller's
    /// own request or operation id.
    pub correlation_id: Option<Arc<str>>,
    pub table_type: TableType,
    pub reason: CommitFailureReason,
}

impl fmt::Display for TransactionCommitFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            operation_id,
            table_type,
            correlation_id,
            reason,
        } = self;
        write!(
            f,
            "TransactionCommitFailure(id={operation_id}, table_type={table_type}, \
             correlation_id={correlation_id:?}, reason={reason})"
        )
    }
}

#[derive(Default)]
struct TransactionCommitAttrs {
    commit_version: u64,
}

impl Visit for TransactionCommitAttrs {
    fn record_u64(&mut self, field: &Field, value: u64) {
        if field.name() == "commit_version" {
            self.commit_version = value;
        }
    }

    fn record_debug(&mut self, _field: &Field, _value: &dyn fmt::Debug) {}
}

// ====================================================================
// DomainMetadataLoad
// ====================================================================

pub(crate) const DOMAIN_METADATA_LOADED_SPAN: &str = "snap.get_domain_metadata";

/// Emitted once per domain metadata load, whether served from the CRC cache (`from_cache`) or
/// from a log replay. Covers connector-issued loads of user domains and kernel-internal loads of
/// system (`delta.*`) domains such as clustering or row tracking.
#[derive(Debug, Clone)]
pub struct DomainMetadataLoadSuccess {
    // === Set during span lifetime ===
    pub from_cache: bool,
    pub num_domains_returned: u64,

    // === Set on span close ===
    pub duration: Duration,
}

impl DomainMetadataLoadSuccess {
    pub(crate) const SPAN_NAME: &'static str = DOMAIN_METADATA_LOADED_SPAN;

    pub(crate) fn from_attrs(_attrs: &Attributes<'_>) -> Self {
        Self {
            from_cache: false,
            num_domains_returned: 0,
            duration: Duration::default(),
        }
    }

    pub(crate) fn record_u64(&mut self, name: &str, value: u64) -> Result<(), &'static str> {
        match name {
            "num_domains_returned" => self.num_domains_returned = value,
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn record_bool(&mut self, name: &str, value: bool) -> Result<(), &'static str> {
        match name {
            "from_cache" => self.from_cache = value,
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn set_duration(&mut self, d: Duration) {
        self.duration = d;
    }
}

impl fmt::Display for DomainMetadataLoadSuccess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            from_cache,
            num_domains_returned,
            duration,
        } = self;
        write!(
            f,
            "DomainMetadataLoadSuccess(duration={duration:?}, from_cache={from_cache}, \
             num_domains_returned={num_domains_returned})"
        )
    }
}

// ====================================================================
// SetTransactionLoad
// ====================================================================

pub(crate) const SET_TRANSACTION_LOADED_SPAN: &str = "snap.get_app_id_version";

/// Emitted once per `SetTransaction` (app id) load, whether served from the CRC cache
/// (`from_cache`) or from a log replay. `found` is true when the app id has a committed
/// transaction version, false when none exists or the existing one is expired.
#[derive(Debug, Clone)]
pub struct SetTransactionLoadSuccess {
    // === Set during span lifetime ===
    pub from_cache: bool,
    pub found: bool,

    // === Set on span close ===
    pub duration: Duration,
}

impl SetTransactionLoadSuccess {
    pub(crate) const SPAN_NAME: &'static str = SET_TRANSACTION_LOADED_SPAN;

    pub(crate) fn from_attrs(_attrs: &Attributes<'_>) -> Self {
        Self {
            from_cache: false,
            found: false,
            duration: Duration::default(),
        }
    }

    pub(crate) fn record_bool(&mut self, name: &str, value: bool) -> Result<(), &'static str> {
        match name {
            "from_cache" => self.from_cache = value,
            "found" => self.found = value,
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn set_duration(&mut self, d: Duration) {
        self.duration = d;
    }
}

impl fmt::Display for SetTransactionLoadSuccess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            from_cache,
            found,
            duration,
        } = self;
        write!(
            f,
            "SetTransactionLoadSuccess(duration={duration:?}, from_cache={from_cache}, found={found})"
        )
    }
}

// ====================================================================
// CrcRead
// ====================================================================

pub(crate) const CRC_READ_COMPLETED_SPAN: &str = "crc_read_completed";

/// A CRC file was read and parsed successfully. `bytes_read` is the raw byte count from storage.
#[derive(Debug, Clone)]
pub struct CrcReadSuccess {
    // === Set during span lifetime ===
    pub bytes_read: u64,

    // === Set on span close ===
    pub duration: Duration,
}

impl CrcReadSuccess {
    pub(crate) const SPAN_NAME: &'static str = CRC_READ_COMPLETED_SPAN;

    pub(crate) fn from_attrs(_attrs: &Attributes<'_>) -> Self {
        Self {
            bytes_read: 0,
            duration: Duration::default(),
        }
    }

    pub(crate) fn record_u64(&mut self, name: &str, value: u64) -> Result<(), &'static str> {
        match name {
            "bytes_read" => self.bytes_read = value,
            _ => return Err(Self::SPAN_NAME),
        }
        Ok(())
    }

    pub(crate) fn set_duration(&mut self, d: Duration) {
        self.duration = d;
    }
}

impl fmt::Display for CrcReadSuccess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            duration,
            bytes_read,
        } = self;
        write!(
            f,
            "CrcReadSuccess(duration={duration:?}, bytes={bytes_read})"
        )
    }
}

// ====================================================================
// JsonReadCompleted
// ====================================================================

/// Emitted once per `JsonHandler::read_json_files` call when the returned iterator is fully
/// consumed or dropped. `bytes_read` is the sum of on-disk `FileMeta::size`, not the
/// deserialized payload size.
#[derive(Debug, Clone)]
pub struct JsonReadCompleted {
    // === Set on span creation ===
    pub num_files: u64,
    pub bytes_read: u64,
}

impl JsonReadCompleted {
    pub(crate) const SPAN_NAME: &'static str = "json_read_completed";

    pub(crate) fn from_attrs(attrs: &Attributes<'_>) -> Self {
        let mut v = FileReadAttrs::default();
        attrs.record(&mut v);
        Self {
            num_files: v.num_files,
            bytes_read: v.bytes_read,
        }
    }
}

impl fmt::Display for JsonReadCompleted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            num_files,
            bytes_read,
        } = self;
        write!(
            f,
            "JsonReadCompleted(files={num_files}, bytes={bytes_read})"
        )
    }
}

// ====================================================================
// ParquetReadCompleted
// ====================================================================

/// Emitted once per `ParquetHandler::read_parquet_files` call when the returned iterator is
/// fully consumed or dropped. `bytes_read` is the sum of on-disk `FileMeta::size`, not the
/// deserialized payload size.
#[derive(Debug, Clone)]
pub struct ParquetReadCompleted {
    // === Set on span creation ===
    pub num_files: u64,
    pub bytes_read: u64,
}

impl ParquetReadCompleted {
    pub(crate) const SPAN_NAME: &'static str = "parquet_read_completed";

    pub(crate) fn from_attrs(attrs: &Attributes<'_>) -> Self {
        let mut v = FileReadAttrs::default();
        attrs.record(&mut v);
        Self {
            num_files: v.num_files,
            bytes_read: v.bytes_read,
        }
    }
}

impl fmt::Display for ParquetReadCompleted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            num_files,
            bytes_read,
        } = self;
        write!(
            f,
            "ParquetReadCompleted(files={num_files}, bytes={bytes_read})"
        )
    }
}

/// Shared attribute decoder for `JsonReadCompleted` and `ParquetReadCompleted`.
#[derive(Default)]
struct FileReadAttrs {
    num_files: u64,
    bytes_read: u64,
}

impl Visit for FileReadAttrs {
    fn record_u64(&mut self, field: &Field, value: u64) {
        match field.name() {
            "num_files" => self.num_files = value,
            "bytes_read" => self.bytes_read = value,
            _ => {}
        }
    }
    fn record_debug(&mut self, _field: &Field, _value: &dyn fmt::Debug) {}
}

// ====================================================================
// ScanMetadataCompleted
// ====================================================================

/// Identifies which scan execution path produced a scan metadata metrics event.
///
/// Serializes to the explicit `serialize` name on each variant for the `scan_type` span field
/// (e.g. `SequentialPhase` -> `"sequential"`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, StrumDisplay, AsRefStr, IntoStaticStr)]
pub enum ScanType {
    /// Sequential phase of [`crate::scan::Scan::parallel_scan_metadata`].
    #[strum(serialize = "sequential")]
    SequentialPhase,
    /// Parallel phase of [`crate::scan::Scan::parallel_scan_metadata`].
    #[strum(serialize = "parallel")]
    ParallelPhase,
    /// Scan metadata from [`crate::scan::Scan::scan_metadata`].
    #[strum(serialize = "full")]
    Full,
}

impl ScanType {
    fn parse_lenient(s: &str) -> Self {
        Self::from_str(s).unwrap_or_else(|e| {
            warn!("Invalid scan_type '{s}' on span: {e}. Using Full.");
            Self::Full
        })
    }
}

// ====================================================================
// SnapshotLoadMetricContext and shared span fields
// ====================================================================

/// The `is_catalog_managed` bool span field carried by every event that records it. It is the
/// confirmed protocol value, except on snapshot-load events, which use the requested mode because
/// the on-disk protocol is not known that early (see `SnapshotBuilder::build`).
pub(crate) const IS_CATALOG_MANAGED_FIELD: &str = "is_catalog_managed";

/// Whether a table is path-based or catalog-managed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum TableType {
    /// Loaded without catalog involvement; commits live directly in the Delta log.
    #[default]
    PathBased,
    /// Backed by a managing catalog.
    CatalogManaged,
}

impl TableType {
    #[internal_api]
    pub(crate) fn from_catalog_managed(is_catalog_managed: bool) -> Self {
        if is_catalog_managed {
            Self::CatalogManaged
        } else {
            Self::PathBased
        }
    }

    pub(crate) fn is_catalog_managed(self) -> bool {
        self == Self::CatalogManaged
    }
}

impl fmt::Display for TableType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::PathBased => "path_based",
            Self::CatalogManaged => "catalog_managed",
        })
    }
}

/// Operation-scoped values threaded through the snapshot-load chain to label its metric events.
#[derive(Debug, Clone, Default)]
pub struct SnapshotLoadMetricContext {
    pub(crate) operation_id: MetricId,
    pub(crate) correlation_id: Option<Arc<str>>,
    pub(crate) is_catalog_managed: bool,
}

pub(crate) fn read_is_catalog_managed(attrs: &Attributes<'_>) -> bool {
    #[derive(Default)]
    struct V(bool);
    impl Visit for V {
        fn record_bool(&mut self, field: &Field, value: bool) {
            if field.name() == IS_CATALOG_MANAGED_FIELD {
                self.0 = value;
            }
        }
        fn record_debug(&mut self, _field: &Field, _value: &dyn fmt::Debug) {}
    }
    let mut v = V::default();
    attrs.record(&mut v);
    v.0
}

/// The `correlation_id` string span field carried by every event that records it. Empty means the
/// caller did not supply one.
pub(crate) const CORRELATION_ID_FIELD: &str = "correlation_id";

/// Extract the optional caller-supplied correlation id from span attributes; empty or absent
/// yields `None`.
pub(crate) fn correlation_id_from_attrs(attrs: &Attributes<'_>) -> Option<Arc<str>> {
    #[derive(Default)]
    struct CorrelationIdVisitor(Option<Arc<str>>);
    impl Visit for CorrelationIdVisitor {
        fn record_str(&mut self, field: &Field, value: &str) {
            if field.name() == CORRELATION_ID_FIELD && !value.is_empty() {
                self.0 = Some(value.into());
            }
        }
        fn record_debug(&mut self, _field: &Field, _value: &dyn fmt::Debug) {}
    }
    let mut v = CorrelationIdVisitor::default();
    attrs.record(&mut v);
    v.0
}

/// A `parallel_scan_metadata` scan emits **two** events (one per phase) sharing the same
/// `operation_id`; `scan_metadata` emits one event with [`ScanType::Full`].
#[derive(Debug, Clone)]
pub struct ScanMetadataCompleted {
    // === Set on span creation ===
    /// Unique ID to correlate this scan with other events.
    pub operation_id: MetricId,
    /// Opaque, caller-supplied id for joining this operation's metric events to the caller's
    /// own request or operation id.
    pub correlation_id: Option<Arc<str>>,
    /// Whether the scanned table is path-based or catalog-managed.
    pub table_type: TableType,
    /// Which scan execution path produced this event.
    pub scan_type: ScanType,
    /// Wall-clock time from scan start to iterator exhaustion.
    pub duration: Duration,
    /// Add files that entered deduplication (excludes files filtered by data skipping).
    pub num_add_files_seen: u64,
    /// Add files that survived log replay (the files the connector reads).
    pub num_active_add_files: u64,
    /// Size in bytes of the files that survived log replay (files to read).
    pub active_add_files_bytes: u64,
    /// Remove files seen (from delta/commit files only).
    pub num_remove_files_seen: u64,
    /// Non-file actions seen (protocol, metadata, etc.).
    pub num_non_file_actions: u64,
    /// Files filtered by predicates (data skipping + partition pruning).
    pub num_predicate_filtered: u64,
    /// Peak size of the deduplication hash set.
    pub peak_hash_set_size: usize,
    /// Time spent in the deduplication visitor (milliseconds).
    pub dedup_visitor_time_ms: u64,
    /// Time spent evaluating predicates (milliseconds).
    pub predicate_eval_time_ms: u64,
}

impl ScanMetadataCompleted {
    pub(crate) const SPAN_NAME: &'static str = "scan.metadata_completed";

    pub(crate) fn from_attrs(attrs: &Attributes<'_>) -> Self {
        let mut v = ScanMetadataCompletedAttrs::default();
        attrs.record(&mut v);
        Self {
            operation_id: MetricId(v.operation_id),
            table_type: TableType::from_catalog_managed(v.is_catalog_managed),
            correlation_id: v.correlation_id,
            scan_type: ScanType::parse_lenient(&v.scan_type),
            duration: Duration::from_nanos(v.duration_ns),
            num_add_files_seen: v.num_add_files_seen,
            num_active_add_files: v.num_active_add_files,
            active_add_files_bytes: v.active_add_files_bytes,
            num_remove_files_seen: v.num_remove_files_seen,
            num_non_file_actions: v.num_non_file_actions,
            num_predicate_filtered: v.num_predicate_filtered,
            peak_hash_set_size: v.peak_hash_set_size as usize,
            dedup_visitor_time_ms: v.dedup_visitor_time_ms,
            predicate_eval_time_ms: v.predicate_eval_time_ms,
        }
    }
}

impl fmt::Display for ScanMetadataCompleted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            operation_id,
            table_type,
            correlation_id,
            scan_type,
            duration,
            num_add_files_seen,
            num_active_add_files,
            active_add_files_bytes,
            num_remove_files_seen,
            num_non_file_actions,
            num_predicate_filtered,
            peak_hash_set_size,
            dedup_visitor_time_ms,
            predicate_eval_time_ms,
        } = self;
        write!(
            f,
            "ScanMetadataCompleted(id={operation_id}, table_type={table_type}, \
             correlation_id={correlation_id:?}, scan_type={scan_type}, duration={duration:?}, \
             add_files_seen={num_add_files_seen}, active_add_files={num_active_add_files}, \
             active_add_files_bytes={active_add_files_bytes}, \
             remove_files_seen={num_remove_files_seen}, non_file_actions={num_non_file_actions}, \
             predicate_filtered={num_predicate_filtered}, peak_hash_set_size={peak_hash_set_size}, \
             dedup_visitor_time_ms={dedup_visitor_time_ms}, predicate_eval_time_ms={predicate_eval_time_ms})"
        )
    }
}

#[derive(Default)]
struct ScanMetadataCompletedAttrs {
    operation_id: Uuid,
    is_catalog_managed: bool,
    correlation_id: Option<Arc<str>>,
    scan_type: String,
    duration_ns: u64,
    num_add_files_seen: u64,
    num_active_add_files: u64,
    active_add_files_bytes: u64,
    num_remove_files_seen: u64,
    num_non_file_actions: u64,
    num_predicate_filtered: u64,
    peak_hash_set_size: u64,
    dedup_visitor_time_ms: u64,
    predicate_eval_time_ms: u64,
}

impl Visit for ScanMetadataCompletedAttrs {
    fn record_bool(&mut self, field: &Field, value: bool) {
        if field.name() == IS_CATALOG_MANAGED_FIELD {
            self.is_catalog_managed = value;
        }
    }

    fn record_str(&mut self, field: &Field, value: &str) {
        if field.name() == CORRELATION_ID_FIELD && !value.is_empty() {
            self.correlation_id = Some(value.into());
        }
    }

    fn record_u64(&mut self, field: &Field, value: u64) {
        match field.name() {
            "duration_ns" => self.duration_ns = value,
            "num_add_files_seen" => self.num_add_files_seen = value,
            "num_active_add_files" => self.num_active_add_files = value,
            "active_add_files_bytes" => self.active_add_files_bytes = value,
            "num_remove_files_seen" => self.num_remove_files_seen = value,
            "num_non_file_actions" => self.num_non_file_actions = value,
            "num_predicate_filtered" => self.num_predicate_filtered = value,
            "peak_hash_set_size" => self.peak_hash_set_size = value,
            "dedup_visitor_time_ms" => self.dedup_visitor_time_ms = value,
            "predicate_eval_time_ms" => self.predicate_eval_time_ms = value,
            _ => {}
        }
    }

    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        let s = format!("{value:?}");
        match field.name() {
            "operation_id" => match Uuid::from_str(&s) {
                Ok(u) => self.operation_id = u,
                Err(e) => warn!(
                    "Invalid uuid '{s}' on {}: {e}",
                    ScanMetadataCompleted::SPAN_NAME
                ),
            },
            "scan_type" => self.scan_type = s,
            _ => {}
        }
    }
}

// ====================================================================
// Storage events (List / Read / Copy)
// ====================================================================
//
// All three storage events share the `STORAGE_SPAN` span name and distinguish themselves via
// a `name=` field carrying one of `<event>::NAME`. The shared [`storage_metric_from_attrs`]
// helper inspects the `name` value and constructs the matching variant.

pub(crate) const STORAGE_SPAN: &str = "storage";

/// Build the appropriate storage `MetricEvent` from the span attributes. Returns `None` if the
/// `name` field is missing or unknown.
pub(crate) fn storage_metric_from_attrs(attrs: &Attributes<'_>) -> Option<MetricEvent> {
    let mut v = StorageAttrs::default();
    attrs.record(&mut v);
    let duration = Duration::from_nanos(v.duration_ns);
    match v.kind {
        StorageKind::List => Some(MetricEvent::StorageListCompleted(StorageListCompleted {
            duration,
            num_files: v.num_files,
        })),
        StorageKind::Read => Some(MetricEvent::StorageReadCompleted(StorageReadCompleted {
            duration,
            num_files: v.num_files,
            bytes_read: v.bytes_read,
        })),
        StorageKind::Copy => Some(MetricEvent::StorageCopyCompleted(StorageCopyCompleted {
            duration,
        })),
        StorageKind::Unknown => None,
    }
}

#[derive(Default)]
enum StorageKind {
    #[default]
    Unknown,
    List,
    Read,
    Copy,
}

#[derive(Default)]
struct StorageAttrs {
    kind: StorageKind,
    num_files: u64,
    bytes_read: u64,
    duration_ns: u64,
}

impl Visit for StorageAttrs {
    fn record_str(&mut self, field: &Field, value: &str) {
        if field.name() == "name" {
            self.kind = match value {
                StorageListCompleted::NAME => StorageKind::List,
                StorageReadCompleted::NAME => StorageKind::Read,
                StorageCopyCompleted::NAME => StorageKind::Copy,
                _ => {
                    warn!("Storage span with unknown name: {value}");
                    StorageKind::Unknown
                }
            };
        }
    }

    fn record_u64(&mut self, field: &Field, value: u64) {
        match field.name() {
            "num_files" => self.num_files = value,
            "bytes_read" => self.bytes_read = value,
            "duration_ns" => self.duration_ns = value,
            _ => {}
        }
    }

    fn record_debug(&mut self, _field: &Field, _value: &dyn fmt::Debug) {}
}

// ============================
// StorageListCompleted
// ============================

/// A storage list operation completed.
#[derive(Debug, Clone)]
pub struct StorageListCompleted {
    // === Set on span creation ===
    pub duration: Duration,
    pub num_files: u64,
}

impl StorageListCompleted {
    pub(crate) const NAME: &'static str = "list_completed";
}

impl fmt::Display for StorageListCompleted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            duration,
            num_files,
        } = self;
        write!(
            f,
            "StorageListCompleted(duration={duration:?}, files={num_files})"
        )
    }
}

// ============================
// StorageReadCompleted
// ============================

/// A storage read operation completed.
#[derive(Debug, Clone)]
pub struct StorageReadCompleted {
    // === Set on span creation ===
    pub duration: Duration,
    pub num_files: u64,
    pub bytes_read: u64,
}

impl StorageReadCompleted {
    pub(crate) const NAME: &'static str = "read_completed";
}

impl fmt::Display for StorageReadCompleted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self {
            duration,
            num_files,
            bytes_read,
        } = self;
        write!(
            f,
            "StorageReadCompleted(duration={duration:?}, files={num_files}, bytes={bytes_read})"
        )
    }
}

// ============================
// StorageCopyCompleted
// ============================

/// A storage copy or rename operation completed.
#[derive(Debug, Clone)]
pub struct StorageCopyCompleted {
    // === Set on span creation ===
    pub duration: Duration,
}

impl StorageCopyCompleted {
    pub(crate) const NAME: &'static str = "copy_completed";
}

impl fmt::Display for StorageCopyCompleted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self { duration } = self;
        write!(f, "StorageCopyCompleted(duration={duration:?})")
    }
}

// ====================================================================
// emit_* helpers
// ====================================================================
//
// Fire a tracing span carrying a pre-built event payload. Used by the scan metadata emission
// site (which constructs the event up front) and by connector-side `JsonHandler` /
// `ParquetHandler` implementations that want to report read metrics.

/// Emit a [`MetricEvent::JsonReadCompleted`] via a tracing span.
///
/// Call once per [`crate::JsonHandler::read_json_files`] invocation, at iterator exhaustion or
/// drop.
pub fn emit_json_read_completed(num_files: u64, bytes_read: u64) {
    let _span = tracing::span!(
        tracing::Level::INFO,
        JsonReadCompleted::SPAN_NAME,
        report = tracing::field::Empty,
        num_files,
        bytes_read,
    );
}

/// Emit a [`MetricEvent::ParquetReadCompleted`] via a tracing span.
///
/// Call once per [`crate::ParquetHandler::read_parquet_files`] invocation, at iterator exhaustion
/// or drop.
pub fn emit_parquet_read_completed(num_files: u64, bytes_read: u64) {
    let _span = tracing::span!(
        tracing::Level::INFO,
        ParquetReadCompleted::SPAN_NAME,
        report = tracing::field::Empty,
        num_files,
        bytes_read,
    );
}

/// Emit a [`MetricEvent::ScanMetadataCompleted`] via a tracing span. Call when the scan metadata
/// iterator is exhausted or dropped.
pub(crate) fn emit_scan_metadata_completed(e: &ScanMetadataCompleted) {
    let _span = tracing::span!(
        tracing::Level::INFO,
        ScanMetadataCompleted::SPAN_NAME,
        report = tracing::field::Empty,
        operation_id = %e.operation_id,
        is_catalog_managed = e.table_type.is_catalog_managed(),
        correlation_id = e.correlation_id.as_deref().unwrap_or(""),
        scan_type = %e.scan_type,
        duration_ns = e.duration.as_nanos() as u64,
        num_add_files_seen = e.num_add_files_seen,
        num_active_add_files = e.num_active_add_files,
        active_add_files_bytes = e.active_add_files_bytes,
        num_remove_files_seen = e.num_remove_files_seen,
        num_non_file_actions = e.num_non_file_actions,
        num_predicate_filtered = e.num_predicate_filtered,
        peak_hash_set_size = e.peak_hash_set_size as u64,
        dedup_visitor_time_ms = e.dedup_visitor_time_ms,
        predicate_eval_time_ms = e.predicate_eval_time_ms,
    );
}

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

    use super::*;

    fn commit_success(operation_id: MetricId) -> TransactionCommitSuccess {
        TransactionCommitSuccess {
            operation_id,
            table_type: TableType::PathBased,
            correlation_id: None,
            commit_version: 1,
            num_add_files: 0,
            num_remove_files: 0,
            num_dv_updates: 0,
            add_files_bytes: 0,
            remove_files_bytes: 0,
            is_blind_append: false,
            data_change: false,
            operation: None,
            prepare_duration: Duration::default(),
            committer_duration: Duration::default(),
            total_duration: Duration::default(),
        }
    }

    #[rstest]
    #[case::conflict("conflict", CommitFailureReason::Conflict)]
    #[case::retryable_io("retryable_io", CommitFailureReason::RetryableIo)]
    #[case::error("error", CommitFailureReason::Error)]
    #[case::unknown_defaults_to_error("totally_unknown", CommitFailureReason::Error)]
    fn record_str_failure_reason_flips_to_expected_reason(
        #[case] value: &str,
        #[case] expected: CommitFailureReason,
    ) {
        let id = MetricId::new();
        let mut event = MetricEvent::TransactionCommitSuccess(commit_success(id));
        event.record_str("failure_reason", value).unwrap();
        let MetricEvent::TransactionCommitFailure(failure) = event else {
            panic!("expected TransactionCommitFailure");
        };
        assert_eq!(failure.operation_id, id);
        assert_eq!(failure.reason, expected);
    }

    #[test]
    fn record_str_operation_sets_field_without_flipping() {
        let mut event = MetricEvent::TransactionCommitSuccess(commit_success(MetricId::new()));
        event.record_str("operation", "WRITE").unwrap();
        let MetricEvent::TransactionCommitSuccess(success) = event else {
            panic!("expected TransactionCommitSuccess");
        };
        assert_eq!(success.operation.as_deref(), Some("WRITE"));
    }

    #[test]
    fn record_u64_num_dv_updates_sets_field() {
        let mut event = MetricEvent::TransactionCommitSuccess(commit_success(MetricId::new()));
        event.record_u64("num_dv_updates", 7).unwrap();
        let MetricEvent::TransactionCommitSuccess(success) = event else {
            panic!("expected TransactionCommitSuccess");
        };
        assert_eq!(success.num_dv_updates, 7);
    }

    #[rstest]
    #[case::conflict(CommitFailureReason::Conflict, "conflict")]
    #[case::retryable_io(CommitFailureReason::RetryableIo, "retryable_io")]
    #[case::error(CommitFailureReason::Error, "error")]
    fn commit_failure_reason_serializes_to_wire_name_and_parses_back(
        #[case] reason: CommitFailureReason,
        #[case] wire: &str,
    ) {
        let serialized: &'static str = reason.into();
        assert_eq!(serialized, wire);
        assert_eq!(CommitFailureReason::from_str(wire).unwrap(), reason);
    }

    #[rstest]
    #[case::sequential(ScanType::SequentialPhase, "sequential")]
    #[case::parallel(ScanType::ParallelPhase, "parallel")]
    #[case::full(ScanType::Full, "full")]
    fn scan_type_serializes_to_wire_name_and_parses_back(
        #[case] scan_type: ScanType,
        #[case] wire: &str,
    ) {
        let serialized: &'static str = scan_type.into();
        assert_eq!(serialized, wire);
        assert_eq!(ScanType::from_str(wire).unwrap(), scan_type);
    }

    #[rstest]
    #[case::known("parallel", ScanType::ParallelPhase)]
    #[case::unknown_defaults_to_full("totally_unknown", ScanType::Full)]
    fn scan_type_parse_lenient_maps_unknown_to_full(
        #[case] value: &str,
        #[case] expected: ScanType,
    ) {
        assert_eq!(ScanType::parse_lenient(value), expected);
    }

    #[test]
    fn into_failure_maps_commit_success_to_error_reason() {
        let id = MetricId::new();
        let failure = MetricEvent::TransactionCommitSuccess(commit_success(id)).into_failure();
        let MetricEvent::TransactionCommitFailure(failure) = failure else {
            panic!("expected TransactionCommitFailure");
        };
        assert_eq!(failure.operation_id, id);
        assert_eq!(failure.reason, CommitFailureReason::Error);
    }

    #[test]
    fn record_str_failure_reason_flip_preserves_correlation_id() {
        let mut success = commit_success(MetricId::new());
        success.correlation_id = Some("commit-req-1".into());
        let mut event = MetricEvent::TransactionCommitSuccess(success);
        event.record_str("failure_reason", "conflict").unwrap();
        let MetricEvent::TransactionCommitFailure(failure) = event else {
            panic!("expected TransactionCommitFailure");
        };
        assert_eq!(failure.correlation_id.as_deref(), Some("commit-req-1"));
    }

    #[test]
    fn into_failure_preserves_correlation_id() {
        let mut success = commit_success(MetricId::new());
        success.correlation_id = Some("commit-req-2".into());
        let MetricEvent::TransactionCommitFailure(failure) =
            MetricEvent::TransactionCommitSuccess(success).into_failure()
        else {
            panic!("expected TransactionCommitFailure");
        };
        assert_eq!(failure.correlation_id.as_deref(), Some("commit-req-2"));

        let snapshot = SnapshotBuildSuccess {
            operation_id: MetricId::new(),
            table_type: TableType::PathBased,
            correlation_id: Some("snap-req-3".into()),
            version: 0,
            duration: Duration::default(),
        };
        let MetricEvent::SnapshotBuildFailure(failure) =
            MetricEvent::SnapshotBuildSuccess(snapshot).into_failure()
        else {
            panic!("expected SnapshotBuildFailure");
        };
        assert_eq!(failure.correlation_id.as_deref(), Some("snap-req-3"));
    }
}