fraiseql-server 2.0.0-alpha.1

HTTP server for FraiseQL v2 GraphQL engine
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
// Phase 12.3 Cycle 9: Performance Optimization (GREEN)
//! Performance optimization for encryption operations including batching,
//! parallelization, caching, and metrics collection.

use std::{
    collections::HashMap,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    time::Instant,
};

use chrono::{DateTime, Utc};

/// Operation metrics for performance monitoring
#[derive(Debug, Clone)]
pub struct OperationMetrics {
    /// Operation type (encrypt, decrypt)
    pub operation:   String,
    /// Latency in microseconds
    pub latency_us:  u64,
    /// Success indicator
    pub success:     bool,
    /// Timestamp
    pub timestamp:   DateTime<Utc>,
    /// Field count (for batch operations)
    pub field_count: usize,
}

impl OperationMetrics {
    /// Create new operation metrics
    pub fn new(operation: impl Into<String>, latency_us: u64, field_count: usize) -> Self {
        Self {
            operation: operation.into(),
            latency_us,
            success: true,
            timestamp: Utc::now(),
            field_count,
        }
    }

    /// Mark as failed
    pub fn with_failure(mut self) -> Self {
        self.success = false;
        self
    }

    /// Get latency in milliseconds
    pub fn latency_ms(&self) -> f64 {
        self.latency_us as f64 / 1000.0
    }
}

/// Batch of encryption operations
#[derive(Debug, Clone)]
pub struct EncryptionBatch {
    /// Batch ID
    pub batch_id:   String,
    /// Fields to encrypt
    pub fields:     Vec<(String, String)>,
    /// Batch creation time
    pub created_at: DateTime<Utc>,
    /// Maximum batch size
    pub max_size:   usize,
}

impl EncryptionBatch {
    /// Create new batch
    pub fn new(batch_id: impl Into<String>, max_size: usize) -> Self {
        Self {
            batch_id: batch_id.into(),
            fields: Vec::new(),
            created_at: Utc::now(),
            max_size,
        }
    }

    /// Add field to batch
    pub fn add_field(
        &mut self,
        field_name: impl Into<String>,
        plaintext: impl Into<String>,
    ) -> bool {
        if self.fields.len() >= self.max_size {
            return false;
        }
        self.fields.push((field_name.into(), plaintext.into()));
        true
    }

    /// Check if batch is full
    pub fn is_full(&self) -> bool {
        self.fields.len() >= self.max_size
    }

    /// Get batch size
    pub fn size(&self) -> usize {
        self.fields.len()
    }

    /// Clear batch
    pub fn clear(&mut self) {
        self.fields.clear();
    }
}

/// Key cache with LRU eviction
pub struct KeyCache {
    /// Cached keys
    cache:        HashMap<String, Vec<u8>>,
    /// Maximum cache size
    max_size:     usize,
    /// Access order for LRU
    access_order: Vec<String>,
    /// Cache hits
    hits:         Arc<AtomicU64>,
    /// Cache misses
    misses:       Arc<AtomicU64>,
}

impl KeyCache {
    /// Create new key cache
    pub fn new(max_size: usize) -> Self {
        Self {
            cache: HashMap::new(),
            max_size,
            access_order: Vec::new(),
            hits: Arc::new(AtomicU64::new(0)),
            misses: Arc::new(AtomicU64::new(0)),
        }
    }

    /// Get key from cache
    pub fn get(&mut self, key_path: &str) -> Option<Vec<u8>> {
        if let Some(key) = self.cache.get(key_path) {
            // Update access order
            self.access_order.retain(|k| k != key_path);
            self.access_order.push(key_path.to_string());
            self.hits.fetch_add(1, Ordering::Relaxed);
            Some(key.clone())
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
            None
        }
    }

    /// Insert key into cache
    pub fn insert(&mut self, key_path: impl Into<String>, key: Vec<u8>) {
        let key_path = key_path.into();

        // If at capacity, evict LRU entry
        if self.cache.len() >= self.max_size && !self.cache.contains_key(&key_path) {
            if let Some(lru_key) = self.access_order.first() {
                let lru = lru_key.clone();
                self.cache.remove(&lru);
                self.access_order.remove(0);
            }
        }

        // Insert or update
        self.cache.insert(key_path.clone(), key);

        // Update access order
        self.access_order.retain(|k| k != &key_path);
        self.access_order.push(key_path);
    }

    /// Get cache statistics
    pub fn stats(&self) -> (u64, u64) {
        (self.hits.load(Ordering::Relaxed), self.misses.load(Ordering::Relaxed))
    }

    /// Get hit rate
    pub fn hit_rate(&self) -> f64 {
        let hits = self.hits.load(Ordering::Relaxed) as f64;
        let misses = self.misses.load(Ordering::Relaxed) as f64;
        let total = hits + misses;
        if total > 0.0 { hits / total } else { 0.0 }
    }

    /// Get cache size
    pub fn size(&self) -> usize {
        self.cache.len()
    }

    /// Clear cache
    pub fn clear(&mut self) {
        self.cache.clear();
        self.access_order.clear();
    }

    /// Get cached entry count
    pub fn entry_count(&self) -> usize {
        self.cache.len()
    }
}

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

/// Performance metrics collector
pub struct PerformanceMonitor {
    /// Collected metrics
    metrics:     Vec<OperationMetrics>,
    /// Maximum metrics to retain
    max_metrics: usize,
    /// Performance SLOs
    slos:        HashMap<String, u64>,
}

impl PerformanceMonitor {
    /// Create new performance monitor
    pub fn new(max_metrics: usize) -> Self {
        Self {
            metrics: Vec::new(),
            max_metrics,
            slos: HashMap::new(),
        }
    }

    /// Record operation metric
    pub fn record_metric(&mut self, metric: OperationMetrics) {
        // Keep bounded history
        if self.metrics.len() >= self.max_metrics {
            self.metrics.remove(0);
        }
        self.metrics.push(metric);
    }

    /// Set SLO for operation
    pub fn set_slo(&mut self, operation: impl Into<String>, latency_us: u64) {
        self.slos.insert(operation.into(), latency_us);
    }

    /// Internal filter helper
    fn filter_metrics<F>(&self, predicate: F) -> Vec<&OperationMetrics>
    where
        F: Fn(&&OperationMetrics) -> bool,
    {
        self.metrics.iter().filter(predicate).collect()
    }

    /// Get metrics for operation
    pub fn metrics_for_operation(&self, operation: &str) -> Vec<&OperationMetrics> {
        self.filter_metrics(|m| m.operation == operation)
    }

    /// Get successful metrics
    pub fn successful_metrics(&self) -> Vec<&OperationMetrics> {
        self.filter_metrics(|m| m.success)
    }

    /// Get failed metrics
    pub fn failed_metrics(&self) -> Vec<&OperationMetrics> {
        self.filter_metrics(|m| !m.success)
    }

    /// Get average latency
    pub fn average_latency_us(&self) -> u64 {
        if self.metrics.is_empty() {
            return 0;
        }
        let sum: u64 = self.metrics.iter().map(|m| m.latency_us).sum();
        sum / self.metrics.len() as u64
    }

    /// Get average latency for operation
    pub fn average_latency_for_operation_us(&self, operation: &str) -> u64 {
        let metrics = self.metrics_for_operation(operation);
        if metrics.is_empty() {
            return 0;
        }
        let sum: u64 = metrics.iter().map(|m| m.latency_us).sum();
        sum / metrics.len() as u64
    }

    /// Get p50 latency (median)
    pub fn p50_latency_us(&self) -> u64 {
        if self.metrics.is_empty() {
            return 0;
        }
        let mut latencies: Vec<_> = self.metrics.iter().map(|m| m.latency_us).collect();
        latencies.sort();
        let idx = latencies.len() / 2;
        latencies[idx]
    }

    /// Get p99 latency
    pub fn p99_latency_us(&self) -> u64 {
        if self.metrics.is_empty() {
            return 0;
        }
        let mut latencies: Vec<_> = self.metrics.iter().map(|m| m.latency_us).collect();
        latencies.sort();
        let idx = (latencies.len() as f64 * 0.99) as usize;
        latencies[idx]
    }

    /// Get max latency
    pub fn max_latency_us(&self) -> u64 {
        self.metrics.iter().map(|m| m.latency_us).max().unwrap_or(0)
    }

    /// Get min latency
    pub fn min_latency_us(&self) -> u64 {
        self.metrics.iter().map(|m| m.latency_us).min().unwrap_or(0)
    }

    /// Get success rate
    pub fn success_rate(&self) -> f64 {
        if self.metrics.is_empty() {
            return 0.0;
        }
        let successful = self.metrics.iter().filter(|m| m.success).count() as f64;
        successful / self.metrics.len() as f64
    }

    /// Get error rate
    pub fn error_rate(&self) -> f64 {
        1.0 - self.success_rate()
    }

    /// Get total fields processed
    pub fn total_fields_processed(&self) -> usize {
        self.metrics.iter().map(|m| m.field_count).sum()
    }

    /// Get operations per second
    pub fn operations_per_second(&self) -> f64 {
        if self.metrics.is_empty() {
            return 0.0;
        }
        self.metrics.len() as f64
    }

    /// Check if SLO violated
    pub fn check_slo(&self, operation: &str) -> bool {
        if let Some(slo) = self.slos.get(operation) {
            let avg_latency = self.average_latency_for_operation_us(operation);
            avg_latency <= *slo
        } else {
            true // No SLO defined
        }
    }

    /// Get all SLO violations
    pub fn check_all_slos(&self) -> Vec<(String, bool)> {
        self.slos.iter().map(|(op, _)| (op.clone(), self.check_slo(op))).collect()
    }

    /// Get metric count
    pub fn metric_count(&self) -> usize {
        self.metrics.len()
    }

    /// Get count by operation
    pub fn operation_count(&self, operation: &str) -> usize {
        self.metrics_for_operation(operation).len()
    }

    /// Clear metrics
    pub fn clear(&mut self) {
        self.metrics.clear();
    }
}

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

/// Operation timing utility
pub struct OperationTimer {
    start: Instant,
}

impl OperationTimer {
    /// Start operation timer
    pub fn start() -> Self {
        Self {
            start: Instant::now(),
        }
    }

    /// Get elapsed microseconds
    pub fn elapsed_us(&self) -> u64 {
        self.start.elapsed().as_micros() as u64
    }

    /// Get elapsed milliseconds
    pub fn elapsed_ms(&self) -> f64 {
        self.elapsed_us() as f64 / 1000.0
    }
}

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

    #[test]
    fn test_operation_metrics_creation() {
        let metric = OperationMetrics::new("encrypt", 1000, 5);
        assert_eq!(metric.operation, "encrypt");
        assert_eq!(metric.latency_us, 1000);
        assert_eq!(metric.field_count, 5);
        assert!(metric.success);
    }

    #[test]
    fn test_operation_metrics_failure() {
        let metric = OperationMetrics::new("decrypt", 2000, 3).with_failure();
        assert!(!metric.success);
    }

    #[test]
    fn test_operation_metrics_latency_ms() {
        let metric = OperationMetrics::new("encrypt", 5000, 1);
        assert_eq!(metric.latency_ms(), 5.0);
    }

    #[test]
    fn test_encryption_batch_creation() {
        let batch = EncryptionBatch::new("batch1", 100);
        assert_eq!(batch.batch_id, "batch1");
        assert_eq!(batch.max_size, 100);
        assert_eq!(batch.size(), 0);
    }

    #[test]
    fn test_encryption_batch_add_field() {
        let mut batch = EncryptionBatch::new("batch1", 10);
        let result = batch.add_field("email", "user@example.com");
        assert!(result);
        assert_eq!(batch.size(), 1);
    }

    #[test]
    fn test_encryption_batch_full() {
        let mut batch = EncryptionBatch::new("batch1", 2);
        batch.add_field("email", "user@example.com");
        batch.add_field("phone", "555-1234");
        assert!(batch.is_full());
        let result = batch.add_field("ssn", "123-45-6789");
        assert!(!result); // Batch full
    }

    #[test]
    fn test_encryption_batch_clear() {
        let mut batch = EncryptionBatch::new("batch1", 10);
        batch.add_field("email", "user@example.com");
        assert_eq!(batch.size(), 1);
        batch.clear();
        assert_eq!(batch.size(), 0);
    }

    #[test]
    fn test_key_cache_creation() {
        let cache = KeyCache::new(100);
        assert_eq!(cache.size(), 0);
        assert_eq!(cache.entry_count(), 0);
    }

    #[test]
    fn test_key_cache_insert_and_get() {
        let mut cache = KeyCache::new(100);
        let key = vec![1, 2, 3, 4];
        cache.insert("key1", key.clone());
        let retrieved = cache.get("key1");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap(), key);
    }

    #[test]
    fn test_key_cache_miss() {
        let mut cache = KeyCache::new(100);
        let result = cache.get("nonexistent");
        assert!(result.is_none());
    }

    #[test]
    fn test_key_cache_lru_eviction() {
        let mut cache = KeyCache::new(2);
        cache.insert("key1", vec![1]);
        cache.insert("key2", vec![2]);
        cache.insert("key3", vec![3]); // Should evict key1

        assert!(cache.get("key1").is_none());
        assert!(cache.get("key2").is_some());
        assert!(cache.get("key3").is_some());
    }

    #[test]
    fn test_key_cache_hit_rate() {
        let mut cache = KeyCache::new(100);
        cache.insert("key1", vec![1]);
        cache.get("key1"); // hit
        cache.get("key1"); // hit
        cache.get("key2"); // miss

        let (hits, misses) = cache.stats();
        assert_eq!(hits, 2);
        assert_eq!(misses, 1);
        assert_eq!(cache.hit_rate(), 2.0 / 3.0);
    }

    #[test]
    fn test_key_cache_clear() {
        let mut cache = KeyCache::new(100);
        cache.insert("key1", vec![1]);
        assert_eq!(cache.size(), 1);
        cache.clear();
        assert_eq!(cache.size(), 0);
    }

    #[test]
    fn test_key_cache_default() {
        let cache = KeyCache::default();
        assert_eq!(cache.max_size, 1000);
    }

    #[test]
    fn test_performance_monitor_record_metric() {
        let mut monitor = PerformanceMonitor::new(100);
        let metric = OperationMetrics::new("encrypt", 1000, 5);
        monitor.record_metric(metric);
        assert_eq!(monitor.metric_count(), 1);
    }

    #[test]
    fn test_performance_monitor_average_latency() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 2000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 3000, 5));
        assert_eq!(monitor.average_latency_us(), 2000);
    }

    #[test]
    fn test_performance_monitor_p99_latency() {
        let mut monitor = PerformanceMonitor::new(100);
        for i in 1..=100 {
            monitor.record_metric(OperationMetrics::new("encrypt", i * 100, 1));
        }
        let p99 = monitor.p99_latency_us();
        assert!(p99 >= 9900); // p99 should be high
    }

    #[test]
    fn test_performance_monitor_success_rate() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        let mut metric = OperationMetrics::new("encrypt", 2000, 5);
        metric = metric.with_failure();
        monitor.record_metric(metric);
        assert_eq!(monitor.success_rate(), 0.5);
    }

    #[test]
    fn test_performance_monitor_slo() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.set_slo("encrypt", 2000);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 1500, 5));
        assert!(monitor.check_slo("encrypt"));
    }

    #[test]
    fn test_performance_monitor_slo_violation() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.set_slo("encrypt", 1400);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 2000, 5));
        assert!(!monitor.check_slo("encrypt")); // Average 1500 > SLO 1400
    }

    #[test]
    fn test_performance_monitor_clear() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        assert_eq!(monitor.metric_count(), 1);
        monitor.clear();
        assert_eq!(monitor.metric_count(), 0);
    }

    #[test]
    fn test_operation_timer() {
        let timer = OperationTimer::start();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let elapsed_us = timer.elapsed_us();
        assert!(elapsed_us >= 10000); // At least 10ms
    }

    #[test]
    fn test_operation_timer_ms() {
        let timer = OperationTimer::start();
        std::thread::sleep(std::time::Duration::from_millis(10));
        let elapsed_ms = timer.elapsed_ms();
        assert!(elapsed_ms >= 10.0);
    }

    #[test]
    fn test_performance_monitor_metrics_for_operation() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        monitor.record_metric(OperationMetrics::new("decrypt", 2000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 1500, 5));

        let encrypt_metrics = monitor.metrics_for_operation("encrypt");
        assert_eq!(encrypt_metrics.len(), 2);
    }

    #[test]
    fn test_performance_monitor_successful_metrics() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        let mut failed = OperationMetrics::new("encrypt", 2000, 5);
        failed = failed.with_failure();
        monitor.record_metric(failed);

        let successful = monitor.successful_metrics();
        assert_eq!(successful.len(), 1);
    }

    #[test]
    fn test_performance_monitor_failed_metrics() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        let mut failed = OperationMetrics::new("encrypt", 2000, 5);
        failed = failed.with_failure();
        monitor.record_metric(failed);

        let failed_metrics = monitor.failed_metrics();
        assert_eq!(failed_metrics.len(), 1);
    }

    #[test]
    fn test_performance_monitor_p50_latency() {
        let mut monitor = PerformanceMonitor::new(100);
        for i in 1..=10 {
            monitor.record_metric(OperationMetrics::new("encrypt", i * 100, 1));
        }
        let p50 = monitor.p50_latency_us();
        assert_eq!(p50, 600); // Median of 100-1000 (index 5 in 0-9 range)
    }

    #[test]
    fn test_performance_monitor_max_min_latency() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 5000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 3000, 5));

        assert_eq!(monitor.max_latency_us(), 5000);
        assert_eq!(monitor.min_latency_us(), 1000);
    }

    #[test]
    fn test_performance_monitor_error_rate() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        let mut failed = OperationMetrics::new("encrypt", 2000, 5);
        failed = failed.with_failure();
        monitor.record_metric(failed);

        assert_eq!(monitor.error_rate(), 0.5);
    }

    #[test]
    fn test_performance_monitor_total_fields_processed() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 2000, 10));
        monitor.record_metric(OperationMetrics::new("encrypt", 3000, 3));

        assert_eq!(monitor.total_fields_processed(), 18);
    }

    #[test]
    fn test_performance_monitor_average_latency_for_operation() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        monitor.record_metric(OperationMetrics::new("decrypt", 4000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 2000, 5));

        let avg_encrypt = monitor.average_latency_for_operation_us("encrypt");
        assert_eq!(avg_encrypt, 1500);
    }

    #[test]
    fn test_performance_monitor_check_all_slos() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.set_slo("encrypt", 2000);
        monitor.set_slo("decrypt", 3000);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        monitor.record_metric(OperationMetrics::new("decrypt", 4000, 5));

        let violations = monitor.check_all_slos();
        assert_eq!(violations.len(), 2);

        // Check that encrypt passes and decrypt fails (order-independent)
        let encrypt_pass = violations.iter().any(|(op, passed)| op == "encrypt" && *passed);
        let decrypt_fail = violations.iter().any(|(op, passed)| op == "decrypt" && !*passed);
        assert!(encrypt_pass);
        assert!(decrypt_fail);
    }

    #[test]
    fn test_performance_monitor_operation_count() {
        let mut monitor = PerformanceMonitor::new(100);
        monitor.record_metric(OperationMetrics::new("encrypt", 1000, 5));
        monitor.record_metric(OperationMetrics::new("encrypt", 2000, 5));
        monitor.record_metric(OperationMetrics::new("decrypt", 3000, 5));

        assert_eq!(monitor.operation_count("encrypt"), 2);
        assert_eq!(monitor.operation_count("decrypt"), 1);
    }
}