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
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

#![allow(missing_docs)] // For generated protos.

//! Aggregate statistics about data stored in persist.

use std::any::Any;
use std::collections::BTreeMap;
use std::fmt::Debug;

use mz_ore::metric;
use mz_ore::metrics::{IntCounter, MetricsRegistry};
use proptest_derive::Arbitrary;
use prost::Message;
use serde::ser::{SerializeMap, SerializeStruct};
use serde_json::json;

use crate::columnar::Data;
use crate::dyn_col::DynColumnRef;
use crate::dyn_struct::ValidityRef;
use crate::part::Part;
use crate::stats::impls::any_struct_stats_cols;
use crate::timestamp::try_parse_monotonic_iso8601_timestamp;

include!(concat!(env!("OUT_DIR"), "/mz_persist_types.stats.rs"));

/// Metrics for [PartStats].
#[derive(Debug)]
pub struct PartStatsMetrics {
    pub mismatched_count: IntCounter,
}

impl PartStatsMetrics {
    pub fn new(registry: &MetricsRegistry) -> Self {
        PartStatsMetrics {
            mismatched_count: registry.register(metric!(
                name: "mz_persist_pushdown_parts_mismatched_stats_count",
                help: "number of parts read with unexpectedly the incorrect type of stats",
            )),
        }
    }
}

/// The logic to use when computing stats for a column of `T: Data`.
///
/// If Custom is used, the DynStats returned must be a`<T as Data>::Stats`.
pub enum StatsFn {
    Default,
    Custom(fn(&DynColumnRef, ValidityRef) -> Result<Box<dyn DynStats>, String>),
}

#[cfg(debug_assertions)]
impl PartialEq for StatsFn {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (StatsFn::Default, StatsFn::Default) => true,
            (StatsFn::Custom(s), StatsFn::Custom(o)) => {
                let s: fn(&'static DynColumnRef, ValidityRef) -> Result<Box<dyn DynStats>, String> =
                    *s;
                let o: fn(&'static DynColumnRef, ValidityRef) -> Result<Box<dyn DynStats>, String> =
                    *o;
                // I think this is not always correct, but it's only used in
                // debug_assertions so as long as CI is happy with it, probably
                // good enough.
                s == o
            }
            (StatsFn::Default, StatsFn::Custom(_)) | (StatsFn::Custom(_), StatsFn::Default) => {
                false
            }
        }
    }
}

impl std::fmt::Debug for StatsFn {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Default => write!(f, "Default"),
            Self::Custom(_) => f.debug_struct("Custom").finish_non_exhaustive(),
        }
    }
}

/// Aggregate statistics about a column of type `T`.
pub trait ColumnStats<T: Data>: DynStats {
    /// An inclusive lower bound on the data contained in the column, if known.
    ///
    /// This will often be a tight bound, but it's not guaranteed. Persist
    /// reserves the right to (for example) invent smaller bounds for long byte
    /// strings. SUBTLE: This means that this exact value may not be present in
    /// the column.
    ///
    /// Similarly, if the column is empty, this will contain `T: Default`.
    /// Emptiness will be indicated in statistics higher up (i.e.
    /// [StructStats]).
    fn lower<'a>(&'a self) -> Option<T::Ref<'a>>;
    /// Same as [Self::lower] but an (also inclusive) upper bound.
    fn upper<'a>(&'a self) -> Option<T::Ref<'a>>;
    /// The number of `None`s if this column is optional or 0 if it isn't.
    fn none_count(&self) -> usize;
}

/// A source of aggregate statistics about a column of data.
pub trait StatsFrom<T> {
    /// Computes statistics from a column of data.
    ///
    /// The validity, if given, indicates which values in the columns are and
    /// are not used for stats. This allows us to model non-nullable columns in
    /// a nullable struct. For optional columns (i.e. ones with their own
    /// validity) it _must be a subset_ of the column's validity, otherwise this
    /// panics.
    fn stats_from(col: &T, validity: ValidityRef) -> Self;
}

/// Type-erased aggregate statistics about a column of data.
pub trait DynStats: Debug + Send + Sync + 'static {
    /// Returns self as a `dyn Any` for downcasting.
    fn as_any(&self) -> &dyn Any;
    /// Returns the name of the erased type for use in error messages.
    fn type_name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }
    /// See [mz_proto::RustType::into_proto].
    fn into_proto(&self) -> ProtoDynStats;
    /// Formats these statistics for use in `INSPECT SHARD` and debugging.
    fn debug_json(&self) -> serde_json::Value;
}

/// Aggregate statistics about data contained in a [Part].
#[derive(Arbitrary, Debug)]
pub struct PartStats {
    /// Aggregate statistics about key data contained in a [Part].
    pub key: StructStats,
}

impl serde::Serialize for PartStats {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let PartStats { key } = self;
        key.serialize(s)
    }
}

impl PartStats {
    /// Calculates and returns stats for the given [Part].
    pub fn new(part: &Part) -> Result<Self, String> {
        let key = part.key_stats()?;
        Ok(PartStats { key })
    }
}

/// Statistics about a column of some non-optional parquet type.
#[cfg_attr(any(test), derive(Clone))]
pub struct PrimitiveStats<T> {
    /// An inclusive lower bound on the data contained in the column.
    ///
    /// This will often be a tight bound, but it's not guaranteed. Persist
    /// reserves the right to (for example) invent smaller bounds for long byte
    /// strings. SUBTLE: This means that this exact value may not be present in
    /// the column.
    ///
    /// Similarly, if the column is empty, this will contain `T: Default`.
    /// Emptiness will be indicated in statistics higher up (i.e.
    /// [StructStats]).
    pub lower: T,
    /// Same as [Self::lower] but an (also inclusive) upper bound.
    pub upper: T,
}

/// Statistics about a column of some optional type.
pub struct OptionStats<T> {
    /// Statistics about the `Some` values in the column.
    pub some: T,
    /// The count of `None` values in the column.
    pub none: usize,
}

/// Statistics about a column of a struct type with a uniform schema (the same
/// columns and associated `T: Data` types in each instance of the struct).
#[derive(Arbitrary, Default)]
pub struct StructStats {
    /// The count of structs in the column.
    pub len: usize,
    /// Statistics about each of the columns in the struct.
    ///
    /// This will often be all of the columns, but it's not guaranteed. Persist
    /// reserves the right to prune statistics about some or all of the columns.
    #[proptest(strategy = "any_struct_stats_cols()")]
    pub cols: BTreeMap<String, Box<dyn DynStats>>,
}

impl std::fmt::Debug for StructStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self.debug_json(), f)
    }
}

impl serde::Serialize for StructStats {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let StructStats { len, cols } = self;
        let mut s = s.serialize_struct("StructStats", 2)?;
        let () = s.serialize_field("len", len)?;
        let () = s.serialize_field("cols", &DynStatsCols(cols))?;
        s.end()
    }
}

struct DynStatsCols<'a>(&'a BTreeMap<String, Box<dyn DynStats>>);

impl serde::Serialize for DynStatsCols<'_> {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let mut s = s.serialize_map(Some(self.0.len()))?;
        for (k, v) in self.0.iter() {
            let v = v.debug_json();
            let () = s.serialize_entry(k, &v)?;
        }
        s.end()
    }
}

impl StructStats {
    /// Returns the statistics for the given column in the struct.
    ///
    /// This will often be all of the columns, but it's not guaranteed. Persist
    /// reserves the right to prune statistics about some or all of the columns.
    pub fn col<T: Data>(&self, name: &str) -> Result<Option<&T::Stats>, String> {
        let Some(stats) = self.cols.get(name) else {
            return Ok(None);
        };
        match stats.as_any().downcast_ref() {
            Some(x) => Ok(Some(x)),
            None => Err(format!(
                "expected stats type {} got {}",
                std::any::type_name::<T::Stats>(),
                stats.type_name()
            )),
        }
    }
}

// Aggregate statistics about a column of Json elements.
//
// Each element could be any of a JsonNull, a bool, a string, a numeric, a list,
// or a map/object. The column might be a single type but could also be a
// mixture of any subset of these types.
#[cfg_attr(any(test), derive(Clone))]
pub enum JsonStats {
    /// A sentinel that indicates there were no elements.
    None,
    /// There were elements from more than one category of: bools, strings,
    /// numerics, lists, maps.
    Mixed,
    /// A sentinel that indicates all elements were `Datum::JsonNull`s.
    JsonNulls,
    /// The min and max bools, or None if there were none.
    Bools(PrimitiveStats<bool>),
    /// The min and max strings, or None if there were none.
    Strings(PrimitiveStats<String>),
    /// The min and max numerics, or None if there were none.
    /// Since we don't have a decimal type here yet, this is stored in serialized
    /// form.
    Numerics(PrimitiveStats<Vec<u8>>),
    /// A sentinel that indicates all elements were `Datum::List`s.
    ///
    /// TODO: We could also do something for list indexes analogous to what we
    /// do for map keys, but it initially seems much less likely that a user
    /// would expect that to work with pushdown, so don't bother keeping the
    /// stats until someone asks for it.
    Lists,
    /// Recursive statistics about the set of keys present in any maps/objects
    /// in the column, or None if there were no maps/objects.
    Maps(BTreeMap<String, JsonMapElementStats>),
}

#[derive(Default)]
#[cfg_attr(any(test), derive(Clone))]
pub struct JsonMapElementStats {
    pub len: usize,
    pub stats: JsonStats,
}

impl Default for JsonStats {
    fn default() -> Self {
        JsonStats::None
    }
}

impl Debug for JsonStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.debug_json(), f)
    }
}

impl JsonStats {
    pub fn debug_json(&self) -> serde_json::Value {
        match self {
            JsonStats::None => json!({}),
            JsonStats::Mixed => "json_mixed".into(),
            JsonStats::JsonNulls => "json_nulls".into(),
            JsonStats::Bools(x) => x.debug_json(),
            JsonStats::Strings(x) => x.debug_json(),
            JsonStats::Numerics(x) => x.debug_json(),
            JsonStats::Lists => "json_lists".into(),
            JsonStats::Maps(x) => x
                .iter()
                .map(|(k, v)| (k.clone(), v.debug_json()))
                .collect::<serde_json::Map<_, _>>()
                .into(),
        }
    }
}

impl JsonMapElementStats {
    pub fn debug_json(&self) -> serde_json::Value {
        json!({"len": self.len, "stats": self.stats.debug_json()})
    }
}

/// Statistics about a column of `Vec<u8>`.
pub enum BytesStats {
    Primitive(PrimitiveStats<Vec<u8>>),
    Json(JsonStats),
    Atomic(AtomicBytesStats),
}

/// `Vec<u8>` stats that cannot safely be trimmed.
#[derive(Debug)]
#[cfg_attr(any(test), derive(Clone))]
pub struct AtomicBytesStats {
    /// See [PrimitiveStats::lower]
    pub lower: Vec<u8>,
    /// See [PrimitiveStats::upper]
    pub upper: Vec<u8>,
}

impl AtomicBytesStats {
    fn debug_json(&self) -> serde_json::Value {
        serde_json::json!({
            "lower": hex::encode(&self.lower),
            "upper": hex::encode(&self.upper),
        })
    }
}

/// Empty set of statistics.
#[derive(Debug)]
#[cfg_attr(any(test), derive(Clone))]
pub struct NoneStats;

/// The length to truncate `Vec<u8>` and `String` stats to.
//
// Ideally, this would be in LaunchDarkly, but the plumbing is tough.
pub const TRUNCATE_LEN: usize = 100;

/// Whether a truncated value should be a lower or upper bound on the original.
pub enum TruncateBound {
    /// Truncate such that the result is <= the original.
    Lower,
    /// Truncate such that the result is >= the original.
    Upper,
}

/// Truncates a u8 slice to the given maximum byte length.
///
/// If `bound` is Lower, the returned value will sort <= the original value, and
/// if `bound` is Upper, it will sort >= the original value.
///
/// Lower bounds will always return Some. Upper bounds might return None if the
/// part that fits in `max_len` is entirely made of `u8::MAX`.
pub fn truncate_bytes(x: &[u8], max_len: usize, bound: TruncateBound) -> Option<Vec<u8>> {
    if x.len() <= max_len {
        return Some(x.to_owned());
    }
    match bound {
        // Any truncation is a lower bound.
        TruncateBound::Lower => Some(x[..max_len].to_owned()),
        TruncateBound::Upper => {
            for idx in (0..max_len).rev() {
                if x[idx] < u8::MAX {
                    let mut ret = x[..=idx].to_owned();
                    ret[idx] += 1;
                    return Some(ret);
                }
            }
            None
        }
    }
}

/// Truncates a string to the given maximum byte length.
///
/// The returned value is a valid utf-8 string. If `bound` is Lower, it will
/// sort <= the original string, and if `bound` is Upper, it will sort >= the
/// original string.
///
/// Lower bounds will always return Some. Upper bounds might return None if the
/// part that fits in `max_len` is entirely made of `char::MAX` (so in practice,
/// probably ~never).
pub fn truncate_string(x: &str, max_len: usize, bound: TruncateBound) -> Option<String> {
    if x.len() <= max_len {
        return Some(x.to_owned());
    }
    // For the output to be valid utf-8, we have to truncate along a char
    // boundary.
    let truncation_idx = x
        .char_indices()
        .map(|(idx, c)| idx + c.len_utf8())
        .take_while(|char_end| *char_end <= max_len)
        .last()
        .unwrap_or(0);
    let truncated = &x[..truncation_idx];
    match bound {
        // Any truncation is a lower bound.
        TruncateBound::Lower => Some(truncated.to_owned()),
        TruncateBound::Upper => {
            // See if we can find a char that's not already the max. If so, take
            // the last of these and increment it.
            for (idx, c) in truncated.char_indices().rev() {
                if let Ok(new_last_char) = char::try_from(u32::from(c) + 1) {
                    // NB: It's technically possible for `new_last_char` to be
                    // more bytes than `c`, which means we could go over
                    // max_len. It isn't a hard requirement for the initial
                    // caller of this, so don't bother with the complexity yet.
                    let mut ret = String::with_capacity(idx + new_last_char.len_utf8());
                    ret.push_str(&truncated[..idx]);
                    ret.push(new_last_char);
                    return Some(ret);
                }
            }
            None
        }
    }
}

pub trait TrimStats: Message {
    /// Attempts to reduce the serialization costs of these stats.
    ///
    /// This is lossy (might increase the false positive rate) and so should
    /// be avoided if the full fidelity stats are within an acceptable cost
    /// threshold.
    fn trim(&mut self);
}

impl TrimStats for ProtoPrimitiveStats {
    fn trim(&mut self) {
        use proto_primitive_stats::*;
        match (&mut self.lower, &mut self.upper) {
            (Some(Lower::LowerString(lower)), Some(Upper::UpperString(upper))) => {
                // If the lower and upper strings both look like iso8601
                // timestamps, then (1) they're small and (2) that's an
                // extremely high signal that we might want to keep them around
                // for filtering. We technically could still recover useful
                // bounds here in the interpret code, but the complexity isn't
                // worth it, so just skip any trimming.
                if try_parse_monotonic_iso8601_timestamp(lower).is_some()
                    && try_parse_monotonic_iso8601_timestamp(upper).is_some()
                {
                    return;
                }

                let common_prefix = lower
                    .char_indices()
                    .zip(upper.chars())
                    .take_while(|((_, x), y)| x == y)
                    .last();
                if let Some(((o, x), y)) = common_prefix {
                    let new_len = o + std::cmp::max(x.len_utf8(), y.len_utf8());
                    *lower = truncate_string(lower, new_len, TruncateBound::Lower)
                        .expect("lower bound should always truncate");
                    if let Some(new_upper) = truncate_string(upper, new_len, TruncateBound::Upper) {
                        *upper = new_upper;
                    }
                }
            }
            _ => {}
        }
    }
}

impl TrimStats for ProtoPrimitiveBytesStats {
    fn trim(&mut self) {
        let common_prefix = self
            .lower
            .iter()
            .zip(self.upper.iter())
            .take_while(|(x, y)| x == y)
            .count();
        self.lower = truncate_bytes(&self.lower, common_prefix + 1, TruncateBound::Lower)
            .expect("lower bound should always truncate");
        if let Some(upper) = truncate_bytes(&self.upper, common_prefix + 1, TruncateBound::Upper) {
            self.upper = upper;
        }
    }
}

impl TrimStats for ProtoJsonStats {
    fn trim(&mut self) {
        use proto_json_stats::*;
        match &mut self.kind {
            Some(Kind::Strings(stats)) => {
                stats.trim();
            }
            Some(Kind::Maps(stats)) => {
                for value in &mut stats.elements {
                    if let Some(stats) = &mut value.stats {
                        stats.trim();
                    }
                }
            }
            Some(
                Kind::None(_)
                | Kind::Mixed(_)
                | Kind::JsonNulls(_)
                | Kind::Bools(_)
                | Kind::Numerics(_)
                | Kind::Lists(_),
            ) => {}
            None => {}
        }
    }
}

impl TrimStats for ProtoBytesStats {
    fn trim(&mut self) {
        use proto_bytes_stats::*;
        match &mut self.kind {
            Some(Kind::Primitive(stats)) => stats.trim(),
            Some(Kind::Json(stats)) => stats.trim(),
            // We explicitly don't trim atomic stats!
            Some(Kind::Atomic(_)) => {}
            None => {}
        }
    }
}

impl TrimStats for ProtoStructStats {
    fn trim(&mut self) {
        use proto_dyn_stats::*;

        for value in self.cols.values_mut() {
            match &mut value.kind {
                Some(Kind::Primitive(stats)) => stats.trim(),
                Some(Kind::Bytes(stats)) => stats.trim(),
                Some(Kind::Struct(stats)) => stats.trim(),
                Some(Kind::None(())) => (),
                None => {}
            }
        }
    }
}

/// Trims the included column status until they fit within a budget.
///
/// This might remove stats for a column entirely, unless `force_keep_col`
/// returns true for that column. The resulting StructStats object is
/// guaranteed to fit within the passed budget, except when the columns that
/// are force-kept are collectively larger than the budget.
///
/// The number of bytes trimmed is returned.
pub fn trim_to_budget(
    stats: &mut ProtoStructStats,
    budget: usize,
    force_keep_col: impl Fn(&str) -> bool,
) -> usize {
    // No trimming necessary should be the overwhelming common case in practice.
    let original_cost = stats.encoded_len();
    if original_cost <= budget {
        return 0;
    }

    // First try any lossy trimming that doesn't lose an entire column.
    stats.trim();
    let new_cost = stats.encoded_len();
    if new_cost <= budget {
        return original_cost.saturating_sub(new_cost);
    }

    // That wasn't enough. Try recursively trimming out entire cols.
    //
    // TODO: There are certainly more elegant things we could do here. One idea
    // would be to call `trim_to_budget_struct` but with a closure for
    // force_keep_col that always returns false. That would potentially at least
    // keep _something_. Another possibility would be to replace this whole bit
    // with some sort of recursive max-cost search with force_keep_col things
    // weighted after everything else.
    let mut budget_shortfall = new_cost.saturating_sub(budget);
    trim_to_budget_struct(stats, &mut budget_shortfall, &force_keep_col);
    original_cost.saturating_sub(stats.encoded_len())
}

/// Recursively trims cols in the struct, greatest-size first, keeping force
/// kept cols and ancestors of force kept cols.
fn trim_to_budget_struct(
    stats: &mut ProtoStructStats,
    budget_shortfall: &mut usize,
    force_keep_col: &impl Fn(&str) -> bool,
) {
    // Sort the columns in order of ascending size and keep however many fit
    // within the budget. This strategy both keeps the largest total number of
    // columns and also optimizes for the sort of columns we expect to need
    // stats in practice (timestamps are numbers or small strings).
    //
    // Note: even though we sort in ascending order, we use `.pop()` to iterate
    // over the elements, which takes from the back of the Vec.
    let mut col_costs: Vec<_> = stats
        .cols
        .iter()
        .map(|(name, stats)| (name.to_owned(), stats.encoded_len()))
        .collect();
    col_costs.sort_unstable_by_key(|(_, c)| *c);

    while *budget_shortfall > 0 {
        let Some((name, cost)) = col_costs.pop() else {
            break;
        };

        if force_keep_col(&name) {
            continue;
        }

        // Otherwise, if the col is a struct, recurse into it.
        //
        // TODO: Do this same recursion for json stats.
        let col_stats = stats.cols.get_mut(&name).expect("col exists");
        match &mut col_stats.kind {
            Some(proto_dyn_stats::Kind::Struct(col_struct)) => {
                trim_to_budget_struct(col_struct, budget_shortfall, force_keep_col);
                // This recursion might have gotten us under budget.
                if *budget_shortfall == 0 {
                    break;
                }
                // Otherwise, if any columns are left, they must have been force
                // kept, which means we need to force keep this struct as well.
                if !col_struct.cols.is_empty() {
                    continue;
                }
                // We have to recompute the cost because trim_to_budget_struct might
                // have already accounted for some of the shortfall.
                *budget_shortfall = budget_shortfall.saturating_sub(col_struct.encoded_len() + 1);
                stats.cols.remove(&name);
            }
            Some(proto_dyn_stats::Kind::Bytes(ProtoBytesStats {
                kind:
                    Some(proto_bytes_stats::Kind::Json(ProtoJsonStats {
                        kind: Some(proto_json_stats::Kind::Maps(col_jsonb)),
                    })),
            })) => {
                trim_to_budget_jsonb(col_jsonb, budget_shortfall, force_keep_col);
                // This recursion might have gotten us under budget.
                if *budget_shortfall == 0 {
                    break;
                }
                // Otherwise, if any columns are left, they must have been force
                // kept, which means we need to force keep this struct as well.
                if !col_jsonb.elements.is_empty() {
                    continue;
                }
                // We have to recompute the cost because trim_to_budget_jsonb might
                // have already accounted for some of the shortfall.
                *budget_shortfall = budget_shortfall.saturating_sub(col_jsonb.encoded_len() + 1);
                stats.cols.remove(&name);
            }
            _ => {
                stats.cols.remove(&name);
                // Each field costs at least the cost of serializing the value
                // and a byte for the tag. (Though a tag may be more than one
                // byte in extreme cases.)
                *budget_shortfall = budget_shortfall.saturating_sub(cost + 1);
            }
        }
    }
}

fn trim_to_budget_jsonb(
    stats: &mut ProtoJsonMapStats,
    budget_shortfall: &mut usize,
    force_keep_col: &impl Fn(&str) -> bool,
) {
    // Sort the columns in order of ascending size and keep however many fit
    // within the budget. This strategy both keeps the largest total number of
    // columns and also optimizes for the sort of columns we expect to need
    // stats in practice (timestamps are numbers or small strings).
    //
    // Note: even though we sort in ascending order, we use `.pop()` to iterate
    // over the elements, which takes from the back of the Vec.
    stats
        .elements
        .sort_unstable_by_key(|element| element.encoded_len());

    // Our strategy is to pop of stats until there are no more, or we're under
    // budget. As we trim anything we want to keep, e.g. with force_keep_col,
    // we stash it here, and later re-append.
    let mut stats_to_keep = Vec::with_capacity(stats.elements.len());

    while *budget_shortfall > 0 {
        let Some(mut column) = stats.elements.pop() else {
            break;
        };

        // We're force keeping this column.
        if force_keep_col(&column.name) {
            stats_to_keep.push(column);
            continue;
        }

        // If the col is another JSON map, recurse into it and trim its stats.
        if let Some(ProtoJsonStats {
            kind: Some(proto_json_stats::Kind::Maps(ref mut col_jsonb)),
        }) = column.stats
        {
            trim_to_budget_jsonb(col_jsonb, budget_shortfall, force_keep_col);

            // We still have some columns left after trimming, so we want to keep these stats.
            if !col_jsonb.elements.is_empty() {
                stats_to_keep.push(column);
            }

            // We've trimmed enough, so we can stop recursing!
            if *budget_shortfall == 0 {
                break;
            }
        } else {
            // Each field costs at least the cost of serializing the value
            // and a byte for the tag. (Though a tag may be more than one
            // byte in extreme cases.)
            *budget_shortfall = budget_shortfall.saturating_sub(column.encoded_len() + 1);
        }
    }

    // Re-add all of the stats we want to keep.
    stats.elements.extend(stats_to_keep);
}

mod impls {
    use std::any::Any;
    use std::collections::BTreeMap;
    use std::fmt::Debug;

    use arrow2::array::{BinaryArray, BooleanArray, PrimitiveArray, Utf8Array};
    use arrow2::bitmap::Bitmap;
    use arrow2::buffer::Buffer;
    use arrow2::compute::aggregate::SimdOrd;
    use arrow2::types::simd::Simd;
    use arrow2::types::NativeType;
    use mz_proto::{IntoRustIfSome, ProtoType, RustType, TryFromProtoError};
    use proptest::strategy::Union;
    use proptest::{collection, prelude::*};
    use serde::Serialize;

    use crate::columnar::Data;
    use crate::dyn_struct::{DynStruct, DynStructCol, ValidityRef};
    use crate::stats::{
        proto_bytes_stats, proto_dyn_stats, proto_json_stats, proto_primitive_stats,
        truncate_bytes, truncate_string, AtomicBytesStats, BytesStats, ColumnStats, DynStats,
        JsonMapElementStats, JsonStats, NoneStats, OptionStats, PrimitiveStats,
        ProtoAtomicBytesStats, ProtoBytesStats, ProtoDynStats, ProtoJsonMapElementStats,
        ProtoJsonMapStats, ProtoJsonStats, ProtoOptionStats, ProtoPrimitiveBytesStats,
        ProtoPrimitiveStats, ProtoStructStats, StatsFrom, StructStats, TruncateBound, TRUNCATE_LEN,
    };

    impl<T: Serialize> Debug for PrimitiveStats<T>
    where
        PrimitiveStats<T>: RustType<ProtoPrimitiveStats>,
    {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let l = serde_json::to_value(&self.lower).expect("valid json");
            let u = serde_json::to_value(&self.upper).expect("valid json");
            Debug::fmt(&serde_json::json!({"lower": l, "upper": u}), f)
        }
    }

    impl<T: Serialize> DynStats for PrimitiveStats<T>
    where
        PrimitiveStats<T>: RustType<ProtoPrimitiveStats> + Send + Sync + 'static,
    {
        fn as_any(&self) -> &dyn Any {
            self
        }
        fn into_proto(&self) -> ProtoDynStats {
            ProtoDynStats {
                option: None,
                kind: Some(proto_dyn_stats::Kind::Primitive(RustType::into_proto(self))),
            }
        }
        fn debug_json(&self) -> serde_json::Value {
            let l = serde_json::to_value(&self.lower).expect("valid json");
            let u = serde_json::to_value(&self.upper).expect("valid json");
            serde_json::json!({"lower": l, "upper": u})
        }
    }

    impl Debug for PrimitiveStats<Vec<u8>> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            Debug::fmt(&self.debug_json(), f)
        }
    }

    impl DynStats for PrimitiveStats<Vec<u8>> {
        fn as_any(&self) -> &dyn Any {
            self
        }
        fn into_proto(&self) -> ProtoDynStats {
            ProtoDynStats {
                option: None,
                kind: Some(proto_dyn_stats::Kind::Bytes(ProtoBytesStats {
                    kind: Some(proto_bytes_stats::Kind::Primitive(RustType::into_proto(
                        self,
                    ))),
                })),
            }
        }
        fn debug_json(&self) -> serde_json::Value {
            serde_json::json!({
                "lower": hex::encode(&self.lower),
                "upper": hex::encode(&self.upper),
            })
        }
    }

    impl<T: DynStats> Debug for OptionStats<T> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            Debug::fmt(&self.debug_json(), f)
        }
    }

    impl<T: DynStats> DynStats for OptionStats<T> {
        fn as_any(&self) -> &dyn Any {
            self
        }
        fn into_proto(&self) -> ProtoDynStats {
            let mut ret = self.some.into_proto();
            // This prevents us from serializing `OptionStats<OptionStats<T>>`, but
            // that's intentionally out of scope. See the comment on ProtoDynStats.
            assert!(ret.option.is_none());
            ret.option = Some(ProtoOptionStats {
                none: self.none.into_proto(),
            });
            ret
        }
        fn debug_json(&self) -> serde_json::Value {
            match self.some.debug_json() {
                serde_json::Value::Object(mut x) => {
                    if self.none > 0 {
                        x.insert("nulls".to_owned(), self.none.into());
                    }
                    serde_json::Value::Object(x)
                }
                s => {
                    serde_json::json!({"nulls": self.none, "not nulls": s})
                }
            }
        }
    }

    impl DynStats for StructStats {
        fn as_any(&self) -> &dyn Any {
            self
        }
        fn into_proto(&self) -> ProtoDynStats {
            ProtoDynStats {
                option: None,
                kind: Some(proto_dyn_stats::Kind::Struct(RustType::into_proto(self))),
            }
        }
        fn debug_json(&self) -> serde_json::Value {
            let mut cols = serde_json::Map::new();
            cols.insert("len".to_owned(), self.len.into());
            for (name, stats) in self.cols.iter() {
                cols.insert(name.clone(), stats.debug_json());
            }
            cols.into()
        }
    }

    impl Debug for BytesStats {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            Debug::fmt(&self.debug_json(), f)
        }
    }

    impl DynStats for BytesStats {
        fn as_any(&self) -> &dyn Any {
            self
        }
        fn into_proto(&self) -> ProtoDynStats {
            ProtoDynStats {
                option: None,
                kind: Some(proto_dyn_stats::Kind::Bytes(RustType::into_proto(self))),
            }
        }
        fn debug_json(&self) -> serde_json::Value {
            match self {
                BytesStats::Primitive(x) => x.debug_json(),
                BytesStats::Json(x) => x.debug_json(),
                BytesStats::Atomic(x) => x.debug_json(),
            }
        }
    }

    impl DynStats for NoneStats {
        fn as_any(&self) -> &dyn Any {
            self
        }

        fn into_proto(&self) -> ProtoDynStats {
            ProtoDynStats {
                option: None,
                kind: Some(proto_dyn_stats::Kind::None(RustType::into_proto(self))),
            }
        }

        fn debug_json(&self) -> serde_json::Value {
            serde_json::Value::String(format!("{self:?}"))
        }
    }

    macro_rules! stats_primitive {
        ($data:ty, $ref:ident) => {
            impl ColumnStats<$data> for PrimitiveStats<$data> {
                fn lower<'a>(&'a self) -> Option<<$data as Data>::Ref<'a>> {
                    Some(self.lower.$ref())
                }
                fn upper<'a>(&'a self) -> Option<<$data as Data>::Ref<'a>> {
                    Some(self.upper.$ref())
                }
                fn none_count(&self) -> usize {
                    0
                }
            }

            impl ColumnStats<Option<$data>> for OptionStats<PrimitiveStats<$data>> {
                fn lower<'a>(&'a self) -> Option<<Option<$data> as Data>::Ref<'a>> {
                    Some(self.some.lower())
                }
                fn upper<'a>(&'a self) -> Option<<Option<$data> as Data>::Ref<'a>> {
                    Some(self.some.upper())
                }
                fn none_count(&self) -> usize {
                    self.none
                }
            }
        };
    }

    stats_primitive!(bool, clone);
    stats_primitive!(u8, clone);
    stats_primitive!(u16, clone);
    stats_primitive!(u32, clone);
    stats_primitive!(u64, clone);
    stats_primitive!(i8, clone);
    stats_primitive!(i16, clone);
    stats_primitive!(i32, clone);
    stats_primitive!(i64, clone);
    stats_primitive!(f32, clone);
    stats_primitive!(f64, clone);
    stats_primitive!(Vec<u8>, as_slice);
    stats_primitive!(String, as_str);

    impl ColumnStats<Vec<u8>> for BytesStats {
        fn lower<'a>(&'a self) -> Option<<Vec<u8> as Data>::Ref<'a>> {
            match self {
                BytesStats::Primitive(x) => x.lower(),
                BytesStats::Json(_) => None,
                BytesStats::Atomic(x) => Some(&x.lower),
            }
        }
        fn upper<'a>(&'a self) -> Option<<Vec<u8> as Data>::Ref<'a>> {
            match self {
                BytesStats::Primitive(x) => x.upper(),
                BytesStats::Json(_) => None,
                BytesStats::Atomic(x) => Some(&x.upper),
            }
        }
        fn none_count(&self) -> usize {
            0
        }
    }

    impl ColumnStats<Option<Vec<u8>>> for OptionStats<BytesStats> {
        fn lower<'a>(&'a self) -> Option<<Option<Vec<u8>> as Data>::Ref<'a>> {
            self.some.lower().map(Some)
        }
        fn upper<'a>(&'a self) -> Option<<Option<Vec<u8>> as Data>::Ref<'a>> {
            self.some.upper().map(Some)
        }
        fn none_count(&self) -> usize {
            self.none
        }
    }

    impl ColumnStats<DynStruct> for StructStats {
        fn lower<'a>(&'a self) -> Option<<DynStruct as Data>::Ref<'a>> {
            // Not meaningful for structs
            None
        }
        fn upper<'a>(&'a self) -> Option<<DynStruct as Data>::Ref<'a>> {
            // Not meaningful for structs
            None
        }
        fn none_count(&self) -> usize {
            0
        }
    }

    impl ColumnStats<Option<DynStruct>> for OptionStats<StructStats> {
        fn lower<'a>(&'a self) -> Option<<Option<DynStruct> as Data>::Ref<'a>> {
            self.some.lower().map(Some)
        }
        fn upper<'a>(&'a self) -> Option<<Option<DynStruct> as Data>::Ref<'a>> {
            self.some.upper().map(Some)
        }
        fn none_count(&self) -> usize {
            self.none
        }
    }

    impl<T: Data> ColumnStats<T> for NoneStats {
        fn lower<'a>(&'a self) -> Option<<T as Data>::Ref<'a>> {
            None
        }

        fn upper<'a>(&'a self) -> Option<<T as Data>::Ref<'a>> {
            None
        }

        fn none_count(&self) -> usize {
            0
        }
    }

    impl<T> ColumnStats<Option<T>> for OptionStats<NoneStats>
    where
        Option<T>: Data,
    {
        fn lower<'a>(&'a self) -> Option<<Option<T> as Data>::Ref<'a>> {
            None
        }

        fn upper<'a>(&'a self) -> Option<<Option<T> as Data>::Ref<'a>> {
            None
        }

        fn none_count(&self) -> usize {
            self.none
        }
    }

    impl StatsFrom<Bitmap> for PrimitiveStats<bool> {
        fn stats_from(col: &Bitmap, validity: ValidityRef) -> Self {
            let array = BooleanArray::new(
                arrow2::datatypes::DataType::Boolean,
                col.clone(),
                validity.0.as_ref().cloned(),
            );
            let lower = arrow2::compute::aggregate::min_boolean(&array).unwrap_or_default();
            let upper = arrow2::compute::aggregate::max_boolean(&array).unwrap_or_default();
            PrimitiveStats { lower, upper }
        }
    }

    impl StatsFrom<BooleanArray> for OptionStats<PrimitiveStats<bool>> {
        fn stats_from(col: &BooleanArray, validity: ValidityRef) -> Self {
            debug_assert!(validity.is_superset(col.validity()));
            let lower = arrow2::compute::aggregate::min_boolean(col).unwrap_or_default();
            let upper = arrow2::compute::aggregate::max_boolean(col).unwrap_or_default();
            let none = col.validity().map_or(0, |x| x.unset_bits());
            OptionStats {
                none,
                some: PrimitiveStats { lower, upper },
            }
        }
    }

    impl<T> StatsFrom<Buffer<T>> for PrimitiveStats<T>
    where
        T: NativeType + Simd,
        T::Simd: SimdOrd<T>,
    {
        fn stats_from(col: &Buffer<T>, validity: ValidityRef) -> Self {
            let array = PrimitiveArray::new(
                T::PRIMITIVE.into(),
                col.clone(),
                validity.0.as_ref().cloned(),
            );
            let lower = arrow2::compute::aggregate::min_primitive::<T>(&array).unwrap_or_default();
            let upper = arrow2::compute::aggregate::max_primitive::<T>(&array).unwrap_or_default();
            PrimitiveStats { lower, upper }
        }
    }

    impl<T> StatsFrom<PrimitiveArray<T>> for OptionStats<PrimitiveStats<T>>
    where
        T: Data + NativeType + Simd,
        T::Simd: SimdOrd<T>,
    {
        fn stats_from(col: &PrimitiveArray<T>, validity: ValidityRef) -> Self {
            debug_assert!(validity.is_superset(col.validity()));
            let lower = arrow2::compute::aggregate::min_primitive::<T>(col).unwrap_or_default();
            let upper = arrow2::compute::aggregate::max_primitive::<T>(col).unwrap_or_default();
            let none = col.validity().map_or(0, |x| x.unset_bits());
            OptionStats {
                none,
                some: PrimitiveStats { lower, upper },
            }
        }
    }

    impl StatsFrom<BinaryArray<i32>> for PrimitiveStats<Vec<u8>> {
        fn stats_from(col: &BinaryArray<i32>, validity: ValidityRef) -> Self {
            assert!(col.validity().is_none());
            let mut array = col.clone();
            array.set_validity(validity.0.as_ref().cloned());
            let lower = arrow2::compute::aggregate::min_binary(&array).unwrap_or_default();
            let lower = truncate_bytes(lower, TRUNCATE_LEN, TruncateBound::Lower)
                .expect("lower bound should always truncate");
            let upper = arrow2::compute::aggregate::max_binary(&array).unwrap_or_default();
            let upper = truncate_bytes(upper, TRUNCATE_LEN, TruncateBound::Upper)
                // NB: The cost+trim stuff will remove the column entirely if
                // it's still too big (also this should be extremely rare in
                // practice).
                .unwrap_or_else(|| upper.to_owned());
            PrimitiveStats { lower, upper }
        }
    }

    impl StatsFrom<BinaryArray<i32>> for OptionStats<PrimitiveStats<Vec<u8>>> {
        fn stats_from(col: &BinaryArray<i32>, validity: ValidityRef) -> Self {
            debug_assert!(validity.is_superset(col.validity()));
            let lower = arrow2::compute::aggregate::min_binary(col).unwrap_or_default();
            let lower = truncate_bytes(lower, TRUNCATE_LEN, TruncateBound::Lower)
                .expect("lower bound should always truncate");
            let upper = arrow2::compute::aggregate::max_binary(col).unwrap_or_default();
            let upper = truncate_bytes(upper, TRUNCATE_LEN, TruncateBound::Upper)
                // NB: The cost+trim stuff will remove the column entirely if
                // it's still too big (also this should be extremely rare in
                // practice).
                .unwrap_or_else(|| upper.to_owned());
            let none = col.validity().map_or(0, |x| x.unset_bits());
            OptionStats {
                none,
                some: PrimitiveStats { lower, upper },
            }
        }
    }

    impl StatsFrom<BinaryArray<i32>> for BytesStats {
        fn stats_from(col: &BinaryArray<i32>, validity: ValidityRef) -> Self {
            BytesStats::Primitive(<PrimitiveStats<Vec<u8>>>::stats_from(col, validity))
        }
    }

    impl StatsFrom<BinaryArray<i32>> for OptionStats<BytesStats> {
        fn stats_from(col: &BinaryArray<i32>, validity: ValidityRef) -> Self {
            let stats = OptionStats::<PrimitiveStats<Vec<u8>>>::stats_from(col, validity);
            OptionStats {
                none: stats.none,
                some: BytesStats::Primitive(stats.some),
            }
        }
    }

    impl StatsFrom<Utf8Array<i32>> for PrimitiveStats<String> {
        fn stats_from(col: &Utf8Array<i32>, validity: ValidityRef) -> Self {
            assert!(col.validity().is_none());
            let mut array = col.clone();
            array.set_validity(validity.0.as_ref().cloned());
            let lower = arrow2::compute::aggregate::min_string(&array).unwrap_or_default();
            let lower = truncate_string(lower, TRUNCATE_LEN, TruncateBound::Lower)
                .expect("lower bound should always truncate");
            let upper = arrow2::compute::aggregate::max_string(&array).unwrap_or_default();
            let upper = truncate_string(upper, TRUNCATE_LEN, TruncateBound::Upper)
                // NB: The cost+trim stuff will remove the column entirely if
                // it's still too big (also this should be extremely rare in
                // practice).
                .unwrap_or_else(|| upper.to_owned());
            PrimitiveStats { lower, upper }
        }
    }

    impl StatsFrom<Utf8Array<i32>> for OptionStats<PrimitiveStats<String>> {
        fn stats_from(col: &Utf8Array<i32>, validity: ValidityRef) -> Self {
            debug_assert!(validity.is_superset(col.validity()));
            let lower = arrow2::compute::aggregate::min_string(col).unwrap_or_default();
            let lower = truncate_string(lower, TRUNCATE_LEN, TruncateBound::Lower)
                .expect("lower bound should always truncate");
            let upper = arrow2::compute::aggregate::max_string(col).unwrap_or_default();
            let upper = truncate_string(upper, TRUNCATE_LEN, TruncateBound::Upper)
                // NB: The cost+trim stuff will remove the column entirely if
                // it's still too big (also this should be extremely rare in
                // practice).
                .unwrap_or_else(|| upper.to_owned());
            let none = col.validity().map_or(0, |x| x.unset_bits());
            OptionStats {
                none,
                some: PrimitiveStats { lower, upper },
            }
        }
    }

    impl StatsFrom<DynStructCol> for StructStats {
        fn stats_from(col: &DynStructCol, validity: ValidityRef) -> Self {
            assert!(col.validity.is_none());
            col.stats(validity).expect("valid stats").some
        }
    }

    impl StatsFrom<DynStructCol> for OptionStats<StructStats> {
        fn stats_from(col: &DynStructCol, validity: ValidityRef) -> Self {
            debug_assert!(validity.is_superset(col.validity.as_ref()));
            col.stats(validity).expect("valid stats")
        }
    }

    impl<T: arrow2::array::Array> StatsFrom<T> for NoneStats {
        fn stats_from(col: &T, _validity: ValidityRef) -> Self {
            assert!(col.validity().is_none());
            NoneStats
        }
    }

    impl<T: arrow2::array::Array> StatsFrom<T> for OptionStats<NoneStats> {
        fn stats_from(col: &T, validity: ValidityRef) -> Self {
            debug_assert!(validity.is_superset(col.validity()));
            let none = col.validity().map_or(0, |x| x.unset_bits());
            OptionStats {
                none,
                some: NoneStats,
            }
        }
    }

    impl RustType<ProtoStructStats> for StructStats {
        fn into_proto(&self) -> ProtoStructStats {
            ProtoStructStats {
                len: self.len.into_proto(),
                cols: self
                    .cols
                    .iter()
                    .map(|(k, v)| (k.into_proto(), v.into_proto()))
                    .collect(),
            }
        }

        fn from_proto(proto: ProtoStructStats) -> Result<Self, TryFromProtoError> {
            let mut cols = BTreeMap::new();
            for (k, v) in proto.cols {
                cols.insert(k.into_rust()?, v.into_rust()?);
            }
            Ok(StructStats {
                len: proto.len.into_rust()?,
                cols,
            })
        }
    }

    impl RustType<ProtoJsonStats> for JsonStats {
        fn into_proto(&self) -> ProtoJsonStats {
            ProtoJsonStats {
                kind: Some(match self {
                    JsonStats::None => proto_json_stats::Kind::None(()),
                    JsonStats::Mixed => proto_json_stats::Kind::Mixed(()),
                    JsonStats::JsonNulls => proto_json_stats::Kind::JsonNulls(()),
                    JsonStats::Bools(x) => proto_json_stats::Kind::Bools(RustType::into_proto(x)),
                    JsonStats::Strings(x) => {
                        proto_json_stats::Kind::Strings(RustType::into_proto(x))
                    }
                    JsonStats::Numerics(x) => {
                        proto_json_stats::Kind::Numerics(RustType::into_proto(x))
                    }
                    JsonStats::Lists => proto_json_stats::Kind::Lists(()),
                    JsonStats::Maps(x) => proto_json_stats::Kind::Maps(ProtoJsonMapStats {
                        elements: x
                            .iter()
                            .map(|(k, v)| ProtoJsonMapElementStats {
                                name: k.into_proto(),
                                len: v.len.into_proto(),
                                stats: Some(RustType::into_proto(&v.stats)),
                            })
                            .collect(),
                    }),
                }),
            }
        }

        fn from_proto(proto: ProtoJsonStats) -> Result<Self, TryFromProtoError> {
            Ok(match proto.kind {
                Some(proto_json_stats::Kind::None(())) => JsonStats::None,
                Some(proto_json_stats::Kind::Mixed(())) => JsonStats::Mixed,
                Some(proto_json_stats::Kind::JsonNulls(())) => JsonStats::JsonNulls,
                Some(proto_json_stats::Kind::Bools(x)) => JsonStats::Bools(x.into_rust()?),
                Some(proto_json_stats::Kind::Strings(x)) => JsonStats::Strings(x.into_rust()?),
                Some(proto_json_stats::Kind::Numerics(x)) => JsonStats::Numerics(x.into_rust()?),
                Some(proto_json_stats::Kind::Lists(())) => JsonStats::Lists,
                Some(proto_json_stats::Kind::Maps(x)) => {
                    let mut elements = BTreeMap::new();
                    for x in x.elements {
                        let stats = JsonMapElementStats {
                            len: x.len.into_rust()?,
                            stats: x.stats.into_rust_if_some("JsonMapElementStats::stats")?,
                        };
                        elements.insert(x.name.into_rust()?, stats);
                    }
                    JsonStats::Maps(elements)
                }
                // Unknown JSON stats type: assume this might have any value.
                None => JsonStats::Mixed,
            })
        }
    }

    impl RustType<ProtoBytesStats> for BytesStats {
        fn into_proto(&self) -> ProtoBytesStats {
            let kind = match self {
                BytesStats::Primitive(x) => {
                    proto_bytes_stats::Kind::Primitive(RustType::into_proto(x))
                }
                BytesStats::Json(x) => proto_bytes_stats::Kind::Json(RustType::into_proto(x)),
                BytesStats::Atomic(x) => proto_bytes_stats::Kind::Atomic(RustType::into_proto(x)),
            };
            ProtoBytesStats { kind: Some(kind) }
        }

        fn from_proto(proto: ProtoBytesStats) -> Result<Self, TryFromProtoError> {
            match proto.kind {
                Some(proto_bytes_stats::Kind::Primitive(x)) => Ok(BytesStats::Primitive(
                    PrimitiveStats::<Vec<u8>>::from_proto(x)?,
                )),
                Some(proto_bytes_stats::Kind::Json(x)) => {
                    Ok(BytesStats::Json(JsonStats::from_proto(x)?))
                }
                Some(proto_bytes_stats::Kind::Atomic(x)) => {
                    Ok(BytesStats::Atomic(AtomicBytesStats::from_proto(x)?))
                }
                None => Err(TryFromProtoError::missing_field("ProtoBytesStats::kind")),
            }
        }
    }

    impl RustType<ProtoAtomicBytesStats> for AtomicBytesStats {
        fn into_proto(&self) -> ProtoAtomicBytesStats {
            ProtoAtomicBytesStats {
                lower: self.lower.into_proto(),
                upper: self.upper.into_proto(),
            }
        }

        fn from_proto(proto: ProtoAtomicBytesStats) -> Result<Self, TryFromProtoError> {
            Ok(AtomicBytesStats {
                lower: proto.lower.into_rust()?,
                upper: proto.upper.into_rust()?,
            })
        }
    }

    impl RustType<()> for NoneStats {
        fn into_proto(&self) -> () {
            ()
        }

        fn from_proto(_proto: ()) -> Result<Self, TryFromProtoError> {
            Ok(NoneStats)
        }
    }

    impl RustType<ProtoDynStats> for Box<dyn DynStats> {
        fn into_proto(&self) -> ProtoDynStats {
            DynStats::into_proto(self.as_ref())
        }

        fn from_proto(mut proto: ProtoDynStats) -> Result<Self, TryFromProtoError> {
            struct BoxFn;
            impl DynStatsFn<Box<dyn DynStats>> for BoxFn {
                fn call<T: DynStats>(self, t: T) -> Result<Box<dyn DynStats>, TryFromProtoError> {
                    Ok(Box::new(t))
                }
            }
            struct OptionStatsFn<F>(usize, F);
            impl<R, F: DynStatsFn<R>> DynStatsFn<R> for OptionStatsFn<F> {
                fn call<T: DynStats>(self, some: T) -> Result<R, TryFromProtoError> {
                    let OptionStatsFn(none, f) = self;
                    f.call(OptionStats { none, some })
                }
            }

            match proto.option.take() {
                Some(option) => {
                    let none = option.none.into_rust()?;
                    dyn_from_proto(proto, OptionStatsFn(none, BoxFn))
                }
                None => dyn_from_proto(proto, BoxFn),
            }
        }
    }

    /// Basically `FnOnce<T: DynStats>(self, t: T) -> R`, if rust would let us
    /// type that.
    ///
    /// We use this in `dyn_from_proto` so that OptionStats can hold a `some: T`
    /// instead of a `Box<dyn DynStats>`.
    trait DynStatsFn<R> {
        fn call<T: DynStats>(self, t: T) -> Result<R, TryFromProtoError>;
    }

    fn dyn_from_proto<R, F: DynStatsFn<R>>(
        proto: ProtoDynStats,
        f: F,
    ) -> Result<R, TryFromProtoError> {
        assert!(proto.option.is_none());
        let kind = proto
            .kind
            .ok_or_else(|| TryFromProtoError::missing_field("ProtoDynStats::kind"))?;
        match kind {
            // Sniff the type of x.lower and use that to determine which type of
            // PrimitiveStats to decode it as.
            proto_dyn_stats::Kind::Primitive(x) => match x.lower {
                Some(proto_primitive_stats::Lower::LowerBool(_)) => {
                    f.call(PrimitiveStats::<bool>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerU8(_)) => {
                    f.call(PrimitiveStats::<u8>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerU16(_)) => {
                    f.call(PrimitiveStats::<u16>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerU32(_)) => {
                    f.call(PrimitiveStats::<u32>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerU64(_)) => {
                    f.call(PrimitiveStats::<u64>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerI8(_)) => {
                    f.call(PrimitiveStats::<i8>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerI16(_)) => {
                    f.call(PrimitiveStats::<i16>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerI32(_)) => {
                    f.call(PrimitiveStats::<i32>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerI64(_)) => {
                    f.call(PrimitiveStats::<i64>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerF32(_)) => {
                    f.call(PrimitiveStats::<f32>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerF64(_)) => {
                    f.call(PrimitiveStats::<f64>::from_proto(x)?)
                }
                Some(proto_primitive_stats::Lower::LowerString(_)) => {
                    f.call(PrimitiveStats::<String>::from_proto(x)?)
                }
                None => Err(TryFromProtoError::missing_field("ProtoPrimitiveStats::min")),
            },
            proto_dyn_stats::Kind::Struct(x) => f.call(StructStats::from_proto(x)?),
            proto_dyn_stats::Kind::Bytes(x) => f.call(BytesStats::from_proto(x)?),
            proto_dyn_stats::Kind::None(x) => f.call(NoneStats::from_proto(x)?),
        }
    }

    macro_rules! primitive_stats_rust_type {
        ($typ:ty, $lower:ident, $upper:ident) => {
            impl RustType<ProtoPrimitiveStats> for PrimitiveStats<$typ> {
                fn into_proto(&self) -> ProtoPrimitiveStats {
                    ProtoPrimitiveStats {
                        lower: Some(proto_primitive_stats::Lower::$lower(
                            self.lower.into_proto(),
                        )),
                        upper: Some(proto_primitive_stats::Upper::$upper(
                            self.upper.into_proto(),
                        )),
                    }
                }

                fn from_proto(proto: ProtoPrimitiveStats) -> Result<Self, TryFromProtoError> {
                    let lower = proto.lower.ok_or_else(|| {
                        TryFromProtoError::missing_field("ProtoPrimitiveStats::lower")
                    })?;
                    let lower = match lower {
                        proto_primitive_stats::Lower::$lower(x) => x.into_rust()?,
                        _ => {
                            return Err(TryFromProtoError::missing_field(
                                "proto_primitive_stats::Lower::$lower",
                            ))
                        }
                    };
                    let upper = proto.upper.ok_or_else(|| {
                        TryFromProtoError::missing_field("ProtoPrimitiveStats::max")
                    })?;
                    let upper = match upper {
                        proto_primitive_stats::Upper::$upper(x) => x.into_rust()?,
                        _ => {
                            return Err(TryFromProtoError::missing_field(
                                "proto_primitive_stats::Upper::$upper",
                            ))
                        }
                    };
                    Ok(PrimitiveStats { lower, upper })
                }
            }
        };
    }

    primitive_stats_rust_type!(bool, LowerBool, UpperBool);
    primitive_stats_rust_type!(u8, LowerU8, UpperU8);
    primitive_stats_rust_type!(u16, LowerU16, UpperU16);
    primitive_stats_rust_type!(u32, LowerU32, UpperU32);
    primitive_stats_rust_type!(u64, LowerU64, UpperU64);
    primitive_stats_rust_type!(i8, LowerI8, UpperI8);
    primitive_stats_rust_type!(i16, LowerI16, UpperI16);
    primitive_stats_rust_type!(i32, LowerI32, UpperI32);
    primitive_stats_rust_type!(i64, LowerI64, UpperI64);
    primitive_stats_rust_type!(f32, LowerF32, UpperF32);
    primitive_stats_rust_type!(f64, LowerF64, UpperF64);
    primitive_stats_rust_type!(String, LowerString, UpperString);

    impl RustType<ProtoPrimitiveBytesStats> for PrimitiveStats<Vec<u8>> {
        fn into_proto(&self) -> ProtoPrimitiveBytesStats {
            ProtoPrimitiveBytesStats {
                lower: self.lower.into_proto(),
                upper: self.upper.into_proto(),
            }
        }

        fn from_proto(proto: ProtoPrimitiveBytesStats) -> Result<Self, TryFromProtoError> {
            let lower = proto.lower.into_rust()?;
            let upper = proto.upper.into_rust()?;
            Ok(PrimitiveStats { lower, upper })
        }
    }

    pub(crate) fn any_struct_stats_cols(
    ) -> impl Strategy<Value = BTreeMap<String, Box<dyn DynStats>>> {
        collection::btree_map(any::<String>(), any_box_dyn_stats(), 1..5)
    }

    fn any_primitive_stats<T>() -> impl Strategy<Value = PrimitiveStats<T>>
    where
        T: Arbitrary + Ord + Serialize,
        PrimitiveStats<T>: RustType<ProtoPrimitiveStats>,
    {
        Strategy::prop_map(any::<(T, T)>(), |(x0, x1)| {
            if x0 <= x1 {
                PrimitiveStats {
                    lower: x0,
                    upper: x1,
                }
            } else {
                PrimitiveStats {
                    lower: x1,
                    upper: x0,
                }
            }
        })
    }

    fn any_primitive_vec_u8_stats() -> impl Strategy<Value = PrimitiveStats<Vec<u8>>> {
        Strategy::prop_map(any::<(Vec<u8>, Vec<u8>)>(), |(x0, x1)| {
            if x0 <= x1 {
                PrimitiveStats {
                    lower: x0,
                    upper: x1,
                }
            } else {
                PrimitiveStats {
                    lower: x1,
                    upper: x0,
                }
            }
        })
    }

    fn any_bytes_stats() -> impl Strategy<Value = BytesStats> {
        Union::new(vec![
            any_primitive_vec_u8_stats()
                .prop_map(BytesStats::Primitive)
                .boxed(),
            any_json_stats().prop_map(BytesStats::Json).boxed(),
            any_primitive_vec_u8_stats()
                .prop_map(|x| {
                    BytesStats::Atomic(AtomicBytesStats {
                        lower: x.lower,
                        upper: x.upper,
                    })
                })
                .boxed(),
        ])
    }

    fn any_json_stats() -> impl Strategy<Value = JsonStats> {
        let leaf = Union::new(vec![
            any::<()>().prop_map(|_| JsonStats::None).boxed(),
            any::<()>().prop_map(|_| JsonStats::Mixed).boxed(),
            any::<()>().prop_map(|_| JsonStats::JsonNulls).boxed(),
            any_primitive_stats::<bool>()
                .prop_map(JsonStats::Bools)
                .boxed(),
            any_primitive_stats::<String>()
                .prop_map(JsonStats::Strings)
                .boxed(),
            any::<()>().prop_map(|_| JsonStats::Lists).boxed(),
        ]);
        leaf.prop_recursive(2, 5, 3, |inner| {
            (collection::btree_map(any::<String>(), inner, 0..3)).prop_map(|cols| {
                let cols = cols
                    .into_iter()
                    .map(|(k, stats)| (k, JsonMapElementStats { len: 1, stats }))
                    .collect();
                JsonStats::Maps(cols)
            })
        })
    }

    fn any_box_dyn_stats() -> impl Strategy<Value = Box<dyn DynStats>> {
        fn into_box_dyn_stats<T: DynStats>(x: T) -> Box<dyn DynStats> {
            let x: Box<dyn DynStats> = Box::new(x);
            x
        }
        let leaf = Union::new(vec![
            any_primitive_stats::<bool>()
                .prop_map(into_box_dyn_stats)
                .boxed(),
            any_primitive_stats::<i64>()
                .prop_map(into_box_dyn_stats)
                .boxed(),
            any_primitive_stats::<String>()
                .prop_map(into_box_dyn_stats)
                .boxed(),
            any_bytes_stats().prop_map(into_box_dyn_stats).boxed(),
        ]);
        leaf.prop_recursive(2, 10, 3, |inner| {
            (
                any::<usize>(),
                collection::btree_map(any::<String>(), inner, 0..3),
            )
                .prop_map(|(len, cols)| into_box_dyn_stats(StructStats { len, cols }))
        })
    }
}

#[cfg(test)]
mod tests {
    use arrow2::array::BinaryArray;
    use mz_proto::RustType;
    use proptest::prelude::*;

    use crate::columnar::sealed::ColumnMut;
    use crate::columnar::ColumnPush;
    use crate::dyn_struct::ValidityRef;

    use super::*;

    #[mz_ore::test]
    fn test_truncate_bytes() {
        #[track_caller]
        fn testcase(x: &[u8], max_len: usize, upper_should_exist: bool) {
            let lower = truncate_bytes(x, max_len, TruncateBound::Lower)
                .expect("lower should always exist");
            assert!(lower.len() <= max_len);
            assert!(lower.as_slice() <= x);
            let upper = truncate_bytes(x, max_len, TruncateBound::Upper);
            assert_eq!(upper_should_exist, upper.is_some());
            if let Some(upper) = upper {
                assert!(upper.len() <= max_len);
                assert!(upper.as_slice() >= x);
            }
        }

        testcase(&[], 0, true);
        testcase(&[], 1, true);
        testcase(&[1], 0, false);
        testcase(&[1], 1, true);
        testcase(&[1], 2, true);
        testcase(&[1, 2], 1, true);
        testcase(&[1, 255], 2, true);
        testcase(&[255, 255], 2, true);
        testcase(&[255, 255, 255], 2, false);
    }

    #[mz_ore::test]
    #[cfg_attr(miri, ignore)] // too slow
    fn test_truncate_bytes_proptest() {
        fn testcase(x: &[u8]) {
            for max_len in 0..=x.len() {
                let lower = truncate_bytes(x, max_len, TruncateBound::Lower)
                    .expect("lower should always exist");
                let upper = truncate_bytes(x, max_len, TruncateBound::Upper);
                assert!(lower.len() <= max_len);
                assert!(lower.as_slice() <= x);
                if let Some(upper) = upper {
                    assert!(upper.len() <= max_len);
                    assert!(upper.as_slice() >= x);
                }
            }
        }

        proptest!(|(x in any::<Vec<u8>>())| {
            // The proptest! macro interferes with rustfmt.
            testcase(x.as_slice())
        });
    }

    #[mz_ore::test]
    fn test_truncate_string() {
        #[track_caller]
        fn testcase(x: &str, max_len: usize, upper_should_exist: bool) {
            let lower = truncate_string(x, max_len, TruncateBound::Lower)
                .expect("lower should always exist");
            let upper = truncate_string(x, max_len, TruncateBound::Upper);
            assert!(lower.len() <= max_len);
            assert!(lower.as_str() <= x);
            assert_eq!(upper_should_exist, upper.is_some());
            if let Some(upper) = upper {
                assert!(upper.len() <= max_len);
                assert!(upper.as_str() >= x);
            }
        }

        testcase("", 0, true);
        testcase("1", 0, false);
        testcase("1", 1, true);
        testcase("12", 1, true);
        testcase("⛄", 0, false);
        testcase("⛄", 1, false);
        testcase("⛄", 3, true);
        testcase("\u{10FFFF}", 3, false);
        testcase("\u{10FFFF}", 4, true);
        testcase("\u{10FFFF}", 5, true);
        testcase("⛄⛄", 3, true);
        testcase("⛄⛄", 4, true);
        testcase("⛄\u{10FFFF}", 6, true);
        testcase("⛄\u{10FFFF}", 7, true);
        testcase("\u{10FFFF}\u{10FFFF}", 7, false);
        testcase("\u{10FFFF}\u{10FFFF}", 8, true);

        // Just because I find this to be delightful.
        assert_eq!(
            truncate_string("⛄⛄", 3, TruncateBound::Upper),
            Some("⛅".to_string())
        );
    }

    #[mz_ore::test]
    #[cfg_attr(miri, ignore)] // too slow
    fn test_truncate_string_proptest() {
        fn testcase(x: &str) {
            for max_len in 0..=x.len() {
                let lower = truncate_string(x, max_len, TruncateBound::Lower)
                    .expect("lower should always exist");
                let upper = truncate_string(x, max_len, TruncateBound::Upper);
                assert!(lower.len() <= max_len);
                assert!(lower.as_str() <= x);
                if let Some(upper) = upper {
                    // As explained in a comment in the impl, we don't quite
                    // treat the max_len as a hard bound here. Give it a little
                    // wiggle room.
                    assert!(upper.len() <= max_len + char::MAX.len_utf8());
                    assert!(upper.as_str() >= x);
                }
            }
        }

        proptest!(|(x in any::<String>())| {
            // The proptest! macro interferes with rustfmt.
            testcase(x.as_str())
        });
    }

    #[mz_ore::test]
    #[cfg_attr(miri, ignore)] // too slow
    fn primitive_cost_trim_proptest() {
        fn primitive_stats<'a, T: Data<Cfg = ()>, F>(xs: &'a [T], f: F) -> (&'a [T], T::Stats)
        where
            F: for<'b> Fn(&'b T) -> T::Ref<'b>,
        {
            let mut col = T::Mut::new(&());
            for x in xs {
                col.push(f(x));
            }
            let col = T::Col::from(col);
            let stats = T::Stats::stats_from(&col, ValidityRef(None));
            (xs, stats)
        }
        fn testcase<T: Data + PartialOrd + Clone + Debug, P>(xs_stats: (&[T], PrimitiveStats<T>))
        where
            PrimitiveStats<T>: RustType<P> + DynStats,
            P: TrimStats,
        {
            let (xs, stats) = xs_stats;
            for x in xs {
                assert!(&stats.lower <= x);
                assert!(&stats.upper >= x);
            }

            let mut proto_stats = RustType::into_proto(&stats);
            let cost_before = proto_stats.encoded_len();
            proto_stats.trim();
            assert!(proto_stats.encoded_len() <= cost_before);
            let stats: PrimitiveStats<T> = RustType::from_proto(proto_stats).unwrap();
            for x in xs {
                assert!(&stats.lower <= x);
                assert!(&stats.upper >= x);
            }
        }

        proptest!(|(a in any::<bool>(), b in any::<bool>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<u8>(), b in any::<u8>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<u16>(), b in any::<u16>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<u32>(), b in any::<u32>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<u64>(), b in any::<u64>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<i8>(), b in any::<i8>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<i16>(), b in any::<i16>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<i32>(), b in any::<i32>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<i64>(), b in any::<i64>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<f32>(), b in any::<f32>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });
        proptest!(|(a in any::<f64>(), b in any::<f64>())| {
            testcase(primitive_stats(&[a, b], |x| *x))
        });

        // Construct strings that are "interesting" in that they have some
        // (possibly empty) shared prefix.
        proptest!(|(prefix in any::<String>(), a in any::<String>(), b in any::<String>())| {
            let vals = &[format!("{}{}", prefix, a), format!("{}{}", prefix, b)];
            testcase(primitive_stats(vals, |x| x))
        });

        // Construct strings that are "interesting" in that they have some
        // (possibly empty) shared prefix.
        proptest!(|(prefix in any::<Vec<u8>>(), a in any::<Vec<u8>>(), b in any::<Vec<u8>>())| {
            let mut sa = prefix.clone();
            sa.extend(&a);
            let mut sb = prefix;
            sb.extend(&b);
            let vals = &[sa, sb];
            let stats = PrimitiveStats::<Vec<u8>>::stats_from(&BinaryArray::<i32>::from_slice(vals), ValidityRef(None));
            testcase((vals, stats));
        });
    }

    #[mz_ore::test]
    fn struct_trim_to_budget() {
        #[track_caller]
        fn testcase(cols: &[(&str, usize)], required: Option<&str>) {
            let cols = cols
                .iter()
                .map(|(key, cost)| {
                    let stats: Box<dyn DynStats> = Box::new(PrimitiveStats {
                        lower: vec![],
                        upper: vec![0u8; *cost],
                    });
                    ((*key).to_owned(), stats)
                })
                .collect();
            let mut stats: ProtoStructStats = RustType::into_proto(&StructStats { len: 0, cols });
            let mut budget = stats.encoded_len().next_power_of_two();
            while budget > 0 {
                let cost_before = stats.encoded_len();
                let trimmed = trim_to_budget(&mut stats, budget, |col| Some(col) == required);
                let cost_after = stats.encoded_len();
                assert!(cost_before >= cost_after);
                assert_eq!(trimmed, cost_before - cost_after);
                if let Some(required) = required {
                    assert!(stats.cols.contains_key(required));
                } else {
                    assert!(cost_after <= budget);
                }
                budget = budget / 2;
            }
        }

        testcase(&[], None);
        testcase(&[("a", 100)], None);
        testcase(&[("a", 1), ("b", 2), ("c", 4)], None);
        testcase(&[("a", 1), ("b", 2), ("c", 4)], Some("b"));
    }

    #[mz_ore::test]
    fn jsonb_trim_to_budget() {
        #[track_caller]
        fn testcase(cols: &[(&str, usize)], required: Option<&str>) {
            let cols = cols
                .iter()
                .map(|(key, cost)| {
                    let stats = JsonStats::Numerics(PrimitiveStats {
                        lower: vec![],
                        upper: vec![0u8; *cost],
                    });
                    let len = stats.debug_json().to_string().len();
                    ((*key).to_owned(), JsonMapElementStats { len, stats })
                })
                .collect();

            // Serialize into proto and extract the necessary type.
            let stats: ProtoJsonStats = RustType::into_proto(&JsonStats::Maps(cols));
            let ProtoJsonStats {
                kind: Some(proto_json_stats::Kind::Maps(mut stats)),
            } = stats
            else {
                panic!("serialized produced wrong type!");
            };

            let mut budget = stats.encoded_len().next_power_of_two();
            while budget > 0 {
                let cost_before = stats.encoded_len();
                trim_to_budget_jsonb(&mut stats, &mut budget, &|col| Some(col) == required);
                let cost_after = stats.encoded_len();
                assert!(cost_before >= cost_after);

                // Assert force keep columns were kept.
                if let Some(required) = required {
                    assert!(stats
                        .elements
                        .iter()
                        .any(|element| element.name == required));
                } else {
                    assert!(cost_after <= budget);
                }

                budget = budget / 2;
            }
        }

        testcase(&[], None);
        testcase(&[("a", 100)], None);
        testcase(&[("a", 1), ("b", 2), ("c", 4)], None);
        testcase(&[("a", 1), ("b", 2), ("c", 4)], Some("b"));
    }

    #[mz_ore::test]
    fn jsonb_trim_to_budget_smoke() {
        let og_stats = JsonStats::Maps(
            [
                (
                    "a".to_string(),
                    JsonMapElementStats {
                        len: 1,
                        stats: JsonStats::Strings(PrimitiveStats {
                            lower: "foobar".to_string(),
                            upper: "foobaz".to_string(),
                        }),
                    },
                ),
                (
                    "context".to_string(),
                    JsonMapElementStats {
                        len: 100,
                        stats: JsonStats::Maps(
                            [
                                (
                                    "b".to_string(),
                                    JsonMapElementStats {
                                        len: 99,
                                        stats: JsonStats::Numerics(PrimitiveStats {
                                            lower: vec![],
                                            upper: vec![42u8; 99],
                                        }),
                                    },
                                ),
                                (
                                    "c".to_string(),
                                    JsonMapElementStats {
                                        len: 1,
                                        stats: JsonStats::Bools(PrimitiveStats {
                                            lower: false,
                                            upper: true,
                                        }),
                                    },
                                ),
                            ]
                            .into(),
                        ),
                    },
                ),
            ]
            .into(),
        );

        // Serialize into proto and extract the necessary type.
        let stats: ProtoJsonStats = RustType::into_proto(&og_stats);
        let ProtoJsonStats {
            kind: Some(proto_json_stats::Kind::Maps(mut stats)),
        } = stats
        else {
            panic!("serialized produced wrong type!");
        };

        let mut budget_shortfall = 50;
        // We should recurse into the "context" message and only drop the "b" column.
        trim_to_budget_jsonb(&mut stats, &mut budget_shortfall, &|_name| false);

        let mut elements = stats
            .elements
            .into_iter()
            .map(|element| (element.name.clone(), element))
            .collect::<BTreeMap<String, _>>();
        assert!(elements.remove("a").is_some());

        let context = elements.remove("context").expect("trimmed too much");
        let Some(ProtoJsonStats {
            kind: Some(proto_json_stats::Kind::Maps(context)),
        }) = context.stats
        else {
            panic!("serialized produced wrong type!")
        };

        // We should only have one element in "context" because we trimmed "b".
        assert_eq!(context.elements.len(), 1);
        assert_eq!(context.elements[0].name, "c");

        // Redo the triming, force keeping the largest column.

        // Serialize into proto and extract the necessary type.
        let stats: ProtoJsonStats = RustType::into_proto(&og_stats);
        let ProtoJsonStats {
            kind: Some(proto_json_stats::Kind::Maps(mut stats)),
        } = stats
        else {
            panic!("serialized produced wrong type!");
        };

        let mut budget_shortfall = 50;
        // We're force keeping "b" which is larger than our budgets_shortfall, so we should drop
        // everything else.
        trim_to_budget_jsonb(&mut stats, &mut budget_shortfall, &|name| name == "b");

        assert_eq!(stats.elements.len(), 1);
        assert_eq!(stats.elements[0].name, "context");

        let Some(ProtoJsonStats {
            kind: Some(proto_json_stats::Kind::Maps(context)),
        }) = &stats.elements[0].stats
        else {
            panic!("serialized produced wrong type!")
        };

        assert_eq!(context.elements.len(), 1);
        assert_eq!(context.elements[0].name, "b");
    }

    // Regression test for a bug found during code review of initial stats
    // trimming PR.
    #[mz_ore::test]
    fn stats_trim_regression_json() {
        // Make sure we recursively trim json string and map stats by asserting
        // that the goes down after trimming.
        #[track_caller]
        fn testcase(stats: JsonStats) {
            let mut stats = stats.into_proto();
            let before = stats.encoded_len();
            stats.trim();
            let after = stats.encoded_len();
            assert!(after < before, "{} vs {}: {:?}", after, before, stats);
        }

        let col = JsonStats::Strings(PrimitiveStats {
            lower: "foobar".into(),
            upper: "foobaz".into(),
        });
        testcase(col.clone());
        let mut cols = BTreeMap::new();
        cols.insert("col".into(), JsonMapElementStats { len: 1, stats: col });
        testcase(JsonStats::Maps(cols));
    }

    // Confirm that fields are being trimmed from largest to smallest.
    #[mz_ore::test]
    fn trim_order_regression() {
        fn dyn_stats(lower: &'static str, upper: &'static str) -> Box<dyn DynStats> {
            Box::new(PrimitiveStats {
                lower: lower.to_owned(),
                upper: upper.to_owned(),
            })
        }
        let stats = StructStats {
            len: 2,
            cols: BTreeMap::from([
                ("foo".to_owned(), dyn_stats("a", "b")),
                (
                    "bar".to_owned(),
                    dyn_stats("aaaaaaaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaab"),
                ),
            ]),
        };

        // The threshold here is arbitrary... we just care that there's some budget where
        // we'll discard the large field before the small one.
        let mut proto_stats = RustType::into_proto(&stats);
        trim_to_budget(&mut proto_stats, 30, |_| false);
        assert!(proto_stats.cols.contains_key("foo"));
        assert!(!proto_stats.cols.contains_key("bar"));
    }

    // Regression test for a bug found by a customer: trim_to_budget method only
    // operates on the top level struct columns. This (sorta) worked before
    // #19309, but now there are always two columns at the top level, "ok" and
    // "err", and the real columns are all nested under "ok".
    #[mz_ore::test]
    fn stats_trim_to_budget_regression_recursion() {
        fn str_stats(n: usize, l: &str, u: &str) -> Box<dyn DynStats> {
            let stats: Box<dyn DynStats> = Box::new(OptionStats {
                none: n,
                some: PrimitiveStats {
                    lower: l.to_owned(),
                    upper: u.to_owned(),
                },
            });
            stats
        }

        const BIG: usize = 100;

        // Model our ok/err structure for SourceData stats for a RelationDesc
        // with wide columns.
        let mut cols = BTreeMap::new();
        for col in 'a'..='z' {
            let col = col.to_string();
            let stats = str_stats(2, "", &col.repeat(BIG));
            cols.insert(col, stats);
        }
        cols.insert("foo_timestamp".to_string(), str_stats(2, "foo", "foo"));
        let source_data_stats = StructStats {
            len: 2,
            cols: BTreeMap::from([
                ("err".to_owned(), str_stats(2, "", "")),
                ("ok".to_owned(), Box::new(StructStats { len: 2, cols })),
            ]),
        };
        let mut proto_stats = RustType::into_proto(&source_data_stats);
        let trimmed = trim_to_budget(&mut proto_stats, BIG, |x| {
            x.ends_with("timestamp") || x == "err"
        });
        // Sanity-check that the test is trimming something.
        assert!(trimmed > 0);
        // We don't want to trim either "ok" or "err".
        assert!(proto_stats.cols.contains_key("ok"));
        assert!(proto_stats.cols.contains_key("err"));
        // Assert that we kept the timestamp column.
        let ok = proto_stats.cols.get("ok").unwrap();
        let proto_dyn_stats::Kind::Struct(ok_struct) = ok.kind.as_ref().unwrap() else {
            panic!("ok was of unexpected type {:?}", ok);
        };
        assert!(ok_struct.cols.contains_key("foo_timestamp"));
    }

    // Regression test for a bug where "lossless" trimming would truncate an
    // upper and lower bound that both parsed as our special iso8601 timestamps
    // into something that no longer did.
    #[mz_ore::test]
    fn stats_trim_iso8601_recursion() {
        use proto_primitive_stats::*;

        let orig = PrimitiveStats {
            lower: "2023-08-19T12:00:00.000Z".to_owned(),
            upper: "2023-08-20T12:00:00.000Z".to_owned(),
        };
        let mut stats = RustType::into_proto(&orig);
        stats.trim();
        // Before the fix, this resulted in "2023-08-" and "2023-08.".
        assert_eq!(stats.lower.unwrap(), Lower::LowerString(orig.lower));
        assert_eq!(stats.upper.unwrap(), Upper::UpperString(orig.upper));
    }
}