nntp-proxy 0.5.1

NNTP proxy server with per-command backend multiplexing, caching, metrics, and TUI dashboard
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
use crate::types::BufferSize;
use bytes::{BufMut, Bytes, BytesMut};
use crossbeam::queue::ArrayQueue;
use smallvec::SmallVec;
use std::future::poll_fn;
use std::ops::{Deref, Range};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::time::Instant;
use tokio::io::{AsyncRead, AsyncWriteExt, ReadBuf};
use tracing::{debug, info, warn};

/// A pooled buffer that automatically returns to the pool when dropped
///
/// # Safety and Initialized Bytes
///
/// The backing allocation is kept logically empty until bytes are read or copied
/// into it. `BytesMut::len()` is the initialized length, and immutable access
/// only exposes that initialized portion.
///
/// ## Usage
/// ```ignore
/// let mut buffer = pool.acquire();
/// let n = buffer.read_from(&mut stream).await?;  // Automatic tracking
/// process(&*buffer);  // Deref returns only &buffer[..n]
/// ```
pub struct PooledBuffer {
    buffer: BytesMut,
    pool: Arc<ArrayQueue<BytesMut>>,
    pool_size: Arc<AtomicUsize>,
    allocated_count: Arc<AtomicUsize>,
    max_pool_size: usize,
    expected_capacity: usize,
    writable_len: usize,
    acquired_at: Instant,
    source: PooledBufferSource,
    counts_toward_pool: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PooledBufferKind {
    Regular,
    Capture,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PooledBufferSource {
    kind: PooledBufferKind,
    fallback: bool,
}

impl PooledBufferSource {
    const fn regular(fallback: bool) -> Self {
        Self {
            kind: PooledBufferKind::Regular,
            fallback,
        }
    }

    const fn capture(fallback: bool) -> Self {
        Self {
            kind: PooledBufferKind::Capture,
            fallback,
        }
    }
}

impl std::fmt::Debug for PooledBuffer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PooledBuffer")
            .field("initialized", &self.buffer.len())
            .field("capacity", &self.buffer.capacity())
            .finish_non_exhaustive()
    }
}

impl PooledBuffer {
    /// Get the backing allocation capacity of the buffer.
    #[must_use]
    #[inline]
    pub fn capacity(&self) -> usize {
        self.buffer.capacity()
    }

    /// Get the number of initialized bytes
    #[must_use]
    #[inline]
    pub fn initialized(&self) -> usize {
        self.buffer.len()
    }

    #[inline]
    fn read_limit(&self) -> usize {
        if self.writable_len == 0 {
            self.buffer.capacity()
        } else {
            self.writable_len
        }
    }

    /// Read from an `AsyncRead` source, automatically tracking initialized bytes
    ///
    /// # Errors
    /// Returns any read error produced by the underlying async reader.
    pub async fn read_from<R>(&mut self, reader: &mut R) -> std::io::Result<usize>
    where
        R: AsyncRead + Unpin,
    {
        self.buffer.clear();
        self.read_into_spare(reader, self.read_limit()).await
    }

    /// Read more data at the current initialized offset, accumulating bytes.
    ///
    /// Unlike `read_from` which resets the buffer, this appends to existing data.
    /// Used when a higher-level reader needs more bytes in the same allocation.
    ///
    /// Returns the number of NEW bytes read (not total).
    ///
    /// # Errors
    /// Returns any read error produced by the underlying async reader.
    pub async fn read_more<R>(&mut self, reader: &mut R) -> std::io::Result<usize>
    where
        R: AsyncRead + Unpin,
    {
        let limit = self.read_limit().saturating_sub(self.buffer.len());
        self.read_into_spare(reader, limit).await
    }

    async fn read_into_spare<R>(&mut self, reader: &mut R, limit: usize) -> std::io::Result<usize>
    where
        R: AsyncRead + Unpin,
    {
        let spare = self.buffer.spare_capacity_mut();
        let read_len = limit.min(spare.len());
        if read_len == 0 {
            return Ok(0);
        }

        let mut read_buf = ReadBuf::uninit(&mut spare[..read_len]);
        poll_fn(|cx| Pin::new(&mut *reader).poll_read(cx, &mut read_buf)).await?;
        let read = read_buf.filled().len();
        // SAFETY: `poll_read` initialized exactly `read` bytes in the spare slice.
        unsafe {
            self.buffer.advance_mut(read);
        }
        Ok(read)
    }

    /// Copy data into buffer and mark as initialized
    ///
    /// # Panics
    /// Panics if `data.len()` > capacity
    #[inline]
    pub fn copy_from_slice(&mut self, data: &[u8]) {
        assert!(
            data.len() <= self.buffer.capacity(),
            "data exceeds buffer capacity"
        );
        self.buffer.clear();
        self.buffer.extend_from_slice(data);
    }

    /// Reset the logical contents of the buffer without changing its backing allocation.
    ///
    /// This is safe for both fixed-size I/O buffers and accumulator-style capture buffers:
    /// callers see an empty initialized slice afterwards, while the underlying allocation
    /// stays available for reuse.
    #[inline]
    pub fn clear(&mut self) {
        self.buffer.clear();
    }

    /// Append data to the buffer (accumulator mode)
    ///
    /// Used when `PooledBuffer` is acquired from capture pool for accumulating
    /// streaming data. Unlike `copy_from_slice` which overwrites, this extends.
    ///
    /// # Performance
    ///
    /// Capture buffers are allocated with sufficient capacity (1 MiB by default).
    /// As long as total accumulated data fits within capacity, this operation performs
    /// no Rust heap allocation.
    ///
    /// If data exceeds capacity, the `BytesMut` will grow automatically (with allocation).
    /// This ensures complete data is always captured rather than truncating, which
    /// would corrupt cached responses.
    ///
    /// # Note on length
    ///
    /// After calling this, `.len()` (via Deref) returns the total accumulated length.
    #[inline]
    pub fn extend_from_slice(&mut self, data: &[u8]) {
        let needed = self.buffer.len() + data.len();
        // Accumulator/capture mode may grow; resized buffers are discarded on drop.
        if needed > self.buffer.capacity() {
            tracing::warn!(
                "Capture buffer growing: {} + {} > {} capacity (will allocate)",
                self.buffer.len(),
                data.len(),
                self.buffer.capacity()
            );
        }
        self.buffer.extend_from_slice(data);
    }

    /// Freeze the initialized bytes into a shared immutable buffer.
    ///
    /// The backing allocation is intentionally detached from the pool because
    /// ownership escapes through `Bytes`.
    #[must_use]
    pub fn freeze(mut self) -> Bytes {
        std::mem::take(&mut self.buffer).freeze()
    }
}

impl Deref for PooledBuffer {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.buffer
    }
}

// Intentionally NO DerefMut or AsMut - forces explicit use of read_from()/read_more()

impl AsRef<[u8]> for PooledBuffer {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.buffer
    }
}

impl Drop for PooledBuffer {
    fn drop(&mut self) {
        let held_micros = duration_micros_u64(self.acquired_at.elapsed());
        record_buffer_hold(self.source, held_micros);
        maybe_log_buffer_hold(self.source, held_micros, self.buffer.capacity());

        if self.buffer.capacity() != self.expected_capacity {
            debug!(
                "Dropping resized pooled buffer instead of returning it to the pool (capacity {} != expected {})",
                self.buffer.capacity(),
                self.expected_capacity
            );
            if self.counts_toward_pool {
                self.allocated_count.fetch_sub(1, Ordering::Relaxed);
            }
            return;
        }

        self.buffer.clear();

        if !self.counts_toward_pool {
            return;
        }

        // Atomically return buffer to pool if pool is not full
        let mut current_size = self.pool_size.load(Ordering::Relaxed);
        while current_size < self.max_pool_size {
            match self.pool_size.compare_exchange_weak(
                current_size,
                current_size + 1,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => {
                    let buffer = std::mem::take(&mut self.buffer);
                    match self.pool.push(buffer) {
                        Ok(()) => return,
                        Err(buffer) => {
                            self.buffer = buffer;
                            self.pool_size.fetch_sub(1, Ordering::Relaxed);
                            self.allocated_count.fetch_sub(1, Ordering::Relaxed);
                            return;
                        }
                    }
                }
                Err(new_size) => {
                    current_size = new_size;
                }
            }
        }
        // If pool is full, buffer is dropped
        self.allocated_count.fetch_sub(1, Ordering::Relaxed);
    }
}

/// Buffered response assembled from one or more pooled capture buffers.
///
/// This avoids reallocating or growing a single `Vec` on the hot path when
/// a multiline response is larger than the typical capture size.
///
/// `ChunkedResponse` is storage only. It intentionally does not expose response
/// boundary helpers such as prefix or terminator checks; callers that need to
/// interpret backend bytes must go through the session framer/backend facade
/// before putting data here.
#[derive(Debug, Default)]
pub struct ChunkedResponse {
    chunks: SmallVec<[ResponseChunk; 16]>,
    len: usize,
}

#[derive(Debug, Default)]
struct ResponseWriteMetrics {
    responses: AtomicUsize,
    single_chunk_responses: AtomicUsize,
    multi_chunk_responses: AtomicUsize,
    chunks_written: AtomicUsize,
    bytes_written: AtomicUsize,
    tiny_chunks: AtomicUsize,
    tiny_chunk_bytes: AtomicUsize,
    small_chunks: AtomicUsize,
    small_chunk_bytes: AtomicUsize,
    max_chunks_per_response: AtomicUsize,
}

#[derive(Debug, Default)]
struct HotPathAllocationMetrics {
    regular_pool_fallback_allocations: AtomicUsize,
    regular_pool_exhaustions: AtomicUsize,
    capture_pool_fallback_allocations: AtomicUsize,
    chunked_response_metadata_spills: AtomicUsize,
    pending_backend_byte_heap_fallbacks: AtomicUsize,
    non_owned_response_write_chunks: AtomicUsize,
    non_owned_response_write_bytes: AtomicUsize,
    regular_pool_buffer_holds: AtomicUsize,
    regular_pool_buffer_hold_micros_total: AtomicU64,
    regular_pool_buffer_hold_micros_max: AtomicU64,
    capture_pool_buffer_holds: AtomicUsize,
    capture_pool_buffer_hold_micros_total: AtomicU64,
    capture_pool_buffer_hold_micros_max: AtomicU64,
}

/// Snapshot of direct client write-path activity from `ChunkedResponse::write_all_to`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ResponseWriteMetricsSnapshot {
    pub responses: usize,
    pub single_chunk_responses: usize,
    pub multi_chunk_responses: usize,
    pub chunks_written: usize,
    pub bytes_written: usize,
    pub tiny_chunks: usize,
    pub tiny_chunk_bytes: usize,
    pub small_chunks: usize,
    pub small_chunk_bytes: usize,
    pub max_chunks_per_response: usize,
}

/// Snapshot of allocation-sensitive hot-path activity.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct HotPathAllocationMetricsSnapshot {
    pub regular_pool_fallback_allocations: usize,
    pub regular_pool_exhaustions: usize,
    pub capture_pool_fallback_allocations: usize,
    pub chunked_response_metadata_spills: usize,
    pub pending_backend_byte_heap_fallbacks: usize,
    pub non_owned_response_write_chunks: usize,
    pub non_owned_response_write_bytes: usize,
    pub regular_pool_buffer_holds: usize,
    pub regular_pool_buffer_hold_micros_total: u64,
    pub regular_pool_buffer_hold_micros_max: u64,
    pub capture_pool_buffer_holds: usize,
    pub capture_pool_buffer_hold_micros_total: u64,
    pub capture_pool_buffer_hold_micros_max: u64,
}

fn response_write_metrics_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| std::env::var_os("NNTP_PROXY_RESPONSE_WRITE_METRICS_SECS").is_some())
}

fn response_write_metrics() -> &'static ResponseWriteMetrics {
    static METRICS: OnceLock<ResponseWriteMetrics> = OnceLock::new();
    METRICS.get_or_init(ResponseWriteMetrics::default)
}

fn hot_path_allocation_metrics() -> &'static HotPathAllocationMetrics {
    static METRICS: OnceLock<HotPathAllocationMetrics> = OnceLock::new();
    METRICS.get_or_init(HotPathAllocationMetrics::default)
}

fn duration_micros_u64(duration: std::time::Duration) -> u64 {
    u64::try_from(duration.as_micros()).unwrap_or(u64::MAX)
}

fn buffer_hold_log_threshold_micros() -> Option<u64> {
    static THRESHOLD: OnceLock<Option<u64>> = OnceLock::new();
    *THRESHOLD.get_or_init(|| {
        std::env::var("NNTP_PROXY_BUFFER_HOLD_LOG_MS")
            .ok()
            .and_then(|value| {
                let millis = value.parse::<u64>().ok()?;
                if millis == 0 {
                    None
                } else {
                    Some(millis.saturating_mul(1000))
                }
            })
    })
}

fn record_buffer_hold(source: PooledBufferSource, held_micros: u64) {
    let metrics = hot_path_allocation_metrics();
    match source.kind {
        PooledBufferKind::Regular => {
            metrics
                .regular_pool_buffer_holds
                .fetch_add(1, Ordering::Relaxed);
            metrics
                .regular_pool_buffer_hold_micros_total
                .fetch_add(held_micros, Ordering::Relaxed);
            metrics
                .regular_pool_buffer_hold_micros_max
                .fetch_max(held_micros, Ordering::Relaxed);
        }
        PooledBufferKind::Capture => {
            metrics
                .capture_pool_buffer_holds
                .fetch_add(1, Ordering::Relaxed);
            metrics
                .capture_pool_buffer_hold_micros_total
                .fetch_add(held_micros, Ordering::Relaxed);
            metrics
                .capture_pool_buffer_hold_micros_max
                .fetch_max(held_micros, Ordering::Relaxed);
        }
    }
}

fn maybe_log_buffer_hold(source: PooledBufferSource, held_micros: u64, capacity: usize) {
    let Some(threshold) = buffer_hold_log_threshold_micros() else {
        return;
    };
    if held_micros < threshold {
        return;
    }

    let pool = match source.kind {
        PooledBufferKind::Regular => "regular",
        PooledBufferKind::Capture => "capture",
    };
    debug!(
        pool,
        fallback = source.fallback,
        held_ms = held_micros / 1000,
        capacity,
        "Pooled buffer held longer than threshold"
    );
}

pub(crate) fn record_pending_backend_byte_heap_fallback() {
    hot_path_allocation_metrics()
        .pending_backend_byte_heap_fallbacks
        .fetch_add(1, Ordering::Relaxed);
}

pub(crate) fn record_non_owned_response_write_chunk(bytes: usize) {
    let metrics = hot_path_allocation_metrics();
    metrics
        .non_owned_response_write_chunks
        .fetch_add(1, Ordering::Relaxed);
    metrics
        .non_owned_response_write_bytes
        .fetch_add(bytes, Ordering::Relaxed);
}

#[must_use]
pub fn hot_path_allocation_metrics_snapshot() -> HotPathAllocationMetricsSnapshot {
    let metrics = hot_path_allocation_metrics();
    HotPathAllocationMetricsSnapshot {
        regular_pool_fallback_allocations: metrics
            .regular_pool_fallback_allocations
            .load(Ordering::Relaxed),
        regular_pool_exhaustions: metrics.regular_pool_exhaustions.load(Ordering::Relaxed),
        capture_pool_fallback_allocations: metrics
            .capture_pool_fallback_allocations
            .load(Ordering::Relaxed),
        chunked_response_metadata_spills: metrics
            .chunked_response_metadata_spills
            .load(Ordering::Relaxed),
        pending_backend_byte_heap_fallbacks: metrics
            .pending_backend_byte_heap_fallbacks
            .load(Ordering::Relaxed),
        non_owned_response_write_chunks: metrics
            .non_owned_response_write_chunks
            .load(Ordering::Relaxed),
        non_owned_response_write_bytes: metrics
            .non_owned_response_write_bytes
            .load(Ordering::Relaxed),
        regular_pool_buffer_holds: metrics.regular_pool_buffer_holds.load(Ordering::Relaxed),
        regular_pool_buffer_hold_micros_total: metrics
            .regular_pool_buffer_hold_micros_total
            .load(Ordering::Relaxed),
        regular_pool_buffer_hold_micros_max: metrics
            .regular_pool_buffer_hold_micros_max
            .load(Ordering::Relaxed),
        capture_pool_buffer_holds: metrics.capture_pool_buffer_holds.load(Ordering::Relaxed),
        capture_pool_buffer_hold_micros_total: metrics
            .capture_pool_buffer_hold_micros_total
            .load(Ordering::Relaxed),
        capture_pool_buffer_hold_micros_max: metrics
            .capture_pool_buffer_hold_micros_max
            .load(Ordering::Relaxed),
    }
}

pub fn reset_hot_path_allocation_metrics() {
    let metrics = hot_path_allocation_metrics();
    metrics
        .regular_pool_fallback_allocations
        .store(0, Ordering::Relaxed);
    metrics.regular_pool_exhaustions.store(0, Ordering::Relaxed);
    metrics
        .capture_pool_fallback_allocations
        .store(0, Ordering::Relaxed);
    metrics
        .chunked_response_metadata_spills
        .store(0, Ordering::Relaxed);
    metrics
        .pending_backend_byte_heap_fallbacks
        .store(0, Ordering::Relaxed);
    metrics
        .non_owned_response_write_chunks
        .store(0, Ordering::Relaxed);
    metrics
        .non_owned_response_write_bytes
        .store(0, Ordering::Relaxed);
    metrics
        .regular_pool_buffer_holds
        .store(0, Ordering::Relaxed);
    metrics
        .regular_pool_buffer_hold_micros_total
        .store(0, Ordering::Relaxed);
    metrics
        .regular_pool_buffer_hold_micros_max
        .store(0, Ordering::Relaxed);
    metrics
        .capture_pool_buffer_holds
        .store(0, Ordering::Relaxed);
    metrics
        .capture_pool_buffer_hold_micros_total
        .store(0, Ordering::Relaxed);
    metrics
        .capture_pool_buffer_hold_micros_max
        .store(0, Ordering::Relaxed);
}

fn record_response_write_metrics(
    chunk_count: usize,
    bytes_written: usize,
    tiny_chunks: usize,
    tiny_chunk_bytes: usize,
    small_chunks: usize,
    small_chunk_bytes: usize,
) {
    if !response_write_metrics_enabled() {
        return;
    }

    let metrics = response_write_metrics();
    metrics.responses.fetch_add(1, Ordering::Relaxed);
    metrics
        .chunks_written
        .fetch_add(chunk_count, Ordering::Relaxed);
    metrics
        .bytes_written
        .fetch_add(bytes_written, Ordering::Relaxed);
    metrics
        .tiny_chunks
        .fetch_add(tiny_chunks, Ordering::Relaxed);
    metrics
        .tiny_chunk_bytes
        .fetch_add(tiny_chunk_bytes, Ordering::Relaxed);
    metrics
        .small_chunks
        .fetch_add(small_chunks, Ordering::Relaxed);
    metrics
        .small_chunk_bytes
        .fetch_add(small_chunk_bytes, Ordering::Relaxed);
    metrics
        .max_chunks_per_response
        .fetch_max(chunk_count, Ordering::Relaxed);
    if chunk_count <= 1 {
        metrics
            .single_chunk_responses
            .fetch_add(1, Ordering::Relaxed);
    } else {
        metrics
            .multi_chunk_responses
            .fetch_add(1, Ordering::Relaxed);
    }
}

#[must_use]
pub fn response_write_metrics_snapshot() -> ResponseWriteMetricsSnapshot {
    let metrics = response_write_metrics();
    ResponseWriteMetricsSnapshot {
        responses: metrics.responses.load(Ordering::Relaxed),
        single_chunk_responses: metrics.single_chunk_responses.load(Ordering::Relaxed),
        multi_chunk_responses: metrics.multi_chunk_responses.load(Ordering::Relaxed),
        chunks_written: metrics.chunks_written.load(Ordering::Relaxed),
        bytes_written: metrics.bytes_written.load(Ordering::Relaxed),
        tiny_chunks: metrics.tiny_chunks.load(Ordering::Relaxed),
        tiny_chunk_bytes: metrics.tiny_chunk_bytes.load(Ordering::Relaxed),
        small_chunks: metrics.small_chunks.load(Ordering::Relaxed),
        small_chunk_bytes: metrics.small_chunk_bytes.load(Ordering::Relaxed),
        max_chunks_per_response: metrics.max_chunks_per_response.load(Ordering::Relaxed),
    }
}

#[derive(Debug)]
struct ResponseChunk {
    storage: ResponseChunkStorage,
    range: Range<usize>,
}

#[derive(Debug)]
enum ResponseChunkStorage {
    Pooled(PooledBuffer),
    #[cfg(test)]
    SharedPooled(Arc<PooledBuffer>),
}

impl ResponseChunk {
    fn as_slice(&self) -> &[u8] {
        match &self.storage {
            ResponseChunkStorage::Pooled(buffer) => &buffer.as_ref()[self.range.clone()],
            #[cfg(test)]
            ResponseChunkStorage::SharedPooled(buffer) => &buffer.as_ref()[self.range.clone()],
        }
    }

    fn initialized(&self) -> usize {
        match &self.storage {
            ResponseChunkStorage::Pooled(buffer) => buffer.initialized(),
            #[cfg(test)]
            ResponseChunkStorage::SharedPooled(buffer) => buffer.initialized(),
        }
    }

    fn capacity(&self) -> usize {
        match &self.storage {
            ResponseChunkStorage::Pooled(buffer) => buffer.capacity(),
            #[cfg(test)]
            ResponseChunkStorage::SharedPooled(buffer) => buffer.capacity(),
        }
    }

    fn can_append(&self) -> bool {
        matches!(self.storage, ResponseChunkStorage::Pooled(_))
            && self.range.end == self.initialized()
            && self.initialized() < self.capacity()
    }

    fn extend_from_slice(&mut self, data: &[u8]) {
        match &mut self.storage {
            ResponseChunkStorage::Pooled(buffer) => buffer.extend_from_slice(data),
            #[cfg(test)]
            ResponseChunkStorage::SharedPooled(_) => {
                panic!("cannot extend shared response chunk")
            }
        }
    }
}

impl ChunkedResponse {
    /// Total buffered length across all chunks.
    #[must_use]
    #[inline]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns true when no bytes are buffered.
    #[must_use]
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Remove all buffered data, returning chunks to the pool on drop.
    #[inline]
    pub fn clear(&mut self) {
        self.chunks.clear();
        self.len = 0;
    }

    /// Append bytes using one or more pooled capture buffers.
    ///
    /// # Panics
    /// Panics if the internal chunk list becomes unexpectedly empty after a
    /// new capture buffer is acquired.
    pub fn extend_from_slice(&mut self, pool: &BufferPool, mut data: &[u8]) {
        while !data.is_empty() {
            let need_new_chunk = self.chunks.last().is_none_or(|chunk| !chunk.can_append());

            if need_new_chunk {
                if self.chunks.len() == self.chunks.inline_size() {
                    hot_path_allocation_metrics()
                        .chunked_response_metadata_spills
                        .fetch_add(1, Ordering::Relaxed);
                }
                self.chunks.push(ResponseChunk {
                    storage: ResponseChunkStorage::Pooled(pool.acquire_capture_now()),
                    range: 0..0,
                });
            }

            let chunk = self
                .chunks
                .last_mut()
                .expect("chunk just pushed or already existed");
            let available = chunk.capacity().saturating_sub(chunk.initialized());
            debug_assert!(available > 0, "chunk must have space after allocation");

            let take = available.min(data.len());
            chunk.extend_from_slice(&data[..take]);
            chunk.range.end += take;
            self.len += take;
            data = &data[take..];
        }
    }

    /// Move a byte range from an initialized pooled buffer into this response.
    ///
    /// This avoids copying large backend reads into separate capture buffers.
    /// The caller must pass only a range already produced by response framing.
    /// Later appends will allocate a fresh pooled chunk when this range does not
    /// end at the initialized length, so skipped bytes are never exposed.
    /// # Panics
    /// Panics if `range` is outside the buffer's initialized bytes.
    pub(crate) fn push_buffer_range(&mut self, buffer: PooledBuffer, range: Range<usize>) {
        assert!(
            range.start <= range.end && range.end <= buffer.initialized(),
            "response range must be inside initialized buffer"
        );
        if self.chunks.len() == self.chunks.inline_size() {
            hot_path_allocation_metrics()
                .chunked_response_metadata_spills
                .fetch_add(1, Ordering::Relaxed);
        }
        self.len += range.end - range.start;
        self.chunks.push(ResponseChunk {
            storage: ResponseChunkStorage::Pooled(buffer),
            range,
        });
    }

    /// Add a range from a shared pooled buffer without copying.
    ///
    /// # Panics
    /// Panics if `range` is outside the pooled buffer's initialized bytes.
    #[cfg(test)]
    pub(crate) fn push_shared_pooled_range(
        &mut self,
        buffer: Arc<PooledBuffer>,
        range: Range<usize>,
    ) {
        assert!(
            range.start <= range.end && range.end <= buffer.initialized(),
            "response range must be inside initialized pooled buffer"
        );
        if self.chunks.len() == self.chunks.inline_size() {
            hot_path_allocation_metrics()
                .chunked_response_metadata_spills
                .fetch_add(1, Ordering::Relaxed);
        }
        self.len += range.end - range.start;
        self.chunks.push(ResponseChunk {
            storage: ResponseChunkStorage::SharedPooled(buffer),
            range,
        });
    }

    /// First chunk of buffered data, if any.
    #[cfg(test)]
    #[must_use]
    pub fn first_chunk(&self) -> Option<&[u8]> {
        self.chunks.first().map(ResponseChunk::as_slice)
    }

    /// Iterate buffered chunks without flattening.
    pub fn iter_chunks(&self) -> impl Iterator<Item = &[u8]> {
        self.chunks.iter().map(ResponseChunk::as_slice)
    }

    /// Copy up to `len` bytes from the front of the response into a small stack-backed buffer.
    pub fn copy_prefix_into(&self, len: usize, out: &mut SmallVec<[u8; 128]>) {
        out.clear();
        let mut remaining = len.min(self.len);
        for chunk in self.iter_chunks() {
            if remaining == 0 {
                break;
            }
            let take = remaining.min(chunk.len());
            out.extend_from_slice(&chunk[..take]);
            remaining -= take;
        }
    }

    /// Copy the buffered response into a contiguous `Vec<u8>`.
    #[must_use]
    pub fn to_vec(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(self.len);
        for chunk in self.iter_chunks() {
            out.extend_from_slice(chunk);
        }
        out
    }

    /// Write all buffered chunks to a sink in order.
    ///
    /// # Errors
    /// Returns any write error produced by the underlying async sink.
    pub async fn write_all_to<W>(&self, writer: &mut W) -> std::io::Result<()>
    where
        W: AsyncWriteExt + Unpin,
    {
        if response_write_metrics_enabled() {
            let mut chunk_count = 0usize;
            let mut tiny_chunks = 0usize;
            let mut tiny_chunk_bytes = 0usize;
            let mut small_chunks = 0usize;
            let mut small_chunk_bytes = 0usize;
            for chunk in self.iter_chunks() {
                chunk_count += 1;
                let len = chunk.len();
                if len <= 256 {
                    tiny_chunks += 1;
                    tiny_chunk_bytes += len;
                }
                if len <= 4096 {
                    small_chunks += 1;
                    small_chunk_bytes += len;
                }
            }
            record_response_write_metrics(
                chunk_count,
                self.len,
                tiny_chunks,
                tiny_chunk_bytes,
                small_chunks,
                small_chunk_bytes,
            );
        }

        for chunk in self.iter_chunks() {
            writer.write_all(chunk).await?;
        }
        Ok(())
    }
}

/// Lock-free buffer pool for reusing large I/O buffers.
///
/// Uses bounded `ArrayQueue`s so queue slots are allocated once at startup and
/// buffer return does not allocate linked queue blocks on the forwarding path.
#[derive(Debug, Clone)]
pub struct BufferPool {
    pool: Arc<ArrayQueue<BytesMut>>,
    buffer_size: BufferSize,
    max_pool_size: usize,
    pool_size: Arc<AtomicUsize>,
    allocated_count: Arc<AtomicUsize>,
    // Capture buffer pool (for accumulating streaming data)
    capture_pool: Arc<ArrayQueue<BytesMut>>,
    capture_capacity: usize,
    max_capture_pool_size: usize,
    capture_pool_size: Arc<AtomicUsize>,
    capture_allocated_count: Arc<AtomicUsize>,
}

impl BufferPool {
    /// Create a page-aligned buffer for optimal DMA performance
    ///
    /// Returns a raw `BytesMut` that will be wrapped in `PooledBuffer` by `acquire()`.
    /// The buffer has a logical length of zero before it enters the pool.
    ///
    /// # Safety
    ///
    /// **INTERNAL USE ONLY.** This function is not exposed publicly and is only used
    /// within the buffer pool implementation where the safety contract is guaranteed.
    ///
    /// The returned buffer has a logical length of zero. Only bytes added to the
    /// `BytesMut` logical length are exposed through the public initialized slice APIs.
    fn create_aligned_buffer(size: usize) -> BytesMut {
        // Align to page boundaries (4KB) for better memory performance
        let page_size = 4096;
        let aligned_size = size.div_ceil(page_size) * page_size;

        BytesMut::with_capacity(aligned_size)
    }

    /// Create a new lazy buffer pool
    ///
    /// # Arguments
    /// * `buffer_size` - Size of each buffer in bytes (must be non-zero)
    /// * `max_pool_size` - Maximum number of buffers to pool
    ///
    /// # Design Philosophy
    ///
    /// **Buffer pool queue capacity is allocated once at application boot**. Backing
    /// buffers are allocated lazily as clients/backend work first need them, then
    /// returned to the pool for reuse. This is a critical performance
    /// optimization:
    ///
    /// - **Boot time**: Queue slots only; idle RSS stays small
    /// - **Warm runtime**: Zero allocations in hot path (acquire/release from pool)
    /// - **Per-connection**: Buffers are borrowed and returned, never owned
    ///
    /// **IMPORTANT**: Do NOT create a `BufferPool` per-client, per-connection, or
    /// per-request. Create ONE pool at application startup and share it across
    /// all operations via Arc or static reference.
    ///
    /// Buffers are allocated on first use up to `max_pool_size`; allocations beyond
    /// that remain visible through fallback metrics.
    #[must_use]
    pub fn new(buffer_size: BufferSize, max_pool_size: usize) -> Self {
        let pool = Arc::new(ArrayQueue::new(max_pool_size.max(1)));
        let pool_size = Arc::new(AtomicUsize::new(0));
        let allocated_count = Arc::new(AtomicUsize::new(0));

        info!(
            "Creating lazy buffer pool for up to {} buffers of {}KB each ({}MB max resident after use)",
            max_pool_size,
            buffer_size.get() / 1024,
            (max_pool_size * buffer_size.get()) / (1024 * 1024)
        );

        Self {
            pool,
            buffer_size,
            max_pool_size,
            pool_size,
            allocated_count,
            // Initialize capture pool as empty (will be configured via with_capture_pool)
            capture_pool: Arc::new(ArrayQueue::new(1)),
            capture_capacity: 0,
            max_capture_pool_size: 0,
            capture_pool_size: Arc::new(AtomicUsize::new(0)),
            capture_allocated_count: Arc::new(AtomicUsize::new(0)),
        }
    }

    /// Configure the capture buffer pool for accumulator buffers
    ///
    /// Capture buffers are used for accumulating streaming data (e.g., caching).
    /// # Arguments
    /// * `capacity` - Size of each capture buffer in bytes (e.g., 1 MiB by default)
    /// * `count` - Maximum number of capture buffers to pool
    #[must_use]
    pub fn with_capture_pool(mut self, capacity: usize, count: usize) -> Self {
        self.capture_pool = Arc::new(ArrayQueue::new(count.max(1)));
        self.capture_pool_size = Arc::new(AtomicUsize::new(0));
        self.capture_allocated_count = Arc::new(AtomicUsize::new(0));

        info!(
            "Creating lazy capture buffer pool for up to {} buffers of {}KB each ({}MB max resident after use)",
            count,
            capacity / 1024,
            (count * capacity) / (1024 * 1024)
        );

        self.capture_capacity = capacity;
        self.max_capture_pool_size = count;

        self
    }

    /// Create a buffer pool suitable for testing
    ///
    /// Uses sensible defaults (8KB buffers, pool of 4) that work for most tests.
    /// Prefer this over manually constructing `BufferPool` in tests.
    ///
    /// # Panics
    /// Panics only if the built-in test buffer size stops satisfying
    /// `BufferSize` validation.
    #[cfg(test)]
    #[must_use]
    pub fn for_tests() -> Self {
        Self::new(BufferSize::try_new(8192).expect("valid size"), 4).with_capture_pool(8192, 2)
    }

    /// Get the current number of available buffers in the pool
    #[must_use]
    pub fn available_buffers(&self) -> usize {
        self.pool_size.load(Ordering::Relaxed)
    }

    /// Get the number of buffers currently in use
    #[must_use]
    pub fn buffers_in_use(&self) -> usize {
        self.allocated_count
            .load(Ordering::Relaxed)
            .saturating_sub(self.available_buffers())
    }

    /// Get buffer pool statistics (available, in-use, total)
    #[must_use]
    pub fn stats(&self) -> (usize, usize, usize) {
        let available = self.available_buffers();
        let in_use = self.buffers_in_use();
        (available, in_use, self.max_pool_size)
    }

    /// Get a buffer from the pool or create a new one (lock-free)
    ///
    /// Returns a `PooledBuffer` that automatically returns to the pool when dropped.
    ///
    /// # Performance: Warm Zero-Allocation Hot Path
    ///
    /// This method allocates lazily until the pool reaches `max_pool_size`.
    /// Once buffers have been created and returned, reuse just pops from the
    /// lock-free queue. This keeps idle RSS low while preserving the warm
    /// zero-allocation forwarding path.
    ///
    /// Only if the pool is exhausted (all buffers in use) will a new buffer
    /// be allocated. Size the pool appropriately to avoid this fallback.
    ///
    /// # Safety Notes
    ///
    /// The buffer may contain old bytes outside its logical length, but immutable
    /// access only exposes `BytesMut::len()` initialized bytes.
    fn wrap_regular_buffer(
        &self,
        buffer: BytesMut,
        fallback: bool,
        counts_toward_pool: bool,
    ) -> PooledBuffer {
        PooledBuffer {
            expected_capacity: buffer.capacity(),
            buffer,
            pool: Arc::clone(&self.pool),
            pool_size: Arc::clone(&self.pool_size),
            allocated_count: Arc::clone(&self.allocated_count),
            max_pool_size: self.max_pool_size,
            writable_len: self.buffer_size.get(),
            acquired_at: Instant::now(),
            source: PooledBufferSource::regular(fallback),
            counts_toward_pool,
        }
    }

    fn try_reserve_regular_slot(&self) -> bool {
        let mut allocated = self.allocated_count.load(Ordering::Relaxed);
        while allocated < self.max_pool_size {
            match self.allocated_count.compare_exchange_weak(
                allocated,
                allocated + 1,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => return true,
                Err(new_allocated) => allocated = new_allocated,
            }
        }
        false
    }

    fn try_reserve_capture_slot(&self) -> bool {
        let mut allocated = self.capture_allocated_count.load(Ordering::Relaxed);
        while allocated < self.max_capture_pool_size {
            match self.capture_allocated_count.compare_exchange_weak(
                allocated,
                allocated + 1,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => return true,
                Err(new_allocated) => allocated = new_allocated,
            }
        }
        false
    }

    fn acquire_now(&self) -> PooledBuffer {
        self.pool.pop().map_or_else(
            || {
                if self.try_reserve_regular_slot() {
                    return self.wrap_regular_buffer(
                        Self::create_aligned_buffer(self.buffer_size.get()),
                        false,
                        true,
                    );
                }

                hot_path_allocation_metrics()
                    .regular_pool_fallback_allocations
                    .fetch_add(1, Ordering::Relaxed);
                warn!(
                    max_pool_size = self.max_pool_size,
                    buffer_size = self.buffer_size.get(),
                    "Regular buffer pool exhausted; allocating fallback buffer"
                );
                self.wrap_regular_buffer(
                    Self::create_aligned_buffer(self.buffer_size.get()),
                    true,
                    false,
                )
            },
            |buffer| {
                self.pool_size.fetch_sub(1, Ordering::Relaxed);
                // Buffer from pool is logically empty and has the expected allocation
                // capacity (enforced on return).
                debug_assert_eq!(buffer.len(), 0);
                self.wrap_regular_buffer(buffer, false, true)
            },
        )
    }

    pub fn acquire(&self) -> PooledBuffer {
        self.acquire_now()
    }

    /// Get a regular buffer only if one is already available in the pool.
    ///
    /// This is for strict proxy forwarding paths where falling back to a fresh
    /// allocation would hide hot-path pressure. Pool exhaustion remains visible
    /// through the separate exhaustion metric, but this method returns `None`
    /// instead of allocating.
    #[cfg(test)]
    pub(crate) fn try_acquire(&self) -> Option<PooledBuffer> {
        let buffer = self.pool.pop().map_or_else(
            || {
                hot_path_allocation_metrics()
                    .regular_pool_exhaustions
                    .fetch_add(1, Ordering::Relaxed);
                None
            },
            Some,
        )?;
        self.pool_size.fetch_sub(1, Ordering::Relaxed);
        debug_assert_eq!(buffer.len(), 0);
        Some(self.wrap_regular_buffer(buffer, false, true))
    }

    /// Get a capture buffer from the capture pool
    ///
    /// Returns a `PooledBuffer` backed by a pooled capture buffer.
    /// Used for accumulating streaming data (e.g., caching articles).
    pub(crate) fn acquire_capture_now(&self) -> PooledBuffer {
        let mut fallback = false;
        let mut counts_toward_pool = true;
        let buffer = self.capture_pool.pop().map_or_else(
            || {
                let capacity = if self.capture_capacity > 0 {
                    self.capture_capacity
                } else {
                    self.buffer_size.get()
                };

                if self.try_reserve_capture_slot() {
                    return BytesMut::with_capacity(capacity);
                }

                fallback = true;
                counts_toward_pool = false;
                hot_path_allocation_metrics()
                    .capture_pool_fallback_allocations
                    .fetch_add(1, Ordering::Relaxed);
                warn!(
                    max_pool_size = self.max_capture_pool_size,
                    capacity, "Capture buffer pool exhausted; allocating fallback buffer"
                );
                // Pool exhausted - allocate a visible fallback buffer.
                BytesMut::with_capacity(capacity)
            },
            |mut buffer| {
                self.capture_pool_size.fetch_sub(1, Ordering::Relaxed);
                // Clear but keep capacity for reuse.
                buffer.clear();
                buffer
            },
        );

        PooledBuffer {
            expected_capacity: buffer.capacity(),
            buffer,
            pool: Arc::clone(&self.capture_pool),
            pool_size: Arc::clone(&self.capture_pool_size),
            allocated_count: Arc::clone(&self.capture_allocated_count),
            max_pool_size: self.max_capture_pool_size,
            writable_len: 0,
            acquired_at: Instant::now(),
            source: PooledBufferSource::capture(fallback),
            counts_toward_pool,
        }
    }

    pub fn acquire_capture(&self) -> PooledBuffer {
        self.acquire_capture_now()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Mutex, MutexGuard};

    fn hot_path_metrics_test_guard() -> MutexGuard<'static, ()> {
        static GUARD: Mutex<()> = Mutex::new(());
        GUARD.lock().expect("hot-path metrics test guard poisoned")
    }
    use tokio::io::AsyncWriteExt;

    #[tokio::test]
    async fn test_buffer_pool_creation() {
        let pool = BufferPool::new(BufferSize::try_new(8192).unwrap(), 10);

        assert_eq!(pool.stats(), (0, 0, 10));

        // Pool should lazily allocate buffers on first use.
        let buffer1 = pool.acquire();
        assert_eq!(buffer1.capacity(), 8192);
        assert_eq!(buffer1.initialized(), 0); // No bytes initialized yet
        // Buffer automatically returned on drop
    }

    #[tokio::test]
    async fn test_acquire_starts_empty_with_stable_capacity() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1);

        let capacity = {
            let buffer = pool.acquire();
            assert_eq!(buffer.initialized(), 0);
            assert_eq!(buffer.len(), 0);
            buffer.capacity()
        };

        let buffer = pool.acquire();
        assert_eq!(buffer.initialized(), 0);
        assert_eq!(buffer.len(), 0);
        assert_eq!(buffer.capacity(), capacity);
    }

    #[tokio::test]
    async fn test_read_from_sets_initialized_without_reducing_capacity() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1);
        let mut buffer = pool.acquire();
        let capacity = buffer.capacity();
        let (mut writer, mut reader) = tokio::io::duplex(64);

        writer.write_all(b"220 ready\r\n").await.unwrap();
        drop(writer);

        let read = buffer.read_from(&mut reader).await.unwrap();
        assert_eq!(read, 11);
        assert_eq!(buffer.initialized(), 11);
        assert_eq!(&*buffer, b"220 ready\r\n");
        assert_eq!(buffer.capacity(), capacity);
    }

    #[tokio::test]
    async fn test_read_from_is_limited_to_fixed_writable_region() {
        let pool = BufferPool::new(BufferSize::try_new(8).unwrap(), 1);
        let mut buffer = pool.acquire();
        assert_eq!(buffer.capacity(), 4096);

        let (mut writer, mut reader) = tokio::io::duplex(64);
        writer
            .write_all(b"220 long response over eight bytes\r\n")
            .await
            .unwrap();
        drop(writer);

        let read = buffer.read_from(&mut reader).await.unwrap();
        assert_eq!(read, 8);
        assert_eq!(buffer.initialized(), 8);
        assert_eq!(buffer[..read].len(), read);
    }

    #[tokio::test]
    async fn test_read_more_appends_after_initialized_bytes() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1);
        let mut buffer = pool.acquire();
        buffer.copy_from_slice(b"22");

        let (mut writer, mut reader) = tokio::io::duplex(64);
        writer.write_all(b"0 ready\r\n").await.unwrap();
        drop(writer);

        let read = buffer.read_more(&mut reader).await.unwrap();
        assert_eq!(read, 9);
        assert_eq!(buffer.initialized(), 11);
        assert_eq!(&*buffer, b"220 ready\r\n");
    }

    #[tokio::test]
    async fn test_read_more_is_limited_to_remaining_fixed_writable_region() {
        let pool = BufferPool::new(BufferSize::try_new(8).unwrap(), 1);
        let mut buffer = pool.acquire();
        buffer.copy_from_slice(b"22");

        let (mut writer, mut reader) = tokio::io::duplex(64);
        writer.write_all(b"0 long response\r\n").await.unwrap();
        drop(writer);

        let read = buffer.read_more(&mut reader).await.unwrap();
        assert_eq!(read, 6);
        assert_eq!(buffer.initialized(), 8);
        assert_eq!(&*buffer, b"220 long");
    }

    #[tokio::test]
    async fn test_copy_from_slice_overwrites_and_allows_up_to_capacity() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1);
        let mut buffer = pool.acquire();
        let capacity = buffer.capacity();

        buffer.copy_from_slice(b"previous bytes");
        assert_eq!(&*buffer, b"previous bytes");

        let data = vec![b'X'; capacity];
        buffer.copy_from_slice(&data);
        assert_eq!(buffer.initialized(), capacity);
        assert_eq!(&buffer[..4], b"XXXX");
        assert_eq!(buffer.capacity(), capacity);
    }

    #[tokio::test]
    #[should_panic(expected = "data exceeds buffer capacity")]
    async fn test_copy_from_slice_rejects_larger_than_capacity() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1);
        let mut buffer = pool.acquire();
        let too_large = vec![b'X'; buffer.capacity() + 1];

        buffer.copy_from_slice(&too_large);
    }

    #[tokio::test]
    async fn test_clear_only_changes_initialized_length() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1);
        let mut buffer = pool.acquire();
        let capacity = buffer.capacity();

        buffer.copy_from_slice(b"abcdef");
        buffer.clear();
        assert_eq!(buffer.initialized(), 0);
        assert_eq!(buffer.len(), 0);
        assert_eq!(buffer.capacity(), capacity);
    }

    #[tokio::test]
    async fn test_resized_buffers_are_discarded_instead_of_repooled() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1).with_capture_pool(8, 1);

        let normal_capacity = {
            let mut buffer = pool.acquire();
            let capacity = buffer.capacity();
            buffer.extend_from_slice(&vec![b'N'; capacity + 1]);
            assert!(buffer.capacity() > capacity);
            capacity
        };

        let buffer = pool.acquire();
        assert_eq!(buffer.capacity(), normal_capacity);
        drop(buffer);

        {
            let mut capture = pool.acquire_capture();
            capture.extend_from_slice(&[b'C'; 9]);
            assert!(capture.capacity() > 8);
        }

        let capture = pool.acquire_capture();
        assert_eq!(capture.capacity(), 8);
    }

    #[tokio::test]
    async fn test_buffer_pool_get_and_return() {
        let pool = BufferPool::new(BufferSize::try_new(4096).unwrap(), 5);

        // Get a buffer
        let buffer = pool.acquire();
        assert_eq!(buffer.capacity(), 4096);
        assert_eq!(buffer.initialized(), 0);

        // Callers see an empty initialized slice until data is read or copied in.

        // Drop it (automatically returns to pool)
        drop(buffer);

        // Get it again - should be from pool
        let buffer2 = pool.acquire();
        assert_eq!(buffer2.capacity(), 4096);
    }

    #[tokio::test]
    async fn test_buffer_pool_exhaustion() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 2);

        // Lazily allocate all pool-owned buffers.
        let buf1 = pool.acquire();
        let buf2 = pool.acquire();

        // Pool is exhausted, should create new buffer
        let buf3 = pool.acquire();
        assert_eq!(buf3.capacity(), 4096);

        // Drop buffers (automatically returned)
        drop(buf1);
        drop(buf2);
        drop(buf3);
    }

    #[tokio::test]
    async fn test_try_acquire_reports_exhaustion_without_allocating() {
        let _guard = hot_path_metrics_test_guard();
        reset_hot_path_allocation_metrics();
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1);

        assert!(pool.try_acquire().is_none());
        {
            let buffer = pool.acquire();
            assert_eq!(buffer.capacity(), 4096);
        }

        let _held = pool.try_acquire().expect("warmed buffer available");

        let before = hot_path_allocation_metrics_snapshot();

        assert!(pool.try_acquire().is_none());

        let after = hot_path_allocation_metrics_snapshot();
        assert_eq!(
            after.regular_pool_fallback_allocations,
            before.regular_pool_fallback_allocations
        );
        assert!(after.regular_pool_exhaustions > before.regular_pool_exhaustions);
        assert_eq!(pool.stats(), (0, 1, 1));
    }

    #[tokio::test]
    async fn test_buffer_hold_metrics_record_regular_and_capture_drops() {
        let _guard = hot_path_metrics_test_guard();
        reset_hot_path_allocation_metrics();
        let pool =
            BufferPool::new(BufferSize::try_new(1024).unwrap(), 1).with_capture_pool(8192, 1);
        let before = hot_path_allocation_metrics_snapshot();

        drop(pool.acquire());
        drop(pool.acquire_capture());

        let after = hot_path_allocation_metrics_snapshot();
        assert!(after.regular_pool_buffer_holds > before.regular_pool_buffer_holds);
        assert!(after.capture_pool_buffer_holds > before.capture_pool_buffer_holds);
    }

    #[tokio::test]
    async fn test_oversized_capture_buffer_is_not_reused() {
        let pool =
            BufferPool::new(BufferSize::try_new(1024).unwrap(), 1).with_capture_pool(8192, 1);

        let mut capture = pool.acquire_capture();
        capture.extend_from_slice(&vec![b'X'; 8193]);
        assert!(capture.capacity() > 8192);
        drop(capture);

        let capture2 = pool.acquire_capture();
        assert_eq!(capture2.capacity(), 8192);
    }

    #[tokio::test]
    async fn test_capture_pool_lazily_allocates_configured_count() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1).with_capture_pool(8, 4);

        assert_eq!(pool.capture_pool_size.load(Ordering::Relaxed), 0);
        assert_eq!(pool.capture_allocated_count.load(Ordering::Relaxed), 0);

        let buffers = [
            pool.acquire_capture(),
            pool.acquire_capture(),
            pool.acquire_capture(),
            pool.acquire_capture(),
        ];

        assert_eq!(pool.capture_pool_size.load(Ordering::Relaxed), 0);
        assert_eq!(pool.capture_allocated_count.load(Ordering::Relaxed), 4);
        assert!(buffers.iter().all(|buffer| buffer.capacity() == 8));
        drop(buffers);

        assert_eq!(pool.capture_pool_size.load(Ordering::Relaxed), 4);
    }

    #[tokio::test]
    async fn test_chunked_response_helpers_without_flattening() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1).with_capture_pool(8, 4);
        let mut response = ChunkedResponse::default();
        response.extend_from_slice(&pool, b"220 0 <id>\r\nBody\r\n.\r\n");

        let chunks: Vec<&[u8]> = response.iter_chunks().collect();
        assert!(chunks.len() > 1, "test requires multi-chunk buffering");
        assert_eq!(chunks.concat(), b"220 0 <id>\r\nBody\r\n.\r\n");

        let mut prefix = SmallVec::<[u8; 128]>::new();
        response.copy_prefix_into(12, &mut prefix);
        assert_eq!(&prefix[..], b"220 0 <id>\r\n");
    }

    #[tokio::test]
    async fn test_chunked_response_uses_more_capture_buffers_instead_of_growing_one() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1).with_capture_pool(8, 4);
        let mut response = ChunkedResponse::default();

        response.extend_from_slice(&pool, b"123456789abcdefghi");

        let chunks: Vec<&[u8]> = response.iter_chunks().collect();
        assert_eq!(
            chunks.iter().map(|chunk| chunk.len()).collect::<Vec<_>>(),
            vec![8, 8, 2]
        );
    }

    #[tokio::test]
    async fn test_chunked_response_copy_prefix_clamps_to_length() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1).with_capture_pool(8, 4);
        let mut response = ChunkedResponse::default();
        response.extend_from_slice(&pool, b"430\r\n");

        let mut prefix = SmallVec::<[u8; 128]>::new();
        response.copy_prefix_into(64, &mut prefix);
        assert_eq!(&prefix[..], b"430\r\n");
    }

    #[tokio::test]
    async fn test_chunked_response_can_own_range_without_copying() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 2);
        let mut buffer = pool.acquire();
        buffer.copy_from_slice(b"xx220 0 <id>\r\nBody\r\n.\r\nyy");
        let expected_ptr = buffer.as_ref()[2..].as_ptr();

        let mut response = ChunkedResponse::default();
        response.push_buffer_range(buffer, 2..23);

        let first = response.first_chunk().expect("range chunk");
        assert_eq!(first.as_ptr(), expected_ptr);
        assert_eq!(first, b"220 0 <id>\r\nBody\r\n.\r\n");
    }

    #[tokio::test]
    async fn test_chunked_response_can_share_pooled_range_without_copying() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 2);
        let mut buffer = pool.acquire();
        buffer.copy_from_slice(b"xx220 0 <id>\r\nBody\r\n.\r\nyy");
        let shared = std::sync::Arc::new(buffer);
        let expected_ptr = shared.as_ref()[2..].as_ptr();

        let mut response = ChunkedResponse::default();
        response.push_shared_pooled_range(std::sync::Arc::clone(&shared), 2..23);

        let first = response.first_chunk().expect("shared pooled range chunk");
        assert_eq!(first.as_ptr(), expected_ptr);
        assert_eq!(first, b"220 0 <id>\r\nBody\r\n.\r\n");
        drop(response);
        drop(shared);
        assert_eq!(pool.available_buffers(), 1);
    }

    #[tokio::test]
    async fn test_freeze_detaches_bytes_from_pool_ownership() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 1);
        let mut buffer = pool.acquire();
        buffer.copy_from_slice(b"223 0 <id>\r\n");
        assert_eq!(pool.available_buffers(), 0);

        let bytes = buffer.freeze();
        assert_eq!(&bytes[..], b"223 0 <id>\r\n");

        drop(bytes);

        assert_eq!(
            pool.available_buffers(),
            0,
            "dropping frozen bytes must not return the detached allocation to the pool"
        );
    }

    #[tokio::test]
    async fn test_buffer_pool_concurrent_access() {
        let pool = BufferPool::new(BufferSize::try_new(2048).unwrap(), 10);

        // Spawn multiple tasks accessing the pool concurrently
        let mut handles = vec![];

        for _ in 0..20 {
            let pool_clone = pool.clone();
            let handle = tokio::spawn(async move {
                let buffer = pool_clone.acquire();
                assert_eq!(buffer.capacity(), 4096);
                // Simulate some work
                tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;
            });
            handles.push(handle);
        }

        // Wait for all tasks to complete
        for handle in handles {
            handle.await.unwrap();
        }
    }

    #[tokio::test]
    async fn test_buffer_alignment() {
        let pool = BufferPool::new(BufferSize::try_new(8192).unwrap(), 1);
        let buffer = pool.acquire();

        // Buffer capacity should be aligned to page boundaries (4KB)
        assert!(buffer.capacity() >= 8192);
        // Should be page-aligned (multiple of 4096)
        assert_eq!(buffer.capacity() % 4096, 0);
    }

    #[tokio::test]
    async fn test_buffer_clear_and_resize() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 2);

        let mut buffer = pool.acquire();

        // Write data using copy_from_slice
        let data = vec![42u8; 101];
        buffer.copy_from_slice(&data);
        assert_eq!(buffer.initialized(), 101);

        // Drop returns it to pool
        drop(buffer);

        // Get it again - may contain old data (performance optimization)
        let buffer2 = pool.acquire();
        assert_eq!(buffer2.capacity(), 4096);
        // Note: buffer may contain previous bytes outside the initialized range.
    }

    #[tokio::test]
    async fn test_buffer_pool_max_size_enforcement() {
        let pool = BufferPool::new(BufferSize::try_new(512).unwrap(), 3);

        // Get all buffers
        let buf1 = pool.acquire();
        let buf2 = pool.acquire();
        let buf3 = pool.acquire();

        // Get one more (should create new)
        let buf4 = pool.acquire();

        // Drop all buffers (automatically returned)
        drop(buf1);
        drop(buf2);
        drop(buf3);
        drop(buf4);

        // Pool should not exceed max size
        // (We can't directly test pool size, but the implementation handles it)
    }

    #[tokio::test]
    async fn test_buffer_wrong_size_not_returned() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 2);

        let buffer = pool.acquire();
        assert_eq!(buffer.capacity(), 4096);

        // PooledBuffer auto-returns on drop with correct size enforcement in Drop impl
        drop(buffer);
    }

    #[tokio::test]
    async fn test_buffer_pool_multiple_get_return_cycles() {
        let pool = BufferPool::new(BufferSize::try_new(4096).unwrap(), 5);

        // Do multiple get/return cycles
        for i in 0u8..20 {
            let mut buffer = pool.acquire();
            assert_eq!(buffer.capacity(), 4096);

            // Write some data using copy_from_slice
            let data = vec![i; 1];
            buffer.copy_from_slice(&data);
            assert_eq!(buffer.initialized(), 1);
        }
    }

    #[test]
    fn test_buffer_pool_clone() {
        let pool1 = BufferPool::new(BufferSize::try_new(1024).unwrap(), 5);
        let _pool2 = pool1;

        // Both should share the same underlying pool
        // (Arc ensures shared ownership)
    }

    #[tokio::test]
    async fn test_different_buffer_sizes() {
        let small_pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 5);
        let medium_pool = BufferPool::new(BufferSize::try_new(8192).unwrap(), 5);
        let large_pool = BufferPool::new(BufferSize::try_new(65536).unwrap(), 5);

        let small_buf = small_pool.acquire();
        let medium_buf = medium_pool.acquire();
        let large_buf = large_pool.acquire();

        assert_eq!(small_buf.capacity(), 4096);
        assert_eq!(medium_buf.capacity(), 8192);
        assert_eq!(large_buf.capacity(), 65536);

        // Buffers auto-return on drop
    }

    #[tokio::test]
    async fn test_buffer_pool_stress() {
        let pool = BufferPool::new(BufferSize::try_new(4096).unwrap(), 10);

        // Stress test with many concurrent operations
        let mut handles = vec![];

        for _ in 0..100 {
            let pool_clone = pool.clone();
            let handle = tokio::spawn(async move {
                for _ in 0..10 {
                    let buffer = pool_clone.acquire();
                    assert_eq!(buffer.capacity(), 4096);
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.await.unwrap();
        }
    }

    #[tokio::test]
    async fn test_pooled_buffer_deref() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 5);
        let mut buffer = pool.acquire();

        // Initially no initialized bytes
        assert_eq!(buffer.len(), 0);

        // Write data
        buffer.copy_from_slice(b"Hello");

        // Deref should return only initialized portion
        assert_eq!(buffer.len(), 5);
        assert_eq!(&*buffer, b"Hello");
    }

    #[tokio::test]
    async fn test_pooled_buffer_as_ref() {
        let pool = BufferPool::new(BufferSize::try_new(512).unwrap(), 5);
        let mut buffer = pool.acquire();

        buffer.copy_from_slice(b"Test data");

        // AsRef should return initialized portion
        let slice: &[u8] = buffer.as_ref();
        assert_eq!(slice, b"Test data");
        assert_eq!(slice.len(), 9);
    }

    #[tokio::test]
    async fn test_copy_from_slice_updates_initialized() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 5);
        let mut buffer = pool.acquire();

        assert_eq!(buffer.initialized(), 0);

        buffer.copy_from_slice(b"abc");
        assert_eq!(buffer.initialized(), 3);

        buffer.copy_from_slice(b"longer text");
        assert_eq!(buffer.initialized(), 11);
    }

    #[tokio::test]
    #[should_panic(expected = "data exceeds buffer capacity")]
    async fn test_copy_from_slice_panic_on_overflow() {
        let pool = BufferPool::new(BufferSize::try_new(10).unwrap(), 5);
        let mut buffer = pool.acquire();

        let too_large = vec![0u8; buffer.capacity() + 1];
        buffer.copy_from_slice(&too_large); // Should panic
    }

    #[tokio::test]
    async fn test_buffer_pool_debug() {
        let pool = BufferPool::new(BufferSize::try_new(2048).unwrap(), 5);
        let debug_str = format!("{pool:?}");
        assert!(debug_str.contains("BufferPool"));
    }

    #[tokio::test]
    async fn test_buffer_initialized_tracking() {
        let pool = BufferPool::new(BufferSize::try_new(1024).unwrap(), 5);
        let mut buffer = pool.acquire();

        // Test multiple writes update initialized correctly
        buffer.copy_from_slice(b"First");
        assert_eq!(buffer.initialized(), 5);
        assert_eq!(&*buffer, b"First");

        buffer.copy_from_slice(b"Second write");
        assert_eq!(buffer.initialized(), 12);
        assert_eq!(&*buffer, b"Second write");
    }

    #[tokio::test]
    async fn test_buffer_capacity_vs_initialized() {
        let pool = BufferPool::new(BufferSize::try_new(8192).unwrap(), 5);
        let mut buffer = pool.acquire();

        // Capacity is full buffer size
        assert_eq!(buffer.capacity(), 8192);

        // Initialized is what we've written
        assert_eq!(buffer.initialized(), 0);

        buffer.copy_from_slice(b"Small");
        assert_eq!(buffer.capacity(), 8192);
        assert_eq!(buffer.initialized(), 5);
    }

    #[tokio::test]
    async fn test_empty_slice_copy() {
        let pool = BufferPool::new(BufferSize::try_new(512).unwrap(), 5);
        let mut buffer = pool.acquire();

        // Copying empty slice should work
        buffer.copy_from_slice(&[]);
        assert_eq!(buffer.initialized(), 0);
        assert_eq!(&*buffer, b"");
    }

    #[tokio::test]
    async fn test_buffer_reuse_preserves_capacity() {
        let pool = BufferPool::new(BufferSize::try_new(2048).unwrap(), 5);

        {
            let mut buffer = pool.acquire();
            buffer.copy_from_slice(b"test");
            assert_eq!(buffer.capacity(), 4096);
        } // Drop returns to pool

        let buffer2 = pool.acquire();
        // Should have same capacity when reused
        assert_eq!(buffer2.capacity(), 4096);
    }

    #[test]
    fn test_buffer_size_alignment() {
        // Test that create_aligned_buffer aligns to page boundaries
        let buffer = BufferPool::create_aligned_buffer(1000);
        // Should be aligned to 4096
        assert_eq!(buffer.len(), 0);
        assert_eq!(buffer.capacity() % 4096, 0);

        let buffer2 = BufferPool::create_aligned_buffer(8192);
        assert_eq!(buffer2.len(), 0);
        assert_eq!(buffer2.capacity() % 4096, 0);
    }
}