proofframe 0.4.0-alpha.4

Rust-native Arrow data contracts, canonical fingerprints, and proof receipts
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
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
#![forbid(unsafe_code)]
//! Native ProofFrame engine for Arrow-backed data contracts.
//!
//! The crate exposes a Rust-native API by default. The Python extension module is available behind
//! the `python` feature and is enabled by the PyPI build configuration. Core invariants are stable
//! enough to publish as an alpha: `pf-fp-v1` canonical dataset fingerprints, disk-backed exact
//! keyed diffs, privacy-preserving PII findings, leakage checks, and signed proof receipts.

mod error;
mod pii;
pub mod receipt;

pub use error::ProofFrameError;

use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};

use ahash::RandomState;
use arrow::array::{
    Array, BinaryArray, BooleanArray, Date32Array, Date64Array, Decimal128Array,
    FixedSizeListArray, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Int64Array,
    LargeBinaryArray, LargeListArray, LargeStringArray, ListArray, MapArray, RecordBatch,
    StringArray, StructArray, TimestampMicrosecondArray, TimestampMillisecondArray,
    TimestampNanosecondArray, TimestampSecondArray, UInt8Array, UInt16Array, UInt32Array,
    UInt64Array,
};
#[cfg(feature = "python")]
use arrow::ffi_stream::ArrowArrayStreamReader;
#[cfg(feature = "python")]
use arrow::pyarrow::PyArrowType;
use arrow::record_batch::RecordBatchReader;
use arrow::util::display::array_value_to_string;
#[cfg(feature = "python")]
use pyo3::exceptions::PyValueError;
#[cfg(feature = "python")]
use pyo3::prelude::*;
use regex::Regex;
use serde::{Deserialize, Serialize};
use tempfile::TempDir;

const DEFAULT_MAX_FINDINGS: usize = 100;
const DIFF_PARTITIONS: usize = 64;

type RowValues = Vec<Option<Vec<u8>>>;
struct RowEntry {
    display_key: String,
    values: RowValues,
    hash: String,
}

#[derive(Debug, Eq, PartialEq)]
struct ColumnSchema {
    name: String,
    data_type: String,
    nullable: bool,
}

/// Per-column summary produced while profiling a dataset.
#[derive(Debug, Serialize)]
pub struct ColumnProfile {
    /// Column name as declared in the Arrow schema.
    pub name: String,
    /// Arrow data type rendered as a stable string.
    pub data_type: String,
    /// Number of null values observed in the column.
    pub null_count: u64,
    /// Number of non-null values observed in the column.
    pub non_null_count: u64,
    /// Count of distinct canonical values seen in the column, when exact distinct is enabled.
    pub distinct_count: Option<usize>,
    /// Minimum numeric value, when the column parses as a number.
    pub min: Option<f64>,
    /// Maximum numeric value, when the column parses as a number.
    pub max: Option<f64>,
}

struct ColumnState {
    null_count: u64,
    non_null_count: u64,
    distinct: Option<HashSet<Vec<u8>>>,
    min: Option<f64>,
    max: Option<f64>,
}

impl ColumnState {
    fn new(distinct_mode: DistinctMode) -> Self {
        Self {
            null_count: 0,
            non_null_count: 0,
            distinct: match distinct_mode {
                DistinctMode::None => None,
                DistinctMode::Exact => Some(HashSet::new()),
            },
            min: None,
            max: None,
        }
    }
}

/// Exact distinct counting can dominate large profiles, so callers can opt out.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum DistinctMode {
    None,
    Exact,
}

impl DistinctMode {
    pub fn from_name(value: &str) -> Result<Self, ProofFrameError> {
        match value {
            "none" => Ok(Self::None),
            "exact" => Ok(Self::Exact),
            other => Err(ProofFrameError::InvalidContract(format!(
                "Unsupported distinct mode `{other}`; expected `none` or `exact`"
            ))),
        }
    }
}

/// Deterministic dataset profile with a canonical content fingerprint.
#[derive(Debug, Serialize)]
pub struct Profile {
    /// Total number of rows scanned across all record batches.
    pub rows: u64,
    /// Per-column profiles in schema order.
    pub columns: Vec<ColumnProfile>,
    /// `pf-fp-v1`-tagged BLAKE3 fingerprint of the ordered data.
    pub fingerprint: String,
}

/// Validation contract: per-column rules plus a bound on emitted findings.
#[derive(Debug, Deserialize, Default)]
pub struct Contract {
    /// Column name to its rule set.
    #[serde(default)]
    pub columns: HashMap<String, ColumnContract>,
    /// Maximum number of findings to retain; the true count is still reported.
    #[serde(default = "default_max_findings")]
    pub max_findings: usize,
}

fn default_max_findings() -> usize {
    DEFAULT_MAX_FINDINGS
}

/// Rule set applied to a single column during validation.
#[derive(Debug, Deserialize, Default)]
pub struct ColumnContract {
    /// Require the column to be present in the schema.
    #[serde(default)]
    pub required: bool,
    /// Reject null values in the column.
    #[serde(default)]
    pub not_null: bool,
    /// Reject duplicate values in the column.
    #[serde(default)]
    pub unique: bool,
    /// Inclusive lower bound for numeric values.
    pub min: Option<f64>,
    /// Inclusive upper bound for numeric values.
    pub max: Option<f64>,
    /// Regular expression each value must match.
    pub pattern: Option<String>,
    /// Allowlist the value must belong to.
    pub allowed: Option<HashSet<String>>,
}

/// A single rule violation with bounded, row-level evidence.
#[derive(Debug, Serialize)]
pub struct Finding {
    /// Rule that produced the finding (for example `not_null` or `unique`).
    pub rule: &'static str,
    /// Column the finding applies to.
    pub column: String,
    /// Zero-based row index, or `None` for schema-level findings.
    pub row: Option<u64>,
    /// Human-readable description of the violation.
    pub message: String,
}

/// Full validation result: findings plus the dataset profile and fingerprint.
#[derive(Debug, Serialize)]
pub struct ValidationReport {
    /// `true` when no violations were found.
    pub valid: bool,
    /// Total number of violations, even if `findings` was truncated.
    pub violation_count: u64,
    /// `true` when `findings` was capped by the contract's `max_findings`.
    pub truncated: bool,
    /// Bounded list of individual findings.
    pub findings: Vec<Finding>,
    /// Dataset profile and canonical fingerprint from the same pass.
    pub profile: Profile,
}

/// Rules-only validation result that skips profiling and fingerprinting.
#[derive(Debug, Serialize)]
pub struct FastValidationReport {
    /// `true` when no violations were found.
    pub valid: bool,
    /// Total number of violations, even if `findings` was truncated.
    pub violation_count: u64,
    /// `true` when `findings` was capped by the contract's `max_findings`.
    pub truncated: bool,
    /// Bounded list of individual findings.
    pub findings: Vec<Finding>,
    /// Total number of rows scanned.
    pub rows: u64,
    /// Evaluation mode identifier (`rules_only`).
    pub mode: &'static str,
}

struct ValidationOutcome {
    findings: Vec<Finding>,
    violation_count: u64,
    truncated: bool,
}

struct ValidationState {
    findings: Vec<Finding>,
    violation_count: u64,
    max_findings: usize,
}

impl ValidationState {
    fn new(max_findings: usize) -> Self {
        Self {
            findings: Vec::new(),
            violation_count: 0,
            max_findings,
        }
    }

    fn record(&mut self, finding: Finding) {
        self.violation_count += 1;
        if self.findings.len() < self.max_findings {
            self.findings.push(finding);
        }
    }

    fn finish(self) -> ValidationOutcome {
        ValidationOutcome {
            truncated: self.violation_count as usize > self.findings.len(),
            violation_count: self.violation_count,
            findings: self.findings,
        }
    }
}

enum UniqueState {
    SignedInt(HashSet<i64, RandomState>),
    UnsignedInt(HashSet<u64, RandomState>),
    Timestamp(HashSet<i64, RandomState>),
    Float32(HashSet<u32, RandomState>),
    Float64(HashSet<u64, RandomState>),
    Utf8(HashSet<String, RandomState>),
    Generic(HashSet<Vec<u8>, RandomState>),
}

impl UniqueState {
    fn for_array(array: &dyn Array) -> Self {
        if array.as_any().is::<Int8Array>()
            || array.as_any().is::<Int16Array>()
            || array.as_any().is::<Int32Array>()
            || array.as_any().is::<Int64Array>()
        {
            Self::SignedInt(HashSet::with_hasher(RandomState::new()))
        } else if array.as_any().is::<UInt8Array>()
            || array.as_any().is::<UInt16Array>()
            || array.as_any().is::<UInt32Array>()
            || array.as_any().is::<UInt64Array>()
        {
            Self::UnsignedInt(HashSet::with_hasher(RandomState::new()))
        } else if array.as_any().is::<TimestampSecondArray>()
            || array.as_any().is::<TimestampMillisecondArray>()
            || array.as_any().is::<TimestampMicrosecondArray>()
            || array.as_any().is::<TimestampNanosecondArray>()
        {
            Self::Timestamp(HashSet::with_hasher(RandomState::new()))
        } else if array.as_any().is::<Float32Array>() {
            Self::Float32(HashSet::with_hasher(RandomState::new()))
        } else if array.as_any().is::<Float64Array>() {
            Self::Float64(HashSet::with_hasher(RandomState::new()))
        } else if array.as_any().is::<StringArray>() {
            Self::Utf8(HashSet::with_hasher(RandomState::new()))
        } else {
            Self::Generic(HashSet::with_hasher(RandomState::new()))
        }
    }
}

/// A row present in both datasets whose values changed.
#[derive(Debug, Serialize)]
pub struct ChangedRow {
    /// Human-readable business key of the changed row.
    pub key: String,
    /// Names of the columns whose values differ.
    pub columns: Vec<String>,
}

/// Exact keyed diff between two datasets.
#[derive(Debug, Serialize)]
pub struct DiffReport {
    /// Business key columns used to align rows.
    pub keys: Vec<String>,
    /// Row count of the "before" dataset.
    pub before_rows: usize,
    /// Row count of the "after" dataset.
    pub after_rows: usize,
    /// Number of keys present only in "after".
    pub added_count: usize,
    /// Number of keys present only in "before".
    pub removed_count: usize,
    /// Number of keys present in both with differing values.
    pub changed_count: usize,
    /// Sorted keys present only in "after".
    pub added_keys: Vec<String>,
    /// Sorted keys present only in "before".
    pub removed_keys: Vec<String>,
    /// Per-key column-level changes, sorted by key.
    pub changed: Vec<ChangedRow>,
}

/// A single PII detection that never carries the matched value.
#[derive(Debug, Serialize)]
pub struct PiiFinding {
    /// Detected PII class (for example `email` or `payment_card`).
    pub kind: &'static str,
    /// Detector confidence (`high` or `medium`).
    pub confidence: &'static str,
    /// Column the value was found in.
    pub column: String,
    /// Zero-based row index of the value.
    pub row: u64,
    /// Domain-separated BLAKE3 fingerprint of the value, never the value itself.
    pub value_fingerprint: String,
}

/// Aggregated PII scan result with bounded per-cell findings.
#[derive(Debug, Serialize)]
pub struct PiiReport {
    /// `true` when at least one PII value was detected.
    pub detected: bool,
    /// Total number of rows scanned.
    pub scanned_rows: u64,
    /// Total number of PII detections, even if `findings` was truncated.
    pub finding_count: usize,
    /// Detection counts grouped by PII class.
    pub counts_by_kind: BTreeMap<&'static str, usize>,
    /// `true` when `findings` was capped by `max_findings`.
    pub truncated: bool,
    /// Bounded list of individual detections.
    pub findings: Vec<PiiFinding>,
}

/// Train/test overlap result that exposes only hashed sample identifiers.
#[derive(Debug, Serialize)]
pub struct LeakageReport {
    /// `true` when any overlap was found between the two datasets.
    pub detected: bool,
    /// Detection mode: `key` for keyed overlap or `full_row` for exact rows.
    pub mode: &'static str,
    /// Key columns used for overlap, empty in full-row mode.
    pub keys: Vec<String>,
    /// Number of rows in the train dataset.
    pub train_rows: usize,
    /// Number of rows in the test dataset.
    pub test_rows: usize,
    /// Number of overlapping identities.
    pub overlap_count: usize,
    /// Overlap as a fraction of distinct train identities.
    pub train_overlap_rate: f64,
    /// Overlap as a fraction of distinct test identities.
    pub test_overlap_rate: f64,
    /// Sorted, bounded sample of hashed overlapping identifiers.
    pub sample_fingerprints: Vec<String>,
    /// `true` when the sample list was capped by `max_samples`.
    pub truncated: bool,
}

#[cfg(feature = "python")]
fn py_err(error: impl std::fmt::Display) -> PyErr {
    PyValueError::new_err(error.to_string())
}

fn update_len_prefixed(hasher: &mut blake3::Hasher, value: &[u8]) {
    hasher.update(&(value.len() as u64).to_le_bytes());
    hasher.update(value);
}

fn update_schema_hash(hasher: &mut blake3::Hasher, name: &str, data_type: &str, nullable: bool) {
    hasher.update(b"pf-schema-field-v1\0");
    update_len_prefixed(hasher, name.as_bytes());
    update_len_prefixed(hasher, data_type.as_bytes());
    hasher.update(&[u8::from(nullable)]);
}

fn canonical_value_bytes(array: &dyn Array, row: usize) -> Result<Vec<u8>, ProofFrameError> {
    if array.is_null(row) {
        return Ok(vec![0]);
    }

    macro_rules! primitive_bytes {
        ($array_ty:ty, $tag:literal) => {
            if let Some(values) = array.as_any().downcast_ref::<$array_ty>() {
                let mut encoded = Vec::with_capacity(1 + 16);
                encoded.push($tag);
                encoded.extend_from_slice(&values.value(row).to_le_bytes());
                return Ok(encoded);
            }
        };
    }

    primitive_bytes!(Int8Array, 1);
    primitive_bytes!(Int16Array, 2);
    primitive_bytes!(Int32Array, 3);
    primitive_bytes!(Int64Array, 4);
    primitive_bytes!(UInt8Array, 5);
    primitive_bytes!(UInt16Array, 6);
    primitive_bytes!(UInt32Array, 7);
    primitive_bytes!(UInt64Array, 8);
    primitive_bytes!(Float32Array, 9);
    primitive_bytes!(Float64Array, 10);
    primitive_bytes!(Date32Array, 11);
    primitive_bytes!(Date64Array, 12);
    primitive_bytes!(TimestampSecondArray, 13);
    primitive_bytes!(TimestampMillisecondArray, 14);
    primitive_bytes!(TimestampMicrosecondArray, 15);
    primitive_bytes!(TimestampNanosecondArray, 16);
    primitive_bytes!(Decimal128Array, 17);

    if let Some(values) = array.as_any().downcast_ref::<BooleanArray>() {
        return Ok(vec![18, u8::from(values.value(row))]);
    }
    if let Some(values) = array.as_any().downcast_ref::<StringArray>() {
        let value = values.value(row).as_bytes();
        let mut encoded = Vec::with_capacity(9 + value.len());
        encoded.push(19);
        encoded.extend_from_slice(&(value.len() as u64).to_le_bytes());
        encoded.extend_from_slice(value);
        return Ok(encoded);
    }
    if let Some(values) = array.as_any().downcast_ref::<LargeStringArray>() {
        let value = values.value(row).as_bytes();
        let mut encoded = Vec::with_capacity(9 + value.len());
        encoded.push(20);
        encoded.extend_from_slice(&(value.len() as u64).to_le_bytes());
        encoded.extend_from_slice(value);
        return Ok(encoded);
    }
    if let Some(values) = array.as_any().downcast_ref::<BinaryArray>() {
        let value = values.value(row);
        let mut encoded = Vec::with_capacity(9 + value.len());
        encoded.push(21);
        encoded.extend_from_slice(&(value.len() as u64).to_le_bytes());
        encoded.extend_from_slice(value);
        return Ok(encoded);
    }
    if let Some(values) = array.as_any().downcast_ref::<LargeBinaryArray>() {
        let value = values.value(row);
        let mut encoded = Vec::with_capacity(9 + value.len());
        encoded.push(22);
        encoded.extend_from_slice(&(value.len() as u64).to_le_bytes());
        encoded.extend_from_slice(value);
        return Ok(encoded);
    }

    // Nested types recurse into their children. Element counts and per-element
    // length prefixes keep boundaries unambiguous, and each nested kind carries a
    // distinct tag so a one-element list cannot collide with its bare element.
    if let Some(values) = array.as_any().downcast_ref::<ListArray>() {
        return encode_child_sequence(23, values.value(row).as_ref());
    }
    if let Some(values) = array.as_any().downcast_ref::<LargeListArray>() {
        return encode_child_sequence(24, values.value(row).as_ref());
    }
    if let Some(values) = array.as_any().downcast_ref::<FixedSizeListArray>() {
        return encode_child_sequence(25, values.value(row).as_ref());
    }
    if let Some(values) = array.as_any().downcast_ref::<StructArray>() {
        let mut encoded = vec![26];
        encoded.extend_from_slice(&(values.num_columns() as u64).to_le_bytes());
        for column in values.columns() {
            let element = canonical_value_bytes(column.as_ref(), row)?;
            encoded.extend_from_slice(&(element.len() as u64).to_le_bytes());
            encoded.extend_from_slice(&element);
        }
        return Ok(encoded);
    }
    if let Some(values) = array.as_any().downcast_ref::<MapArray>() {
        // A map row is a struct array of {key, value} entries in physical order.
        return encode_child_sequence(27, &values.value(row));
    }

    Err(ProofFrameError::UnsupportedType(
        array.data_type().to_string(),
    ))
}

/// Encode every element of a nested child array with a tag, an element count,
/// and per-element length prefixes.
fn encode_child_sequence(tag: u8, child: &dyn Array) -> Result<Vec<u8>, ProofFrameError> {
    let mut encoded = vec![tag];
    encoded.extend_from_slice(&(child.len() as u64).to_le_bytes());
    for index in 0..child.len() {
        let element = canonical_value_bytes(child, index)?;
        encoded.extend_from_slice(&(element.len() as u64).to_le_bytes());
        encoded.extend_from_slice(&element);
    }
    Ok(encoded)
}

fn value_for_rules(array: &dyn Array, row: usize) -> Result<String, ProofFrameError> {
    array_value_to_string(array, row).map_err(Into::into)
}

fn update_hash(
    hasher: &mut blake3::Hasher,
    column: usize,
    array: &dyn Array,
    row: usize,
) -> Result<(), ProofFrameError> {
    hasher.update(b"pf-cell-v1\0");
    hasher.update(&(column as u64).to_le_bytes());
    let encoded = canonical_value_bytes(array, row)?;
    update_len_prefixed(hasher, &encoded);
    Ok(())
}

fn row_values_hash(values: &RowValues) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"pf-diff-row-v1\0");
    for (column, value) in values.iter().enumerate() {
        hasher.update(&(column as u64).to_le_bytes());
        match value {
            Some(bytes) => update_len_prefixed(&mut hasher, bytes),
            None => {
                hasher.update(&u64::MAX.to_le_bytes());
            }
        };
    }
    hasher.finalize().to_hex().to_string()
}

fn inspect_batches<R>(
    reader: R,
    contract: Option<&Contract>,
    distinct_mode: DistinctMode,
) -> Result<(Profile, ValidationOutcome), ProofFrameError>
where
    R: RecordBatchReader,
{
    let schema = reader.schema();
    let mut states = schema
        .fields()
        .iter()
        .map(|_| ColumnState::new(distinct_mode))
        .collect::<Vec<_>>();
    let mut seen_unique: HashMap<String, HashSet<Vec<u8>>> = HashMap::new();
    let mut patterns: HashMap<String, Regex> = HashMap::new();
    let max_findings = contract.map_or(DEFAULT_MAX_FINDINGS, |value| value.max_findings);
    let mut validation = ValidationState::new(max_findings);

    if let Some(contract) = contract {
        for (name, rule) in &contract.columns {
            if rule.required && schema.index_of(name).is_err() {
                validation.record(Finding {
                    rule: "required",
                    column: name.clone(),
                    row: None,
                    message: format!("Required column `{name}` is missing"),
                });
            }
            if rule.unique {
                seen_unique.insert(name.clone(), HashSet::new());
            }
            if let Some(pattern) = &rule.pattern {
                patterns.insert(name.clone(), Regex::new(pattern)?);
            }
        }
    }

    let mut rows = 0_u64;
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"pf-fp-v1\0");
    for field in schema.fields() {
        let data_type = field.data_type().to_string();
        update_schema_hash(&mut hasher, field.name(), &data_type, field.is_nullable());
    }
    hasher.update(b"pf-fp-body-v1\0");
    for maybe_batch in reader {
        let batch = maybe_batch?;
        for row in 0..batch.num_rows() {
            let global_row = rows + row as u64;
            for (column_index, array) in batch.columns().iter().enumerate() {
                let field = schema.field(column_index);
                let state = &mut states[column_index];
                if array.is_null(row) {
                    state.null_count += 1;
                    update_hash(&mut hasher, column_index, array.as_ref(), row)?;
                    if let Some(rule) = contract.and_then(|value| value.columns.get(field.name())) {
                        if rule.not_null {
                            validation.record(Finding {
                                rule: "not_null",
                                column: field.name().clone(),
                                row: Some(global_row),
                                message: "Null value is not allowed".to_string(),
                            });
                        }
                    }
                    continue;
                }

                state.non_null_count += 1;
                update_hash(&mut hasher, column_index, array.as_ref(), row)?;
                let value_key = canonical_value_bytes(array.as_ref(), row)?;
                if let Some(distinct) = &mut state.distinct {
                    distinct.insert(value_key.clone());
                }
                if let Some(number) = numeric_value(array.as_ref(), row)? {
                    state.min = Some(state.min.map_or(number, |current| current.min(number)));
                    state.max = Some(state.max.map_or(number, |current| current.max(number)));
                }

                if let Some(rule) = contract.and_then(|value| value.columns.get(field.name())) {
                    if rule.unique
                        && !seen_unique
                            .get_mut(field.name())
                            .expect("unique set initialized")
                            .insert(value_key)
                    {
                        let value = value_for_rules(array.as_ref(), row)?;
                        validation.record(Finding {
                            rule: "unique",
                            column: field.name().clone(),
                            row: Some(global_row),
                            message: format!("Duplicate value `{value}`"),
                        });
                    }
                    let numeric = if rule.min.is_some() || rule.max.is_some() {
                        numeric_value(array.as_ref(), row)?
                    } else {
                        None
                    };
                    if let Some(min) = rule.min {
                        if numeric.is_some_and(|number| number < min) {
                            let value = value_for_rules(array.as_ref(), row)?;
                            validation.record(Finding {
                                rule: "min",
                                column: field.name().clone(),
                                row: Some(global_row),
                                message: format!("Value `{value}` is below {min}"),
                            });
                        }
                    }
                    if let Some(max) = rule.max {
                        if numeric.is_some_and(|number| number > max) {
                            let value = value_for_rules(array.as_ref(), row)?;
                            validation.record(Finding {
                                rule: "max",
                                column: field.name().clone(),
                                row: Some(global_row),
                                message: format!("Value `{value}` is above {max}"),
                            });
                        }
                    }
                    if patterns.contains_key(field.name()) || rule.allowed.is_some() {
                        let value = value_for_rules(array.as_ref(), row)?;
                        if let Some(regex) = patterns.get(field.name()) {
                            if !regex.is_match(&value) {
                                validation.record(Finding {
                                    rule: "pattern",
                                    column: field.name().clone(),
                                    row: Some(global_row),
                                    message: format!(
                                        "Value `{value}` does not match `{}`",
                                        regex.as_str()
                                    ),
                                });
                            }
                        }
                        if let Some(allowed) = &rule.allowed {
                            if !allowed.contains(&value) {
                                validation.record(Finding {
                                    rule: "allowed",
                                    column: field.name().clone(),
                                    row: Some(global_row),
                                    message: format!("Value `{value}` is not in the allowlist"),
                                });
                            }
                        }
                    }
                }
            }
        }
        rows += batch.num_rows() as u64;
    }

    let columns = schema
        .fields()
        .iter()
        .zip(states)
        .map(|(field, state)| ColumnProfile {
            name: field.name().clone(),
            data_type: field.data_type().to_string(),
            null_count: state.null_count,
            non_null_count: state.non_null_count,
            distinct_count: state.distinct.as_ref().map(HashSet::len),
            min: state.min,
            max: state.max,
        })
        .collect();
    Ok((
        Profile {
            rows,
            columns,
            fingerprint: format!("pf-fp-v1:{}", hasher.finalize().to_hex()),
        },
        validation.finish(),
    ))
}

fn row_partition(key: &[u8]) -> usize {
    let digest = blake3::hash(key);
    let mut bytes = [0_u8; 8];
    bytes.copy_from_slice(&digest.as_bytes()[..8]);
    (u64::from_le_bytes(bytes) as usize) % DIFF_PARTITIONS
}

fn schema_signature<R: RecordBatchReader>(reader: &R) -> Vec<ColumnSchema> {
    reader
        .schema()
        .fields()
        .iter()
        .map(|field| ColumnSchema {
            name: field.name().clone(),
            data_type: field.data_type().to_string(),
            nullable: field.is_nullable(),
        })
        .collect()
}

fn schema_names(signature: &[ColumnSchema]) -> Vec<String> {
    signature.iter().map(|field| field.name.clone()).collect()
}

fn diff_key(
    batch: &RecordBatch,
    key_indexes: &[usize],
    row: usize,
) -> Result<(Vec<u8>, String), ProofFrameError> {
    let mut canonical = Vec::new();
    let mut display = Vec::with_capacity(key_indexes.len());
    for index in key_indexes {
        let array = batch.column(*index);
        let value = canonical_value_bytes(array.as_ref(), row)?;
        canonical.extend_from_slice(&(*index as u64).to_le_bytes());
        canonical.extend_from_slice(&(value.len() as u64).to_le_bytes());
        canonical.extend_from_slice(&value);
        if array.is_null(row) {
            display.push("<null>".to_string());
        } else {
            display.push(value_for_rules(array.as_ref(), row)?);
        }
    }
    Ok((canonical, display.join("\u{1f}")))
}

fn write_u64(writer: &mut BufWriter<File>, value: u64) -> Result<(), ProofFrameError> {
    writer.write_all(&value.to_le_bytes()).map_err(Into::into)
}

fn read_u64(reader: &mut BufReader<File>) -> Result<Option<u64>, ProofFrameError> {
    let mut bytes = [0_u8; 8];
    match reader.read_exact(&mut bytes) {
        Ok(()) => Ok(Some(u64::from_le_bytes(bytes))),
        Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => Ok(None),
        Err(error) => Err(error.into()),
    }
}

fn write_bytes(writer: &mut BufWriter<File>, value: &[u8]) -> Result<(), ProofFrameError> {
    write_u64(writer, value.len() as u64)?;
    writer.write_all(value).map_err(Into::into)
}

fn read_bytes(reader: &mut BufReader<File>) -> Result<Vec<u8>, ProofFrameError> {
    let len = read_u64(reader)?.ok_or_else(|| {
        ProofFrameError::CorruptData("Truncated diff partition record".to_string())
    })?;
    let mut value = vec![0_u8; len as usize];
    reader.read_exact(&mut value)?;
    Ok(value)
}

fn write_row_record(
    writer: &mut BufWriter<File>,
    key: &[u8],
    entry: &RowEntry,
) -> Result<(), ProofFrameError> {
    write_bytes(writer, key)?;
    write_bytes(writer, entry.display_key.as_bytes())?;
    write_bytes(writer, entry.hash.as_bytes())?;
    write_u64(writer, entry.values.len() as u64)?;
    for value in &entry.values {
        match value {
            Some(bytes) => write_bytes(writer, bytes)?,
            None => write_u64(writer, u64::MAX)?,
        }
    }
    Ok(())
}

fn read_row_record(
    reader: &mut BufReader<File>,
) -> Result<Option<(Vec<u8>, RowEntry)>, ProofFrameError> {
    let Some(key_len) = read_u64(reader)? else {
        return Ok(None);
    };
    let mut key = vec![0_u8; key_len as usize];
    reader.read_exact(&mut key)?;
    let display_key = String::from_utf8(read_bytes(reader)?)?;
    let hash = String::from_utf8(read_bytes(reader)?)?;
    let value_count = read_u64(reader)?.ok_or_else(|| {
        ProofFrameError::CorruptData("Truncated diff partition record".to_string())
    })?;
    let mut values = Vec::with_capacity(value_count as usize);
    for _ in 0..value_count {
        let len = read_u64(reader)?
            .ok_or_else(|| ProofFrameError::CorruptData("Truncated diff value".to_string()))?;
        if len == u64::MAX {
            values.push(None);
        } else {
            let mut value = vec![0_u8; len as usize];
            reader.read_exact(&mut value)?;
            values.push(Some(value));
        }
    }
    Ok(Some((
        key,
        RowEntry {
            display_key,
            values,
            hash,
        },
    )))
}

fn partition_rows<R>(
    reader: R,
    keys: &[String],
    directory: &Path,
    prefix: &str,
) -> Result<(Vec<ColumnSchema>, usize, Vec<PathBuf>), ProofFrameError>
where
    R: RecordBatchReader,
{
    let schema = reader.schema();
    let key_indexes = keys
        .iter()
        .map(|key| {
            schema
                .index_of(key)
                .map_err(|_| ProofFrameError::MissingColumn(key.clone()))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let signature = schema_signature(&reader);
    let paths = (0..DIFF_PARTITIONS)
        .map(|partition| directory.join(format!("{prefix}-{partition}.pfpart")))
        .collect::<Vec<_>>();
    let mut writers = paths
        .iter()
        .map(|path| File::create(path).map(BufWriter::new))
        .collect::<Result<Vec<_>, _>>()?;
    let mut row_count = 0_usize;
    for maybe_batch in reader {
        let batch: RecordBatch = maybe_batch?;
        for row in 0..batch.num_rows() {
            let (key, display_key) = diff_key(&batch, &key_indexes, row)?;
            let values = batch
                .columns()
                .iter()
                .map(|array| {
                    if array.is_null(row) {
                        Ok(None)
                    } else {
                        canonical_value_bytes(array.as_ref(), row).map(Some)
                    }
                })
                .collect::<Result<Vec<_>, _>>()?;
            let hash = row_values_hash(&values);
            let partition = row_partition(&key);
            write_row_record(
                &mut writers[partition],
                &key,
                &RowEntry {
                    display_key,
                    values,
                    hash,
                },
            )?;
            row_count += 1;
        }
    }
    for writer in &mut writers {
        writer.flush()?;
    }
    Ok((signature, row_count, paths))
}

fn process_diff_partition(
    before_path: &Path,
    after_path: &Path,
    column_names: &[String],
    added_keys: &mut Vec<String>,
    removed_keys: &mut Vec<String>,
    changed: &mut Vec<ChangedRow>,
) -> Result<(), ProofFrameError> {
    let mut before_rows: HashMap<Vec<u8>, RowEntry> = HashMap::new();
    let mut before_reader = BufReader::new(File::open(before_path)?);
    while let Some((key, entry)) = read_row_record(&mut before_reader)? {
        let display_key = entry.display_key.clone();
        if before_rows.insert(key, entry).is_some() {
            return Err(ProofFrameError::DuplicateKey(display_key));
        }
    }

    let mut seen_after: HashSet<Vec<u8>> = HashSet::new();
    let mut after_reader = BufReader::new(File::open(after_path)?);
    while let Some((key, entry)) = read_row_record(&mut after_reader)? {
        if !seen_after.insert(key.clone()) {
            return Err(ProofFrameError::DuplicateKey(entry.display_key.clone()));
        }
        if let Some(before_entry) = before_rows.get(&key) {
            if before_entry.hash != entry.hash {
                let columns = before_entry
                    .values
                    .iter()
                    .zip(&entry.values)
                    .zip(column_names)
                    .filter(|((before, after), _)| before != after)
                    .map(|(_, name)| name.clone())
                    .collect();
                changed.push(ChangedRow {
                    key: entry.display_key,
                    columns,
                });
            }
        } else {
            added_keys.push(entry.display_key);
        }
    }

    removed_keys.extend(before_rows.iter().filter_map(|(key, entry)| {
        if seen_after.contains(key) {
            None
        } else {
            Some(entry.display_key.clone())
        }
    }));
    Ok(())
}

fn privacy_fingerprint(value: &str) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"proofframe:privacy:v1\0");
    hasher.update(value.as_bytes());
    hasher.finalize().to_hex()[..16].to_string()
}

fn collect_leakage_ids<R>(
    reader: R,
    keys: &[String],
) -> Result<(Vec<String>, usize, HashSet<String>), ProofFrameError>
where
    R: RecordBatchReader,
{
    let schema = reader.schema();
    let names = schema
        .fields()
        .iter()
        .map(|field| field.name().clone())
        .collect::<Vec<_>>();
    let indexes = if keys.is_empty() {
        (0..schema.fields().len()).collect::<Vec<_>>()
    } else {
        keys.iter()
            .map(|key| {
                schema
                    .index_of(key)
                    .map_err(|_| ProofFrameError::MissingColumn(key.clone()))
            })
            .collect::<Result<Vec<_>, _>>()?
    };
    let mut row_count = 0_usize;
    let mut ids = HashSet::new();
    for maybe_batch in reader {
        let batch = maybe_batch?;
        for row in 0..batch.num_rows() {
            let mut hasher = blake3::Hasher::new();
            hasher.update(b"proofframe:leakage:v1\0");
            for index in &indexes {
                let array = batch.column(*index);
                update_hash(&mut hasher, *index, array.as_ref(), row)?;
            }
            ids.insert(hasher.finalize().to_hex().to_string());
            row_count += 1;
        }
    }
    Ok((names, row_count, ids))
}

fn numeric_value(array: &dyn Array, row: usize) -> Result<Option<f64>, ProofFrameError> {
    if let Some(values) = array.as_any().downcast_ref::<Float64Array>() {
        Ok(Some(values.value(row)))
    } else if let Some(values) = array.as_any().downcast_ref::<Float32Array>() {
        Ok(Some(f64::from(values.value(row))))
    } else if let Some(values) = array.as_any().downcast_ref::<Int8Array>() {
        Ok(Some(f64::from(values.value(row))))
    } else if let Some(values) = array.as_any().downcast_ref::<Int16Array>() {
        Ok(Some(f64::from(values.value(row))))
    } else if let Some(values) = array.as_any().downcast_ref::<Int32Array>() {
        Ok(Some(f64::from(values.value(row))))
    } else if let Some(values) = array.as_any().downcast_ref::<Int64Array>() {
        Ok(Some(values.value(row) as f64))
    } else if let Some(values) = array.as_any().downcast_ref::<UInt8Array>() {
        Ok(Some(f64::from(values.value(row))))
    } else if let Some(values) = array.as_any().downcast_ref::<UInt16Array>() {
        Ok(Some(f64::from(values.value(row))))
    } else if let Some(values) = array.as_any().downcast_ref::<UInt32Array>() {
        Ok(Some(f64::from(values.value(row))))
    } else if let Some(values) = array.as_any().downcast_ref::<UInt64Array>() {
        Ok(Some(values.value(row) as f64))
    } else if let Some(values) = array.as_any().downcast_ref::<TimestampSecondArray>() {
        Ok(Some(values.value(row) as f64))
    } else if let Some(values) = array.as_any().downcast_ref::<TimestampMillisecondArray>() {
        Ok(Some(values.value(row) as f64))
    } else if let Some(values) = array.as_any().downcast_ref::<TimestampMicrosecondArray>() {
        Ok(Some(values.value(row) as f64))
    } else if let Some(values) = array.as_any().downcast_ref::<TimestampNanosecondArray>() {
        Ok(Some(values.value(row) as f64))
    } else {
        Ok(None)
    }
}

fn is_numeric_array(array: &dyn Array) -> bool {
    array.as_any().is::<Int8Array>()
        || array.as_any().is::<Int16Array>()
        || array.as_any().is::<Int32Array>()
        || array.as_any().is::<Int64Array>()
        || array.as_any().is::<UInt8Array>()
        || array.as_any().is::<UInt16Array>()
        || array.as_any().is::<UInt32Array>()
        || array.as_any().is::<UInt64Array>()
        || array.as_any().is::<Float32Array>()
        || array.as_any().is::<Float64Array>()
}

fn push_duplicate(validation: &mut ValidationState, column: &str, row: u64) {
    validation.record(Finding {
        rule: "unique",
        column: column.to_string(),
        row: Some(row),
        message: "Duplicate value detected".to_string(),
    });
}

fn check_unique(
    state: &mut UniqueState,
    array: &dyn Array,
    column: &str,
    row_offset: u64,
    validation: &mut ValidationState,
) -> Result<(), ProofFrameError> {
    match state {
        UniqueState::SignedInt(seen) => {
            check_unique_signed(array, seen, column, row_offset, validation)
        }
        UniqueState::UnsignedInt(seen) => {
            check_unique_unsigned(array, seen, column, row_offset, validation)
        }
        UniqueState::Timestamp(seen) => {
            check_unique_timestamp(array, seen, column, row_offset, validation)
        }
        UniqueState::Float32(seen) => {
            let values = array
                .as_any()
                .downcast_ref::<Float32Array>()
                .expect("type fixed from schema");
            for row in 0..values.len() {
                if values.is_valid(row) && !seen.insert(values.value(row).to_bits()) {
                    push_duplicate(validation, column, row_offset + row as u64);
                }
            }
        }
        UniqueState::Float64(seen) => {
            let values = array
                .as_any()
                .downcast_ref::<Float64Array>()
                .expect("type fixed from schema");
            for row in 0..values.len() {
                if values.is_valid(row) && !seen.insert(values.value(row).to_bits()) {
                    push_duplicate(validation, column, row_offset + row as u64);
                }
            }
        }
        UniqueState::Utf8(seen) => {
            let values = array
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("type fixed from schema");
            for row in 0..values.len() {
                if values.is_valid(row) && !seen.insert(values.value(row).to_owned()) {
                    push_duplicate(validation, column, row_offset + row as u64);
                }
            }
        }
        UniqueState::Generic(seen) => {
            for row in 0..array.len() {
                if array.is_valid(row) {
                    let value = canonical_value_bytes(array, row)?;
                    if !seen.insert(value) {
                        push_duplicate(validation, column, row_offset + row as u64);
                    }
                }
            }
        }
    }
    Ok(())
}

fn check_unique_signed(
    array: &dyn Array,
    seen: &mut HashSet<i64, RandomState>,
    column: &str,
    row_offset: u64,
    validation: &mut ValidationState,
) {
    macro_rules! check {
        ($ty:ty) => {
            if let Some(values) = array.as_any().downcast_ref::<$ty>() {
                for row in 0..values.len() {
                    if values.is_valid(row) && !seen.insert(values.value(row) as i64) {
                        push_duplicate(validation, column, row_offset + row as u64);
                    }
                }
                return;
            }
        };
    }
    check!(Int8Array);
    check!(Int16Array);
    check!(Int32Array);
    check!(Int64Array);
    unreachable!("type fixed from schema");
}

fn check_unique_unsigned(
    array: &dyn Array,
    seen: &mut HashSet<u64, RandomState>,
    column: &str,
    row_offset: u64,
    validation: &mut ValidationState,
) {
    macro_rules! check {
        ($ty:ty) => {
            if let Some(values) = array.as_any().downcast_ref::<$ty>() {
                for row in 0..values.len() {
                    if values.is_valid(row) && !seen.insert(values.value(row) as u64) {
                        push_duplicate(validation, column, row_offset + row as u64);
                    }
                }
                return;
            }
        };
    }
    check!(UInt8Array);
    check!(UInt16Array);
    check!(UInt32Array);
    check!(UInt64Array);
    unreachable!("type fixed from schema");
}

fn check_unique_timestamp(
    array: &dyn Array,
    seen: &mut HashSet<i64, RandomState>,
    column: &str,
    row_offset: u64,
    validation: &mut ValidationState,
) {
    macro_rules! check {
        ($ty:ty) => {
            if let Some(values) = array.as_any().downcast_ref::<$ty>() {
                for row in 0..values.len() {
                    if values.is_valid(row) && !seen.insert(values.value(row)) {
                        push_duplicate(validation, column, row_offset + row as u64);
                    }
                }
                return;
            }
        };
    }
    check!(TimestampSecondArray);
    check!(TimestampMillisecondArray);
    check!(TimestampMicrosecondArray);
    check!(TimestampNanosecondArray);
    unreachable!("type fixed from schema");
}

fn check_range(
    array: &dyn Array,
    rule: &ColumnContract,
    column: &str,
    row_offset: u64,
    validation: &mut ValidationState,
) -> Result<(), ProofFrameError> {
    macro_rules! check_native {
        ($ty:ty, $convert:expr) => {
            if let Some(values) = array.as_any().downcast_ref::<$ty>() {
                for row in 0..values.len() {
                    if values.is_valid(row) {
                        let number = $convert(values.value(row));
                        push_range_findings(
                            number,
                            rule,
                            column,
                            row_offset + row as u64,
                            validation,
                        );
                    }
                }
                return Ok(());
            }
        };
    }
    check_native!(Float64Array, |value: f64| value);
    check_native!(Float32Array, |value: f32| f64::from(value));
    check_native!(Int8Array, |value: i8| f64::from(value));
    check_native!(Int16Array, |value: i16| f64::from(value));
    check_native!(Int32Array, |value: i32| f64::from(value));
    check_native!(Int64Array, |value: i64| value as f64);
    check_native!(UInt8Array, |value: u8| f64::from(value));
    check_native!(UInt16Array, |value: u16| f64::from(value));
    check_native!(UInt32Array, |value: u32| f64::from(value));
    check_native!(UInt64Array, |value: u64| value as f64);
    check_native!(TimestampSecondArray, |value: i64| value as f64);
    check_native!(TimestampMillisecondArray, |value: i64| value as f64);
    check_native!(TimestampMicrosecondArray, |value: i64| value as f64);
    check_native!(TimestampNanosecondArray, |value: i64| value as f64);

    for row in 0..array.len() {
        if array.is_valid(row) {
            if let Some(value) = numeric_value(array, row)? {
                push_range_findings(value, rule, column, row_offset + row as u64, validation);
            }
        }
    }
    Ok(())
}

fn push_range_findings(
    number: f64,
    rule: &ColumnContract,
    column: &str,
    row: u64,
    validation: &mut ValidationState,
) {
    if rule.min.is_some_and(|minimum| number < minimum) {
        validation.record(Finding {
            rule: "min",
            column: column.to_string(),
            row: Some(row),
            message: format!("Value is below {}", rule.min.unwrap()),
        });
    }
    if rule.max.is_some_and(|maximum| number > maximum) {
        validation.record(Finding {
            rule: "max",
            column: column.to_string(),
            row: Some(row),
            message: format!("Value is above {}", rule.max.unwrap()),
        });
    }
}

fn validate_fast_batches<R>(
    reader: R,
    contract: &Contract,
) -> Result<FastValidationReport, ProofFrameError>
where
    R: RecordBatchReader,
{
    let schema = reader.schema();
    let mut validation = ValidationState::new(contract.max_findings);
    let mut patterns = HashMap::new();
    let mut unique_states: HashMap<String, UniqueState> = HashMap::new();
    for (name, rule) in &contract.columns {
        if rule.required && schema.index_of(name).is_err() {
            validation.record(Finding {
                rule: "required",
                column: name.clone(),
                row: None,
                message: format!("Required column `{name}` is missing"),
            });
        }
        if let Some(pattern) = &rule.pattern {
            patterns.insert(name.clone(), Regex::new(pattern)?);
        }
    }

    let mut rows = 0_u64;
    for maybe_batch in reader {
        let batch = maybe_batch?;
        for (column_index, field) in schema.fields().iter().enumerate() {
            let Some(rule) = contract.columns.get(field.name()) else {
                continue;
            };
            let array = batch.column(column_index);
            if rule.unique {
                unique_states
                    .entry(field.name().clone())
                    .or_insert_with(|| UniqueState::for_array(array.as_ref()));
            }
            if rule.not_null && array.null_count() > 0 {
                for row in 0..batch.num_rows() {
                    if array.is_null(row) {
                        validation.record(Finding {
                            rule: "not_null",
                            column: field.name().clone(),
                            row: Some(rows + row as u64),
                            message: "Null value is not allowed".to_string(),
                        });
                    }
                }
            }
            if rule.unique {
                check_unique(
                    unique_states
                        .get_mut(field.name())
                        .expect("unique state initialized"),
                    array.as_ref(),
                    field.name(),
                    rows,
                    &mut validation,
                )?;
            }
            if rule.min.is_some() || rule.max.is_some() {
                check_range(array.as_ref(), rule, field.name(), rows, &mut validation)?;
            }
            if rule.pattern.is_some() || rule.allowed.is_some() {
                for row in 0..batch.num_rows() {
                    if array.is_null(row) {
                        continue;
                    }
                    let value = value_for_rules(array.as_ref(), row)?;
                    if patterns
                        .get(field.name())
                        .is_some_and(|pattern| !pattern.is_match(&value))
                    {
                        validation.record(Finding {
                            rule: "pattern",
                            column: field.name().clone(),
                            row: Some(rows + row as u64),
                            message: "Value does not match the required pattern".to_string(),
                        });
                    }
                    if rule
                        .allowed
                        .as_ref()
                        .is_some_and(|allowed| !allowed.contains(&value))
                    {
                        validation.record(Finding {
                            rule: "allowed",
                            column: field.name().clone(),
                            row: Some(rows + row as u64),
                            message: "Value is not in the allowlist".to_string(),
                        });
                    }
                }
            }
        }
        rows += batch.num_rows() as u64;
    }
    let outcome = validation.finish();
    Ok(FastValidationReport {
        valid: outcome.violation_count == 0,
        violation_count: outcome.violation_count,
        truncated: outcome.truncated,
        findings: outcome.findings,
        rows,
        mode: "rules_only",
    })
}

/// Profile Arrow record batches and return typed Rust metadata.
pub fn profile_reader<R>(reader: R) -> Result<Profile, ProofFrameError>
where
    R: RecordBatchReader,
{
    profile_reader_with_distinct(reader, DistinctMode::Exact)
}

/// Profile Arrow record batches with configurable exact distinct counting.
pub fn profile_reader_with_distinct<R>(
    reader: R,
    distinct_mode: DistinctMode,
) -> Result<Profile, ProofFrameError>
where
    R: RecordBatchReader,
{
    inspect_batches(reader, None, distinct_mode).map(|(profile, _)| profile)
}

fn fingerprint_batches<R>(reader: R) -> Result<(u64, String), ProofFrameError>
where
    R: RecordBatchReader,
{
    let schema = reader.schema();
    let mut rows = 0_u64;
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"pf-fp-v1\0");
    for field in schema.fields() {
        let data_type = field.data_type().to_string();
        update_schema_hash(&mut hasher, field.name(), &data_type, field.is_nullable());
    }
    hasher.update(b"pf-fp-body-v1\0");
    for maybe_batch in reader {
        let batch = maybe_batch?;
        for row in 0..batch.num_rows() {
            for (column_index, array) in batch.columns().iter().enumerate() {
                update_hash(&mut hasher, column_index, array.as_ref(), row)?;
            }
        }
        rows += batch.num_rows() as u64;
    }
    Ok((rows, format!("pf-fp-v1:{}", hasher.finalize().to_hex())))
}

/// Return only the canonical dataset fingerprint, without profiling or exact distinct state.
pub fn fingerprint_reader<R>(reader: R) -> Result<String, ProofFrameError>
where
    R: RecordBatchReader,
{
    fingerprint_batches(reader).map(|(_, fingerprint)| fingerprint)
}

/// Validate Arrow record batches with the full profiling path.
pub fn validate_reader<R>(
    reader: R,
    contract: &Contract,
) -> Result<ValidationReport, ProofFrameError>
where
    R: RecordBatchReader,
{
    let (profile, outcome) = inspect_batches(reader, Some(contract), DistinctMode::Exact)?;
    Ok(ValidationReport {
        valid: outcome.violation_count == 0,
        violation_count: outcome.violation_count,
        truncated: outcome.truncated,
        findings: outcome.findings,
        profile,
    })
}

/// Validate Arrow record batches with the rules-only fast path.
pub fn validate_fast_reader<R>(
    reader: R,
    contract: &Contract,
) -> Result<FastValidationReport, ProofFrameError>
where
    R: RecordBatchReader,
{
    validate_fast_batches(reader, contract)
}

/// Compute an exact keyed diff between two Arrow readers.
pub fn diff_readers<B, A>(
    before: B,
    after: A,
    keys: &[String],
) -> Result<DiffReport, ProofFrameError>
where
    B: RecordBatchReader,
    A: RecordBatchReader,
{
    if keys.is_empty() {
        return Err(ProofFrameError::NoKeyColumns);
    }
    let directory = TempDir::new()?;
    let (before_schema, before_count, before_paths) =
        partition_rows(before, keys, directory.path(), "before")?;
    let (after_schema, after_count, after_paths) =
        partition_rows(after, keys, directory.path(), "after")?;
    if before_schema != after_schema {
        return Err(ProofFrameError::SchemaMismatch(
            "normalize columns before row-level diff".to_string(),
        ));
    }
    let column_names = schema_names(&before_schema);

    let mut added_keys = Vec::new();
    let mut removed_keys = Vec::new();
    let mut changed = Vec::new();
    for (before_path, after_path) in before_paths.iter().zip(&after_paths) {
        process_diff_partition(
            before_path,
            after_path,
            &column_names,
            &mut added_keys,
            &mut removed_keys,
            &mut changed,
        )?;
    }
    added_keys.sort();
    removed_keys.sort();
    changed.sort_by(|left, right| left.key.cmp(&right.key));
    Ok(DiffReport {
        keys: keys.to_vec(),
        before_rows: before_count,
        after_rows: after_count,
        added_count: added_keys.len(),
        removed_count: removed_keys.len(),
        changed_count: changed.len(),
        added_keys,
        removed_keys,
        changed,
    })
}

/// Scan Arrow record batches for high-signal PII patterns.
pub fn scan_pii_reader<R>(reader: R, max_findings: usize) -> Result<PiiReport, ProofFrameError>
where
    R: RecordBatchReader,
{
    let schema = reader.schema();
    let detector = pii::Detector::new()?;
    let mut findings = Vec::new();
    let mut counts = BTreeMap::new();
    let mut scanned_rows = 0_u64;
    let mut total_findings = 0_usize;
    for maybe_batch in reader {
        let batch = maybe_batch?;
        for row in 0..batch.num_rows() {
            for (column, array) in batch.columns().iter().enumerate() {
                if array.is_null(row) {
                    continue;
                }
                let value = value_for_rules(array.as_ref(), row)?;
                if let Some(classification) =
                    detector.classify_cell(&value, is_numeric_array(array.as_ref()))
                {
                    total_findings += 1;
                    *counts.entry(classification.kind).or_insert(0) += 1;
                    if findings.len() < max_findings {
                        findings.push(PiiFinding {
                            kind: classification.kind,
                            confidence: classification.confidence,
                            column: schema.field(column).name().clone(),
                            row: scanned_rows + row as u64,
                            value_fingerprint: privacy_fingerprint(&value),
                        });
                    }
                }
            }
        }
        scanned_rows += batch.num_rows() as u64;
    }
    Ok(PiiReport {
        detected: total_findings > 0,
        scanned_rows,
        finding_count: total_findings,
        counts_by_kind: counts,
        truncated: total_findings > findings.len(),
        findings,
    })
}

/// Detect train/test row or key leakage between two Arrow readers.
pub fn detect_leakage_readers<TR, TE>(
    train: TR,
    test: TE,
    keys: &[String],
    max_samples: usize,
) -> Result<LeakageReport, ProofFrameError>
where
    TR: RecordBatchReader,
    TE: RecordBatchReader,
{
    let (train_names, train_rows, train_ids) = collect_leakage_ids(train, keys)?;
    let (test_names, test_rows, test_ids) = collect_leakage_ids(test, keys)?;
    if keys.is_empty() && train_names != test_names {
        return Err(ProofFrameError::SchemaMismatch(
            "full-row leakage detection requires identical columns".to_string(),
        ));
    }
    let mut overlap = train_ids
        .intersection(&test_ids)
        .cloned()
        .collect::<Vec<_>>();
    overlap.sort();
    let overlap_count = overlap.len();
    let truncated = overlap_count > max_samples;
    overlap.truncate(max_samples);
    let rate = |count: usize, total: usize| {
        if total == 0 {
            0.0
        } else {
            count as f64 / total as f64
        }
    };
    Ok(LeakageReport {
        detected: overlap_count > 0,
        mode: if keys.is_empty() { "full_row" } else { "key" },
        keys: keys.to_vec(),
        train_rows,
        test_rows,
        overlap_count,
        train_overlap_rate: rate(overlap_count, train_ids.len()),
        test_overlap_rate: rate(overlap_count, test_ids.len()),
        sample_fingerprints: overlap,
        truncated,
    })
}

#[cfg(feature = "python")]
#[pyfunction]
#[pyo3(signature = (source, distinct="exact"))]
fn profile_arrow(source: PyArrowType<ArrowArrayStreamReader>, distinct: &str) -> PyResult<String> {
    let distinct_mode = DistinctMode::from_name(distinct).map_err(py_err)?;
    let profile = profile_reader_with_distinct(source.0, distinct_mode).map_err(py_err)?;
    serde_json::to_string(&profile).map_err(py_err)
}

#[cfg(feature = "python")]
#[pyfunction]
fn fingerprint_arrow(source: PyArrowType<ArrowArrayStreamReader>) -> PyResult<String> {
    fingerprint_reader(source.0).map_err(py_err)
}

#[cfg(feature = "python")]
#[pyfunction]
fn validate_arrow(
    source: PyArrowType<ArrowArrayStreamReader>,
    contract_json: &str,
) -> PyResult<String> {
    let contract: Contract = serde_json::from_str(contract_json)
        .map_err(|error| py_err(ProofFrameError::InvalidContract(error.to_string())))?;
    let report = validate_reader(source.0, &contract).map_err(py_err)?;
    serde_json::to_string(&report).map_err(py_err)
}

#[cfg(feature = "python")]
#[pyfunction]
fn validate_fast_arrow(
    source: PyArrowType<ArrowArrayStreamReader>,
    contract_json: &str,
) -> PyResult<String> {
    let contract: Contract = serde_json::from_str(contract_json)
        .map_err(|error| py_err(ProofFrameError::InvalidContract(error.to_string())))?;
    let report = validate_fast_batches(source.0, &contract).map_err(py_err)?;
    serde_json::to_string(&report).map_err(py_err)
}

#[cfg(feature = "python")]
#[pyfunction]
fn diff_arrow(
    before: PyArrowType<ArrowArrayStreamReader>,
    after: PyArrowType<ArrowArrayStreamReader>,
    keys: Vec<String>,
) -> PyResult<String> {
    let report = diff_readers(before.0, after.0, &keys).map_err(py_err)?;
    serde_json::to_string(&report).map_err(py_err)
}

#[cfg(feature = "python")]
#[pyfunction]
#[pyo3(signature = (source, max_findings=100))]
fn scan_pii_arrow(
    source: PyArrowType<ArrowArrayStreamReader>,
    max_findings: usize,
) -> PyResult<String> {
    let report = scan_pii_reader(source.0, max_findings).map_err(py_err)?;
    serde_json::to_string(&report).map_err(py_err)
}

#[cfg(feature = "python")]
#[pyfunction]
#[pyo3(signature = (train, test, keys, max_samples=20))]
fn detect_leakage_arrow(
    train: PyArrowType<ArrowArrayStreamReader>,
    test: PyArrowType<ArrowArrayStreamReader>,
    keys: Vec<String>,
    max_samples: usize,
) -> PyResult<String> {
    let report = detect_leakage_readers(train.0, test.0, &keys, max_samples).map_err(py_err)?;
    serde_json::to_string(&report).map_err(py_err)
}

#[cfg(feature = "python")]
#[pyfunction]
fn generate_signing_keypair() -> PyResult<String> {
    receipt::generate_keypair_json().map_err(py_err)
}

#[cfg(feature = "python")]
#[pyfunction]
fn sign_proof_receipt(report_json: &str, private_key: &str) -> PyResult<String> {
    receipt::sign_json(report_json, private_key).map_err(py_err)
}

#[cfg(feature = "python")]
#[pyfunction]
fn verify_proof_receipt(receipt_json: &str) -> PyResult<String> {
    let verification = receipt::verify_json(receipt_json).map_err(py_err)?;
    serde_json::to_string(&verification).map_err(py_err)
}

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

    use arrow::array::ArrayRef;
    use arrow::datatypes::{DataType, Field, Schema};
    use arrow::record_batch::RecordBatchIterator;
    use proptest::prelude::*;

    fn reader_from_batch(batch: RecordBatch) -> impl RecordBatchReader {
        let schema = batch.schema();
        RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema)
    }

    fn finding_signature(findings: &[Finding]) -> Vec<(&'static str, String, Option<u64>)> {
        let mut signature = findings
            .iter()
            .map(|finding| (finding.rule, finding.column.clone(), finding.row))
            .collect::<Vec<_>>();
        signature.sort();
        signature
    }

    proptest! {
        #[test]
        fn full_and_fast_paths_have_same_rule_verdicts(
            rows in prop::collection::vec((-10_i64..10, -250_i32..250), 0..40)
        ) {
            let ids = rows.iter().map(|(id, _)| *id).collect::<Vec<_>>();
            let scores = rows
                .iter()
                .map(|(_, score)| f64::from(*score) / 100.0)
                .collect::<Vec<_>>();
            let schema = Arc::new(Schema::new(vec![
                Field::new("id", DataType::Int64, false),
                Field::new("score", DataType::Float64, false),
            ]));
            let batch = RecordBatch::try_new(
                schema,
                vec![
                    Arc::new(Int64Array::from(ids)) as ArrayRef,
                    Arc::new(Float64Array::from(scores)) as ArrayRef,
                ],
            )
            .unwrap();
            let contract = Contract {
                columns: HashMap::from([
                    (
                        "id".to_string(),
                        ColumnContract {
                            unique: true,
                            min: Some(-3.0),
                            max: Some(3.0),
                            ..ColumnContract::default()
                        },
                    ),
                    (
                        "score".to_string(),
                        ColumnContract {
                            unique: true,
                            min: Some(-1.0),
                            max: Some(1.0),
                            ..ColumnContract::default()
                        },
                    ),
                ]),
                max_findings: 1_000,
            };

            let (_, full_outcome) =
                inspect_batches(reader_from_batch(batch.clone()), Some(&contract), DistinctMode::Exact)
                    .unwrap();
            let fast_report = validate_fast_batches(reader_from_batch(batch), &contract).unwrap();

            prop_assert_eq!(
                finding_signature(&full_outcome.findings),
                finding_signature(&fast_report.findings)
            );
            prop_assert_eq!(full_outcome.violation_count, fast_report.violation_count);
            prop_assert_eq!(full_outcome.truncated, fast_report.truncated);
        }
    }

    #[test]
    fn nested_columns_fingerprint_without_error() {
        use arrow::array::{Int64Builder, ListBuilder, StructArray};

        fn nested_batch(second: i64) -> RecordBatch {
            let mut list_builder = ListBuilder::new(Int64Builder::new());
            list_builder.values().append_value(1);
            list_builder.values().append_value(2);
            list_builder.append(true);
            list_builder.values().append_value(second);
            list_builder.append(true);
            let tags = Arc::new(list_builder.finish()) as ArrayRef;

            let group = StructArray::from(vec![
                (
                    Arc::new(Field::new("id", DataType::Int64, false)),
                    Arc::new(Int64Array::from(vec![10_i64, 20])) as ArrayRef,
                ),
                (
                    Arc::new(Field::new("team", DataType::Utf8, false)),
                    Arc::new(StringArray::from(vec!["a", "b"])) as ArrayRef,
                ),
            ]);

            let schema = Arc::new(Schema::new(vec![
                Field::new("tags", tags.data_type().clone(), true),
                Field::new("group", group.data_type().clone(), false),
            ]));
            RecordBatch::try_new(schema, vec![tags, Arc::new(group) as ArrayRef]).unwrap()
        }

        let first = profile_reader(reader_from_batch(nested_batch(3))).unwrap();
        let repeat = profile_reader(reader_from_batch(nested_batch(3))).unwrap();
        let different = profile_reader(reader_from_batch(nested_batch(99))).unwrap();

        assert!(first.fingerprint.starts_with("pf-fp-v1:"));
        assert_eq!(first.fingerprint, repeat.fingerprint);
        assert_ne!(first.fingerprint, different.fingerprint);
    }

    fn int_string_batch() -> RecordBatch {
        let schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::Int64, false),
            Field::new("name", DataType::Utf8, true),
        ]));
        RecordBatch::try_new(
            schema,
            vec![
                Arc::new(Int64Array::from(vec![1_i64, 2, 3])) as ArrayRef,
                Arc::new(StringArray::from(vec![Some("a"), None, Some("c")])) as ArrayRef,
            ],
        )
        .unwrap()
    }

    /// Golden fingerprint. If the canonical encoding changes, this pin must be
    /// updated together with a new `pf-fp` tag — a silent change is a bug.
    #[test]
    fn fingerprint_is_pinned() {
        let fingerprint = profile_reader(reader_from_batch(int_string_batch()))
            .unwrap()
            .fingerprint;
        assert_eq!(
            fingerprint,
            "pf-fp-v1:4dc74e666725f040dea7e788827d0411e59c19a72b55f2ce27f22ed9a00afb42",
            "canonical fingerprint changed; update the pin and bump the tag if intentional"
        );
    }

    #[test]
    fn fingerprint_ignores_batch_boundaries() {
        let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
        let whole = RecordBatch::try_new(
            schema.clone(),
            vec![Arc::new(Int64Array::from(vec![1_i64, 2, 3, 4])) as ArrayRef],
        )
        .unwrap();
        let first = RecordBatch::try_new(
            schema.clone(),
            vec![Arc::new(Int64Array::from(vec![1_i64, 2])) as ArrayRef],
        )
        .unwrap();
        let second = RecordBatch::try_new(
            schema.clone(),
            vec![Arc::new(Int64Array::from(vec![3_i64, 4])) as ArrayRef],
        )
        .unwrap();

        let single = profile_reader(reader_from_batch(whole))
            .unwrap()
            .fingerprint;
        let split = profile_reader(RecordBatchIterator::new(
            vec![Ok(first), Ok(second)].into_iter(),
            schema,
        ))
        .unwrap()
        .fingerprint;
        assert_eq!(single, split);
    }

    #[test]
    fn typed_unique_semantics_are_explicit() {
        let timestamp_batch = RecordBatch::try_new(
            Arc::new(Schema::new(vec![Field::new(
                "ts",
                DataType::Timestamp(arrow::datatypes::TimeUnit::Microsecond, None),
                false,
            )])),
            vec![Arc::new(TimestampMicrosecondArray::from(vec![10_i64, 11, 10])) as ArrayRef],
        )
        .unwrap();
        let contract = Contract {
            columns: HashMap::from([(
                "ts".to_string(),
                ColumnContract {
                    unique: true,
                    ..ColumnContract::default()
                },
            )]),
            max_findings: 100,
        };
        let report = validate_fast_reader(reader_from_batch(timestamp_batch), &contract).unwrap();
        assert!(!report.valid);
        assert_eq!(report.findings[0].row, Some(2));

        let nan_a = f64::from_bits(0x7ff8_0000_0000_0001);
        let nan_b = f64::from_bits(0x7ff8_0000_0000_0002);
        let floats = RecordBatch::try_new(
            Arc::new(Schema::new(vec![Field::new("v", DataType::Float64, false)])),
            vec![Arc::new(Float64Array::from(vec![-0.0, 0.0, nan_a, nan_b, nan_a])) as ArrayRef],
        )
        .unwrap();
        let contract = Contract {
            columns: HashMap::from([(
                "v".to_string(),
                ColumnContract {
                    unique: true,
                    ..ColumnContract::default()
                },
            )]),
            max_findings: 100,
        };
        let report = validate_fast_reader(reader_from_batch(floats), &contract).unwrap();
        assert_eq!(report.violation_count, 1);
        assert_eq!(report.findings[0].row, Some(4));
    }

    proptest! {
        #[test]
        fn fingerprint_tracks_data_changes(
            left in prop::collection::vec(any::<i64>(), 1..20),
            right in prop::collection::vec(any::<i64>(), 1..20),
        ) {
            let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int64, false)]));
            let fingerprint = |data: &[i64]| {
                let batch = RecordBatch::try_new(
                    schema.clone(),
                    vec![Arc::new(Int64Array::from(data.to_vec())) as ArrayRef],
                )
                .unwrap();
                profile_reader(reader_from_batch(batch)).unwrap().fingerprint
            };
            let left_fp = fingerprint(&left);
            let right_fp = fingerprint(&right);
            if left == right {
                prop_assert_eq!(left_fp, right_fp);
            } else {
                prop_assert_ne!(left_fp, right_fp);
            }
        }
    }
}

#[cfg(feature = "python")]
#[pymodule]
fn _proofframe(module: &Bound<'_, PyModule>) -> PyResult<()> {
    module.add_function(wrap_pyfunction!(profile_arrow, module)?)?;
    module.add_function(wrap_pyfunction!(fingerprint_arrow, module)?)?;
    module.add_function(wrap_pyfunction!(validate_arrow, module)?)?;
    module.add_function(wrap_pyfunction!(validate_fast_arrow, module)?)?;
    module.add_function(wrap_pyfunction!(diff_arrow, module)?)?;
    module.add_function(wrap_pyfunction!(scan_pii_arrow, module)?)?;
    module.add_function(wrap_pyfunction!(detect_leakage_arrow, module)?)?;
    module.add_function(wrap_pyfunction!(generate_signing_keypair, module)?)?;
    module.add_function(wrap_pyfunction!(sign_proof_receipt, module)?)?;
    module.add_function(wrap_pyfunction!(verify_proof_receipt, module)?)?;
    module.add("__version__", env!("CARGO_PKG_VERSION"))?;
    Ok(())
}