alice-analytics 0.4.0

High-performance telemetry & probabilistic statistical estimation — HyperLogLog++, DDSketch, Count-Min Sketch, local differential privacy, streaming anomaly detection
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
//! Lock-Free Metric Aggregation Pipeline
//!
//! Zero-allocation metric collection into pre-allocated sketches.
//! Designed for high-throughput telemetry without GC pauses.

use crate::math::{f64_u64, hash_index, u64_f64};

use crate::sketch::{DDSketch256, HyperLogLog10, Mergeable};

// ============================================================================
// Ring Buffer for Hot Metrics
// ============================================================================

/// Lock-free single-producer single-consumer ring buffer
///
/// Used for pushing hot metrics from producer to consumer without locks.
#[derive(Debug)]
pub struct RingBuffer<T: Copy + Default, const N: usize> {
    /// Buffer storage
    buffer: [T; N],
    /// Write position (only modified by producer)
    write_pos: usize,
    /// Read position (only modified by consumer)
    read_pos: usize,
    /// Count of dropped items due to full buffer
    dropped: u64,
}

impl<T: Copy + Default, const N: usize> RingBuffer<T, N> {
    /// Create a new empty ring buffer
    #[must_use]
    pub fn new() -> Self {
        Self {
            buffer: [T::default(); N],
            write_pos: 0,
            read_pos: 0,
            dropped: 0,
        }
    }

    /// Push an item (returns false if buffer is full)
    #[inline]
    /// # Panics
    ///
    /// `N == 0` の場合 (容量 0 のリングバッファは書き込み位置を持てない)
    /// 型引数の前提違反なので `Result` にせず panic する 契約は
    /// `tests/panic_contract.rs` が pin する
    pub const fn push(&mut self, item: T) -> bool {
        assert!(N > 0, "RingBuffer needs N > 0 (got a zero-capacity buffer)");
        let next_write = (self.write_pos + 1) % N;
        if next_write == self.read_pos {
            // Buffer full
            self.dropped += 1;
            return false;
        }
        self.buffer[self.write_pos] = item;
        self.write_pos = next_write;
        true
    }

    /// Pop an item (returns None if buffer is empty)
    #[inline]
    pub const fn pop(&mut self) -> Option<T> {
        if self.read_pos == self.write_pos {
            // Buffer empty
            return None;
        }
        let item = self.buffer[self.read_pos];
        self.read_pos = (self.read_pos + 1) % N;
        Some(item)
    }

    /// Check if buffer is empty
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.read_pos == self.write_pos
    }

    /// Check if buffer is full
    ///
    /// `N <= 1` has no usable slot (one is always reserved to tell full from
    /// empty), so such a buffer is full from the start; answering that keeps
    /// this accessor total for `N == 0`, where `% N` would divide by zero.
    #[inline]
    pub const fn is_full(&self) -> bool {
        N <= 1 || (self.write_pos + 1) % N == self.read_pos
    }

    /// Get current length
    #[inline]
    pub const fn len(&self) -> usize {
        if self.write_pos >= self.read_pos {
            self.write_pos - self.read_pos
        } else {
            N - self.read_pos + self.write_pos
        }
    }

    /// Get capacity
    ///
    /// One slot is always empty to distinguish full from empty, so the usable
    /// capacity is `N - 1`; `saturating_sub` keeps the accessor total for
    /// `N == 0`, where the subtraction would underflow.
    #[inline]
    pub const fn capacity(&self) -> usize {
        N.saturating_sub(1)
    }

    /// Get count of dropped items
    #[inline]
    pub const fn dropped(&self) -> u64 {
        self.dropped
    }

    /// Clear the buffer
    pub const fn clear(&mut self) {
        self.write_pos = 0;
        self.read_pos = 0;
        self.dropped = 0;
    }
}

impl<T: Copy + Default, const N: usize> Default for RingBuffer<T, N> {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Metric Event Types
// ============================================================================

/// Type of metric event
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum MetricType {
    /// Counter increment
    #[default]
    Counter,
    /// Gauge value (current state)
    Gauge,
    /// Histogram observation (latency, size, etc.)
    Histogram,
    /// Unique item (for cardinality)
    Unique,
}

/// A metric event to be processed
#[derive(Clone, Copy, Debug, Default)]
pub struct MetricEvent {
    /// Metric name hash
    pub name_hash: u64,
    /// Metric type
    pub metric_type: MetricType,
    /// Value (interpretation depends on type)
    pub value: f64,
    /// Timestamp (optional, epoch millis)
    pub timestamp: u64,
}

impl MetricEvent {
    /// Create a counter increment event
    #[inline]
    #[must_use]
    pub const fn counter(name_hash: u64, delta: f64) -> Self {
        Self {
            name_hash,
            metric_type: MetricType::Counter,
            value: delta,
            timestamp: 0,
        }
    }

    /// Create a gauge event
    #[inline]
    #[must_use]
    pub const fn gauge(name_hash: u64, value: f64) -> Self {
        Self {
            name_hash,
            metric_type: MetricType::Gauge,
            value,
            timestamp: 0,
        }
    }

    /// Create a histogram observation
    #[inline]
    #[must_use]
    pub const fn histogram(name_hash: u64, value: f64) -> Self {
        Self {
            name_hash,
            metric_type: MetricType::Histogram,
            value,
            timestamp: 0,
        }
    }

    /// Create a unique item event
    #[inline]
    #[must_use]
    pub const fn unique(name_hash: u64, item_hash: u64) -> Self {
        Self {
            name_hash,
            metric_type: MetricType::Unique,
            value: u64_f64(item_hash),
            timestamp: 0,
        }
    }

    /// Set timestamp
    #[inline]
    #[must_use]
    pub const fn with_timestamp(mut self, ts: u64) -> Self {
        self.timestamp = ts;
        self
    }
}

// ============================================================================
// Metric Slot - Pre-allocated storage for a single metric
// ============================================================================

/// Pre-allocated storage for a metric's aggregated data
#[derive(Clone, Debug)]
pub struct MetricSlot {
    /// Metric name hash
    pub name_hash: u64,
    /// Counter value (for Counter type)
    pub counter: f64,
    /// Gauge value (for Gauge type)
    pub gauge: f64,
    /// `HyperLogLog` for unique counting (P=10, 1KB)
    pub hll: HyperLogLog10,
    /// `DDSketch` for histogram/quantiles (256 bins, use alpha >= 0.05)
    pub ddsketch: DDSketch256,
    /// Event count
    pub event_count: u64,
    /// Last update timestamp
    pub last_update: u64,
}

impl MetricSlot {
    /// Create a new metric slot
    ///
    /// Note: With 256 bins, use alpha >= 0.05 for best results
    #[must_use]
    pub fn new(name_hash: u64, alpha: f64) -> Self {
        Self {
            name_hash,
            counter: 0.0,
            gauge: 0.0,
            hll: HyperLogLog10::new(),
            ddsketch: DDSketch256::new(alpha),
            event_count: 0,
            last_update: 0,
        }
    }

    /// Process a metric event
    pub fn process(&mut self, event: &MetricEvent) {
        self.event_count += 1;
        if event.timestamp > self.last_update {
            self.last_update = event.timestamp;
        }

        match event.metric_type {
            MetricType::Counter => {
                self.counter += event.value;
            }
            MetricType::Gauge => {
                self.gauge = event.value;
            }
            MetricType::Histogram => {
                self.ddsketch.insert(event.value);
            }
            MetricType::Unique => {
                self.hll.insert_hash(f64_u64(event.value));
            }
        }
    }

    /// Reset the slot
    pub const fn reset(&mut self) {
        self.counter = 0.0;
        self.gauge = 0.0;
        self.hll.clear();
        self.ddsketch.clear();
        self.event_count = 0;
        self.last_update = 0;
    }
}

impl Mergeable for MetricSlot {
    fn merge(&mut self, other: &Self) {
        self.counter += other.counter;
        // For gauge, take the latest
        if other.last_update > self.last_update {
            self.gauge = other.gauge;
            self.last_update = other.last_update;
        }
        self.hll.merge(&other.hll);
        self.ddsketch.merge(&other.ddsketch);
        self.event_count += other.event_count;
    }
}

// ============================================================================
// Metric Pipeline - Main aggregation pipeline
// ============================================================================

/// High-performance metric aggregation pipeline
///
/// Features:
/// - Pre-allocated metric slots (zero runtime allocation)
/// - Ring buffer for async metric submission
/// - Mergeable sketches for distributed aggregation
///
/// # Example
/// ```
/// use alice_analytics::pipeline::{MetricPipeline, MetricEvent};
///
/// // Create pipeline with 64 metric slots
/// let mut pipeline = MetricPipeline::<64, 1024>::new(0.05);
///
/// // Submit metrics
/// pipeline.submit(MetricEvent::counter(hash("requests"), 1.0));
/// pipeline.submit(MetricEvent::histogram(hash("latency"), 42.5));
///
/// // Process pending events
/// pipeline.flush();
///
/// fn hash(s: &str) -> u64 {
///     use alice_analytics::sketch::FnvHasher;
///     FnvHasher::hash_bytes(s.as_bytes())
/// }
/// ```
#[derive(Debug)]
pub struct MetricPipeline<const SLOTS: usize, const QUEUE_SIZE: usize> {
    /// Pre-allocated metric slots
    slots: [Option<MetricSlot>; SLOTS],
    /// Event queue (ring buffer)
    queue: RingBuffer<MetricEvent, QUEUE_SIZE>,
    /// `DDSketch` alpha parameter
    alpha: f64,
    /// Total events processed
    total_events: u64,
}

impl<const SLOTS: usize, const QUEUE_SIZE: usize> MetricPipeline<SLOTS, QUEUE_SIZE> {
    /// Create a new metric pipeline
    ///
    /// # Arguments
    /// * `alpha` - Relative error for `DDSketch` (e.g., 0.01 for 1%)
    #[must_use]
    pub fn new(alpha: f64) -> Self {
        // Use array initialization with Default
        const NONE_SLOT: Option<MetricSlot> = None;
        Self {
            slots: [NONE_SLOT; SLOTS],
            queue: RingBuffer::new(),
            alpha,
            total_events: 0,
        }
    }

    /// Submit a metric event to the queue
    ///
    /// Returns false if queue is full (event dropped)
    #[inline]
    pub const fn submit(&mut self, event: MetricEvent) -> bool {
        self.queue.push(event)
    }

    /// Process all pending events in the queue
    pub fn flush(&mut self) {
        while let Some(event) = self.queue.pop() {
            self.process_event(event);
        }
    }

    /// Process a single event directly (bypasses queue)
    fn process_event(&mut self, event: MetricEvent) {
        self.total_events += 1;

        // Find or create slot for this metric
        let slot_idx = hash_index(event.name_hash) % SLOTS;

        // Check if slot exists and matches
        if let Some(ref mut slot) = self.slots[slot_idx] {
            if slot.name_hash == event.name_hash {
                slot.process(&event);
                return;
            }
            // Hash collision - process into existing slot anyway (approximation)
            slot.process(&event);
        } else {
            // Create new slot
            let mut slot = MetricSlot::new(event.name_hash, self.alpha);
            slot.process(&event);
            self.slots[slot_idx] = Some(slot);
        }
    }

    /// Get a metric slot by name hash
    #[must_use]
    pub fn get_slot(&self, name_hash: u64) -> Option<&MetricSlot> {
        let slot_idx = hash_index(name_hash) % SLOTS;
        self.slots[slot_idx]
            .as_ref()
            .filter(|s| s.name_hash == name_hash)
    }

    /// Get mutable reference to a metric slot
    pub fn get_slot_mut(&mut self, name_hash: u64) -> Option<&mut MetricSlot> {
        let slot_idx = hash_index(name_hash) % SLOTS;
        self.slots[slot_idx]
            .as_mut()
            .filter(|s| s.name_hash == name_hash)
    }

    /// Iterate over all active slots
    pub fn iter_slots(&self) -> impl Iterator<Item = &MetricSlot> {
        self.slots.iter().filter_map(|s| s.as_ref())
    }

    /// Get total events processed
    #[inline]
    #[must_use]
    pub const fn total_events(&self) -> u64 {
        self.total_events
    }

    /// Get count of dropped events
    #[inline]
    #[must_use]
    pub const fn dropped_events(&self) -> u64 {
        self.queue.dropped()
    }

    /// Get queue length
    #[inline]
    #[must_use]
    pub const fn queue_len(&self) -> usize {
        self.queue.len()
    }

    /// Reset all slots
    pub fn reset(&mut self) {
        for s in self.slots.iter_mut().flatten() {
            s.reset();
        }
        self.queue.clear();
        self.total_events = 0;
    }
}

// ============================================================================
// Metric Registry - Named metric management
// ============================================================================

/// Entry in the metric registry
#[derive(Clone, Debug)]
pub struct MetricEntry {
    /// Metric name (for display)
    pub name: [u8; 64],
    /// Name length
    pub name_len: usize,
    /// Name hash
    pub hash: u64,
    /// Metric type
    pub metric_type: MetricType,
}

impl MetricEntry {
    /// Create a new metric entry
    #[must_use]
    pub fn new(name: &str, metric_type: MetricType) -> Self {
        use crate::sketch::FnvHasher;

        let mut name_buf = [0u8; 64];
        let len = name.len().min(64);
        name_buf[..len].copy_from_slice(&name.as_bytes()[..len]);

        Self {
            name: name_buf,
            name_len: len,
            hash: FnvHasher::hash_bytes(name.as_bytes()),
            metric_type,
        }
    }

    /// Get name as string slice
    #[must_use]
    pub fn name_str(&self) -> &str {
        core::str::from_utf8(&self.name[..self.name_len]).unwrap_or("")
    }
}

/// Registry of named metrics
#[derive(Clone, Debug)]
pub struct MetricRegistry<const N: usize> {
    /// Registered metrics
    entries: [Option<MetricEntry>; N],
    /// Count of registered metrics
    count: usize,
}

impl<const N: usize> MetricRegistry<N> {
    /// Create a new empty registry
    #[must_use]
    pub const fn new() -> Self {
        const NONE_ENTRY: Option<MetricEntry> = None;
        Self {
            entries: [NONE_ENTRY; N],
            count: 0,
        }
    }

    /// Register a new metric
    ///
    /// Returns the metric hash, or None if registry is full
    pub fn register(&mut self, name: &str, metric_type: MetricType) -> Option<u64> {
        if self.count >= N {
            return None;
        }

        let entry = MetricEntry::new(name, metric_type);
        let hash = entry.hash;

        // Find empty slot
        for slot in &mut self.entries {
            if slot.is_none() {
                *slot = Some(entry);
                self.count += 1;
                return Some(hash);
            }
        }

        None
    }

    /// Look up a metric by name
    #[must_use]
    pub fn lookup(&self, name: &str) -> Option<&MetricEntry> {
        use crate::sketch::FnvHasher;
        let hash = FnvHasher::hash_bytes(name.as_bytes());
        self.lookup_by_hash(hash)
    }

    /// Look up a metric by hash
    #[must_use]
    pub fn lookup_by_hash(&self, hash: u64) -> Option<&MetricEntry> {
        self.entries
            .iter()
            .filter_map(|e| e.as_ref())
            .find(|e| e.hash == hash)
    }

    /// Iterate over registered metrics
    pub fn iter(&self) -> impl Iterator<Item = &MetricEntry> {
        self.entries.iter().filter_map(|e| e.as_ref())
    }

    /// Get count of registered metrics
    #[inline]
    #[must_use]
    pub const fn count(&self) -> usize {
        self.count
    }
}

impl<const N: usize> Default for MetricRegistry<N> {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Snapshot - Point-in-time metric export
// ============================================================================

/// Snapshot of a single metric's state
#[derive(Clone, Debug)]
pub struct MetricSnapshot {
    /// Metric name hash
    pub name_hash: u64,
    /// Counter value
    pub counter: f64,
    /// Gauge value
    pub gauge: f64,
    /// Cardinality estimate (from HLL)
    pub cardinality: f64,
    /// P50 latency
    pub p50: f64,
    /// P95 latency
    pub p95: f64,
    /// P99 latency
    pub p99: f64,
    /// Mean value
    pub mean: f64,
    /// Min value
    pub min: f64,
    /// Max value
    pub max: f64,
    /// Event count
    pub event_count: u64,
}

impl From<&MetricSlot> for MetricSnapshot {
    fn from(slot: &MetricSlot) -> Self {
        Self {
            name_hash: slot.name_hash,
            counter: slot.counter,
            gauge: slot.gauge,
            cardinality: slot.hll.cardinality(),
            p50: slot.ddsketch.quantile(0.50),
            p95: slot.ddsketch.quantile(0.95),
            p99: slot.ddsketch.quantile(0.99),
            mean: slot.ddsketch.mean(),
            min: slot.ddsketch.min(),
            max: slot.ddsketch.max(),
            event_count: slot.event_count,
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
    use super::*;
    use crate::sketch::FnvHasher;

    fn hash(s: &str) -> u64 {
        FnvHasher::hash_bytes(s.as_bytes())
    }

    #[test]
    fn test_ring_buffer_basic() {
        let mut rb = RingBuffer::<u32, 4>::new();

        assert!(rb.is_empty());
        assert!(!rb.is_full());
        assert_eq!(rb.capacity(), 3);

        assert!(rb.push(1));
        assert!(rb.push(2));
        assert!(rb.push(3));
        assert!(!rb.push(4)); // Full

        assert_eq!(rb.pop(), Some(1));
        assert_eq!(rb.pop(), Some(2));
        assert_eq!(rb.pop(), Some(3));
        assert_eq!(rb.pop(), None);
    }

    #[test]
    fn test_ring_buffer_wrap() {
        let mut rb = RingBuffer::<u32, 4>::new();

        rb.push(1);
        rb.push(2);
        assert_eq!(rb.pop(), Some(1));

        rb.push(3);
        rb.push(4);
        assert_eq!(rb.pop(), Some(2));
        assert_eq!(rb.pop(), Some(3));
        assert_eq!(rb.pop(), Some(4));
        assert_eq!(rb.pop(), None);
    }

    #[test]
    fn test_metric_event() {
        let counter = MetricEvent::counter(hash("requests"), 1.0);
        assert_eq!(counter.metric_type, MetricType::Counter);
        assert_eq!(counter.value, 1.0);

        let hist = MetricEvent::histogram(hash("latency"), 42.5);
        assert_eq!(hist.metric_type, MetricType::Histogram);
        assert_eq!(hist.value, 42.5);
    }

    #[test]
    fn test_metric_slot() {
        let mut slot = MetricSlot::new(hash("test"), 0.05);

        slot.process(&MetricEvent::counter(hash("test"), 5.0));
        slot.process(&MetricEvent::counter(hash("test"), 3.0));
        assert_eq!(slot.counter, 8.0);

        slot.process(&MetricEvent::gauge(hash("test"), 100.0));
        assert_eq!(slot.gauge, 100.0);

        slot.process(&MetricEvent::histogram(hash("test"), 10.0));
        slot.process(&MetricEvent::histogram(hash("test"), 20.0));
        assert_eq!(slot.ddsketch.count(), 2);
    }

    #[test]
    fn test_metric_pipeline() {
        let mut pipeline = MetricPipeline::<64, 1024>::new(0.05);

        let req_hash = hash("http.requests");
        let lat_hash = hash("http.latency");

        // Submit events
        for _ in 0..100 {
            pipeline.submit(MetricEvent::counter(req_hash, 1.0));
        }
        for lat in [10.0, 20.0, 30.0, 40.0, 50.0] {
            pipeline.submit(MetricEvent::histogram(lat_hash, lat));
        }

        // Flush
        pipeline.flush();

        // Check results
        let req_slot = pipeline.get_slot(req_hash).unwrap();
        assert_eq!(req_slot.counter, 100.0);

        let lat_slot = pipeline.get_slot(lat_hash).unwrap();
        assert_eq!(lat_slot.ddsketch.count(), 5);
    }

    #[test]
    fn test_metric_registry() {
        let mut registry = MetricRegistry::<16>::new();

        let h1 = registry
            .register("http.requests", MetricType::Counter)
            .unwrap();
        let h2 = registry
            .register("http.latency", MetricType::Histogram)
            .unwrap();

        assert_ne!(h1, h2);
        assert_eq!(registry.count(), 2);

        let entry = registry.lookup("http.requests").unwrap();
        assert_eq!(entry.metric_type, MetricType::Counter);
    }

    #[test]
    fn test_metric_snapshot() {
        let mut slot = MetricSlot::new(hash("test"), 0.05);

        slot.process(&MetricEvent::counter(hash("test"), 100.0));
        for v in [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0] {
            slot.process(&MetricEvent::histogram(hash("test"), v));
        }

        let snapshot = MetricSnapshot::from(&slot);
        assert_eq!(snapshot.counter, 100.0);
        assert_eq!(snapshot.event_count, 11);
        assert!((snapshot.mean - 55.0).abs() < 1.0);
    }

    #[test]
    fn test_ring_buffer_len() {
        let mut rb = RingBuffer::<u32, 8>::new();
        assert_eq!(rb.len(), 0);
        rb.push(1);
        rb.push(2);
        assert_eq!(rb.len(), 2);
        rb.pop();
        assert_eq!(rb.len(), 1);
    }

    #[test]
    fn test_ring_buffer_dropped() {
        let mut rb = RingBuffer::<u32, 3>::new();
        rb.push(1);
        rb.push(2);
        assert!(!rb.push(3)); // Full (cap=2)
        assert_eq!(rb.dropped(), 1);
    }

    #[test]
    fn test_ring_buffer_clear() {
        let mut rb = RingBuffer::<u32, 8>::new();
        rb.push(1);
        rb.push(2);
        rb.clear();
        assert!(rb.is_empty());
        assert_eq!(rb.dropped(), 0);
    }

    #[test]
    fn test_ring_buffer_default() {
        let rb = RingBuffer::<u32, 8>::default();
        assert!(rb.is_empty());
    }

    #[test]
    fn test_metric_event_with_timestamp() {
        let ev = MetricEvent::counter(42, 1.0).with_timestamp(12345);
        assert_eq!(ev.timestamp, 12345);
    }

    #[test]
    fn test_metric_event_gauge() {
        let ev = MetricEvent::gauge(1, 99.0);
        assert_eq!(ev.metric_type, MetricType::Gauge);
        assert_eq!(ev.value, 99.0);
    }

    #[test]
    fn test_metric_event_unique() {
        let ev = MetricEvent::unique(1, 42);
        assert_eq!(ev.metric_type, MetricType::Unique);
    }

    #[test]
    fn test_metric_slot_reset() {
        let mut slot = MetricSlot::new(1, 0.05);
        slot.process(&MetricEvent::counter(1, 10.0));
        slot.reset();
        assert_eq!(slot.counter, 0.0);
        assert_eq!(slot.event_count, 0);
    }

    #[test]
    fn test_metric_slot_merge() {
        let mut s1 = MetricSlot::new(1, 0.05);
        let mut s2 = MetricSlot::new(1, 0.05);
        s1.process(&MetricEvent::counter(1, 10.0));
        s2.process(&MetricEvent::counter(1, 20.0));
        s1.merge(&s2);
        assert_eq!(s1.counter, 30.0);
    }

    #[test]
    fn test_pipeline_total_events() {
        let mut pipeline = MetricPipeline::<16, 64>::new(0.05);
        pipeline.submit(MetricEvent::counter(1, 1.0));
        pipeline.submit(MetricEvent::counter(1, 1.0));
        pipeline.flush();
        assert_eq!(pipeline.total_events(), 2);
    }

    #[test]
    fn test_pipeline_dropped_events() {
        let mut pipeline = MetricPipeline::<16, 3>::new(0.05);
        pipeline.submit(MetricEvent::counter(1, 1.0));
        pipeline.submit(MetricEvent::counter(1, 1.0));
        // Cap is 2 (N-1), third should be dropped
        pipeline.submit(MetricEvent::counter(1, 1.0));
        assert_eq!(pipeline.dropped_events(), 1);
    }

    #[test]
    fn test_pipeline_queue_len() {
        let mut pipeline = MetricPipeline::<16, 64>::new(0.05);
        pipeline.submit(MetricEvent::counter(1, 1.0));
        assert_eq!(pipeline.queue_len(), 1);
        pipeline.flush();
        assert_eq!(pipeline.queue_len(), 0);
    }

    #[test]
    fn test_pipeline_get_slot_mut() {
        let mut pipeline = MetricPipeline::<64, 128>::new(0.05);
        let h = hash("test_metric");
        pipeline.submit(MetricEvent::counter(h, 5.0));
        pipeline.flush();
        let slot = pipeline.get_slot_mut(h).unwrap();
        assert_eq!(slot.counter, 5.0);
    }

    #[test]
    fn test_pipeline_iter_slots() {
        let mut pipeline = MetricPipeline::<64, 128>::new(0.05);
        pipeline.submit(MetricEvent::counter(hash("a"), 1.0));
        pipeline.submit(MetricEvent::counter(hash("b"), 2.0));
        pipeline.flush();
        let count = pipeline.iter_slots().count();
        assert!(count >= 1);
    }

    #[test]
    fn test_pipeline_reset() {
        let mut pipeline = MetricPipeline::<16, 64>::new(0.05);
        pipeline.submit(MetricEvent::counter(1, 1.0));
        pipeline.flush();
        pipeline.reset();
        assert_eq!(pipeline.total_events(), 0);
    }

    #[test]
    fn test_metric_registry_full() {
        let mut registry = MetricRegistry::<2>::new();
        registry.register("a", MetricType::Counter);
        registry.register("b", MetricType::Counter);
        assert!(registry.register("c", MetricType::Counter).is_none());
    }

    #[test]
    fn test_metric_registry_default() {
        let registry = MetricRegistry::<8>::default();
        assert_eq!(registry.count(), 0);
    }

    #[test]
    fn test_metric_registry_lookup_by_hash() {
        let mut registry = MetricRegistry::<16>::new();
        let h = registry.register("test", MetricType::Histogram).unwrap();
        let entry = registry.lookup_by_hash(h).unwrap();
        assert_eq!(entry.metric_type, MetricType::Histogram);
    }

    #[test]
    fn test_metric_registry_iter() {
        let mut registry = MetricRegistry::<16>::new();
        registry.register("a", MetricType::Counter);
        registry.register("b", MetricType::Gauge);
        assert_eq!(registry.iter().count(), 2);
    }

    #[test]
    fn test_metric_entry_name_str() {
        let entry = MetricEntry::new("http.requests", MetricType::Counter);
        assert_eq!(entry.name_str(), "http.requests");
    }

    // `format!` / `Vec` / the entropy-seeded constructors are `std`-only,
    // so this case cannot run on the `no_std` build
    #[cfg(feature = "std")]
    #[test]
    fn test_metric_snapshot_debug() {
        let slot = MetricSlot::new(1, 0.05);
        let snapshot = MetricSnapshot::from(&slot);
        let s = format!("{snapshot:?}");
        assert!(s.contains("name_hash"));
    }
}