shardex 0.1.0

A high-performance memory-mapped vector search engine with ACID transactions and incremental updates
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
//! Monitoring and Statistics Collection
//!
//! This module provides comprehensive monitoring capabilities for Shardex operations including:
//! - Performance metrics (latency percentiles, throughput)
//! - Resource usage tracking (memory, disk, file descriptors)
//! - Historical data collection and trending
//! - Bloom filter hit rate monitoring
//!
//! The monitoring system is designed to be non-intrusive with minimal performance overhead
//! while providing detailed operational visibility.

use hdrhistogram::Histogram;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use tokio::sync::RwLock;

// HDRHistogram configuration constants
const HISTOGRAM_MIN_MICROS: u64 = 1; // 1 microsecond minimum
const HISTOGRAM_MAX_MICROS: u64 = 3_600_000_000; // 1 hour in microseconds
const HISTOGRAM_PRECISION: u8 = 3; // 3 significant digits

/// Enhanced index statistics with comprehensive performance monitoring
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DetailedIndexStats {
    // Basic index metrics
    pub total_shards: usize,
    pub total_postings: usize,
    pub pending_operations: usize,
    pub memory_usage: usize,
    pub disk_usage: usize,
    pub active_postings: usize,
    pub deleted_postings: usize,
    pub average_shard_utilization: f32,
    pub vector_dimension: usize,

    // Performance metrics
    pub search_latency_p50: Duration,
    pub search_latency_p95: Duration,
    pub search_latency_p99: Duration,
    pub write_throughput: f64, // operations per second
    pub read_throughput: f64,  // searches per second

    // Bloom filter metrics
    pub bloom_filter_hit_rate: f64,
    pub bloom_filter_false_positive_rate: f64,
    pub bloom_filter_memory_usage: usize,

    // Resource tracking
    pub file_descriptor_count: usize,
    pub memory_mapped_regions: usize,
    pub wal_segment_count: usize,
    pub active_connections: usize,

    // Historical tracking
    pub uptime: Duration,
    pub total_operations: u64,
    pub last_updated: SystemTime,
}

/// Real-time performance monitoring system
///
/// Refactored to reduce lock contention by using:
/// - Atomic counters for simple metrics that can be updated concurrently
/// - Single RwLock for complex aggregated metrics that require coordination
/// - Lock-free operation counters for high-frequency updates
pub struct PerformanceMonitor {
    /// Atomic counters for high-frequency simple metrics
    counters: Arc<AtomicCounters>,
    /// Complex metrics that require coordination (protected by single lock)
    complex_metrics: Arc<RwLock<ComplexMetrics>>,
    /// System start time for uptime calculation
    start_time: Instant,
}

/// Atomic counters for lock-free metric updates
#[derive(Debug)]
pub struct AtomicCounters {
    // Search counters
    pub total_searches: std::sync::atomic::AtomicU64,
    pub successful_searches: std::sync::atomic::AtomicU64,
    pub failed_searches: std::sync::atomic::AtomicU64,

    // Write counters
    pub total_writes: std::sync::atomic::AtomicU64,
    pub successful_writes: std::sync::atomic::AtomicU64,
    pub failed_writes: std::sync::atomic::AtomicU64,
    pub bytes_written: std::sync::atomic::AtomicU64,

    // Bloom filter counters
    pub bloom_filter_hits: std::sync::atomic::AtomicU64,
    pub bloom_filter_misses: std::sync::atomic::AtomicU64,
    pub bloom_filter_false_positives: std::sync::atomic::AtomicU64,

    // Resource counters
    pub file_descriptor_count: std::sync::atomic::AtomicUsize,
    pub active_connections: std::sync::atomic::AtomicUsize,
    pub total_operations: std::sync::atomic::AtomicU64,
}

impl Default for AtomicCounters {
    fn default() -> Self {
        Self {
            total_searches: std::sync::atomic::AtomicU64::new(0),
            successful_searches: std::sync::atomic::AtomicU64::new(0),
            failed_searches: std::sync::atomic::AtomicU64::new(0),
            total_writes: std::sync::atomic::AtomicU64::new(0),
            successful_writes: std::sync::atomic::AtomicU64::new(0),
            failed_writes: std::sync::atomic::AtomicU64::new(0),
            bytes_written: std::sync::atomic::AtomicU64::new(0),
            bloom_filter_hits: std::sync::atomic::AtomicU64::new(0),
            bloom_filter_misses: std::sync::atomic::AtomicU64::new(0),
            bloom_filter_false_positives: std::sync::atomic::AtomicU64::new(0),
            file_descriptor_count: std::sync::atomic::AtomicUsize::new(0),
            active_connections: std::sync::atomic::AtomicUsize::new(0),
            total_operations: std::sync::atomic::AtomicU64::new(0),
        }
    }
}

/// Complex metrics requiring coordination and calculation
#[derive(Debug)]
pub struct ComplexMetrics {
    // Search metrics with HDRHistogram-based percentile tracking
    pub search_latency_calculator: PercentileCalculator,
    pub recent_search_times: std::collections::VecDeque<Instant>,

    // Write metrics with HDRHistogram-based percentile tracking
    pub write_latency_calculator: PercentileCalculator,
    pub recent_write_times: std::collections::VecDeque<Instant>,
    pub last_write_time: Option<Instant>,

    // Bloom filter metrics
    pub bloom_filter_memory_usage: usize,

    // Document text metrics
    pub text_storage_size: usize,
    pub text_retrieval_cache_hits: u64,
    pub text_retrieval_cache_misses: u64,

    // Resource metrics
    pub memory_usage: usize,
    pub memory_mapped_regions: usize,
    pub wal_segment_count: usize,

    // Historical data
    pub snapshots: std::collections::VecDeque<MetricsSnapshot>,
    pub last_updated: SystemTime,
}

impl Default for ComplexMetrics {
    fn default() -> Self {
        Self {
            search_latency_calculator: PercentileCalculator::new(),
            recent_search_times: std::collections::VecDeque::new(),
            write_latency_calculator: PercentileCalculator::new(),
            recent_write_times: std::collections::VecDeque::new(),
            last_write_time: None,
            bloom_filter_memory_usage: 0,
            text_storage_size: 0,
            text_retrieval_cache_hits: 0,
            text_retrieval_cache_misses: 0,
            memory_usage: 0,
            memory_mapped_regions: 0,
            wal_segment_count: 0,
            snapshots: std::collections::VecDeque::new(),
            last_updated: SystemTime::UNIX_EPOCH,
        }
    }
}

/// Metrics snapshot for historical tracking
#[derive(Debug, Clone)]
pub struct MetricsSnapshot {
    pub timestamp: SystemTime,
    pub total_operations: u64,
    pub memory_usage: usize,
    pub search_throughput: f64,
    pub write_throughput: f64,
    pub bloom_filter_hit_rate: f64,
}

impl Default for MetricsSnapshot {
    fn default() -> Self {
        Self {
            timestamp: SystemTime::now(),
            total_operations: 0,
            memory_usage: 0,
            search_throughput: 0.0,
            write_throughput: 0.0,
            bloom_filter_hit_rate: 0.0,
        }
    }
}

/// Write operation performance metrics
#[derive(Debug, Clone, Default)]
pub struct WriteMetrics {
    pub total_writes: u64,
    pub successful_writes: u64,
    pub failed_writes: u64,
    pub average_write_latency_ms: f64,
    pub write_throughput_ops_per_sec: f64,
    pub bytes_written: u64,
    pub last_write_time: Option<Instant>,
    /// WAL-specific metrics
    pub wal_writes: u64,
    pub wal_flushes: u64,
    pub average_wal_flush_latency_ms: f64,
}

/// Bloom filter performance tracking
#[derive(Debug, Clone, Default)]
pub struct BloomFilterMetrics {
    pub total_lookups: u64,
    pub hits: u64,
    pub misses: u64,
    pub false_positives: u64,
    pub hit_rate: f64,
    pub false_positive_rate: f64,
    pub average_lookup_time_ns: f64,
    pub memory_usage_bytes: usize,
}

/// System resource usage metrics
#[derive(Debug, Clone, Default)]
pub struct ResourceMetrics {
    pub memory_usage_bytes: usize,
    pub disk_usage_bytes: usize,
    pub file_descriptor_count: usize,
    pub memory_mapped_regions: usize,
    pub wal_segment_count: usize,
    pub shard_file_count: usize,
    pub active_connections: usize,
}

/// Document text storage performance metrics
#[derive(Debug, Clone, Default)]
pub struct DocumentTextMetrics {
    pub total_documents: u64,
    pub total_text_size: u64,
    pub average_document_size: f64,
    pub document_storage_operations: u64,
    pub document_retrieval_operations: u64,
}

/// Historical data for trending analysis
#[derive(Debug, Clone)]
pub struct HistoricalData {
    pub data_points: Vec<HistoricalDataPoint>,
    pub max_data_points: usize,
    pub collection_interval: Duration,
    pub last_collection: Option<Instant>,
}

/// A single historical data point
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HistoricalDataPoint {
    pub timestamp: SystemTime,
    pub search_latency_p95: Duration,
    pub write_throughput: f64,
    pub memory_usage: usize,
    pub disk_usage: usize,
    pub bloom_filter_hit_rate: f64,
    pub active_shards: usize,
    pub pending_operations: usize,
}

/// Trend analysis utility
#[derive(Debug, Clone)]
pub struct TrendAnalysis {
    pub slope: f64,
    pub correlation: f64,
    pub trend_direction: TrendDirection,
    pub confidence: f64,
}

/// Trend direction indicator
#[derive(Debug, Clone, PartialEq)]
pub enum TrendDirection {
    Increasing,
    Decreasing,
    Stable,
}

/// Enhanced percentile calculator using HDRHistogram for accurate and efficient percentile tracking
pub struct PercentileCalculator {
    /// HDRHistogram for efficient percentile calculations
    /// Records values in microseconds to avoid precision loss
    histogram: Histogram<u64>,
    /// Total number of samples recorded
    sample_count: usize,
}

impl std::fmt::Debug for PercentileCalculator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PercentileCalculator")
            .field("sample_count", &self.sample_count)
            .field("min_us", &self.histogram.min())
            .field("max_us", &self.histogram.max())
            .field("mean_us", &(self.histogram.mean() as u64))
            .finish()
    }
}

impl PerformanceMonitor {
    /// Create a new performance monitor with reduced lock contention
    pub fn new() -> Self {
        Self {
            counters: Arc::new(AtomicCounters::default()),
            complex_metrics: Arc::new(RwLock::new(ComplexMetrics::default())),
            start_time: Instant::now(),
        }
    }

    /// Record a search operation with reduced lock contention
    pub async fn record_search(&self, latency: Duration, _result_count: usize, success: bool) {
        // Update simple counters atomically (lock-free)
        self.counters
            .total_searches
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        if success {
            self.counters
                .successful_searches
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        } else {
            self.counters
                .failed_searches
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
        self.counters
            .total_operations
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        // Update complex metrics that require coordination (single lock)
        let mut complex = self.complex_metrics.write().await;
        complex.search_latency_calculator.add_sample(latency);
        complex.recent_search_times.push_back(Instant::now());

        // Keep only recent timestamps for throughput calculation (last 60 seconds)
        let now = Instant::now();
        while let Some(&front_time) = complex.recent_search_times.front() {
            if now.duration_since(front_time) > Duration::from_secs(60) {
                complex.recent_search_times.pop_front();
            } else {
                break;
            }
        }

        complex.last_updated = SystemTime::now();
    }

    /// Record a write operation with reduced lock contention
    pub async fn record_write(&self, latency: Duration, bytes_written: u64, success: bool) {
        // Update simple counters atomically (lock-free)
        self.counters
            .total_writes
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        if success {
            self.counters
                .successful_writes
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        } else {
            self.counters
                .failed_writes
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
        self.counters
            .bytes_written
            .fetch_add(bytes_written, std::sync::atomic::Ordering::Relaxed);
        self.counters
            .total_operations
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        // Update complex metrics that require coordination (single lock)
        let mut complex = self.complex_metrics.write().await;
        complex.write_latency_calculator.add_sample(latency);
        complex.recent_write_times.push_back(Instant::now());
        complex.last_write_time = Some(Instant::now());

        // Keep only recent timestamps for throughput calculation (last 60 seconds)
        let now = Instant::now();
        while let Some(&front_time) = complex.recent_write_times.front() {
            if now.duration_since(front_time) > Duration::from_secs(60) {
                complex.recent_write_times.pop_front();
            } else {
                break;
            }
        }

        complex.last_updated = SystemTime::now();
    }

    /// Record bloom filter operation with reduced lock contention
    pub async fn record_bloom_filter_lookup(&self, hit: bool, _lookup_time: Duration, false_positive: bool) {
        // Update simple counters atomically (lock-free)
        if hit {
            self.counters
                .bloom_filter_hits
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        } else {
            self.counters
                .bloom_filter_misses
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }

        if false_positive {
            self.counters
                .bloom_filter_false_positives
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }

        self.counters
            .total_operations
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    /// Update resource usage metrics
    pub async fn update_resource_metrics(&self, memory_usage: usize, _disk_usage: usize, fd_count: usize) {
        let mut complex = self.complex_metrics.write().await;
        complex.memory_usage = memory_usage;
        // Update atomic file descriptor count
        self.counters
            .file_descriptor_count
            .store(fd_count, std::sync::atomic::Ordering::Relaxed);
    }

    /// Increment the total operations counter
    pub fn increment_operations_counter(&self) {
        self.counters
            .total_operations
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    /// Add a specific count to the operations counter
    pub fn add_operations_count(&self, count: u64) {
        self.counters
            .total_operations
            .fetch_add(count, std::sync::atomic::Ordering::Relaxed);
    }

    /// Increment the successful searches counter
    pub fn increment_successful_searches(&self) {
        self.counters
            .successful_searches
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    /// Increment the failed searches counter  
    pub fn increment_failed_searches(&self) {
        self.counters
            .failed_searches
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    /// Increment the successful writes counter
    pub fn increment_successful_writes(&self) {
        self.counters
            .successful_writes
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    /// Increment the failed writes counter
    pub fn increment_failed_writes(&self) {
        self.counters
            .failed_writes
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }

    /// Update bytes written counter
    pub fn add_bytes_written(&self, bytes: u64) {
        self.counters
            .bytes_written
            .fetch_add(bytes, std::sync::atomic::Ordering::Relaxed);
    }

    /// Get detailed stats with computed metrics
    pub async fn get_detailed_stats(&self) -> DetailedIndexStats {
        let mut complex = self.complex_metrics.write().await;

        // Calculate percentiles using HDRHistogram
        let search_p50 = complex.search_latency_calculator.percentile(0.5);
        let search_p95 = complex.search_latency_calculator.percentile(0.95);
        let search_p99 = complex.search_latency_calculator.percentile(0.99);

        // Calculate throughput from recent operations
        let search_throughput = complex.recent_search_times.len() as f64 / 60.0; // per second over last minute
        let write_throughput = complex.recent_write_times.len() as f64 / 60.0;

        // Calculate bloom filter hit rate
        let bloom_hits = self
            .counters
            .bloom_filter_hits
            .load(std::sync::atomic::Ordering::Relaxed);
        let bloom_misses = self
            .counters
            .bloom_filter_misses
            .load(std::sync::atomic::Ordering::Relaxed);
        let bloom_total = bloom_hits + bloom_misses;
        let bloom_hit_rate = if bloom_total > 0 {
            bloom_hits as f64 / bloom_total as f64
        } else {
            0.0
        };

        let bloom_false_positives = self
            .counters
            .bloom_filter_false_positives
            .load(std::sync::atomic::Ordering::Relaxed);
        let bloom_false_positive_rate = if bloom_total > 0 {
            bloom_false_positives as f64 / bloom_total as f64
        } else {
            0.0
        };

        DetailedIndexStats {
            total_shards: 1, // Simplified
            total_postings: 0,
            pending_operations: 0,
            memory_usage: complex.memory_usage,
            disk_usage: 0, // Not tracked in new design
            active_postings: 0,
            deleted_postings: 0,
            average_shard_utilization: 0.0,
            vector_dimension: 0,
            search_latency_p50: search_p50,
            search_latency_p95: search_p95,
            search_latency_p99: search_p99,
            write_throughput,
            read_throughput: search_throughput,
            bloom_filter_hit_rate: bloom_hit_rate,
            bloom_filter_false_positive_rate: bloom_false_positive_rate,
            bloom_filter_memory_usage: complex.bloom_filter_memory_usage,
            file_descriptor_count: self
                .counters
                .file_descriptor_count
                .load(std::sync::atomic::Ordering::Relaxed),
            memory_mapped_regions: complex.memory_mapped_regions,
            wal_segment_count: complex.wal_segment_count,
            active_connections: self
                .counters
                .active_connections
                .load(std::sync::atomic::Ordering::Relaxed),
            uptime: self.start_time.elapsed(),
            total_operations: self
                .counters
                .total_operations
                .load(std::sync::atomic::Ordering::Relaxed),
            last_updated: complex.last_updated,
        }
    }
}

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

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

impl PercentileCalculator {
    pub fn new() -> Self {
        // Create histogram that can track values from 1 microsecond to 1 hour with 3 significant digits
        // This provides good precision for latency measurements
        let histogram = Histogram::new_with_bounds(HISTOGRAM_MIN_MICROS, HISTOGRAM_MAX_MICROS, HISTOGRAM_PRECISION)
            .expect("Failed to create HDRHistogram with valid bounds");

        Self {
            histogram,
            sample_count: 0,
        }
    }

    /// Add a duration sample to the histogram
    pub fn add_sample(&mut self, duration: Duration) {
        // Convert duration to microseconds for histogram storage
        // HDRHistogram works with integers, so we use microseconds for good precision
        let micros = duration.as_micros() as u64;

        // Clamp to valid range (1 microsecond to 1 hour)
        let clamped_micros = micros.clamp(HISTOGRAM_MIN_MICROS, HISTOGRAM_MAX_MICROS);

        if let Err(e) = self.histogram.record(clamped_micros) {
            // Log error but continue operation - this is monitoring code and shouldn't break the system
            tracing::warn!("Failed to record histogram sample {}: {}", clamped_micros, e);
        } else {
            self.sample_count += 1;
        }
    }

    /// Get percentile value from the histogram
    pub fn percentile(&mut self, p: f64) -> Duration {
        if self.sample_count == 0 {
            return Duration::ZERO;
        }

        // Convert percentile (0.0-1.0) to percentile value (0.0-100.0)
        let percentile_value = (p * 100.0).clamp(0.0, 100.0);

        // Get value at percentile (in microseconds)
        let micros = self.histogram.value_at_percentile(percentile_value);

        // Convert back to Duration
        Duration::from_micros(micros)
    }

    /// Clear all samples from the histogram
    pub fn clear(&mut self) {
        self.histogram.clear();
        self.sample_count = 0;
    }

    /// Get the total number of samples recorded
    pub fn sample_count(&self) -> usize {
        self.sample_count
    }

    /// Get minimum value recorded
    pub fn min(&self) -> Duration {
        if self.sample_count == 0 {
            Duration::ZERO
        } else {
            Duration::from_micros(self.histogram.min())
        }
    }

    /// Get maximum value recorded  
    pub fn max(&self) -> Duration {
        if self.sample_count == 0 {
            Duration::ZERO
        } else {
            Duration::from_micros(self.histogram.max())
        }
    }

    /// Get mean value
    pub fn mean(&self) -> Duration {
        if self.sample_count == 0 {
            Duration::ZERO
        } else {
            Duration::from_micros(self.histogram.mean() as u64)
        }
    }
}

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

    // Test tolerance constants for percentile testing
    const PERCENTILE_TEST_TOLERANCE_MS: u64 = 5; // 5ms tolerance for percentile tests

    #[tokio::test]
    async fn test_performance_monitor() {
        let monitor = PerformanceMonitor::new();

        // Test write recording
        monitor
            .record_write(Duration::from_millis(10), 1024, true)
            .await;
        monitor
            .record_write(Duration::from_millis(15), 2048, true)
            .await;

        let stats = monitor.get_detailed_stats().await;
        assert!(stats.write_throughput >= 0.0);
        assert!(stats.uptime > Duration::ZERO);
    }

    #[tokio::test]
    async fn test_bloom_filter_metrics() {
        let monitor = PerformanceMonitor::new();

        // Record some bloom filter operations
        monitor
            .record_bloom_filter_lookup(true, Duration::from_nanos(100), false)
            .await;
        monitor
            .record_bloom_filter_lookup(false, Duration::from_nanos(150), false)
            .await;
        monitor
            .record_bloom_filter_lookup(true, Duration::from_nanos(120), true)
            .await;

        let stats = monitor.get_detailed_stats().await;
        assert!(stats.bloom_filter_hit_rate > 0.0);
        assert!(stats.bloom_filter_false_positive_rate >= 0.0);
    }

    #[test]
    fn test_percentile_calculator() {
        let mut calc = PercentileCalculator::new();

        // Add sample data (1ms to 100ms)
        for i in 1..=100 {
            calc.add_sample(Duration::from_millis(i));
        }

        // Test that we have recorded the expected number of samples
        assert_eq!(calc.sample_count(), 100);

        // Test percentiles (HDRHistogram may have slight variations due to bucketing)
        // We test within reasonable ranges since HDRHistogram uses bucketing
        let p50 = calc.percentile(0.5);
        let p95 = calc.percentile(0.95);
        let p99 = calc.percentile(0.99);

        // P50 should be around 50ms (within tolerance)
        assert!(
            p50 >= Duration::from_millis(50 - PERCENTILE_TEST_TOLERANCE_MS)
                && p50 <= Duration::from_millis(50 + PERCENTILE_TEST_TOLERANCE_MS),
            "P50 was {:?}, expected around 50ms",
            p50
        );

        // P95 should be around 95ms (within tolerance)
        assert!(
            p95 >= Duration::from_millis(95 - PERCENTILE_TEST_TOLERANCE_MS)
                && p95 <= Duration::from_millis(95 + PERCENTILE_TEST_TOLERANCE_MS),
            "P95 was {:?}, expected around 95ms",
            p95
        );

        // P99 should be around 99ms (within tolerance)
        assert!(
            p99 >= Duration::from_millis(99 - PERCENTILE_TEST_TOLERANCE_MS)
                && p99 <= Duration::from_millis(99 + PERCENTILE_TEST_TOLERANCE_MS),
            "P99 was {:?}, expected around 99ms",
            p99
        );

        // Test min/max (HDRHistogram may have slight bucketing variations)
        assert_eq!(calc.min(), Duration::from_millis(1));

        // Max should be close to 100ms but HDRHistogram bucketing may cause minor variations
        let max_val = calc.max();
        assert!(
            max_val >= Duration::from_millis(100)
                && max_val <= Duration::from_millis(100 + PERCENTILE_TEST_TOLERANCE_MS),
            "Max was {:?}, expected around 100ms",
            max_val
        );

        // Test edge cases
        calc.clear();
        assert_eq!(calc.sample_count(), 0);
        assert_eq!(calc.percentile(0.5), Duration::ZERO);
        assert_eq!(calc.min(), Duration::ZERO);
        assert_eq!(calc.max(), Duration::ZERO);

        // Single sample test - create a fresh calculator to avoid any state issues
        let mut fresh_calc = PercentileCalculator::new();
        fresh_calc.add_sample(Duration::from_millis(42));
        assert_eq!(fresh_calc.sample_count(), 1);

        // With single sample, all percentiles should return the same value
        // HDRHistogram bucketing may cause minor variations, so allow small tolerance
        let p50 = fresh_calc.percentile(0.5);
        let p95 = fresh_calc.percentile(0.95);
        let min_val = fresh_calc.min();
        let max_val = fresh_calc.max();

        // Allow for HDRHistogram bucketing variations (within reasonable range)
        assert!(
            p50 >= Duration::from_millis(35) && p50 <= Duration::from_millis(50),
            "P50 was {:?}, expected around 42ms",
            p50
        );
        assert!(
            p95 >= Duration::from_millis(35) && p95 <= Duration::from_millis(50),
            "P95 was {:?}, expected around 42ms",
            p95
        );
        assert!(
            min_val >= Duration::from_millis(35) && min_val <= Duration::from_millis(50),
            "Min was {:?}, expected around 42ms",
            min_val
        );
        assert!(
            max_val >= Duration::from_millis(35) && max_val <= Duration::from_millis(50),
            "Max was {:?}, expected around 42ms",
            max_val
        );
    }

    #[test]
    fn test_percentile_calculator_with_microsecond_precision() {
        let mut calc = PercentileCalculator::new();

        // Add samples with microsecond precision
        for i in 1..=1000 {
            calc.add_sample(Duration::from_micros(i));
        }

        assert_eq!(calc.sample_count(), 1000);

        // Test that we can handle microsecond-level precision
        let p50 = calc.percentile(0.5);
        let p95 = calc.percentile(0.95);

        // Values should be in microseconds range
        assert!(p50.as_micros() > 400 && p50.as_micros() < 600);
        assert!(p95.as_micros() > 900 && p95.as_micros() < 1000);

        // Test mean calculation
        let mean = calc.mean();
        assert!(mean.as_micros() > 400 && mean.as_micros() < 600);
    }

    #[test]
    fn test_percentile_calculator_extreme_values() {
        let mut calc = PercentileCalculator::new();

        // Test with very small values (should be clamped to 1 microsecond minimum)
        calc.add_sample(Duration::from_nanos(1));
        calc.add_sample(Duration::from_nanos(500));
        calc.add_sample(Duration::from_micros(10));
        calc.add_sample(Duration::from_millis(1));

        assert_eq!(calc.sample_count(), 4);

        let min_val = calc.min();
        // Should be at least 1 microsecond due to clamping
        assert!(min_val >= Duration::from_micros(1));

        let max_val = calc.max();
        // HDRHistogram bucketing may cause minor variations
        assert!(
            max_val >= Duration::from_millis(1) && max_val <= Duration::from_millis(2),
            "Max was {:?}, expected around 1ms",
            max_val
        );
    }
}