Skip to main content

vtcode_core/tools/
search_metrics.rs

1/// Search operation metrics and optimization
2///
3/// Tracks token cost of search results to enable intelligent caching,
4/// sampling, and summarization of expensive searches in large codebases.
5use hashbrown::HashMap;
6use vtcode_commons::tokens::heuristic_tokens_from_byte_len;
7
8/// Metrics for a single search operation
9#[derive(Debug, Clone)]
10pub struct SearchMetric {
11    /// Search pattern used
12    pub pattern: String,
13    /// Number of matches found
14    pub match_count: usize,
15    /// Estimated tokens for results
16    pub result_tokens: usize,
17    /// Time to execute search
18    pub duration_ms: u64,
19    /// Files searched
20    pub files_searched: usize,
21    /// Whether search was expensive (high token cost)
22    pub is_expensive: bool,
23}
24
25/// Tracks search operation metrics for optimization
26#[derive(Debug, Clone)]
27pub struct SearchMetrics {
28    /// All recorded searches indexed by pattern
29    searches: HashMap<String, SearchMetric>,
30    /// Total token cost of all searches
31    pub total_tokens: usize,
32    /// Total searches executed
33    pub total_searches: usize,
34    /// Token threshold for "expensive" searches (default: 10000)
35    expensive_threshold: usize,
36}
37
38impl Default for SearchMetrics {
39    fn default() -> Self {
40        Self::new()
41    }
42}
43
44impl SearchMetrics {
45    /// Create new search metrics tracker
46    pub fn new() -> Self {
47        Self {
48            searches: HashMap::new(),
49            total_tokens: 0,
50            total_searches: 0,
51            expensive_threshold: 10000,
52        }
53    }
54
55    /// Set token threshold for expensive searches
56    pub fn with_expensive_threshold(mut self, threshold: usize) -> Self {
57        self.expensive_threshold = threshold;
58        self
59    }
60
61    /// Record a search operation
62    pub fn record_search(
63        &mut self,
64        pattern: &str,
65        match_count: usize,
66        result_chars: usize,
67        duration_ms: u64,
68        files_searched: usize,
69    ) {
70        // Estimate tokens from the character count with the canonical heuristic.
71        let estimated_tokens = heuristic_tokens_from_byte_len(result_chars);
72        let is_expensive = estimated_tokens > self.expensive_threshold;
73
74        let metric = SearchMetric {
75            pattern: pattern.to_owned(),
76            match_count,
77            result_tokens: estimated_tokens,
78            duration_ms,
79            files_searched,
80            is_expensive,
81        };
82
83        self.total_tokens += estimated_tokens;
84        self.total_searches += 1;
85        self.searches.insert(pattern.to_owned(), metric);
86    }
87
88    /// Get metric for a specific pattern
89    pub fn get_search(&self, pattern: &str) -> Option<&SearchMetric> {
90        self.searches.get(pattern)
91    }
92
93    /// Find most expensive searches
94    pub fn expensive_searches(&self, limit: usize) -> Vec<&SearchMetric> {
95        let mut searches: Vec<_> = self.searches.values().filter(|s| s.is_expensive).collect();
96        searches.sort_by_key(|a| std::cmp::Reverse(a.result_tokens));
97        searches.into_iter().take(limit).collect()
98    }
99
100    /// Find slowest searches
101    pub fn slowest_searches(&self, limit: usize) -> Vec<&SearchMetric> {
102        let mut searches: Vec<_> = self.searches.values().collect();
103        searches.sort_by_key(|a| std::cmp::Reverse(a.duration_ms));
104        searches.into_iter().take(limit).collect()
105    }
106
107    /// Calculate average tokens per search
108    pub fn avg_tokens_per_search(&self) -> f64 {
109        if self.total_searches == 0 {
110            0.0
111        } else {
112            self.total_tokens as f64 / self.total_searches as f64
113        }
114    }
115
116    /// Check if search should be sampled (too many results)
117    pub fn should_sample_results(&self, pattern: &str) -> bool {
118        self.get_search(pattern).map(|m| m.is_expensive).unwrap_or(false)
119    }
120
121    /// Estimate sampling ratio for expensive search
122    ///
123    /// Returns a value between 0.1 (10% of results) and 1.0 (no sampling)
124    pub fn estimate_sampling_ratio(&self, pattern: &str) -> f64 {
125        if let Some(metric) = self.get_search(pattern) {
126            if !metric.is_expensive {
127                return 1.0;
128            }
129
130            // Linear interpolation: at threshold = 1.0, at 2x threshold = 0.1
131            let ratio = self.expensive_threshold as f64 / metric.result_tokens as f64;
132            (ratio * 0.9 + 0.1).clamp(0.1, 1.0)
133        } else {
134            1.0 // No sampling if not tracked
135        }
136    }
137
138    /// Format metrics for display
139    pub fn format_summary(&self) -> String {
140        use std::fmt::Write;
141        // Pre-allocate with reasonable estimate for metrics summary
142        let mut output = String::with_capacity(512);
143        output.push_str("[SEARCH] Metrics Summary\n");
144        let _ = writeln!(output, "  Total searches: {}", self.total_searches);
145        let _ = writeln!(output, "  Total tokens: {}", self.total_tokens);
146        let _ = writeln!(output, "  Avg tokens/search: {:.0}", self.avg_tokens_per_search());
147        let _ = writeln!(output, "  Expensive searches: {}", self.searches.values().filter(|s| s.is_expensive).count());
148
149        let expensive = self.expensive_searches(3);
150        if !expensive.is_empty() {
151            output.push_str("\n  Most expensive searches:\n");
152            for (i, metric) in expensive.iter().enumerate() {
153                let _ = writeln!(
154                    output,
155                    "    {}. '{}': {} tokens ({} matches)",
156                    i + 1,
157                    metric.pattern,
158                    metric.result_tokens,
159                    metric.match_count
160                );
161            }
162        }
163
164        output
165    }
166
167    /// Clear all metrics
168    pub fn reset(&mut self) {
169        self.searches.clear();
170        self.total_tokens = 0;
171        self.total_searches = 0;
172    }
173
174    /// Get stats for monitoring
175    pub fn stats(&self) -> SearchMetricsStats {
176        let expensive_count = self.searches.values().filter(|s| s.is_expensive).count();
177        SearchMetricsStats {
178            total_searches: self.total_searches,
179            total_tokens: self.total_tokens,
180            expensive_searches: expensive_count,
181            avg_tokens_per_search: self.avg_tokens_per_search(),
182        }
183    }
184}
185
186/// Statistics for search metrics
187#[derive(Debug, Clone)]
188pub struct SearchMetricsStats {
189    pub total_searches: usize,
190    pub total_tokens: usize,
191    pub expensive_searches: usize,
192    pub avg_tokens_per_search: f64,
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn test_creates_metrics() {
201        let metrics = SearchMetrics::new();
202        assert_eq!(metrics.total_searches, 0);
203        assert_eq!(metrics.total_tokens, 0);
204    }
205
206    #[test]
207    fn test_records_search() {
208        let mut metrics = SearchMetrics::new();
209        metrics.record_search("fn main", 5, 1000, 10, 3);
210
211        assert_eq!(metrics.total_searches, 1);
212        assert!(metrics.total_tokens > 0);
213
214        let metric = metrics.get_search("fn main").unwrap();
215        assert_eq!(metric.match_count, 5);
216        assert_eq!(metric.files_searched, 3);
217    }
218
219    #[test]
220    fn test_identifies_expensive_searches() {
221        let mut metrics = SearchMetrics::new().with_expensive_threshold(5000);
222        // This will be expensive (12500 tokens estimated)
223        metrics.record_search("common_pattern", 100, 50000, 50, 50);
224
225        let metric = metrics.get_search("common_pattern").unwrap();
226        assert!(metric.is_expensive);
227    }
228
229    #[test]
230    fn test_expensive_searches() {
231        let mut metrics = SearchMetrics::new().with_expensive_threshold(5000);
232        metrics.record_search("pattern1", 10, 25000, 20, 5);
233        metrics.record_search("pattern2", 5, 2000, 10, 2);
234        metrics.record_search("pattern3", 50, 30000, 100, 20);
235
236        let expensive = metrics.expensive_searches(2);
237        assert_eq!(expensive.len(), 2);
238        assert!(expensive[0].result_tokens > expensive[1].result_tokens);
239    }
240
241    #[test]
242    fn test_slowest_searches() {
243        let mut metrics = SearchMetrics::new();
244        metrics.record_search("fast", 10, 1000, 5, 2);
245        metrics.record_search("slow", 10, 1000, 100, 2);
246        metrics.record_search("medium", 10, 1000, 50, 2);
247
248        let slowest = metrics.slowest_searches(2);
249        assert_eq!(slowest.len(), 2);
250        assert!(slowest[0].duration_ms > slowest[1].duration_ms);
251    }
252
253    #[test]
254    fn test_sampling_ratio() {
255        let mut metrics = SearchMetrics::new().with_expensive_threshold(10000);
256
257        // Non-expensive search should not be sampled
258        metrics.record_search("cheap", 10, 5000, 10, 5);
259        assert!((metrics.estimate_sampling_ratio("cheap") - 1.0).abs() < f64::EPSILON);
260
261        // Expensive search should be sampled
262        metrics.record_search("expensive", 100, 50000, 100, 50);
263        let ratio = metrics.estimate_sampling_ratio("expensive");
264        assert!(ratio < 1.0);
265        assert!(ratio >= 0.1);
266    }
267
268    #[test]
269    fn test_average_tokens() {
270        let mut metrics = SearchMetrics::new();
271        metrics.record_search("search1", 10, 4000, 10, 5);
272        metrics.record_search("search2", 5, 8000, 20, 3);
273
274        let avg = metrics.avg_tokens_per_search();
275        assert!(avg > 0.0);
276        // Should be approximately (1000 + 2000) / 2 = 1500
277    }
278
279    #[test]
280    fn test_should_sample_results() {
281        let mut metrics = SearchMetrics::new().with_expensive_threshold(5000);
282        metrics.record_search("cheap", 10, 2000, 10, 5);
283        metrics.record_search("expensive", 100, 50000, 100, 50);
284
285        assert!(!metrics.should_sample_results("cheap"));
286        assert!(metrics.should_sample_results("expensive"));
287    }
288
289    #[test]
290    fn test_format_summary() {
291        let mut metrics = SearchMetrics::new();
292        metrics.record_search("pattern1", 10, 4000, 10, 5);
293
294        let summary = metrics.format_summary();
295        assert!(summary.contains("[SEARCH] Metrics Summary"));
296        assert!(summary.contains("Total searches: 1"));
297    }
298
299    #[test]
300    fn test_reset() {
301        let mut metrics = SearchMetrics::new();
302        metrics.record_search("pattern1", 10, 4000, 10, 5);
303
304        metrics.reset();
305        assert_eq!(metrics.total_searches, 0);
306        assert_eq!(metrics.total_tokens, 0);
307        assert!(metrics.get_search("pattern1").is_none());
308    }
309
310    #[test]
311    fn test_stats() {
312        let mut metrics = SearchMetrics::new().with_expensive_threshold(5000);
313        metrics.record_search("cheap", 10, 2000, 10, 5);
314        metrics.record_search("expensive", 100, 50000, 100, 50);
315
316        let stats = metrics.stats();
317        assert_eq!(stats.total_searches, 2);
318        assert_eq!(stats.expensive_searches, 1);
319        assert!(stats.avg_tokens_per_search > 0.0);
320    }
321}