amaters-server 0.2.0

AmateRS server binary
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
//! Metrics collection module
//!
//! Provides metrics collection for monitoring server performance including
//! histograms for latency tracking, per-operation type metrics, and storage metrics.

use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use parking_lot::Mutex;

// ---------------------------------------------------------------------------
// Histogram
// ---------------------------------------------------------------------------

/// Default histogram buckets (in seconds) for latency tracking
pub const DEFAULT_BUCKETS: [f64; 12] = [
    0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
];

/// A snapshot of histogram state at a point in time
#[derive(Debug, Clone)]
pub struct HistogramSnapshot {
    /// Upper bounds for each bucket
    pub buckets: Vec<f64>,
    /// Cumulative count for each bucket (index `i` = count of observations <= `buckets[i]`)
    pub counts: Vec<u64>,
    /// Total number of observations
    pub total_count: u64,
    /// Sum of all observed values
    pub sum: f64,
}

impl HistogramSnapshot {
    /// Calculate an approximate percentile (0.0..=1.0) from bucket data.
    ///
    /// Uses linear interpolation within the bucket that contains the target rank.
    /// Returns `None` if no observations have been recorded.
    pub fn percentile(&self, p: f64) -> Option<f64> {
        if self.total_count == 0 || !(0.0..=1.0).contains(&p) {
            return None;
        }

        let target = p * self.total_count as f64;

        let mut prev_count: u64 = 0;
        let mut prev_bound: f64 = 0.0;

        for (i, &upper) in self.buckets.iter().enumerate() {
            let cumulative = self.counts[i];
            if (cumulative as f64) >= target {
                // Linear interpolation within this bucket
                let bucket_count = cumulative - prev_count;
                if bucket_count == 0 {
                    return Some(upper);
                }
                let fraction = (target - prev_count as f64) / bucket_count as f64;
                let value = prev_bound + fraction * (upper - prev_bound);
                return Some(value);
            }
            prev_count = cumulative;
            prev_bound = upper;
        }

        // All observations are above the largest bucket
        // Return the largest bucket boundary as an approximation
        self.buckets.last().copied()
    }

    /// Convenience: p50
    pub fn p50(&self) -> Option<f64> {
        self.percentile(0.50)
    }

    /// Convenience: p95
    pub fn p95(&self) -> Option<f64> {
        self.percentile(0.95)
    }

    /// Convenience: p99
    pub fn p99(&self) -> Option<f64> {
        self.percentile(0.99)
    }
}

/// Thread-safe histogram for tracking value distributions.
///
/// Uses `parking_lot::Mutex` for interior mutability.
#[derive(Clone)]
pub struct Histogram {
    inner: Arc<Mutex<HistogramInner>>,
}

struct HistogramInner {
    buckets: Vec<f64>,
    counts: Vec<u64>,
    total_count: u64,
    sum: f64,
}

impl Histogram {
    /// Create a histogram with the default latency buckets.
    pub fn new() -> Self {
        Self::with_buckets(&DEFAULT_BUCKETS)
    }

    /// Create a histogram with custom bucket upper bounds.
    ///
    /// Buckets are sorted on creation.
    pub fn with_buckets(bounds: &[f64]) -> Self {
        let mut sorted = bounds.to_vec();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        let len = sorted.len();
        Self {
            inner: Arc::new(Mutex::new(HistogramInner {
                buckets: sorted,
                counts: vec![0; len],
                total_count: 0,
                sum: 0.0,
            })),
        }
    }

    /// Record a single observation.
    pub fn observe(&self, value: f64) {
        let mut inner = self.inner.lock();
        inner.total_count += 1;
        inner.sum += value;
        // Increment cumulative counts for all buckets whose bound >= value
        let len = inner.buckets.len();
        for i in 0..len {
            if value <= inner.buckets[i] {
                inner.counts[i] += 1;
            }
        }
    }

    /// Record a `Duration` as seconds.
    pub fn observe_duration(&self, d: Duration) {
        self.observe(d.as_secs_f64());
    }

    /// Take a snapshot of the current state.
    pub fn snapshot(&self) -> HistogramSnapshot {
        let inner = self.inner.lock();
        HistogramSnapshot {
            buckets: inner.buckets.clone(),
            counts: inner.counts.clone(),
            total_count: inner.total_count,
            sum: inner.sum,
        }
    }

    /// Reset all counts (useful for testing).
    #[cfg(test)]
    fn reset(&self) {
        let mut inner = self.inner.lock();
        for c in inner.counts.iter_mut() {
            *c = 0;
        }
        inner.total_count = 0;
        inner.sum = 0.0;
    }
}

impl Default for Histogram {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// OperationType
// ---------------------------------------------------------------------------

/// Types of database operations tracked individually.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OperationType {
    Get,
    Put,
    Delete,
    Range,
    Batch,
    Stream,
}

impl OperationType {
    /// All variants in definition order.
    pub const ALL: [OperationType; 6] = [
        OperationType::Get,
        OperationType::Put,
        OperationType::Delete,
        OperationType::Range,
        OperationType::Batch,
        OperationType::Stream,
    ];

    /// Lower-case label suitable for Prometheus metrics.
    pub fn as_label(&self) -> &'static str {
        match self {
            OperationType::Get => "get",
            OperationType::Put => "put",
            OperationType::Delete => "delete",
            OperationType::Range => "range",
            OperationType::Batch => "batch",
            OperationType::Stream => "stream",
        }
    }
}

impl fmt::Display for OperationType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_label())
    }
}

// ---------------------------------------------------------------------------
// Per-operation metrics
// ---------------------------------------------------------------------------

/// Metrics for a single operation type.
#[derive(Clone)]
struct OperationMetrics {
    count: Arc<AtomicU64>,
    errors: Arc<AtomicU64>,
    latency: Histogram,
}

impl OperationMetrics {
    fn new() -> Self {
        Self {
            count: Arc::new(AtomicU64::new(0)),
            errors: Arc::new(AtomicU64::new(0)),
            latency: Histogram::new(),
        }
    }
}

/// Snapshot of per-operation metrics.
#[derive(Debug, Clone)]
pub struct OperationSnapshot {
    pub op_type: OperationType,
    pub count: u64,
    pub errors: u64,
    pub latency: HistogramSnapshot,
}

// ---------------------------------------------------------------------------
// Storage metrics (gauges + counters)
// ---------------------------------------------------------------------------

/// Atomic gauge that supports increment, decrement, and direct set.
#[derive(Clone)]
struct AtomicGauge(Arc<AtomicU64>);

impl AtomicGauge {
    fn new() -> Self {
        Self(Arc::new(AtomicU64::new(0)))
    }

    fn inc(&self, v: u64) {
        self.0.fetch_add(v, Ordering::Relaxed);
    }

    fn dec(&self, v: u64) {
        self.0.fetch_sub(v, Ordering::Relaxed);
    }

    fn set(&self, v: u64) {
        self.0.store(v, Ordering::Relaxed);
    }

    fn get(&self) -> u64 {
        self.0.load(Ordering::Relaxed)
    }
}

/// Snapshot of storage-level metrics.
#[derive(Debug, Clone, Default)]
pub struct StorageSnapshot {
    pub memtable_size_bytes: u64,
    pub sstable_count: u64,
    pub compaction_count: u64,
    pub compaction_bytes_written: u64,
    pub wal_size_bytes: u64,
    pub block_cache_hits: u64,
    pub block_cache_misses: u64,
}

// ---------------------------------------------------------------------------
// MetricsCollector
// ---------------------------------------------------------------------------

/// Metrics collector
///
/// Tracks various server metrics using atomic counters, histograms, and gauges.
#[derive(Clone)]
pub struct MetricsCollector {
    // --- existing counters ---
    requests_total: Arc<AtomicU64>,
    requests_success: Arc<AtomicU64>,
    requests_failed: Arc<AtomicU64>,
    bytes_read: Arc<AtomicU64>,
    bytes_written: Arc<AtomicU64>,
    active_connections: Arc<AtomicU64>,
    queries_total: Arc<AtomicU64>,
    query_time_us: Arc<AtomicU64>,

    // --- request latency histogram ---
    request_latency: Histogram,

    // --- per-operation metrics ---
    op_get: OperationMetrics,
    op_put: OperationMetrics,
    op_delete: OperationMetrics,
    op_range: OperationMetrics,
    op_batch: OperationMetrics,
    op_stream: OperationMetrics,

    // --- storage gauges / counters ---
    memtable_size_bytes: AtomicGauge,
    sstable_count: AtomicGauge,
    compaction_count: AtomicGauge,
    compaction_bytes_written: AtomicGauge,
    wal_size_bytes: AtomicGauge,
    block_cache_hits: AtomicGauge,
    block_cache_misses: AtomicGauge,
}

impl MetricsCollector {
    /// Create a new metrics collector
    pub fn new() -> Self {
        Self {
            requests_total: Arc::new(AtomicU64::new(0)),
            requests_success: Arc::new(AtomicU64::new(0)),
            requests_failed: Arc::new(AtomicU64::new(0)),
            bytes_read: Arc::new(AtomicU64::new(0)),
            bytes_written: Arc::new(AtomicU64::new(0)),
            active_connections: Arc::new(AtomicU64::new(0)),
            queries_total: Arc::new(AtomicU64::new(0)),
            query_time_us: Arc::new(AtomicU64::new(0)),
            request_latency: Histogram::new(),
            op_get: OperationMetrics::new(),
            op_put: OperationMetrics::new(),
            op_delete: OperationMetrics::new(),
            op_range: OperationMetrics::new(),
            op_batch: OperationMetrics::new(),
            op_stream: OperationMetrics::new(),
            memtable_size_bytes: AtomicGauge::new(),
            sstable_count: AtomicGauge::new(),
            compaction_count: AtomicGauge::new(),
            compaction_bytes_written: AtomicGauge::new(),
            wal_size_bytes: AtomicGauge::new(),
            block_cache_hits: AtomicGauge::new(),
            block_cache_misses: AtomicGauge::new(),
        }
    }

    // --- existing counter methods ---

    /// Increment total requests
    pub fn inc_requests(&self) {
        self.requests_total.fetch_add(1, Ordering::Relaxed);
    }

    /// Increment successful requests
    pub fn inc_success(&self) {
        self.requests_success.fetch_add(1, Ordering::Relaxed);
    }

    /// Increment failed requests
    pub fn inc_failed(&self) {
        self.requests_failed.fetch_add(1, Ordering::Relaxed);
    }

    /// Add bytes read
    pub fn add_bytes_read(&self, bytes: u64) {
        self.bytes_read.fetch_add(bytes, Ordering::Relaxed);
    }

    /// Add bytes written
    pub fn add_bytes_written(&self, bytes: u64) {
        self.bytes_written.fetch_add(bytes, Ordering::Relaxed);
    }

    /// Increment active connections
    pub fn inc_connections(&self) {
        self.active_connections.fetch_add(1, Ordering::Relaxed);
    }

    /// Decrement active connections
    pub fn dec_connections(&self) {
        self.active_connections.fetch_sub(1, Ordering::Relaxed);
    }

    /// Increment queries executed
    pub fn inc_queries(&self) {
        self.queries_total.fetch_add(1, Ordering::Relaxed);
    }

    /// Add query execution time in microseconds
    pub fn add_query_time(&self, duration_us: u64) {
        self.query_time_us.fetch_add(duration_us, Ordering::Relaxed);
    }

    // --- request latency histogram ---

    /// Record a request latency duration.
    pub fn observe_request_latency(&self, d: Duration) {
        self.request_latency.observe_duration(d);
    }

    /// Get the request latency histogram reference.
    pub fn request_latency(&self) -> &Histogram {
        &self.request_latency
    }

    // --- per-operation metrics ---

    fn op_metrics(&self, op: OperationType) -> &OperationMetrics {
        match op {
            OperationType::Get => &self.op_get,
            OperationType::Put => &self.op_put,
            OperationType::Delete => &self.op_delete,
            OperationType::Range => &self.op_range,
            OperationType::Batch => &self.op_batch,
            OperationType::Stream => &self.op_stream,
        }
    }

    /// Record a completed operation with its type, duration, and success status.
    pub fn record_operation(&self, op_type: OperationType, duration: Duration, success: bool) {
        let m = self.op_metrics(op_type);
        m.count.fetch_add(1, Ordering::Relaxed);
        if !success {
            m.errors.fetch_add(1, Ordering::Relaxed);
        }
        m.latency.observe_duration(duration);
    }

    /// Take a snapshot of per-operation metrics for one type.
    pub fn operation_snapshot(&self, op_type: OperationType) -> OperationSnapshot {
        let m = self.op_metrics(op_type);
        OperationSnapshot {
            op_type,
            count: m.count.load(Ordering::Relaxed),
            errors: m.errors.load(Ordering::Relaxed),
            latency: m.latency.snapshot(),
        }
    }

    // --- storage metrics ---

    /// Set the current memtable size in bytes.
    pub fn set_memtable_size(&self, bytes: u64) {
        self.memtable_size_bytes.set(bytes);
    }

    /// Set the current SSTable count.
    pub fn set_sstable_count(&self, count: u64) {
        self.sstable_count.set(count);
    }

    /// Increment the compaction counter.
    pub fn inc_compaction_count(&self) {
        self.compaction_count.inc(1);
    }

    /// Add bytes written during compaction.
    pub fn add_compaction_bytes(&self, bytes: u64) {
        self.compaction_bytes_written.inc(bytes);
    }

    /// Set the current WAL size in bytes.
    pub fn set_wal_size(&self, bytes: u64) {
        self.wal_size_bytes.set(bytes);
    }

    /// Record a block cache hit.
    pub fn inc_block_cache_hit(&self) {
        self.block_cache_hits.inc(1);
    }

    /// Record a block cache miss.
    pub fn inc_block_cache_miss(&self) {
        self.block_cache_misses.inc(1);
    }

    /// Increment memtable size gauge.
    pub fn inc_memtable_size(&self, bytes: u64) {
        self.memtable_size_bytes.inc(bytes);
    }

    /// Decrement memtable size gauge.
    pub fn dec_memtable_size(&self, bytes: u64) {
        self.memtable_size_bytes.dec(bytes);
    }

    /// Increment sstable count gauge.
    pub fn inc_sstable_count(&self) {
        self.sstable_count.inc(1);
    }

    /// Decrement sstable count gauge.
    pub fn dec_sstable_count(&self) {
        self.sstable_count.dec(1);
    }

    /// Take a storage metrics snapshot.
    pub fn storage_snapshot(&self) -> StorageSnapshot {
        StorageSnapshot {
            memtable_size_bytes: self.memtable_size_bytes.get(),
            sstable_count: self.sstable_count.get(),
            compaction_count: self.compaction_count.get(),
            compaction_bytes_written: self.compaction_bytes_written.get(),
            wal_size_bytes: self.wal_size_bytes.get(),
            block_cache_hits: self.block_cache_hits.get(),
            block_cache_misses: self.block_cache_misses.get(),
        }
    }

    // --- snapshot ---

    /// Get snapshot of current metrics
    pub fn snapshot(&self) -> MetricsSnapshot {
        MetricsSnapshot {
            requests_total: self.requests_total.load(Ordering::Relaxed),
            requests_success: self.requests_success.load(Ordering::Relaxed),
            requests_failed: self.requests_failed.load(Ordering::Relaxed),
            bytes_read: self.bytes_read.load(Ordering::Relaxed),
            bytes_written: self.bytes_written.load(Ordering::Relaxed),
            active_connections: self.active_connections.load(Ordering::Relaxed),
            queries_total: self.queries_total.load(Ordering::Relaxed),
            query_time_us: self.query_time_us.load(Ordering::Relaxed),
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
            request_latency: self.request_latency.snapshot(),
            operations: OperationType::ALL
                .iter()
                .map(|&op| self.operation_snapshot(op))
                .collect(),
            storage: self.storage_snapshot(),
        }
    }

    // --- prometheus ---

    /// Format metrics as Prometheus-style text
    pub fn to_prometheus(&self) -> String {
        let snapshot = self.snapshot();
        let mut out = String::with_capacity(4096);

        // --- existing counters ---
        write_counter(
            &mut out,
            "amaters_requests_total",
            "Total number of requests",
            snapshot.requests_total,
        );
        write_counter(
            &mut out,
            "amaters_requests_success",
            "Total number of successful requests",
            snapshot.requests_success,
        );
        write_counter(
            &mut out,
            "amaters_requests_failed",
            "Total number of failed requests",
            snapshot.requests_failed,
        );
        write_counter(
            &mut out,
            "amaters_bytes_read",
            "Total bytes read",
            snapshot.bytes_read,
        );
        write_counter(
            &mut out,
            "amaters_bytes_written",
            "Total bytes written",
            snapshot.bytes_written,
        );
        write_gauge(
            &mut out,
            "amaters_active_connections",
            "Current active connections",
            snapshot.active_connections,
        );
        write_counter(
            &mut out,
            "amaters_queries_total",
            "Total queries executed",
            snapshot.queries_total,
        );
        write_counter(
            &mut out,
            "amaters_query_time_us_total",
            "Total query execution time in microseconds",
            snapshot.query_time_us,
        );

        // --- request latency histogram ---
        write_histogram(
            &mut out,
            "amaters_request_latency_seconds",
            "Request latency in seconds",
            &snapshot.request_latency,
        );

        // --- per-operation metrics ---
        for op_snap in &snapshot.operations {
            let label = op_snap.op_type.as_label();
            let prefix = format!("amaters_op_{label}");
            write_counter_with_label(
                &mut out,
                "amaters_op_count",
                "Operation count",
                &format!("op=\"{label}\""),
                op_snap.count,
            );
            write_counter_with_label(
                &mut out,
                "amaters_op_errors",
                "Operation errors",
                &format!("op=\"{label}\""),
                op_snap.errors,
            );
            write_histogram(
                &mut out,
                &format!("{prefix}_latency_seconds"),
                &format!("Latency for {label} operations in seconds"),
                &op_snap.latency,
            );
        }

        // --- storage metrics ---
        let s = &snapshot.storage;
        write_gauge(
            &mut out,
            "amaters_memtable_size_bytes",
            "Current memtable size in bytes",
            s.memtable_size_bytes,
        );
        write_gauge(
            &mut out,
            "amaters_sstable_count",
            "Current SSTable count",
            s.sstable_count,
        );
        write_counter(
            &mut out,
            "amaters_compaction_count",
            "Total compaction operations",
            s.compaction_count,
        );
        write_counter(
            &mut out,
            "amaters_compaction_bytes_written",
            "Total bytes written during compaction",
            s.compaction_bytes_written,
        );
        write_gauge(
            &mut out,
            "amaters_wal_size_bytes",
            "Current WAL size in bytes",
            s.wal_size_bytes,
        );
        write_counter(
            &mut out,
            "amaters_block_cache_hits",
            "Block cache hits",
            s.block_cache_hits,
        );
        write_counter(
            &mut out,
            "amaters_block_cache_misses",
            "Block cache misses",
            s.block_cache_misses,
        );

        out
    }

    /// Reset all metrics (useful for testing)
    #[cfg(test)]
    pub fn reset(&self) {
        self.requests_total.store(0, Ordering::Relaxed);
        self.requests_success.store(0, Ordering::Relaxed);
        self.requests_failed.store(0, Ordering::Relaxed);
        self.bytes_read.store(0, Ordering::Relaxed);
        self.bytes_written.store(0, Ordering::Relaxed);
        self.active_connections.store(0, Ordering::Relaxed);
        self.queries_total.store(0, Ordering::Relaxed);
        self.query_time_us.store(0, Ordering::Relaxed);
        self.request_latency.reset();
        for &op in &OperationType::ALL {
            let m = self.op_metrics(op);
            m.count.store(0, Ordering::Relaxed);
            m.errors.store(0, Ordering::Relaxed);
            m.latency.reset();
        }
        self.memtable_size_bytes.set(0);
        self.sstable_count.set(0);
        self.compaction_count.set(0);
        self.compaction_bytes_written.set(0);
        self.wal_size_bytes.set(0);
        self.block_cache_hits.set(0);
        self.block_cache_misses.set(0);
    }
}

impl Default for MetricsCollector {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Prometheus formatting helpers
// ---------------------------------------------------------------------------

fn write_counter(out: &mut String, name: &str, help: &str, value: u64) {
    use std::fmt::Write;
    let _ = writeln!(out, "# HELP {name} {help}");
    let _ = writeln!(out, "# TYPE {name} counter");
    let _ = writeln!(out, "{name} {value}");
    let _ = writeln!(out);
}

fn write_counter_with_label(out: &mut String, name: &str, help: &str, label: &str, value: u64) {
    use std::fmt::Write;
    let _ = writeln!(out, "# HELP {name} {help}");
    let _ = writeln!(out, "# TYPE {name} counter");
    let _ = writeln!(out, "{name}{{{label}}} {value}");
    let _ = writeln!(out);
}

fn write_gauge(out: &mut String, name: &str, help: &str, value: u64) {
    use std::fmt::Write;
    let _ = writeln!(out, "# HELP {name} {help}");
    let _ = writeln!(out, "# TYPE {name} gauge");
    let _ = writeln!(out, "{name} {value}");
    let _ = writeln!(out);
}

fn write_histogram(out: &mut String, name: &str, help: &str, snap: &HistogramSnapshot) {
    use std::fmt::Write;
    let _ = writeln!(out, "# HELP {name} {help}");
    let _ = writeln!(out, "# TYPE {name} histogram");
    for (i, &bound) in snap.buckets.iter().enumerate() {
        let le = format_f64(bound);
        let _ = writeln!(out, "{name}_bucket{{le=\"{le}\"}} {}", snap.counts[i]);
    }
    let _ = writeln!(out, "{name}_bucket{{le=\"+Inf\"}} {}", snap.total_count);
    let _ = writeln!(out, "{name}_sum {}", format_f64(snap.sum));
    let _ = writeln!(out, "{name}_count {}", snap.total_count);
    let _ = writeln!(out);
}

/// Format an f64 without unnecessary trailing zeros but always at least one decimal.
fn format_f64(v: f64) -> String {
    if v == f64::INFINITY {
        "+Inf".to_string()
    } else if v == f64::NEG_INFINITY {
        "-Inf".to_string()
    } else if v.is_nan() {
        "NaN".to_string()
    } else {
        // Use enough precision, then trim trailing zeros
        let s = format!("{v:.6}");
        let s = s.trim_end_matches('0');
        // Keep at least one decimal digit
        if s.ends_with('.') {
            format!("{s}0")
        } else {
            s.to_string()
        }
    }
}

// ---------------------------------------------------------------------------
// MetricsSnapshot
// ---------------------------------------------------------------------------

/// Snapshot of metrics at a point in time
#[derive(Debug, Clone)]
pub struct MetricsSnapshot {
    pub requests_total: u64,
    pub requests_success: u64,
    pub requests_failed: u64,
    pub bytes_read: u64,
    pub bytes_written: u64,
    pub active_connections: u64,
    pub queries_total: u64,
    pub query_time_us: u64,
    pub timestamp: u64,
    /// Request latency histogram snapshot
    pub request_latency: HistogramSnapshot,
    /// Per-operation type snapshots
    pub operations: Vec<OperationSnapshot>,
    /// Storage metrics
    pub storage: StorageSnapshot,
}

impl MetricsSnapshot {
    /// Calculate average query time in microseconds
    pub fn avg_query_time_us(&self) -> f64 {
        if self.queries_total == 0 {
            0.0
        } else {
            self.query_time_us as f64 / self.queries_total as f64
        }
    }

    /// Calculate success rate (0.0 to 1.0)
    pub fn success_rate(&self) -> f64 {
        if self.requests_total == 0 {
            0.0
        } else {
            self.requests_success as f64 / self.requests_total as f64
        }
    }

    /// Format as human-readable string
    pub fn format_human(&self) -> String {
        format!(
            "Metrics:\n\
             Requests:    {} total, {} success, {} failed (success rate: {:.2}%)\n\
             Data:        {} bytes read, {} bytes written\n\
             Connections: {} active\n\
             Queries:     {} total, avg time: {:.2} \u{03bc}s\n\
             Timestamp:   {}",
            self.requests_total,
            self.requests_success,
            self.requests_failed,
            self.success_rate() * 100.0,
            self.bytes_read,
            self.bytes_written,
            self.active_connections,
            self.queries_total,
            self.avg_query_time_us(),
            self.timestamp,
        )
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- Histogram tests --

    #[test]
    fn test_histogram_bucket_counting() {
        let h = Histogram::with_buckets(&[1.0, 5.0, 10.0]);

        h.observe(0.5); // bucket 1.0
        h.observe(3.0); // bucket 5.0
        h.observe(7.0); // bucket 10.0
        h.observe(15.0); // above all buckets

        let snap = h.snapshot();
        assert_eq!(snap.total_count, 4);
        // cumulative: <=1.0 => 1, <=5.0 => 2, <=10.0 => 3
        assert_eq!(snap.counts, vec![1, 2, 3]);
        let expected_sum = 0.5 + 3.0 + 7.0 + 15.0;
        assert!((snap.sum - expected_sum).abs() < 1e-9);
    }

    #[test]
    fn test_histogram_exact_boundary() {
        let h = Histogram::with_buckets(&[1.0, 5.0, 10.0]);
        h.observe(1.0);
        h.observe(5.0);
        h.observe(10.0);

        let snap = h.snapshot();
        // 1.0 <= 1.0, 5.0 <= 5.0, 10.0 <= 10.0 => all counted cumulatively
        assert_eq!(snap.counts, vec![1, 2, 3]);
        assert_eq!(snap.total_count, 3);
    }

    #[test]
    fn test_histogram_default_buckets() {
        let h = Histogram::new();
        let snap = h.snapshot();
        assert_eq!(snap.buckets.len(), 12);
        assert_eq!(snap.buckets[0], 0.001);
        assert_eq!(snap.buckets[11], 10.0);
    }

    #[test]
    fn test_histogram_observe_duration() {
        let h = Histogram::with_buckets(&[0.01, 0.1, 1.0]);
        h.observe_duration(Duration::from_millis(5)); // 0.005s -> bucket 0.01
        let snap = h.snapshot();
        assert_eq!(snap.counts[0], 1);
        assert_eq!(snap.total_count, 1);
        assert!((snap.sum - 0.005).abs() < 1e-6);
    }

    // -- Percentile tests --

    #[test]
    fn test_percentile_empty() {
        let h = Histogram::with_buckets(&[1.0, 5.0, 10.0]);
        let snap = h.snapshot();
        assert!(snap.p50().is_none());
        assert!(snap.p95().is_none());
        assert!(snap.p99().is_none());
    }

    #[test]
    fn test_percentile_single_value() {
        let h = Histogram::with_buckets(&[1.0, 5.0, 10.0]);
        h.observe(0.5);
        let snap = h.snapshot();

        let p50 = snap.p50().expect("should have p50");
        // Single value at 0.5 falls in first bucket [0, 1.0]
        // target = 0.5 * 1 = 0.5, bucket has count=1
        // fraction = 0.5/1 = 0.5, value = 0.0 + 0.5 * 1.0 = 0.5
        assert!((p50 - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_percentile_many_values() {
        let h = Histogram::with_buckets(&[1.0, 2.0, 5.0, 10.0]);
        // Put 50 values in [0,1], 40 in (1,2], 9 in (2,5], 1 in (5,10]
        for _ in 0..50 {
            h.observe(0.5);
        }
        for _ in 0..40 {
            h.observe(1.5);
        }
        for _ in 0..9 {
            h.observe(3.0);
        }
        h.observe(7.0);

        let snap = h.snapshot();
        assert_eq!(snap.total_count, 100);

        // p50: target = 50 => hits bucket[0] (count=50), at the boundary
        let p50 = snap.p50().expect("should have p50");
        assert!(p50 <= 1.0 + 1e-9, "p50={p50} should be <= 1.0");

        // p95: target = 95, cumulative: 50, 90, 99 => bucket 2 (bound=5.0)
        let p95 = snap.p95().expect("should have p95");
        assert!(p95 > 2.0 - 1e-9 && p95 <= 5.0 + 1e-9, "p95={p95}");

        // p99: target = 99, cumulative 99 at bucket 2 => at boundary
        let p99 = snap.p99().expect("should have p99");
        assert!(p99 <= 5.0 + 1e-9, "p99={p99}");
    }

    #[test]
    fn test_percentile_boundary_values() {
        let snap = HistogramSnapshot {
            buckets: vec![1.0, 5.0, 10.0],
            counts: vec![0, 0, 0],
            total_count: 0,
            sum: 0.0,
        };
        assert!(snap.percentile(-0.1).is_none());
        assert!(snap.percentile(1.1).is_none());
    }

    // -- Concurrent histogram test --

    #[test]
    fn test_histogram_concurrent() {
        let h = Histogram::with_buckets(&[1.0, 5.0, 10.0]);
        let threads: Vec<_> = (0..8)
            .map(|_| {
                let h2 = h.clone();
                thread::spawn(move || {
                    for i in 0..1000 {
                        h2.observe(i as f64 % 12.0);
                    }
                })
            })
            .collect();
        for t in threads {
            t.join().expect("thread should not panic");
        }
        let snap = h.snapshot();
        assert_eq!(snap.total_count, 8000);
    }

    // -- OperationType tests --

    #[test]
    fn test_operation_type_labels() {
        assert_eq!(OperationType::Get.as_label(), "get");
        assert_eq!(OperationType::Put.as_label(), "put");
        assert_eq!(OperationType::Delete.as_label(), "delete");
        assert_eq!(OperationType::Range.as_label(), "range");
        assert_eq!(OperationType::Batch.as_label(), "batch");
        assert_eq!(OperationType::Stream.as_label(), "stream");
    }

    #[test]
    fn test_operation_type_display() {
        assert_eq!(format!("{}", OperationType::Get), "get");
    }

    // -- MetricsCollector existing tests --

    #[test]
    fn test_metrics_collector_creation() {
        let collector = MetricsCollector::new();
        let snapshot = collector.snapshot();

        assert_eq!(snapshot.requests_total, 0);
        assert_eq!(snapshot.requests_success, 0);
        assert_eq!(snapshot.requests_failed, 0);
    }

    #[test]
    fn test_increment_requests() {
        let collector = MetricsCollector::new();

        collector.inc_requests();
        collector.inc_requests();
        collector.inc_success();
        collector.inc_failed();

        let snapshot = collector.snapshot();
        assert_eq!(snapshot.requests_total, 2);
        assert_eq!(snapshot.requests_success, 1);
        assert_eq!(snapshot.requests_failed, 1);
    }

    #[test]
    fn test_bytes_tracking() {
        let collector = MetricsCollector::new();

        collector.add_bytes_read(1024);
        collector.add_bytes_written(2048);

        let snapshot = collector.snapshot();
        assert_eq!(snapshot.bytes_read, 1024);
        assert_eq!(snapshot.bytes_written, 2048);
    }

    #[test]
    fn test_connections() {
        let collector = MetricsCollector::new();

        collector.inc_connections();
        collector.inc_connections();
        assert_eq!(collector.snapshot().active_connections, 2);

        collector.dec_connections();
        assert_eq!(collector.snapshot().active_connections, 1);
    }

    #[test]
    fn test_queries() {
        let collector = MetricsCollector::new();

        collector.inc_queries();
        collector.add_query_time(1000);
        collector.inc_queries();
        collector.add_query_time(2000);

        let snapshot = collector.snapshot();
        assert_eq!(snapshot.queries_total, 2);
        assert_eq!(snapshot.query_time_us, 3000);
        assert_eq!(snapshot.avg_query_time_us(), 1500.0);
    }

    #[test]
    fn test_success_rate() {
        let collector = MetricsCollector::new();

        collector.inc_requests();
        collector.inc_success();
        collector.inc_requests();
        collector.inc_failed();

        let snapshot = collector.snapshot();
        assert_eq!(snapshot.success_rate(), 0.5);
    }

    #[test]
    fn test_reset() {
        let collector = MetricsCollector::new();

        collector.inc_requests();
        collector.inc_success();
        collector.record_operation(OperationType::Get, Duration::from_millis(10), true);
        collector.set_memtable_size(1024);
        assert_eq!(collector.snapshot().requests_total, 1);

        collector.reset();
        let snap = collector.snapshot();
        assert_eq!(snap.requests_total, 0);
        assert_eq!(snap.storage.memtable_size_bytes, 0);
        assert_eq!(snap.operations[0].count, 0);
    }

    #[test]
    fn test_human_format() {
        let collector = MetricsCollector::new();
        collector.inc_requests();
        collector.inc_success();

        let snapshot = collector.snapshot();
        let formatted = snapshot.format_human();

        assert!(formatted.contains("Metrics:"));
        assert!(formatted.contains("Requests:"));
        assert!(formatted.contains("1 total"));
    }

    // -- Record operation tests --

    #[test]
    fn test_record_operation_success() {
        let collector = MetricsCollector::new();
        collector.record_operation(OperationType::Get, Duration::from_millis(5), true);
        collector.record_operation(OperationType::Get, Duration::from_millis(10), true);

        let snap = collector.operation_snapshot(OperationType::Get);
        assert_eq!(snap.count, 2);
        assert_eq!(snap.errors, 0);
        assert_eq!(snap.latency.total_count, 2);
    }

    #[test]
    fn test_record_operation_failure() {
        let collector = MetricsCollector::new();
        collector.record_operation(OperationType::Put, Duration::from_millis(100), false);

        let snap = collector.operation_snapshot(OperationType::Put);
        assert_eq!(snap.count, 1);
        assert_eq!(snap.errors, 1);
    }

    #[test]
    fn test_record_all_operation_types() {
        let collector = MetricsCollector::new();
        for &op in &OperationType::ALL {
            collector.record_operation(op, Duration::from_millis(1), true);
        }
        for &op in &OperationType::ALL {
            let snap = collector.operation_snapshot(op);
            assert_eq!(snap.count, 1, "op={op} should have count 1");
        }
    }

    // -- Storage metrics tests --

    #[test]
    fn test_storage_gauges_set() {
        let collector = MetricsCollector::new();
        collector.set_memtable_size(4096);
        collector.set_sstable_count(10);
        collector.set_wal_size(8192);

        let s = collector.storage_snapshot();
        assert_eq!(s.memtable_size_bytes, 4096);
        assert_eq!(s.sstable_count, 10);
        assert_eq!(s.wal_size_bytes, 8192);
    }

    #[test]
    fn test_storage_gauge_inc_dec() {
        let collector = MetricsCollector::new();

        collector.inc_memtable_size(1000);
        collector.inc_memtable_size(500);
        assert_eq!(collector.storage_snapshot().memtable_size_bytes, 1500);

        collector.dec_memtable_size(300);
        assert_eq!(collector.storage_snapshot().memtable_size_bytes, 1200);

        collector.inc_sstable_count();
        collector.inc_sstable_count();
        assert_eq!(collector.storage_snapshot().sstable_count, 2);

        collector.dec_sstable_count();
        assert_eq!(collector.storage_snapshot().sstable_count, 1);
    }

    #[test]
    fn test_storage_counters() {
        let collector = MetricsCollector::new();
        collector.inc_compaction_count();
        collector.inc_compaction_count();
        collector.add_compaction_bytes(10_000);
        collector.inc_block_cache_hit();
        collector.inc_block_cache_hit();
        collector.inc_block_cache_miss();

        let s = collector.storage_snapshot();
        assert_eq!(s.compaction_count, 2);
        assert_eq!(s.compaction_bytes_written, 10_000);
        assert_eq!(s.block_cache_hits, 2);
        assert_eq!(s.block_cache_misses, 1);
    }

    // -- Prometheus output tests --

    #[test]
    fn test_prometheus_format() {
        let collector = MetricsCollector::new();

        collector.inc_requests();
        collector.inc_success();

        let prometheus = collector.to_prometheus();
        assert!(prometheus.contains("amaters_requests_total 1"));
        assert!(prometheus.contains("amaters_requests_success 1"));
    }

    #[test]
    fn test_prometheus_histogram_format() {
        let collector = MetricsCollector::new();
        collector.observe_request_latency(Duration::from_millis(5)); // 0.005s
        collector.observe_request_latency(Duration::from_millis(50)); // 0.050s

        let prom = collector.to_prometheus();

        // Should contain histogram type
        assert!(
            prom.contains("# TYPE amaters_request_latency_seconds histogram"),
            "missing histogram TYPE line"
        );

        // Should have _bucket lines with le= labels
        assert!(
            prom.contains("amaters_request_latency_seconds_bucket{le=\"0.005\"} 1"),
            "bucket le=0.005 should have count 1"
        );
        assert!(
            prom.contains("amaters_request_latency_seconds_bucket{le=\"0.05\"} 2"),
            "bucket le=0.05 should have count 2"
        );

        // +Inf bucket
        assert!(
            prom.contains("amaters_request_latency_seconds_bucket{le=\"+Inf\"} 2"),
            "missing +Inf bucket"
        );

        // _sum and _count
        assert!(
            prom.contains("amaters_request_latency_seconds_count 2"),
            "missing _count"
        );
        assert!(
            prom.contains("amaters_request_latency_seconds_sum"),
            "missing _sum"
        );
    }

    #[test]
    fn test_prometheus_operation_metrics() {
        let collector = MetricsCollector::new();
        collector.record_operation(OperationType::Get, Duration::from_millis(1), true);
        collector.record_operation(OperationType::Get, Duration::from_millis(2), false);

        let prom = collector.to_prometheus();
        assert!(
            prom.contains("amaters_op_count{op=\"get\"} 2"),
            "missing op count"
        );
        assert!(
            prom.contains("amaters_op_errors{op=\"get\"} 1"),
            "missing op errors"
        );
        assert!(
            prom.contains("amaters_op_get_latency_seconds_count 2"),
            "missing op latency count"
        );
    }

    #[test]
    fn test_prometheus_storage_metrics() {
        let collector = MetricsCollector::new();
        collector.set_memtable_size(4096);
        collector.inc_compaction_count();

        let prom = collector.to_prometheus();
        assert!(
            prom.contains("amaters_memtable_size_bytes 4096"),
            "missing memtable gauge"
        );
        assert!(
            prom.contains("amaters_compaction_count 1"),
            "missing compaction counter"
        );
    }

    #[test]
    fn test_prometheus_type_help_comments() {
        let collector = MetricsCollector::new();
        let prom = collector.to_prometheus();

        // Every metric should have HELP and TYPE
        assert!(prom.contains("# HELP amaters_requests_total"));
        assert!(prom.contains("# TYPE amaters_requests_total counter"));
        assert!(prom.contains("# HELP amaters_active_connections"));
        assert!(prom.contains("# TYPE amaters_active_connections gauge"));
        assert!(prom.contains("# TYPE amaters_request_latency_seconds histogram"));
        assert!(prom.contains("# TYPE amaters_memtable_size_bytes gauge"));
        assert!(prom.contains("# TYPE amaters_compaction_count counter"));
        assert!(prom.contains("# TYPE amaters_block_cache_hits counter"));
    }

    // -- Concurrent MetricsCollector test --

    #[test]
    fn test_concurrent_metric_updates() {
        let collector = MetricsCollector::new();
        let threads: Vec<_> = (0..8)
            .map(|i| {
                let c = collector.clone();
                thread::spawn(move || {
                    for _ in 0..500 {
                        c.inc_requests();
                        if i % 2 == 0 {
                            c.inc_success();
                        } else {
                            c.inc_failed();
                        }
                        c.record_operation(OperationType::Get, Duration::from_micros(100), true);
                        c.inc_block_cache_hit();
                    }
                })
            })
            .collect();

        for t in threads {
            t.join().expect("thread should not panic");
        }

        let snap = collector.snapshot();
        assert_eq!(snap.requests_total, 4000);
        assert_eq!(snap.requests_success + snap.requests_failed, 4000);
        assert_eq!(snap.storage.block_cache_hits, 4000);

        let get_snap = collector.operation_snapshot(OperationType::Get);
        assert_eq!(get_snap.count, 4000);
        assert_eq!(get_snap.latency.total_count, 4000);
    }

    // -- format_f64 tests --

    #[test]
    fn test_format_f64() {
        assert_eq!(format_f64(0.001), "0.001");
        assert_eq!(format_f64(1.0), "1.0");
        assert_eq!(format_f64(10.0), "10.0");
        assert_eq!(format_f64(0.025), "0.025");
        assert_eq!(format_f64(f64::INFINITY), "+Inf");
    }

    // -- Snapshot in MetricsSnapshot --

    #[test]
    fn test_snapshot_includes_all_fields() {
        let collector = MetricsCollector::new();
        collector.inc_requests();
        collector.observe_request_latency(Duration::from_millis(1));
        collector.record_operation(OperationType::Put, Duration::from_millis(2), true);
        collector.set_memtable_size(2048);

        let snap = collector.snapshot();
        assert_eq!(snap.requests_total, 1);
        assert_eq!(snap.request_latency.total_count, 1);
        assert_eq!(snap.operations.len(), 6); // all 6 op types
        assert_eq!(snap.storage.memtable_size_bytes, 2048);

        // Find the Put operation
        let put = snap
            .operations
            .iter()
            .find(|o| o.op_type == OperationType::Put)
            .expect("should have Put snapshot");
        assert_eq!(put.count, 1);
    }
}