oxirs-core 0.2.2

Core RDF and SPARQL functionality for OxiRS - native Rust implementation with zero dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! Query plan caching for improved performance
//!
//! This module provides an LRU cache for compiled query plans with persistence support.

use crate::query::plan::ExecutionPlan;
use crate::OxirsError;
use lru::LruCache;
use scirs2_core::metrics::Counter;
use serde::{Deserialize, Serialize};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::num::NonZeroUsize;
use std::path::Path;
use std::sync::{Arc, RwLock};
use std::time::Instant;

/// Query plan cache with LRU eviction
///
/// Caches compiled execution plans to avoid repeated query compilation
/// and optimization overhead.
///
/// This is the full-featured LRU implementation backed by the `lru` crate and
/// SciRS2 metrics.  For a simpler, self-contained cache see [`QueryPlanCache`] below.
pub struct LruQueryPlanCache {
    /// LRU cache for execution plans
    cache: Arc<RwLock<LruCache<u64, CachedPlan>>>,
    /// Cache statistics
    stats: Arc<RwLock<CacheStatistics>>,
    /// Metrics counters
    hit_counter: Counter,
    miss_counter: Counter,
    eviction_counter: Counter,
    /// Cache configuration
    config: CacheConfig,
}

/// Cached execution plan with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedPlan {
    /// The compiled execution plan
    pub plan: SerializablePlan,
    /// Query signature (hash)
    pub signature: u64,
    /// When the plan was cached
    pub cached_at_ms: u128,
    /// How many times this plan was accessed
    pub access_count: u64,
    /// Last access time
    pub last_accessed_ms: u128,
    /// Estimated execution cost
    pub estimated_cost: f64,
    /// Average actual execution time (milliseconds)
    pub avg_execution_time_ms: f64,
}

/// Serializable representation of execution plan
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SerializablePlan {
    /// Triple scan operation
    TripleScan { pattern_desc: String },
    /// Hash join operation
    HashJoin {
        left: Box<SerializablePlan>,
        right: Box<SerializablePlan>,
        join_vars: Vec<String>,
    },
    /// Filter operation
    Filter {
        input: Box<SerializablePlan>,
        expr_desc: String,
    },
    /// Projection operation
    Project {
        input: Box<SerializablePlan>,
        variables: Vec<String>,
    },
    /// Union operation
    Union {
        left: Box<SerializablePlan>,
        right: Box<SerializablePlan>,
    },
    /// Empty plan
    Empty,
}

/// Cache configuration
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// Maximum number of cached plans
    pub max_size: usize,
    /// Enable persistence to disk
    pub enable_persistence: bool,
    /// Path for persisted cache
    pub persistence_path: Option<String>,
    /// Time-to-live for cached plans (milliseconds)
    pub ttl_ms: Option<u128>,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_size: 1000,
            enable_persistence: false,
            persistence_path: None,
            ttl_ms: Some(3_600_000), // 1 hour
        }
    }
}

/// Cache statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CacheStatistics {
    /// Total cache hits
    pub hits: u64,
    /// Total cache misses
    pub misses: u64,
    /// Total evictions
    pub evictions: u64,
    /// Current cache size
    pub current_size: usize,
    /// Total plans cached
    pub total_cached: u64,
}

impl LruQueryPlanCache {
    /// Create a new query plan cache
    pub fn new(config: CacheConfig) -> Self {
        let capacity = NonZeroUsize::new(config.max_size)
            .unwrap_or(NonZeroUsize::new(1000).expect("1000 is non-zero"));

        Self {
            cache: Arc::new(RwLock::new(LruCache::new(capacity))),
            stats: Arc::new(RwLock::new(CacheStatistics::default())),
            hit_counter: Counter::new("plan_cache.hits".to_string()),
            miss_counter: Counter::new("plan_cache.misses".to_string()),
            eviction_counter: Counter::new("plan_cache.evictions".to_string()),
            config,
        }
    }

    /// Get a cached plan for a query string
    pub fn get(&self, query: &str) -> Option<CachedPlan> {
        let signature = Self::compute_signature(query);

        let start = Instant::now();

        let result = {
            let mut cache = self.cache.write().ok()?;
            cache.get_mut(&signature).cloned()
        };

        let _elapsed = start.elapsed(); // Track elapsed time for future use

        if let Some(mut plan) = result {
            // Update access metrics
            plan.access_count += 1;
            plan.last_accessed_ms = Instant::now().elapsed().as_millis();

            // Check TTL
            if let Some(ttl) = self.config.ttl_ms {
                let age = plan.last_accessed_ms - plan.cached_at_ms;
                if age > ttl {
                    // Expired, remove from cache
                    self.remove(query);
                    self.record_miss();
                    return None;
                }
            }

            // Update cache with new access info
            if let Ok(mut cache) = self.cache.write() {
                cache.put(signature, plan.clone());
            }

            self.record_hit();
            Some(plan)
        } else {
            self.record_miss();
            None
        }
    }

    /// Put a compiled plan into the cache
    pub fn put(
        &self,
        query: &str,
        plan: ExecutionPlan,
        estimated_cost: f64,
    ) -> Result<(), OxirsError> {
        let signature = Self::compute_signature(query);
        let serializable = Self::convert_to_serializable(&plan);

        let cached_plan = CachedPlan {
            plan: serializable,
            signature,
            cached_at_ms: Instant::now().elapsed().as_millis(),
            access_count: 0,
            last_accessed_ms: Instant::now().elapsed().as_millis(),
            estimated_cost,
            avg_execution_time_ms: 0.0,
        };

        let mut cache = self
            .cache
            .write()
            .map_err(|e| OxirsError::Query(format!("Failed to write cache: {}", e)))?;

        // Check if we're evicting an entry
        let will_evict = cache.len() >= cache.cap().get();
        if will_evict {
            self.record_eviction();
        }

        cache.put(signature, cached_plan);

        // Update statistics
        let mut stats = self
            .stats
            .write()
            .map_err(|e| OxirsError::Query(format!("Failed to write stats: {}", e)))?;
        stats.current_size = cache.len();
        stats.total_cached += 1;

        Ok(())
    }

    /// Remove a cached plan
    pub fn remove(&self, query: &str) -> Option<CachedPlan> {
        let signature = Self::compute_signature(query);

        self.cache.write().ok()?.pop(&signature)
    }

    /// Clear all cached plans
    pub fn clear(&self) -> Result<(), OxirsError> {
        let mut cache = self
            .cache
            .write()
            .map_err(|e| OxirsError::Query(format!("Failed to write cache: {}", e)))?;
        cache.clear();

        let mut stats = self
            .stats
            .write()
            .map_err(|e| OxirsError::Query(format!("Failed to write stats: {}", e)))?;
        stats.current_size = 0;

        Ok(())
    }

    /// Get cache statistics
    pub fn statistics(&self) -> CacheStatistics {
        self.stats
            .read()
            .ok()
            .map(|s| s.clone())
            .unwrap_or_default()
    }

    /// Get cache hit rate
    pub fn hit_rate(&self) -> f64 {
        let stats = self.statistics();
        let total = stats.hits + stats.misses;
        if total == 0 {
            return 0.0;
        }
        stats.hits as f64 / total as f64
    }

    /// Persist cache to disk
    pub fn persist(&self) -> Result<(), OxirsError> {
        if !self.config.enable_persistence {
            return Ok(());
        }

        let path = self
            .config
            .persistence_path
            .as_ref()
            .ok_or_else(|| OxirsError::Io("No persistence path configured".to_string()))?;

        let cache = self
            .cache
            .read()
            .map_err(|e| OxirsError::Query(format!("Failed to read cache: {}", e)))?;

        // Convert cache to serializable format
        let entries: Vec<(u64, CachedPlan)> = cache.iter().map(|(k, v)| (*k, v.clone())).collect();

        let json = serde_json::to_string_pretty(&entries)
            .map_err(|e| OxirsError::Serialize(e.to_string()))?;

        std::fs::write(path, json).map_err(|e| OxirsError::Io(e.to_string()))?;

        tracing::info!("Persisted {} cached plans to {}", entries.len(), path);

        Ok(())
    }

    /// Load cache from disk
    pub fn load(&self) -> Result<(), OxirsError> {
        if !self.config.enable_persistence {
            return Ok(());
        }

        let path = self
            .config
            .persistence_path
            .as_ref()
            .ok_or_else(|| OxirsError::Io("No persistence path configured".to_string()))?;

        if !Path::new(path).exists() {
            return Ok(()); // No cached data to load
        }

        let json = std::fs::read_to_string(path).map_err(|e| OxirsError::Io(e.to_string()))?;

        let entries: Vec<(u64, CachedPlan)> =
            serde_json::from_str(&json).map_err(|e| OxirsError::Parse(e.to_string()))?;

        let mut cache = self
            .cache
            .write()
            .map_err(|e| OxirsError::Query(format!("Failed to write cache: {}", e)))?;

        for (sig, plan) in entries {
            cache.put(sig, plan);
        }

        tracing::info!("Loaded {} cached plans from {}", cache.len(), path);

        Ok(())
    }

    /// Update execution time for a cached plan
    pub fn update_execution_time(
        &self,
        query: &str,
        execution_time_ms: f64,
    ) -> Result<(), OxirsError> {
        let signature = Self::compute_signature(query);

        let mut cache = self
            .cache
            .write()
            .map_err(|e| OxirsError::Query(format!("Failed to write cache: {}", e)))?;

        if let Some(plan) = cache.get_mut(&signature) {
            // Update average execution time with exponential moving average
            let alpha = 0.3; // Weight for new measurement
            if plan.avg_execution_time_ms == 0.0 {
                plan.avg_execution_time_ms = execution_time_ms;
            } else {
                plan.avg_execution_time_ms =
                    alpha * execution_time_ms + (1.0 - alpha) * plan.avg_execution_time_ms;
            }
        }

        Ok(())
    }

    // Private helper methods

    fn compute_signature(query: &str) -> u64 {
        let mut hasher = DefaultHasher::new();
        query.hash(&mut hasher);
        hasher.finish()
    }

    fn convert_to_serializable(plan: &ExecutionPlan) -> SerializablePlan {
        match plan {
            ExecutionPlan::TripleScan { pattern } => SerializablePlan::TripleScan {
                pattern_desc: format!("{:?}", pattern),
            },
            ExecutionPlan::HashJoin {
                left,
                right,
                join_vars,
            } => SerializablePlan::HashJoin {
                left: Box::new(Self::convert_to_serializable(left)),
                right: Box::new(Self::convert_to_serializable(right)),
                join_vars: join_vars.iter().map(|v| format!("{:?}", v)).collect(),
            },
            ExecutionPlan::Filter { input, condition } => SerializablePlan::Filter {
                input: Box::new(Self::convert_to_serializable(input)),
                expr_desc: format!("{:?}", condition),
            },
            ExecutionPlan::Project { input, vars } => SerializablePlan::Project {
                input: Box::new(Self::convert_to_serializable(input)),
                variables: vars.iter().map(|v| format!("{:?}", v)).collect(),
            },
            ExecutionPlan::Union { left, right } => SerializablePlan::Union {
                left: Box::new(Self::convert_to_serializable(left)),
                right: Box::new(Self::convert_to_serializable(right)),
            },
            _ => SerializablePlan::Empty,
        }
    }

    fn record_hit(&self) {
        self.hit_counter.add(1);
        if let Ok(mut stats) = self.stats.write() {
            stats.hits += 1;
        }
    }

    fn record_miss(&self) {
        self.miss_counter.add(1);
        if let Ok(mut stats) = self.stats.write() {
            stats.misses += 1;
        }
    }

    fn record_eviction(&self) {
        self.eviction_counter.add(1);
        if let Ok(mut stats) = self.stats.write() {
            stats.evictions += 1;
        }
    }
}

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

    #[test]
    fn test_cache_creation() {
        let config = CacheConfig::default();
        let cache = LruQueryPlanCache::new(config);

        let stats = cache.statistics();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
    }

    #[test]
    fn test_cache_put_get() {
        let config = CacheConfig::default();
        let cache = LruQueryPlanCache::new(config);

        let query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o }";
        let plan = ExecutionPlan::TripleScan {
            pattern: crate::model::pattern::TriplePattern::new(None, None, None),
        };

        cache
            .put(query, plan, 100.0)
            .expect("cache put should succeed");

        let cached = cache.get(query);
        assert!(cached.is_some());
        assert_eq!(
            cached.expect("cached value should exist").estimated_cost,
            100.0
        );
    }

    #[test]
    fn test_cache_miss() {
        let config = CacheConfig::default();
        let cache = LruQueryPlanCache::new(config);

        let result = cache.get("SELECT ?s WHERE { ?s ?p ?o }");
        assert!(result.is_none());

        let stats = cache.statistics();
        assert_eq!(stats.misses, 1);
    }

    #[test]
    fn test_cache_remove() {
        let config = CacheConfig::default();
        let cache = LruQueryPlanCache::new(config);

        let query = "SELECT ?s WHERE { ?s ?p ?o }";
        let plan = ExecutionPlan::TripleScan {
            pattern: crate::model::pattern::TriplePattern::new(None, None, None),
        };

        cache
            .put(query, plan, 50.0)
            .expect("cache put should succeed");
        assert!(cache.get(query).is_some());

        cache.remove(query);
        assert!(cache.get(query).is_none());
    }

    #[test]
    fn test_cache_clear() {
        let config = CacheConfig::default();
        let cache = LruQueryPlanCache::new(config);

        let plan = ExecutionPlan::TripleScan {
            pattern: crate::model::pattern::TriplePattern::new(None, None, None),
        };

        cache
            .put("query1", plan.clone(), 50.0)
            .expect("cache put should succeed");
        cache
            .put("query2", plan, 75.0)
            .expect("cache put should succeed");

        cache.clear().expect("cache clear should succeed");

        let stats = cache.statistics();
        assert_eq!(stats.current_size, 0);
    }

    #[test]
    fn test_hit_rate() {
        let config = CacheConfig::default();
        let cache = LruQueryPlanCache::new(config);

        let plan = ExecutionPlan::TripleScan {
            pattern: crate::model::pattern::TriplePattern::new(None, None, None),
        };

        let query = "SELECT * WHERE { ?s ?p ?o }";
        cache
            .put(query, plan, 100.0)
            .expect("cache put should succeed");

        // One hit
        cache.get(query);
        // One miss
        cache.get("SELECT * WHERE { ?x ?y ?z }");

        let hit_rate = cache.hit_rate();
        assert!((hit_rate - 0.5).abs() < 0.01); // 50% hit rate
    }

    #[test]
    fn test_lru_eviction() {
        let config = CacheConfig {
            max_size: 2, // Small cache for testing
            ..Default::default()
        };

        let cache = LruQueryPlanCache::new(config);

        let plan = ExecutionPlan::TripleScan {
            pattern: crate::model::pattern::TriplePattern::new(None, None, None),
        };

        cache
            .put("query1", plan.clone(), 10.0)
            .expect("cache put should succeed");
        cache
            .put("query2", plan.clone(), 20.0)
            .expect("cache put should succeed");
        cache
            .put("query3", plan, 30.0)
            .expect("cache put should succeed"); // Should evict query1

        assert!(cache.get("query1").is_none()); // Evicted
        assert!(cache.get("query2").is_some());
        assert!(cache.get("query3").is_some());
    }

    #[test]
    fn test_execution_time_update() {
        let config = CacheConfig::default();
        let cache = LruQueryPlanCache::new(config);

        let query = "SELECT ?s WHERE { ?s ?p ?o }";
        let plan = ExecutionPlan::TripleScan {
            pattern: crate::model::pattern::TriplePattern::new(None, None, None),
        };

        cache
            .put(query, plan, 100.0)
            .expect("cache put should succeed");

        cache
            .update_execution_time(query, 50.0)
            .expect("update should succeed");

        let cached = cache.get(query).expect("cache get should succeed");
        assert_eq!(cached.avg_execution_time_ms, 50.0);

        cache
            .update_execution_time(query, 70.0)
            .expect("update should succeed");

        let cached2 = cache.get(query).expect("cache get should succeed");
        // Should be exponential moving average
        assert!(cached2.avg_execution_time_ms > 50.0 && cached2.avg_execution_time_ms < 70.0);
    }
}

// ===========================================================================
// Simpler, self-contained QueryPlanCache
//
// A lightweight alternative to LruQueryPlanCache that does not depend on the
// `lru` crate or SciRS2 metrics and is easier to use in unit tests and in
// parts of the system that only need basic LRU semantics.
// ===========================================================================

use std::collections::HashMap;

/// A compiled SPARQL query plan ready for execution.
#[derive(Debug, Clone)]
pub struct QueryPlan {
    /// FNV / DefaultHasher hash of the original query string.
    pub query_hash: u64,
    /// The raw SPARQL query string.
    pub original_query: String,
    /// Human-readable descriptions of the optimized pattern steps.
    pub optimized_patterns: Vec<String>,
    /// Estimated execution cost (lower is better).
    pub estimated_cost: f64,
    /// Unix timestamp (ms) when this plan was created.
    pub created_at_ms: i64,
}

impl QueryPlan {
    fn now_ms() -> i64 {
        use std::time::{SystemTime, UNIX_EPOCH};
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0)
    }

    /// Construct a new plan.  `created_at_ms` is set to the current time.
    pub fn new(
        query_hash: u64,
        original_query: impl Into<String>,
        optimized_patterns: Vec<String>,
        estimated_cost: f64,
    ) -> Self {
        Self {
            query_hash,
            original_query: original_query.into(),
            optimized_patterns,
            estimated_cost,
            created_at_ms: Self::now_ms(),
        }
    }
}

/// Aggregated statistics for a [`QueryPlanCache`] instance.
#[derive(Debug, Clone, Default)]
pub struct PlanCacheStats {
    /// Number of successful cache lookups.
    pub hits: u64,
    /// Number of failed cache lookups.
    pub misses: u64,
    /// Number of plans evicted to make room for new entries.
    pub evictions: u64,
    /// Current number of entries in the cache.
    pub size: usize,
}

/// A simple LRU query-plan cache with O(n) eviction.
///
/// This is deliberately kept dependency-free (no `lru` crate, no SciRS2).
/// The access order vector has the most-recently-used entry at the **front**
/// (index 0) and the least-recently-used at the **back**.
///
/// For the high-throughput LRU cache backed by the `lru` crate, see
/// [`LruQueryPlanCache`].
pub struct QueryPlanCache {
    plans: HashMap<u64, QueryPlan>,
    /// Most-recently-used at index 0; least-recently-used at the back.
    access_order: Vec<u64>,
    max_size: usize,
    stats: PlanCacheStats,
}

impl QueryPlanCache {
    /// Create a new cache that can hold at most `max_size` plans.
    ///
    /// If `max_size` is 0 it is treated as 1 to avoid degenerate behaviour.
    pub fn new(max_size: usize) -> Self {
        let max_size = max_size.max(1);
        Self {
            plans: HashMap::new(),
            access_order: Vec::new(),
            max_size,
            stats: PlanCacheStats::default(),
        }
    }

    /// Retrieve the plan for `query_hash`.
    ///
    /// On a hit the entry is moved to the front of the access-order list and
    /// `stats.hits` is incremented.  On a miss `stats.misses` is incremented.
    pub fn get(&mut self, query_hash: u64) -> Option<&QueryPlan> {
        if self.plans.contains_key(&query_hash) {
            // Move to front of access_order.
            if let Some(pos) = self.access_order.iter().position(|&h| h == query_hash) {
                self.access_order.remove(pos);
            }
            self.access_order.insert(0, query_hash);
            self.stats.hits += 1;
            self.plans.get(&query_hash)
        } else {
            self.stats.misses += 1;
            None
        }
    }

    /// Insert a plan into the cache.
    ///
    /// If the cache is at capacity, [`evict_lru`] is called first.  The new
    /// entry is placed at the front of the access-order list.
    ///
    /// [`evict_lru`]: QueryPlanCache::evict_lru
    pub fn insert(&mut self, plan: QueryPlan) {
        let hash = plan.query_hash;

        // If the hash is already present, remove it from access_order so it
        // can be re-inserted at the front.
        if self.plans.contains_key(&hash) {
            if let Some(pos) = self.access_order.iter().position(|&h| h == hash) {
                self.access_order.remove(pos);
            }
        } else if self.plans.len() >= self.max_size {
            self.evict_lru();
        }

        self.plans.insert(hash, plan);
        self.access_order.insert(0, hash);
        self.stats.size = self.plans.len();
    }

    /// Remove and return the least-recently-used plan (the one at the back of
    /// the access-order list).  Increments `stats.evictions`.
    ///
    /// Returns `None` if the cache is empty.
    pub fn evict_lru(&mut self) -> Option<QueryPlan> {
        let lru_hash = self.access_order.pop()?;
        let plan = self.plans.remove(&lru_hash);
        self.stats.evictions += 1;
        self.stats.size = self.plans.len();
        plan
    }

    /// Remove a specific plan by hash.  Returns `true` if it existed.
    pub fn invalidate(&mut self, query_hash: u64) -> bool {
        let existed = self.plans.remove(&query_hash).is_some();
        if existed {
            if let Some(pos) = self.access_order.iter().position(|&h| h == query_hash) {
                self.access_order.remove(pos);
            }
            self.stats.size = self.plans.len();
        }
        existed
    }

    /// Remove all entries and reset size to zero (other statistics are kept).
    pub fn clear(&mut self) {
        self.plans.clear();
        self.access_order.clear();
        self.stats.size = 0;
    }

    /// Return a snapshot of the current statistics.
    pub fn stats(&self) -> &PlanCacheStats {
        &self.stats
    }

    /// Cache hit rate: `hits / (hits + misses)`, or `0.0` if no operations
    /// have been performed yet.
    pub fn hit_rate(&self) -> f64 {
        let total = self.stats.hits + self.stats.misses;
        if total == 0 {
            0.0
        } else {
            self.stats.hits as f64 / total as f64
        }
    }

    /// Current number of cached plans.
    pub fn len(&self) -> usize {
        self.plans.len()
    }

    /// Return `true` if the cache contains no plans.
    pub fn is_empty(&self) -> bool {
        self.plans.is_empty()
    }
}

// ---------------------------------------------------------------------------
// Tests for the simple QueryPlanCache
// ---------------------------------------------------------------------------

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

    fn make_plan(hash: u64, query: &str, cost: f64) -> QueryPlan {
        QueryPlan::new(hash, query, vec!["scan".to_string()], cost)
    }

    #[test]
    fn test_simple_cache_new_is_empty() {
        let cache = QueryPlanCache::new(10);
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_simple_cache_insert_and_get_hit() {
        let mut cache = QueryPlanCache::new(10);
        cache.insert(make_plan(1, "SELECT ?s ?p ?o WHERE {?s ?p ?o}", 100.0));
        let plan = cache.get(1);
        assert!(plan.is_some());
        assert_eq!(plan.expect("plan should exist").query_hash, 1);
    }

    #[test]
    fn test_simple_cache_miss_increments_stat() {
        let mut cache = QueryPlanCache::new(10);
        assert!(cache.get(42).is_none());
        assert_eq!(cache.stats().misses, 1);
        assert_eq!(cache.stats().hits, 0);
    }

    #[test]
    fn test_simple_cache_hit_increments_stat() {
        let mut cache = QueryPlanCache::new(10);
        cache.insert(make_plan(7, "SELECT * WHERE {?s ?p ?o}", 50.0));
        cache.get(7);
        assert_eq!(cache.stats().hits, 1);
        assert_eq!(cache.stats().misses, 0);
    }

    #[test]
    fn test_simple_cache_hit_rate_zero_initially() {
        let cache = QueryPlanCache::new(5);
        assert_eq!(cache.hit_rate(), 0.0);
    }

    #[test]
    fn test_simple_cache_hit_rate_after_ops() {
        let mut cache = QueryPlanCache::new(5);
        cache.insert(make_plan(1, "q1", 10.0));
        cache.get(1); // hit
        cache.get(2); // miss
        let rate = cache.hit_rate();
        assert!((rate - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_simple_cache_evict_lru_on_full() {
        let mut cache = QueryPlanCache::new(2);
        cache.insert(make_plan(1, "q1", 1.0)); // LRU = q1
        cache.insert(make_plan(2, "q2", 2.0)); // LRU = q1, MRU = q2
                                               // Insert q3 — q1 should be evicted.
        cache.insert(make_plan(3, "q3", 3.0));
        assert_eq!(cache.len(), 2);
        assert!(cache.get(1).is_none(), "q1 should have been evicted");
        assert!(cache.get(2).is_some());
        assert!(cache.get(3).is_some());
    }

    #[test]
    fn test_simple_cache_evict_lru_access_order() {
        let mut cache = QueryPlanCache::new(2);
        cache.insert(make_plan(1, "q1", 1.0));
        cache.insert(make_plan(2, "q2", 2.0));
        // Access q1 to make it MRU; q2 becomes LRU.
        cache.get(1);
        // Insert q3 — q2 should be evicted.
        cache.insert(make_plan(3, "q3", 3.0));
        assert!(cache.get(2).is_none(), "q2 should have been evicted");
        assert!(cache.get(1).is_some());
        assert!(cache.get(3).is_some());
    }

    #[test]
    fn test_simple_cache_evict_lru_explicit() {
        let mut cache = QueryPlanCache::new(5);
        cache.insert(make_plan(1, "q1", 1.0));
        cache.insert(make_plan(2, "q2", 2.0));
        let evicted = cache.evict_lru();
        assert!(evicted.is_some());
        assert_eq!(cache.stats().evictions, 1);
        assert_eq!(cache.len(), 1);
    }

    #[test]
    fn test_simple_cache_evict_lru_empty_returns_none() {
        let mut cache = QueryPlanCache::new(5);
        assert!(cache.evict_lru().is_none());
    }

    #[test]
    fn test_simple_cache_invalidate_existing() {
        let mut cache = QueryPlanCache::new(5);
        cache.insert(make_plan(99, "q99", 9.0));
        let removed = cache.invalidate(99);
        assert!(removed);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_simple_cache_invalidate_missing_returns_false() {
        let mut cache = QueryPlanCache::new(5);
        assert!(!cache.invalidate(404));
    }

    #[test]
    fn test_simple_cache_clear() {
        let mut cache = QueryPlanCache::new(5);
        cache.insert(make_plan(1, "q1", 1.0));
        cache.insert(make_plan(2, "q2", 2.0));
        cache.clear();
        assert!(cache.is_empty());
        assert_eq!(cache.stats().size, 0);
    }

    #[test]
    fn test_simple_cache_plan_fields() {
        let plan = QueryPlan::new(
            42,
            "SELECT * WHERE {?s ?p ?o}",
            vec!["index_scan".to_string()],
            2.5,
        );
        assert_eq!(plan.query_hash, 42);
        assert_eq!(plan.optimized_patterns, vec!["index_scan".to_string()]);
        assert!((plan.estimated_cost - 2.5).abs() < 1e-9);
        assert!(plan.created_at_ms >= 0);
    }

    #[test]
    fn test_simple_cache_stats_size_tracks_inserts() {
        let mut cache = QueryPlanCache::new(10);
        cache.insert(make_plan(1, "q1", 1.0));
        cache.insert(make_plan(2, "q2", 2.0));
        assert_eq!(cache.stats().size, 2);
    }

    #[test]
    fn test_simple_cache_reinsertion_updates_access_order() {
        let mut cache = QueryPlanCache::new(3);
        cache.insert(make_plan(1, "q1", 1.0));
        cache.insert(make_plan(2, "q2", 2.0));
        // Re-insert q1; it should become MRU.  Then insert q3: q2 (LRU) is evicted.
        cache.insert(make_plan(1, "q1", 1.5)); // update q1, now MRU
                                               // Cache at capacity (2 distinct hashes since max_size=3 and we have 2).
                                               // Insert q3 now — cache has room, no eviction.
        cache.insert(make_plan(3, "q3", 3.0));
        assert_eq!(cache.len(), 3); // 1, 2, 3 all present
    }
}