kacrab 0.2.0

A Kafka client for Rust, built from the protocol up.
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
//! Per topic-partition record accumulation for producer batching.

use std::{
    collections::VecDeque,
    sync::Arc,
    time::{Duration, Instant},
};

use ahash::{AHashMap, AHashSet};
use kacrab_protocol::{signed_varint_len, signed_varlong_len};

use super::{
    batch::current_time_ms,
    error::{ProducerError, Result},
    record::{DeliverySender, ProducerRecord, SendFuture},
    transaction::ProducerBatchState,
};
use crate::wire::{PartitionMetadata, TopicMetadata};

/// Kafka default `batch.size`: 16 KiB is the Kafka producer baseline that gives
/// useful batching without forcing large per-partition buffers.
const DEFAULT_BATCH_SIZE: usize = 16_384;
/// Kafka default `linger.ms` is zero for the raw accumulator; typed
/// `ProducerConfig` can raise this to Kafka's current producer default.
const DEFAULT_LINGER: Duration = Duration::ZERO;
/// Kafka default `buffer.memory`: 32 MiB bounds queued records while leaving
/// enough room for many topic-partition batches.
const DEFAULT_BUFFER_MEMORY: usize = 33_554_432;
/// Per-record accumulator accounting overhead. It reserves space for the record
/// struct, delivery bookkeeping, and hash-map queue metadata so backpressure
/// trips before payload bytes alone exhaust memory.
const ESTIMATED_RECORD_OVERHEAD_BYTES: usize = 64;
pub(crate) const RECORD_BATCH_OVERHEAD_BYTES: usize = 61;
const COMPRESSION_RATE_ESTIMATION_FACTOR: f32 = 1.05;

/// Configuration for producer record accumulation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AccumulatorConfig {
    /// Target batch size in estimated buffered bytes.
    pub batch_size: usize,
    /// Time to wait before a non-full partition batch becomes ready.
    pub linger: Duration,
    /// Total estimated producer memory available to buffered records.
    pub buffer_memory: usize,
}

impl Default for AccumulatorConfig {
    fn default() -> Self {
        Self {
            batch_size: DEFAULT_BATCH_SIZE,
            linger: DEFAULT_LINGER,
            buffer_memory: DEFAULT_BUFFER_MEMORY,
        }
    }
}

impl AccumulatorConfig {
    /// Set the target batch size in estimated buffered bytes.
    #[must_use]
    pub const fn batch_size(mut self, bytes: usize) -> Self {
        self.batch_size = if bytes == 0 { 1 } else { bytes };
        self
    }

    /// Set the linger duration.
    #[must_use]
    pub const fn linger(mut self, linger: Duration) -> Self {
        self.linger = linger;
        self
    }

    /// Set the total estimated buffer memory.
    #[must_use]
    pub const fn buffer_memory(mut self, bytes: usize) -> Self {
        self.buffer_memory = bytes;
        self
    }
}

/// A drained topic-partition batch ready for request construction.
#[derive(Debug)]
pub struct ReadyBatch {
    pub(crate) identity: ReadyBatchIdentity,
    /// Topic name.
    pub topic: String,
    /// Partition index.
    pub partition: i32,
    /// Records accumulated for this topic-partition.
    pub records: Vec<ProducerRecord>,
    /// Batch delivery state waiting on this topic-partition ack.
    pub(crate) delivery: Option<DeliverySender>,
    /// Estimated batch bytes used for produce-batch metrics.
    pub bytes: usize,
    /// Bytes currently held against pooled buffer memory.
    pub(crate) pooled_buffer_bytes: usize,
    /// Timestamp for the first record in this batch.
    pub first_append_at: Instant,
    /// Idempotent producer fields assigned once for this drained batch.
    pub(crate) producer_state: Option<ProducerBatchState>,
}

impl ReadyBatch {
    #[cfg(test)]
    pub(crate) const fn identity(&self) -> ReadyBatchIdentity {
        self.identity
    }

    pub(crate) const fn pooled_buffer_bytes(&self) -> usize {
        self.pooled_buffer_bytes
    }

    pub(crate) fn split_for_retry_with_compression_ratio(
        self,
        target_batch_bytes: usize,
        compression_ratio: f32,
    ) -> Option<Vec<Self>> {
        if self.records.len() <= 1 {
            return None;
        }
        let identity = self.identity;
        let topic = self.topic;
        let partition = self.partition;
        let mut delivery = self.delivery;
        let first_append_at = self.first_append_at;
        let producer_state = self.producer_state;
        let original_bytes = self.bytes;
        let split_groups =
            split_records_by_batch_target(self.records, target_batch_bytes, compression_ratio);
        let mut remaining_bytes = original_bytes;
        let last_index = split_groups.len().saturating_sub(1);
        let split = split_groups
            .into_iter()
            .enumerate()
            .map(|(index, group)| {
                let bytes = if index == last_index {
                    remaining_bytes
                } else {
                    let bytes = group.bytes.min(remaining_bytes);
                    remaining_bytes = remaining_bytes.saturating_sub(bytes);
                    bytes
                };
                Self {
                    identity: identity.split_child(u32::try_from(index).unwrap_or(u32::MAX)),
                    topic: topic.clone(),
                    partition,
                    records: group.records,
                    delivery: if index == 0 { delivery.take() } else { None },
                    bytes,
                    pooled_buffer_bytes: 0,
                    first_append_at,
                    producer_state: split_producer_state(producer_state, group.first_record_index),
                }
            })
            .collect();
        Some(split)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum ReadyBatchIdentity {
    Accumulator(u64),
    Split {
        parent: u64,
        index: u32,
    },
    #[cfg(test)]
    Test(u64),
}

impl ReadyBatchIdentity {
    const fn split_child(self, index: u32) -> Self {
        match self {
            Self::Accumulator(parent) | Self::Split { parent, .. } => Self::Split { parent, index },
            #[cfg(test)]
            Self::Test(parent) => Self::Split { parent, index },
        }
    }

    const fn split_parent(self) -> Option<Self> {
        match self {
            Self::Split { parent, .. } => Some(Self::Accumulator(parent)),
            Self::Accumulator(_) => None,
            #[cfg(test)]
            Self::Test(_) => None,
        }
    }

    #[cfg(test)]
    pub(crate) const fn test(id: u64) -> Self {
        Self::Test(id)
    }
}

struct SplitRecordGroup {
    first_record_index: usize,
    records: Vec<ProducerRecord>,
    bytes: usize,
}

/// Per-partition queue sizes used by adaptive sticky partitioning.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PartitionQueueLoad {
    pub(crate) queue_sizes: Vec<i32>,
    pub(crate) partition_ids: Vec<i32>,
    pub(crate) length: usize,
}

/// Result metadata for an append operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct AppendStatus {
    pub(crate) batch_ready: bool,
    pub(crate) ready_batch_records: usize,
    pub(crate) starts_new_batch: bool,
}

/// Bounded producer record accumulator keyed by topic-partition.
#[derive(Debug)]
pub struct RecordAccumulator {
    config: AccumulatorConfig,
    partitions: AHashMap<TopicPartition, PartitionQueue>,
    buffered_batch_identities: AHashSet<ReadyBatchIdentity>,
    incomplete_batch_identities: AHashSet<ReadyBatchIdentity>,
    buffered_bytes: usize,
    next_batch_id: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct TopicPartition {
    topic: Arc<str>,
    partition: i32,
}

#[derive(Debug)]
struct PartitionQueue {
    batches: VecDeque<PartitionBatch>,
}

#[derive(Debug)]
struct PartitionBatch {
    identity: ReadyBatchIdentity,
    records: Vec<ProducerRecord>,
    delivery: Option<DeliverySender>,
    producer_state: Option<ProducerBatchState>,
    buffer_bytes: usize,
    batch_bytes: usize,
    compression_sizing: CompressionSizing,
    sealed: bool,
    first_append_at: Instant,
}

#[derive(Debug, Clone, Copy)]
struct AppendTarget {
    sealed_previous_records: usize,
    record_batch_bytes: usize,
    starts_new_batch: bool,
    reserved_buffer_bytes: usize,
}

#[derive(Debug, Clone, Copy)]
struct CompressionSizing {
    ratio: f32,
}

impl CompressionSizing {
    const NONE: Self = Self { ratio: 1.0 };

    fn new(ratio: f32) -> Self {
        if ratio.is_finite() && ratio > 0.0 {
            Self { ratio }
        } else {
            Self::NONE
        }
    }

    const fn uses_estimate(self) -> bool {
        (self.ratio - 1.0).abs() > f32::EPSILON
    }
}

impl RecordAccumulator {
    /// Create an empty accumulator.
    #[must_use]
    pub fn new(config: AccumulatorConfig) -> Self {
        Self {
            config,
            partitions: AHashMap::new(),
            buffered_batch_identities: AHashSet::new(),
            incomplete_batch_identities: AHashSet::new(),
            buffered_bytes: 0,
            next_batch_id: 0,
        }
    }

    /// Estimated buffered bytes currently held by the accumulator.
    #[must_use]
    pub const fn buffered_bytes(&self) -> usize {
        self.buffered_bytes
    }

    pub(crate) const fn buffer_memory(&self) -> usize {
        self.config.buffer_memory
    }

    pub(crate) fn has_available_memory_for_reserved_with_compression_ratio(
        &self,
        record: &ProducerRecord,
        reserved_bytes: usize,
        compression_ratio: f32,
    ) -> bool {
        let append_reservation =
            self.append_buffer_reservation_with_compression_ratio(record, compression_ratio);
        append_reservation
            <= self
                .config
                .buffer_memory
                .saturating_sub(self.buffered_bytes)
                .saturating_sub(reserved_bytes)
    }

    /// Records currently buffered in the producer accumulator.
    #[must_use]
    pub fn buffered_records(&self) -> usize {
        self.partitions
            .values()
            .flat_map(|queue| queue.batches.iter())
            .map(|batch| batch.records.len())
            .sum()
    }

    /// Batches currently owned by the producer accumulator.
    #[must_use]
    pub(crate) fn buffered_batches(&self) -> usize {
        self.partitions
            .values()
            .map(|queue| queue.batches.len())
            .sum()
    }

    /// Build queue load stats for one topic while excluding partitions
    /// whose leaders are temporarily unavailable for adaptive sticky routing.
    pub(crate) fn partition_queue_load_with_availability<F>(
        &self,
        topic_metadata: &TopicMetadata,
        mut is_partition_available: F,
    ) -> Option<PartitionQueueLoad>
    where
        F: FnMut(&PartitionMetadata) -> bool,
    {
        let partition_count = topic_metadata.partitions.len();
        if partition_count < 2 {
            return None;
        }
        let mut queue_sizes = vec![0; partition_count];
        let mut partition_ids = vec![0; partition_count];
        let mut length = 0;
        for partition in &topic_metadata.partitions {
            let key = TopicPartition {
                topic: Arc::<str>::from(topic_metadata.name.as_str()),
                partition: partition.partition_index,
            };
            let queue = self.partitions.get(&key)?;
            if partition.leader_id < 0 {
                continue;
            }
            let size = i32::try_from(queue.batches.len()).ok()?;
            if is_partition_available(partition) {
                *queue_sizes.get_mut(length)? = size;
                *partition_ids.get_mut(length)? = partition.partition_index;
                length = length.checked_add(1)?;
            }
        }
        Some(PartitionQueueLoad {
            queue_sizes,
            partition_ids,
            length,
        })
    }

    /// Append a record using the current clock.
    pub fn append(&mut self, record: ProducerRecord) -> Result<()> {
        self.append_internal(record, Instant::now())
            .map(|_status| ())
    }

    /// Append a record at a supplied timestamp. Useful for deterministic tests.
    pub fn append_at(&mut self, record: ProducerRecord, now: Instant) -> Result<()> {
        self.append_internal(record, now).map(|_status| ())
    }

    /// Append a record at a supplied timestamp and report whether a batch became ready.
    #[cfg(test)]
    pub(crate) fn append_with_status_at(
        &mut self,
        record: ProducerRecord,
        now: Instant,
    ) -> Result<AppendStatus> {
        self.append_internal(record, now)
    }

    #[cfg(test)]
    pub(crate) fn append_with_status_at_compression_ratio(
        &mut self,
        record: ProducerRecord,
        now: Instant,
        compression_ratio: f32,
    ) -> Result<AppendStatus> {
        self.append_internal_with_compression_sizing(
            record,
            now,
            CompressionSizing::new(compression_ratio),
        )
    }

    /// Append a record and return a delivery handle for its eventual broker ack.
    pub fn append_for_delivery(&mut self, record: ProducerRecord) -> Result<SendFuture> {
        let (delivery, _status) =
            self.append_internal_for_delivery(record, Instant::now(), 1, CompressionSizing::NONE)?;
        delivery.ok_or(ProducerError::DeliveryDropped)
    }

    pub(crate) fn append_for_delivery_with_status_at_compression_ratio(
        &mut self,
        record: ProducerRecord,
        now: Instant,
        compression_ratio: f32,
    ) -> Result<(SendFuture, AppendStatus)> {
        let (delivery, status) = self.append_internal_for_delivery(
            record,
            now,
            1,
            CompressionSizing::new(compression_ratio),
        )?;
        let Some(delivery) = delivery else {
            return Err(ProducerError::DeliveryDropped);
        };
        Ok((delivery, status))
    }

    fn append_internal(&mut self, record: ProducerRecord, now: Instant) -> Result<AppendStatus> {
        self.append_internal_with_compression_sizing(record, now, CompressionSizing::NONE)
    }

    fn append_internal_with_compression_sizing(
        &mut self,
        record: ProducerRecord,
        now: Instant,
        compression_sizing: CompressionSizing,
    ) -> Result<AppendStatus> {
        let record = record_with_append_timestamp(record);
        let key = TopicPartition {
            topic: Arc::<str>::clone(&record.topic),
            partition: record.partition,
        };
        let batch_size = self.config.batch_size.max(1);
        let available = self
            .config
            .buffer_memory
            .saturating_sub(self.buffered_bytes);
        // Single hash lookup: take the (mutable) partition queue up front and
        // compute the append target from it, instead of an immutable get()
        // followed by a separate entry() — both hash the topic Arc<str> on every
        // append. An empty queue plans the same target as a missing one.
        let queue = self
            .partitions
            .entry(key)
            .or_insert_with(|| PartitionQueue {
                batches: VecDeque::new(),
            });
        let target = planned_append_target(Some(&*queue), &record, batch_size, compression_sizing);
        if target.reserved_buffer_bytes > available {
            return Err(ProducerError::Backpressure);
        }
        let next_identity = &mut self.next_batch_id;
        if let Some(identity) = apply_append_target(queue, now, batch_size, target, next_identity) {
            let _inserted = self.buffered_batch_identities.insert(identity);
            let _inserted = self.incomplete_batch_identities.insert(identity);
        }
        let Some(batch) = queue.batches.back_mut() else {
            return Err(ProducerError::Backpressure);
        };
        batch.compression_sizing = compression_sizing;
        batch.batch_bytes = batch.batch_bytes.saturating_add(target.record_batch_bytes);
        let current_batch_records = batch.records.len().saturating_add(1);
        let current_batch_ready =
            estimated_batch_bytes_for_sizing(batch.batch_bytes, compression_sizing) >= batch_size;
        batch.records.push(record);
        self.buffered_bytes = self
            .buffered_bytes
            .saturating_add(target.reserved_buffer_bytes);
        Ok(append_status(
            target.sealed_previous_records,
            current_batch_ready,
            current_batch_records,
            target.starts_new_batch,
        ))
    }

    fn append_internal_for_delivery(
        &mut self,
        record: ProducerRecord,
        now: Instant,
        metadata_capacity: usize,
        compression_sizing: CompressionSizing,
    ) -> Result<(Option<SendFuture>, AppendStatus)> {
        let record = record_with_append_timestamp(record);
        let key = TopicPartition {
            topic: Arc::<str>::clone(&record.topic),
            partition: record.partition,
        };
        let batch_size = self.config.batch_size.max(1);
        let available = self
            .config
            .buffer_memory
            .saturating_sub(self.buffered_bytes);
        // Single hash lookup: take the (mutable) partition queue up front and
        // compute the append target from it, instead of an immutable get()
        // followed by a separate entry() — both hash the topic Arc<str> on every
        // append. An empty queue plans the same target as a missing one.
        let queue = self
            .partitions
            .entry(key)
            .or_insert_with(|| PartitionQueue {
                batches: VecDeque::new(),
            });
        let target = planned_append_target(Some(&*queue), &record, batch_size, compression_sizing);
        if target.reserved_buffer_bytes > available {
            return Err(ProducerError::Backpressure);
        }
        let next_identity = &mut self.next_batch_id;
        if let Some(identity) = apply_append_target(queue, now, batch_size, target, next_identity) {
            let _inserted = self.buffered_batch_identities.insert(identity);
            let _inserted = self.incomplete_batch_identities.insert(identity);
        }
        let Some(batch) = queue.batches.back_mut() else {
            return Err(ProducerError::Backpressure);
        };
        batch.compression_sizing = compression_sizing;
        batch.batch_bytes = batch.batch_bytes.saturating_add(target.record_batch_bytes);
        let delivery = if let Some(sender) = &mut batch.delivery {
            Some(sender.delivery_for_record(&record))
        } else {
            let (sender, delivery) =
                SendFuture::channel_for_record_with_metadata_capacity(&record, metadata_capacity);
            batch.delivery = Some(sender);
            Some(delivery)
        };
        let current_batch_records = batch.records.len().saturating_add(1);
        let current_batch_ready =
            estimated_batch_bytes_for_sizing(batch.batch_bytes, compression_sizing) >= batch_size;
        batch.records.push(record);
        self.buffered_bytes = self
            .buffered_bytes
            .saturating_add(target.reserved_buffer_bytes);
        Ok((
            delivery,
            append_status(
                target.sealed_previous_records,
                current_batch_ready,
                current_batch_records,
                target.starts_new_batch,
            ),
        ))
    }

    fn append_buffer_reservation_with_compression_ratio(
        &self,
        record: &ProducerRecord,
        compression_ratio: f32,
    ) -> usize {
        let key = TopicPartition {
            topic: Arc::<str>::clone(&record.topic),
            partition: record.partition,
        };
        let batch_size = self.config.batch_size.max(1);
        planned_append_target(
            self.partitions.get(&key),
            record,
            batch_size,
            CompressionSizing::new(compression_ratio),
        )
        .reserved_buffer_bytes
    }

    /// Drain topic-partition batches that are ready by size or linger timeout.
    pub fn drain_ready(&mut self, now: Instant) -> Vec<ReadyBatch> {
        let batch_size = self.config.batch_size;
        let linger = self.config.linger;
        let ready_keys: Vec<_> = self
            .partitions
            .iter()
            .filter_map(|(key, queue)| {
                queue
                    .batches
                    .front()
                    .is_some_and(|batch| batch_is_ready(batch, now, batch_size, linger))
                    .then_some(key.clone())
            })
            .collect();
        let mut ready = Vec::with_capacity(ready_keys.len());
        for key in ready_keys {
            if let Some(queue) = self.partitions.get_mut(&key) {
                while queue
                    .batches
                    .front()
                    .is_some_and(|batch| batch_is_ready(batch, now, batch_size, linger))
                {
                    let Some(batch) = queue.batches.pop_front() else {
                        break;
                    };
                    let bytes = ready_batch_bytes(&batch);
                    let _removed = self.buffered_batch_identities.remove(&batch.identity);
                    self.buffered_bytes = self.buffered_bytes.saturating_sub(batch.buffer_bytes);
                    ready.push(ReadyBatch {
                        identity: batch.identity,
                        topic: key.topic.to_string(),
                        partition: key.partition,
                        records: batch.records,
                        delivery: batch.delivery,
                        bytes,
                        pooled_buffer_bytes: batch.buffer_bytes,
                        first_append_at: batch.first_append_at,
                        producer_state: batch.producer_state,
                    });
                }
            }
        }
        ready
    }

    /// Drain at most one ready front batch per partition.
    ///
    /// The dispatch selector emits at most one new request per partition per
    /// cycle, so draining every ready batch (like [`drain_ready`]) only to
    /// re-enqueue all but one is O(N) wasted work per dispatch. This drains
    /// exactly what one selection consumes — the lowest-sequence (front) batch of
    /// each partition that is ready — keeping the re-dispatch hot path O(partitions)
    /// so the wire pipeline stays full under real broker latency.
    pub fn drain_front_ready(&mut self, now: Instant) -> Vec<ReadyBatch> {
        let batch_size = self.config.batch_size;
        let linger = self.config.linger;
        let mut ready = Vec::new();
        for (key, queue) in &mut self.partitions {
            if !queue
                .batches
                .front()
                .is_some_and(|batch| batch_is_ready(batch, now, batch_size, linger))
            {
                continue;
            }
            let Some(batch) = queue.batches.pop_front() else {
                continue;
            };
            let bytes = ready_batch_bytes(&batch);
            let _removed = self.buffered_batch_identities.remove(&batch.identity);
            self.buffered_bytes = self.buffered_bytes.saturating_sub(batch.buffer_bytes);
            ready.push(ReadyBatch {
                identity: batch.identity,
                topic: key.topic.to_string(),
                partition: key.partition,
                records: batch.records,
                delivery: batch.delivery,
                bytes,
                pooled_buffer_bytes: batch.buffer_bytes,
                first_append_at: batch.first_append_at,
                producer_state: batch.producer_state,
            });
        }
        ready
    }

    /// Return the next time any buffered batch should be considered ready.
    pub fn next_ready_at(&self, now: Instant) -> Option<Instant> {
        let batch_size = self.config.batch_size;
        let linger = self.config.linger;
        self.partitions
            .values()
            .filter_map(|queue| queue.batches.front())
            .map(|batch| batch_next_ready_at(batch, now, batch_size, linger))
            .min()
    }

    /// Drain every buffered topic-partition batch regardless of size or linger.
    pub fn drain_all(&mut self) -> Vec<ReadyBatch> {
        let partitions = std::mem::take(&mut self.partitions);
        let mut batches = Vec::with_capacity(partitions.len());
        for (key, queue) in partitions {
            for batch in queue.batches {
                let bytes = ready_batch_bytes(&batch);
                batches.push(ReadyBatch {
                    identity: batch.identity,
                    topic: key.topic.to_string(),
                    partition: key.partition,
                    records: batch.records,
                    delivery: batch.delivery,
                    bytes,
                    pooled_buffer_bytes: batch.buffer_bytes,
                    first_append_at: batch.first_append_at,
                    producer_state: batch.producer_state,
                });
            }
        }
        self.buffered_batch_identities.clear();
        self.buffered_bytes = 0;
        batches
    }

    /// Drain and complete every buffered batch for abort/force-close paths.
    pub(crate) fn discard_all(&mut self) -> Vec<ReadyBatch> {
        let batches = self.drain_all();
        let identities = batches.iter().map(|batch| batch.identity);
        let _completed = self.complete_batch_identities(identities);
        batches
    }

    /// Return drained batches to the accumulator without re-estimating record sizes.
    pub fn requeue_front(&mut self, batches: Vec<ReadyBatch>) -> Result<()> {
        self.validate_requeue_identities(&batches)?;
        let split_parents: Vec<_> = batches
            .iter()
            .filter_map(|batch| batch.identity.split_parent())
            .filter(|parent| self.incomplete_batch_identities.contains(parent))
            .collect();
        for batch in batches.into_iter().rev() {
            let identity = batch.identity;
            let pooled_buffer_bytes = batch.pooled_buffer_bytes;
            let key = TopicPartition {
                topic: batch.topic.into(),
                partition: batch.partition,
            };
            let entry = self
                .partitions
                .entry(key)
                .or_insert_with(|| PartitionQueue {
                    batches: VecDeque::new(),
                });
            let queued_batch = PartitionBatch {
                identity: batch.identity,
                records: batch.records,
                delivery: batch.delivery,
                producer_state: batch.producer_state,
                buffer_bytes: pooled_buffer_bytes,
                batch_bytes: batch.bytes,
                compression_sizing: CompressionSizing::NONE,
                sealed: true,
                first_append_at: batch.first_append_at,
            };
            insert_requeued_batch(&mut entry.batches, queued_batch);
            let _inserted = self.buffered_batch_identities.insert(identity);
            let _inserted = self.incomplete_batch_identities.insert(identity);
            self.buffered_bytes = self.buffered_bytes.saturating_add(pooled_buffer_bytes);
        }
        let _completed = self.complete_batch_identities(split_parents);
        Ok(())
    }

    pub(crate) fn complete_batch_identities<I>(&mut self, identities: I) -> usize
    where
        I: IntoIterator<Item = ReadyBatchIdentity>,
    {
        let mut completed = 0usize;
        for identity in identities {
            if self.incomplete_batch_identities.remove(&identity) {
                completed = completed.saturating_add(1);
            }
        }
        completed
    }

    #[cfg(test)]
    pub(crate) fn split_and_requeue_front(&mut self, batch: ReadyBatch) -> usize {
        let Some(split) = batch.split_for_retry_with_compression_ratio(self.config.batch_size, 1.0)
        else {
            return 0;
        };
        let count = split.len();
        self.requeue_front(split)
            .expect("split retry batches should have unique identities");
        count
    }

    fn validate_requeue_identities(&self, batches: &[ReadyBatch]) -> Result<()> {
        let mut seen = AHashSet::with_capacity(batches.len());
        for batch in batches {
            if self.buffered_batch_identities.contains(&batch.identity)
                || !seen.insert(batch.identity)
                || !self.can_requeue_identity(batch.identity)
            {
                return Err(ProducerError::BatchLifecycle(
                    "duplicate ready batch identity requeued",
                ));
            }
        }
        Ok(())
    }

    fn can_requeue_identity(&self, identity: ReadyBatchIdentity) -> bool {
        #[cfg(test)]
        if matches!(identity, ReadyBatchIdentity::Test(_)) {
            return true;
        }
        self.incomplete_batch_identities.contains(&identity)
            || identity
                .split_parent()
                .is_some_and(|parent| self.incomplete_batch_identities.contains(&parent))
    }
}

/// Thread-safe wrapper around [`RecordAccumulator`].
///
/// The inner accumulator keeps its single-threaded logic unchanged; this wrapper
/// guards it with a short `std::sync::Mutex` held only across synchronous
/// accumulator operations. That lets concurrent `send(&self)` appends use the
/// accumulator directly without going through the producer's async sender mutex
/// (which serialized every append). All accumulator methods are synchronous, so
/// the guard is never held across an `.await`.
#[derive(Debug)]
pub struct SharedAccumulator {
    inner: std::sync::Mutex<RecordAccumulator>,
}

impl SharedAccumulator {
    pub(crate) const fn new(accumulator: RecordAccumulator) -> Self {
        Self {
            inner: std::sync::Mutex::new(accumulator),
        }
    }

    /// Build a shared accumulator from a config.
    pub fn with_config(config: AccumulatorConfig) -> Self {
        Self::new(RecordAccumulator::new(config))
    }

    /// Append a record (delegates to the inner accumulator under the lock).
    pub fn append(&self, record: ProducerRecord) -> Result<()> {
        self.lock().append(record)
    }

    /// Append a record at a supplied timestamp.
    pub fn append_at(&self, record: ProducerRecord, now: Instant) -> Result<()> {
        self.lock().append_at(record, now)
    }

    /// Append a record and return its delivery future.
    pub fn append_for_delivery(&self, record: ProducerRecord) -> Result<SendFuture> {
        self.lock().append_for_delivery(record)
    }

    #[cfg(test)]
    pub(crate) fn append_with_status_at(
        &self,
        record: ProducerRecord,
        now: Instant,
    ) -> Result<AppendStatus> {
        self.lock().append_with_status_at(record, now)
    }

    /// Lock the accumulator for a short synchronous critical section. Never hold
    /// the returned guard across an `.await`.
    pub(crate) fn lock(&self) -> std::sync::MutexGuard<'_, RecordAccumulator> {
        self.inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    // --- Delegates: each acquires the short lock and forwards to the inner
    // accumulator, so callers keep their existing call sites (only the parameter
    // type changes from `&mut RecordAccumulator` to `&SharedAccumulator`). ---

    pub(crate) fn append_for_delivery_with_status_at_compression_ratio(
        &self,
        record: ProducerRecord,
        now: Instant,
        compression_ratio: f32,
    ) -> Result<(SendFuture, AppendStatus)> {
        self.lock()
            .append_for_delivery_with_status_at_compression_ratio(record, now, compression_ratio)
    }

    #[cfg(test)]
    pub(crate) fn append_with_status_at_compression_ratio(
        &self,
        record: ProducerRecord,
        now: Instant,
        compression_ratio: f32,
    ) -> Result<AppendStatus> {
        self.lock()
            .append_with_status_at_compression_ratio(record, now, compression_ratio)
    }

    pub(crate) fn buffer_memory(&self) -> usize {
        self.lock().buffer_memory()
    }

    pub(crate) fn partition_queue_load_with_availability<F>(
        &self,
        topic_metadata: &TopicMetadata,
        is_partition_available: F,
    ) -> Option<PartitionQueueLoad>
    where
        F: FnMut(&PartitionMetadata) -> bool,
    {
        self.lock()
            .partition_queue_load_with_availability(topic_metadata, is_partition_available)
    }

    pub(crate) fn buffered_batches(&self) -> usize {
        self.lock().buffered_batches()
    }

    /// Bytes currently buffered across all partitions.
    pub fn buffered_bytes(&self) -> usize {
        self.lock().buffered_bytes()
    }

    pub(crate) fn buffered_records(&self) -> usize {
        self.lock().buffered_records()
    }

    pub(crate) fn complete_batch_identities<I>(&self, identities: I) -> usize
    where
        I: IntoIterator<Item = ReadyBatchIdentity>,
    {
        self.lock().complete_batch_identities(identities)
    }

    pub(crate) fn discard_all(&self) -> Vec<ReadyBatch> {
        self.lock().discard_all()
    }

    pub(crate) fn drain_all(&self) -> Vec<ReadyBatch> {
        self.lock().drain_all()
    }

    /// Drain all batches that are ready to dispatch.
    pub fn drain_ready(&self, now: Instant) -> Vec<ReadyBatch> {
        self.lock().drain_ready(now)
    }

    /// Drain at most one ready front batch per partition (re-dispatch hot path).
    pub fn drain_front_ready(&self, now: Instant) -> Vec<ReadyBatch> {
        self.lock().drain_front_ready(now)
    }

    pub(crate) fn has_available_memory_for_reserved_with_compression_ratio(
        &self,
        record: &ProducerRecord,
        reserved_bytes: usize,
        compression_ratio: f32,
    ) -> bool {
        self.lock()
            .has_available_memory_for_reserved_with_compression_ratio(
                record,
                reserved_bytes,
                compression_ratio,
            )
    }

    pub(crate) fn next_ready_at(&self, now: Instant) -> Option<Instant> {
        self.lock().next_ready_at(now)
    }

    pub(crate) fn requeue_front(&self, batches: Vec<ReadyBatch>) -> Result<()> {
        self.lock().requeue_front(batches)
    }
}

fn split_producer_state(
    producer_state: Option<ProducerBatchState>,
    record_index: usize,
) -> Option<ProducerBatchState> {
    let mut state = producer_state?;
    let offset = i32::try_from(record_index).unwrap_or(i32::MAX);
    state.base_sequence = state.base_sequence.checked_add(offset).unwrap_or(i32::MAX);
    Some(state)
}

fn insert_requeued_batch(queue: &mut VecDeque<PartitionBatch>, batch: PartitionBatch) {
    let Some(producer_state) = batch.producer_state else {
        queue.push_front(batch);
        return;
    };
    let insert_at = queue
        .iter()
        .position(|existing| {
            existing.producer_state.is_none_or(|existing_state| {
                existing_state.base_sequence >= producer_state.base_sequence
            })
        })
        .unwrap_or(queue.len());
    queue.insert(insert_at, batch);
}

fn ready_batch_bytes(batch: &PartitionBatch) -> usize {
    estimated_batch_bytes_for_sizing(batch.batch_bytes, batch.compression_sizing)
}

fn batch_is_ready(
    batch: &PartitionBatch,
    now: Instant,
    batch_size: usize,
    linger: Duration,
) -> bool {
    batch.sealed
        || estimated_batch_bytes_for_sizing(batch.batch_bytes, batch.compression_sizing)
            >= batch_size
        || now.duration_since(batch.first_append_at) >= linger
}

fn batch_next_ready_at(
    batch: &PartitionBatch,
    now: Instant,
    batch_size: usize,
    linger: Duration,
) -> Instant {
    if batch.sealed
        || estimated_batch_bytes_for_sizing(batch.batch_bytes, batch.compression_sizing)
            >= batch_size
    {
        return now;
    }
    let Some(deadline) = batch.first_append_at.checked_add(linger) else {
        return now;
    };
    if deadline <= now { now } else { deadline }
}

pub(crate) fn estimate_record_bytes(record: &ProducerRecord) -> usize {
    let key_bytes = record.key.as_ref().map_or(0, bytes::Bytes::len);
    let value_bytes = record.value.as_ref().map_or(0, bytes::Bytes::len);
    let header_bytes = estimate_headers_bytes(record);
    ESTIMATED_RECORD_OVERHEAD_BYTES
        .checked_add(record.topic.len())
        .and_then(|bytes| bytes.checked_add(key_bytes))
        .and_then(|bytes| bytes.checked_add(value_bytes))
        .and_then(|bytes| bytes.checked_add(header_bytes))
        .unwrap_or(usize::MAX)
}

pub(crate) fn estimate_record_batch_bytes(record: &ProducerRecord) -> usize {
    estimate_first_record_batch_bytes(record)
}

const fn append_status(
    sealed_previous_records: usize,
    current_batch_ready: bool,
    current_batch_records: usize,
    starts_new_batch: bool,
) -> AppendStatus {
    let ready_batch_records = if sealed_previous_records > 0 {
        sealed_previous_records
    } else if current_batch_ready {
        current_batch_records
    } else {
        0
    };
    AppendStatus {
        batch_ready: ready_batch_records > 0,
        ready_batch_records,
        starts_new_batch,
    }
}

fn record_with_append_timestamp(mut record: ProducerRecord) -> ProducerRecord {
    if record.timestamp_ms.is_none() {
        record.timestamp_ms = Some(current_time_ms());
    }
    record
}

fn planned_append_target(
    queue: Option<&PartitionQueue>,
    record: &ProducerRecord,
    batch_size: usize,
    compression_sizing: CompressionSizing,
) -> AppendTarget {
    queue.and_then(|queue| queue.batches.back()).map_or_else(
        || new_batch_append_target(0, record, batch_size),
        |batch| {
            if batch.sealed {
                return new_batch_append_target(batch.records.len(), record, batch_size);
            }
            let next_record_bytes = estimate_next_record_batch_bytes(&batch.records, record);
            let estimated_current_batch_bytes =
                estimated_batch_bytes_for_sizing(batch.batch_bytes, compression_sizing);
            let cannot_fit = !batch.records.is_empty()
                && estimated_current_batch_bytes.saturating_add(next_record_bytes) > batch_size;
            if cannot_fit {
                new_batch_append_target(batch.records.len(), record, batch_size)
            } else {
                AppendTarget {
                    sealed_previous_records: 0,
                    record_batch_bytes: next_record_bytes,
                    starts_new_batch: false,
                    reserved_buffer_bytes: 0,
                }
            }
        },
    )
}

#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    reason = "Kafka compression ratio estimates are f32 and only influence conservative sizing."
)]
fn estimated_batch_bytes_for_sizing(
    uncompressed_batch_bytes: usize,
    compression_sizing: CompressionSizing,
) -> usize {
    if !compression_sizing.uses_estimate()
        || uncompressed_batch_bytes <= RECORD_BATCH_OVERHEAD_BYTES
    {
        return uncompressed_batch_bytes;
    }
    let uncompressed_records_bytes =
        uncompressed_batch_bytes.saturating_sub(RECORD_BATCH_OVERHEAD_BYTES);
    RECORD_BATCH_OVERHEAD_BYTES.saturating_add(
        ((uncompressed_records_bytes as f32)
            * compression_sizing.ratio
            * COMPRESSION_RATE_ESTIMATION_FACTOR)
            .ceil() as usize,
    )
}

fn new_batch_append_target(
    sealed_previous_records: usize,
    record: &ProducerRecord,
    batch_size: usize,
) -> AppendTarget {
    let record_batch_bytes = estimate_first_record_batch_bytes(record);
    AppendTarget {
        sealed_previous_records,
        record_batch_bytes,
        starts_new_batch: true,
        reserved_buffer_bytes: batch_buffer_reservation(batch_size, record_batch_bytes),
    }
}

fn apply_append_target(
    queue: &mut PartitionQueue,
    now: Instant,
    batch_size: usize,
    target: AppendTarget,
    next_identity: &mut u64,
) -> Option<ReadyBatchIdentity> {
    if !target.starts_new_batch {
        return None;
    }
    if target.sealed_previous_records > 0
        && let Some(batch) = queue.batches.back_mut()
    {
        batch.sealed = true;
    }
    let identity = allocate_ready_batch_identity(next_identity);
    queue.batches.push_back(new_partition_batch(
        identity,
        now,
        batch_size,
        target.record_batch_bytes,
        target.reserved_buffer_bytes,
    ));
    Some(identity)
}

const fn batch_buffer_reservation(batch_size: usize, first_record_bytes: usize) -> usize {
    if first_record_bytes > batch_size {
        first_record_bytes
    } else {
        batch_size
    }
}

fn new_partition_batch(
    identity: ReadyBatchIdentity,
    now: Instant,
    batch_size: usize,
    first_record_bytes: usize,
    buffer_bytes: usize,
) -> PartitionBatch {
    PartitionBatch {
        identity,
        records: Vec::with_capacity(estimated_batch_record_capacity(
            batch_size,
            first_record_bytes,
        )),
        delivery: None,
        producer_state: None,
        buffer_bytes,
        batch_bytes: RECORD_BATCH_OVERHEAD_BYTES,
        compression_sizing: CompressionSizing::NONE,
        sealed: false,
        first_append_at: now,
    }
}

const fn allocate_ready_batch_identity(next_identity: &mut u64) -> ReadyBatchIdentity {
    let identity = ReadyBatchIdentity::Accumulator(*next_identity);
    *next_identity = next_identity.saturating_add(1);
    identity
}

fn estimated_batch_record_capacity(batch_size: usize, first_record_bytes: usize) -> usize {
    const MAX_PREALLOCATED_RECORDS: usize = 4096;

    let record_bytes = first_record_bytes.max(1);
    let payload_budget = batch_size
        .saturating_sub(RECORD_BATCH_OVERHEAD_BYTES)
        .max(record_bytes);
    payload_budget
        .checked_div(record_bytes)
        .unwrap_or(1)
        .clamp(1, MAX_PREALLOCATED_RECORDS)
}
fn split_records_by_batch_target(
    records: Vec<ProducerRecord>,
    target_batch_bytes: usize,
    compression_ratio: f32,
) -> Vec<SplitRecordGroup> {
    let target_batch_bytes = target_batch_bytes.max(1);
    let compression_ratio = compression_ratio.max(1.0);
    let mut groups = Vec::new();
    let mut current = SplitRecordGroup {
        first_record_index: 0,
        records: Vec::new(),
        bytes: 0,
    };
    let mut current_batch_bytes = RECORD_BATCH_OVERHEAD_BYTES;

    for (record_index, record) in records.into_iter().enumerate() {
        let record_batch_bytes = estimate_next_record_batch_bytes(&current.records, &record);
        let adjusted_record_batch_bytes =
            apply_compression_ratio_estimate(record_batch_bytes, compression_ratio);
        if !current.records.is_empty()
            && current_batch_bytes.saturating_add(adjusted_record_batch_bytes) > target_batch_bytes
        {
            groups.push(current);
            current = SplitRecordGroup {
                first_record_index: record_index,
                records: Vec::new(),
                bytes: 0,
            };
            current_batch_bytes = RECORD_BATCH_OVERHEAD_BYTES;
        }

        let record_batch_bytes = estimate_next_record_batch_bytes(&current.records, &record);
        let adjusted_record_batch_bytes =
            apply_compression_ratio_estimate(record_batch_bytes, compression_ratio);
        current_batch_bytes = current_batch_bytes.saturating_add(adjusted_record_batch_bytes);
        current.bytes = current.bytes.saturating_add(estimate_record_bytes(&record));
        current.records.push(record);
    }

    if !current.records.is_empty() {
        groups.push(current);
    }
    groups
}

#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    reason = "Kafka compression ratio estimates are f32; split grouping only needs conservative \
              byte estimates."
)]
fn apply_compression_ratio_estimate(bytes: usize, compression_ratio: f32) -> usize {
    ((bytes as f32) * compression_ratio).ceil() as usize
}

#[cfg(test)]
fn estimate_ready_batch_encoded_bytes(records: &[ProducerRecord]) -> usize {
    let first_timestamp_ms = records.first().and_then(|record| record.timestamp_ms);
    records
        .iter()
        .enumerate()
        .fold(RECORD_BATCH_OVERHEAD_BYTES, |bytes, (offset, record)| {
            bytes.saturating_add(estimate_record_batch_bytes_at_offset(
                record,
                offset,
                first_timestamp_ms,
            ))
        })
}

fn estimate_first_record_batch_bytes(record: &ProducerRecord) -> usize {
    estimate_record_batch_bytes_at_offset(record, 0, record.timestamp_ms)
}

fn estimate_next_record_batch_bytes(
    current_records: &[ProducerRecord],
    record: &ProducerRecord,
) -> usize {
    let first_timestamp_ms = current_records
        .first()
        .and_then(|record| record.timestamp_ms)
        .or(record.timestamp_ms);
    estimate_record_batch_bytes_at_offset(record, current_records.len(), first_timestamp_ms)
}

fn estimate_record_batch_bytes_at_offset(
    record: &ProducerRecord,
    offset_delta: usize,
    first_timestamp_ms: Option<i64>,
) -> usize {
    let key_bytes = record.key.as_ref().map_or(0, bytes::Bytes::len);
    let value_bytes = record.value.as_ref().map_or(0, bytes::Bytes::len);
    let offset_delta = i32::try_from(offset_delta).unwrap_or(i32::MAX);
    let timestamp_delta = record.timestamp_ms.map_or(0, |timestamp| {
        first_timestamp_ms.map_or(timestamp, |first_timestamp| {
            timestamp.saturating_sub(first_timestamp)
        })
    });
    let header_count = i32::try_from(record.headers.len()).unwrap_or(i32::MAX);
    let body_len = 1usize
        .saturating_add(signed_varlong_len(timestamp_delta))
        .saturating_add(signed_varint_len(offset_delta))
        .saturating_add(nullable_record_bytes_len(key_bytes, record.key.is_some()))
        .saturating_add(nullable_record_bytes_len(
            value_bytes,
            record.value.is_some(),
        ))
        .saturating_add(signed_varint_len(header_count))
        .saturating_add(estimate_headers_bytes(record));
    let body_len = i32::try_from(body_len).unwrap_or(i32::MAX);
    signed_varint_len(body_len).saturating_add(usize::try_from(body_len).unwrap_or(usize::MAX))
}

fn estimate_headers_bytes(record: &ProducerRecord) -> usize {
    if record.headers.is_empty() {
        return 0;
    }
    record.headers.iter().fold(0usize, |bytes, header| {
        bytes
            .saturating_add(record_bytes_len(header.key.len()))
            .saturating_add(nullable_record_bytes_len(
                header.value.as_ref().map_or(0, bytes::Bytes::len),
                header.value.is_some(),
            ))
    })
}

fn record_bytes_len(bytes: usize) -> usize {
    let len = i32::try_from(bytes).unwrap_or(i32::MAX);
    signed_varint_len(len).saturating_add(bytes)
}

fn nullable_record_bytes_len(bytes: usize, is_some: bool) -> usize {
    if is_some {
        record_bytes_len(bytes)
    } else {
        signed_varint_len(-1)
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::expect_used,
        clippy::missing_assert_message,
        clippy::unwrap_used,
        reason = "Unit test fixtures fail fastest with contextual unwrap/expect calls."
    )]

    use std::time::{Duration, Instant};

    use bytes::Bytes;

    use super::{
        AccumulatorConfig, CompressionSizing, ProducerError, RECORD_BATCH_OVERHEAD_BYTES,
        ReadyBatch, ReadyBatchIdentity, RecordAccumulator, estimate_ready_batch_encoded_bytes,
        estimate_record_batch_bytes, estimated_batch_bytes_for_sizing,
    };
    use crate::producer::{
        ProducerCompression, ProducerIdentity, ProducerRecord, transaction::ProducerBatchState,
    };

    const TEST_LARGE_BATCH_SIZE: usize = 16 * 1024;
    const TEST_PRODUCER_IDENTITY: ProducerIdentity = ProducerIdentity {
        producer_id: 42,
        producer_epoch: 3,
    };

    fn ready_batch_for_requeue(
        topic: &'static str,
        partition: i32,
        value: &'static [u8],
        identity: u64,
        now: Instant,
    ) -> ReadyBatch {
        let record = ProducerRecord::new(topic, partition).value(Bytes::from_static(value));
        let bytes = estimate_ready_batch_encoded_bytes(std::slice::from_ref(&record));
        ReadyBatch {
            identity: ReadyBatchIdentity::test(identity),
            topic: topic.to_owned(),
            partition,
            records: vec![record],
            delivery: None,
            bytes,
            pooled_buffer_bytes: 128,
            first_append_at: now,
            producer_state: None,
        }
    }

    trait ReadyBatchTestExt {
        fn with_producer_base_sequence(self, base_sequence: i32) -> ReadyBatch;
    }

    impl ReadyBatchTestExt for ReadyBatch {
        fn with_producer_base_sequence(mut self, base_sequence: i32) -> ReadyBatch {
            self.producer_state = Some(ProducerBatchState {
                identity: TEST_PRODUCER_IDENTITY,
                base_sequence,
            });
            self
        }
    }

    #[test]
    fn config_builder_clamps_zero_batch_size() {
        let config = AccumulatorConfig::default()
            .batch_size(0)
            .linger(Duration::from_millis(2))
            .buffer_memory(128);

        assert_eq!(config.batch_size, 1);
        assert_eq!(config.linger, Duration::from_millis(2));
        assert_eq!(config.buffer_memory, 128);
    }

    #[test]
    fn append_for_delivery_rejects_when_buffer_memory_is_full() {
        let mut accumulator = RecordAccumulator::new(AccumulatorConfig::default().buffer_memory(1));

        let error = accumulator
            .append_for_delivery(ProducerRecord::new("orders", 0).value(Bytes::from_static(b"v")))
            .expect_err("small buffer should apply backpressure");

        assert!(matches!(error, ProducerError::Backpressure));
    }

    #[test]
    fn append_reserves_one_batch_buffer_per_topic_partition_like_java() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(128)
                .linger(Duration::from_secs(1))
                .buffer_memory(128),
        );

        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                now,
            )
            .expect("first record reserves the batch buffer");
        assert_eq!(accumulator.buffered_bytes(), 128);

        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"b")),
                now,
            )
            .expect("same open batch should not reserve another buffer");
        assert_eq!(accumulator.buffered_bytes(), 128);

        let error = accumulator
            .append_at(
                ProducerRecord::new("orders", 1).value(Bytes::from_static(b"c")),
                now,
            )
            .expect_err("different partition needs another batch buffer");
        assert!(matches!(error, ProducerError::Backpressure));

        let drained = accumulator.drain_all();
        assert_eq!(drained.len(), 1);
        assert_eq!(drained[0].pooled_buffer_bytes(), 128);
        assert_eq!(
            drained[0].bytes,
            estimate_ready_batch_encoded_bytes(&drained[0].records)
        );
        assert_eq!(accumulator.buffered_bytes(), 0);
    }

    #[test]
    fn drain_reports_encoded_batch_bytes_separately_from_pooled_buffer() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(256)
                .linger(Duration::from_secs(1))
                .buffer_memory(256),
        );
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0)
                    .try_timestamp_ms(1_000)
                    .expect("timestamp")
                    .header("trace-id", Bytes::from_static(b"abc"))
                    .value(Bytes::from_static(b"value")),
                now,
            )
            .expect("first record reserves the batch buffer");

        let drained = accumulator.drain_all();
        let encoded_bytes = estimate_ready_batch_encoded_bytes(&drained[0].records);

        assert_eq!(drained.len(), 1);
        assert_eq!(drained[0].bytes, encoded_bytes);
        assert_eq!(drained[0].pooled_buffer_bytes(), 256);
        assert_ne!(drained[0].bytes, drained[0].pooled_buffer_bytes());
    }

    #[test]
    fn append_with_compression_ratio_uses_memory_records_has_room_estimate() {
        let now = Instant::now();
        let record = ProducerRecord::new("orders", 0).value(Bytes::from(vec![b'x'; 128]));
        let record_bytes = estimate_record_batch_bytes(&record);
        let batch_size = RECORD_BATCH_OVERHEAD_BYTES
            .saturating_add(record_bytes)
            .saturating_add(record_bytes * 3 / 4);

        let mut raw = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(batch_size)
                .buffer_memory(batch_size * 4)
                .linger(Duration::from_secs(1)),
        );
        let _first_raw = raw
            .append_with_status_at_compression_ratio(record.clone(), now, 1.0)
            .expect("append first raw record");
        let raw_status = raw
            .append_with_status_at_compression_ratio(record.clone(), now, 1.0)
            .expect("append second raw record");

        let mut compressed = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(batch_size)
                .buffer_memory(batch_size * 4)
                .linger(Duration::from_secs(1)),
        );
        let _first_compressed = compressed
            .append_with_status_at_compression_ratio(record.clone(), now, 0.50)
            .expect("append first compressed record");
        let compressed_status = compressed
            .append_with_status_at_compression_ratio(record, now, 0.50)
            .expect("append second compressed record");

        assert!(raw_status.starts_new_batch);
        assert_eq!(raw.buffered_batches(), 2);
        assert!(!compressed_status.starts_new_batch);
        assert_eq!(compressed.buffered_batches(), 1);
    }

    #[test]
    fn drain_ready_uses_compression_ratio_has_room_estimate() {
        let now = Instant::now();
        let record = ProducerRecord::new("orders", 0).value(Bytes::from(vec![b'x'; 128]));
        let record_bytes = estimate_record_batch_bytes(&record);
        let batch_size = RECORD_BATCH_OVERHEAD_BYTES
            .saturating_add(record_bytes)
            .saturating_add(record_bytes * 3 / 4);
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(batch_size)
                .buffer_memory(batch_size * 4)
                .linger(Duration::from_secs(1)),
        );

        let _first_status = accumulator
            .append_with_status_at_compression_ratio(record.clone(), now, 0.50)
            .expect("append first compressed record");
        let status = accumulator
            .append_with_status_at_compression_ratio(record, now, 0.50)
            .expect("append second compressed record");
        let ready = accumulator.drain_ready(now);

        assert!(!status.batch_ready);
        assert!(ready.is_empty());
        assert_eq!(accumulator.buffered_batches(), 1);
    }

    #[test]
    fn drain_reports_ratio_aware_estimated_batch_bytes_like_java() {
        let now = Instant::now();
        let record = ProducerRecord::new("orders", 0).value(Bytes::from(vec![b'x'; 128]));
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(1024)
                .buffer_memory(4096)
                .linger(Duration::from_secs(1)),
        );

        let _first_status = accumulator
            .append_with_status_at_compression_ratio(record.clone(), now, 0.50)
            .expect("append first compressed record");
        let _second_status = accumulator
            .append_with_status_at_compression_ratio(record, now, 0.50)
            .expect("append second compressed record");
        let drained = accumulator.drain_all();
        let raw_bytes = estimate_ready_batch_encoded_bytes(&drained[0].records);
        let estimated_bytes =
            estimated_batch_bytes_for_sizing(raw_bytes, CompressionSizing::new(0.50));

        assert_eq!(drained.len(), 1);
        assert_eq!(drained[0].bytes, estimated_bytes);
        assert_ne!(drained[0].bytes, raw_bytes);
    }

    #[test]
    fn requeue_front_preserves_ratio_aware_estimated_batch_bytes_like_java() {
        let now = Instant::now();
        let record = ProducerRecord::new("orders", 0).value(Bytes::from(vec![b'x'; 128]));
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(1024)
                .buffer_memory(4096)
                .linger(Duration::from_secs(1)),
        );

        let _first_status = accumulator
            .append_with_status_at_compression_ratio(record.clone(), now, 0.50)
            .expect("append first compressed record");
        let _second_status = accumulator
            .append_with_status_at_compression_ratio(record, now, 0.50)
            .expect("append second compressed record");
        let drained = accumulator.drain_all();
        let expected_bytes = drained[0].bytes;

        accumulator
            .requeue_front(drained)
            .expect("requeue should preserve batch accounting");
        let requeued = accumulator.drain_all();
        let raw_bytes = estimate_ready_batch_encoded_bytes(&requeued[0].records);

        assert_eq!(requeued.len(), 1);
        assert_eq!(requeued[0].bytes, expected_bytes);
        assert_ne!(requeued[0].bytes, raw_bytes);
    }

    #[test]
    fn requeue_front_prepends_records_and_preserves_earliest_linger_time() {
        let now = Instant::now();
        let later = now.checked_add(Duration::from_millis(5)).unwrap_or(now);
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                later,
            )
            .expect("append later record");
        let existing = accumulator.drain_all();
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"b")),
                later,
            )
            .expect("append existing record");

        accumulator
            .requeue_front(existing)
            .expect("requeue should preserve existing batch identity");
        let batches = accumulator.drain_all();
        let values: Vec<_> = batches
            .iter()
            .flat_map(|batch| batch.records.iter())
            .filter_map(|record| record.value.as_ref())
            .cloned()
            .collect();

        assert_eq!(values, [Bytes::from_static(b"a"), Bytes::from_static(b"b")]);
    }

    #[test]
    fn append_after_requeue_starts_new_batch_instead_of_mutating_retry_batch() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                now,
            )
            .expect("append retry candidate");
        let retry = accumulator.drain_all();
        accumulator
            .requeue_front(retry)
            .expect("requeue should preserve retry batch identity");

        let status = accumulator
            .append_with_status_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"b")),
                now,
            )
            .expect("append new record after retry batch");
        let batches = accumulator.drain_all();
        let values: Vec<_> = batches
            .iter()
            .map(|batch| {
                batch
                    .records
                    .iter()
                    .filter_map(|record| record.value.as_ref())
                    .cloned()
                    .collect::<Vec<_>>()
            })
            .collect();

        assert!(status.starts_new_batch);
        assert_eq!(batches.len(), 2);
        assert_eq!(
            values,
            [
                vec![Bytes::from_static(b"a")],
                vec![Bytes::from_static(b"b")]
            ]
        );
    }

    #[test]
    fn requeue_front_preserves_multiple_batch_order_for_same_partition() {
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(1)
                .linger(Duration::from_secs(1)),
        );
        accumulator
            .append(ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")))
            .expect("append first record");
        accumulator
            .append(ProducerRecord::new("orders", 0).value(Bytes::from_static(b"b")))
            .expect("append second record");
        let drained = accumulator.drain_all();

        accumulator
            .requeue_front(drained)
            .expect("requeue should preserve distinct batch identities");
        let batches = accumulator.drain_all();
        let values: Vec<_> = batches
            .iter()
            .filter_map(|batch| batch.records.first())
            .filter_map(|record| record.value.as_ref())
            .cloned()
            .collect();

        assert_eq!(values, [Bytes::from_static(b"a"), Bytes::from_static(b"b")]);
    }

    #[test]
    fn requeue_front_inserts_idempotent_batches_by_sequence_like_java() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(1)
                .buffer_memory(TEST_LARGE_BATCH_SIZE),
        );
        let later =
            ready_batch_for_requeue("orders", 0, b"b", 2, now).with_producer_base_sequence(1);
        let earlier =
            ready_batch_for_requeue("orders", 0, b"a", 1, now).with_producer_base_sequence(0);

        accumulator
            .requeue_front(vec![later, earlier])
            .expect("requeue should accept distinct idempotent batches");
        let batches = accumulator.drain_all();
        let sequences: Vec<_> = batches
            .iter()
            .filter_map(|batch| batch.producer_state.map(|state| state.base_sequence))
            .collect();

        assert_eq!(sequences, [0, 1]);
    }

    #[test]
    fn requeue_front_rejects_duplicate_batch_identity_without_double_counting() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                now,
            )
            .expect("append record");
        let batch = accumulator.drain_all().pop().expect("drained batch");
        let duplicate = ReadyBatch {
            identity: batch.identity,
            topic: batch.topic.clone(),
            partition: batch.partition,
            records: vec![ProducerRecord::new("orders", 0).value(Bytes::from_static(b"b"))],
            delivery: None,
            bytes: batch.bytes,
            pooled_buffer_bytes: batch.pooled_buffer_bytes,
            first_append_at: batch.first_append_at,
            producer_state: None,
        };

        accumulator
            .requeue_front(vec![batch])
            .expect("first requeue should succeed");
        let buffered_bytes = accumulator.buffered_bytes();
        let error = accumulator
            .requeue_front(vec![duplicate])
            .expect_err("duplicate identity should fail like incomplete-batch invariant");

        assert!(matches!(error, ProducerError::BatchLifecycle(_)));
        assert_eq!(accumulator.buffered_bytes(), buffered_bytes);
        assert_eq!(accumulator.buffered_batches(), 1);
    }

    #[test]
    fn requeue_front_rejects_completed_batch_identity_without_double_counting() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                now,
            )
            .expect("append record");
        let batch = accumulator.drain_all().pop().expect("drained batch");
        let identity = batch.identity;
        assert_eq!(accumulator.complete_batch_identities([identity]), 1);
        let buffered_bytes = accumulator.buffered_bytes();
        let error = accumulator
            .requeue_front(vec![batch])
            .expect_err("completed batch identity should not be requeued");

        assert!(matches!(error, ProducerError::BatchLifecycle(_)));
        assert_eq!(accumulator.buffered_bytes(), buffered_bytes);
        assert_eq!(accumulator.buffered_batches(), 0);
    }

    #[test]
    fn complete_batch_identities_reports_actual_completed_count() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                now,
            )
            .expect("append record");
        let batch = accumulator.drain_all().pop().expect("drained batch");
        let identity = batch.identity;

        let completed = accumulator.complete_batch_identities([identity]);
        let duplicate_completed = accumulator.complete_batch_identities([identity]);
        let stale_completed = accumulator.complete_batch_identities([ReadyBatchIdentity::test(99)]);

        assert_eq!(completed, 1);
        assert_eq!(duplicate_completed, 0);
        assert_eq!(stale_completed, 0);
    }

    #[test]
    fn discard_all_completes_batch_identities_without_double_counting() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                now,
            )
            .expect("append record");

        let batch = accumulator.discard_all().pop().expect("discarded batch");
        let buffered_bytes = accumulator.buffered_bytes();
        let error = accumulator
            .requeue_front(vec![batch])
            .expect_err("discarded batch identity should be completed");

        assert!(matches!(error, ProducerError::BatchLifecycle(_)));
        assert_eq!(accumulator.buffered_bytes(), buffered_bytes);
        assert_eq!(accumulator.buffered_batches(), 0);
    }

    #[test]
    fn split_and_requeue_front_rebuilds_multi_record_batch_for_retry() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                now,
            )
            .expect("append first record");
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"b")),
                now,
            )
            .expect("append second record");
        let batch = accumulator
            .drain_all()
            .pop()
            .expect("drained oversized batch");

        let split_count = accumulator.split_and_requeue_front(batch);
        let split = accumulator.drain_all();
        let values: Vec<_> = split
            .iter()
            .flat_map(|batch| batch.records.iter())
            .filter_map(|record| record.value.as_ref())
            .cloned()
            .collect();

        assert_eq!(split_count, 1);
        assert_eq!(split.len(), 1);
        assert_eq!(split[0].records.len(), 2);
        assert_eq!(values, [Bytes::from_static(b"a"), Bytes::from_static(b"b")]);
    }

    #[test]
    fn split_and_requeue_front_deallocates_parent_pooled_buffer_like_java() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        for value in [b"a".as_slice(), b"bb".as_slice(), b"ccc".as_slice()] {
            accumulator
                .append_at(
                    ProducerRecord::new("orders", 0).value(Bytes::copy_from_slice(value)),
                    now,
                )
                .expect("append record");
        }
        let batch = accumulator
            .drain_all()
            .pop()
            .expect("drained oversized batch");

        let split_count = accumulator.split_and_requeue_front(batch);

        assert_eq!(split_count, 1);
        assert_eq!(accumulator.buffered_bytes(), 0);
        assert_eq!(accumulator.buffered_batches(), 1);
    }

    #[test]
    fn ready_batch_encoded_byte_estimate_matches_encoder_for_timestamped_records() {
        let records = vec![
            ProducerRecord::new("orders", 0)
                .try_timestamp_ms(1_000)
                .expect("first timestamp")
                .header("trace-id", Bytes::from_static(b"abc"))
                .value(Bytes::from_static(b"first")),
            ProducerRecord::new("orders", 0)
                .try_timestamp_ms(1_025)
                .expect("second timestamp")
                .header_null("null-header")
                .value(Bytes::from_static(b"second")),
        ];

        let estimated = estimate_ready_batch_encoded_bytes(&records);
        let encoded = super::super::batch::encode_record_batch_with_producer_state_at_offset(
            &records,
            ProducerCompression::default(),
            None,
            0,
        )
        .expect("batch should encode");

        assert_eq!(estimated, encoded.len());
    }

    #[test]
    fn ready_batch_split_for_retry_groups_records_by_target_batch_size() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        for value in [b"a".as_slice(), b"b".as_slice(), b"c".as_slice()] {
            accumulator
                .append_at(
                    ProducerRecord::new("orders", 0).value(Bytes::copy_from_slice(value)),
                    now,
                )
                .expect("append record");
        }
        let batch = accumulator
            .drain_all()
            .pop()
            .expect("drained oversized batch");

        let split = batch
            .split_for_retry_with_compression_ratio(78, 1.0)
            .expect("multi-record batch should split for retry");

        assert_eq!(split.len(), 2);
        assert_eq!(split[0].records.len(), 2);
        assert_eq!(split[1].records.len(), 1);
    }

    #[test]
    fn ready_batch_split_for_retry_applies_compression_ratio_to_target() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        for value in [b"a".as_slice(), b"b".as_slice(), b"c".as_slice()] {
            accumulator
                .append_at(
                    ProducerRecord::new("orders", 0).value(Bytes::copy_from_slice(value)),
                    now,
                )
                .expect("append record");
        }
        let batch = accumulator
            .drain_all()
            .pop()
            .expect("drained oversized batch");

        let split = batch
            .split_for_retry_with_compression_ratio(78, 2.0)
            .expect("multi-record batch should split for retry");

        assert_eq!(split.len(), 3);
        assert!(split.iter().all(|batch| batch.records.len() == 1));
    }

    #[test]
    fn ready_batch_split_for_retry_assigns_distinct_child_identities() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_secs(1)),
        );
        for value in [b"a".as_slice(), b"b".as_slice(), b"c".as_slice()] {
            accumulator
                .append_at(
                    ProducerRecord::new("orders", 0).value(Bytes::copy_from_slice(value)),
                    now,
                )
                .expect("append record");
        }
        let batch = accumulator
            .drain_all()
            .pop()
            .expect("drained oversized batch");
        let parent_identity = batch.identity();

        let split = batch
            .split_for_retry_with_compression_ratio(78, 2.0)
            .expect("multi-record batch should split for retry");

        assert_eq!(split.len(), 3);
        assert!(
            split
                .iter()
                .all(|batch| batch.identity() != parent_identity)
        );
        assert_ne!(split[0].identity(), split[1].identity());
        assert_ne!(split[1].identity(), split[2].identity());
    }

    #[test]
    fn append_status_reports_when_next_record_seals_ready_batch() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(128)
                .linger(Duration::from_secs(1)),
        );
        for _ in 0..8 {
            let status = accumulator
                .append_with_status_at(
                    ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                    now,
                )
                .expect("append record");
            assert!(!status.batch_ready);
        }

        let status = accumulator
            .append_with_status_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                now,
            )
            .expect("append record");

        assert!(status.batch_ready);
    }

    #[test]
    fn append_status_reports_new_batch_for_linger_wakeup_policy() {
        let now = Instant::now();
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(128)
                .linger(Duration::from_secs(1)),
        );

        let first = accumulator
            .append_with_status_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                now,
            )
            .expect("append first record");
        let second = accumulator
            .append_with_status_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"b")),
                now,
            )
            .expect("append second record");

        assert!(first.starts_new_batch);
        assert!(!second.starts_new_batch);
    }

    #[test]
    fn next_ready_at_reports_earliest_linger_deadline() {
        let base = Instant::now();
        let later_append = base
            .checked_add(Duration::from_millis(5))
            .expect("later append instant");
        let first_deadline = base
            .checked_add(Duration::from_millis(10))
            .expect("first linger deadline");
        let before_deadline = base
            .checked_add(Duration::from_millis(6))
            .expect("before linger deadline");
        let after_deadline = base
            .checked_add(Duration::from_millis(11))
            .expect("after linger deadline");
        let mut accumulator = RecordAccumulator::new(
            AccumulatorConfig::default()
                .batch_size(TEST_LARGE_BATCH_SIZE)
                .buffer_memory(TEST_LARGE_BATCH_SIZE * 4)
                .linger(Duration::from_millis(10)),
        );
        accumulator
            .append_at(
                ProducerRecord::new("orders", 0).value(Bytes::from_static(b"a")),
                base,
            )
            .expect("append first partition");
        accumulator
            .append_at(
                ProducerRecord::new("orders", 1).value(Bytes::from_static(b"b")),
                later_append,
            )
            .expect("append second partition");

        assert_eq!(
            accumulator.next_ready_at(before_deadline),
            Some(first_deadline)
        );
        assert_eq!(
            accumulator.next_ready_at(after_deadline),
            Some(after_deadline)
        );
    }
}