Skip to main content

vtcode_core/tools/
grep_cache.rs

1//! Caching layer for grep file search results to avoid redundant searches
2//!
3//! This module provides a cache for search results, keyed by search parameters
4//! to eliminate duplicate searches for identical patterns and paths.
5//!
6//! Uses `UnifiedCache` from `crate::cache` for LRU eviction, TTL, and stats.
7
8use super::grep_backend::MAX_SEARCH_RESULTS;
9use super::grep_file::{GrepSearchInput, GrepSearchResult};
10use crate::cache::{CacheKey, DEFAULT_CACHE_TTL, EvictionPolicy, UnifiedCache, estimate_json_size};
11use std::sync::Arc;
12
13/// Cache key for search results - includes all parameters that affect search results
14#[derive(Debug, Clone, Hash, PartialEq, Eq)]
15struct SearchCacheKey {
16    pattern: String,
17    path: String,
18    case_sensitive: Option<bool>,
19    literal: bool,
20    glob_pattern: Option<String>,
21    include_hidden: bool,
22    max_results: usize,
23    respect_ignore_files: bool,
24    max_file_size: Option<usize>,
25    files_with_matches: bool,
26    max_result_bytes: Option<usize>,
27    extra_ignore_globs: Option<Vec<String>>,
28}
29
30impl CacheKey for SearchCacheKey {
31    fn to_cache_key(&self) -> String {
32        // Encode every discriminating field so `remove_where` prefix/suffix/
33        // contains invalidation buckets entries correctly. The previous key
34        // omitted 7 fields, so invalidation could drop or retain the wrong
35        // entries for queries that differed only in those fields.
36        [
37            "grep",
38            self.pattern.as_str(),
39            self.path.as_str(),
40            &format!("{:?}", self.case_sensitive),
41            &self.literal.to_string(),
42            &format!("{:?}", self.glob_pattern),
43            &self.include_hidden.to_string(),
44            &self.max_results.to_string(),
45            &self.respect_ignore_files.to_string(),
46            &format!("{:?}", self.max_file_size),
47            &self.files_with_matches.to_string(),
48            &format!("{:?}", self.max_result_bytes),
49            &format!("{:?}", self.extra_ignore_globs),
50        ]
51        .join("\u{1f}")
52    }
53}
54
55impl From<&GrepSearchInput> for SearchCacheKey {
56    fn from(input: &GrepSearchInput) -> Self {
57        Self {
58            pattern: input.pattern.clone(),
59            path: input.path.clone(),
60            // The case mode distinguishes smart-case from always-insensitive,
61            // so the raw option is kept rather than collapsed to a bool.
62            case_sensitive: input.case_sensitive,
63            literal: input.literal.unwrap_or(false),
64            glob_pattern: input.glob_pattern.clone(),
65            include_hidden: input.include_hidden.unwrap_or(false),
66            max_results: input.max_results.unwrap_or(MAX_SEARCH_RESULTS.get()),
67            respect_ignore_files: input.respect_ignore_files.unwrap_or(true),
68            max_file_size: input.max_file_size,
69            files_with_matches: input.files_with_matches.unwrap_or(false),
70            max_result_bytes: input.max_result_bytes,
71            extra_ignore_globs: input.extra_ignore_globs.clone(),
72        }
73    }
74}
75
76/// Thread-safe cache for search results backed by `UnifiedCache`
77pub struct GrepSearchCache {
78    cache: UnifiedCache<SearchCacheKey, GrepSearchResult>,
79}
80
81impl GrepSearchCache {
82    /// Create a new cache with the specified capacity
83    pub fn new(capacity: usize) -> Self {
84        Self {
85            cache: UnifiedCache::new(capacity, DEFAULT_CACHE_TTL, EvictionPolicy::Lru),
86        }
87    }
88
89    /// Get cached result if available
90    pub fn get(&self, input: &GrepSearchInput) -> Option<Arc<GrepSearchResult>> {
91        let key = SearchCacheKey::from(input);
92        self.cache.get(&key)
93    }
94
95    /// Cache a search result
96    pub fn put(&self, input: &GrepSearchInput, result: GrepSearchResult) {
97        let key = SearchCacheKey::from(input);
98        let size_bytes = size_of::<GrepSearchResult>() as u64
99            + result.query.len() as u64
100            + result.matches.iter().map(estimate_json_size).sum::<u64>();
101        self.cache.insert(key, result, size_bytes);
102    }
103
104    /// Check if this search should be cached (only results with real hits).
105    ///
106    /// `GrepSearchResult::matches` holds raw search-backend JSON stream events, so
107    /// a no-hit search is still non-empty: it carries the per-file
108    /// `begin`/`end` records and the final `summary`. Caching those would
109    /// turn every miss into a stale silent negative — the cache has no
110    /// file-change invalidation (TTL and LRU eviction only), so matches
111    /// created within the TTL window would stay hidden. Only searches with
112    /// at least one `match`-type event are cached: a stale positive at least
113    /// surfaces old hits the agent can notice when opening the file, while a
114    /// stale negative hides new ones with no signal. Repeated no-match
115    /// queries therefore re-run the search — the accepted cost until the cache
116    /// gains a write-path invalidation hook.
117    pub fn should_cache(result: &GrepSearchResult) -> bool {
118        result
119            .matches
120            .iter()
121            .any(|entry| entry.get("type").and_then(serde_json::Value::as_str) == Some("match"))
122    }
123
124    /// Clear the cache
125    pub fn clear(&self) {
126        self.cache.clear();
127    }
128
129    /// Get cache statistics
130    pub fn stats(&self) -> (usize, usize) {
131        let stats = self.cache.stats();
132        (stats.current_size, stats.max_size)
133    }
134}
135
136impl Default for GrepSearchCache {
137    fn default() -> Self {
138        Self::new(100) // Default to 100 entries
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    fn make_test_input(pattern: &str, path: &str) -> GrepSearchInput {
147        GrepSearchInput {
148            pattern: pattern.to_string(),
149            path: path.to_string(),
150            case_sensitive: Some(true),
151            literal: None,
152            glob_pattern: Some("*.rs".to_string()),
153            include_hidden: None,
154            max_results: Some(5), // AGENTS.md requires max 5 results
155            respect_ignore_files: None,
156            max_file_size: None,
157            files_with_matches: None,
158            max_result_bytes: None,
159            timeout: None,
160            extra_ignore_globs: None,
161        }
162    }
163
164    #[test]
165    fn test_cache_key_equality() {
166        let input1 = make_test_input("test", "/path");
167        let input2 = make_test_input("test", "/path");
168
169        let key1 = SearchCacheKey::from(&input1);
170        let key2 = SearchCacheKey::from(&input2);
171        assert_eq!(key1, key2);
172    }
173
174    #[test]
175    fn test_cache_operations() {
176        let cache = GrepSearchCache::new(10);
177
178        let input = make_test_input("test", "/path");
179
180        let result = GrepSearchResult {
181            query: "test".to_string(),
182            matches: vec![serde_json::json!({"file": "test.rs", "line": 1})],
183            truncated: false,
184            total_matches: None,
185        };
186
187        // Cache miss
188        assert!(cache.get(&input).is_none());
189
190        // Cache result
191        cache.put(&input, result.clone());
192
193        // Cache hit
194        let cached = cache.get(&input).unwrap();
195        assert_eq!(cached.query, result.query);
196        assert_eq!(cached.matches.len(), result.matches.len());
197        assert_eq!(cached.truncated, result.truncated);
198    }
199
200    #[test]
201    fn empty_results_are_not_cached_so_stale_negatives_cannot_mask_new_matches() {
202        let cache = GrepSearchCache::new(10);
203        let input = make_test_input("never-matches", "/path");
204        let result = GrepSearchResult {
205            query: "never-matches".to_string(),
206            matches: vec![],
207            truncated: false,
208            total_matches: None,
209        };
210
211        // The cache has no file-change invalidation (TTL/LRU only), so a
212        // cached miss would silently hide matches created inside the TTL
213        // window. A bare empty result must fail the caching gate.
214        assert!(!GrepSearchCache::should_cache(&result));
215
216        // A no-hit search is NOT empty: the backend keeps the
217        // per-file begin/end (and summary) stream events in `matches`.
218        // Those alone must also fail the gate — this is the shape a real
219        // miss actually arrives in.
220        let no_hit_events = GrepSearchResult {
221            matches: vec![
222                serde_json::json!({"type": "begin", "data": {"path": {"text": "/ws/a.rs"}}}),
223                serde_json::json!({"type": "end", "data": {"path": {"text": "/ws/a.rs"}}}),
224            ],
225            ..result.clone()
226        };
227        assert!(!GrepSearchCache::should_cache(&no_hit_events));
228
229        // A result carrying at least one real `match` event stays cacheable
230        // and round-trips: the gate is match presence, not event count.
231        let with_matches = GrepSearchResult {
232            matches: vec![serde_json::json!({
233                "type": "match",
234                "data": {"path": {"text": "/ws/a.rs"}, "lines": {"text": "needle\n"}, "line_number": 1}
235            })],
236            ..result.clone()
237        };
238        assert!(GrepSearchCache::should_cache(&with_matches));
239
240        cache.put(&input, with_matches);
241        let cached = cache.get(&input).expect("result with a real match must be served from cache");
242        assert_eq!(cached.matches.len(), 1);
243    }
244}