asupersync 0.4.2

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Artifact cache and memory pressure tracking for the lab runtime.
//!
//! Provides memory pressure monitoring and artifact cache management for
//! deterministic lab scenario replay. This module supports NUMA-aware
//! cache pressure projection and artifact lifecycle management.
//!
//! # Key Components
//! - Memory pressure snapshots for lab scenario determinism
//! - Artifact cache with memory-aware eviction policies
//! - NUMA-topology-independent pressure calculations
//! - Deterministic cache behavior for reproducible lab runs

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

const ARTIFACT_HOT_WINDOW_NANOS: u64 = 5 * 60 * 1_000_000_000;
const ARTIFACT_ID_HASH_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const ARTIFACT_ID_HASH_PRIME: u64 = 0x0000_0100_0000_01b3;

fn stable_artifact_id_hash(id: &str) -> u64 {
    id.as_bytes()
        .iter()
        .fold(ARTIFACT_ID_HASH_OFFSET_BASIS, |hash, byte| {
            (hash ^ u64::from(*byte)).wrapping_mul(ARTIFACT_ID_HASH_PRIME)
        })
}

/// Memory pressure snapshot for deterministic lab scenario replay.
///
/// Captures cache state at a specific point in time to enable reproducible
/// memory pressure calculations across different host configurations.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactMemoryPressureSnapshot {
    /// Total bytes currently cached in memory.
    pub resident_bytes: u64,
    /// Maximum memory budget for cached artifacts.
    pub max_resident_bytes: u64,
    /// Memory used by recently accessed artifacts.
    pub hot_resident_bytes: u64,
    /// Memory used by cold/eviction-candidate artifacts.
    pub cold_resident_bytes: u64,
    /// Bytes eligible for spilling to disk.
    pub spill_eligible_bytes: u64,
    /// Bytes cached on remote NUMA nodes.
    pub remote_numa_bytes: u64,
    /// Memory pressure level in basis points (0-10000).
    pub pressure_bps: u16,
    /// True when cache is under high pressure (above threshold).
    pub high_pressure: bool,
    /// Deduplication savings in bytes.
    pub duplicate_bytes_avoided: u64,
    /// Number of cached artifacts.
    pub artifact_count: u32,
}

impl Default for ArtifactMemoryPressureSnapshot {
    fn default() -> Self {
        Self {
            resident_bytes: 0,
            max_resident_bytes: 1024 * 1024 * 1024, // 1GB default budget
            hot_resident_bytes: 0,
            cold_resident_bytes: 0,
            spill_eligible_bytes: 0,
            remote_numa_bytes: 0,
            pressure_bps: 0,
            high_pressure: false,
            duplicate_bytes_avoided: 0,
            artifact_count: 0,
        }
    }
}

impl ArtifactMemoryPressureSnapshot {
    /// Create a snapshot with current time.
    #[must_use]
    pub fn now() -> Self {
        Self::default()
    }

    /// Get pressure level as a floating-point ratio (0.0 to 1.0).
    #[must_use]
    pub fn pressure_ratio(&self) -> f64 {
        f64::from(self.pressure_bps) / 10_000.0
    }

    /// Calculate memory utilization ratio (0.0 to 1.0).
    #[must_use]
    pub fn utilization_ratio(&self) -> f64 {
        if self.max_resident_bytes == 0 {
            0.0
        } else {
            self.resident_bytes as f64 / self.max_resident_bytes as f64
        }
    }

    /// Check if cache is under memory pressure (above threshold).
    #[must_use]
    pub const fn is_under_pressure(&self) -> bool {
        self.high_pressure
    }
}

/// Configuration for the artifact cache.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactCacheConfig {
    /// Maximum memory budget for cached artifacts.
    pub max_cache_size_bytes: u64,
    /// Threshold for triggering eviction (as ratio of max_cache_size).
    pub eviction_threshold_ratio: u32, // Fixed-point: divide by 10000
    /// Time-to-live for cached artifacts in seconds.
    pub default_ttl_secs: u64,
    /// Maximum number of artifacts to cache.
    pub max_artifact_count: u32,
    /// Enable NUMA-aware caching hints.
    pub numa_aware: bool,
    /// Eviction policy configuration.
    pub eviction_policy: EvictionPolicy,
}

impl Default for ArtifactCacheConfig {
    fn default() -> Self {
        Self {
            max_cache_size_bytes: 1024 * 1024 * 1024, // 1GB
            eviction_threshold_ratio: 7500,           // 75%
            default_ttl_secs: 3600,                   // 1 hour
            max_artifact_count: 10_000,
            numa_aware: true,
            eviction_policy: EvictionPolicy::LruWithTtl,
        }
    }
}

/// Cache eviction policies for artifact management.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EvictionPolicy {
    /// Least Recently Used with TTL expiration.
    LruWithTtl,
    /// Most Recently Used (for specific workload patterns).
    Mru,
    /// Size-based eviction (largest artifacts first).
    LargestFirst,
    /// Random eviction for testing purposes.
    Random,
}

/// Metadata for a cached artifact.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactMetadata {
    /// Unique identifier for the artifact.
    pub id: String,
    /// Size of the artifact in bytes.
    pub size_bytes: u64,
    /// When the artifact was first cached.
    pub cached_at_nanos: u64,
    /// When the artifact was last accessed.
    pub last_accessed_nanos: u64,
    /// Number of times this artifact has been accessed.
    pub access_count: u32,
    /// TTL expiration time.
    pub expires_at_nanos: u64,
    /// NUMA node affinity hint (if applicable).
    pub numa_node_hint: Option<u8>,
    /// Priority for eviction decisions (higher = keep longer).
    pub priority: u8,
}

/// Statistics for cache performance monitoring.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CacheStatistics {
    /// Total cache hits since creation.
    pub total_hits: u64,
    /// Total cache misses since creation.
    pub total_misses: u64,
    /// Total evictions since creation.
    pub total_evictions: u64,
    /// Total artifacts stored since creation.
    pub total_stored: u64,
    /// Current cache hit rate in basis points.
    pub current_hit_rate_bps: u16,
    /// Average artifact access time in nanoseconds.
    pub avg_access_time_nanos: u64,
    /// Peak memory usage achieved.
    pub peak_memory_bytes: u64,
}

/// In-memory artifact cache implementation.
///
/// This is a simple implementation suitable for lab scenarios and testing.
/// Production usage would typically integrate with more sophisticated cache
/// backends and persistence layers.
#[derive(Debug)]
pub struct ArtifactCache {
    /// Cache configuration.
    config: ArtifactCacheConfig,
    /// Cached artifact metadata.
    metadata: HashMap<String, ArtifactMetadata>,
    /// Cached artifact data.
    data: HashMap<String, Vec<u8>>,
    /// Performance statistics.
    statistics: CacheStatistics,
    /// Current total size of cached artifacts.
    current_size_bytes: u64,
}

impl ArtifactCache {
    /// Create a new artifact cache with the given configuration.
    #[must_use]
    pub fn new(config: ArtifactCacheConfig) -> Self {
        Self {
            config,
            metadata: HashMap::new(),
            data: HashMap::new(),
            statistics: CacheStatistics::default(),
            current_size_bytes: 0,
        }
    }

    /// Create a cache with default configuration.
    #[must_use]
    pub fn default_config() -> Self {
        Self::new(ArtifactCacheConfig::default())
    }

    /// Take a memory pressure snapshot of the current cache state.
    ///
    /// `now_nanos` must use the same clock domain as timestamps supplied to
    /// [`Self::put`], [`Self::get`], and [`Self::invalidate_expired`]. Keeping
    /// the clock explicit makes lab replay deterministic and prevents Unix
    /// timestamps from being compared with process-relative monotonic time.
    #[must_use]
    pub fn memory_pressure_snapshot(&self, now_nanos: u64) -> ArtifactMemoryPressureSnapshot {
        // Calculate hot vs cold set sizes
        let threshold_nanos = now_nanos.saturating_sub(ARTIFACT_HOT_WINDOW_NANOS);
        let (hot_bytes, cold_bytes) = self.metadata.values().fold((0u64, 0u64), |acc, meta| {
            if meta.last_accessed_nanos >= threshold_nanos {
                (acc.0.saturating_add(meta.size_bytes), acc.1)
            } else {
                (acc.0, acc.1.saturating_add(meta.size_bytes))
            }
        });

        // Calculate pressure level in basis points
        let utilization = if self.config.max_cache_size_bytes == 0 {
            0.0
        } else {
            self.current_size_bytes as f64 / self.config.max_cache_size_bytes as f64
        };
        let pressure_bps = (utilization * 10_000.0).min(10_000.0) as u16;
        let high_pressure = pressure_bps >= 7_500; // 75% threshold

        // Calculate spill-eligible bytes (cold bytes that can be evicted)
        let spill_eligible_bytes = cold_bytes.min(self.current_size_bytes / 2);

        ArtifactMemoryPressureSnapshot {
            resident_bytes: self.current_size_bytes,
            max_resident_bytes: self.config.max_cache_size_bytes,
            hot_resident_bytes: hot_bytes,
            cold_resident_bytes: cold_bytes,
            spill_eligible_bytes,
            remote_numa_bytes: 0, // Would need NUMA topology detection
            pressure_bps,
            high_pressure,
            duplicate_bytes_avoided: 0, // Would need dedup tracking
            artifact_count: u32::try_from(self.metadata.len()).unwrap_or(u32::MAX),
        }
    }

    /// Check if an artifact is cached.
    #[must_use]
    pub fn contains(&self, id: &str) -> bool {
        self.metadata.contains_key(id)
    }

    /// Get current cache statistics.
    #[must_use]
    pub const fn statistics(&self) -> &CacheStatistics {
        &self.statistics
    }

    /// Get current cache configuration.
    #[must_use]
    pub const fn config(&self) -> &ArtifactCacheConfig {
        &self.config
    }

    /// Get the current number of cached artifacts.
    #[must_use]
    pub fn len(&self) -> usize {
        self.metadata.len()
    }

    /// Check if the cache is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.metadata.is_empty()
    }

    /// Get the current total size of cached artifacts.
    #[must_use]
    pub const fn current_size_bytes(&self) -> u64 {
        self.current_size_bytes
    }

    /// Retrieve a cached artifact by ID at `now_nanos` in the cache clock domain.
    /// Returns None if the artifact is not cached or has expired.
    pub fn get(&mut self, id: &str, now_nanos: u64) -> Option<&[u8]> {
        // Check if artifact exists and hasn't expired
        if let Some(meta) = self.metadata.get_mut(id) {
            if meta.expires_at_nanos > now_nanos {
                // Update access statistics
                meta.last_accessed_nanos = now_nanos;
                meta.access_count = meta.access_count.saturating_add(1);
                self.statistics.total_hits = self.statistics.total_hits.saturating_add(1);

                // Return cached data
                self.data.get(id).map(|v| v.as_slice())
            } else {
                // Expired - remove from cache
                self.remove_expired(id);
                self.statistics.total_misses = self.statistics.total_misses.saturating_add(1);
                None
            }
        } else {
            self.statistics.total_misses = self.statistics.total_misses.saturating_add(1);
            None
        }
    }

    /// Store an artifact at `now_nanos` in the cache clock domain.
    /// Returns true if successfully cached, false if eviction failed to make space.
    pub fn put(&mut self, id: String, data: Vec<u8>, now_nanos: u64) -> bool {
        let artifact_size = data.len() as u64;

        // Reject impossible admissions before expiry cleanup or eviction so a
        // failed put cannot destroy otherwise valid cached artifacts.
        if artifact_size > self.config.max_cache_size_bytes || self.config.max_artifact_count == 0 {
            return false;
        }
        // Reclaim expired entries and the prior value before calculating byte
        // capacity. A replacement consumes only its net post-removal size; using
        // the full incoming size while the old value is still resident can evict
        // unrelated artifacts even when the replacement fits exactly.
        self.invalidate_expired(now_nanos);
        self.remove_internal(&id);

        // Check if we need to evict to make space
        if !self.ensure_capacity_for(artifact_size) {
            return false;
        }

        // Create metadata
        let metadata = ArtifactMetadata {
            id: id.clone(),
            size_bytes: artifact_size,
            cached_at_nanos: now_nanos,
            last_accessed_nanos: now_nanos,
            access_count: 0,
            expires_at_nanos: now_nanos
                .saturating_add(self.config.default_ttl_secs.saturating_mul(1_000_000_000)),
            numa_node_hint: None, // Could be enhanced with NUMA detection
            priority: 128,        // Default priority
        };

        // Store data and metadata
        self.data.insert(id.clone(), data);
        self.metadata.insert(id, metadata);
        self.current_size_bytes += artifact_size;
        self.statistics.total_stored = self.statistics.total_stored.saturating_add(1);

        true
    }

    /// Remove a specific artifact from the cache.
    /// Returns true if the artifact was removed, false if it didn't exist.
    pub fn remove(&mut self, id: &str) -> bool {
        self.remove_internal(id)
    }

    /// Evict artifacts based on the configured eviction policy.
    /// Returns the number of artifacts evicted.
    pub fn evict(&mut self, target_bytes: u64) -> u32 {
        self.evict_for_capacity(target_bytes, 0)
    }

    /// Evict until both byte and artifact-count targets have been satisfied.
    fn evict_for_capacity(&mut self, target_bytes: u64, target_artifacts: usize) -> u32 {
        let mut evicted_count = 0usize;
        let mut evicted_bytes = 0u64;

        // Collect eviction candidates based on policy - clone to avoid borrow checker issues
        let mut candidates: Vec<_> = self
            .metadata
            .iter()
            .map(|(id, meta)| (id.clone(), meta.clone(), stable_artifact_id_hash(id)))
            .collect();

        match self.config.eviction_policy {
            EvictionPolicy::LruWithTtl => {
                // Sort by last accessed time (oldest first), then by ID so
                // equal timestamps remain deterministic across hash seeds.
                candidates.sort_by(|(left_id, left_meta, _), (right_id, right_meta, _)| {
                    left_meta
                        .last_accessed_nanos
                        .cmp(&right_meta.last_accessed_nanos)
                        .then_with(|| left_id.cmp(right_id))
                });
            }
            EvictionPolicy::Mru => {
                // Sort by last accessed time (newest first), then by ID.
                candidates.sort_by(|(left_id, left_meta, _), (right_id, right_meta, _)| {
                    right_meta
                        .last_accessed_nanos
                        .cmp(&left_meta.last_accessed_nanos)
                        .then_with(|| left_id.cmp(right_id))
                });
            }
            EvictionPolicy::LargestFirst => {
                // Sort by size (largest first), then by ID.
                candidates.sort_by(|(left_id, left_meta, _), (right_id, right_meta, _)| {
                    right_meta
                        .size_bytes
                        .cmp(&left_meta.size_bytes)
                        .then_with(|| left_id.cmp(right_id))
                });
            }
            EvictionPolicy::Random => {
                // Use a stable full-ID hash for reproducible pseudo-random
                // ordering, with the ID itself as a total collision tie-break.
                candidates.sort_by(|(left_id, _, left_hash), (right_id, _, right_hash)| {
                    left_hash
                        .cmp(right_hash)
                        .then_with(|| left_id.cmp(right_id))
                });
            }
        }

        // Evict until we've freed enough space
        for (id, meta, _) in candidates {
            if evicted_bytes >= target_bytes && evicted_count >= target_artifacts {
                break;
            }

            evicted_bytes = evicted_bytes.saturating_add(meta.size_bytes);
            self.remove_internal(&id);
            evicted_count = evicted_count.saturating_add(1);
        }

        self.statistics.total_evictions = self
            .statistics
            .total_evictions
            .saturating_add(u64::try_from(evicted_count).unwrap_or(u64::MAX));
        u32::try_from(evicted_count).unwrap_or(u32::MAX)
    }

    /// Remove all expired artifacts from the cache.
    /// Returns the number of artifacts invalidated.
    pub fn invalidate_expired(&mut self, now_nanos: u64) -> u32 {
        let mut invalidated_count = 0;

        // Collect expired artifact IDs
        let expired_ids: Vec<String> = self
            .metadata
            .iter()
            .filter_map(|(id, meta)| {
                if meta.expires_at_nanos <= now_nanos {
                    Some(id.clone())
                } else {
                    None
                }
            })
            .collect();

        // Remove expired artifacts
        for id in expired_ids {
            self.remove_internal(&id);
            invalidated_count += 1;
        }

        invalidated_count
    }

    /// Clear all artifacts from the cache.
    pub fn clear(&mut self) {
        self.metadata.clear();
        self.data.clear();
        self.current_size_bytes = 0;
    }

    /// Internal helper to remove an artifact and update statistics.
    fn remove_internal(&mut self, id: &str) -> bool {
        if let Some(meta) = self.metadata.remove(id) {
            self.data.remove(id);
            self.current_size_bytes = self.current_size_bytes.saturating_sub(meta.size_bytes);
            true
        } else {
            false
        }
    }

    /// Remove a specific expired artifact.
    fn remove_expired(&mut self, id: &str) {
        self.remove_internal(id);
    }

    /// Ensure there's capacity for a new artifact of the given size.
    fn ensure_capacity_for(&mut self, needed_bytes: u64) -> bool {
        // The caller removes a same-ID predecessor before reaching this point,
        // so replacements consume the vacated slot while new IDs may need a
        // count-based eviction.
        let max_artifact_count =
            usize::try_from(self.config.max_artifact_count).unwrap_or(usize::MAX);
        let artifacts_to_free = self
            .metadata
            .len()
            .saturating_add(1)
            .saturating_sub(max_artifact_count);

        // Check if we have enough byte and artifact slots now.
        let available_bytes = self
            .config
            .max_cache_size_bytes
            .saturating_sub(self.current_size_bytes);
        if available_bytes >= needed_bytes && artifacts_to_free == 0 {
            return true;
        }

        // Need to evict enough items to satisfy both bounds.
        let bytes_to_free = needed_bytes.saturating_sub(available_bytes);
        let target_eviction = if bytes_to_free == 0 {
            0
        } else {
            let eviction_threshold = u64::try_from(
                (u128::from(self.config.max_cache_size_bytes)
                    * u128::from(self.config.eviction_threshold_ratio))
                    / 10_000,
            )
            .unwrap_or(u64::MAX);

            // If we're above eviction threshold, be more aggressive.
            if self.current_size_bytes > eviction_threshold {
                bytes_to_free.saturating_add(self.current_size_bytes / 4)
            } else {
                bytes_to_free
            }
        };

        self.evict_for_capacity(target_eviction, artifacts_to_free);

        // Check if we now have enough space under both configured limits.
        let final_available = self
            .config
            .max_cache_size_bytes
            .saturating_sub(self.current_size_bytes);
        final_available >= needed_bytes && self.metadata.len() < max_artifact_count
    }
}

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

    const TEST_NOW_NANOS: u64 = 1_000_000_000_000;

    #[test]
    fn artifact_memory_pressure_snapshot_default() {
        let snapshot = ArtifactMemoryPressureSnapshot::default();
        assert_eq!(snapshot.resident_bytes, 0);
        assert_eq!(snapshot.artifact_count, 0);
        assert_eq!(snapshot.pressure_bps, 0);
        assert!(!snapshot.is_under_pressure());
        assert_eq!(snapshot.pressure_ratio(), 0.0);
        assert_eq!(snapshot.utilization_ratio(), 0.0);
    }

    #[test]
    fn artifact_memory_pressure_snapshot_calculations() {
        let mut snapshot = ArtifactMemoryPressureSnapshot::default();
        snapshot.pressure_bps = 7500; // 75%
        snapshot.resident_bytes = 512 * 1024 * 1024; // 512MiB
        snapshot.max_resident_bytes = 1024 * 1024 * 1024; // 1GiB
        snapshot.high_pressure = true;

        assert_eq!(snapshot.pressure_ratio(), 0.75);
        assert_eq!(snapshot.utilization_ratio(), 0.5);
        assert!(snapshot.is_under_pressure()); // At threshold
    }

    #[test]
    fn artifact_cache_creation() {
        let config = ArtifactCacheConfig::default();
        let cache = ArtifactCache::new(config);

        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.current_size_bytes(), 0);
    }

    #[test]
    fn artifact_cache_put_and_get() {
        let mut cache = ArtifactCache::default_config();
        let test_data = b"test artifact data".to_vec();
        let test_id = "test-artifact-1".to_string();

        // Put artifact
        assert!(cache.put(test_id.clone(), test_data.clone(), TEST_NOW_NANOS));
        assert_eq!(cache.len(), 1);
        assert_eq!(cache.current_size_bytes(), test_data.len() as u64);
        assert!(cache.contains(&test_id));

        // Get artifact
        let retrieved = cache.get(&test_id, TEST_NOW_NANOS);
        assert!(retrieved.is_some());
        assert_eq!(
            retrieved.expect("cache should contain stored artifact"),
            test_data.as_slice()
        );

        // Verify access count increased
        let stats = cache.statistics();
        assert_eq!(stats.total_hits, 1);
        assert_eq!(stats.total_misses, 0);
        assert_eq!(stats.total_stored, 1);
    }

    #[test]
    fn artifact_cache_remove() {
        let mut cache = ArtifactCache::default_config();
        let test_data = b"test data".to_vec();
        let test_id = "test-id".to_string();

        // Put and then remove
        cache.put(test_id.clone(), test_data, TEST_NOW_NANOS);
        assert!(cache.contains(&test_id));
        assert!(cache.remove(&test_id));
        assert!(!cache.contains(&test_id));
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.current_size_bytes(), 0);

        // Removing non-existent artifact should return false
        assert!(!cache.remove("non-existent"));
    }

    #[test]
    fn artifact_cache_eviction() {
        let config = ArtifactCacheConfig {
            max_cache_size_bytes: 100,      // Small cache for testing
            eviction_threshold_ratio: 5000, // 50%
            ..ArtifactCacheConfig::default()
        };
        let mut cache = ArtifactCache::new(config);

        // Fill cache beyond capacity
        cache.put("item1".to_string(), vec![0u8; 40], TEST_NOW_NANOS);
        cache.put("item2".to_string(), vec![1u8; 40], TEST_NOW_NANOS);
        cache.put("item3".to_string(), vec![2u8; 40], TEST_NOW_NANOS); // This should trigger eviction

        // Should have evicted some items to stay under capacity
        assert!(cache.current_size_bytes() <= 100);
        assert!(cache.len() <= 2); // At least one item should be evicted
    }

    #[test]
    fn artifact_cache_replacement_at_capacity_preserves_peer() {
        let config = ArtifactCacheConfig {
            max_cache_size_bytes: 100,
            eviction_threshold_ratio: 7500,
            eviction_policy: EvictionPolicy::LargestFirst,
            ..ArtifactCacheConfig::default()
        };
        let mut cache = ArtifactCache::new(config);

        assert!(cache.put("replace".to_string(), vec![1; 50], TEST_NOW_NANOS));
        assert!(cache.put("peer".to_string(), vec![2; 50], TEST_NOW_NANOS));
        assert_eq!(cache.current_size_bytes(), 100);
        assert!(cache.put("replace".to_string(), vec![3; 50], TEST_NOW_NANOS));

        assert_eq!(cache.len(), 2);
        assert_eq!(cache.current_size_bytes(), 100);
        assert_eq!(
            cache.data.get("replace").map(Vec::as_slice),
            Some(&[3; 50][..])
        );
        assert_eq!(
            cache.data.get("peer").map(Vec::as_slice),
            Some(&[2; 50][..])
        );
        assert_eq!(cache.statistics().total_evictions, 0);
    }

    #[test]
    fn artifact_cache_oversized_put_preserves_existing_entries() {
        let config = ArtifactCacheConfig {
            max_cache_size_bytes: 100,
            eviction_policy: EvictionPolicy::LargestFirst,
            ..ArtifactCacheConfig::default()
        };
        let mut cache = ArtifactCache::new(config);

        assert!(cache.put("replace".to_string(), vec![1; 40], TEST_NOW_NANOS));
        assert!(cache.put("peer".to_string(), vec![2; 50], TEST_NOW_NANOS));

        assert!(!cache.put("oversized".to_string(), vec![3; 101], TEST_NOW_NANOS));
        assert!(!cache.put("replace".to_string(), vec![4; 101], TEST_NOW_NANOS));

        assert_eq!(cache.len(), 2);
        assert_eq!(cache.current_size_bytes(), 90);
        assert_eq!(
            cache.data.get("replace").map(Vec::as_slice),
            Some(&[1; 40][..])
        );
        assert_eq!(
            cache.data.get("peer").map(Vec::as_slice),
            Some(&[2; 50][..])
        );
        assert!(!cache.contains("oversized"));
        assert_eq!(cache.statistics().total_evictions, 0);
        assert_eq!(cache.statistics().total_stored, 2);
    }

    #[test]
    fn artifact_cache_clear() {
        let mut cache = ArtifactCache::default_config();

        // Add some artifacts
        cache.put("item1".to_string(), vec![0u8; 10], TEST_NOW_NANOS);
        cache.put("item2".to_string(), vec![1u8; 20], TEST_NOW_NANOS);

        assert_eq!(cache.len(), 2);
        assert_eq!(cache.current_size_bytes(), 30);

        // Clear cache
        cache.clear();
        assert!(cache.is_empty());
        assert_eq!(cache.current_size_bytes(), 0);
    }

    #[test]
    fn artifact_cache_miss() {
        let mut cache = ArtifactCache::default_config();

        // Get non-existent artifact
        let result = cache.get("non-existent", TEST_NOW_NANOS);
        assert!(result.is_none());

        let stats = cache.statistics();
        assert_eq!(stats.total_misses, 1);
        assert_eq!(stats.total_hits, 0);
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.current_size_bytes(), 0);
        assert!(!cache.contains("test"));
    }

    #[test]
    fn artifact_cache_memory_pressure_snapshot() {
        let cache = ArtifactCache::default_config();
        let snapshot = cache.memory_pressure_snapshot(TEST_NOW_NANOS);

        assert_eq!(snapshot.resident_bytes, 0);
        assert_eq!(snapshot.artifact_count, 0);
        assert_eq!(snapshot.pressure_bps, 0);
        assert_eq!(snapshot.hot_resident_bytes, 0);
        assert_eq!(snapshot.cold_resident_bytes, 0);
    }

    #[test]
    fn artifact_cache_snapshot_classifies_hot_cold_and_spill_in_one_clock_domain() {
        let config = ArtifactCacheConfig {
            max_cache_size_bytes: 200,
            ..ArtifactCacheConfig::default()
        };
        let mut cache = ArtifactCache::new(config);
        let cold_time = TEST_NOW_NANOS - ARTIFACT_HOT_WINDOW_NANOS - 1;

        assert!(cache.put("cold".to_string(), vec![0; 40], cold_time));
        assert!(cache.put("hot".to_string(), vec![1; 60], TEST_NOW_NANOS));

        let snapshot = cache.memory_pressure_snapshot(TEST_NOW_NANOS);
        assert_eq!(snapshot.resident_bytes, 100);
        assert_eq!(snapshot.hot_resident_bytes, 60);
        assert_eq!(snapshot.cold_resident_bytes, 40);
        assert_eq!(snapshot.spill_eligible_bytes, 40);
        assert_eq!(snapshot.pressure_bps, 5_000);
        assert_eq!(snapshot.artifact_count, 2);
    }

    #[test]
    fn artifact_cache_snapshot_boundary_and_access_refresh_are_deterministic() {
        let mut cache = ArtifactCache::default_config();
        let boundary_time = TEST_NOW_NANOS - ARTIFACT_HOT_WINDOW_NANOS;

        assert!(cache.put("boundary".to_string(), vec![0; 10], boundary_time));
        assert!(cache.put("older".to_string(), vec![1; 20], boundary_time - 1));

        let before = cache.memory_pressure_snapshot(TEST_NOW_NANOS);
        assert_eq!(before.hot_resident_bytes, 10);
        assert_eq!(before.cold_resident_bytes, 20);
        assert_eq!(
            cache.memory_pressure_snapshot(TEST_NOW_NANOS),
            before,
            "an unchanged explicit clock must produce an identical snapshot"
        );

        assert_eq!(cache.get("older", TEST_NOW_NANOS), Some(&[1; 20][..]));
        let after = cache.memory_pressure_snapshot(TEST_NOW_NANOS);
        assert_eq!(after.hot_resident_bytes, 30);
        assert_eq!(after.cold_resident_bytes, 0);
        assert_eq!(after.spill_eligible_bytes, 0);

        let mut zero_clock_cache = ArtifactCache::default_config();
        assert!(zero_clock_cache.put("zero".to_string(), vec![2; 7], 0));
        let zero_snapshot = zero_clock_cache.memory_pressure_snapshot(0);
        assert_eq!(zero_snapshot.hot_resident_bytes, 7);
        assert_eq!(zero_snapshot.cold_resident_bytes, 0);
    }

    #[test]
    fn artifact_cache_expiry_uses_the_explicit_clock_domain() {
        let config = ArtifactCacheConfig {
            default_ttl_secs: 1,
            ..ArtifactCacheConfig::default()
        };
        let mut cache = ArtifactCache::new(config);
        let inserted_at = 5;
        let expires_at = inserted_at + 1_000_000_000;

        assert!(cache.put("ttl".to_string(), vec![3; 4], inserted_at));
        assert_eq!(cache.get("ttl", expires_at - 1), Some(&[3; 4][..]));
        assert_eq!(cache.get("ttl", expires_at), None);
        assert!(!cache.contains("ttl"));
    }

    #[test]
    fn eviction_policy_serialization() {
        let policies = [
            EvictionPolicy::LruWithTtl,
            EvictionPolicy::Mru,
            EvictionPolicy::LargestFirst,
            EvictionPolicy::Random,
        ];

        for policy in &policies {
            let serialized =
                serde_json::to_string(policy).expect("eviction policy should serialize to JSON");
            let deserialized: EvictionPolicy = serde_json::from_str(&serialized)
                .expect("serialized policy should deserialize from JSON");
            assert_eq!(*policy, deserialized);
        }
    }

    #[test]
    fn cache_config_default_values() {
        let config = ArtifactCacheConfig::default();
        assert_eq!(config.max_cache_size_bytes, 1024 * 1024 * 1024);
        assert_eq!(config.eviction_threshold_ratio, 7500);
        assert_eq!(config.default_ttl_secs, 3600);
        assert_eq!(config.max_artifact_count, 10_000);
        assert!(config.numa_aware);
        assert_eq!(config.eviction_policy, EvictionPolicy::LruWithTtl);
    }
}