krafka 0.15.0

A pure Rust, async-native Apache Kafka client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
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
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
//! Key→value table for log-compacted Kafka topics.
//!
//! The primary type is [`CompactedTable`] — a standalone, Kafka-agnostic
//! data structure that maintains an in-memory key→value snapshot from a
//! stream of [`ConsumerRecord`]s. It handles tombstones (records with null
//! values) automatically and tracks changes via [`TableChange`].
//!
//! Because `CompactedTable` is decoupled from the consumer, it composes
//! with any [`Consumer`] — group-coordinated, standalone, or manually
//! assigned:
//!
//! ```rust,ignore
//! use krafka::consumer::{Consumer, CompactedTable};
//! use std::time::Duration;
//!
//! let consumer = Consumer::builder()
//!     .bootstrap_servers("localhost:9092")
//!     .group_id("my-group")
//!     .build()
//!     .await?;
//! consumer.subscribe(&["user-profiles"]).await?;
//!
//! let mut table = CompactedTable::new();
//! loop {
//!     let records = consumer.poll(Duration::from_secs(1)).await?;
//!     let changes = table.apply(&records);
//!     for change in &changes {
//!         println!("{:?}", change);
//!     }
//! }
//! ```
//!
//! For the common case of scanning an entire compacted topic from the
//! beginning, [`CompactedTopicConsumer`] bundles a [`Consumer`] and
//! [`CompactedTable`] together with built-in caught-up detection:
//!
//! ```rust,ignore
//! use krafka::consumer::CompactedTopicConsumer;
//! use std::time::Duration;
//!
//! let mut ctc = CompactedTopicConsumer::builder()
//!     .bootstrap_servers("localhost:9092")
//!     .topic("user-profiles")
//!     .build()
//!     .await?;
//!
//! ctc.scan(Duration::from_secs(1)).await?;
//!
//! if let Some(value) = ctc.table().get(b"user-123") {
//!     println!("User: {:?}", value);
//! }
//! ```

use ahash::AHashMap as HashMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use bytes::Bytes;
use tokio::sync::Mutex;
use tracing::{debug, info};

use super::record::ConsumerRecord;
use super::{AutoOffsetReset, Consumer, ConsumerRebalanceListener, TopicPartition};
use crate::auth::AuthConfig;
use crate::error::{KrafkaError, Result};
use crate::{Offset, PartitionId, Timestamp};

/// A single entry in a [`CompactedTable`], carrying the value together with
/// the provenance metadata (offset and broker timestamp) of the most recent
/// record that wrote it.
///
/// Accessing the timestamp lets callers implement freshness policies such as
/// "reject state older than 24 h" without coupling to a separate metadata
/// store.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompactedEntry {
    /// The current value for the key.
    pub value: Bytes,
    /// Broker-assigned append timestamp (milliseconds since epoch) of the
    /// record that last wrote this key.  Matches the `timestamp` field of
    /// the originating [`ConsumerRecord`].
    pub timestamp_ms: Timestamp,
    /// Log offset of the record that last wrote this key.
    pub offset: Offset,
    /// Partition the record came from.
    pub partition: PartitionId,
}

impl CompactedEntry {
    /// Returns `true` if the entry's timestamp is older than `max_age`.
    #[inline]
    pub fn is_stale(&self, max_age: std::time::Duration) -> bool {
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(i64::MAX);
        now_ms.saturating_sub(self.timestamp_ms) > max_age.as_millis() as i64
    }
}

/// A change to a [`CompactedTable`].
///
/// Returned by [`CompactedTable::apply()`] to describe how the table
/// was modified after processing a record.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TableChange {
    /// The record key.
    pub key: Bytes,
    /// The previous value (`None` if the key was not in the table).
    pub old_value: Option<Bytes>,
    /// The new value (`None` for a tombstone / deletion).
    pub new_value: Option<Bytes>,
    /// Partition the record came from.
    pub partition: PartitionId,
    /// Offset of the record within the partition.
    pub offset: Offset,
    /// Record timestamp.
    pub timestamp: Timestamp,
}

impl TableChange {
    /// Returns `true` if this change is a deletion (tombstone).
    #[inline]
    pub fn is_delete(&self) -> bool {
        self.new_value.is_none()
    }

    /// Returns `true` if this is an insert (key was not previously in the table).
    #[inline]
    pub fn is_insert(&self) -> bool {
        self.old_value.is_none() && self.new_value.is_some()
    }

    /// Returns `true` if this is an update (key existed with a previous value).
    #[inline]
    pub fn is_update(&self) -> bool {
        self.old_value.is_some() && self.new_value.is_some()
    }
}

/// Metrics snapshot for a [`CompactedTable`] or [`CompactedTopicConsumer`].
///
/// Returned by [`CompactedTable::metrics_snapshot()`] and
/// [`CompactedTopicConsumer::metrics_snapshot()`]. All counts are
/// monotonically increasing since the table was created.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompactedTableSnapshot {
    /// Number of distinct keys currently held in the table.
    pub entry_count: u64,
    /// Total records processed (including tombstones and keyless records).
    pub records_processed: u64,
    /// Total tombstone records processed (keys removed from the table).
    pub tombstones_processed: u64,
    /// `true` once all assigned partitions have been read up to the
    /// high-water mark at scan time.
    ///
    /// Always `false` for a bare [`CompactedTable`] (which has no consumer
    /// attached); use [`CompactedTopicConsumer::metrics_snapshot()`] to
    /// obtain an accurate `caught_up` value.
    pub caught_up: bool,
}

/// Rewinds a partition to the start of its log.
///
/// Exists so the rebalance listener can be exercised without a live broker
/// connection; [`Consumer`] is the only production implementation.
trait PartitionRewinder: Send + Sync {
    fn rewind_to_beginning<'a>(
        &'a self,
        topic: &'a str,
        partition: PartitionId,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>>;
}

impl PartitionRewinder for Consumer {
    fn rewind_to_beginning<'a>(
        &'a self,
        topic: &'a str,
        partition: PartitionId,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> {
        Box::pin(self.seek_to_beginning(topic, partition))
    }
}

/// A [`ConsumerRebalanceListener`] that keeps a shared [`CompactedTable`] in
/// sync with the consumer's assignment across rebalances.
///
/// This is the recommended way to integrate a [`CompactedTable`] with a
/// group-coordinated [`Consumer`]: wrap the table in an
/// `Arc<Mutex<CompactedTable>>`, share a clone with this listener, and
/// register the listener on the consumer before subscribing.
///
/// # Behaviour
///
/// - **Revoked / lost partitions** — only the entries that came from those
///   partitions are removed. Entries from partitions this consumer kept are
///   preserved, because their committed position has already moved past the
///   records that produced them and they would otherwise never be re-read.
/// - **Assigned partitions** — the entries of each newly assigned partition
///   are dropped and the partition is rewound to the beginning of the log.
///   A compacted-topic table is only correct if every owned partition is
///   replayed from its start; resuming from a committed offset would surface
///   just the keys written after the rebalance and report `None` for every
///   other live key.
///
/// Rewinding requires a handle to the consumer, which does not exist yet when
/// the listener is registered on the builder. Call
/// [`attach_consumer()`](Self::attach_consumer) once the consumer is built —
/// until then, assignments are pruned but not rewound, and a warning is
/// logged.
///
/// Because [`CompactedTable`] entries record a partition but not a topic,
/// pruning matches on partition id across all topics. Use one table per topic
/// with multi-topic consumers.
///
/// # Example
///
/// ```rust,ignore
/// use std::sync::Arc;
/// use tokio::sync::Mutex;
/// use krafka::consumer::{Consumer, CompactedTable, CompactedTableClearListener};
///
/// let table = Arc::new(Mutex::new(CompactedTable::new()));
/// let listener = CompactedTableClearListener::new(Arc::clone(&table));
///
/// let consumer = Arc::new(
///     Consumer::builder()
///         .bootstrap_servers("localhost:9092")
///         .group_id("my-group")
///         .rebalance_listener(listener.clone())
///         .build()
///         .await?,
/// );
/// // Lets the listener seek newly assigned partitions to the beginning.
/// listener.attach_consumer(Arc::clone(&consumer));
/// consumer.subscribe(&["config-topic"]).await?;
///
/// loop {
///     let records = consumer.poll(Duration::from_secs(1)).await?;
///     let mut t = table.lock().await;
///     t.ingest(&records);
/// }
/// ```
#[derive(Clone)]
pub struct CompactedTableClearListener {
    table: Arc<Mutex<CompactedTable>>,
    /// Set once via `attach_consumer()`; shared by every clone of the listener
    /// so attaching after registration is visible to the registered copy.
    rewinder: Arc<std::sync::OnceLock<Arc<dyn PartitionRewinder>>>,
}

impl fmt::Debug for CompactedTableClearListener {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompactedTableClearListener")
            .field("consumer_attached", &self.rewinder.get().is_some())
            .finish()
    }
}

impl CompactedTableClearListener {
    /// Create a new listener that prunes `table` as partitions change owner.
    ///
    /// Attach the consumer with
    /// [`attach_consumer()`](Self::attach_consumer) so newly assigned
    /// partitions can be replayed from the beginning of the log.
    pub fn new(table: Arc<Mutex<CompactedTable>>) -> Self {
        Self {
            table,
            rewinder: Arc::new(std::sync::OnceLock::new()),
        }
    }

    /// Give the listener the consumer it belongs to, enabling it to seek
    /// newly assigned partitions to the beginning of the log.
    ///
    /// Call this once, right after the consumer is built and before
    /// subscribing. The handle is shared by every clone of this listener, so
    /// it takes effect for the copy already registered on the consumer.
    /// Subsequent calls are ignored.
    pub fn attach_consumer(&self, consumer: Arc<Consumer>) {
        if self.rewinder.set(consumer).is_err() {
            tracing::warn!(
                "CompactedTableClearListener: consumer already attached; ignoring repeat call"
            );
        }
    }

    /// Create a listener with an arbitrary rewind target (test seam).
    #[cfg(test)]
    fn with_rewinder(
        table: Arc<Mutex<CompactedTable>>,
        rewinder: Arc<dyn PartitionRewinder>,
    ) -> Self {
        let cell = std::sync::OnceLock::new();
        let _ = cell.set(rewinder);
        Self {
            table,
            rewinder: Arc::new(cell),
        }
    }

    /// Drop the entries produced by `partitions` from the shared table.
    async fn prune(&self, partitions: &[TopicPartition], reason: &str) {
        if partitions.is_empty() {
            return;
        }
        let ids: Vec<PartitionId> = partitions.iter().map(|tp| tp.partition).collect();
        let removed = self.table.lock().await.remove_partitions(&ids);
        debug!(
            partitions = ?ids,
            removed,
            reason,
            "CompactedTableClearListener pruned table entries"
        );
    }
}

impl ConsumerRebalanceListener for CompactedTableClearListener {
    /// Drops any stale state for the newly assigned partitions and rewinds
    /// each of them to the beginning of the log, so the table is rebuilt from
    /// the partition's full history rather than from the committed offset.
    async fn on_partitions_assigned(&self, partitions: &[TopicPartition]) {
        if partitions.is_empty() {
            return;
        }

        // A gained partition is replayed in full, so any leftover entries for
        // it would only be duplicated work at best and stale at worst.
        self.prune(partitions, "assigned").await;

        let Some(rewinder) = self.rewinder.get() else {
            tracing::warn!(
                partitions = partitions.len(),
                "CompactedTableClearListener: no consumer attached, cannot rewind newly \
                 assigned partitions; the table will only observe keys written after this \
                 rebalance. Call attach_consumer() after building the consumer."
            );
            return;
        };

        for tp in partitions {
            match rewinder.rewind_to_beginning(&tp.topic, tp.partition).await {
                Ok(()) => debug!(
                    topic = %tp.topic,
                    partition = tp.partition,
                    "CompactedTableClearListener rewound newly assigned partition"
                ),
                Err(e) => tracing::warn!(
                    topic = %tp.topic,
                    partition = tp.partition,
                    error = %e,
                    "CompactedTableClearListener failed to rewind newly assigned partition; \
                     the table may be missing keys for it"
                ),
            }
        }
    }

    /// Removes only the entries belonging to the revoked partitions, leaving
    /// the state of retained partitions intact.
    async fn on_partitions_revoked(&self, partitions: &[TopicPartition]) {
        self.prune(partitions, "revoked").await;
    }

    /// Removes only the entries belonging to the lost partitions, leaving the
    /// state of retained partitions intact.
    async fn on_partitions_lost(&self, partitions: &[TopicPartition]) {
        self.prune(partitions, "lost").await;
    }
}

/// In-memory key→value table built from log-compacted Kafka records.
///
/// `CompactedTable` is a standalone data structure with no dependency on
/// [`Consumer`] or Kafka networking. Feed it [`ConsumerRecord`]s via
/// [`apply()`](Self::apply) and it maintains a snapshot that reflects
/// the latest value for each key, handling tombstones automatically.
///
/// # Composability
///
/// Because it is decoupled from the consumer, `CompactedTable` works with
/// **any** consumer setup — group, standalone, or manual assignment:
///
/// ```rust,ignore
/// let consumer = Consumer::builder()
///     .bootstrap_servers("localhost:9092")
///     .group_id("my-group")
///     .build()
///     .await?;
/// consumer.subscribe(&["config-topic"]).await?;
///
/// let mut table = CompactedTable::new();
/// loop {
///     let records = consumer.poll(Duration::from_secs(1)).await?;
///     let changes = table.apply(&records);
///     for change in &changes {
///         println!("{:?}", change);
///     }
/// }
/// ```
///
/// # Record handling
///
/// - Records **without a key** are skipped (compacted topics require keys).
/// - **Tombstones** (key present, value absent) remove the key from the table.
/// - All other records insert or update the table entry for that key.
///
/// # Cross-partition keys
///
/// The table is keyed purely by record key, not by (partition, key). If the
/// same key appears in multiple partitions (e.g., due to a custom partitioner
/// or producer misconfiguration), entries will be conflated with last-write-wins
/// ordering across partitions. This matches the common single-writer pattern
/// for compacted topics; if partition-scoped dedup is required, encode the
/// partition into the key before feeding records to the table.
///
/// # Equality
///
/// Two tables are equal if they contain the same key→value entries,
/// regardless of processing history (`records_processed`,
/// `tombstones_processed`). This follows the `std` convention where
/// collection equality reflects contents, not metadata.
#[derive(Default, Clone)]
pub struct CompactedTable {
    /// The key→entry map (value + provenance metadata).
    entries: HashMap<Bytes, CompactedEntry>,
    /// Total records processed (including tombstones and keyless records).
    records_processed: u64,
    /// Total tombstones processed.
    tombstones_processed: u64,
}

impl CompactedTable {
    /// Create an empty table.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a table pre-allocated for the expected number of keys.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            entries: HashMap::with_capacity(capacity),
            records_processed: 0,
            tombstones_processed: 0,
        }
    }

    /// Apply a batch of consumer records to the table.
    ///
    /// Returns a list of [`TableChange`]s — one per keyed record applied.
    /// Records without a key are counted but produce no change.
    /// Tombstones always produce a change for their key, even if the key was
    /// not present in the table; in that case both `old_value` and `new_value`
    /// are `None`.
    #[must_use = "use ingest() if changes are not needed"]
    pub fn apply(&mut self, records: &[ConsumerRecord]) -> Vec<TableChange> {
        // Don't pre-allocate records.len(): keyless records are skipped and
        // produce no change, so that would over-allocate for mixed batches.
        let mut changes = Vec::new();

        for record in records {
            self.records_processed += 1;

            // Compacted topics require keys; skip keyless records.
            let Some(ref key) = record.key else {
                continue;
            };

            let change = self.apply_keyed_record(key, record);
            changes.push(change);
        }

        changes
    }

    /// Get the current entry for a key, including value, timestamp, and offset.
    ///
    /// Returns `None` if the key is not in the table (never seen or deleted
    /// by a tombstone).
    pub fn get(&self, key: &[u8]) -> Option<&CompactedEntry> {
        self.entries.get(key)
    }

    /// Get just the value bytes for a key, without provenance metadata.
    ///
    /// Equivalent to `get(key).map(|e| &e.value)`. Use [`get`](Self::get)
    /// when you also need the timestamp or offset.
    pub fn get_value(&self, key: &[u8]) -> Option<&Bytes> {
        self.entries.get(key).map(|e| &e.value)
    }

    /// Check if the table contains the given key.
    pub fn contains_key(&self, key: &[u8]) -> bool {
        self.entries.contains_key(key)
    }

    /// Get the number of keys currently in the table.
    #[inline]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if the table has no keys.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Iterate over all key→entry pairs.
    pub fn iter(&self) -> impl Iterator<Item = (&Bytes, &CompactedEntry)> {
        self.entries.iter()
    }

    /// Iterate over all keys in the table.
    pub fn keys(&self) -> impl Iterator<Item = &Bytes> {
        self.entries.keys()
    }

    /// Iterate over all entries in the table.
    pub fn values(&self) -> impl Iterator<Item = &CompactedEntry> {
        self.entries.values()
    }

    /// Get a snapshot (clone) of the key→entry map.
    ///
    /// Returns all entries including provenance metadata. Use
    /// [`Clone::clone()`] if you need a full copy including counters.
    #[must_use]
    pub fn snapshot(&self) -> HashMap<Bytes, CompactedEntry> {
        self.entries.clone()
    }

    /// Total records processed (including tombstones and keyless records).
    pub fn records_processed(&self) -> u64 {
        self.records_processed
    }

    /// Total tombstones processed.
    pub fn tombstones_processed(&self) -> u64 {
        self.tombstones_processed
    }

    /// Return a metrics snapshot for this table.
    ///
    /// The `caught_up` field is always `false` for a bare `CompactedTable`.
    /// Use [`CompactedTopicConsumer::metrics_snapshot()`] for a snapshot that
    /// includes the caught-up status.
    #[must_use]
    pub fn metrics_snapshot(&self) -> CompactedTableSnapshot {
        CompactedTableSnapshot {
            entry_count: self.entries.len() as u64,
            records_processed: self.records_processed,
            tombstones_processed: self.tombstones_processed,
            caught_up: false,
        }
    }

    /// Apply records to the table without tracking changes.
    ///
    /// This is semantically identical to [`apply()`](Self::apply) but skips
    /// building the [`TableChange`] list, avoiding allocations and `Bytes`
    /// ref-count churn. Prefer this during bulk loads (e.g., initial scan)
    /// where only the final table state matters.
    pub fn ingest(&mut self, records: &[ConsumerRecord]) {
        for record in records {
            self.records_processed += 1;

            let Some(ref key) = record.key else {
                continue;
            };

            self.ingest_keyed_record(key, record);
        }
    }

    /// Shared mutation logic for a single keyed record, returning a
    /// [`TableChange`] describing the modification.
    fn apply_keyed_record(&mut self, key: &Bytes, record: &ConsumerRecord) -> TableChange {
        if record.is_tombstone() {
            self.tombstones_processed += 1;
            let old_entry = self.entries.remove(key.as_ref());
            TableChange {
                key: key.clone(),
                old_value: old_entry.map(|e| e.value),
                new_value: None,
                partition: record.partition,
                offset: record.offset,
                timestamp: record.timestamp,
            }
        } else {
            // value must be Some here because is_tombstone() returned false and key is Some
            let Some(value) = record.value.clone() else {
                unreachable!("non-tombstone compacted record must have a value");
            };
            let key_owned = key.clone();
            let new_entry = CompactedEntry {
                value: value.clone(),
                timestamp_ms: record.timestamp,
                offset: record.offset,
                partition: record.partition,
            };
            // Warn if the same key arrives from a different partition — this is
            // almost always a producer misconfiguration or unexpected custom partitioner
            // and will silently produce last-write-wins semantics across partitions.
            if let Some(existing) = self.entries.get(key_owned.as_ref())
                && existing.partition != record.partition
            {
                tracing::warn!(
                    existing_partition = existing.partition,
                    new_partition = record.partition,
                    "CompactedTable: key appears in multiple partitions; \
                     entries will be conflated with last-write-wins semantics. \
                     If partition-scoped dedup is required, encode the partition \
                     into the key before ingesting records."
                );
            }
            let old_entry = self.entries.insert(key_owned.clone(), new_entry);
            TableChange {
                key: key_owned,
                old_value: old_entry.map(|e| e.value),
                new_value: Some(value),
                partition: record.partition,
                offset: record.offset,
                timestamp: record.timestamp,
            }
        }
    }

    /// Shared mutation logic for a single keyed record without producing a
    /// [`TableChange`]. Avoids extra clones needed for the change struct.
    fn ingest_keyed_record(&mut self, key: &Bytes, record: &ConsumerRecord) {
        if record.is_tombstone() {
            self.tombstones_processed += 1;
            self.entries.remove(key.as_ref());
        } else {
            // value must be Some here because is_tombstone() returned false and key is Some
            let Some(value) = record.value.clone() else {
                unreachable!("non-tombstone compacted record must have a value");
            };
            // Warn if the same key arrives from a different partition — this is
            // almost always a producer misconfiguration or unexpected custom partitioner
            // and will silently produce last-write-wins semantics across partitions.
            if let Some(existing) = self.entries.get(key.as_ref())
                && existing.partition != record.partition
            {
                tracing::warn!(
                    existing_partition = existing.partition,
                    new_partition = record.partition,
                    "CompactedTable: key appears in multiple partitions; \
                     entries will be conflated with last-write-wins semantics. \
                     If partition-scoped dedup is required, encode the partition \
                     into the key before ingesting records."
                );
            }
            self.entries.insert(
                key.clone(),
                CompactedEntry {
                    value,
                    timestamp_ms: record.timestamp,
                    offset: record.offset,
                    partition: record.partition,
                },
            );
        }
    }

    /// Clear the table, removing all entries and resetting counters.
    ///
    /// Useful when the table needs to be rebuilt from scratch. When only some
    /// partitions change ownership during a rebalance, prefer
    /// [`remove_partitions()`](Self::remove_partitions), which keeps the state
    /// of the partitions that are still owned.
    pub fn clear(&mut self) {
        self.entries.clear();
        self.records_processed = 0;
        self.tombstones_processed = 0;
    }

    /// Remove every entry that was last written by one of `partitions`,
    /// leaving entries from all other partitions untouched.
    ///
    /// Returns the number of entries removed.
    ///
    /// This is the correct reaction to a partial rebalance: dropping only the
    /// partitions this consumer no longer owns preserves the state of the
    /// partitions it kept. Clearing the whole table instead would discard
    /// retained state that the consumer will never re-read, because its
    /// committed position on those partitions has already advanced past the
    /// records that built it.
    ///
    /// Entries are matched on partition id alone — the table does not record
    /// the topic a key came from — so with a multi-topic consumer this also
    /// removes same-numbered partitions of other topics. Use one table per
    /// topic if that matters.
    ///
    /// The `records_processed` and `tombstones_processed` counters are
    /// deliberately left unchanged: they are lifetime totals of ingest work
    /// performed, not a description of current table contents.
    pub fn remove_partitions(&mut self, partitions: &[PartitionId]) -> usize {
        if partitions.is_empty() {
            return 0;
        }
        let before = self.entries.len();
        self.entries
            .retain(|_, entry| !partitions.contains(&entry.partition));
        before - self.entries.len()
    }
}

impl<'a> IntoIterator for &'a CompactedTable {
    type Item = (&'a Bytes, &'a CompactedEntry);
    type IntoIter = std::collections::hash_map::Iter<'a, Bytes, CompactedEntry>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.iter()
    }
}

impl IntoIterator for CompactedTable {
    type Item = (Bytes, CompactedEntry);
    type IntoIter = std::collections::hash_map::IntoIter<Bytes, CompactedEntry>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.into_iter()
    }
}

impl fmt::Debug for CompactedTable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompactedTable")
            .field("len", &self.entries.len())
            .field("records_processed", &self.records_processed)
            .field("tombstones_processed", &self.tombstones_processed)
            .finish()
    }
}

impl PartialEq for CompactedTable {
    /// Compares entries only — processing counters are ignored.
    /// Two tables with the same key→entry content are equal regardless
    /// of how many records were processed to reach that state.
    fn eq(&self, other: &Self) -> bool {
        self.entries == other.entries
    }
}

impl Eq for CompactedTable {}

// ---------------------------------------------------------------------------
// CompactedTopicConsumer — convenience wrapper
// ---------------------------------------------------------------------------

/// Default upper bound on how long [`CompactedTopicConsumer::scan()`] waits
/// for every partition to reach its target offset before giving up.
const DEFAULT_SCAN_TIMEOUT: Duration = Duration::from_secs(300);

/// The operations `scan()` needs from a consumer.
///
/// Abstracting them keeps the scan loop — including its deadline handling —
/// testable without a live broker. [`Consumer`] is the only production
/// implementation.
trait ScanSource: Sync {
    fn poll_records(
        &self,
        timeout: Duration,
    ) -> impl std::future::Future<Output = Result<Vec<ConsumerRecord>>> + Send;

    fn assigned_partitions(
        &self,
        topic: &str,
    ) -> impl std::future::Future<Output = Vec<PartitionId>> + Send;

    fn partition_position(
        &self,
        topic: &str,
        partition: PartitionId,
    ) -> impl std::future::Future<Output = Option<Offset>> + Send;

    fn end_offsets(
        &self,
        topic: &str,
    ) -> impl std::future::Future<Output = Result<HashMap<PartitionId, Result<Offset>>>> + Send;
}

impl ScanSource for Consumer {
    async fn poll_records(&self, timeout: Duration) -> Result<Vec<ConsumerRecord>> {
        self.poll(timeout).await
    }

    async fn assigned_partitions(&self, topic: &str) -> Vec<PartitionId> {
        self.assignment()
            .await
            .get(topic)
            .cloned()
            .unwrap_or_default()
    }

    async fn partition_position(&self, topic: &str, partition: PartitionId) -> Option<Offset> {
        self.position(topic, partition).await
    }

    async fn end_offsets(&self, topic: &str) -> Result<HashMap<PartitionId, Result<Offset>>> {
        self.offsets_for_times_for_topic(topic, -1).await
    }
}

/// A partition that has not yet reached its scan target offset.
#[derive(Debug, Clone, PartialEq, Eq)]
struct LaggingPartition {
    partition: PartitionId,
    /// Consumer position, or `None` when no position is known yet (e.g. the
    /// partition has no leader and was never fetched).
    position: Option<Offset>,
    target: Offset,
}

impl fmt::Display for LaggingPartition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.position {
            Some(pos) => write!(
                f,
                "partition {} (position {}, target {})",
                self.partition, pos, self.target
            ),
            None => write!(
                f,
                "partition {} (position unknown, target {})",
                self.partition, self.target
            ),
        }
    }
}

/// Build the error returned when a scan runs out of time, naming every
/// partition that is still behind together with its position and target so
/// the stall can be attributed to a specific partition.
fn scan_timeout_error(topic: &str, timeout: Duration, lagging: &[LaggingPartition]) -> KrafkaError {
    let detail = lagging
        .iter()
        .map(|l| l.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    KrafkaError::timeout(format!(
        "scan of compacted topic '{topic}' did not catch up within {timeout:?}; \
         partitions still behind their target offset: [{detail}]"
    ))
}

/// Partitions that have not yet reached their target offset.
///
/// Only currently assigned partitions are considered. A partition whose
/// position is unknown counts as lagging, as does one whose target is missing
/// from the current assignment — the latter means the assignment changed
/// mid-scan and the snapshot can no longer be satisfied.
async fn lagging_partitions<S: ScanSource>(
    source: &S,
    topic: &str,
    targets: &HashMap<PartitionId, Offset>,
) -> Vec<LaggingPartition> {
    let assigned = source.assigned_partitions(topic).await;

    if assigned.is_empty() {
        // Nothing assigned means nothing can advance; report every target.
        let mut all: Vec<LaggingPartition> = targets
            .iter()
            .map(|(&partition, &target)| LaggingPartition {
                partition,
                position: None,
                target,
            })
            .collect();
        all.sort_by_key(|l| l.partition);
        return all;
    }

    let mut lagging = Vec::new();
    for partition in assigned {
        let Some(&target) = targets.get(&partition) else {
            // Not part of the snapshot (e.g. added after the scan started).
            continue;
        };
        // A target of 0 or -1 means the partition is empty; nothing to consume.
        if target <= 0 {
            continue;
        }

        let position = source.partition_position(topic, partition).await;
        if position.is_none_or(|pos| pos < target) {
            lagging.push(LaggingPartition {
                partition,
                position,
                target,
            });
        }
    }
    lagging.sort_by_key(|l| l.partition);
    lagging
}

/// Drive a bounded scan of `topic` into `table`.
///
/// Polls until every assigned partition reaches the high-watermark snapshot
/// taken at the start, or until `timeout` elapses — in which case the returned
/// error names the partitions that never got there.
async fn run_scan<S: ScanSource>(
    source: &S,
    topic: &str,
    table: &mut CompactedTable,
    poll_timeout: Duration,
    timeout: Duration,
) -> Result<()> {
    // Fail fast if no partitions are assigned — avoids a scan that can only
    // ever time out (especially when using from_consumer() without assign()).
    if source.assigned_partitions(topic).await.is_empty() {
        return Err(KrafkaError::invalid_state(format!(
            "no partitions assigned for topic '{topic}'; \
             assign partitions before calling scan()"
        )));
    }

    // Snapshot the latest offsets (high-water marks) **before** starting
    // the poll loop.  Comparing against a fixed snapshot means the scan
    // terminates even when new records arrive during the scan, avoiding
    // the HWM-chasing race that makes scans on active topics non-terminating.
    let hwm_results = source.end_offsets(topic).await?;

    // Fail fast on any per-partition error: a missing partition in the
    // target map causes the caught-up check to silently skip it, which
    // would prematurely declare the scan complete without having consumed
    // that partition's data.
    let mut scan_target_hwms: HashMap<PartitionId, Offset> =
        HashMap::with_capacity(hwm_results.len());
    for (partition, result) in hwm_results {
        let offset = result.map_err(|e| {
            KrafkaError::invalid_state(format!(
                "failed to fetch high-watermark for '{topic}' partition {partition}: {e}"
            ))
        })?;
        scan_target_hwms.insert(partition, offset);
    }

    if scan_target_hwms.values().all(|&hwm| hwm <= 0) {
        // All partitions are empty (HWM = 0) — nothing to scan.
        info!("Compacted topic '{topic}' has no data yet (all partition HWMs = 0); scan complete");
        return Ok(());
    }

    // Keep only non-empty partitions in the target map; empty partitions
    // are satisfied immediately and don't need to be polled.
    scan_target_hwms.retain(|_, &mut hwm| hwm > 0);

    info!(
        topic = %topic,
        partitions = scan_target_hwms.len(),
        timeout = ?timeout,
        "Starting compacted topic scan (HWM snapshot taken)"
    );

    let deadline = std::time::Instant::now() + timeout;

    loop {
        let mut records = source.poll_records(poll_timeout).await?;
        let before_len = records.len();
        records.retain(|r| r.topic == topic);
        let filtered = before_len - records.len();
        if filtered > 0 {
            debug!("Filtered out {filtered} record(s) from other topics during scan for '{topic}'");
        }
        table.ingest(&records);

        let lagging = lagging_partitions(source, topic, &scan_target_hwms).await;
        if lagging.is_empty() {
            info!(
                "Compacted topic scan complete for '{}': {} keys, {} records processed, \
                 {} tombstones",
                topic,
                table.len(),
                table.records_processed(),
                table.tombstones_processed(),
            );
            return Ok(());
        }

        // A partition can stall indefinitely (no leader, offsets that never
        // resolve), so the loop is bounded by wall-clock time rather than
        // trusting every partition to eventually converge.
        if std::time::Instant::now() >= deadline {
            return Err(scan_timeout_error(topic, timeout, &lagging));
        }
    }
}

/// Convenience wrapper that pairs a [`Consumer`] with a [`CompactedTable`]
/// for the common pattern of scanning an entire compacted topic.
///
/// When constructed via [`builder()`](Self::builder), it creates a
/// standalone (no group) consumer, assigns all partitions from the earliest
/// offset, and provides [`scan()`](Self::scan) to block until the table is
/// fully populated.
///
/// Other constructors, such as [`from_consumer()`](Self::from_consumer),
/// use the caller-provided consumer configuration and assignment as-is.
///
/// For fully custom consumer setups, you can also use [`CompactedTable`]
/// directly with your own [`Consumer`].
///
/// # Example
///
/// ```rust,ignore
/// use krafka::consumer::CompactedTopicConsumer;
/// use std::time::Duration;
///
/// let mut ctc = CompactedTopicConsumer::builder()
///     .bootstrap_servers("localhost:9092")
///     .topic("user-profiles")
///     .build()
///     .await?;
///
/// // Build the initial snapshot
/// ctc.scan(Duration::from_secs(1)).await?;
///
/// // Read a key
/// if let Some(value) = ctc.table().get(b"user-123") {
///     println!("User profile: {:?}", value);
/// }
///
/// // Continue tailing for live updates
/// loop {
///     let changes = ctc.poll(Duration::from_secs(1)).await?;
///     for change in &changes {
///         println!("{:?}", change);
///     }
/// }
/// ```
pub struct CompactedTopicConsumer {
    /// The underlying Kafka consumer.
    consumer: Consumer,
    /// Topic name.
    topic: String,
    /// In-memory key→value table.
    table: CompactedTable,
    /// Whether the initial scan has completed (caught up to high watermarks).
    caught_up: bool,
}

impl fmt::Debug for CompactedTopicConsumer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompactedTopicConsumer")
            .field("topic", &self.topic)
            .field("caught_up", &self.caught_up)
            .field("table", &self.table)
            .finish()
    }
}

impl CompactedTopicConsumer {
    /// Create a new builder.
    pub fn builder() -> CompactedTopicConsumerBuilder {
        CompactedTopicConsumerBuilder::default()
    }

    /// Create a `CompactedTopicConsumer` from an already-configured [`Consumer`].
    ///
    /// The consumer should already have partitions assigned for the given
    /// topic (e.g., via [`Consumer::assign()`]). This constructor performs no
    /// partition discovery and does not modify the consumer's subscription
    /// or assignment.
    ///
    /// If the consumer is subscribed/assigned to additional topics, records
    /// from those topics are filtered out (logged at debug level) — only
    /// records matching the given `topic` are applied to the table.
    ///
    /// This constructor is the best fit for consumers with stable, explicit
    /// assignments. If you wrap a group-coordinated consumer whose assignment
    /// can change over time, note that the table owned by this wrapper is not
    /// pruned when partitions are revoked: keys loaded from partitions that
    /// are no longer assigned remain in it. Drop them from a rebalance
    /// callback with
    /// [`table_mut().remove_partitions()`](CompactedTable::remove_partitions),
    /// or share an `Arc<Mutex<CompactedTable>>` with a
    /// [`CompactedTableClearListener`], which does that bookkeeping (and the
    /// matching rewind of newly assigned partitions) for you.
    ///
    /// Use this when you need full control over the consumer configuration
    /// (TLS, auth, timeouts, etc.) beyond what the builder exposes.
    pub fn from_consumer(consumer: Consumer, topic: impl Into<String>) -> Self {
        Self {
            consumer,
            topic: topic.into(),
            table: CompactedTable::new(),
            caught_up: false,
        }
    }

    /// Scan the topic from the consumer's current position until all
    /// partitions are caught up.
    ///
    /// This method does not seek to the beginning of the topic and does not
    /// clear or reset the current table state before polling. It repeatedly
    /// polls using the given `poll_timeout` until the consumer's position on
    /// every assigned partition reaches or exceeds the latest known high
    /// watermark.
    ///
    /// When this scanner is created via the builder, the internal consumer is
    /// initialized with [`AutoOffsetReset::Earliest`], so an initial `scan()`
    /// will typically read from the beginning of the topic. When using
    /// [`from_consumer()`](Self::from_consumer), however, scanning starts from
    /// whatever position that consumer already has.
    ///
    /// `scan()` takes a **point-in-time snapshot** of the latest offsets
    /// (high-water marks) for all assigned partitions at the moment it is
    /// called, then reads until the consumer's position on every partition
    /// reaches or exceeds those snapshot offsets. Records written to the
    /// topic *after* the snapshot is taken are not counted towards the
    /// caught-up condition — this bounds the scan to a deterministic target
    /// rather than chasing a continuously advancing watermark.
    ///
    /// The scan is bounded: if the partitions have not all reached their
    /// target within five minutes, it returns a timeout error instead of
    /// polling forever. Use [`scan_with_timeout()`](Self::scan_with_timeout)
    /// to choose a different bound.
    ///
    /// If this call returns `Ok`, [`is_caught_up()`](Self::is_caught_up) is
    /// `true` and the table contains the latest value for every live key
    /// observed up to the snapshot watermark.
    ///
    /// # Errors
    ///
    /// Returns an error if any poll fails unrecoverably, if the initial
    /// watermark snapshot cannot be obtained, or if the scan does not catch
    /// up in time — the timeout error names each partition that is still
    /// behind along with its position and target offset.
    pub async fn scan(&mut self, poll_timeout: Duration) -> Result<()> {
        self.scan_with_timeout(poll_timeout, DEFAULT_SCAN_TIMEOUT)
            .await
    }

    /// Like [`scan()`](Self::scan), but with an explicit upper bound on how
    /// long the scan may run.
    ///
    /// A partition can fail to make progress indefinitely — it may have no
    /// leader, or its offsets may never resolve — so the scan loop is bounded
    /// by wall-clock time. When `timeout` elapses with partitions still short
    /// of their target, the returned error lists those partitions with their
    /// last known position and the target they were expected to reach, which
    /// identifies the stalled partition directly.
    ///
    /// `timeout` bounds the whole scan, not an individual poll; a single poll
    /// may still block for up to `poll_timeout` past the deadline before the
    /// timeout is detected.
    ///
    /// # Errors
    ///
    /// Returns an error if no partitions are assigned, if any poll fails
    /// unrecoverably, if the watermark snapshot cannot be obtained, or if
    /// `timeout` elapses before every partition reaches its target.
    pub async fn scan_with_timeout(
        &mut self,
        poll_timeout: Duration,
        timeout: Duration,
    ) -> Result<()> {
        run_scan(
            &self.consumer,
            &self.topic,
            &mut self.table,
            poll_timeout,
            timeout,
        )
        .await?;
        self.caught_up = true;
        Ok(())
    }

    /// Poll for new records and update the table.
    ///
    /// Returns a list of [`TableChange`]s describing how the table was
    /// modified. An empty list means no new records were received.
    ///
    /// Also updates the [`is_caught_up()`](Self::is_caught_up) flag if the
    /// consumer reaches the high watermarks for the first time.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying consumer poll fails.
    pub async fn poll(&mut self, timeout: Duration) -> Result<Vec<TableChange>> {
        let mut records = self.consumer.poll(timeout).await?;
        let before_len = records.len();
        records.retain(|r| r.topic == self.topic);
        let filtered = before_len - records.len();
        if filtered > 0 {
            debug!(
                "Filtered out {} record(s) from other topics during poll for '{}'",
                filtered, self.topic
            );
        }
        let changes = self.table.apply(&records);

        if !self.caught_up && self.check_caught_up().await {
            self.caught_up = true;
            debug!(
                "CompactedTopicConsumer for '{}' caught up via poll()",
                self.topic
            );
        }

        Ok(changes)
    }

    /// Returns a reference to the underlying [`CompactedTable`].
    pub fn table(&self) -> &CompactedTable {
        &self.table
    }

    /// Returns a mutable reference to the underlying [`CompactedTable`].
    pub fn table_mut(&mut self) -> &mut CompactedTable {
        &mut self.table
    }

    /// Returns `true` after the consumer has caught up to the topic's high
    /// watermarks. Becomes `true` when [`scan()`](Self::scan) completes or
    /// when [`poll()`](Self::poll) naturally reaches the end.
    pub fn is_caught_up(&self) -> bool {
        self.caught_up
    }

    /// Return a metrics snapshot for this consumer, including table statistics
    /// and the caught-up flag.
    #[must_use]
    pub fn metrics_snapshot(&self) -> CompactedTableSnapshot {
        let mut snap = self.table.metrics_snapshot();
        snap.caught_up = self.caught_up;
        snap
    }

    /// Returns the topic name.
    pub fn topic(&self) -> &str {
        &self.topic
    }

    /// Returns a reference to the underlying [`Consumer`].
    ///
    /// Useful for calling consumer operations not exposed on this wrapper,
    /// such as seek, pause, commit, or reading assignment/metrics.
    pub fn consumer(&self) -> &Consumer {
        &self.consumer
    }

    /// Returns a mutable reference to the underlying [`Consumer`].
    pub fn consumer_mut(&mut self) -> &mut Consumer {
        &mut self.consumer
    }

    /// Unwrap this wrapper and return the underlying [`Consumer`] and
    /// [`CompactedTable`].
    pub fn into_parts(self) -> (Consumer, CompactedTable) {
        (self.consumer, self.table)
    }

    /// Close the underlying consumer and surface shutdown errors.
    pub async fn close(&self) -> Result<()> {
        self.consumer.close().await
    }

    /// Check if all assigned partitions have reached their live cached high
    /// watermarks.
    ///
    /// This is used by [`poll()`](Self::poll) for best-effort post-scan
    /// caught-up detection. The bounded [`scan()`](Self::scan) operation
    /// compares against a pre-scan HWM snapshot instead.
    async fn check_caught_up(&self) -> bool {
        let assignments = self.consumer.assignment().await;
        let Some(partitions) = assignments.get(&self.topic) else {
            return false;
        };

        for &partition in partitions {
            let position = self.consumer.position(&self.topic, partition).await;
            let high_watermark = self
                .consumer
                .cached_end_offset(&self.topic, partition)
                .await;

            match (position, high_watermark) {
                // Position at or past the high watermark — caught up.
                (Some(pos), Some(hw)) if pos >= hw => continue,
                // High watermark is 0 — empty partition, nothing to consume.
                (_, Some(0)) => continue,
                // Position or high watermark not yet known, or still behind.
                _ => return false,
            }
        }

        true
    }
}

/// Builder for [`CompactedTopicConsumer`].
#[derive(Default)]
pub struct CompactedTopicConsumerBuilder {
    bootstrap_servers: Option<String>,
    topic: Option<String>,
    client_id: Option<String>,
    request_timeout: Option<Duration>,
    fetch_max_bytes: Option<i32>,
    max_partition_fetch_bytes: Option<i32>,
    max_poll_records: Option<i32>,
    auth: Option<AuthConfig>,
    #[cfg(feature = "socks5")]
    proxy: Option<crate::network::ProxyConfig>,
}

impl CompactedTopicConsumerBuilder {
    /// Set the Kafka bootstrap servers (required).
    pub fn bootstrap_servers(mut self, servers: impl Into<String>) -> Self {
        self.bootstrap_servers = Some(servers.into());
        self
    }

    /// Set the compacted topic to consume (required).
    pub fn topic(mut self, topic: impl Into<String>) -> Self {
        self.topic = Some(topic.into());
        self
    }

    /// Set the client ID sent to the broker.
    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_id = Some(client_id.into());
        self
    }

    /// Set the request timeout for broker RPCs.
    pub fn request_timeout(mut self, timeout: Duration) -> Self {
        self.request_timeout = Some(timeout);
        self
    }

    /// Set the maximum bytes to fetch per request.
    pub fn fetch_max_bytes(mut self, bytes: i32) -> Self {
        self.fetch_max_bytes = Some(bytes);
        self
    }

    /// Set the maximum bytes to fetch per partition per request.
    pub fn max_partition_fetch_bytes(mut self, bytes: i32) -> Self {
        self.max_partition_fetch_bytes = Some(bytes);
        self
    }

    /// Set the maximum number of records returned per poll.
    pub fn max_poll_records(mut self, max: i32) -> Self {
        self.max_poll_records = Some(max);
        self
    }

    /// Set authentication configuration.
    pub fn auth(mut self, auth: AuthConfig) -> Self {
        self.auth = Some(auth);
        self
    }

    /// Set SOCKS5 proxy configuration.
    ///
    /// Routes all broker connections through the specified SOCKS5 proxy.
    #[cfg(feature = "socks5")]
    pub fn proxy(mut self, proxy: crate::network::ProxyConfig) -> Self {
        self.proxy = Some(proxy);
        self
    }

    /// Build the [`CompactedTopicConsumer`].
    ///
    /// Creates an internal [`Consumer`] in standalone mode (no consumer group),
    /// discovers all partitions for the topic, and assigns them starting from
    /// the earliest available offset.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `bootstrap_servers` or `topic` is not set.
    /// - The broker is unreachable or the topic does not exist.
    pub async fn build(self) -> Result<CompactedTopicConsumer> {
        let bootstrap_servers = self
            .bootstrap_servers
            .ok_or_else(|| KrafkaError::config("bootstrap_servers is required"))?;
        let topic = self
            .topic
            .ok_or_else(|| KrafkaError::config("topic is required for CompactedTopicConsumer"))?;

        let mut consumer_builder = Consumer::builder()
            .bootstrap_servers(&bootstrap_servers)
            .auto_offset_reset(AutoOffsetReset::Earliest)
            .enable_auto_commit(false);

        if let Some(client_id) = self.client_id {
            consumer_builder = consumer_builder.client_id(client_id);
        }
        if let Some(timeout) = self.request_timeout {
            consumer_builder = consumer_builder.request_timeout(timeout);
        }
        if let Some(bytes) = self.fetch_max_bytes {
            consumer_builder = consumer_builder.fetch_max_bytes(bytes);
        }
        if let Some(bytes) = self.max_partition_fetch_bytes {
            consumer_builder = consumer_builder.max_partition_fetch_bytes(bytes);
        }
        if let Some(max) = self.max_poll_records {
            consumer_builder = consumer_builder.max_poll_records(max);
        }
        if let Some(auth) = self.auth {
            consumer_builder = consumer_builder.auth(auth);
        }
        #[cfg(feature = "socks5")]
        if let Some(proxy) = self.proxy {
            consumer_builder = consumer_builder.proxy(proxy);
        }

        let consumer = consumer_builder.build().await?;

        // Refresh metadata to get the latest partition count for the topic.
        // Consumer::build() fetches an initial snapshot, but it may already
        // be slightly stale if the topic was recently expanded.
        consumer
            .metadata
            .refresh_for_topics(Some(&[&topic]))
            .await?;

        // Discover partitions and assign all of them
        let partition_count = consumer.metadata.partition_count(&topic).ok_or_else(|| {
            KrafkaError::config(format!("topic '{topic}' not found in cluster metadata"))
        })?;

        let partition_count = PartitionId::try_from(partition_count).map_err(|_| {
            KrafkaError::config(format!(
                "topic '{topic}' has too many partitions to fit in PartitionId"
            ))
        })?;

        let partitions: Vec<PartitionId> = (0..partition_count).collect();
        consumer.assign(&topic, partitions).await?;

        info!(
            "CompactedTopicConsumer initialized for '{}' with {} partitions",
            topic, partition_count
        );

        Ok(CompactedTopicConsumer::from_consumer(consumer, topic))
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    fn make_record(
        key: Option<&str>,
        value: Option<&str>,
        partition: PartitionId,
        offset: Offset,
    ) -> ConsumerRecord {
        ConsumerRecord {
            topic: "test-topic".to_string(),
            partition,
            offset,
            timestamp: offset * 1000,
            timestamp_type: 0,
            key: key.map(|k| Bytes::from(k.to_string())),
            value: value.map(|v| Bytes::from(v.to_string())),
            headers: Vec::new(),
            leader_epoch: None,
            delivery_count: None,
        }
    }

    // -----------------------------------------------------------------------
    // CompactedTable tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_table_insert() {
        let mut table = CompactedTable::new();
        let records = vec![
            make_record(Some("k1"), Some("v1"), 0, 0),
            make_record(Some("k2"), Some("v2"), 0, 1),
        ];

        let changes = table.apply(&records);

        assert_eq!(table.len(), 2);
        assert_eq!(table.get_value(b"k1"), Some(&Bytes::from("v1")));
        assert_eq!(table.get_value(b"k2"), Some(&Bytes::from("v2")));
        assert_eq!(changes.len(), 2);
        assert!(changes[0].is_insert());
        assert!(changes[1].is_insert());
        assert_eq!(table.records_processed(), 2);
        assert_eq!(table.tombstones_processed(), 0);
    }

    #[test]
    fn test_table_update() {
        let mut table = CompactedTable::new();
        table.ingest(&[make_record(Some("k1"), Some("old"), 0, 0)]);

        let changes = table.apply(&[make_record(Some("k1"), Some("new"), 0, 5)]);

        assert_eq!(table.len(), 1);
        assert_eq!(table.get_value(b"k1"), Some(&Bytes::from("new")));
        assert_eq!(changes.len(), 1);
        assert!(changes[0].is_update());
        assert_eq!(changes[0].old_value, Some(Bytes::from("old")));
        assert_eq!(changes[0].new_value, Some(Bytes::from("new")));
    }

    #[test]
    fn test_table_tombstone() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("k1"), Some("v1"), 0, 0),
            make_record(Some("k2"), Some("v2"), 0, 1),
        ]);

        let changes = table.apply(&[make_record(Some("k1"), None, 0, 10)]);

        assert_eq!(table.len(), 1);
        assert!(!table.contains_key(b"k1"));
        assert_eq!(table.get_value(b"k2"), Some(&Bytes::from("v2")));
        assert_eq!(changes.len(), 1);
        assert!(changes[0].is_delete());
        assert_eq!(changes[0].old_value, Some(Bytes::from("v1")));
        assert_eq!(changes[0].new_value, None);
        assert_eq!(table.tombstones_processed(), 1);
    }

    #[test]
    fn test_table_tombstone_for_missing_key() {
        let mut table = CompactedTable::new();
        let changes = table.apply(&[make_record(Some("missing"), None, 0, 0)]);

        assert!(table.is_empty());
        assert_eq!(changes.len(), 1);
        assert!(changes[0].is_delete());
        assert_eq!(changes[0].old_value, None);
        assert_eq!(table.tombstones_processed(), 1);
    }

    #[test]
    fn test_table_skips_keyless() {
        let mut table = CompactedTable::new();
        let records = vec![
            make_record(None, Some("value-without-key"), 0, 0),
            make_record(Some("k1"), Some("v1"), 0, 1),
        ];

        let changes = table.apply(&records);

        assert_eq!(table.len(), 1);
        assert_eq!(changes.len(), 1);
        assert_eq!(table.records_processed(), 2);
    }

    #[test]
    fn test_table_full_lifecycle() {
        let mut table = CompactedTable::new();

        // Insert
        let changes = table.apply(&[
            make_record(Some("user-1"), Some("Alice"), 0, 0),
            make_record(Some("user-2"), Some("Bob"), 0, 1),
        ]);
        assert_eq!(table.len(), 2);
        assert!(changes.iter().all(|c| c.is_insert()));

        // Update
        let changes = table.apply(&[make_record(Some("user-1"), Some("Alice V2"), 0, 2)]);
        assert_eq!(table.get_value(b"user-1"), Some(&Bytes::from("Alice V2")));
        assert!(changes[0].is_update());

        // Delete
        let changes = table.apply(&[make_record(Some("user-2"), None, 0, 3)]);
        assert_eq!(table.len(), 1);
        assert!(changes[0].is_delete());

        // Re-insert deleted key
        let changes = table.apply(&[make_record(Some("user-2"), Some("Bob V2"), 0, 4)]);
        assert_eq!(table.len(), 2);
        assert!(changes[0].is_insert());
    }

    #[test]
    fn test_table_empty_input() {
        let mut table = CompactedTable::new();
        table.ingest(&[make_record(Some("k1"), Some("v1"), 0, 0)]);

        let changes = table.apply(&[]);

        assert_eq!(table.len(), 1);
        assert!(changes.is_empty());
    }

    #[test]
    fn test_table_multiple_partitions() {
        let mut table = CompactedTable::new();
        let records = vec![
            make_record(Some("k1"), Some("v1"), 0, 0),
            make_record(Some("k2"), Some("v2"), 1, 0),
            make_record(Some("k1"), Some("v1-updated"), 0, 1),
        ];

        let changes = table.apply(&records);

        assert_eq!(table.len(), 2);
        assert_eq!(table.get_value(b"k1"), Some(&Bytes::from("v1-updated")));
        assert_eq!(changes.len(), 3);
        assert!(changes[0].is_insert());
        assert!(changes[1].is_insert());
        assert!(changes[2].is_update());
        assert_eq!(changes[0].partition, 0);
        assert_eq!(changes[1].partition, 1);
    }

    #[test]
    fn test_table_with_capacity() {
        let table = CompactedTable::with_capacity(100);
        assert!(table.is_empty());
        assert_eq!(table.records_processed(), 0);
    }

    #[test]
    fn test_table_iter() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("a"), Some("1"), 0, 0),
            make_record(Some("b"), Some("2"), 0, 1),
        ]);

        let items: HashMap<&Bytes, &Bytes> = table.iter().map(|(k, e)| (k, &e.value)).collect();
        assert_eq!(items.len(), 2);
        assert_eq!(items[&Bytes::from("a")], &Bytes::from("1"));
        assert_eq!(items[&Bytes::from("b")], &Bytes::from("2"));
    }

    #[test]
    fn test_table_snapshot() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("k1"), Some("v1"), 0, 0),
            make_record(Some("k2"), Some("v2"), 0, 1),
        ]);

        let snap = table.snapshot();
        assert_eq!(snap.len(), 2);
        assert_eq!(
            snap.get(&Bytes::from("k1")).map(|e| &e.value),
            Some(&Bytes::from("v1"))
        );
    }

    #[test]
    fn test_table_debug() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("k1"), Some("v1"), 0, 0),
            make_record(Some("k2"), None, 0, 1),
        ]);
        let debug = format!("{table:?}");
        assert!(debug.contains("len: 1"));
        assert!(debug.contains("records_processed: 2"));
        assert!(debug.contains("tombstones_processed: 1"));
    }

    #[test]
    fn test_table_clear() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("k1"), Some("v1"), 0, 0),
            make_record(Some("k2"), None, 0, 1),
        ]);
        assert_eq!(table.len(), 1);
        assert_eq!(table.records_processed(), 2);
        assert_eq!(table.tombstones_processed(), 1);

        table.clear();

        assert!(table.is_empty());
        assert_eq!(table.records_processed(), 0);
        assert_eq!(table.tombstones_processed(), 0);
    }

    #[test]
    fn test_table_into_iterator() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("a"), Some("1"), 0, 0),
            make_record(Some("b"), Some("2"), 0, 1),
        ]);

        let items: HashMap<&Bytes, &Bytes> =
            (&table).into_iter().map(|(k, e)| (k, &e.value)).collect();
        assert_eq!(items.len(), 2);
        assert_eq!(items[&Bytes::from("a")], &Bytes::from("1"));
    }

    #[test]
    fn test_table_change_classification() {
        // Insert: old=None, new=Some
        let insert = TableChange {
            key: Bytes::from("k"),
            old_value: None,
            new_value: Some(Bytes::from("v")),
            partition: 0,
            offset: 0,
            timestamp: 0,
        };
        assert!(insert.is_insert());
        assert!(!insert.is_update());
        assert!(!insert.is_delete());

        // Update: old=Some, new=Some
        let update = TableChange {
            key: Bytes::from("k"),
            old_value: Some(Bytes::from("old")),
            new_value: Some(Bytes::from("new")),
            partition: 0,
            offset: 1,
            timestamp: 1000,
        };
        assert!(!update.is_insert());
        assert!(update.is_update());
        assert!(!update.is_delete());

        // Delete: new=None
        let delete = TableChange {
            key: Bytes::from("k"),
            old_value: Some(Bytes::from("v")),
            new_value: None,
            partition: 0,
            offset: 2,
            timestamp: 2000,
        };
        assert!(!delete.is_insert());
        assert!(!delete.is_update());
        assert!(delete.is_delete());
    }

    #[test]
    fn test_table_keys() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("a"), Some("1"), 0, 0),
            make_record(Some("b"), Some("2"), 0, 1),
        ]);

        let mut keys: Vec<&Bytes> = table.keys().collect();
        keys.sort();
        assert_eq!(keys, vec![&Bytes::from("a"), &Bytes::from("b")]);
    }

    #[test]
    fn test_table_values() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("a"), Some("1"), 0, 0),
            make_record(Some("b"), Some("2"), 0, 1),
        ]);

        let mut values: Vec<&Bytes> = table.values().map(|e| &e.value).collect();
        values.sort();
        assert_eq!(values, vec![&Bytes::from("1"), &Bytes::from("2")]);
    }

    #[test]
    fn test_table_owned_into_iterator() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("a"), Some("1"), 0, 0),
            make_record(Some("b"), Some("2"), 0, 1),
        ]);

        let items: HashMap<Bytes, Bytes> = table.into_iter().map(|(k, e)| (k, e.value)).collect();
        assert_eq!(items.len(), 2);
        assert_eq!(items.get(&Bytes::from("a")), Some(&Bytes::from("1")));
        assert_eq!(items.get(&Bytes::from("b")), Some(&Bytes::from("2")));
    }

    #[test]
    fn test_table_clone_preserves_state() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("k1"), Some("v1"), 0, 0),
            make_record(Some("k2"), Some("v2"), 0, 1),
            make_record(Some("k3"), None, 0, 2), // tombstone (key never existed)
        ]);

        let cloned = table.clone();

        assert_eq!(cloned.len(), table.len());
        assert_eq!(cloned.get(b"k1"), table.get(b"k1"));
        assert_eq!(cloned.get(b"k2"), table.get(b"k2"));
        assert_eq!(cloned.records_processed(), table.records_processed());
        assert_eq!(cloned.tombstones_processed(), table.tombstones_processed());
    }

    #[test]
    fn test_table_ingest() {
        let mut table = CompactedTable::new();
        let records = vec![
            make_record(Some("k1"), Some("v1"), 0, 0),
            make_record(Some("k2"), Some("v2"), 0, 1),
            make_record(None, Some("no-key"), 0, 2),
            make_record(Some("k1"), None, 0, 3), // tombstone
        ];

        table.ingest(&records);

        assert_eq!(table.len(), 1);
        assert!(!table.contains_key(b"k1"));
        assert_eq!(table.get_value(b"k2"), Some(&Bytes::from("v2")));
        assert_eq!(table.records_processed(), 4);
        assert_eq!(table.tombstones_processed(), 1);
    }

    #[test]
    fn test_table_ingest_matches_apply_state() {
        let records = vec![
            make_record(Some("a"), Some("1"), 0, 0),
            make_record(Some("b"), Some("2"), 1, 0),
            make_record(Some("a"), Some("3"), 0, 1),
            make_record(Some("b"), None, 1, 1),
        ];

        let mut via_apply = CompactedTable::new();
        let _ = via_apply.apply(&records);

        let mut via_ingest = CompactedTable::new();
        via_ingest.ingest(&records);

        // Both methods must produce identical table state (entries + counters).
        assert_eq!(via_apply, via_ingest);
        assert_eq!(
            via_apply.records_processed(),
            via_ingest.records_processed()
        );
        assert_eq!(
            via_apply.tombstones_processed(),
            via_ingest.tombstones_processed()
        );
    }

    #[test]
    fn test_table_equality_ignores_counters() {
        // Two tables built from different batches but with identical final entries
        // (same key, value, offset, timestamp) must compare equal regardless of
        // how many total records were processed.
        let mut t1 = CompactedTable::new();
        t1.ingest(&[make_record(Some("k"), Some("v"), 0, 5)]);

        let mut t2 = CompactedTable::new();
        t2.ingest(&[
            make_record(None, Some("noise"), 0, 0), // keyless — skipped, but counted
            make_record(Some("k"), Some("v"), 0, 5), // same key/value/offset/ts
        ]);

        // Same entries, different counters.
        assert_eq!(t1, t2);
        assert_ne!(t1.records_processed(), t2.records_processed());
    }

    #[test]
    fn test_table_same_key_lifecycle_in_single_batch() {
        let mut table = CompactedTable::new();
        let records = vec![
            make_record(Some("x"), Some("v1"), 0, 0), // insert
            make_record(Some("x"), Some("v2"), 0, 1), // update
            make_record(Some("x"), None, 0, 2),       // delete
            make_record(Some("x"), Some("v3"), 0, 3), // re-insert
        ];

        let changes = table.apply(&records);

        assert_eq!(table.len(), 1);
        assert_eq!(table.get_value(b"x"), Some(&Bytes::from("v3")));
        assert_eq!(changes.len(), 4);

        // Insert: no previous value
        assert!(changes[0].is_insert());
        assert_eq!(changes[0].old_value, None);
        assert_eq!(changes[0].new_value, Some(Bytes::from("v1")));

        // Update: old_value reflects in-batch state, not just pre-batch
        assert!(changes[1].is_update());
        assert_eq!(changes[1].old_value, Some(Bytes::from("v1")));
        assert_eq!(changes[1].new_value, Some(Bytes::from("v2")));

        // Delete: old_value is the most recent in-batch value
        assert!(changes[2].is_delete());
        assert_eq!(changes[2].old_value, Some(Bytes::from("v2")));

        // Re-insert after in-batch delete: treated as fresh insert
        assert!(changes[3].is_insert());
        assert_eq!(changes[3].old_value, None);
        assert_eq!(changes[3].new_value, Some(Bytes::from("v3")));

        assert_eq!(table.records_processed(), 4);
        assert_eq!(table.tombstones_processed(), 1);
    }

    #[test]
    fn test_all_public_types_are_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<CompactedTable>();
        assert_send_sync::<TableChange>();
        assert_send_sync::<CompactedTopicConsumer>();
        assert_send_sync::<CompactedTopicConsumerBuilder>();
    }

    #[tokio::test]
    async fn test_builder_missing_bootstrap_servers() {
        let result = CompactedTopicConsumerBuilder::default()
            .topic("test")
            .build()
            .await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("bootstrap_servers")
        );
    }

    // -----------------------------------------------------------------------
    // Partition-scoped pruning
    // -----------------------------------------------------------------------

    #[test]
    fn test_remove_partitions_removes_only_listed_partitions() {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("p0-a"), Some("v"), 0, 0),
            make_record(Some("p1-a"), Some("v"), 1, 0),
            make_record(Some("p1-b"), Some("v"), 1, 1),
            make_record(Some("p2-a"), Some("v"), 2, 0),
        ]);

        let removed = table.remove_partitions(&[1]);

        assert_eq!(removed, 2);
        assert_eq!(table.len(), 2);
        assert!(table.contains_key(b"p0-a"));
        assert!(table.contains_key(b"p2-a"));
        assert!(!table.contains_key(b"p1-a"));
        assert!(!table.contains_key(b"p1-b"));
        // Lifetime counters describe work done, not current contents.
        assert_eq!(table.records_processed(), 4);
    }

    #[test]
    fn test_remove_partitions_empty_list_is_noop() {
        let mut table = CompactedTable::new();
        table.ingest(&[make_record(Some("k"), Some("v"), 0, 0)]);

        assert_eq!(table.remove_partitions(&[]), 0);
        assert_eq!(table.len(), 1);
    }

    // -----------------------------------------------------------------------
    // CompactedTableClearListener
    // -----------------------------------------------------------------------

    #[derive(Default)]
    struct RecordingRewinder {
        calls: std::sync::Mutex<Vec<(String, PartitionId)>>,
    }

    impl RecordingRewinder {
        fn calls(&self) -> Vec<(String, PartitionId)> {
            self.calls.lock().unwrap().clone()
        }
    }

    impl PartitionRewinder for RecordingRewinder {
        fn rewind_to_beginning<'a>(
            &'a self,
            topic: &'a str,
            partition: PartitionId,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> {
            self.calls
                .lock()
                .unwrap()
                .push((topic.to_string(), partition));
            Box::pin(async { Ok(()) })
        }
    }

    fn populated_table() -> Arc<Mutex<CompactedTable>> {
        let mut table = CompactedTable::new();
        table.ingest(&[
            make_record(Some("p0"), Some("v"), 0, 0),
            make_record(Some("p1"), Some("v"), 1, 0),
            make_record(Some("p2"), Some("v"), 2, 0),
        ]);
        Arc::new(Mutex::new(table))
    }

    #[tokio::test]
    async fn test_listener_revocation_prunes_only_revoked_partitions() {
        let table = populated_table();
        let listener = CompactedTableClearListener::new(Arc::clone(&table));

        listener
            .on_partitions_revoked(&[TopicPartition::new("test-topic", 1)])
            .await;

        let t = table.lock().await;
        assert_eq!(t.len(), 2, "retained partitions must survive revocation");
        assert!(t.contains_key(b"p0"));
        assert!(t.contains_key(b"p2"));
        assert!(!t.contains_key(b"p1"));
    }

    #[tokio::test]
    async fn test_listener_loss_prunes_only_lost_partitions() {
        let table = populated_table();
        let listener = CompactedTableClearListener::new(Arc::clone(&table));

        listener
            .on_partitions_lost(&[TopicPartition::new("test-topic", 2)])
            .await;

        let t = table.lock().await;
        assert_eq!(t.len(), 2);
        assert!(t.contains_key(b"p0"));
        assert!(t.contains_key(b"p1"));
        assert!(!t.contains_key(b"p2"));
    }

    #[tokio::test]
    async fn test_listener_assignment_rewinds_new_partitions() {
        let table = populated_table();
        let rewinder = Arc::new(RecordingRewinder::default());
        let listener = CompactedTableClearListener::with_rewinder(
            Arc::clone(&table),
            Arc::clone(&rewinder) as Arc<dyn PartitionRewinder>,
        );

        listener
            .on_partitions_assigned(&[
                TopicPartition::new("test-topic", 1),
                TopicPartition::new("test-topic", 3),
            ])
            .await;

        assert_eq!(
            rewinder.calls(),
            vec![("test-topic".to_string(), 1), ("test-topic".to_string(), 3)],
            "newly assigned partitions must be replayed from the start"
        );

        // Stale state for a re-gained partition is dropped; untouched
        // partitions keep theirs.
        let t = table.lock().await;
        assert!(!t.contains_key(b"p1"));
        assert!(t.contains_key(b"p0"));
        assert!(t.contains_key(b"p2"));
    }

    #[tokio::test]
    async fn test_listener_assignment_without_consumer_does_not_panic() {
        let table = populated_table();
        let listener = CompactedTableClearListener::new(Arc::clone(&table));

        listener
            .on_partitions_assigned(&[TopicPartition::new("test-topic", 0)])
            .await;

        let t = table.lock().await;
        assert!(!t.contains_key(b"p0"));
        assert_eq!(t.len(), 2);
    }

    #[tokio::test]
    async fn test_listener_empty_rebalance_is_noop() {
        let table = populated_table();
        let listener = CompactedTableClearListener::new(Arc::clone(&table));

        listener.on_partitions_revoked(&[]).await;
        listener.on_partitions_assigned(&[]).await;

        assert_eq!(table.lock().await.len(), 3);
    }

    // -----------------------------------------------------------------------
    // Bounded scan
    // -----------------------------------------------------------------------

    /// A `ScanSource` whose partition positions advance by a fixed amount per
    /// poll, so a test can model both a converging and a permanently stalled
    /// partition.
    struct FakeScanSource {
        assigned: Vec<PartitionId>,
        end_offsets: HashMap<PartitionId, Offset>,
        positions: std::sync::Mutex<HashMap<PartitionId, Offset>>,
        /// Per-partition position increment applied on every poll.
        advance: HashMap<PartitionId, Offset>,
        first_poll_records: std::sync::Mutex<Vec<ConsumerRecord>>,
    }

    impl FakeScanSource {
        fn new(
            assigned: &[PartitionId],
            end_offsets: &[(PartitionId, Offset)],
            positions: &[(PartitionId, Offset)],
            advance: &[(PartitionId, Offset)],
        ) -> Self {
            Self {
                assigned: assigned.to_vec(),
                end_offsets: end_offsets.iter().copied().collect(),
                positions: std::sync::Mutex::new(positions.iter().copied().collect()),
                advance: advance.iter().copied().collect(),
                first_poll_records: std::sync::Mutex::new(Vec::new()),
            }
        }

        fn with_records(self, records: Vec<ConsumerRecord>) -> Self {
            *self.first_poll_records.lock().unwrap() = records;
            self
        }
    }

    impl ScanSource for FakeScanSource {
        async fn poll_records(&self, _timeout: Duration) -> Result<Vec<ConsumerRecord>> {
            let mut positions = self.positions.lock().unwrap();
            for (partition, step) in &self.advance {
                *positions.entry(*partition).or_insert(0) += *step;
            }
            drop(positions);
            Ok(std::mem::take(
                &mut *self.first_poll_records.lock().unwrap(),
            ))
        }

        async fn assigned_partitions(&self, _topic: &str) -> Vec<PartitionId> {
            self.assigned.clone()
        }

        async fn partition_position(&self, _topic: &str, partition: PartitionId) -> Option<Offset> {
            self.positions.lock().unwrap().get(&partition).copied()
        }

        async fn end_offsets(&self, _topic: &str) -> Result<HashMap<PartitionId, Result<Offset>>> {
            Ok(self.end_offsets.iter().map(|(&p, &o)| (p, Ok(o))).collect())
        }
    }

    #[tokio::test]
    async fn test_scan_times_out_and_names_lagging_partitions() {
        // Partition 0 converges immediately; partition 1 never moves and
        // partition 2 has no position at all (e.g. no leader).
        let source = FakeScanSource::new(
            &[0, 1, 2],
            &[(0, 10), (1, 5), (2, 7)],
            &[(0, 10), (1, 2)],
            &[],
        );
        let mut table = CompactedTable::new();

        let err = run_scan(
            &source,
            "test-topic",
            &mut table,
            Duration::from_millis(1),
            Duration::from_millis(30),
        )
        .await
        .expect_err("scan must not run forever when a partition never converges");

        let msg = err.to_string();
        assert!(
            msg.contains("partition 1 (position 2, target 5)"),
            "error must name the stalled partition and its lag: {msg}"
        );
        assert!(
            msg.contains("partition 2 (position unknown, target 7)"),
            "error must name partitions with no known position: {msg}"
        );
        assert!(
            !msg.contains("partition 0"),
            "caught-up partitions must not be reported as lagging: {msg}"
        );
    }

    #[tokio::test]
    async fn test_scan_completes_when_partitions_reach_targets() {
        let source = FakeScanSource::new(&[0], &[(0, 3)], &[(0, 0)], &[(0, 3)])
            .with_records(vec![make_record(Some("k1"), Some("v1"), 0, 0)]);
        let mut table = CompactedTable::new();

        run_scan(
            &source,
            "test-topic",
            &mut table,
            Duration::from_millis(1),
            Duration::from_secs(5),
        )
        .await
        .unwrap();

        assert_eq!(table.get_value(b"k1"), Some(&Bytes::from("v1")));
    }

    #[tokio::test]
    async fn test_scan_requires_an_assignment() {
        let source = FakeScanSource::new(&[], &[], &[], &[]);
        let mut table = CompactedTable::new();

        let err = run_scan(
            &source,
            "test-topic",
            &mut table,
            Duration::from_millis(1),
            Duration::from_millis(10),
        )
        .await
        .unwrap_err();

        assert!(err.to_string().contains("no partitions assigned"));
    }

    #[tokio::test]
    async fn test_scan_returns_early_for_empty_topic() {
        let source = FakeScanSource::new(&[0], &[(0, 0)], &[], &[]);
        let mut table = CompactedTable::new();

        run_scan(
            &source,
            "test-topic",
            &mut table,
            Duration::from_millis(1),
            Duration::from_millis(10),
        )
        .await
        .unwrap();

        assert!(table.is_empty());
    }

    #[tokio::test]
    async fn test_lagging_partitions_ignores_empty_and_unknown_targets() {
        // Partition 0 is empty (target 0), partition 9 is assigned but was not
        // in the snapshot; neither may hold the scan back.
        let source = FakeScanSource::new(&[0, 9], &[], &[], &[]);
        let targets: HashMap<PartitionId, Offset> = [(0, 0)].into_iter().collect();

        assert!(
            lagging_partitions(&source, "test-topic", &targets)
                .await
                .is_empty()
        );
    }

    #[test]
    fn test_scan_timeout_error_lists_every_lagging_partition() {
        let err = scan_timeout_error(
            "cfg",
            Duration::from_secs(2),
            &[
                LaggingPartition {
                    partition: 3,
                    position: Some(7),
                    target: 42,
                },
                LaggingPartition {
                    partition: 4,
                    position: None,
                    target: 1,
                },
            ],
        );

        let msg = err.to_string();
        assert!(msg.contains("cfg"));
        assert!(msg.contains("partition 3 (position 7, target 42)"));
        assert!(msg.contains("partition 4 (position unknown, target 1)"));
    }

    #[tokio::test]
    async fn test_builder_missing_topic() {
        let result = CompactedTopicConsumerBuilder::default()
            .bootstrap_servers("localhost:9092")
            .build()
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("topic"));
    }
}