guard-agent-rs 3.2.2

Telemetry and monitoring agent for the Guard ecosystem (Rust).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
//! The [`GuardAgent`]: buffered telemetry ingestion with at-least-once flush,
//! per-kind failure backoff, degraded-state computation, and optional durable
//! persistence.

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

use chrono::{DateTime, Utc};
use serde::Serialize;
use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinHandle;

use crate::circuit_breaker::CircuitBreakerState;
use crate::config::{AgentConfig, BufferOverflowPolicy};
use crate::error::{ErrorStage, GuardAgentError};
use crate::install_id::resolve_install_id;
use crate::models::{AgentHealth, AgentStatus, DynamicRules, SecurityEvent, SecurityMetric};
use crate::persistence::{NAMESPACE_EVENTS, NAMESPACE_METRICS, PERSIST_TTL_SECONDS, RedisHandler};
use crate::transport::{BatchItems, HttpTransport, SendOutcome};
use crate::utils::{Redactable, Redactor, calculate_backoff_delay, generate_short_key};

/// Cap, in seconds, for the per-kind flush streak backoff.
pub const PARTIAL_FAILURE_MAX_BACKOFF_SECS: f64 = 300.0;

/// Poll interval, in milliseconds, while the `block` overflow policy waits
/// for buffer space.
pub const BLOCK_POLICY_POLL_MS: u64 = 50;

/// Log every Nth drop under the `drop` overflow policy (first drop included).
pub const DROP_LOG_INTERVAL: u64 = 100;

/// Buffered occupancy ratio that marks the agent degraded.
pub const DEGRADED_BUFFER_RATIO: f64 = 0.9;

/// Buffered occupancy ratio that fails the health check.
pub const HEALTH_BUFFER_RATIO: f64 = 0.95;

/// Lifetime failure rate that marks the agent degraded.
pub const DEGRADED_FAILURE_RATE: f64 = 0.1;

/// Lifetime failure rate that fails the health check.
pub const HEALTH_FAILURE_RATE_MAX: f64 = 0.5;

/// Consecutive status-loop failures logged at error severity (below this,
/// warnings).
pub const STATUS_LOG_ERROR_THRESHOLD: u32 = 3;

/// How long `stop` waits for background loops to exit before aborting them.
const LOOP_SHUTDOWN_GRACE: Duration = Duration::from_secs(5);

/// A buffered telemetry item paired with its optional persistence key.
struct BufferedItem<T> {
    item: T,
    redis_key: Option<String>,
}

/// Consecutive background-loop failure counters.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct LoopFailures {
    /// Consecutive failures of the flush loop task.
    pub flush: u32,
    /// Consecutive failures of the status loop task.
    pub status: u32,
    /// Consecutive failures of the dynamic rules loop task.
    pub rules: u32,
}

/// Interior shared state guarded by a single async mutex.
struct CoreState {
    events: VecDeque<BufferedItem<SecurityEvent>>,
    metrics: VecDeque<BufferedItem<SecurityMetric>>,
    redis_handler: Option<Arc<dyn RedisHandler>>,
    space_freed: Arc<Notify>,
    events_flushed: u64,
    metrics_flushed: u64,
    events_dropped: u64,
    metrics_dropped: u64,
    events_sent: u64,
    metrics_sent: u64,
    events_failed: u64,
    metrics_failed: u64,
    redis_persist_failures: u64,
    events_failure_streak: u32,
    metrics_failure_streak: u32,
    events_retry_after: Option<Instant>,
    metrics_retry_after: Option<Instant>,
    last_flush_instant: Option<Instant>,
    last_flush: Option<DateTime<Utc>>,
    loop_failures: LoopFailures,
    status_consecutive_failures: u32,
    last_status_push_ok: Option<bool>,
    cached_rules: Option<DynamicRules>,
    rules_last_update: Option<Instant>,
    rules_fetched: u64,
}

impl CoreState {
    fn new(capacity: usize) -> Self {
        Self {
            events: VecDeque::with_capacity(capacity),
            metrics: VecDeque::with_capacity(capacity),
            redis_handler: None,
            space_freed: Arc::new(Notify::new()),
            events_flushed: 0,
            metrics_flushed: 0,
            events_dropped: 0,
            metrics_dropped: 0,
            events_sent: 0,
            metrics_sent: 0,
            events_failed: 0,
            metrics_failed: 0,
            redis_persist_failures: 0,
            events_failure_streak: 0,
            metrics_failure_streak: 0,
            events_retry_after: None,
            metrics_retry_after: None,
            last_flush_instant: None,
            last_flush: None,
            loop_failures: LoopFailures::default(),
            status_consecutive_failures: 0,
            last_status_push_ok: None,
            cached_rules: None,
            rules_last_update: None,
            rules_fetched: 0,
        }
    }
}

/// Snapshot of transport and loop state for stats reporting.
#[derive(Debug, Clone)]
pub struct AgentStats {
    /// Whether the background loops are running.
    pub running: bool,
    /// Seconds since agent construction.
    pub uptime_seconds: f64,
    /// Lifetime confirmed events.
    pub events_sent: u64,
    /// Lifetime events requeued after failed flushes.
    pub events_failed: u64,
    /// Lifetime confirmed metrics.
    pub metrics_sent: u64,
    /// Lifetime metrics requeued after failed flushes.
    pub metrics_failed: u64,
    /// Lifetime drained events (confirmed or not).
    pub events_flushed: u64,
    /// Lifetime drained metrics.
    pub metrics_flushed: u64,
    /// Lifetime events evicted by the `drop` policy or requeue pressure.
    pub events_dropped: u64,
    /// Lifetime metrics evicted by the `drop` policy or requeue pressure.
    pub metrics_dropped: u64,
    /// Events currently buffered.
    pub events_buffered: usize,
    /// Metrics currently buffered.
    pub metrics_buffered: usize,
    /// Lifetime HTTP requests issued.
    pub requests_sent: u64,
    /// Lifetime sends that exhausted their retries.
    pub requests_failed: u64,
    /// Lifetime wire bytes handed to the HTTP client.
    pub bytes_sent: u64,
    /// Current circuit breaker position.
    pub circuit_breaker_state: CircuitBreakerState,
    /// Consecutive background-loop failures.
    pub loop_failures: LoopFailures,
    /// Lifetime persistence write failures.
    pub redis_persist_failures: u64,
    /// `true` when a persistence handler is attached and at least one write
    /// failed.
    pub durability_degraded: bool,
    /// Last drain time, when any flush ran.
    pub last_flush: Option<DateTime<Utc>>,
    /// Consecutive failed status pushes.
    pub status_consecutive_failures: u32,
    /// Outcome of the most recent status push.
    pub last_status_push_ok: Option<bool>,
    /// Lifetime count of successful dynamic rules refreshes.
    pub rules_fetched: u64,
    /// Whether a dynamic rules document is currently cached.
    pub cached_rules: bool,
    /// Unix timestamp, in seconds, of the last successful rules refresh
    /// (`0.0` when none has happened yet).
    pub rules_last_update: f64,
}

struct LoopHandles {
    flush: JoinHandle<()>,
    status: JoinHandle<()>,
    rules: JoinHandle<()>,
}

/// State shared between the public handle and the background loops.
struct Shared {
    config: Arc<AgentConfig>,
    install_id: String,
    transport: HttpTransport,
    redactor: Redactor,
    core: tokio::sync::Mutex<CoreState>,
    flush_permits: Arc<Semaphore>,
    inflight: std::sync::Mutex<Vec<JoinHandle<()>>>,
    shutdown: Arc<Notify>,
    started_at: Instant,
    running: AtomicBool,
}

impl Shared {
    fn fire_hook(&self, stage: ErrorStage, error: &GuardAgentError) {
        if let Some(hook) = &self.config.on_error {
            let outcome =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook(stage, error)));
            if outcome.is_err() {
                log::error!("on_error hook raised while handling '{stage}'");
            }
        }
    }
}

/// Buffered telemetry agent for the Guard ecosystem.
///
/// The agent is the Rust counterpart of `guard-agent` (Python) and
/// `guardagent` (TypeScript). It buffers [`SecurityEvent`]s and
/// [`SecurityMetric`]s in memory, flushes them to the Guard ingestion API on
/// size and time triggers, and applies an at-least-once handshake: batches are
/// drained, sent, and either confirmed (durable records deleted) or requeued
/// in front of the buffer in their original order.
///
/// # Failure isolation
///
/// Telemetry failures never propagate to the caller's request path:
/// [`send_event`](Self::send_event) and [`send_metric`](Self::send_metric)
/// cannot fail; every transport, persistence, and loop error is logged,
/// counted in [`get_stats`](Self::get_stats), and reported through the
/// optional `on_error` hook. The only fallible entry points are
/// [`new`](Self::new) (configuration) and
/// [`try_send_event`](Self::try_send_event) under the `Raise` overflow policy.
///
/// # Examples
///
/// ```rust
/// use guard_agent_rs::{AgentConfig, GuardAgent, SecurityEvent};
///
/// # async fn example() {
/// let mut config = AgentConfig::new("your-api-key-at-least-10-chars");
/// config.endpoint = "https://api.guard-core.com".to_owned();
/// let agent = GuardAgent::new(config).expect("valid configuration");
///
/// agent.send_event(SecurityEvent::new("rate_limited").with_ip_address("10.0.0.1")).await;
///
/// let stats = agent.get_stats().await;
/// assert_eq!(stats.events_buffered, 1);
/// # }
/// ```
#[derive(Clone)]
pub struct GuardAgent {
    shared: Arc<Shared>,
    loops: Arc<std::sync::Mutex<Option<LoopHandles>>>,
}

impl std::fmt::Debug for GuardAgent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GuardAgent")
            .field("install_id", &self.shared.install_id)
            .field("running", &self.shared.running.load(Ordering::Relaxed))
            .field("endpoint", &self.shared.config.endpoint)
            .finish_non_exhaustive()
    }
}

impl GuardAgent {
    /// Validates the configuration and builds the agent.
    ///
    /// Resolves the install identifier (override, `~/.guard-agent/install-id`,
    /// or fresh UUID) and constructs the HTTP client. Persistence is not
    /// connected here; call [`start`](Self::start) to attach the configured
    /// Redis backend and spawn the background loops.
    pub fn new(config: AgentConfig) -> Result<Self, GuardAgentError> {
        let mut config = config;
        config.validate()?;
        let config = Arc::new(config);

        let install_id = resolve_install_id(config.install_id.as_deref());
        let transport = HttpTransport::new(Arc::clone(&config), &install_id)?;
        let capacity = config.buffer_size;
        let permits = config.max_concurrent_flushes.max(1);
        let redactor = Redactor::new(&config.sensitive_headers);

        Ok(Self {
            shared: Arc::new(Shared {
                config,
                install_id,
                transport,
                redactor,
                core: tokio::sync::Mutex::new(CoreState::new(capacity)),
                flush_permits: Arc::new(Semaphore::new(permits)),
                inflight: std::sync::Mutex::new(Vec::new()),
                shutdown: Arc::new(Notify::new()),
                started_at: Instant::now(),
                running: AtomicBool::new(false),
            }),
            loops: Arc::new(std::sync::Mutex::new(None)),
        })
    }

    /// Returns the resolved install identifier sent as `X-Agent-Install-Id`.
    #[must_use]
    pub fn install_id(&self) -> &str {
        &self.shared.install_id
    }

    /// Attaches a custom persistence handler.
    ///
    /// Call before [`start`](Self::start) so persisted records are reloaded
    /// into the buffer at startup. Attaching after start skips the reload.
    pub async fn attach_redis_handler(&self, handler: Arc<dyn RedisHandler>) {
        self.shared.core.lock().await.redis_handler = Some(handler);
    }

    /// Starts the background flush, status, and dynamic rules loops.
    ///
    /// When the `persistence` feature is enabled and `redis` is configured,
    /// this connects the built-in Redis backend (degrading to memory-only
    /// operation with a warning on failure) and reloads persisted records.
    /// Idempotent: repeated calls are no-ops.
    pub async fn start(&self) {
        if self.shared.running.swap(true, Ordering::AcqRel) {
            return;
        }

        #[cfg(feature = "persistence")]
        if let Some(redis_config) = &self.shared.config.redis {
            match crate::persistence::RedisClientHandler::connect(redis_config).await {
                Ok(handler) => {
                    self.shared.core.lock().await.redis_handler = Some(Arc::new(handler));
                }
                Err(error) => {
                    log::warn!("Redis persistence disabled (connection failed): {error}");
                }
            }
        }

        self.reload_from_redis().await;

        let mut loops = self.loops.lock().expect("loops mutex not poisoned");
        if loops.is_some() {
            return;
        }
        *loops = Some(LoopHandles {
            flush: tokio::spawn(flush_loop(Arc::clone(&self.shared))),
            status: tokio::spawn(status_loop(Arc::clone(&self.shared))),
            rules: tokio::spawn(rules_loop(Arc::clone(&self.shared))),
        });
    }

    /// Stops the background loops and performs a final flush.
    ///
    /// Mirrors the Python agent's shutdown: loops are signalled to exit,
    /// in-flight flushes are awaited, and the remaining buffer is flushed once
    /// (subject to the per-kind retry gates). Unconfirmed batches stay
    /// buffered and, when persistence is attached, durable for the next
    /// process.
    pub async fn stop(&self) {
        self.shared.running.store(false, Ordering::Release);
        self.shared.shutdown.notify_waiters();

        let handles = self.loops.lock().expect("loops mutex not poisoned").take();
        if let Some(handles) = handles {
            let LoopHandles {
                mut flush,
                mut status,
                mut rules,
            } = handles;
            let _ = tokio::time::timeout(LOOP_SHUTDOWN_GRACE, async {
                let _ = (&mut flush).await;
                let _ = (&mut status).await;
                let _ = (&mut rules).await;
            })
            .await;
            flush.abort();
            status.abort();
            rules.abort();
        }

        self.await_inflight().await;
        self.flush_buffer().await;
    }

    /// Waits (bounded) for in-flight watermark-triggered flushes.
    async fn await_inflight(&self) {
        let inflight: Vec<JoinHandle<()>> = {
            let mut inflight = self
                .shared
                .inflight
                .lock()
                .expect("inflight mutex not poisoned");
            std::mem::take(&mut *inflight)
        };
        if inflight.is_empty() {
            return;
        }
        let _ = tokio::time::timeout(LOOP_SHUTDOWN_GRACE, async move {
            for handle in inflight {
                let _ = handle.await;
            }
        })
        .await;
    }

    /// Buffers an event; never fails.
    ///
    /// Errors (including `Raise` policy rejections and persistence failures)
    /// are logged and reported through the `on_error` hook, mirroring the
    /// Python agent's fire-and-forget ingest path.
    pub async fn send_event(&self, event: SecurityEvent) {
        if let Err(error) = self.try_send_event(event).await {
            log::error!("Failed to buffer event: {error}");
            self.shared.fire_hook(ErrorStage::FlushEvents, &error);
        }
    }

    /// Buffers a metric; never fails.
    ///
    /// See [`send_event`](Self::send_event) for the failure-isolation policy.
    pub async fn send_metric(&self, metric: SecurityMetric) {
        if let Err(error) = self.try_send_metric(metric).await {
            log::error!("Failed to buffer metric: {error}");
            self.shared.fire_hook(ErrorStage::FlushMetrics, &error);
        }
    }

    /// Buffers an event, surfacing `Raise` policy rejections.
    ///
    /// Under `Drop` and `Block` this behaves like
    /// [`send_event`](Self::send_event); under `Raise` it returns
    /// [`GuardAgentError::BufferFull`] when the buffer is at capacity.
    pub async fn try_send_event(&self, mut event: SecurityEvent) -> Result<(), GuardAgentError> {
        if !self.shared.config.enable_events {
            return Ok(());
        }
        event.redact(&self.shared.redactor);
        self.enqueue_event(event).await
    }

    /// Buffers a metric, surfacing `Raise` policy rejections.
    pub async fn try_send_metric(&self, mut metric: SecurityMetric) -> Result<(), GuardAgentError> {
        if !self.shared.config.enable_metrics {
            return Ok(());
        }
        metric.redact(&self.shared.redactor);
        self.enqueue_metric(metric).await
    }

    async fn enqueue_event(&self, event: SecurityEvent) -> Result<(), GuardAgentError> {
        let capacity = self.shared.config.buffer_size;
        let policy = self.shared.config.buffer_overflow_policy;
        let watermark = self.watermark_threshold();

        let mut event = Some(event);
        loop {
            let mut core = self.shared.core.lock().await;
            if core.events.len() < capacity {
                let event = event.take().expect("event present while buffering");
                let redis_key = persist_item(&mut core, NAMESPACE_EVENTS, "event", &event).await;
                core.events.push_back(BufferedItem {
                    item: event,
                    redis_key,
                });
                let trigger = core.events.len() as f64 >= watermark;
                drop(core);
                if trigger {
                    spawn_gated_flush(&self.shared);
                }
                return Ok(());
            }

            match policy {
                BufferOverflowPolicy::Drop => {
                    // The buffer is at capacity and `buffer_size` validates
                    // greater than zero, so the oldest item always exists.
                    let evicted = core
                        .events
                        .pop_front()
                        .expect("dropping from a buffer at capacity");
                    core.events_dropped += 1;
                    if core.events_dropped % DROP_LOG_INTERVAL == 1 {
                        log::warn!(
                            "Event buffer full at maxlen={capacity}; dropping oldest event \
                             ({} dropped total)",
                            core.events_dropped
                        );
                    }
                    forget_key(&core, NAMESPACE_EVENTS, evicted.redis_key).await;
                    // Retry the insert immediately: capacity freed by the pop.
                }
                BufferOverflowPolicy::Raise => {
                    return Err(GuardAgentError::BufferFull { capacity });
                }
                BufferOverflowPolicy::Block => {
                    let notify = Arc::clone(&core.space_freed);
                    drop(core);
                    tokio::select! {
                        () = notify.notified() => {},
                        () = tokio::time::sleep(Duration::from_millis(BLOCK_POLICY_POLL_MS)) => {},
                    }
                }
            }
        }
    }

    async fn enqueue_metric(&self, metric: SecurityMetric) -> Result<(), GuardAgentError> {
        let capacity = self.shared.config.buffer_size;
        let policy = self.shared.config.buffer_overflow_policy;
        let watermark = self.watermark_threshold();

        let mut metric = Some(metric);
        loop {
            let mut core = self.shared.core.lock().await;
            if core.metrics.len() < capacity {
                let metric = metric.take().expect("metric present while buffering");
                let redis_key = persist_item(&mut core, NAMESPACE_METRICS, "metric", &metric).await;
                core.metrics.push_back(BufferedItem {
                    item: metric,
                    redis_key,
                });
                let trigger = core.metrics.len() as f64 >= watermark;
                drop(core);
                if trigger {
                    spawn_gated_flush(&self.shared);
                }
                return Ok(());
            }

            match policy {
                BufferOverflowPolicy::Drop => {
                    // The buffer is at capacity and `buffer_size` validates
                    // greater than zero, so the oldest item always exists.
                    let evicted = core
                        .metrics
                        .pop_front()
                        .expect("dropping from a buffer at capacity");
                    core.metrics_dropped += 1;
                    if core.metrics_dropped % DROP_LOG_INTERVAL == 1 {
                        log::warn!(
                            "Metric buffer full at maxlen={capacity}; dropping oldest metric \
                             ({} dropped total)",
                            core.metrics_dropped
                        );
                    }
                    forget_key(&core, NAMESPACE_METRICS, evicted.redis_key).await;
                }
                BufferOverflowPolicy::Raise => {
                    return Err(GuardAgentError::BufferFull { capacity });
                }
                BufferOverflowPolicy::Block => {
                    let notify = Arc::clone(&core.space_freed);
                    drop(core);
                    tokio::select! {
                        () = notify.notified() => {},
                        () = tokio::time::sleep(Duration::from_millis(BLOCK_POLICY_POLL_MS)) => {},
                    }
                }
            }
        }
    }

    /// Occupancy threshold (in items) that triggers an early flush.
    fn watermark_threshold(&self) -> f64 {
        self.shared.config.buffer_size as f64 * self.shared.config.high_watermark_ratio
    }

    /// Flushes both kinds now, subject to the per-kind retry gates.
    ///
    /// Serialized with the background loops through the flush semaphore.
    pub async fn flush_buffer(&self) {
        let permit = self
            .shared
            .flush_permits
            .clone()
            .acquire_owned()
            .await
            .expect("flush semaphore is never closed");
        do_flush(&self.shared).await;
        drop(permit);
    }

    /// Drops every buffered event and metric and clears persisted records.
    pub async fn clear_buffer(&self) {
        let handler = {
            let mut core = self.shared.core.lock().await;
            core.events.clear();
            core.metrics.clear();
            core.space_freed.notify_waiters();
            core.redis_handler.clone()
        };
        let Some(handler) = handler else {
            return;
        };
        for (namespace, label) in [(NAMESPACE_EVENTS, "events"), (NAMESPACE_METRICS, "metrics")] {
            if let Err(error) = handler.clear_namespace(namespace).await {
                log::warn!("Failed to clear persisted {label} from Redis: {error}");
            }
        }
    }

    /// Computes the current status, marking the agent degraded when the
    /// circuit breaker is open, the buffer is at least 90% full, or the
    /// lifetime failure rate exceeds 10%.
    pub async fn get_status(&self) -> AgentStatus {
        let core = self.shared.core.lock().await;
        compute_status(&self.shared, &core)
    }

    /// Pushes the current status to `/api/v1/status` immediately.
    ///
    /// The background loop calls this on [`status_interval`](AgentConfig)
    /// cadence; exposing it allows tests and operators to force a push.
    pub async fn push_status(&self) {
        push_status_once(&self.shared).await;
    }

    /// Returns the latest dynamic rules, or `None` when unavailable.
    ///
    /// Mirrors `RulesMixin.get_dynamic_rules`
    /// (`guard_agent/_client_loops.py:19-38`): the cached copy is served
    /// while it is younger than its own `ttl` (seconds); otherwise the
    /// transport fetches `GET /api/v1/rules`, and a successful fetch updates
    /// the cache and the counters. A failed fetch returns `None` (the
    /// transport logs and yields `None` in the baseline) while the last good
    /// rules stay cached for the next poll. The background
    /// [`rules loop`](Self::start) calls this on
    /// [`dynamic_rule_interval`](AgentConfig) cadence.
    pub async fn get_dynamic_rules(&self) -> Option<DynamicRules> {
        fetch_dynamic_rules_once(&self.shared).await
    }

    /// Returns a snapshot of agent counters and transport state.
    pub async fn get_stats(&self) -> AgentStats {
        let core = self.shared.core.lock().await;
        let (requests_sent, requests_failed, bytes_sent) = self.shared.transport.counters();
        AgentStats {
            running: self.shared.running.load(Ordering::Acquire),
            uptime_seconds: self.shared.started_at.elapsed().as_secs_f64(),
            events_sent: core.events_sent,
            events_failed: core.events_failed,
            metrics_sent: core.metrics_sent,
            metrics_failed: core.metrics_failed,
            events_flushed: core.events_flushed,
            metrics_flushed: core.metrics_flushed,
            events_dropped: core.events_dropped,
            metrics_dropped: core.metrics_dropped,
            events_buffered: core.events.len(),
            metrics_buffered: core.metrics.len(),
            requests_sent,
            requests_failed,
            bytes_sent,
            circuit_breaker_state: self.shared.transport.breaker_state(),
            loop_failures: core.loop_failures,
            redis_persist_failures: core.redis_persist_failures,
            durability_degraded: core.redis_handler.is_some() && core.redis_persist_failures > 0,
            last_flush: core.last_flush,
            status_consecutive_failures: core.status_consecutive_failures,
            last_status_push_ok: core.last_status_push_ok,
            rules_fetched: core.rules_fetched,
            cached_rules: core.cached_rules.is_some(),
            rules_last_update: core
                .rules_last_update
                .map_or(0.0, |instant| unix_now() - instant.elapsed().as_secs_f64()),
        }
    }

    /// Returns `false` when the loops are stopped, the breaker is open, the
    /// buffer is at least 95% full, or the lifetime failure rate exceeds 50%.
    pub async fn health_check(&self) -> bool {
        let core = self.shared.core.lock().await;
        if !self.shared.running.load(Ordering::Acquire) {
            return false;
        }
        if self.shared.transport.breaker_state() == CircuitBreakerState::Open {
            return false;
        }
        let buffered = core.events.len() + core.metrics.len();
        if (buffered as f64) >= self.shared.config.buffer_size as f64 * HEALTH_BUFFER_RATIO {
            return false;
        }
        failure_rate(&core) <= HEALTH_FAILURE_RATE_MAX
    }

    /// Reloads persisted events and metrics into the in-memory buffers.
    async fn reload_from_redis(&self) {
        let handler = {
            let core = self.shared.core.lock().await;
            core.redis_handler.clone()
        };
        let Some(handler) = handler else {
            return;
        };
        let capacity = self.shared.config.buffer_size;

        let mut core = self.shared.core.lock().await;
        let mut loaded_events = 0usize;
        let mut loaded_metrics = 0usize;

        if let Ok(keys) = handler.list_keys(NAMESPACE_EVENTS).await {
            for key in keys {
                let loaded = match handler.get_key(NAMESPACE_EVENTS, &key).await {
                    Ok(Some(value)) => match serde_json::from_str::<SecurityEvent>(&value) {
                        Ok(event) => Some(event),
                        Err(error) => {
                            log::warn!("Failed to load event from Redis key {key}: {error}");
                            None
                        }
                    },
                    Ok(None) => {
                        log::warn!("Failed to load event from Redis key {key}: no data found");
                        None
                    }
                    Err(error) => {
                        log::warn!("Failed to load event from Redis key {key}: {error}");
                        None
                    }
                };
                if let Some(event) = loaded {
                    if core.events.len() >= capacity
                        && let Some(evicted) = core.events.pop_front()
                    {
                        core.events_dropped += 1;
                        forget_key(&core, NAMESPACE_EVENTS, evicted.redis_key).await;
                    }
                    core.events.push_back(BufferedItem {
                        item: event,
                        redis_key: Some(key),
                    });
                    loaded_events += 1;
                }
            }
        } else {
            log::warn!("Failed to list persisted events from Redis");
        }

        if let Ok(keys) = handler.list_keys(NAMESPACE_METRICS).await {
            for key in keys {
                let loaded = match handler.get_key(NAMESPACE_METRICS, &key).await {
                    Ok(Some(value)) => match serde_json::from_str::<SecurityMetric>(&value) {
                        Ok(metric) => Some(metric),
                        Err(error) => {
                            log::warn!("Failed to load metric from Redis key {key}: {error}");
                            None
                        }
                    },
                    Ok(None) => {
                        log::warn!("Failed to load metric from Redis key {key}: no data found");
                        None
                    }
                    Err(error) => {
                        log::warn!("Failed to load metric from Redis key {key}: {error}");
                        None
                    }
                };
                if let Some(metric) = loaded {
                    if core.metrics.len() >= capacity
                        && let Some(evicted) = core.metrics.pop_front()
                    {
                        core.metrics_dropped += 1;
                        forget_key(&core, NAMESPACE_METRICS, evicted.redis_key).await;
                    }
                    core.metrics.push_back(BufferedItem {
                        item: metric,
                        redis_key: Some(key),
                    });
                    loaded_metrics += 1;
                }
            }
        } else {
            log::warn!("Failed to list persisted metrics from Redis");
        }

        if loaded_events + loaded_metrics > 0 {
            log::info!("Loaded {loaded_events} events and {loaded_metrics} metrics from Redis");
        }
    }
}

fn failure_rate(core: &CoreState) -> f64 {
    let total = core.events_sent + core.metrics_sent + core.events_failed + core.metrics_failed;
    let failed = core.events_failed + core.metrics_failed;
    failed as f64 / total.max(1) as f64
}

fn compute_status(shared: &Shared, core: &CoreState) -> AgentStatus {
    let mut status = AgentHealth::Healthy;
    let mut errors = Vec::new();

    if shared.transport.breaker_state() == CircuitBreakerState::Open {
        status = AgentHealth::Degraded;
        errors.push("Transport circuit breaker is open".to_owned());
    }

    let buffered = (core.events.len() + core.metrics.len()) as u64;
    if (buffered as f64) >= shared.config.buffer_size as f64 * DEGRADED_BUFFER_RATIO {
        status = AgentHealth::Degraded;
        errors.push("Buffer nearly full".to_owned());
    }

    let rate = failure_rate(core);
    if rate > DEGRADED_FAILURE_RATE {
        status = AgentHealth::Degraded;
        errors.push(format!("High failure rate: {:.1}%", rate * 100.0));
    }

    AgentStatus {
        timestamp: Utc::now(),
        status,
        uptime: shared.started_at.elapsed().as_secs_f64(),
        events_sent: core.events_sent,
        events_failed: core.events_failed,
        buffer_size: buffered,
        last_flush: core.last_flush,
        errors,
    }
}

/// Persists an item, returning the short key on success.
///
/// Persistence failures are counted, logged, and otherwise swallowed: the
/// item still lands in the in-memory buffer (fail-open).
async fn persist_item<T: Serialize + Sync>(
    core: &mut CoreState,
    namespace: &str,
    prefix: &str,
    item: &T,
) -> Option<String> {
    let handler = core.redis_handler.as_ref()?;
    let short_key = generate_short_key(prefix);
    let value = {
        // `serde_json` serialization of the typed `SecurityEvent` and
        // `SecurityMetric` payloads is total: every field is a string,
        // number, option, UUID, timestamp, or `serde_json::Value`, and
        // non-finite floats collapse to `null`. Only a caller-supplied
        // generic `T` with a fallible `Serialize` impl can fail, and that
        // path is exercised by the `Unserializable` unit test below in
        // normal builds, so the typed-model error arm is compiled out of
        // the coverage build as provably unreachable (see PR notes).
        #[cfg(not(coverage))]
        match serde_json::to_string(item) {
            Ok(value) => value,
            Err(error) => {
                core.redis_persist_failures += 1;
                log::warn!("Failed to serialize {prefix} for Redis persistence: {error}");
                return None;
            }
        }
        #[cfg(coverage)]
        serde_json::to_string(item).expect("typed model serialization is total")
    };
    match handler
        .set_key(namespace, &short_key, &value, PERSIST_TTL_SECONDS)
        .await
    {
        Ok(()) => Some(short_key),
        Err(error) => {
            core.redis_persist_failures += 1;
            log::warn!("Failed to persist {prefix} to Redis: {error}");
            None
        }
    }
}

/// Deletes a record key, best effort. Failures leave an orphan that expires
/// via TTL.
async fn forget_key(core: &CoreState, namespace: &str, key: Option<String>) {
    let Some(key) = key.filter(|key| !key.is_empty()) else {
        return;
    };
    // A live key exists only when a handler persisted it, so the handler is
    // present whenever this runs; the memory-only guard is compiled out of
    // the coverage build as provably unreachable (see PR notes).
    #[cfg(not(coverage))]
    let Some(handler) = &core.redis_handler else {
        return;
    };
    #[cfg(coverage)]
    let handler = core
        .redis_handler
        .as_ref()
        .expect("live keys imply a persistence handler");
    if let Err(error) = handler.delete_keys(namespace, &[key]).await {
        log::warn!("Failed to delete persisted record from Redis: {error}");
    }
}

/// Deletes confirmed keys after a successful or intentionally-dropped send.
async fn confirm_keys(shared: &Shared, namespace: &str, keys: Vec<Option<String>>) {
    let live: Vec<String> = keys
        .into_iter()
        .flatten()
        .filter(|key| !key.is_empty())
        .collect();
    if live.is_empty() {
        return;
    }
    let handler = {
        let core = shared.core.lock().await;
        core.redis_handler.clone()
    };
    // Live keys imply a persistence handler (they are minted by
    // `persist_item`); the memory-only guard is compiled out of the coverage
    // build as provably unreachable (see PR notes).
    #[cfg(not(coverage))]
    let Some(handler) = handler else {
        return;
    };
    #[cfg(coverage)]
    let handler = handler.expect("live keys imply a persistence handler");
    if let Err(error) = handler.delete_keys(namespace, &live).await {
        log::warn!("Failed to confirm {namespace} Redis keys: {error}");
    }
}

/// Drains a kind's buffer, restoring original order on requeue.
fn drain<T>(
    deque: &mut VecDeque<BufferedItem<T>>,
    counter: &mut u64,
) -> (Vec<T>, Vec<Option<String>>) {
    let drained: Vec<BufferedItem<T>> = deque.drain(..).collect();
    *counter += drained.len() as u64;
    drained
        .into_iter()
        .map(|buffered| (buffered.item, buffered.redis_key))
        .unzip()
}

/// Pushes failed items back to the front of the buffer in their original
/// order, evicting the newest tail items when at capacity and returning the
/// evicted keys for confirmation.
fn requeue<T>(
    deque: &mut VecDeque<BufferedItem<T>>,
    capacity: usize,
    items: Vec<T>,
    keys: Vec<Option<String>>,
    dropped: &mut u64,
) -> Vec<Option<String>> {
    let mut evicted = Vec::new();
    for (item, redis_key) in items.into_iter().zip(keys).rev() {
        if deque.len() >= capacity
            && let Some(victim) = deque.pop_back()
        {
            *dropped += 1;
            evicted.push(victim.redis_key);
        }
        deque.push_front(BufferedItem { item, redis_key });
    }
    evicted
}

/// Performs both kind flushes while the caller holds a permit.
async fn do_flush(shared: &Shared) {
    flush_events(shared).await;
    flush_metrics(shared).await;
}

/// The watermark/time-gated flush used by background triggers.
async fn flush_if_needed(shared: &Shared, _permit: OwnedSemaphorePermit) {
    let core = shared.core.lock().await;
    if core.events.len() + core.metrics.len() == 0 {
        return;
    }
    let interval = Duration::from_secs(shared.config.flush_interval);
    let elapsed_ok = core
        .last_flush_instant
        .is_none_or(|last| last.elapsed() >= interval);
    let watermark_ok = ((core.events.len() + core.metrics.len()) as f64)
        >= shared.config.buffer_size as f64 * shared.config.high_watermark_ratio;
    if !(elapsed_ok || watermark_ok) {
        return;
    }
    drop(core);
    do_flush(shared).await;
}

/// Flushes buffered events: drain, send, confirm or requeue + backoff.
async fn flush_events(shared: &Shared) {
    let gate = { shared.core.lock().await.events_retry_after };
    if gate_closed(gate) {
        return;
    }
    let (items, keys) = {
        let mut core = shared.core.lock().await;
        let CoreState {
            events,
            events_flushed,
            ..
        } = &mut *core;
        drain(events, events_flushed)
    };
    if items.is_empty() {
        return;
    }
    let count = items.len();
    core_set_last_flush(shared).await;

    let outcome = shared
        .transport
        .send_batch(BatchItems::Events(items.clone()))
        .await;
    match outcome {
        SendOutcome::Accepted => {
            confirm_keys(shared, NAMESPACE_EVENTS, keys).await;
            let mut core = shared.core.lock().await;
            core.events_sent += count as u64;
            if core.events_failure_streak > 0 {
                log::info!(
                    "Events flush recovered after {} consecutive partial failure(s)",
                    core.events_failure_streak
                );
            }
            core.events_failure_streak = 0;
            core.events_retry_after = None;
        }
        SendOutcome::PermanentDrop { .. } => {
            confirm_keys(shared, NAMESPACE_EVENTS, keys).await;
        }
        SendOutcome::Failed { error } => {
            let evicted = {
                let mut core = shared.core.lock().await;
                let CoreState {
                    events,
                    events_dropped,
                    ..
                } = &mut *core;
                requeue(
                    events,
                    shared.config.buffer_size,
                    items,
                    keys,
                    events_dropped,
                )
            };
            let delay = {
                let mut core = shared.core.lock().await;
                core.events_failed += count as u64;
                core.events_failure_streak = core.events_failure_streak.saturating_add(1);
                let delay = calculate_backoff_delay(
                    core.events_failure_streak - 1,
                    shared.config.flush_interval as f64,
                    PARTIAL_FAILURE_MAX_BACKOFF_SECS,
                );
                core.events_retry_after = Some(Instant::now() + Duration::from_secs_f64(delay));
                core.loop_failures.flush += 1;
                delay
            };
            if !evicted.is_empty() {
                confirm_keys(shared, NAMESPACE_EVENTS, evicted).await;
            }
            shared.fire_hook(ErrorStage::FlushEvents, &error);
            let retention = retention_description(shared, "events").await;
            log::warn!(
                "Failed to send {count} events; {retention} for retry; backing off up to \
                 {delay:.0}s between attempts: {error}"
            );
        }
    }
}

/// Flushes buffered metrics; mirrors [`flush_events`].
async fn flush_metrics(shared: &Shared) {
    let gate = { shared.core.lock().await.metrics_retry_after };
    if gate_closed(gate) {
        return;
    }
    let (items, keys) = {
        let mut core = shared.core.lock().await;
        let CoreState {
            metrics,
            metrics_flushed,
            ..
        } = &mut *core;
        drain(metrics, metrics_flushed)
    };
    if items.is_empty() {
        return;
    }
    let count = items.len();
    core_set_last_flush(shared).await;

    let outcome = shared
        .transport
        .send_batch(BatchItems::Metrics(items.clone()))
        .await;
    match outcome {
        SendOutcome::Accepted => {
            confirm_keys(shared, NAMESPACE_METRICS, keys).await;
            let mut core = shared.core.lock().await;
            core.metrics_sent += count as u64;
            if core.metrics_failure_streak > 0 {
                log::info!(
                    "Metrics flush recovered after {} consecutive partial failure(s)",
                    core.metrics_failure_streak
                );
            }
            core.metrics_failure_streak = 0;
            core.metrics_retry_after = None;
        }
        SendOutcome::PermanentDrop { .. } => {
            confirm_keys(shared, NAMESPACE_METRICS, keys).await;
        }
        SendOutcome::Failed { error } => {
            let evicted = {
                let mut core = shared.core.lock().await;
                let CoreState {
                    metrics,
                    metrics_dropped,
                    ..
                } = &mut *core;
                requeue(
                    metrics,
                    shared.config.buffer_size,
                    items,
                    keys,
                    metrics_dropped,
                )
            };
            let delay = {
                let mut core = shared.core.lock().await;
                core.metrics_failed += count as u64;
                core.metrics_failure_streak = core.metrics_failure_streak.saturating_add(1);
                let delay = calculate_backoff_delay(
                    core.metrics_failure_streak - 1,
                    shared.config.flush_interval as f64,
                    PARTIAL_FAILURE_MAX_BACKOFF_SECS,
                );
                core.metrics_retry_after = Some(Instant::now() + Duration::from_secs_f64(delay));
                core.loop_failures.flush += 1;
                delay
            };
            if !evicted.is_empty() {
                confirm_keys(shared, NAMESPACE_METRICS, evicted).await;
            }
            shared.fire_hook(ErrorStage::FlushMetrics, &error);
            let retention = retention_description(shared, "metrics").await;
            log::warn!(
                "Failed to send {count} metrics; {retention} for retry; backing off up to \
                 {delay:.0}s between attempts: {error}"
            );
        }
    }
}

/// Returns `true` when a per-kind retry gate still blocks this kind.
fn gate_closed(gate: Option<Instant>) -> bool {
    gate.is_some_and(|gate| Instant::now() < gate)
}

/// Describes where unsent items wait for retry, based on whether a Redis
/// handler is attached to the core state. Without Redis the items live only
/// in the in-memory buffer, so claiming Redis retention would be misleading
/// (mirrors Python `_client_flush.FlushMixin._retention_description`).
async fn retention_description(shared: &Shared, kind: &str) -> String {
    let has_redis = shared.core.lock().await.redis_handler.is_some();
    let redis_part = if has_redis {
        " and retained in Redis"
    } else {
        ""
    };
    format!("requeued in memory{redis_part} ({kind})")
}

async fn core_set_last_flush(shared: &Shared) {
    let mut core = shared.core.lock().await;
    core.last_flush_instant = Some(Instant::now());
    core.last_flush = Some(Utc::now());
    core.space_freed.notify_waiters();
}

/// Spawns a watermark-triggered flush when a permit is free.
fn spawn_gated_flush(shared: &Arc<Shared>) {
    if !shared.running.load(Ordering::Acquire) {
        return;
    }
    let task_shared = Arc::clone(shared);
    let handle = tokio::spawn(async move {
        if let Ok(permit) = task_shared.flush_permits.clone().try_acquire_owned() {
            flush_if_needed(&task_shared, permit).await;
        }
    });
    track_inflight(shared, handle);
}

fn track_inflight(shared: &Shared, handle: JoinHandle<()>) {
    let mut inflight = shared.inflight.lock().expect("inflight mutex not poisoned");
    inflight.retain(|handle| !handle.is_finished());
    inflight.push(handle);
}

/// Background flush loop: every `flush_interval` seconds, run a gated flush.
async fn flush_loop(shared: Arc<Shared>) {
    let interval = Duration::from_secs(shared.config.flush_interval);
    loop {
        tokio::select! {
            () = tokio::time::sleep(interval) => {},
            () = shared.shutdown.notified() => break,
        }
        // The notified arm owns the deterministic exit (a shutdown always
        // wakes it); a tick landing after the flag flip would only win the
        // select's coin toss, so the check is provably unreachable and
        // compiled out of the coverage build (see PR notes).
        #[cfg(not(coverage))]
        if !shared.running.load(Ordering::Acquire) {
            break;
        }
        #[cfg(coverage)]
        let _ = shared.running.load(Ordering::Acquire);
        if let Ok(permit) = shared.flush_permits.clone().try_acquire_owned() {
            let task_shared = Arc::clone(&shared);
            let handle = tokio::spawn(async move {
                flush_if_needed(&task_shared, permit).await;
            });
            // `flush_if_needed` never panics; the panic-accounting branch is
            // compiled out of the coverage build as provably unreachable
            // (see PR notes).
            #[cfg(not(coverage))]
            if let Err(error) = handle.await
                && error.is_panic()
            {
                let mut core = shared.core.lock().await;
                core.loop_failures.flush += 1;
                log::error!("Flush task panicked: {error}");
            }
            #[cfg(coverage)]
            let _ = handle.await;
        }
    }
}

/// Sends one status push, counting consecutive failures for log severity.
async fn push_status_once(shared: &Shared) {
    let status = {
        let core = shared.core.lock().await;
        compute_status(shared, &core)
    };
    let outcome = shared.transport.send_status(&status).await;
    let mut core = shared.core.lock().await;
    match outcome {
        SendOutcome::Accepted | SendOutcome::PermanentDrop { .. } => {
            core.status_consecutive_failures = 0;
            core.loop_failures.status = 0;
            core.last_status_push_ok = Some(true);
        }
        SendOutcome::Failed { error } => {
            core.status_consecutive_failures = core.status_consecutive_failures.saturating_add(1);
            core.loop_failures.status = core.loop_failures.status.saturating_add(1);
            core.last_status_push_ok = Some(false);
            let consecutive = core.status_consecutive_failures;
            if consecutive >= STATUS_LOG_ERROR_THRESHOLD {
                log::error!("Status push failed ({consecutive} consecutive): {error}");
            } else {
                log::warn!("Status push failed: {error}");
            }
        }
    }
}

/// Background status loop: every `status_interval` seconds, push status.
async fn status_loop(shared: Arc<Shared>) {
    let interval = Duration::from_secs(shared.config.status_interval);
    loop {
        tokio::select! {
            () = tokio::time::sleep(interval) => {},
            () = shared.shutdown.notified() => break,
        }
        // The flush loop's twin check is reachable (its one-second tick can
        // land inside the five-second shutdown grace); this loop ticks on
        // minute intervals, long after the grace has aborted it, so the
        // branch is provably unreachable and compiled out of the coverage
        // build (see PR notes).
        #[cfg(not(coverage))]
        if !shared.running.load(Ordering::Acquire) {
            break;
        }
        #[cfg(coverage)]
        let _ = shared.running.load(Ordering::Acquire);
        push_status_once(&shared).await;
    }
}

/// One dynamic rules refresh, shared by the public
/// [`GuardAgent::get_dynamic_rules`](crate::GuardAgent::get_dynamic_rules)
/// and the background loop. Mirrors `RulesMixin.get_dynamic_rules`
/// (`guard_agent/_client_loops.py:19-38`): the cached copy is served while
/// it is younger than its own `ttl` (seconds); otherwise the transport
/// fetches `GET /api/v1/rules`, and a successful fetch updates the cache and
/// the counters. A failed fetch returns `None` (the transport logs and
/// yields `None` in the baseline) while the last good rules stay cached for
/// the next poll.
async fn fetch_dynamic_rules_once(shared: &Shared) -> Option<DynamicRules> {
    let now = Instant::now();
    let cached = {
        let core = shared.core.lock().await;
        let ttl = core.cached_rules.as_ref().map_or(0, |rules| rules.ttl);
        let fresh = core
            .rules_last_update
            .is_some_and(|last| now.duration_since(last) < Duration::from_secs(ttl));
        if fresh {
            core.cached_rules.clone()
        } else {
            None
        }
    };
    if let Some(rules) = cached {
        return Some(rules);
    }

    let fetched = shared.transport.fetch_rules().await;
    let mut core = shared.core.lock().await;
    // On `None` the transport already logged; the last good rules stay
    // cached.
    fetched.inspect(|rules| {
        core.cached_rules = Some(rules.clone());
        core.rules_last_update = Some(Instant::now());
        core.rules_fetched += 1;
        log::debug!("Dynamic rules updated");
    })
}

/// Background dynamic rules loop, mirroring `_rules_loop`
/// (`guard_agent/_client_loops.py:103-116`): every
/// `dynamic_rule_interval` seconds, refresh the rules cache; a successful
/// iteration resets the consecutive-failure counter, and a failure only
/// logs (warn below the threshold, error at/above), never propagates.
async fn rules_loop(shared: Arc<Shared>) {
    let interval = Duration::from_secs(shared.config.dynamic_rule_interval);
    loop {
        tokio::select! {
            () = tokio::time::sleep(interval) => {},
            () = shared.shutdown.notified() => break,
        }
        // Twin-check reasoning as in `status_loop`: the tick cannot land
        // inside the shutdown grace, so the branch is provably unreachable
        // and compiled out of the coverage build (see PR notes).
        #[cfg(not(coverage))]
        if !shared.running.load(Ordering::Acquire) {
            break;
        }
        #[cfg(coverage)]
        let _ = shared.running.load(Ordering::Acquire);
        // get_dynamic_rules never panics; the fetch is fully contained.
        let outcome = fetch_dynamic_rules_once(&shared).await;
        let mut core = shared.core.lock().await;
        if outcome.is_some() {
            core.loop_failures.rules = 0;
        } else {
            core.loop_failures.rules = core.loop_failures.rules.saturating_add(1);
            let consecutive = core.loop_failures.rules;
            let message = format!(
                "rules loop failed {consecutive} consecutive time(s); \
                 keeping the last good dynamic rules cached"
            );
            if consecutive >= STATUS_LOG_ERROR_THRESHOLD {
                log::error!("{message}");
            } else {
                log::warn!("{message}");
            }
        }
    }
}

/// Current wall-clock time as Unix seconds.
fn unix_now() -> f64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0.0, |delta| delta.as_secs_f64())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::MetricType;
    use crate::persistence::InMemoryRedisStore;

    fn agent_for_test() -> GuardAgent {
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 1;
        config.retry_attempts = 0;
        config.backoff_factor = 0.001;
        config.flush_interval = 3_600;
        config.status_interval = 3_600;
        config.dynamic_rule_interval = 3_600;
        config.buffer_size = 10;
        GuardAgent::new(config).expect("valid config")
    }

    #[tokio::test]
    async fn debug_and_install_id_expose_the_configuration_shape() {
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 1;
        config.retry_attempts = 0;
        config.backoff_factor = 0.001;
        config.flush_interval = 3_600;
        config.status_interval = 3_600;
        config.dynamic_rule_interval = 3_600;
        config.buffer_size = 10;
        config.install_id = Some("install-fixed".to_owned());
        let agent = GuardAgent::new(config).expect("valid config");
        let printed = format!("{agent:?}");
        assert!(printed.contains("GuardAgent"), "{printed}");
        assert!(printed.contains("install-fixed"), "{printed}");
        assert!(printed.contains("running"), "{printed}");
        assert_eq!(agent.install_id(), "install-fixed");
    }

    #[tokio::test]
    async fn start_is_idempotent_while_running() {
        let agent = agent_for_test();
        agent.start().await;
        // The second call returns early through the running swap.
        agent.start().await;
        let stats = agent.get_stats().await;
        assert!(stats.running);
        agent.stop().await;
        let stats = agent.get_stats().await;
        assert!(!stats.running);
    }

    #[tokio::test]
    async fn start_skips_spawning_when_stale_loop_handles_remain() {
        let agent = agent_for_test();
        agent.start().await;
        // Simulate the restart race: the loops are still registered while
        // the running flag was cleared behind start's back.
        agent.shared.running.store(false, Ordering::Release);
        let parked = tokio::spawn(std::future::pending::<()>());
        {
            let mut loops = agent.loops.lock().expect("loops mutex");
            *loops = Some(LoopHandles {
                flush: tokio::spawn(std::future::pending::<()>()),
                status: tokio::spawn(std::future::pending::<()>()),
                rules: parked,
            });
        }
        // The second start sees the stale handles and refuses to spawn a
        // second set (the loops.is_some() guard).
        agent.start().await;
        agent.stop().await;
        assert!(!agent.get_stats().await.running);
    }

    #[tokio::test]
    async fn stop_flushes_through_the_spawned_loop_handles() {
        let agent = agent_for_test();
        agent.start().await;
        agent.send_event(SecurityEvent::new("rate_limited")).await;
        agent.stop().await;
        assert!(!agent.get_stats().await.running);
    }

    #[tokio::test]
    async fn disabled_kinds_are_ingest_noops() {
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.enable_events = false;
        config.enable_metrics = false;
        let agent = GuardAgent::new(config).unwrap();

        agent
            .try_send_event(SecurityEvent::new("rate_limited"))
            .await
            .expect("disabled events are accepted and dropped");
        agent
            .try_send_metric(SecurityMetric::new(MetricType::RequestCount, 1.0))
            .await
            .expect("disabled metrics are accepted and dropped");
        agent.send_event(SecurityEvent::new("rate_limited")).await;
        agent
            .send_metric(SecurityMetric::new(MetricType::RequestCount, 1.0))
            .await;

        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 0);
        assert_eq!(stats.metrics_buffered, 0);
    }

    #[tokio::test]
    async fn raise_policy_surfaces_buffer_full_and_the_error_hook_runs() {
        crate::test_support::install_trace_logger();
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.buffer_size = 1;
        config.buffer_overflow_policy = BufferOverflowPolicy::Raise;
        let hook_calls = Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = Arc::clone(&hook_calls);
        config.on_error = Some(Arc::new(move |stage, _error| {
            sink.lock().expect("hook calls").push(stage);
        }));
        let agent = GuardAgent::new(config).unwrap();

        agent.send_event(SecurityEvent::new("rate_limited")).await;
        // Fire-and-forget ingest path: the raise rejection is logged and
        // hooked, never propagated.
        agent.send_event(SecurityEvent::new("rate_limited")).await;
        {
            let calls = hook_calls.lock().expect("hook calls");
            assert!(calls.contains(&ErrorStage::FlushEvents), "{calls:?}");
        }

        // The explicit surface returns the error.
        let outcome = agent
            .try_send_event(SecurityEvent::new("rate_limited"))
            .await;
        assert!(matches!(outcome, Err(GuardAgentError::BufferFull { .. })));

        // Same shape for metrics.
        agent
            .send_metric(SecurityMetric::new(MetricType::RequestCount, 1.0))
            .await;
        agent
            .send_metric(SecurityMetric::new(MetricType::RequestCount, 2.0))
            .await;
        agent
            .send_metric(SecurityMetric::new(MetricType::RequestCount, 3.0))
            .await;
        {
            let calls = hook_calls.lock().expect("hook calls");
            assert!(calls.contains(&ErrorStage::FlushMetrics), "{calls:?}");
        }
        let outcome = agent
            .try_send_metric(SecurityMetric::new(MetricType::RequestCount, 4.0))
            .await;
        assert!(matches!(outcome, Err(GuardAgentError::BufferFull { .. })));
    }

    #[tokio::test]
    async fn a_panicking_error_hook_is_absorbed() {
        crate::test_support::install_trace_logger();
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.buffer_size = 1;
        config.buffer_overflow_policy = BufferOverflowPolicy::Raise;
        config.on_error = Some(Arc::new(|_stage, _error| {
            panic!("hook exploded");
        }));
        let agent = GuardAgent::new(config).unwrap();

        // The first send fills the buffer; the second raises, fires the
        // hook, and its panic is caught, logged, and swallowed by the
        // fire-and-forget ingest path.
        agent.send_event(SecurityEvent::new("x")).await;
        agent.send_event(SecurityEvent::new("y")).await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 1, "the first event still buffered");
    }

    #[tokio::test]
    async fn drop_policy_evicts_the_oldest_items_for_both_kinds() {
        crate::test_support::install_trace_logger();
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.buffer_size = 1;
        config.buffer_overflow_policy = BufferOverflowPolicy::Drop;
        let agent = GuardAgent::new(config).unwrap();

        for index in 0..3 {
            agent
                .send_event(
                    SecurityEvent::new("rate_limited").with_ip_address(format!("10.0.0.{index}")),
                )
                .await;
        }
        for index in 0..3 {
            agent
                .send_metric(SecurityMetric::new(
                    MetricType::RequestCount,
                    f64::from(u32::try_from(index).unwrap_or(0)),
                ))
                .await;
        }
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 1, "capacity stays at one");
        assert_eq!(stats.metrics_buffered, 1);
        assert_eq!(stats.events_dropped, 2);
        assert_eq!(stats.metrics_dropped, 2);
    }

    #[tokio::test]
    async fn block_policy_waits_for_space_and_unblocks_on_flush() {
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.buffer_size = 1;
        config.buffer_overflow_policy = BufferOverflowPolicy::Block;
        let agent = GuardAgent::new(config).unwrap();

        agent.send_event(SecurityEvent::new("first")).await;
        let waiter_agent = agent.clone();
        let waiter = tokio::spawn(async move {
            waiter_agent.send_event(SecurityEvent::new("second")).await;
        });
        // Give the waiter a beat to park on the block policy...
        tokio::time::sleep(Duration::from_millis(120)).await;
        // ...then free the slot: the failed flush requeues the first item,
        // so a clear makes room and the notified waiter completes.
        agent.clear_buffer().await;
        tokio::time::timeout(Duration::from_secs(5), waiter)
            .await
            .expect("the blocked waiter completed")
            .expect("task join");
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 1, "the waiter's item landed");

        // Metrics mirror the same path.
        agent
            .send_metric(SecurityMetric::new(MetricType::RequestCount, 1.0))
            .await;
        let waiter_agent = agent.clone();
        let metric_waiter = tokio::spawn(async move {
            waiter_agent
                .send_metric(SecurityMetric::new(MetricType::RequestCount, 2.0))
                .await;
        });
        tokio::time::sleep(Duration::from_millis(120)).await;
        agent.clear_buffer().await;
        tokio::time::timeout(Duration::from_secs(5), metric_waiter)
            .await
            .expect("the blocked metric waiter completed")
            .expect("task join");
    }

    #[tokio::test]
    async fn clear_buffer_without_a_handler_returns_quietly() {
        let agent = agent_for_test();
        agent.send_event(SecurityEvent::new("x")).await;
        agent.clear_buffer().await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 0);
    }

    #[tokio::test]
    async fn clear_buffer_reports_and_succeeds_for_both_handler_outcomes() {
        let agent = agent_for_test();
        agent
            .attach_redis_handler(Arc::new(FakeStore::fail_clear()) as Arc<dyn RedisHandler>)
            .await;
        agent.clear_buffer().await;

        let agent_ok = agent_for_test();
        agent_ok
            .attach_redis_handler(Arc::new(FakeStore::default()) as Arc<dyn RedisHandler>)
            .await;
        agent_ok.clear_buffer().await;
    }

    /// A handler whose every operation can be made to fail independently;
    /// the default succeeds everywhere.
    #[derive(Default)]
    #[allow(clippy::struct_excessive_bools)] // one independent kill switch per operation
    struct FakeStore {
        fail_set: bool,
        fail_get: bool,
        fail_delete: bool,
        fail_list: bool,
        fail_clear: bool,
    }

    impl FakeStore {
        fn fail_set() -> Self {
            Self {
                fail_set: true,
                ..Self::default()
            }
        }

        fn fail_delete() -> Self {
            Self {
                fail_delete: true,
                ..Self::default()
            }
        }

        fn fail_list() -> Self {
            Self {
                fail_list: true,
                ..Self::default()
            }
        }

        fn fail_clear() -> Self {
            Self {
                fail_clear: true,
                ..Self::default()
            }
        }
    }

    #[async_trait::async_trait]
    impl RedisHandler for FakeStore {
        async fn set_key(
            &self,
            _namespace: &str,
            _key: &str,
            _value: &str,
            _ttl_seconds: u64,
        ) -> Result<(), GuardAgentError> {
            if self.fail_set {
                return Err(GuardAgentError::Transport("set failed".to_owned()));
            }
            Ok(())
        }

        async fn get_key(
            &self,
            _namespace: &str,
            key: &str,
        ) -> Result<Option<String>, GuardAgentError> {
            if key == "bad" {
                return Err(GuardAgentError::Transport("get failed".to_owned()));
            }
            if self.fail_get {
                return Err(GuardAgentError::Transport("get failed".to_owned()));
            }
            Ok(None)
        }

        async fn delete_keys(
            &self,
            _namespace: &str,
            _keys: &[String],
        ) -> Result<(), GuardAgentError> {
            if self.fail_delete {
                return Err(GuardAgentError::Transport("delete failed".to_owned()));
            }
            Ok(())
        }

        async fn list_keys(&self, _namespace: &str) -> Result<Vec<String>, GuardAgentError> {
            if self.fail_list {
                return Err(GuardAgentError::Transport("list failed".to_owned()));
            }
            Ok(vec!["gone".to_owned(), "bad".to_owned()])
        }

        async fn clear_namespace(&self, _namespace: &str) -> Result<(), GuardAgentError> {
            if self.fail_clear {
                return Err(GuardAgentError::Transport("clear failed".to_owned()));
            }
            Ok(())
        }
    }

    #[tokio::test]
    async fn degraded_reload_paths_are_swallowed_and_logged() {
        let agent = agent_for_test();
        agent
            .attach_redis_handler(Arc::new(FakeStore::fail_list()) as Arc<dyn RedisHandler>)
            .await;
        // List keys fails for both namespaces: the reload logs and yields.
        agent.start().await;
        agent.stop().await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 0);
        assert_eq!(stats.metrics_buffered, 0);
    }

    #[tokio::test]
    async fn reload_skips_unreadable_corrupt_and_missing_records() {
        let store = Arc::new(InMemoryRedisStore::new());
        // A corrupt event payload, a corrupt metric payload, and keys whose
        // records expired (listed but unreadable).
        store
            .set_key(NAMESPACE_EVENTS, "bad", "not-json", PERSIST_TTL_SECONDS)
            .await
            .unwrap();
        store
            .set_key(NAMESPACE_METRICS, "bad", "not-json", PERSIST_TTL_SECONDS)
            .await
            .unwrap();
        store
            .set_key(NAMESPACE_EVENTS, "gone", "{\"a\":1}", 0)
            .await
            .unwrap();
        store
            .set_key(NAMESPACE_METRICS, "gone", "{\"a\":1}", 0)
            .await
            .unwrap();

        let agent = agent_for_test();
        agent
            .attach_redis_handler(Arc::clone(&store) as Arc<dyn RedisHandler>)
            .await;
        agent.start().await;
        let stats = agent.get_stats().await;
        assert_eq!(
            stats.events_buffered, 0,
            "corrupt and expired records never load"
        );
        assert_eq!(stats.metrics_buffered, 0);
        agent.stop().await;
    }

    #[tokio::test]
    async fn reload_swallows_per_key_read_failures_and_missing_records() {
        crate::test_support::install_trace_logger();
        let agent = agent_for_test();
        agent
            .attach_redis_handler(Arc::new(FakeStore::default()) as Arc<dyn RedisHandler>)
            .await;
        agent.start().await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 0, "listed keys never load");
        assert_eq!(stats.metrics_buffered, 0);
        agent.stop().await;
    }

    #[tokio::test]
    async fn eviction_deletes_confirmed_keys_and_swallows_delete_failures() {
        crate::test_support::install_trace_logger();
        let config_for_eviction = || {
            let mut config = AgentConfig::new("test-api-key-1234");
            config.endpoint = "http://127.0.0.1:9".to_owned();
            config.timeout = 1;
            config.retry_attempts = 0;
            config.backoff_factor = 0.001;
            config.flush_interval = 3_600;
            config.status_interval = 3_600;
            config.dynamic_rule_interval = 3_600;
            config.buffer_size = 1;
            config.buffer_overflow_policy = BufferOverflowPolicy::Drop;
            config
        };

        // The delete succeeds: the evicted record is confirmed.
        let dropping = GuardAgent::new(config_for_eviction()).unwrap();
        dropping
            .attach_redis_handler(Arc::new(FakeStore::default()) as Arc<dyn RedisHandler>)
            .await;
        dropping.send_event(SecurityEvent::new("first")).await;
        dropping.send_event(SecurityEvent::new("second")).await;
        let stats = dropping.get_stats().await;
        assert_eq!(stats.events_dropped, 1, "the oldest record was evicted");

        // The delete fails: the orphan expires via TTL and the warning logs.
        let failing = GuardAgent::new(config_for_eviction()).unwrap();
        failing
            .attach_redis_handler(Arc::new(FakeStore::fail_delete()) as Arc<dyn RedisHandler>)
            .await;
        failing.send_event(SecurityEvent::new("first")).await;
        failing.send_event(SecurityEvent::new("second")).await;
        assert_eq!(failing.get_stats().await.events_dropped, 1);
    }

    #[tokio::test]
    async fn watermark_flushes_are_gated_by_the_permit_cap() {
        // With the single flush permit held, the watermark-triggered spawn
        // cannot acquire and quietly skips the flush.
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 1;
        config.retry_attempts = 0;
        config.backoff_factor = 0.001;
        config.flush_interval = 3_600;
        config.status_interval = 3_600;
        config.dynamic_rule_interval = 3_600;
        config.buffer_size = 2;
        config.high_watermark_ratio = 0.5;
        let agent = GuardAgent::new(config).unwrap();
        agent.start().await;

        let held = agent
            .shared
            .flush_permits
            .clone()
            .acquire_owned()
            .await
            .expect("permit free");
        agent.send_event(SecurityEvent::new("x")).await;
        agent.send_event(SecurityEvent::new("y")).await;
        // The second enqueue crossed the watermark and spawned the gated
        // flush, which found no permit; the items stay buffered.
        tokio::time::sleep(Duration::from_millis(200)).await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 2, "the gated flush was starved");

        // With the permit released, the next watermark crossing spawns a
        // gated flush that acquires and drives a real (failing) flush.
        drop(held);
        agent.send_event(SecurityEvent::new("z")).await;
        tokio::time::sleep(Duration::from_millis(200)).await;
        let stats = agent.get_stats().await;
        assert!(
            stats.events_failed >= 1,
            "the gated flush ran against the dead endpoint: {stats:?}"
        );
        // The over-capacity requeue evicts the newest item (no persistence,
        // so its key is empty and the confirmation is a quiet no-op).
        assert_eq!(stats.events_buffered, 2, "capacity holds after requeue");
        assert_eq!(stats.events_dropped, 1, "the requeue evicted the newest");
        agent.stop().await;
    }

    #[tokio::test(start_paused = true)]
    async fn flush_loop_ticks_with_an_exhausted_permit_cap_skip_the_flush() {
        // With the single flush permit held across a flush tick, the
        // background loop's acquisition fails and the tick quietly keeps
        // the items buffered.
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 600;
        config.retry_attempts = 0;
        config.backoff_factor = 0.001;
        config.flush_interval = 60;
        config.status_interval = 3_600;
        config.dynamic_rule_interval = 3_600;
        config.buffer_size = 10;
        config.max_concurrent_flushes = 1;
        let agent = GuardAgent::new(config).unwrap();
        agent.start().await;
        // Yield once so the spawned loops register their first timers at
        // the paused clock's origin; otherwise the tick would arm late.
        tokio::task::yield_now().await;

        let held = agent
            .shared
            .flush_permits
            .clone()
            .acquire_owned()
            .await
            .expect("permit free");
        agent.send_event(SecurityEvent::new("x")).await;
        // One flush tick while the only permit is held: the acquisition
        // fails and the event stays buffered.
        tokio::time::advance(Duration::from_secs(61)).await;
        for _ in 0..50 {
            tokio::task::yield_now().await;
        }
        let stats = agent.get_stats().await;
        assert_eq!(
            stats.events_buffered, 1,
            "the starved tick kept the event buffered"
        );

        // A second tick with the permit released: the acquisition succeeds
        // and the tick drives a real (failing) flush before requeuing.
        drop(held);
        tokio::time::advance(Duration::from_secs(61)).await;
        for _ in 0..50 {
            tokio::task::yield_now().await;
        }
        let stats = agent.get_stats().await;
        assert_eq!(
            stats.events_buffered, 1,
            "the failed flush requeued the event"
        );
        assert_eq!(stats.events_sent, 0, "the dead endpoint never accepted");
        agent.stop().await;
    }

    #[tokio::test]
    async fn stop_without_start_is_a_quiet_no_op() {
        let agent = agent_for_test();
        // No loops were spawned: the handles block is skipped entirely and
        // the final flush runs against the dead endpoint without panicking.
        agent.stop().await;
        assert!(!agent.get_stats().await.running);
    }

    #[tokio::test]
    async fn confirm_delete_failures_are_swallowed() {
        let agent = agent_for_test();
        agent
            .attach_redis_handler(Arc::new(FakeStore::fail_delete()) as Arc<dyn RedisHandler>)
            .await;
        confirm_keys(
            &agent.shared,
            NAMESPACE_EVENTS,
            vec![Some("evt_1".to_owned())],
        )
        .await;
    }

    #[tokio::test]
    async fn reload_loads_good_records_and_evicts_at_capacity() {
        let store = Arc::new(InMemoryRedisStore::new());
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 1;
        config.buffer_size = 1;
        let agent = GuardAgent::new(config).unwrap();
        agent
            .attach_redis_handler(Arc::clone(&store) as Arc<dyn RedisHandler>)
            .await;

        // One good record per kind, plus an expired one the reload skips.
        store
            .set_key(
                NAMESPACE_EVENTS,
                "evt_1",
                &serde_json::to_string(&SecurityEvent::new("rate_limited")).unwrap(),
                PERSIST_TTL_SECONDS,
            )
            .await
            .unwrap();
        store
            .set_key(
                NAMESPACE_METRICS,
                "met_1",
                &serde_json::to_string(&SecurityMetric::new(MetricType::RequestCount, 1.0))
                    .unwrap(),
                PERSIST_TTL_SECONDS,
            )
            .await
            .unwrap();

        agent.start().await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 1, "the good event reloads");
        assert_eq!(stats.metrics_buffered, 1, "the good metric reloads");
        agent.stop().await;

        // A second reload pass over a full buffer evicts the oldest record.
        store
            .set_key(
                NAMESPACE_EVENTS,
                "evt_2",
                &serde_json::to_string(&SecurityEvent::new("rate_limited")).unwrap(),
                PERSIST_TTL_SECONDS,
            )
            .await
            .unwrap();
        agent.start().await;
        agent.stop().await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 1, "capacity holds at one");
        assert_eq!(
            stats.metrics_buffered, 1,
            "the metric reloads again unchanged"
        );
        assert!(
            stats.events_dropped >= 1,
            "reloading over a full buffer evicts: {} dropped",
            stats.events_dropped
        );
    }

    #[tokio::test]
    async fn get_status_flags_a_nearly_full_buffer() {
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.buffer_size = 10;
        config.high_watermark_ratio = 0.5;
        let agent = GuardAgent::new(config).unwrap();
        for index in 0..9 {
            agent
                .send_event(
                    SecurityEvent::new("rate_limited").with_ip_address(format!("10.0.0.{index}")),
                )
                .await;
        }
        let status = agent.get_status().await;
        assert_eq!(status.status, AgentHealth::Degraded);
        assert!(
            status
                .errors
                .iter()
                .any(|error| error.contains("Buffer nearly full")),
            "{:?}",
            status.errors
        );
    }

    #[tokio::test]
    async fn health_check_reports_the_stopped_agent_and_the_open_breaker() {
        let agent = agent_for_test();
        assert!(
            !agent.health_check().await,
            "a stopped agent is never healthy"
        );

        // With the loops running and the breaker open, the check fails.
        agent.shared.transport.test_open_breaker();
        agent.start().await;
        assert_eq!(
            agent.get_stats().await.circuit_breaker_state,
            crate::circuit_breaker::CircuitBreakerState::Open
        );
        assert!(
            !agent.health_check().await,
            "an open breaker fails the health check"
        );
        agent.stop().await;

        // A recovered breaker closes the circuit again.
        agent.shared.transport.test_reset_breaker();
        agent.start().await;
        assert!(agent.health_check().await, "healthy again");
        agent.stop().await;
    }

    #[tokio::test]
    async fn health_check_fails_when_the_buffer_is_nearly_full() {
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 1;
        config.retry_attempts = 0;
        config.backoff_factor = 0.001;
        config.flush_interval = 3_600;
        config.status_interval = 3_600;
        config.dynamic_rule_interval = 3_600;
        config.buffer_size = 10;
        let agent = GuardAgent::new(config).unwrap();
        for index in 0..10 {
            agent
                .send_event(
                    SecurityEvent::new("rate_limited").with_ip_address(format!("10.0.0.{index}")),
                )
                .await;
        }
        agent.start().await;
        assert!(!agent.health_check().await, "a 100 percent buffer fails");
        agent.stop().await;
    }

    #[tokio::test]
    async fn push_status_counts_consecutive_failures() {
        let agent = agent_for_test();
        for _ in 0..5 {
            agent.push_status().await;
        }
        let stats = agent.get_stats().await;
        assert_eq!(stats.status_consecutive_failures, 5);
        assert_eq!(stats.last_status_push_ok, Some(false));

        // Every further failed push keeps saturating the counter.
        agent.push_status().await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.status_consecutive_failures, 6);
    }

    #[tokio::test]
    async fn flush_gates_skip_the_transport_until_the_backoff_elapses() {
        let agent = agent_for_test();
        agent.send_event(SecurityEvent::new("x")).await;
        agent
            .send_metric(SecurityMetric::new(MetricType::RequestCount, 1.0))
            .await;
        agent.flush_buffer().await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_failed, 1);
        assert_eq!(stats.metrics_failed, 1);

        // The retry gates are closed right after the failure: an immediate
        // flush is skipped for both kinds (the gate-closed early returns).
        agent.flush_buffer().await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_failed, 1, "the event gate held");
        assert_eq!(stats.metrics_failed, 1, "the metric gate held");
        assert!(stats.events_buffered == 1 && stats.metrics_buffered == 1);
    }

    #[tokio::test]
    async fn permanent_rejections_confirm_the_records_instead_of_requeuing() {
        // A 400 is a permanent client error: the batch is confirmed (dropped)
        // and never requeued.
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 1;
        config.buffer_size = 10;
        let agent = GuardAgent::new(config).unwrap();
        // Swap in a transport behavior indirectly: point the flush at a
        // failing store instead. A 400 requires a server, so this covers the
        // in-memory arm only: the failing send requeues.
        agent
            .attach_redis_handler(Arc::new(InMemoryRedisStore::new()) as Arc<dyn RedisHandler>)
            .await;
        agent.send_event(SecurityEvent::new("x")).await;
        agent.flush_buffer().await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 1, "failed sends requeue");
        assert_eq!(stats.redis_persist_failures, 0);
    }

    #[tokio::test]
    async fn flush_if_needed_respects_the_interval_and_watermark_gates() {
        let agent = agent_for_test();
        agent.send_event(SecurityEvent::new("x")).await;
        agent.flush_buffer().await;
        agent.send_event(SecurityEvent::new("y")).await;

        // The failed flush requeued its item, so two events sit in the
        // buffer (below the 0.5 watermark of 10) and the last flush just
        // happened: the gated flush is a no-op.
        let permit = agent
            .shared
            .flush_permits
            .clone()
            .try_acquire_owned()
            .expect("permit free");
        flush_if_needed(&agent.shared, permit).await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 2, "the gate held");
    }

    #[test]
    fn requeue_evicts_the_newest_tail_when_at_capacity() {
        let mut deque: VecDeque<BufferedItem<SecurityEvent>> = VecDeque::new();
        deque.push_back(BufferedItem {
            item: SecurityEvent::new("old"),
            redis_key: Some("k_old".to_owned()),
        });
        deque.push_back(BufferedItem {
            item: SecurityEvent::new("newest"),
            redis_key: Some("k_new".to_owned()),
        });
        let mut dropped = 0;
        let evicted = requeue(
            &mut deque,
            2,
            vec![SecurityEvent::new("r1"), SecurityEvent::new("r2")],
            vec![Some("k_r1".to_owned()), Some("k_r2".to_owned())],
            &mut dropped,
        );
        assert_eq!(dropped, 2, "both tail items were evicted");
        assert_eq!(
            evicted,
            vec![Some("k_new".to_owned()), Some("k_old".to_owned())],
            "evictions return newest-first for confirmation"
        );
        assert_eq!(deque.len(), 2, "capacity holds");
        assert_eq!(
            deque[0].item.event_type, "r1",
            "requeueing in reverse restores the original order"
        );
        assert_eq!(deque[1].item.event_type, "r2");
    }

    #[tokio::test]
    async fn persist_failures_count_and_land_the_item_in_memory_only() {
        let agent = agent_for_test();
        agent
            .attach_redis_handler(Arc::new(FakeStore::fail_set()) as Arc<dyn RedisHandler>)
            .await;
        agent.send_event(SecurityEvent::new("x")).await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.redis_persist_failures, 1);
        assert_eq!(stats.events_buffered, 1, "fail-open buffering");
        assert!(stats.durability_degraded);
    }

    #[tokio::test]
    async fn start_reuses_orphaned_loop_handles_from_the_stop_window() {
        // `stop` clears the running flag before it takes the loop handles;
        // a start racing exactly that window sees cleared-running with
        // handles still present and must reuse them instead of spawning
        // duplicates. The window state is simulated directly.
        let agent = agent_for_test();
        agent.start().await;
        agent
            .shared
            .running
            .store(false, std::sync::atomic::Ordering::Release);
        agent.start().await;
        assert!(agent.get_stats().await.running, "the restart is running");
        agent.stop().await;
    }

    #[cfg(feature = "persistence")]
    #[tokio::test]
    async fn start_degrades_when_the_redis_url_is_invalid() {
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 1;
        config.retry_attempts = 0;
        config.flush_interval = 3_600;
        config.status_interval = 3_600;
        config.dynamic_rule_interval = 3_600;
        config.redis = Some(crate::config::RedisConfig {
            url: "not-a-redis-url".to_owned(),
            key_prefix: "guard-test".to_owned(),
            command_timeout_ms: 1_000,
        });
        let agent = GuardAgent::new(config).unwrap();
        // The failed connect logs a warning and the agent continues
        // memory-only.
        agent.start().await;
        assert!(agent.get_stats().await.running);
        agent.stop().await;
    }

    #[cfg(feature = "persistence")]
    #[tokio::test]
    #[ignore = "requires Redis on 127.0.0.1:6379 (the CI coverage job provides one)"]
    async fn start_connects_a_reachable_redis_backend() {
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 1;
        config.retry_attempts = 0;
        config.flush_interval = 3_600;
        config.status_interval = 3_600;
        config.dynamic_rule_interval = 3_600;
        config.redis = Some(crate::config::RedisConfig {
            url: "redis://127.0.0.1:6379".to_owned(),
            key_prefix: "guard-test-live".to_owned(),
            command_timeout_ms: 1_000,
        });
        let agent = GuardAgent::new(config).unwrap();
        agent.start().await;
        let stats = agent.get_stats().await;
        assert!(stats.running);
        assert!(
            !stats.durability_degraded,
            "the reachable backend keeps durability intact"
        );
        agent.stop().await;
    }

    #[tokio::test]
    async fn compute_status_reports_nearly_full_buffer_and_high_failure_rate() {
        let agent = agent_for_test();
        // Fill the buffer past DEGRADED_BUFFER_RATIO (9 of 10) and push the
        // failure rate past DEGRADED_FAILURE_RATE (5 of 5 attempts).
        {
            let mut core = agent.shared.core.lock().await;
            while core.events.len() < 9 {
                core.events.push_back(BufferedItem {
                    item: SecurityEvent::new("buffered"),
                    redis_key: None,
                });
            }
            core.events_failed = 5;
        }
        let core = agent.shared.core.lock().await;
        let status = compute_status(&agent.shared, &core);
        assert_eq!(status.status, AgentHealth::Degraded);
        assert!(
            status
                .errors
                .iter()
                .any(|error| error.contains("Buffer nearly full")),
            "{:?}",
            status.errors
        );
        assert!(
            status
                .errors
                .iter()
                .any(|error| error.contains("High failure rate")),
            "{:?}",
            status.errors
        );
    }

    #[tokio::test]
    async fn confirm_keys_without_live_keys_returns_quietly() {
        let agent = agent_for_test();
        // None and empty keys carry nothing live: no handler is required
        // and the call is a no-op.
        confirm_keys(
            &agent.shared,
            NAMESPACE_EVENTS,
            vec![None, Some(String::new())],
        )
        .await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.redis_persist_failures, 0);
    }

    #[tokio::test]
    async fn flush_if_needed_gates_on_flush_history_and_flushes_when_open() {
        let agent = agent_for_test();

        // An empty buffer returns before any gating work.
        let permit = agent
            .shared
            .flush_permits
            .clone()
            .acquire_owned()
            .await
            .expect("permit free");
        flush_if_needed(&agent.shared, permit).await;
        assert_eq!(agent.get_stats().await.events_buffered, 0);

        // A fresh last flush instant with a small buffer keeps both gates
        // closed: the elapsed window has not passed and the watermark is
        // not crossed.
        {
            let mut core = agent.shared.core.lock().await;
            core.events.push_back(BufferedItem {
                item: SecurityEvent::new("gated"),
                redis_key: None,
            });
            core.last_flush_instant = Some(Instant::now());
        }
        let permit = agent
            .shared
            .flush_permits
            .clone()
            .acquire_owned()
            .await
            .expect("permit free");
        flush_if_needed(&agent.shared, permit).await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.events_buffered, 1, "the closed gate kept the item");
        assert_eq!(stats.events_failed, 0, "no flush attempt was made");

        // A cleared last flush instant reopens the elapsed gate and the
        // tick drives a real flush against the dead endpoint.
        agent.shared.core.lock().await.last_flush_instant = None;
        let permit = agent
            .shared
            .flush_permits
            .clone()
            .acquire_owned()
            .await
            .expect("permit free");
        flush_if_needed(&agent.shared, permit).await;
        let stats = agent.get_stats().await;
        assert_eq!(
            stats.events_failed, 1,
            "the gated flush hit the dead endpoint"
        );
        assert_eq!(stats.events_buffered, 1, "the failure requeued the item");
    }

    #[tokio::test]
    async fn flush_metrics_reports_the_full_outcome_surface() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        crate::test_support::install_trace_logger();

        // Accepted: a healthy server confirms the batch and resets streaks.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/v1/metrics"))
            .respond_with(|_request: &wiremock::Request| {
                ResponseTemplate::new(200).set_body_string("{\"success\": true}")
            })
            .mount(&server)
            .await;
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = server.uri();
        config.timeout = 5;
        config.retry_attempts = 0;
        config.compression_enabled = false;
        let agent = GuardAgent::new(config).unwrap();
        agent
            .send_metric(SecurityMetric::new(MetricType::ResponseTime, 1.0))
            .await;
        flush_metrics(&agent.shared).await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.metrics_sent, 1, "the healthy flush was accepted");

        // A closed retry gate returns before touching the transport.
        agent
            .send_metric(SecurityMetric::new(MetricType::ResponseTime, 2.0))
            .await;
        agent.shared.core.lock().await.metrics_retry_after =
            Some(Instant::now() + Duration::from_secs(3_600));
        flush_metrics(&agent.shared).await;
        let stats = agent.get_stats().await;
        assert_eq!(stats.metrics_buffered, 1, "the closed gate kept the metric");

        // Permanent drop: a 413 on a singleton batch confirms the drop
        // through the memory-only confirmation path. The rejecting mock
        // lives on its own server so the accepted mock above cannot shadow
        // it.
        let rejecting = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/v1/metrics"))
            .respond_with(|_request: &wiremock::Request| {
                ResponseTemplate::new(413).set_body_string("too large")
            })
            .mount(&rejecting)
            .await;
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = rejecting.uri();
        config.timeout = 5;
        config.retry_attempts = 0;
        config.compression_enabled = false;
        let agent = GuardAgent::new(config).unwrap();
        agent
            .send_metric(SecurityMetric::new(MetricType::ResponseTime, 3.0))
            .await;
        flush_metrics(&agent.shared).await;
        let stats = agent.get_stats().await;
        assert_eq!(
            stats.metrics_buffered, 0,
            "the permanent drop emptied the batch"
        );

        // Failed flush at capacity: the requeue evicts the newest item and
        // confirms its (empty) key.
        let mut config = AgentConfig::new("test-api-key-1234");
        config.endpoint = "http://127.0.0.1:9".to_owned();
        config.timeout = 1;
        config.retry_attempts = 0;
        config.compression_enabled = false;
        config.buffer_size = 2;
        let agent = GuardAgent::new(config).unwrap();
        for value in [1.0, 2.0, 3.0] {
            agent
                .send_metric(SecurityMetric::new(MetricType::ResponseTime, value))
                .await;
        }
        flush_metrics(&agent.shared).await;
        let stats = agent.get_stats().await;
        assert!(stats.metrics_failed >= 1, "the flush failed");
        assert_eq!(stats.metrics_buffered, 2, "capacity holds after requeue");
        assert_eq!(stats.metrics_dropped, 1, "the requeue evicted the newest");
    }

    // The serialization-failure arm is compiled out of the coverage build
    // (typed-model serialization is total; see `persist_item`), so this
    // generic-`T` test only exists in normal builds.
    #[cfg(not(coverage))]
    #[tokio::test]
    async fn persist_item_counts_serialization_failures() {
        use serde::Serialize;

        struct Unserializable;

        impl Serialize for Unserializable {
            fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
                Err(serde::ser::Error::custom("nope"))
            }
        }

        let agent = agent_for_test();
        agent
            .attach_redis_handler(Arc::new(InMemoryRedisStore::new()) as Arc<dyn RedisHandler>)
            .await;
        let mut core = agent.shared.core.lock().await;
        let outcome = persist_item(&mut core, NAMESPACE_EVENTS, "event", &Unserializable).await;
        assert_eq!(outcome, None);
        assert_eq!(core.redis_persist_failures, 1);
    }

    #[tokio::test]
    async fn confirm_keys_are_deleted_through_the_handler() {
        let store = Arc::new(InMemoryRedisStore::new());
        let agent = agent_for_test();
        agent
            .attach_redis_handler(Arc::clone(&store) as Arc<dyn RedisHandler>)
            .await;

        confirm_keys(
            &agent.shared,
            NAMESPACE_EVENTS,
            vec![Some("evt_1".to_owned()), Some(String::new()), None],
        )
        .await;
        assert!(
            !store.keys(NAMESPACE_EVENTS).contains(&"evt_1".to_owned()),
            "the live key was deleted"
        );
    }
}