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