oxcache 0.5.0-rc.7

A production-grade multi-level cache library for Rust: L1 memory (Moka/DashMap) + L2 distributed (Redis/Valkey/Dragonfly/Aerospike) + optional L3 disk (redb).
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
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: MIT
//! Unified metrics collection system that consolidates all metrics functionality

use crate::core::CacheLayer;
use dashmap::DashMap;
use once_cell::sync::Lazy;
use serde::Serialize;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

/// Unified metrics collector
///
/// This provides a centralized way to collect and manage all cache metrics
/// with support for different metric types and aggregation strategies.
#[derive(Clone, Debug, Default)]
pub struct UnifiedMetrics {
    inner: Arc<UnifiedMetricsInner>,
}

struct UnifiedMetricsInner {
    /// High-frequency atomic counters
    counters: AtomicCounters,
    /// Low-frequency dynamic metrics
    dynamic_metrics: DashMap<String, MetricValue>,
    /// Per-service operation totals(R9 service 维度,显式记录才存在)
    service_operation_counters: DashMap<String, AtomicU64>,
    /// 超出 `max_service_labels` 后被丢弃归因的操作次数
    service_label_overflow: AtomicU64,
    /// Configuration
    config: MetricsConfig,
}

impl std::fmt::Debug for UnifiedMetricsInner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UnifiedMetricsInner")
            .field("counters", &"<AtomicCounters>")
            .field("dynamic_metrics", &self.dynamic_metrics)
            .field("config", &self.config)
            .finish()
    }
}

impl Default for UnifiedMetricsInner {
    fn default() -> Self {
        Self {
            counters: AtomicCounters::default(),
            dynamic_metrics: DashMap::new(),
            service_operation_counters: DashMap::new(),
            service_label_overflow: AtomicU64::new(0),
            config: MetricsConfig::default(),
        }
    }
}

/// Atomic counters for high-frequency metrics
#[derive(Debug)]
pub struct AtomicCounters {
    /// L1 cache hits
    pub l1_hits: AtomicU64,
    /// L1 cache misses
    pub l1_misses: AtomicU64,
    /// L2 cache hits
    pub l2_hits: AtomicU64,
    /// L2 cache misses
    pub l2_misses: AtomicU64,
    /// L1 cache sets
    pub l1_sets: AtomicU64,
    /// L2 cache sets
    pub l2_sets: AtomicU64,
    /// L1 cache deletes
    pub l1_deletes: AtomicU64,
    /// L2 cache deletes
    pub l2_deletes: AtomicU64,
    /// Total operations
    pub total_operations: AtomicU64,
    /// Errors
    pub errors: AtomicU64,
    /// Prefetch operations
    pub prefetch_total: AtomicU64,
    /// Compression operations
    pub compression_total: AtomicU64,
    /// Compression bytes saved
    pub compression_bytes_saved: AtomicU64,
    /// L1 cache item count
    pub l1_items: AtomicU64,
    /// L1 cache capacity used (bytes)
    pub l1_capacity_used: AtomicU64,
    /// L2 degradation events (circuit breaker opened)
    pub l2_degraded: AtomicU64,
    /// L2 retry attempts total
    pub l2_retry_total: AtomicU64,
    /// Backfill success count (per backend)
    pub backfill_success: AtomicU64,
    /// Backfill failure count (per backend)
    pub backfill_failed: AtomicU64,
    /// Eviction / expiry removal count
    pub evictions: AtomicU64,
}

/// Metric value types
#[derive(Debug, Clone, Serialize)]
pub enum MetricValue {
    Counter(u64),
    Gauge(f64),
    Histogram(HistogramData),
    Timer(TimerData),
    Text(String),
}

/// Histogram data for distribution metrics
#[derive(Debug, Clone, Serialize)]
pub struct HistogramData {
    pub count: u64,
    pub sum: f64,
    pub min: f64,
    pub max: f64,
    pub buckets: Vec<(f64, u64)>,
}

/// Timer data for duration metrics
#[derive(Debug, Clone, Serialize)]
pub struct TimerData {
    pub count: u64,
    pub total_duration: Duration,
    pub min_duration: Duration,
    pub max_duration: Duration,
}

/// Metrics configuration
#[derive(Debug, Clone)]
pub struct MetricsConfig {
    /// Whether to enable detailed metrics
    pub detailed: bool,
    /// Histogram bucket boundaries
    pub histogram_buckets: Vec<f64>,
    /// Maximum number of dynamic metrics
    pub max_dynamic_metrics: usize,
    /// service 维度标签基数上限(R9):不同 service 名超过该数量后,新标签的
    /// 归因被丢弃并计入 `oxcache_service_labels_overflow_total`,防标签爆炸
    pub max_service_labels: usize,
    /// Metrics retention period for time-based eviction of stale snapshots.
    /// Currently configured but not actively consumed by the eviction logic;
    /// reserved for future implementation of snapshot lifecycle management.
    pub retention_period: Option<Duration>,
}

impl Default for AtomicCounters {
    fn default() -> Self {
        Self {
            l1_hits: AtomicU64::new(0),
            l1_misses: AtomicU64::new(0),
            l2_hits: AtomicU64::new(0),
            l2_misses: AtomicU64::new(0),
            l1_sets: AtomicU64::new(0),
            l2_sets: AtomicU64::new(0),
            l1_deletes: AtomicU64::new(0),
            l2_deletes: AtomicU64::new(0),
            total_operations: AtomicU64::new(0),
            errors: AtomicU64::new(0),
            prefetch_total: AtomicU64::new(0),
            compression_total: AtomicU64::new(0),
            compression_bytes_saved: AtomicU64::new(0),
            l1_items: AtomicU64::new(0),
            l1_capacity_used: AtomicU64::new(0),
            l2_degraded: AtomicU64::new(0),
            l2_retry_total: AtomicU64::new(0),
            backfill_success: AtomicU64::new(0),
            backfill_failed: AtomicU64::new(0),
            evictions: AtomicU64::new(0),
        }
    }
}

impl Default for MetricsConfig {
    fn default() -> Self {
        Self {
            detailed: true,
            histogram_buckets: vec![
                0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0,
            ],
            max_dynamic_metrics: 1000,
            max_service_labels: 64,
            retention_period: Some(Duration::from_secs(3600)), // 1 hour
        }
    }
}

impl UnifiedMetrics {
    /// Create a new unified metrics collector with default configuration
    pub fn new() -> Self {
        Self::with_config(MetricsConfig::default())
    }

    /// Create a new unified metrics collector with custom configuration
    pub fn with_config(config: MetricsConfig) -> Self {
        Self {
            inner: Arc::new(UnifiedMetricsInner {
                counters: AtomicCounters::default(),
                dynamic_metrics: DashMap::new(),
                service_operation_counters: DashMap::new(),
                service_label_overflow: AtomicU64::new(0),
                config,
            }),
        }
    }

    /// Record a cache operation
    pub fn record_operation(&self, operation: CacheOperation) {
        // Update atomic counters
        match (&operation.layer, &operation.op_type, &operation.result) {
            (CacheLayer::L1, CacheOpType::Get, CacheOpResult::Hit) => {
                self.inner.counters.l1_hits.fetch_add(1, Ordering::Relaxed);
                self.inner
                    .counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
            }
            (CacheLayer::L1, CacheOpType::Get, CacheOpResult::Miss) => {
                self.inner
                    .counters
                    .l1_misses
                    .fetch_add(1, Ordering::Relaxed);
                self.inner
                    .counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
            }
            (CacheLayer::L2, CacheOpType::Get, CacheOpResult::Hit) => {
                self.inner.counters.l2_hits.fetch_add(1, Ordering::Relaxed);
                self.inner
                    .counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
            }
            (CacheLayer::L2, CacheOpType::Get, CacheOpResult::Miss) => {
                self.inner
                    .counters
                    .l2_misses
                    .fetch_add(1, Ordering::Relaxed);
                self.inner
                    .counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
            }
            (CacheLayer::L1, CacheOpType::Set, CacheOpResult::Success) => {
                self.inner.counters.l1_sets.fetch_add(1, Ordering::Relaxed);
                self.inner
                    .counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
            }
            (CacheLayer::L2, CacheOpType::Set, CacheOpResult::Success) => {
                self.inner.counters.l2_sets.fetch_add(1, Ordering::Relaxed);
                self.inner
                    .counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
            }
            (CacheLayer::L1, CacheOpType::Delete, CacheOpResult::Success) => {
                self.inner
                    .counters
                    .l1_deletes
                    .fetch_add(1, Ordering::Relaxed);
                self.inner
                    .counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
            }
            (CacheLayer::L2, CacheOpType::Delete, CacheOpResult::Success) => {
                self.inner
                    .counters
                    .l2_deletes
                    .fetch_add(1, Ordering::Relaxed);
                self.inner
                    .counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
            }
            (_, _, CacheOpResult::Error) => {
                self.inner.counters.errors.fetch_add(1, Ordering::Relaxed);
                self.inner
                    .counters
                    .total_operations
                    .fetch_add(1, Ordering::Relaxed);
            }
            _ => {}
        }

        // Update dynamic metrics if detailed mode is enabled
        if self.inner.config.detailed {
            let key = format!(
                "cache:operations:{}:{}:{}",
                operation.layer, operation.op_type, operation.result
            );
            self.increment_counter(&key, 1);
        }
    }

    /// Record operation duration
    pub fn record_duration(&self, operation: &CacheOperation, duration: Duration) {
        if !self.inner.config.detailed {
            return;
        }

        let key = format!("cache:duration:{}:{}", operation.layer, operation.op_type);
        self.record_timer(&key, duration);
    }

    /// Record a custom metric
    pub fn record_custom(&self, key: &str, value: MetricValue) {
        if self.inner.dynamic_metrics.len() >= self.inner.config.max_dynamic_metrics {
            // Remove an arbitrary metric if at capacity.
            // NOTE: DashMap does not guarantee iteration order, so this is
            // NOT true LRU/oldest-first eviction. A sequence-counter-based
            // approach would be needed for deterministic ordering.
            if let Some(first_key) = self
                .inner
                .dynamic_metrics
                .iter()
                .next()
                .map(|r| r.key().clone())
            {
                self.inner.dynamic_metrics.remove(&first_key);
            }
        }
        self.inner.dynamic_metrics.insert(key.to_string(), value);
    }

    /// Increment a counter metric
    pub fn increment_counter(&self, key: &str, value: u64) {
        self.inner
            .dynamic_metrics
            .entry(key.to_string())
            .and_modify(|metric| {
                if let MetricValue::Counter(count) = metric {
                    *count += value;
                }
            })
            .or_insert(MetricValue::Counter(value));
    }

    /// Record a cache operation attributed to a service label(R9 service 维度)
    ///
    /// 原子总账与无标签路径完全一致;service 归因记入独立
    /// `service_operation_counters`(稳态为分片读锁 + `fetch_add`,写锁仅
    /// 首次建键)。标签基数超过 `max_service_labels` 时,新标签的归因被
    /// 丢弃并计入溢出计数(总账不受影响)——防标签爆炸;并发首触经
    /// entry 合并无丢计数,极端交错至多短暂越限 1 个标签。
    /// 默认不启用:仅显式经本方法(如 service 标签 recorder)记录的
    /// 操作才产生 service 维度数据。
    pub fn record_operation_with_service(&self, operation: &CacheOperation, service: &str) {
        self.record_operation(operation.clone());
        if service.is_empty() {
            return;
        }
        let cap = self.inner.config.max_service_labels;
        // 稳态:分片读锁 + fetch_add(值内嵌原子),不取分片写锁
        if let Some(count) = self.inner.service_operation_counters.get(service) {
            count.fetch_add(1, Ordering::Relaxed);
            return;
        }
        // 首触慢路径:上限复核后 entry 合并建键与并发重复首触(无丢计数)
        if self.inner.service_operation_counters.len() < cap {
            self.inner
                .service_operation_counters
                .entry(service.to_string())
                .and_modify(|count| {
                    count.fetch_add(1, Ordering::Relaxed);
                })
                .or_insert_with(|| AtomicU64::new(1));
        } else if let Some(count) = self.inner.service_operation_counters.get_mut(service) {
            // 双检:并发首触的键可能刚被另一线程建立(满载瞬间的竞态)
            count.fetch_add(1, Ordering::Relaxed);
        } else {
            self.inner
                .service_label_overflow
                .fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Record one backend-labeled operation (dynamic counter
    /// `oxcache_backend_<name>_operations_total`). Exported by
    /// [`Self::export_prometheus_standard`] with a `backend` label.
    pub fn record_backend_operation(&self, backend: &str) {
        self.increment_counter(&format!("oxcache_backend_{backend}_operations_total"), 1);
    }

    /// Snapshot of backend-labeled operation counters, sorted by name for
    /// deterministic export output.
    pub fn backend_operation_counters(&self) -> Vec<(String, u64)> {
        let mut out: Vec<(String, u64)> = self
            .inner
            .dynamic_metrics
            .iter()
            .filter_map(|entry| {
                let key = entry.key();
                if key.starts_with("oxcache_backend_")
                    && key.ends_with("_operations_total")
                    && let MetricValue::Counter(count) = entry.value()
                {
                    return Some((key.clone(), *count));
                }
                None
            })
            .collect();
        out.sort_by(|a, b| a.0.cmp(&b.0));
        out
    }

    /// Snapshot of per-service operation counters(R9),sorted by name for
    /// deterministic export output. Only contains services explicitly
    /// recorded via [`Self::record_operation_with_service`].
    pub fn service_operation_counters(&self) -> Vec<(String, u64)> {
        let mut out: Vec<(String, u64)> = self
            .inner
            .service_operation_counters
            .iter()
            .map(|entry| (entry.key().clone(), entry.value().load(Ordering::Relaxed)))
            .collect();
        out.sort_by(|a, b| a.0.cmp(&b.0));
        out
    }

    /// 超出标签基数上限后被丢弃归因的操作次数
    pub fn service_label_overflow(&self) -> u64 {
        self.inner.service_label_overflow.load(Ordering::Relaxed)
    }

    /// Set a gauge metric
    pub fn set_gauge(&self, key: &str, value: f64) {
        self.inner
            .dynamic_metrics
            .insert(key.to_string(), MetricValue::Gauge(value));
    }

    /// Record a histogram value
    pub fn record_histogram(&self, key: &str, value: f64) {
        self.inner
            .dynamic_metrics
            .entry(key.to_string())
            .and_modify(|metric| {
                if let MetricValue::Histogram(hist) = metric {
                    hist.count += 1;
                    hist.sum += value;
                    hist.min = hist.min.min(value);
                    hist.max = hist.max.max(value);

                    // Update buckets
                    for (boundary, count) in &mut hist.buckets {
                        if value <= *boundary {
                            *count += 1;
                        }
                    }
                }
            })
            .or_insert_with(|| {
                let buckets = self
                    .inner
                    .config
                    .histogram_buckets
                    .iter()
                    .map(|&boundary| (boundary, if value <= boundary { 1 } else { 0 }))
                    .collect();

                MetricValue::Histogram(HistogramData {
                    count: 1,
                    sum: value,
                    min: value,
                    max: value,
                    buckets,
                })
            });
    }

    /// Record a timer value
    pub fn record_timer(&self, key: &str, duration: Duration) {
        self.inner
            .dynamic_metrics
            .entry(key.to_string())
            .and_modify(|metric| {
                if let MetricValue::Timer(timer) = metric {
                    timer.count += 1;
                    timer.total_duration += duration;
                    timer.min_duration = timer.min_duration.min(duration);
                    timer.max_duration = timer.max_duration.max(duration);
                }
            })
            .or_insert_with(|| {
                MetricValue::Timer(TimerData {
                    count: 1,
                    total_duration: duration,
                    min_duration: duration,
                    max_duration: duration,
                })
            });
    }

    /// Get atomic counter values
    pub fn get_counters(&self) -> CounterSnapshot {
        CounterSnapshot {
            l1_hits: self.inner.counters.l1_hits.load(Ordering::Relaxed),
            l1_misses: self.inner.counters.l1_misses.load(Ordering::Relaxed),
            l2_hits: self.inner.counters.l2_hits.load(Ordering::Relaxed),
            l2_misses: self.inner.counters.l2_misses.load(Ordering::Relaxed),
            l1_sets: self.inner.counters.l1_sets.load(Ordering::Relaxed),
            l2_sets: self.inner.counters.l2_sets.load(Ordering::Relaxed),
            l1_deletes: self.inner.counters.l1_deletes.load(Ordering::Relaxed),
            l2_deletes: self.inner.counters.l2_deletes.load(Ordering::Relaxed),
            total_operations: self.inner.counters.total_operations.load(Ordering::Relaxed),
            errors: self.inner.counters.errors.load(Ordering::Relaxed),
            prefetch_total: self.inner.counters.prefetch_total.load(Ordering::Relaxed),
            compression_total: self
                .inner
                .counters
                .compression_total
                .load(Ordering::Relaxed),
            compression_bytes_saved: self
                .inner
                .counters
                .compression_bytes_saved
                .load(Ordering::Relaxed),
            l1_items: self.inner.counters.l1_items.load(Ordering::Relaxed),
            l1_capacity_used: self.inner.counters.l1_capacity_used.load(Ordering::Relaxed),
            l2_degraded: self.inner.counters.l2_degraded.load(Ordering::Relaxed),
            l2_retry_total: self.inner.counters.l2_retry_total.load(Ordering::Relaxed),
            backfill_success: self.inner.counters.backfill_success.load(Ordering::Relaxed),
            backfill_failed: self.inner.counters.backfill_failed.load(Ordering::Relaxed),
            evictions: self.inner.counters.evictions.load(Ordering::Relaxed),
        }
    }

    /// Get all dynamic metrics
    pub fn get_dynamic_metrics(&self) -> std::collections::HashMap<String, MetricValue> {
        self.inner
            .dynamic_metrics
            .iter()
            .map(|r| (r.key().clone(), r.value().clone()))
            .collect()
    }

    /// Create a comprehensive snapshot
    pub fn snapshot(&self) -> MetricsSnapshot {
        MetricsSnapshot {
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            counters: self.get_counters(),
            dynamic_metrics: self.get_dynamic_metrics(),
            service_operations: self.service_operation_counters().into_iter().collect(),
        }
    }

    /// Reset all metrics
    pub fn reset(&self) {
        // Reset atomic counters
        self.inner.counters.l1_hits.store(0, Ordering::Relaxed);
        self.inner.counters.l1_misses.store(0, Ordering::Relaxed);
        self.inner.counters.l2_hits.store(0, Ordering::Relaxed);
        self.inner.counters.l2_misses.store(0, Ordering::Relaxed);
        self.inner.counters.l1_sets.store(0, Ordering::Relaxed);
        self.inner.counters.l2_sets.store(0, Ordering::Relaxed);
        self.inner.counters.l1_deletes.store(0, Ordering::Relaxed);
        self.inner.counters.l2_deletes.store(0, Ordering::Relaxed);
        self.inner
            .counters
            .total_operations
            .store(0, Ordering::Relaxed);
        self.inner.counters.errors.store(0, Ordering::Relaxed);
        self.inner
            .counters
            .prefetch_total
            .store(0, Ordering::Relaxed);
        self.inner
            .counters
            .compression_total
            .store(0, Ordering::Relaxed);
        self.inner
            .counters
            .compression_bytes_saved
            .store(0, Ordering::Relaxed);
        self.inner.counters.l1_items.store(0, Ordering::Relaxed);
        self.inner
            .counters
            .l1_capacity_used
            .store(0, Ordering::Relaxed);
        self.inner.counters.l2_degraded.store(0, Ordering::Relaxed);
        self.inner
            .counters
            .l2_retry_total
            .store(0, Ordering::Relaxed);
        self.inner
            .counters
            .backfill_success
            .store(0, Ordering::Relaxed);
        self.inner
            .counters
            .backfill_failed
            .store(0, Ordering::Relaxed);
        self.inner.counters.evictions.store(0, Ordering::Relaxed);

        // Clear dynamic metrics
        self.inner.dynamic_metrics.clear();

        // Clear service dimension(R9)
        self.inner.service_operation_counters.clear();
        self.inner
            .service_label_overflow
            .store(0, Ordering::Relaxed);
    }

    /// Export metrics in Prometheus format
    pub fn export_prometheus(&self) -> String {
        let snapshot = self.snapshot();
        snapshot.export_prometheus()
    }

    /// Export metrics in JSON format
    #[cfg(any(feature = "serialization", feature = "full"))]
    pub fn export_json(&self) -> Result<String, serde_json::Error> {
        let snapshot = self.snapshot();
        serde_json::to_string_pretty(&snapshot)
    }

    /// Calculate hit rates
    pub fn hit_rates(&self) -> HitRates {
        let counters = self.get_counters();

        let l1_total = counters.l1_hits.saturating_add(counters.l1_misses);
        let l2_total = counters.l2_hits.saturating_add(counters.l2_misses);
        let total_hits = counters.l1_hits.saturating_add(counters.l2_hits);
        let total_misses = counters.l1_misses.saturating_add(counters.l2_misses);
        let overall_total = total_hits.saturating_add(total_misses);

        HitRates {
            l1_hit_rate: if l1_total > 0 {
                counters.l1_hits as f64 / l1_total as f64
            } else {
                0.0
            },
            l2_hit_rate: if l2_total > 0 {
                counters.l2_hits as f64 / l2_total as f64
            } else {
                0.0
            },
            overall_hit_rate: if overall_total > 0 {
                total_hits as f64 / overall_total as f64
            } else {
                0.0
            },
        }
    }

    /// Record an L2 retry event.
    pub fn record_l2_retry(&self) {
        self.inner
            .counters
            .l2_retry_total
            .fetch_add(1, Ordering::Relaxed);
    }

    /// Record an L2 degradation event (circuit breaker opened).
    pub fn record_l2_degraded(&self) {
        self.inner
            .counters
            .l2_degraded
            .fetch_add(1, Ordering::Relaxed);
    }

    /// Record a backfill success event.
    pub fn record_backfill_success(&self) {
        self.inner
            .counters
            .backfill_success
            .fetch_add(1, Ordering::Relaxed);
    }

    /// Record a backfill failure event.
    pub fn record_backfill_failed(&self) {
        self.inner
            .counters
            .backfill_failed
            .fetch_add(1, Ordering::Relaxed);
    }

    /// Record eviction / expiry removals.
    ///
    /// `count` is the number of entries removed (batch eviction supported).
    pub fn record_eviction(&self, count: u64) {
        self.inner
            .counters
            .evictions
            .fetch_add(count, Ordering::Relaxed);
    }

    /// Current eviction counter value.
    pub fn eviction_count(&self) -> u64 {
        self.inner.counters.evictions.load(Ordering::Relaxed)
    }

    /// Record one operation latency sample (in **seconds**) into the
    /// standard Prometheus latency histogram
    /// ([`OPERATION_LATENCY_HISTOGRAM`]).
    ///
    /// Uses fixed Prometheus-style buckets; cumulative semantics
    /// (`value <= boundary`), matching exposition format expectations.
    pub fn record_latency_seconds(&self, seconds: f64) {
        let value = if seconds.is_nan() || seconds.is_sign_negative() {
            0.0
        } else {
            seconds
        };
        self.inner
            .dynamic_metrics
            .entry(OPERATION_LATENCY_HISTOGRAM.to_string())
            .and_modify(|metric| {
                if let MetricValue::Histogram(hist) = metric {
                    hist.count += 1;
                    hist.sum += value;
                    hist.min = hist.min.min(value);
                    hist.max = hist.max.max(value);
                    for (boundary, count) in &mut hist.buckets {
                        if value <= *boundary {
                            *count += 1;
                        }
                    }
                }
            })
            .or_insert_with(|| {
                let buckets = PROMETHEUS_LATENCY_BUCKETS
                    .iter()
                    .map(|&boundary| (boundary, u64::from(value <= boundary)))
                    .collect();
                MetricValue::Histogram(HistogramData {
                    count: 1,
                    sum: value,
                    min: value,
                    max: value,
                    buckets,
                })
            });
    }

    /// Export metrics in **standard Prometheus exposition format**.
    ///
    /// Emits compliant `# HELP` / `# TYPE` headers with `oxcache_*` metric
    /// names: hits/misses (per layer), sets/deletes, evictions, operations,
    /// errors and the operation latency histogram in seconds.
    ///
    /// The legacy [`export_prometheus`](Self::export_prometheus) output is
    /// kept unchanged for backward compatibility.
    pub fn export_prometheus_standard(&self) -> String {
        let counters = self.get_counters();
        let mut out = String::with_capacity(2048);

        let counter_line = |out: &mut String, name: &str, help: &str| {
            out.push_str(&format!("# HELP {name} {help}.\n"));
            out.push_str(&format!("# TYPE {name} counter\n"));
        };

        counter_line(&mut out, "oxcache_hits_total", "Total cache hits");
        out.push_str(&format!(
            "oxcache_hits_total{{layer=\"l1\"}} {}\n",
            counters.l1_hits
        ));
        out.push_str(&format!(
            "oxcache_hits_total{{layer=\"l2\"}} {}\n",
            counters.l2_hits
        ));

        counter_line(&mut out, "oxcache_misses_total", "Total cache misses");
        out.push_str(&format!(
            "oxcache_misses_total{{layer=\"l1\"}} {}\n",
            counters.l1_misses
        ));
        out.push_str(&format!(
            "oxcache_misses_total{{layer=\"l2\"}} {}\n",
            counters.l2_misses
        ));

        counter_line(&mut out, "oxcache_sets_total", "Total cache writes");
        out.push_str(&format!(
            "oxcache_sets_total{{layer=\"l1\"}} {}\n",
            counters.l1_sets
        ));
        out.push_str(&format!(
            "oxcache_sets_total{{layer=\"l2\"}} {}\n",
            counters.l2_sets
        ));

        counter_line(&mut out, "oxcache_deletes_total", "Total cache deletions");
        out.push_str(&format!(
            "oxcache_deletes_total{{layer=\"l1\"}} {}\n",
            counters.l1_deletes
        ));
        out.push_str(&format!(
            "oxcache_deletes_total{{layer=\"l2\"}} {}\n",
            counters.l2_deletes
        ));

        counter_line(&mut out, "oxcache_evictions_total", "Total cache evictions");
        out.push_str(&format!("oxcache_evictions_total {}\n", counters.evictions));

        counter_line(
            &mut out,
            "oxcache_operations_total",
            "Total cache operations",
        );
        out.push_str(&format!(
            "oxcache_operations_total {}\n",
            counters.total_operations
        ));

        counter_line(&mut out, "oxcache_errors_total", "Total cache errors");
        out.push_str(&format!("oxcache_errors_total {}\n", counters.errors));

        // Backend-labeled operation counters (dynamic, sorted deterministically)
        for (key, count) in &self.backend_operation_counters() {
            let backend = key
                .trim_start_matches("oxcache_backend_")
                .trim_end_matches("_operations_total");
            out.push_str(&format!("# HELP {key} Operations on backend {backend}.\n"));
            out.push_str(&format!("# TYPE {key} counter\n"));
            out.push_str(&format!(
                "{key}{{backend=\"{}\"}} {count}\n",
                escape_prometheus_label_value(backend)
            ));
        }

        // Service-labeled operation counters (R9, sorted deterministically).
        // 默认关闭:无显式 service 归因时本节整体缺席(导出与既有格式兼容)
        let service_counters = self.service_operation_counters();
        if !service_counters.is_empty() {
            out.push_str(
                "# HELP oxcache_service_operations_total Operations attributed to service labels.\n",
            );
            out.push_str("# TYPE oxcache_service_operations_total counter\n");
            for (service, count) in &service_counters {
                out.push_str(&format!(
                    "oxcache_service_operations_total{{service=\"{}\"}} {count}\n",
                    escape_prometheus_label_value(service)
                ));
            }
        }

        // 溢出计数独立门控:即使 service map 为空(如 max_service_labels=0),
        // 被丢弃的归因次数也必须在导出面可观测
        let overflow = self.service_label_overflow();
        if overflow > 0 {
            out.push_str(
                "# HELP oxcache_service_labels_overflow_total Operations dropped after the service label cardinality cap.\n",
            );
            out.push_str("# TYPE oxcache_service_labels_overflow_total counter\n");
            out.push_str(&format!(
                "oxcache_service_labels_overflow_total {overflow}\n"
            ));
        }

        // Latency histogram (seconds, cumulative buckets + +Inf + sum/count)
        out.push_str(
            "# HELP oxcache_operation_duration_seconds Cache operation latency in seconds.\n",
        );
        out.push_str("# TYPE oxcache_operation_duration_seconds histogram\n");
        if let Some(MetricValue::Histogram(hist)) = self
            .inner
            .dynamic_metrics
            .get(OPERATION_LATENCY_HISTOGRAM)
            .map(|r| r.value().clone())
        {
            for (boundary, count) in &hist.buckets {
                out.push_str(&format!(
                    "oxcache_operation_duration_seconds_bucket{{le=\"{boundary}\"}} {count}\n"
                ));
            }
            out.push_str(&format!(
                "oxcache_operation_duration_seconds_bucket{{le=\"+Inf\"}} {}\n",
                hist.count
            ));
            out.push_str(&format!(
                "oxcache_operation_duration_seconds_sum {}\n",
                hist.sum
            ));
            out.push_str(&format!(
                "oxcache_operation_duration_seconds_count {}\n",
                hist.count
            ));
        } else {
            out.push_str("oxcache_operation_duration_seconds_bucket{le=\"+Inf\"} 0\n");
            out.push_str("oxcache_operation_duration_seconds_sum 0\n");
            out.push_str("oxcache_operation_duration_seconds_count 0\n");
        }

        out
    }
}

/// Standard Prometheus metric name of the operation latency histogram
pub const OPERATION_LATENCY_HISTOGRAM: &str = "oxcache_operation_duration_seconds";

/// Escape a label value for the Prometheus text exposition format
///(`\\` → `\\\\`、`"` → `\"`、`\n` → `\n`)——标签值是自由表单字符串
///(如 R9 service 名),不转义会静默破坏格式或伪造额外序列
pub(crate) fn escape_prometheus_label_value(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            other => out.push(other),
        }
    }
    out
}

/// Fixed buckets (seconds) for the standard latency histogram
pub const PROMETHEUS_LATENCY_BUCKETS: &[f64] = &[
    0.000_1, 0.000_5, 0.001, 0.005, 0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
];

/// Cache operation information
#[derive(Debug, Clone)]
pub struct CacheOperation {
    pub layer: CacheLayer,
    pub op_type: CacheOpType,
    pub result: CacheOpResult,
}

/// Cache operation type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CacheOpType {
    Get,
    Set,
    Delete,
    Clear,
}

impl std::fmt::Display for CacheOpType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CacheOpType::Get => write!(f, "Get"),
            CacheOpType::Set => write!(f, "Set"),
            CacheOpType::Delete => write!(f, "Delete"),
            CacheOpType::Clear => write!(f, "Clear"),
        }
    }
}

/// Cache operation result
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CacheOpResult {
    Hit,
    Miss,
    Success,
    Error,
}

impl std::fmt::Display for CacheOpResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CacheOpResult::Hit => write!(f, "Hit"),
            CacheOpResult::Miss => write!(f, "Miss"),
            CacheOpResult::Success => write!(f, "Success"),
            CacheOpResult::Error => write!(f, "Error"),
        }
    }
}

/// Snapshot of atomic counters
#[derive(Debug, Clone, Serialize)]
pub struct CounterSnapshot {
    pub l1_hits: u64,
    pub l1_misses: u64,
    pub l2_hits: u64,
    pub l2_misses: u64,
    pub l1_sets: u64,
    pub l2_sets: u64,
    pub l1_deletes: u64,
    pub l2_deletes: u64,
    pub total_operations: u64,
    pub errors: u64,
    pub prefetch_total: u64,
    pub compression_total: u64,
    pub compression_bytes_saved: u64,
    /// L1 cache item count (not yet wired to cache operations)
    pub l1_items: u64,
    /// L1 cache capacity used in bytes (not yet wired to cache operations)
    pub l1_capacity_used: u64,
    /// L2 degradation events (circuit breaker opened)
    pub l2_degraded: u64,
    /// L2 retry attempts total
    pub l2_retry_total: u64,
    /// Backfill success count
    pub backfill_success: u64,
    /// Backfill failure count
    pub backfill_failed: u64,
    /// Eviction / expiry removal count
    pub evictions: u64,
}

/// Comprehensive metrics snapshot
#[derive(Debug, Clone, Serialize)]
pub struct MetricsSnapshot {
    /// Unix timestamp (seconds since epoch)
    pub timestamp: u64,
    pub counters: CounterSnapshot,
    pub dynamic_metrics: std::collections::HashMap<String, MetricValue>,
    /// Per-service operation totals(R9;无显式 service 归因时为空 map)
    #[serde(skip_serializing_if = "std::collections::HashMap::is_empty")]
    pub service_operations: std::collections::HashMap<String, u64>,
}

/// Hit rate calculations
#[derive(Debug, Clone)]
pub struct HitRates {
    pub l1_hit_rate: f64,
    pub l2_hit_rate: f64,
    pub overall_hit_rate: f64,
}

impl MetricsSnapshot {
    /// Export in Prometheus format
    pub fn export_prometheus(&self) -> String {
        let mut output = String::new();
        output.push_str("# Cache Metrics Snapshot\n");
        output.push_str(&format!("# Generated at: {}\n", self.timestamp));

        // Export counters
        output.push_str(&format!("cache_l1_hits_total {}\n", self.counters.l1_hits));
        output.push_str(&format!(
            "cache_l1_misses_total {}\n",
            self.counters.l1_misses
        ));
        output.push_str(&format!("cache_l2_hits_total {}\n", self.counters.l2_hits));
        output.push_str(&format!(
            "cache_l2_misses_total {}\n",
            self.counters.l2_misses
        ));
        output.push_str(&format!("cache_l1_sets_total {}\n", self.counters.l1_sets));
        output.push_str(&format!("cache_l2_sets_total {}\n", self.counters.l2_sets));
        output.push_str(&format!(
            "cache_l1_deletes_total {}\n",
            self.counters.l1_deletes
        ));
        output.push_str(&format!(
            "cache_l2_deletes_total {}\n",
            self.counters.l2_deletes
        ));
        output.push_str(&format!(
            "cache_operations_total {}\n",
            self.counters.total_operations
        ));
        output.push_str(&format!("cache_errors_total {}\n", self.counters.errors));
        output.push_str(&format!(
            "cache_evictions_total {}\n",
            self.counters.evictions
        ));
        output.push_str(&format!("cache_l1_items {}\n", self.counters.l1_items));
        output.push_str(&format!(
            "cache_l1_capacity_used_bytes {}\n",
            self.counters.l1_capacity_used
        ));
        output.push_str(&format!(
            "cache_l2_degraded_total {}\n",
            self.counters.l2_degraded
        ));
        output.push_str(&format!(
            "cache_l2_retry_total {}\n",
            self.counters.l2_retry_total
        ));
        output.push_str(&format!(
            "cache_backfill_success_total {}\n",
            self.counters.backfill_success
        ));
        output.push_str(&format!(
            "cache_backfill_failed_total {}\n",
            self.counters.backfill_failed
        ));

        // Export dynamic metrics
        for (key, value) in &self.dynamic_metrics {
            match value {
                MetricValue::Counter(count) => {
                    output.push_str(&format!("{}_counter {}\n", key, count));
                }
                MetricValue::Gauge(value) => {
                    output.push_str(&format!("{}_gauge {}\n", key, value));
                }
                MetricValue::Histogram(hist) => {
                    output.push_str(&format!("{}_histogram_sum {}\n", key, hist.sum));
                    output.push_str(&format!("{}_histogram_count {}\n", key, hist.count));
                    for (boundary, count) in &hist.buckets {
                        output.push_str(&format!(
                            "{}_histogram_bucket{{le=\"{}\"}} {}\n",
                            key, boundary, count
                        ));
                    }
                }
                MetricValue::Timer(timer) => {
                    output.push_str(&format!(
                        "{}_timer_seconds_sum {}\n",
                        key,
                        timer.total_duration.as_secs_f64()
                    ));
                    output.push_str(&format!("{}_timer_seconds_count {}\n", key, timer.count));
                }
                MetricValue::Text(text) => {
                    output.push_str(&format!("{}_info \"{}\"\n", key, text));
                }
            }
        }

        output
    }
}

/// Global unified metrics instance
pub static GLOBAL_UNIFIED_METRICS: Lazy<UnifiedMetrics> = Lazy::new(UnifiedMetrics::new);

/// Convenience functions for global metrics
pub mod convenience {
    use super::*;

    /// Record a cache operation using global metrics
    pub fn record_operation(operation: CacheOperation) {
        GLOBAL_UNIFIED_METRICS.record_operation(operation);
    }

    /// Get global hit rates
    pub fn hit_rates() -> HitRates {
        GLOBAL_UNIFIED_METRICS.hit_rates()
    }

    /// Export global metrics in Prometheus format
    pub fn export_prometheus() -> String {
        GLOBAL_UNIFIED_METRICS.export_prometheus()
    }

    /// Export global metrics in JSON format
    #[cfg(any(feature = "serialization", feature = "full"))]
    pub fn export_json() -> Result<String, serde_json::Error> {
        GLOBAL_UNIFIED_METRICS.export_json()
    }

    /// Reset global metrics
    pub fn reset() {
        GLOBAL_UNIFIED_METRICS.reset();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_atomic_counters() {
        let metrics = UnifiedMetrics::new();

        // Record some operations
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Hit,
        });

        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Miss,
        });

        let counters = metrics.get_counters();
        assert_eq!(counters.l1_hits, 1);
        assert_eq!(counters.l1_misses, 1);
        assert_eq!(counters.total_operations, 2);
    }

    #[test]
    fn test_hit_rates() {
        let metrics = UnifiedMetrics::new();

        // Record operations
        for _ in 0..7 {
            metrics.record_operation(CacheOperation {
                layer: CacheLayer::L1,
                op_type: CacheOpType::Get,
                result: CacheOpResult::Hit,
            });
        }

        for _ in 0..3 {
            metrics.record_operation(CacheOperation {
                layer: CacheLayer::L1,
                op_type: CacheOpType::Get,
                result: CacheOpResult::Miss,
            });
        }

        let hit_rates = metrics.hit_rates();
        assert_eq!(hit_rates.l1_hit_rate, 0.7);
        assert_eq!(hit_rates.l2_hit_rate, 0.0);
        assert_eq!(hit_rates.overall_hit_rate, 0.7);
    }

    #[test]
    fn test_dynamic_metrics() {
        let metrics = UnifiedMetrics::new();

        // Test counter
        metrics.increment_counter("test_counter", 5);
        metrics.increment_counter("test_counter", 3);

        // Test gauge
        metrics.set_gauge("test_gauge", 42.5);

        // Test histogram
        metrics.record_histogram("test_histogram", 1.5);
        metrics.record_histogram("test_histogram", 2.7);

        // Test timer
        metrics.record_timer("test_timer", Duration::from_millis(100));
        metrics.record_timer("test_timer", Duration::from_millis(200));

        let dynamic_metrics = metrics.get_dynamic_metrics();

        let counter_metric = dynamic_metrics.get("test_counter");
        assert!(
            matches!(counter_metric, Some(MetricValue::Counter(count)) if *count == 8),
            "Expected counter metric with value 8, got {:?}",
            counter_metric
        );

        let gauge_metric = dynamic_metrics.get("test_gauge");
        assert!(
            matches!(gauge_metric, Some(MetricValue::Gauge(value)) if *value == 42.5),
            "Expected gauge metric with value 42.5, got {:?}",
            gauge_metric
        );
    }

    #[test]
    fn test_snapshot() {
        let metrics = UnifiedMetrics::new();

        // Record some operations
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Set,
            result: CacheOpResult::Success,
        });

        let snapshot = metrics.snapshot();
        assert_eq!(snapshot.counters.l1_sets, 1);
        assert!(
            snapshot.dynamic_metrics.is_empty()
                || !snapshot.dynamic_metrics.contains_key("detailed")
        );

        // Test export
        let prometheus = snapshot.export_prometheus();
        assert!(prometheus.contains("cache_l1_sets_total 1"));

        let json = serde_json::to_string_pretty(&snapshot).unwrap();
        assert!(json.contains("l1_sets"));
    }

    #[test]
    // 重置全局单例,必须与其它读写全局指标的测试互斥(并行竞态曾致 offload delta 断言偶败)
    #[serial_test::serial]
    fn test_global_metrics() {
        // Reset global metrics
        convenience::reset();

        // Record operation using global metrics
        convenience::record_operation(CacheOperation {
            layer: CacheLayer::L2,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Hit,
        });

        let hit_rates = convenience::hit_rates();
        assert_eq!(hit_rates.l2_hit_rate, 1.0);

        let prometheus = convenience::export_prometheus();
        assert!(prometheus.contains("cache_l2_hits_total 1"));
    }

    #[test]
    fn test_unified_metrics_default_impl() {
        // Triggers Default for UnifiedMetricsInner (lines 45, 47-49)
        let metrics = UnifiedMetrics::default();
        let counters = metrics.get_counters();
        assert_eq!(counters.l1_hits, 0);
        assert_eq!(counters.total_operations, 0);
    }

    #[test]
    fn test_unified_metrics_debug_format() {
        // Triggers Debug for UnifiedMetricsInner (lines 35-39)
        let metrics = UnifiedMetrics::new();
        let debug_str = format!("{:?}", metrics);
        assert!(debug_str.contains("UnifiedMetrics"));
        assert!(debug_str.contains("UnifiedMetricsInner"));
        assert!(debug_str.contains("dynamic_metrics"));
        assert!(debug_str.contains("config"));
    }

    #[test]
    fn test_l2_get_miss_operation() {
        // Covers lines 205-206
        let metrics = UnifiedMetrics::new();
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L2,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Miss,
        });
        let counters = metrics.get_counters();
        assert_eq!(counters.l2_misses, 1);
        assert_eq!(counters.total_operations, 1);
    }

    #[test]
    fn test_l2_set_success_operation() {
        // Covers lines 213-214
        let metrics = UnifiedMetrics::new();
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L2,
            op_type: CacheOpType::Set,
            result: CacheOpResult::Success,
        });
        let counters = metrics.get_counters();
        assert_eq!(counters.l2_sets, 1);
        assert_eq!(counters.total_operations, 1);
    }

    #[test]
    fn test_l1_delete_success_operation() {
        // Covers lines 217-218
        let metrics = UnifiedMetrics::new();
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Delete,
            result: CacheOpResult::Success,
        });
        let counters = metrics.get_counters();
        assert_eq!(counters.l1_deletes, 1);
        assert_eq!(counters.total_operations, 1);
    }

    #[test]
    fn test_l2_delete_success_operation() {
        // Covers lines 221-222
        let metrics = UnifiedMetrics::new();
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L2,
            op_type: CacheOpType::Delete,
            result: CacheOpResult::Success,
        });
        let counters = metrics.get_counters();
        assert_eq!(counters.l2_deletes, 1);
        assert_eq!(counters.total_operations, 1);
    }

    #[test]
    fn test_error_result_operation() {
        // Covers lines 225-226 (the Error arm)
        let metrics = UnifiedMetrics::new();
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Error,
        });
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L2,
            op_type: CacheOpType::Set,
            result: CacheOpResult::Error,
        });
        let counters = metrics.get_counters();
        assert_eq!(counters.errors, 2);
        assert_eq!(counters.total_operations, 2);
    }

    #[test]
    fn test_record_duration_with_detailed_disabled() {
        // Covers lines 242-243 (early return when detailed=false)
        let config = MetricsConfig {
            detailed: false,
            ..MetricsConfig::default()
        };
        let metrics = UnifiedMetrics::with_config(config);
        let op = CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Hit,
        };
        // Should be a no-op (early return)
        metrics.record_duration(&op, Duration::from_millis(100));
        let dynamic = metrics.get_dynamic_metrics();
        assert!(!dynamic.keys().any(|k| k.contains("duration")));
    }

    #[test]
    fn test_record_duration_with_detailed_enabled() {
        // Covers lines 247-248 (record_timer call)
        let metrics = UnifiedMetrics::new();
        let op = CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Hit,
        };
        metrics.record_duration(&op, Duration::from_millis(150));
        let dynamic = metrics.get_dynamic_metrics();
        let timer_key = "cache:duration:L1:Get";
        assert!(
            dynamic.contains_key(timer_key),
            "Expected timer metric at key {}",
            timer_key
        );
        match dynamic.get(timer_key) {
            Some(MetricValue::Timer(t)) => {
                assert_eq!(t.count, 1);
                assert_eq!(t.total_duration, Duration::from_millis(150));
            }
            other => panic!("Expected Timer, got {:?}", other),
        }
    }

    #[test]
    fn test_record_custom_at_capacity_check() {
        // Covers lines 252-253 (capacity check) and 259 (insert).
        // Uses max_dynamic_metrics=0 so the capacity check triggers on an empty map.
        // When the map is empty, iter().next() returns None, so the eviction body
        // (line 256) is skipped — avoiding a deadlock that exists in record_custom
        // when iter().next() returns Some and remove() is called while the iterator
        // still holds a read lock on the DashMap shard.
        let config = MetricsConfig {
            max_dynamic_metrics: 0,
            ..MetricsConfig::default()
        };
        let metrics = UnifiedMetrics::with_config(config);

        // Capacity check triggers (0 >= 0), but map is empty so no eviction.
        metrics.record_custom("only_metric", MetricValue::Counter(1));
        let dynamic = metrics.get_dynamic_metrics();
        assert!(
            dynamic.contains_key("only_metric"),
            "metric should be present after insert"
        );
        assert_eq!(dynamic.len(), 1);
    }

    #[test]
    fn test_record_custom_under_capacity_no_eviction() {
        let config = MetricsConfig {
            max_dynamic_metrics: 10,
            ..MetricsConfig::default()
        };
        let metrics = UnifiedMetrics::with_config(config);
        metrics.record_custom("a", MetricValue::Counter(1));
        metrics.record_custom("b", MetricValue::Counter(2));
        let dynamic = metrics.get_dynamic_metrics();
        assert_eq!(dynamic.len(), 2);
        assert!(dynamic.contains_key("a"));
        assert!(dynamic.contains_key("b"));
    }

    #[test]
    fn test_export_json_method() {
        // Covers lines 416-418 (export_json method on UnifiedMetrics)
        let metrics = UnifiedMetrics::new();
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Hit,
        });
        let json = metrics.export_json().unwrap();
        assert!(json.contains("counters"));
        assert!(json.contains("l1_hits"));
        assert!(json.contains("dynamic_metrics"));
    }

    #[test]
    fn test_cache_op_type_clear_display() {
        // Covers line 473-474 (CacheOpType::Clear Display arm)
        assert_eq!(CacheOpType::Clear.to_string(), "Clear");
    }

    #[test]
    fn test_cache_op_type_all_display_variants() {
        // Covers all Display arms for CacheOpType
        assert_eq!(CacheOpType::Get.to_string(), "Get");
        assert_eq!(CacheOpType::Set.to_string(), "Set");
        assert_eq!(CacheOpType::Delete.to_string(), "Delete");
        assert_eq!(CacheOpType::Clear.to_string(), "Clear");
    }

    #[test]
    fn test_cache_op_result_error_display() {
        // Covers line 494 (CacheOpResult::Error Display arm)
        assert_eq!(CacheOpResult::Error.to_string(), "Error");
    }

    #[test]
    fn test_cache_op_result_all_display_variants() {
        // Covers all Display arms for CacheOpResult
        assert_eq!(CacheOpResult::Hit.to_string(), "Hit");
        assert_eq!(CacheOpResult::Miss.to_string(), "Miss");
        assert_eq!(CacheOpResult::Success.to_string(), "Success");
        assert_eq!(CacheOpResult::Error.to_string(), "Error");
    }

    #[test]
    fn test_export_prometheus_gauge_metric() {
        // Covers lines 561-562 (MetricValue::Gauge in export_prometheus)
        let metrics = UnifiedMetrics::new();
        metrics.set_gauge("my_gauge", 42.5);
        let prom = metrics.export_prometheus();
        assert!(prom.contains("my_gauge_gauge 42.5"));
    }

    #[test]
    fn test_export_prometheus_histogram_metric() {
        // Covers lines 564-568 (MetricValue::Histogram in export_prometheus)
        let metrics = UnifiedMetrics::new();
        metrics.record_histogram("my_histogram", 1.5);
        metrics.record_histogram("my_histogram", 2.5);
        let prom = metrics.export_prometheus();
        assert!(prom.contains("my_histogram_histogram_sum 4"));
        assert!(prom.contains("my_histogram_histogram_count 2"));
        // Buckets should be present
        assert!(prom.contains("my_histogram_histogram_bucket"));
        assert!(prom.contains("le=\""));
    }

    #[test]
    fn test_export_prometheus_timer_metric() {
        // Covers lines 571-572, 575, 577 (MetricValue::Timer in export_prometheus)
        let metrics = UnifiedMetrics::new();
        metrics.record_timer("my_timer", Duration::from_millis(250));
        let prom = metrics.export_prometheus();
        assert!(prom.contains("my_timer_timer_seconds_sum"));
        assert!(prom.contains("my_timer_timer_seconds_count 1"));
    }

    #[test]
    fn test_export_prometheus_text_metric() {
        // Covers lines 579-580 (MetricValue::Text in export_prometheus)
        let metrics = UnifiedMetrics::new();
        metrics.record_custom("my_info", MetricValue::Text("version1".to_string()));
        let prom = metrics.export_prometheus();
        assert!(prom.contains("my_info_info \"version1\""));
    }

    #[test]
    fn test_export_prometheus_counter_dynamic_metric() {
        // Covers line 559 (MetricValue::Counter in export_prometheus dynamic section)
        let metrics = UnifiedMetrics::new();
        metrics.increment_counter("my_dyn_counter", 7);
        let prom = metrics.export_prometheus();
        assert!(prom.contains("my_dyn_counter_counter 7"));
    }

    #[test]
    // 同 test_global_metrics:重置全局单例,须串行
    #[serial_test::serial]
    fn test_convenience_export_json() {
        // Covers lines 613-614 (convenience::export_json)
        convenience::reset();
        let json = convenience::export_json().unwrap();
        assert!(json.contains("counters"));
        assert!(json.contains("l1_hits"));
        assert!(json.contains("dynamic_metrics"));
    }

    #[test]
    fn test_metrics_config_default() {
        let config = MetricsConfig::default();
        assert!(config.detailed);
        assert!(!config.histogram_buckets.is_empty());
        assert_eq!(config.max_dynamic_metrics, 1000);
        assert_eq!(config.retention_period, Some(Duration::from_secs(3600)));
    }

    #[test]
    fn test_atomic_counters_default() {
        let counters = AtomicCounters::default();
        assert_eq!(counters.l1_hits.load(Ordering::Relaxed), 0);
        assert_eq!(counters.l1_misses.load(Ordering::Relaxed), 0);
        assert_eq!(counters.errors.load(Ordering::Relaxed), 0);
        assert_eq!(counters.prefetch_total.load(Ordering::Relaxed), 0);
    }

    #[test]
    fn test_reset_clears_all_metrics() {
        let metrics = UnifiedMetrics::new();
        metrics.record_operation(CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Hit,
        });
        metrics.increment_counter("custom", 5);
        assert!(!metrics.get_dynamic_metrics().is_empty());

        metrics.reset();
        let counters = metrics.get_counters();
        assert_eq!(counters.l1_hits, 0);
        assert_eq!(counters.total_operations, 0);
        assert!(metrics.get_dynamic_metrics().is_empty());
    }

    #[test]
    fn test_hit_rates_overall_default_is_zero() {
        // When no operations recorded, overall_hit_rate returns 0.0 (consistent with l1/l2)
        let metrics = UnifiedMetrics::new();
        let rates = metrics.hit_rates();
        assert_eq!(rates.l1_hit_rate, 0.0);
        assert_eq!(rates.l2_hit_rate, 0.0);
        assert_eq!(rates.overall_hit_rate, 0.0);
    }

    // ========================================================================
    // service 维度(R9):显式记录才计数、双格式可见、基数上限
    // ========================================================================

    fn l1_hit() -> CacheOperation {
        CacheOperation {
            layer: CacheLayer::L1,
            op_type: CacheOpType::Get,
            result: CacheOpResult::Hit,
        }
    }

    #[test]
    fn service_dimension_records_per_service_and_exports_prometheus() {
        let metrics = UnifiedMetrics::new();
        metrics.record_operation_with_service(&l1_hit(), "svc-a");
        metrics.record_operation_with_service(&l1_hit(), "svc-a");
        metrics.record_operation_with_service(&l1_hit(), "svc-b");

        // 原子总账照常递增(service 维度是附加拆分而非替代)
        assert_eq!(metrics.get_counters().l1_hits, 3);

        let export = metrics.export_prometheus_standard();
        assert!(
            export.contains("# HELP oxcache_service_operations_total"),
            "HELP line missing: {export}"
        );
        assert!(
            export.contains("# TYPE oxcache_service_operations_total counter"),
            "TYPE line missing: {export}"
        );
        assert!(
            export.contains("oxcache_service_operations_total{service=\"svc-a\"} 2"),
            "svc-a line missing: {export}"
        );
        assert!(
            export.contains("oxcache_service_operations_total{service=\"svc-b\"} 1"),
            "svc-b line missing: {export}"
        );
        // 未溢出时不出现溢出行
        assert!(!export.contains("service_labels_overflow"));
    }

    #[test]
    fn service_dimension_default_off() {
        // 默认(无 service 标签的 record_operation)不产生任何 service 行——
        // 未显式开启时导出与既有格式逐字节兼容
        let metrics = UnifiedMetrics::new();
        metrics.record_operation(l1_hit());
        assert_eq!(metrics.get_counters().l1_hits, 1);

        let export = metrics.export_prometheus_standard();
        assert!(
            !export.contains("oxcache_service_operations_total"),
            "service lines must be absent by default: {export}"
        );
        assert!(metrics.service_operation_counters().is_empty());
        // JSON 面同一承诺:skip_serializing_if 使空 map 整体缺席
        #[cfg(feature = "serialization")]
        {
            let json = metrics.export_json().unwrap();
            assert!(
                !json.contains("\"service_operations\""),
                "default snapshot JSON must omit service_operations: {json}"
            );
        }
    }

    #[test]
    fn service_dimension_cap_prevents_label_explosion() {
        let config = MetricsConfig {
            max_service_labels: 2,
            ..MetricsConfig::default()
        };
        let metrics = UnifiedMetrics::with_config(config);

        metrics.record_operation_with_service(&l1_hit(), "svc-1");
        metrics.record_operation_with_service(&l1_hit(), "svc-2");
        // 超出上限的第 3 个 service:不进 map,计入溢出计数;总账不受影响
        metrics.record_operation_with_service(&l1_hit(), "svc-3");
        metrics.record_operation_with_service(&l1_hit(), "svc-3");

        let counters = metrics.service_operation_counters();
        assert_eq!(counters.len(), 2, "cap must hold: {counters:?}");
        assert!(counters.iter().all(|(k, _)| k != "svc-3"));

        let export = metrics.export_prometheus_standard();
        assert!(
            !export.contains("svc-3"),
            "over-cap service must not appear: {export}"
        );
        assert!(
            export.contains("oxcache_service_labels_overflow_total 2"),
            "overflow counter must reflect dropped attributions: {export}"
        );
        // 总账照常
        assert_eq!(metrics.get_counters().l1_hits, 4);
    }

    #[cfg(feature = "serialization")]
    #[test]
    fn service_dimension_visible_in_json() {
        let metrics = UnifiedMetrics::new();
        metrics.record_operation_with_service(&l1_hit(), "orders");
        metrics.record_operation_with_service(&l1_hit(), "orders");

        let snapshot = metrics.snapshot();
        assert_eq!(
            snapshot.service_operations.get("orders"),
            Some(&2),
            "snapshot must carry per-service counters"
        );

        let json = metrics.export_json().unwrap();
        assert!(json.contains("\"service_operations\""), "json key: {json}");
        assert!(json.contains("\"orders\""), "json service name: {json}");
    }

    #[test]
    fn service_dimension_reset_clears_counters() {
        let metrics = UnifiedMetrics::new();
        metrics.record_operation_with_service(&l1_hit(), "svc-reset");
        metrics.reset();
        assert!(metrics.service_operation_counters().is_empty());
        let export = metrics.export_prometheus_standard();
        assert!(!export.contains("svc-reset"));
    }

    #[test]
    fn service_label_value_is_escaped_in_prometheus_export() {
        // 引号/反斜杠/换行必须转义:否则 exposition 格式被破坏或可伪造序列
        let metrics = UnifiedMetrics::new();
        let hostile = "svc\"quote\\back\nnewline";
        metrics.record_operation_with_service(&l1_hit(), hostile);
        metrics.record_operation_with_service(&l1_hit(), hostile);

        let export = metrics.export_prometheus_standard();
        let expected_line =
            "oxcache_service_operations_total{service=\"svc\\\"quote\\\\back\\nnewline\"} 2";
        assert!(
            export.contains(expected_line),
            "escaped service line missing: {export}"
        );
        // 序列总数不得因注入而增加:转义后恰好一行 service 计数序列
        assert_eq!(
            export
                .matches("oxcache_service_operations_total{service=")
                .count(),
            1,
            "hostile label must not forge extra series: {export}"
        );
        // 原始未转义字符不得出现
        assert!(!export.contains("svc\"quote"));
    }

    #[test]
    fn service_dimension_cap_zero_keeps_overflow_visible() {
        let config = MetricsConfig {
            max_service_labels: 0,
            ..MetricsConfig::default()
        };
        let metrics = UnifiedMetrics::with_config(config);
        metrics.record_operation_with_service(&l1_hit(), "svc-any");
        metrics.record_operation_with_service(&l1_hit(), "svc-any");

        // cap=0 时 map 恒空,但溢出次数必须在 prometheus 导出面可观测
        assert!(metrics.service_operation_counters().is_empty());
        assert_eq!(metrics.service_label_overflow(), 2);
        let export = metrics.export_prometheus_standard();
        assert!(
            export.contains("oxcache_service_labels_overflow_total 2"),
            "overflow must be exported even with empty service map: {export}"
        );
        // 总账照常
        assert_eq!(metrics.get_counters().l1_hits, 2);
    }

    #[test]
    fn service_dimension_concurrent_first_touch_has_no_lost_counts() {
        use std::sync::Arc;

        let metrics = Arc::new(UnifiedMetrics::new());
        // 多线程并发首触同一新 service:entry 合并语义下计数不得丢失
        let handles: Vec<_> = (0..8)
            .map(|_| {
                let metrics = Arc::clone(&metrics);
                std::thread::spawn(move || {
                    for _ in 0..250 {
                        metrics.record_operation_with_service(&l1_hit(), "svc-race");
                    }
                })
            })
            .collect();
        for handle in handles {
            handle.join().unwrap();
        }

        let counters = metrics.service_operation_counters();
        assert_eq!(
            counters.first().map(|(_, c)| *c),
            Some(2_000),
            "concurrent first-touch must not lose counts: {counters:?}"
        );
    }
}