memd 1.9.0

Local memory CLI for AI agents with hybrid retrieval
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
//! Tiered search coordinator with cache/hot/warm fallback
//!
//! TieredSearcher routes queries through the tiered architecture:
//! semantic cache (fastest) -> hot tier (fast) -> warm tier (standard).
//! It automatically promotes frequently accessed chunks and demotes stale ones.

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

use parking_lot::RwLock;

use crate::error::Result;
use crate::index::SearchResult;
use crate::types::{ChunkId, TenantId};

use super::access_tracker::{AccessEvent, AccessTracker};
use super::hot_tier::HotTier;
use super::semantic_cache::{CachedResult, SemanticCache};

/// Configuration for tiered search
#[derive(Debug, Clone)]
pub struct TieredSearcherConfig {
    /// Enable semantic cache (default true)
    pub enable_cache: bool,
    /// Enable hot tier (default true)
    pub enable_hot_tier: bool,
    /// Minimum score for promotion to hot tier (default 0.4)
    pub promotion_threshold: f32,
    /// Number of queries without access before demotion (default 100)
    pub demotion_queries_threshold: u32,
    /// Auto-promote chunks from matching project (default true)
    pub auto_promote_on_project_match: bool,
    /// Enable debug output for tier decisions (default false)
    pub debug_tier_decisions: bool,
}

impl Default for TieredSearcherConfig {
    fn default() -> Self {
        Self {
            enable_cache: true,
            enable_hot_tier: true,
            promotion_threshold: 0.4,
            demotion_queries_threshold: 100,
            auto_promote_on_project_match: true,
            debug_tier_decisions: false,
        }
    }
}

/// Source tier for a search result
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceTier {
    /// Result came from semantic cache
    Cache,
    /// Result came from hot tier
    Hot,
    /// Result came from warm tier
    Warm,
}

/// Action for a tier decision
#[derive(Debug, Clone)]
pub enum TierAction {
    /// Promote chunk to hot tier
    Promote {
        /// Source tier being promoted from
        from: SourceTier,
        /// Promotion score
        score: f32,
    },
    /// Demote chunk from hot tier
    Demote {
        /// Reason for demotion
        reason: String,
    },
    /// No action needed
    None,
}

/// A decision about tier placement for a chunk
#[derive(Debug, Clone)]
pub struct TierDecision {
    /// The chunk being evaluated
    pub chunk_id: ChunkId,
    /// The action to take
    pub action: TierAction,
    /// Human-readable reason
    pub reason: String,
    /// Promotion/access score if applicable
    pub score: Option<f32>,
    /// Which tier the chunk is currently in
    pub source_tier: SourceTier,
}

/// A chunk with score and source tier info
#[derive(Debug, Clone)]
pub struct ScoredChunk {
    /// The chunk ID
    pub chunk_id: ChunkId,
    /// Similarity/relevance score
    pub score: f32,
    /// Which tier returned this result
    pub source_tier: SourceTier,
}

/// Timing breakdown for tiered search
#[derive(Debug, Clone, Default)]
pub struct TieredTiming {
    /// Time spent on cache lookup (ms)
    pub cache_lookup_ms: u64,
    /// Time spent on hot tier search (ms)
    pub hot_tier_ms: u64,
    /// Time spent on warm tier search (ms)
    pub warm_tier_ms: u64,
    /// Time spent on promotion checks (ms)
    pub promotion_check_ms: u64,
    /// Total search time (ms)
    pub total_ms: u64,
}

/// Result of a tiered search
#[derive(Debug, Clone)]
pub struct TieredSearchResult {
    /// Search results with scores
    pub results: Vec<ScoredChunk>,
    /// Primary source tier (first non-empty result source)
    pub source_tier: SourceTier,
    /// Whether cache was hit
    pub cache_hit: bool,
    /// Whether hot tier returned results
    pub hot_tier_hit: bool,
    /// Timing breakdown
    pub timing: TieredTiming,
    /// Tier decisions (only if debug enabled)
    pub tier_decisions: Vec<TierDecision>,
}

/// Trait for warm tier search operations
///
/// Abstracts the warm tier (main index) to allow different implementations.
pub trait WarmTierSearch: Send + Sync {
    /// Search the warm tier
    fn search(&self, query_embedding: &[f32], k: usize) -> Result<Vec<SearchResult>>;

    /// Get the embedding for a chunk (for promotion to hot tier)
    fn get_embedding(&self, chunk_id: &ChunkId) -> Option<Vec<f32>>;

    /// Get current version for cache invalidation
    fn get_version(&self) -> u64;

    /// Get the total number of indexed chunks
    fn len(&self) -> usize;

    /// Check if warm tier is empty
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// Tiered search coordinator
///
/// Coordinates cache/hot/warm fallback chain and manages promotion/demotion.
pub struct TieredSearcher<W: WarmTierSearch> {
    /// Semantic query cache
    cache: Arc<SemanticCache>,
    /// Hot tier with promoted chunks
    hot_tier: Arc<RwLock<HotTier>>,
    /// Access tracker for promotion scoring
    access_tracker: Arc<RwLock<AccessTracker>>,
    /// Warm tier (main index)
    warm_tier: Arc<W>,
    /// Configuration
    config: TieredSearcherConfig,
    /// Query counter for demotion checks
    query_counter: AtomicU64,
    /// Last demotion check timestamp (Unix ms)
    last_demotion_check: AtomicU64,
}

impl<W: WarmTierSearch> TieredSearcher<W> {
    /// Create a new tiered searcher
    pub fn new(
        cache: Arc<SemanticCache>,
        hot_tier: Arc<RwLock<HotTier>>,
        access_tracker: Arc<RwLock<AccessTracker>>,
        warm_tier: Arc<W>,
        config: TieredSearcherConfig,
    ) -> Self {
        Self {
            cache,
            hot_tier,
            access_tracker,
            warm_tier,
            config,
            query_counter: AtomicU64::new(0),
            last_demotion_check: AtomicU64::new(current_time_ms() as u64),
        }
    }

    /// Expose the warm tier (used by storage layer to bump its version
    /// counter on writes; see Phase 3.5). Returning `Arc` preserves
    /// the trait-object abstraction.
    pub fn warm_tier(&self) -> Arc<W> {
        Arc::clone(&self.warm_tier)
    }

    /// Get the current configuration
    pub fn config(&self) -> &TieredSearcherConfig {
        &self.config
    }

    /// Get the query counter value
    pub fn query_count(&self) -> u64 {
        self.query_counter.load(Ordering::Relaxed)
    }

    /// Search across tiers with cache -> hot -> warm fallback
    ///
    /// Returns results from the fastest tier that has them:
    /// 1. Semantic cache (if enabled and similar query found)
    /// 2. Hot tier (if enabled and has results)
    /// 3. Warm tier (always searched as fallback)
    pub fn search(
        &self,
        query_embedding: &[f32],
        tenant_id: &TenantId,
        project_id: Option<&str>,
        k: usize,
    ) -> Result<TieredSearchResult> {
        self.search_internal(query_embedding, tenant_id, project_id, k, false)
    }

    /// Search with debug tier decisions enabled
    pub fn search_with_debug(
        &self,
        query_embedding: &[f32],
        tenant_id: &TenantId,
        project_id: Option<&str>,
        k: usize,
    ) -> Result<TieredSearchResult> {
        self.search_internal(query_embedding, tenant_id, project_id, k, true)
    }

    /// Internal search implementation
    fn search_internal(
        &self,
        query_embedding: &[f32],
        tenant_id: &TenantId,
        project_id: Option<&str>,
        k: usize,
        debug: bool,
    ) -> Result<TieredSearchResult> {
        let total_start = Instant::now();
        let mut timing = TieredTiming::default();
        let mut tier_decisions = Vec::new();

        // Increment query counter
        self.query_counter.fetch_add(1, Ordering::Relaxed);

        // Keep the cache generation tied to the snapshot this search starts from.
        let version = self.warm_tier.get_version();

        // Step 1: Cache lookup (if enabled)
        let cache_start = Instant::now();
        let cache_result = if self.config.enable_cache {
            self.cache
                .lookup_with_limit(query_embedding, tenant_id, project_id, version, k)
        } else {
            None
        };
        timing.cache_lookup_ms = cache_start.elapsed().as_millis() as u64;

        // If cache hit, return immediately
        if let Some(hit) = cache_result {
            let results: Vec<ScoredChunk> = hit
                .results
                .into_iter()
                .take(k)
                .map(|r| ScoredChunk {
                    chunk_id: r.chunk_id,
                    score: r.score,
                    source_tier: SourceTier::Cache,
                })
                .collect();

            timing.total_ms = total_start.elapsed().as_millis() as u64;

            return Ok(TieredSearchResult {
                results,
                source_tier: SourceTier::Cache,
                cache_hit: true,
                hot_tier_hit: false,
                timing,
                tier_decisions,
            });
        }

        // Step 2: Hot tier search (if enabled)
        let hot_start = Instant::now();
        let hot_results = if self.config.enable_hot_tier {
            let hot_tier = self.hot_tier.read();
            hot_tier.search(query_embedding, k)?
        } else {
            Vec::new()
        };
        timing.hot_tier_ms = hot_start.elapsed().as_millis() as u64;

        let hot_tier_hit = !hot_results.is_empty();

        // Step 3: Warm tier search (always as fallback)
        let warm_start = Instant::now();
        let warm_results = self.warm_tier.search(query_embedding, k)?;
        timing.warm_tier_ms = warm_start.elapsed().as_millis() as u64;

        // Step 4: Merge and deduplicate results
        let merged = self.merge_results(&hot_results, &warm_results, k, debug, &mut tier_decisions);

        // Step 5: Record access for all returned chunks
        {
            let tracker = self.access_tracker.write();
            for chunk in &merged {
                let event = if let Some(proj) = project_id {
                    AccessEvent::with_project(chunk.chunk_id.clone(), proj.to_string())
                } else {
                    AccessEvent::new(chunk.chunk_id.clone())
                };
                tracker.record_access(event);
            }
        }

        // Step 6: Cache results (if cache enabled)
        if self.config.enable_cache && !merged.is_empty() {
            let cached_results: Vec<CachedResult> = merged
                .iter()
                .map(|r| CachedResult {
                    chunk_id: r.chunk_id.clone(),
                    score: r.score,
                    text_preview: String::new(), // No text preview in this path
                })
                .collect();

            self.cache.insert_with_limit(
                query_embedding.to_vec(),
                tenant_id.clone(),
                project_id.map(|s| s.to_string()),
                cached_results,
                version,
                k,
            );
        }

        // Determine primary source tier
        let source_tier = if hot_tier_hit {
            SourceTier::Hot
        } else {
            SourceTier::Warm
        };

        timing.total_ms = total_start.elapsed().as_millis() as u64;

        Ok(TieredSearchResult {
            results: merged,
            source_tier,
            cache_hit: false,
            hot_tier_hit,
            timing,
            tier_decisions: if debug || self.config.debug_tier_decisions {
                tier_decisions
            } else {
                Vec::new()
            },
        })
    }

    /// Merge hot and warm tier results, deduplicating by chunk_id
    ///
    /// Prefers hot tier scores when a chunk appears in both.
    fn merge_results(
        &self,
        hot_results: &[SearchResult],
        warm_results: &[SearchResult],
        k: usize,
        debug: bool,
        tier_decisions: &mut Vec<TierDecision>,
    ) -> Vec<ScoredChunk> {
        use std::collections::HashMap;

        let mut seen: HashMap<ChunkId, ScoredChunk> = HashMap::new();

        // Hot tier results first (preferred)
        for result in hot_results {
            if debug {
                tier_decisions.push(TierDecision {
                    chunk_id: result.chunk_id.clone(),
                    action: TierAction::None,
                    reason: format!("Found in hot tier with score {:.3}", result.score),
                    score: Some(result.score),
                    source_tier: SourceTier::Hot,
                });
            }
            seen.insert(
                result.chunk_id.clone(),
                ScoredChunk {
                    chunk_id: result.chunk_id.clone(),
                    score: result.score,
                    source_tier: SourceTier::Hot,
                },
            );
        }

        // Warm tier results (only if not already in hot)
        for result in warm_results {
            if !seen.contains_key(&result.chunk_id) {
                if debug {
                    tier_decisions.push(TierDecision {
                        chunk_id: result.chunk_id.clone(),
                        action: TierAction::None,
                        reason: format!("Found in warm tier with score {:.3}", result.score),
                        score: Some(result.score),
                        source_tier: SourceTier::Warm,
                    });
                }
                seen.insert(
                    result.chunk_id.clone(),
                    ScoredChunk {
                        chunk_id: result.chunk_id.clone(),
                        score: result.score,
                        source_tier: SourceTier::Warm,
                    },
                );
            }
        }

        // Sort by score descending and take top k. `seen` is a HashMap, so
        // equal scores need a fixed tie-break or the order varies per run.
        let mut results: Vec<ScoredChunk> = seen.into_values().collect();
        results.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.chunk_id.cmp(&b.chunk_id))
        });
        results.truncate(k);
        results
    }

    /// Check for chunks to promote to hot tier
    ///
    /// Returns a list of tier decisions for chunks that were promoted.
    /// Chunks are promoted if they have a promotion score >= threshold
    /// and are not already in the hot tier.
    pub fn check_promotions(
        &self,
        tenant_id: &TenantId,
        project_id: Option<&str>,
    ) -> Vec<TierDecision> {
        if !self.config.enable_hot_tier {
            return Vec::new();
        }

        let mut decisions = Vec::new();

        // Get top candidates from access tracker
        let candidates = {
            let tracker = self.access_tracker.read();
            tracker.get_top_candidates(100, project_id)
        };

        // Filter and promote eligible chunks
        let hot_tier = self.hot_tier.write();

        for candidate in candidates {
            // Skip if already in hot tier
            if hot_tier.contains(&candidate.chunk_id) {
                continue;
            }

            // Check promotion threshold
            if candidate.score < self.config.promotion_threshold {
                continue;
            }

            // Get embedding from warm tier for hot tier promotion
            let embedding = match self.warm_tier.get_embedding(&candidate.chunk_id) {
                Some(e) => e,
                None => continue, // Skip if no embedding available
            };

            // Promote to hot tier
            match hot_tier.promote(
                candidate.chunk_id.clone(),
                embedding,
                tenant_id.clone(),
                candidate.score,
            ) {
                Ok(true) => {
                    decisions.push(TierDecision {
                        chunk_id: candidate.chunk_id,
                        action: TierAction::Promote {
                            from: SourceTier::Warm,
                            score: candidate.score,
                        },
                        reason: format!(
                            "Promoted due to high access score ({:.3}): freq={:.2}, recency={:.2}, project={:.2}",
                            candidate.score,
                            candidate.frequency_component,
                            candidate.recency_component,
                            candidate.project_component,
                        ),
                        score: Some(candidate.score),
                        source_tier: SourceTier::Warm,
                    });
                }
                Ok(false) => {
                    // Already in hot tier or at capacity
                }
                Err(_) => {
                    // Promotion failed, skip
                }
            }
        }

        decisions
    }

    /// Check for chunks to demote from hot tier
    ///
    /// Demotes chunks that have dropped below half the promotion threshold.
    /// Only runs after demotion_queries_threshold queries.
    pub fn check_demotions(&self, project_id: Option<&str>) -> Vec<TierDecision> {
        if !self.config.enable_hot_tier {
            return Vec::new();
        }

        // Check if we've hit the query threshold
        let query_count = self.query_counter.load(Ordering::Relaxed);
        let threshold = self.config.demotion_queries_threshold as u64;

        if query_count < threshold {
            return Vec::new();
        }

        // Reset query counter
        self.query_counter.store(0, Ordering::Relaxed);
        self.last_demotion_check
            .store(current_time_ms() as u64, Ordering::Relaxed);

        let mut decisions = Vec::new();
        let demotion_threshold = self.config.promotion_threshold * 0.5;

        // Get all candidates from access tracker that might be in hot tier
        let all_candidates = {
            let tracker = self.access_tracker.read();
            tracker.get_top_candidates(1000, project_id)
        };

        // Check each candidate - demote those in hot tier with low scores
        let hot_tier = self.hot_tier.write();

        for candidate in all_candidates {
            if !hot_tier.contains(&candidate.chunk_id) {
                continue;
            }

            // Check if score dropped below demotion threshold
            if candidate.score < demotion_threshold {
                // Demote from hot tier
                if hot_tier.demote(&candidate.chunk_id) {
                    decisions.push(TierDecision {
                        chunk_id: candidate.chunk_id,
                        action: TierAction::Demote {
                            reason: format!(
                                "Score ({:.3}) dropped below demotion threshold ({:.3})",
                                candidate.score, demotion_threshold
                            ),
                        },
                        reason: format!(
                            "Demoted due to low access score ({:.3} < {:.3})",
                            candidate.score, demotion_threshold
                        ),
                        score: Some(candidate.score),
                        source_tier: SourceTier::Hot,
                    });
                }
            }
        }

        decisions
    }

    /// Run periodic maintenance tasks
    ///
    /// - Check for promotions
    /// - Check for demotions
    /// - Evict if hot tier over capacity
    /// - Prune cache index
    pub fn run_maintenance(&self, tenant_id: &TenantId) -> MaintenanceResult {
        let start = Instant::now();

        // Check promotions (no project context for periodic maintenance)
        let promotions = self.check_promotions(tenant_id, None);

        // Check demotions
        let demotions = self.check_demotions(None);

        // Evict if hot tier over capacity
        let evictions = {
            let hot_tier = self.hot_tier.write();
            let total_indexed = self.warm_tier.len();
            hot_tier.evict_if_needed(total_indexed)
        };

        // Prune cache index
        self.cache.prune_index();

        MaintenanceResult {
            promotions_count: promotions.len(),
            demotions_count: demotions.len(),
            evictions_count: evictions,
            duration_ms: start.elapsed().as_millis() as u64,
            promotion_decisions: promotions,
            demotion_decisions: demotions,
        }
    }

    /// Maybe promote a chunk immediately on access if it matches project
    ///
    /// Returns a tier decision if the chunk was promoted.
    pub fn maybe_promote_on_access(
        &self,
        chunk_id: &ChunkId,
        tenant_id: &TenantId,
        project_id: Option<&str>,
    ) -> Option<TierDecision> {
        // Check if auto-promotion is enabled
        if !self.config.auto_promote_on_project_match || !self.config.enable_hot_tier {
            return None;
        }

        // Need project context for project-based promotion
        let project_id = project_id?;

        // Check if already in hot tier
        {
            let hot_tier = self.hot_tier.read();
            if hot_tier.contains(chunk_id) {
                return None;
            }
        }

        // Get promotion score with project context
        let score = {
            let tracker = self.access_tracker.read();
            tracker.get_promotion_score(chunk_id, Some(project_id))
        };

        // Check if eligible for promotion
        if !score.eligible || score.score < self.config.promotion_threshold {
            return None;
        }

        // Project component must be non-zero (accessed from this project)
        if score.project_component == 0.0 {
            return None;
        }

        // Get embedding for promotion
        let embedding = self.warm_tier.get_embedding(chunk_id)?;

        // Promote to hot tier
        let hot_tier = self.hot_tier.write();
        match hot_tier.promote(chunk_id.clone(), embedding, tenant_id.clone(), score.score) {
            Ok(true) => Some(TierDecision {
                chunk_id: chunk_id.clone(),
                action: TierAction::Promote {
                    from: SourceTier::Warm,
                    score: score.score,
                },
                reason: format!(
                    "Auto-promoted due to project match and high score ({:.3})",
                    score.score
                ),
                score: Some(score.score),
                source_tier: SourceTier::Warm,
            }),
            _ => None,
        }
    }
}

/// Result of running maintenance
#[derive(Debug, Clone)]
pub struct MaintenanceResult {
    /// Number of chunks promoted
    pub promotions_count: usize,
    /// Number of chunks demoted
    pub demotions_count: usize,
    /// Number of chunks evicted from hot tier
    pub evictions_count: usize,
    /// Time taken for maintenance (ms)
    pub duration_ms: u64,
    /// Detailed promotion decisions
    pub promotion_decisions: Vec<TierDecision>,
    /// Detailed demotion decisions
    pub demotion_decisions: Vec<TierDecision>,
}

/// Get current time in milliseconds
fn current_time_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tiered::{AccessTrackerConfig, HotTierConfig, SemanticCacheConfig};

    /// Mock warm tier for testing
    struct MockWarmTier {
        results: RwLock<Vec<SearchResult>>,
        embeddings: RwLock<std::collections::HashMap<ChunkId, Vec<f32>>>,
        version: AtomicU64,
        replacement_on_search: RwLock<Option<Vec<SearchResult>>>,
    }

    impl MockWarmTier {
        fn new() -> Self {
            Self {
                results: RwLock::new(Vec::new()),
                embeddings: RwLock::new(std::collections::HashMap::new()),
                version: AtomicU64::new(1),
                replacement_on_search: RwLock::new(None),
            }
        }

        fn add_chunk(&self, chunk_id: ChunkId, embedding: Vec<f32>, score: f32) {
            self.results.write().push(SearchResult {
                chunk_id: chunk_id.clone(),
                score,
            });
            self.embeddings.write().insert(chunk_id, embedding);
        }
    }

    impl WarmTierSearch for MockWarmTier {
        fn search(&self, _query_embedding: &[f32], k: usize) -> Result<Vec<SearchResult>> {
            let results = {
                let results = self.results.read();
                results.iter().take(k).cloned().collect()
            };
            if let Some(replacement) = self.replacement_on_search.write().take() {
                *self.results.write() = replacement;
                self.version.fetch_add(1, Ordering::Relaxed);
            }
            Ok(results)
        }

        fn get_embedding(&self, chunk_id: &ChunkId) -> Option<Vec<f32>> {
            self.embeddings.read().get(chunk_id).cloned()
        }

        fn get_version(&self) -> u64 {
            self.version.load(Ordering::Relaxed)
        }

        fn len(&self) -> usize {
            self.results.read().len()
        }
    }

    fn make_test_searcher() -> TieredSearcher<MockWarmTier> {
        let cache = Arc::new(SemanticCache::new(SemanticCacheConfig::default()));
        let hot_tier = Arc::new(RwLock::new(HotTier::new(HotTierConfig::default())));
        let access_tracker = Arc::new(RwLock::new(AccessTracker::new(
            AccessTrackerConfig::default(),
        )));
        let warm_tier = Arc::new(MockWarmTier::new());

        TieredSearcher::new(
            cache,
            hot_tier,
            access_tracker,
            warm_tier,
            TieredSearcherConfig::default(),
        )
    }

    #[test]
    fn test_config_defaults() {
        let config = TieredSearcherConfig::default();
        assert!(config.enable_cache);
        assert!(config.enable_hot_tier);
        assert!((config.promotion_threshold - 0.4).abs() < 0.01);
        assert_eq!(config.demotion_queries_threshold, 100);
        assert!(config.auto_promote_on_project_match);
        assert!(!config.debug_tier_decisions);
    }

    #[test]
    fn test_tiered_searcher_creation() {
        let searcher = make_test_searcher();
        assert_eq!(searcher.query_count(), 0);
        assert!(searcher.config().enable_cache);
    }

    #[test]
    fn test_source_tier_equality() {
        assert_eq!(SourceTier::Cache, SourceTier::Cache);
        assert_ne!(SourceTier::Cache, SourceTier::Hot);
        assert_ne!(SourceTier::Hot, SourceTier::Warm);
    }

    #[test]
    fn test_mock_warm_tier() {
        let warm = MockWarmTier::new();
        let chunk_id = ChunkId::new();
        let embedding = vec![1.0, 0.0, 0.0, 0.0];

        warm.add_chunk(chunk_id.clone(), embedding.clone(), 0.95);

        assert_eq!(warm.len(), 1);
        assert!(warm.get_embedding(&chunk_id).is_some());

        let results = warm.search(&embedding, 10).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].chunk_id, chunk_id);
    }

    fn make_tenant() -> TenantId {
        TenantId::new("test_tenant").unwrap()
    }

    type TestSearcher = (
        TieredSearcher<MockWarmTier>,
        Arc<SemanticCache>,
        Arc<RwLock<HotTier>>,
        Arc<RwLock<AccessTracker>>,
    );

    fn make_searcher_with_warm(warm: Arc<MockWarmTier>) -> TestSearcher {
        let cache = Arc::new(SemanticCache::new(SemanticCacheConfig::default()));
        let hot_tier_config = HotTierConfig {
            hnsw_config: crate::index::HnswConfig {
                dimension: 4,
                max_elements: 100,
                ..Default::default()
            },
            ..Default::default()
        };
        let hot_tier = Arc::new(RwLock::new(HotTier::new(hot_tier_config)));
        let access_tracker_config = AccessTrackerConfig {
            min_accesses_for_promotion: 2,
            ..Default::default()
        };
        let access_tracker = Arc::new(RwLock::new(AccessTracker::new(access_tracker_config)));

        let searcher = TieredSearcher::new(
            cache.clone(),
            hot_tier.clone(),
            access_tracker.clone(),
            warm,
            TieredSearcherConfig::default(),
        );

        (searcher, cache, hot_tier, access_tracker)
    }

    fn normalize(v: &mut [f32]) {
        let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            for x in v.iter_mut() {
                *x /= norm;
            }
        }
    }

    #[test]
    fn test_warm_tier_fallback() {
        let warm = Arc::new(MockWarmTier::new());
        let chunk_id = ChunkId::new();
        let mut embedding = vec![1.0, 0.0, 0.0, 0.0];
        normalize(&mut embedding);

        warm.add_chunk(chunk_id.clone(), embedding.clone(), 0.95);

        let (searcher, cache, _, _) = make_searcher_with_warm(warm);
        let tenant = make_tenant();

        let result = searcher.search(&embedding, &tenant, None, 10).unwrap();

        assert!(!result.cache_hit);
        assert!(!result.hot_tier_hit);
        assert_eq!(result.source_tier, SourceTier::Warm);
        assert_eq!(result.results.len(), 1);
        assert_eq!(result.results[0].chunk_id, chunk_id);
        assert_eq!(result.results[0].source_tier, SourceTier::Warm);

        let repeated = searcher.search(&embedding, &tenant, None, 10).unwrap();
        assert!(repeated.cache_hit);
        assert_eq!(repeated.results.len(), 1);
        assert_eq!(cache.get_stats().cache_hits, 1);
    }

    #[test]
    fn test_hot_tier_fallback() {
        let warm = Arc::new(MockWarmTier::new());
        let chunk_id = ChunkId::new();
        let mut embedding = vec![1.0, 0.0, 0.0, 0.0];
        normalize(&mut embedding);

        warm.add_chunk(chunk_id.clone(), embedding.clone(), 0.85);

        let (searcher, _, hot_tier, _) = make_searcher_with_warm(warm);
        let tenant = make_tenant();

        // Manually promote to hot tier
        {
            let ht = hot_tier.write();
            ht.promote(chunk_id.clone(), embedding.clone(), tenant.clone(), 0.9)
                .unwrap();
        }

        let result = searcher.search(&embedding, &tenant, None, 10).unwrap();

        assert!(!result.cache_hit);
        assert!(result.hot_tier_hit);
        assert_eq!(result.source_tier, SourceTier::Hot);
        assert!(!result.results.is_empty());
        // Hot tier result should be present
        let hot_results: Vec<_> = result
            .results
            .iter()
            .filter(|r| r.source_tier == SourceTier::Hot)
            .collect();
        assert!(!hot_results.is_empty(), "Should have hot tier results");
    }

    #[test]
    fn test_cache_hit_fast_path() {
        let warm = Arc::new(MockWarmTier::new());
        let chunk_id = ChunkId::new();
        let mut embedding = vec![1.0, 0.0, 0.0, 0.0];
        normalize(&mut embedding);

        warm.add_chunk(chunk_id.clone(), embedding.clone(), 0.95);

        let (searcher, _, _, _) = make_searcher_with_warm(warm);
        let tenant = make_tenant();

        // First search populates cache
        let result1 = searcher.search(&embedding, &tenant, None, 1).unwrap();
        assert!(!result1.cache_hit);

        // Second search should hit cache
        let result2 = searcher.search(&embedding, &tenant, None, 1).unwrap();
        assert!(result2.cache_hit);
        assert_eq!(result2.source_tier, SourceTier::Cache);
    }

    #[test]
    fn test_cache_respects_increasing_and_decreasing_k() {
        let warm = Arc::new(MockWarmTier::new());
        let embedding = vec![1.0, 0.0, 0.0, 0.0];
        for score in [0.9, 0.8, 0.7] {
            warm.add_chunk(ChunkId::new(), embedding.clone(), score);
        }

        let (searcher, cache, _, _) = make_searcher_with_warm(warm);
        let tenant = make_tenant();

        let small = searcher.search(&embedding, &tenant, None, 1).unwrap();
        assert!(!small.cache_hit);
        assert_eq!(small.results.len(), 1);

        let large = searcher.search(&embedding, &tenant, None, 3).unwrap();
        assert!(!large.cache_hit);
        assert_eq!(large.results.len(), 3);
        let stats = cache.get_stats();
        assert_eq!(stats.cache_hits, 0);
        assert_eq!(stats.cache_misses, 1);

        let medium = searcher.search(&embedding, &tenant, None, 2).unwrap();
        assert!(medium.cache_hit);
        assert_eq!(medium.results.len(), 2);
    }

    #[test]
    fn test_cache_publication_uses_version_captured_before_search() {
        let warm = Arc::new(MockWarmTier::new());
        let old_chunk_id = ChunkId::new();
        let new_chunk_id = ChunkId::new();
        let embedding = vec![1.0, 0.0, 0.0, 0.0];
        warm.add_chunk(old_chunk_id.clone(), embedding.clone(), 0.9);
        *warm.replacement_on_search.write() = Some(vec![SearchResult {
            chunk_id: new_chunk_id.clone(),
            score: 1.0,
        }]);

        let (searcher, _, _, _) = make_searcher_with_warm(warm.clone());
        let tenant = make_tenant();

        let first = searcher.search(&embedding, &tenant, None, 1).unwrap();
        assert!(!first.cache_hit);
        assert_eq!(first.results[0].chunk_id, old_chunk_id);
        assert_eq!(warm.get_version(), 2);

        let second = searcher.search(&embedding, &tenant, None, 1).unwrap();
        assert!(!second.cache_hit);
        assert_eq!(second.results[0].chunk_id, new_chunk_id);
    }

    #[test]
    fn test_promotion_on_repeated_access() {
        let warm = Arc::new(MockWarmTier::new());
        let chunk_id = ChunkId::new();
        let mut embedding = vec![1.0, 0.0, 0.0, 0.0];
        normalize(&mut embedding);

        warm.add_chunk(chunk_id.clone(), embedding.clone(), 0.95);

        // Create searcher with lower promotion threshold for testing
        let cache = Arc::new(SemanticCache::new(SemanticCacheConfig::default()));
        let hot_tier_config = HotTierConfig {
            hnsw_config: crate::index::HnswConfig {
                dimension: 4,
                max_elements: 100,
                ..Default::default()
            },
            ..Default::default()
        };
        let hot_tier = Arc::new(RwLock::new(HotTier::new(hot_tier_config)));
        let access_tracker_config = AccessTrackerConfig {
            min_accesses_for_promotion: 2,
            ..Default::default()
        };
        let access_tracker = Arc::new(RwLock::new(AccessTracker::new(access_tracker_config)));

        let config = TieredSearcherConfig {
            promotion_threshold: 0.3, // Lower threshold for test
            enable_cache: false,      // Disable cache so we hit warm tier each time
            ..Default::default()
        };

        let searcher = TieredSearcher::new(
            cache,
            hot_tier.clone(),
            access_tracker,
            warm.clone(),
            config,
        );
        let tenant = make_tenant();

        // Multiple searches to build up access score
        for _ in 0..3 {
            let _ = searcher.search(&embedding, &tenant, None, 10).unwrap();
        }

        // Run promotions
        let decisions = searcher.check_promotions(&tenant, None);

        // Should have promoted the chunk
        assert!(
            !decisions.is_empty(),
            "Should have promotion decisions after repeated access"
        );
        assert!(hot_tier.read().contains(&chunk_id));
    }

    #[test]
    fn test_demotion_after_inactivity() {
        let warm = Arc::new(MockWarmTier::new());
        let chunk_id = ChunkId::new();
        let mut embedding = vec![1.0, 0.0, 0.0, 0.0];
        normalize(&mut embedding);

        warm.add_chunk(chunk_id.clone(), embedding.clone(), 0.95);

        let cache = Arc::new(SemanticCache::new(SemanticCacheConfig::default()));
        let hot_tier_config = HotTierConfig {
            hnsw_config: crate::index::HnswConfig {
                dimension: 4,
                max_elements: 100,
                ..Default::default()
            },
            ..Default::default()
        };
        let hot_tier = Arc::new(RwLock::new(HotTier::new(hot_tier_config)));
        let access_tracker = Arc::new(RwLock::new(AccessTracker::new(
            AccessTrackerConfig::default(),
        )));

        let config = TieredSearcherConfig {
            promotion_threshold: 0.4,
            demotion_queries_threshold: 5, // Low threshold for test
            enable_cache: false,
            ..Default::default()
        };

        let searcher = TieredSearcher::new(
            cache,
            hot_tier.clone(),
            access_tracker,
            warm.clone(),
            config,
        );
        let tenant = make_tenant();

        // Manually promote to hot tier with low score
        {
            let ht = hot_tier.write();
            ht.promote(chunk_id.clone(), embedding.clone(), tenant.clone(), 0.1)
                .unwrap();
        }

        assert!(hot_tier.read().contains(&chunk_id));

        // Simulate queries without accessing this chunk (search different embedding)
        let mut other_embedding = vec![0.0, 1.0, 0.0, 0.0];
        normalize(&mut other_embedding);
        for _ in 0..6 {
            let _ = searcher.search(&other_embedding, &tenant, None, 10);
        }

        // Check demotions - should find chunk has low score
        let _decisions = searcher.check_demotions(None);

        // Note: The chunk might not be demoted if access tracker doesn't track it
        // since we never searched for it. This test validates the mechanism works.
        // For a real test, we'd need to record some access first then let it decay.
    }

    #[test]
    fn test_project_based_promotion() {
        let warm = Arc::new(MockWarmTier::new());
        let chunk_id = ChunkId::new();
        let mut embedding = vec![1.0, 0.0, 0.0, 0.0];
        normalize(&mut embedding);

        warm.add_chunk(chunk_id.clone(), embedding.clone(), 0.95);

        let cache = Arc::new(SemanticCache::new(SemanticCacheConfig::default()));
        let hot_tier_config = HotTierConfig {
            hnsw_config: crate::index::HnswConfig {
                dimension: 4,
                max_elements: 100,
                ..Default::default()
            },
            ..Default::default()
        };
        let hot_tier = Arc::new(RwLock::new(HotTier::new(hot_tier_config)));
        let access_tracker_config = AccessTrackerConfig {
            min_accesses_for_promotion: 2,
            project_weight: 0.3, // Higher project weight for testing
            ..Default::default()
        };
        let access_tracker = Arc::new(RwLock::new(AccessTracker::new(access_tracker_config)));

        let config = TieredSearcherConfig {
            promotion_threshold: 0.3,
            auto_promote_on_project_match: true,
            enable_cache: false,
            ..Default::default()
        };

        let searcher = TieredSearcher::new(
            cache,
            hot_tier.clone(),
            access_tracker,
            warm.clone(),
            config,
        );
        let tenant = make_tenant();
        let project_id = "my_project";

        // Search with project context multiple times
        for _ in 0..3 {
            let _ = searcher
                .search(&embedding, &tenant, Some(project_id), 10)
                .unwrap();
        }

        // Try auto-promotion
        let decision = searcher.maybe_promote_on_access(&chunk_id, &tenant, Some(project_id));

        // Should have promoted due to project match
        assert!(
            decision.is_some() || hot_tier.read().contains(&chunk_id),
            "Should promote chunk with project context"
        );
    }

    #[test]
    fn test_debug_tier_decisions() {
        let warm = Arc::new(MockWarmTier::new());
        let chunk_id = ChunkId::new();
        let mut embedding = vec![1.0, 0.0, 0.0, 0.0];
        normalize(&mut embedding);

        warm.add_chunk(chunk_id.clone(), embedding.clone(), 0.95);

        let (searcher, _, _, _) = make_searcher_with_warm(warm);
        let tenant = make_tenant();

        // Search with debug enabled
        let result = searcher
            .search_with_debug(&embedding, &tenant, None, 10)
            .unwrap();

        // Should have tier decisions
        assert!(
            !result.tier_decisions.is_empty(),
            "Debug search should have tier decisions"
        );

        // Check that decisions have meaningful content
        for decision in &result.tier_decisions {
            assert!(!decision.reason.is_empty());
            assert!(decision.score.is_some());
        }
    }

    #[test]
    fn test_maintenance_result() {
        let warm = Arc::new(MockWarmTier::new());
        let (searcher, _, _, _) = make_searcher_with_warm(warm);
        let tenant = make_tenant();

        let result = searcher.run_maintenance(&tenant);

        // Maintenance should complete without error
        assert!(result.duration_ms < 1000); // Should be fast
    }

    #[test]
    fn test_query_counter_increments() {
        let warm = Arc::new(MockWarmTier::new());
        let (searcher, _, _, _) = make_searcher_with_warm(warm);
        let tenant = make_tenant();
        let embedding = vec![1.0, 0.0, 0.0, 0.0];

        assert_eq!(searcher.query_count(), 0);

        let _ = searcher.search(&embedding, &tenant, None, 10);
        assert_eq!(searcher.query_count(), 1);

        let _ = searcher.search(&embedding, &tenant, None, 10);
        assert_eq!(searcher.query_count(), 2);
    }
}