quantrs2-circuit 0.1.3

Quantum circuit representation and DSL for the QuantRS2 framework
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
//! Circuit caching for repeated execution
//!
//! This module provides sophisticated caching mechanisms for quantum circuits to avoid
//! redundant compilation, optimization, and execution overhead when circuits are reused
//! across multiple invocations.

use crate::builder::Circuit;
use crate::simulator_interface::{CompiledCircuit, ExecutionResult};
use crate::transpiler::TranspilationResult;
use quantrs2_core::{
    error::{QuantRS2Error, QuantRS2Result},
    gate::GateOp,
};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime};

/// Cache entry for compiled circuits
#[derive(Debug, Clone)]
pub struct CacheEntry<T> {
    /// Cached value
    pub value: T,
    /// Creation timestamp
    pub created_at: SystemTime,
    /// Last access timestamp
    pub last_accessed: SystemTime,
    /// Access count
    pub access_count: usize,
    /// Cache key hash
    pub key_hash: u64,
    /// Size estimate in bytes
    pub size_bytes: usize,
}

/// Cache eviction policy
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvictionPolicy {
    /// Least Recently Used
    LRU,
    /// Least Frequently Used
    LFU,
    /// Time To Live
    TTL(Duration),
    /// First In First Out
    FIFO,
    /// Random eviction
    Random,
    /// Size-based eviction
    SizeBased,
}

/// Cache configuration
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// Maximum number of entries
    pub max_entries: usize,
    /// Maximum memory usage in bytes
    pub max_memory_bytes: usize,
    /// Eviction policy
    pub eviction_policy: EvictionPolicy,
    /// Enable compression for stored circuits
    pub enable_compression: bool,
    /// Cache hit statistics collection
    pub collect_stats: bool,
    /// Persistence to disk
    pub persist_to_disk: bool,
    /// Disk cache directory
    pub cache_directory: Option<String>,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_entries: 1000,
            max_memory_bytes: 100 * 1024 * 1024, // 100 MB
            eviction_policy: EvictionPolicy::LRU,
            enable_compression: true,
            collect_stats: true,
            persist_to_disk: false,
            cache_directory: None,
        }
    }
}

/// Cache statistics
#[derive(Debug, Clone, Default)]
pub struct CacheStats {
    /// Total cache hits
    pub hits: usize,
    /// Total cache misses
    pub misses: usize,
    /// Total evictions
    pub evictions: usize,
    /// Current memory usage
    pub memory_usage_bytes: usize,
    /// Average access time
    pub avg_access_time: Duration,
    /// Cache efficiency ratio
    pub hit_ratio: f64,
}

/// Circuit signature for cache key generation
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct CircuitSignature {
    /// Number of qubits
    pub num_qubits: usize,
    /// Gate sequence hash
    pub gate_sequence_hash: u64,
    /// Parameter hash (for parametrized gates)
    pub parameter_hash: u64,
    /// Compiler options hash
    pub options_hash: u64,
}

/// Generic cache implementation with configurable policies
pub struct CircuitCache<T: Clone> {
    /// Cache entries
    entries: Arc<RwLock<HashMap<u64, CacheEntry<T>>>>,
    /// Access order for LRU
    access_order: Arc<Mutex<VecDeque<u64>>>,
    /// Cache configuration
    config: CacheConfig,
    /// Cache statistics
    stats: Arc<Mutex<CacheStats>>,
    /// Background cleanup thread handle
    cleanup_handle: Option<std::thread::JoinHandle<()>>,
}

impl<T: Clone + Send + Sync + 'static> CircuitCache<T> {
    /// Create a new circuit cache
    #[must_use]
    pub fn new(config: CacheConfig) -> Self {
        Self {
            entries: Arc::new(RwLock::new(HashMap::new())),
            access_order: Arc::new(Mutex::new(VecDeque::new())),
            config,
            stats: Arc::new(Mutex::new(CacheStats::default())),
            cleanup_handle: None,
        }
    }

    /// Create cache with default configuration
    #[must_use]
    pub fn with_default_config() -> Self {
        Self::new(CacheConfig::default())
    }

    /// Get value from cache
    #[must_use]
    pub fn get(&self, key: &CircuitSignature) -> Option<T> {
        let start_time = Instant::now();
        let key_hash = self.hash_signature(key);

        let result = {
            let entries = self
                .entries
                .read()
                .expect("Cache entries lock poisoned - another thread panicked");
            entries.get(&key_hash).map(|entry| entry.value.clone())
        };

        if let Some(value) = &result {
            self.update_access(key_hash);
            if self.config.collect_stats {
                self.update_stats(true, start_time.elapsed());
            }
        } else if self.config.collect_stats {
            self.update_stats(false, start_time.elapsed());
        }

        result
    }

    /// Put value into cache
    pub fn put(&self, key: CircuitSignature, value: T) -> QuantRS2Result<()> {
        let key_hash = self.hash_signature(&key);
        let size_estimate = self.estimate_size(&value);

        // Check if we need to evict entries
        self.ensure_capacity(size_estimate)?;

        let entry = CacheEntry {
            value,
            created_at: SystemTime::now(),
            last_accessed: SystemTime::now(),
            access_count: 1,
            key_hash,
            size_bytes: size_estimate,
        };

        {
            let mut entries = self
                .entries
                .write()
                .expect("Cache entries lock poisoned - another thread panicked");
            entries.insert(key_hash, entry);
        }

        self.update_access(key_hash);
        self.update_memory_usage(size_estimate as isize);

        Ok(())
    }

    /// Remove entry from cache
    #[must_use]
    pub fn remove(&self, key: &CircuitSignature) -> Option<T> {
        let key_hash = self.hash_signature(key);

        let removed = {
            let mut entries = self
                .entries
                .write()
                .expect("Cache entries lock poisoned - another thread panicked");
            entries.remove(&key_hash)
        };

        if let Some(entry) = &removed {
            self.remove_from_access_order(key_hash);
            self.update_memory_usage(-(entry.size_bytes as isize));
        }

        removed.map(|entry| entry.value)
    }

    /// Clear all cache entries
    pub fn clear(&self) {
        {
            let mut entries = self
                .entries
                .write()
                .expect("Cache entries lock poisoned - another thread panicked");
            entries.clear();
        }

        {
            let mut access_order = self
                .access_order
                .lock()
                .expect("Access order lock poisoned - another thread panicked");
            access_order.clear();
        }

        if let Ok(mut stats) = self.stats.lock() {
            stats.memory_usage_bytes = 0;
        }
    }

    /// Get cache statistics
    #[must_use]
    pub fn get_stats(&self) -> CacheStats {
        self.stats
            .lock()
            .expect("Cache stats lock poisoned - another thread panicked")
            .clone()
    }

    /// Get current cache size
    #[must_use]
    pub fn size(&self) -> usize {
        self.entries
            .read()
            .expect("Cache entries lock poisoned - another thread panicked")
            .len()
    }

    /// Check if cache contains key
    #[must_use]
    pub fn contains_key(&self, key: &CircuitSignature) -> bool {
        let key_hash = self.hash_signature(key);
        self.entries
            .read()
            .expect("Cache entries lock poisoned - another thread panicked")
            .contains_key(&key_hash)
    }

    /// Start background cleanup process
    pub fn start_cleanup(&mut self, interval: Duration) {
        let entries = Arc::clone(&self.entries);
        let config = self.config.clone();
        let stats = Arc::clone(&self.stats);

        let handle = std::thread::spawn(move || {
            loop {
                std::thread::sleep(interval);

                if let Ok(mut entries_guard) = entries.write() {
                    let now = SystemTime::now();
                    let mut to_remove = Vec::new();

                    // TTL-based cleanup
                    if let EvictionPolicy::TTL(ttl) = &config.eviction_policy {
                        for (key, entry) in entries_guard.iter() {
                            if let Ok(elapsed) = now.duration_since(entry.created_at) {
                                if elapsed > *ttl {
                                    to_remove.push(*key);
                                }
                            }
                        }

                        for key in to_remove {
                            if let Some(entry) = entries_guard.remove(&key) {
                                if let Ok(mut stats_guard) = stats.lock() {
                                    stats_guard.evictions += 1;
                                    stats_guard.memory_usage_bytes = stats_guard
                                        .memory_usage_bytes
                                        .saturating_sub(entry.size_bytes);
                                }
                            }
                        }
                    }
                }
            }
        });

        self.cleanup_handle = Some(handle);
    }

    /// Hash circuit signature
    fn hash_signature(&self, signature: &CircuitSignature) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        let mut hasher = DefaultHasher::new();
        signature.hash(&mut hasher);
        hasher.finish()
    }

    /// Update access information
    fn update_access(&self, key_hash: u64) {
        // Update last accessed time
        if let Ok(mut entries) = self.entries.write() {
            if let Some(entry) = entries.get_mut(&key_hash) {
                entry.last_accessed = SystemTime::now();
                entry.access_count += 1;
            }
        }

        // Update access order for LRU
        if matches!(self.config.eviction_policy, EvictionPolicy::LRU) {
            let mut access_order = self
                .access_order
                .lock()
                .expect("Access order lock poisoned - another thread panicked");

            // Remove from current position
            access_order.retain(|&x| x != key_hash);

            // Add to front
            access_order.push_front(key_hash);
        }
    }

    /// Remove from access order tracking
    fn remove_from_access_order(&self, key_hash: u64) {
        let mut access_order = self
            .access_order
            .lock()
            .expect("Access order lock poisoned - another thread panicked");
        access_order.retain(|&x| x != key_hash);
    }

    /// Update cache statistics
    fn update_stats(&self, hit: bool, access_time: Duration) {
        if let Ok(mut stats) = self.stats.lock() {
            if hit {
                stats.hits += 1;
            } else {
                stats.misses += 1;
            }

            let total_accesses = stats.hits + stats.misses;
            stats.hit_ratio = stats.hits as f64 / total_accesses as f64;

            // Update average access time (simple moving average)
            let current_avg_nanos = stats.avg_access_time.as_nanos() as f64;
            let new_avg_nanos = current_avg_nanos
                .mul_add((total_accesses - 1) as f64, access_time.as_nanos() as f64)
                / total_accesses as f64;
            stats.avg_access_time = Duration::from_nanos(new_avg_nanos as u64);
        }
    }

    /// Update memory usage statistics
    fn update_memory_usage(&self, delta: isize) {
        if let Ok(mut stats) = self.stats.lock() {
            if delta > 0 {
                stats.memory_usage_bytes = stats.memory_usage_bytes.saturating_add(delta as usize);
            } else {
                stats.memory_usage_bytes =
                    stats.memory_usage_bytes.saturating_sub((-delta) as usize);
            }
        }
    }

    /// Ensure cache has capacity for new entry
    fn ensure_capacity(&self, new_entry_size: usize) -> QuantRS2Result<()> {
        let current_stats = self.get_stats();
        let would_exceed_memory =
            current_stats.memory_usage_bytes + new_entry_size > self.config.max_memory_bytes;
        let would_exceed_count = self.size() >= self.config.max_entries;

        if would_exceed_memory || would_exceed_count {
            self.evict_entries(new_entry_size)?;
        }

        Ok(())
    }

    /// Evict entries based on policy
    fn evict_entries(&self, needed_space: usize) -> QuantRS2Result<()> {
        match &self.config.eviction_policy {
            EvictionPolicy::LRU => self.evict_lru(needed_space),
            EvictionPolicy::LFU => self.evict_lfu(needed_space),
            EvictionPolicy::FIFO => self.evict_fifo(needed_space),
            EvictionPolicy::Random => self.evict_random(needed_space),
            EvictionPolicy::SizeBased => self.evict_size_based(needed_space),
            EvictionPolicy::TTL(_) => Ok(()), // TTL is handled by background cleanup
        }
    }

    /// Evict using LRU policy
    fn evict_lru(&self, needed_space: usize) -> QuantRS2Result<()> {
        let mut freed_space = 0;
        let mut evicted_count = 0;

        while freed_space < needed_space && self.size() > 0 {
            let key_to_evict = {
                let access_order = self
                    .access_order
                    .lock()
                    .expect("Access order lock poisoned - another thread panicked");
                access_order.back().copied()
            };

            if let Some(key) = key_to_evict {
                if let Ok(mut entries) = self.entries.write() {
                    if let Some(entry) = entries.remove(&key) {
                        freed_space += entry.size_bytes;
                        evicted_count += 1;
                        self.remove_from_access_order(key);
                    }
                }
            } else {
                break;
            }
        }

        if let Ok(mut stats) = self.stats.lock() {
            stats.evictions += evicted_count;
            stats.memory_usage_bytes = stats.memory_usage_bytes.saturating_sub(freed_space);
        }

        Ok(())
    }

    /// Evict using LFU policy
    fn evict_lfu(&self, needed_space: usize) -> QuantRS2Result<()> {
        let mut freed_space = 0;
        let mut evicted_count = 0;

        while freed_space < needed_space && self.size() > 0 {
            let key_to_evict = {
                let entries = self
                    .entries
                    .read()
                    .expect("Cache entries lock poisoned - another thread panicked");
                entries
                    .iter()
                    .min_by_key(|(_, entry)| entry.access_count)
                    .map(|(key, _)| *key)
            };

            if let Some(key) = key_to_evict {
                if let Ok(mut entries) = self.entries.write() {
                    if let Some(entry) = entries.remove(&key) {
                        freed_space += entry.size_bytes;
                        evicted_count += 1;
                        self.remove_from_access_order(key);
                    }
                }
            } else {
                break;
            }
        }

        if let Ok(mut stats) = self.stats.lock() {
            stats.evictions += evicted_count;
            stats.memory_usage_bytes = stats.memory_usage_bytes.saturating_sub(freed_space);
        }

        Ok(())
    }

    /// Evict using FIFO policy
    fn evict_fifo(&self, needed_space: usize) -> QuantRS2Result<()> {
        let mut freed_space = 0;
        let mut evicted_count = 0;

        while freed_space < needed_space && self.size() > 0 {
            let key_to_evict = {
                let entries = self
                    .entries
                    .read()
                    .expect("Cache entries lock poisoned - another thread panicked");
                entries
                    .iter()
                    .min_by_key(|(_, entry)| entry.created_at)
                    .map(|(key, _)| *key)
            };

            if let Some(key) = key_to_evict {
                if let Ok(mut entries) = self.entries.write() {
                    if let Some(entry) = entries.remove(&key) {
                        freed_space += entry.size_bytes;
                        evicted_count += 1;
                        self.remove_from_access_order(key);
                    }
                }
            } else {
                break;
            }
        }

        if let Ok(mut stats) = self.stats.lock() {
            stats.evictions += evicted_count;
            stats.memory_usage_bytes = stats.memory_usage_bytes.saturating_sub(freed_space);
        }

        Ok(())
    }

    /// Evict random entries
    fn evict_random(&self, needed_space: usize) -> QuantRS2Result<()> {
        use scirs2_core::random::prelude::*;
        let mut rng = thread_rng();
        let mut freed_space = 0;
        let mut evicted_count = 0;

        while freed_space < needed_space && self.size() > 0 {
            let key_to_evict = {
                let entries = self
                    .entries
                    .read()
                    .expect("Cache entries lock poisoned - another thread panicked");
                let keys: Vec<u64> = entries.keys().copied().collect();
                if keys.is_empty() {
                    None
                } else {
                    let idx = rng.random_range(0..keys.len());
                    Some(keys[idx])
                }
            };

            if let Some(key) = key_to_evict {
                if let Ok(mut entries) = self.entries.write() {
                    if let Some(entry) = entries.remove(&key) {
                        freed_space += entry.size_bytes;
                        evicted_count += 1;
                        self.remove_from_access_order(key);
                    }
                }
            } else {
                break;
            }
        }

        if let Ok(mut stats) = self.stats.lock() {
            stats.evictions += evicted_count;
            stats.memory_usage_bytes = stats.memory_usage_bytes.saturating_sub(freed_space);
        }

        Ok(())
    }

    /// Evict largest entries first
    fn evict_size_based(&self, needed_space: usize) -> QuantRS2Result<()> {
        let mut freed_space = 0;
        let mut evicted_count = 0;

        while freed_space < needed_space && self.size() > 0 {
            let key_to_evict = {
                let entries = self
                    .entries
                    .read()
                    .expect("Cache entries lock poisoned - another thread panicked");
                entries
                    .iter()
                    .max_by_key(|(_, entry)| entry.size_bytes)
                    .map(|(key, _)| *key)
            };

            if let Some(key) = key_to_evict {
                if let Ok(mut entries) = self.entries.write() {
                    if let Some(entry) = entries.remove(&key) {
                        freed_space += entry.size_bytes;
                        evicted_count += 1;
                        self.remove_from_access_order(key);
                    }
                }
            } else {
                break;
            }
        }

        if let Ok(mut stats) = self.stats.lock() {
            stats.evictions += evicted_count;
            stats.memory_usage_bytes = stats.memory_usage_bytes.saturating_sub(freed_space);
        }

        Ok(())
    }

    /// Estimate size of cached value
    const fn estimate_size(&self, _value: &T) -> usize {
        // This is a simplified size estimation
        // In practice, this would use serialization or memory introspection
        std::mem::size_of::<T>() + 1024 // Base overhead estimate
    }
}

/// Specialized cache for compiled circuits
pub type CompiledCircuitCache = CircuitCache<CompiledCircuit>;

/// Specialized cache for execution results
pub type ExecutionResultCache = CircuitCache<ExecutionResult>;

/// Specialized cache for transpilation results
pub type TranspilationCache<const N: usize> = CircuitCache<TranspilationResult<N>>;

/// Circuit signature generator for different circuit types
pub struct SignatureGenerator;

impl SignatureGenerator {
    /// Generate signature for a circuit
    #[must_use]
    pub fn generate_circuit_signature<const N: usize>(
        circuit: &Circuit<N>,
        options_hash: u64,
    ) -> CircuitSignature {
        use std::collections::hash_map::DefaultHasher;

        let mut gate_hasher = DefaultHasher::new();
        let mut param_hasher = DefaultHasher::new();

        // Hash gate sequence
        for gate in circuit.gates() {
            gate.name().hash(&mut gate_hasher);
            for qubit in gate.qubits() {
                qubit.id().hash(&mut gate_hasher);
            }

            // Hash parameters if any (simplified)
            // In practice, this would extract actual gate parameters
            0u64.hash(&mut param_hasher);
        }

        CircuitSignature {
            num_qubits: N,
            gate_sequence_hash: gate_hasher.finish(),
            parameter_hash: param_hasher.finish(),
            options_hash,
        }
    }

    /// Generate signature with compilation options
    #[must_use]
    pub fn generate_with_compilation_options<const N: usize>(
        circuit: &Circuit<N>,
        backend: &str,
        optimization_level: u32,
    ) -> CircuitSignature {
        use std::collections::hash_map::DefaultHasher;

        let mut options_hasher = DefaultHasher::new();
        backend.hash(&mut options_hasher);
        optimization_level.hash(&mut options_hasher);

        Self::generate_circuit_signature(circuit, options_hasher.finish())
    }

    /// Generate signature with transpilation options
    #[must_use]
    pub fn generate_with_transpilation_options<const N: usize>(
        circuit: &Circuit<N>,
        device: &str,
        strategy: &str,
    ) -> CircuitSignature {
        use std::collections::hash_map::DefaultHasher;

        let mut options_hasher = DefaultHasher::new();
        device.hash(&mut options_hasher);
        strategy.hash(&mut options_hasher);

        Self::generate_circuit_signature(circuit, options_hasher.finish())
    }
}

/// High-level cache manager that coordinates different cache types
pub struct CacheManager {
    /// Cache for compiled circuits
    pub compiled_cache: CompiledCircuitCache,
    /// Cache for execution results
    pub execution_cache: ExecutionResultCache,
    /// Global cache configuration
    config: CacheConfig,
}

impl CacheManager {
    /// Create a new cache manager
    #[must_use]
    pub fn new(config: CacheConfig) -> Self {
        Self {
            compiled_cache: CompiledCircuitCache::new(config.clone()),
            execution_cache: ExecutionResultCache::new(config.clone()),
            config,
        }
    }

    /// Create with default configuration
    #[must_use]
    pub fn with_default_config() -> Self {
        Self::new(CacheConfig::default())
    }

    /// Get aggregated cache statistics
    #[must_use]
    pub fn get_aggregated_stats(&self) -> HashMap<String, CacheStats> {
        let mut stats = HashMap::new();
        stats.insert("compiled".to_string(), self.compiled_cache.get_stats());
        stats.insert("execution".to_string(), self.execution_cache.get_stats());
        stats
    }

    /// Clear all caches
    pub fn clear_all(&self) {
        self.compiled_cache.clear();
        self.execution_cache.clear();
    }

    /// Start background cleanup for all caches
    pub fn start_background_cleanup(&mut self, interval: Duration) {
        self.compiled_cache.start_cleanup(interval);
        self.execution_cache.start_cleanup(interval);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use quantrs2_core::gate::single::Hadamard;
    use quantrs2_core::qubit::QubitId;

    #[test]
    fn test_cache_creation() {
        let cache: CircuitCache<String> = CircuitCache::with_default_config();
        assert_eq!(cache.size(), 0);
    }

    #[test]
    fn test_cache_put_get() {
        let cache: CircuitCache<String> = CircuitCache::with_default_config();
        let signature = CircuitSignature {
            num_qubits: 2,
            gate_sequence_hash: 12345,
            parameter_hash: 67890,
            options_hash: 11111,
        };

        cache
            .put(signature.clone(), "test_value".to_string())
            .expect("Failed to put value into cache");
        let result = cache.get(&signature);
        assert_eq!(result, Some("test_value".to_string()));
    }

    #[test]
    fn test_cache_miss() {
        let cache: CircuitCache<String> = CircuitCache::with_default_config();
        let signature = CircuitSignature {
            num_qubits: 2,
            gate_sequence_hash: 12345,
            parameter_hash: 67890,
            options_hash: 11111,
        };

        let result = cache.get(&signature);
        assert_eq!(result, None);
    }

    #[test]
    fn test_signature_generation() {
        let mut circuit = Circuit::<2>::new();
        circuit
            .add_gate(Hadamard { target: QubitId(0) })
            .expect("Failed to add Hadamard gate");

        let signature = SignatureGenerator::generate_circuit_signature(&circuit, 0);
        assert_eq!(signature.num_qubits, 2);
        assert_ne!(signature.gate_sequence_hash, 0);
    }

    #[test]
    fn test_cache_stats() {
        let cache: CircuitCache<String> = CircuitCache::with_default_config();
        let signature = CircuitSignature {
            num_qubits: 2,
            gate_sequence_hash: 12345,
            parameter_hash: 67890,
            options_hash: 11111,
        };

        // Miss
        let _ = cache.get(&signature);

        // Put and hit
        cache
            .put(signature.clone(), "test".to_string())
            .expect("Failed to put value into cache");
        let _ = cache.get(&signature);

        let stats = cache.get_stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.hit_ratio, 0.5);
    }

    #[test]
    fn test_cache_manager() {
        let manager = CacheManager::with_default_config();
        let stats = manager.get_aggregated_stats();
        assert!(stats.contains_key("compiled"));
        assert!(stats.contains_key("execution"));
    }
}