repotoire 0.2.17

Graph-powered code analysis CLI
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
//! Architectural bottleneck detector using betweenness centrality
//!
//! Identifies functions that sit on many execution paths (high betweenness),
//! indicating architectural bottlenecks that are critical points of failure.
//!
//! Uses Brandes algorithm for betweenness centrality calculation.

use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphClient;
use crate::models::{Finding, Severity};
use anyhow::Result;
use rayon::prelude::*;
use std::collections::{HashMap, VecDeque};
use tracing::{debug, info};
use uuid::Uuid;

/// Detects architectural bottlenecks using betweenness centrality.
///
/// Functions with high betweenness centrality appear on many shortest paths
/// between other functions, making them critical architectural components.
/// Changes to these functions have high blast radius.
pub struct ArchitecturalBottleneckDetector {
    config: DetectorConfig,
    /// Complexity threshold for severity escalation
    high_complexity_threshold: u32,
}

impl ArchitecturalBottleneckDetector {
    /// Create a new detector with default config
    pub fn new() -> Self {
        Self {
            config: DetectorConfig::new(),
            high_complexity_threshold: 20,
        }
    }

    /// Create with custom config
    pub fn with_config(config: DetectorConfig) -> Self {
        let high_complexity_threshold = config.get_option_or("high_complexity_threshold", 20);
        Self {
            config,
            high_complexity_threshold,
        }
    }

    /// Calculate betweenness centrality using Brandes algorithm (parallelized)
    fn calculate_betweenness(&self, adj: &[Vec<usize>], num_nodes: usize) -> Vec<f64> {
        if num_nodes == 0 {
            return vec![];
        }

        // Run BFS from each source node in parallel
        let partial_scores: Vec<Vec<f64>> = (0..num_nodes)
            .into_par_iter()
            .map(|source| {
                let mut partial = vec![0.0; num_nodes];
                let mut stack = Vec::new();
                let mut predecessors: Vec<Vec<usize>> = vec![vec![]; num_nodes];
                let mut num_paths = vec![0.0; num_nodes];
                num_paths[source] = 1.0;
                let mut distance: Vec<i32> = vec![-1; num_nodes];
                distance[source] = 0;

                let mut queue = VecDeque::new();
                queue.push_back(source);

                // BFS
                while let Some(v) = queue.pop_front() {
                    stack.push(v);
                    for &w in &adj[v] {
                        if distance[w] < 0 {
                            distance[w] = distance[v] + 1;
                            queue.push_back(w);
                        }
                        if distance[w] == distance[v] + 1 {
                            num_paths[w] += num_paths[v];
                            predecessors[w].push(v);
                        }
                    }
                }

                // Backtrack to accumulate dependencies
                let mut dependency = vec![0.0; num_nodes];
                while let Some(w) = stack.pop() {
                    for &v in &predecessors[w] {
                        let contrib = (num_paths[v] / num_paths[w]) * (1.0 + dependency[w]);
                        dependency[v] += contrib;
                    }
                    if w != source {
                        partial[w] += dependency[w];
                    }
                }

                partial
            })
            .collect();

        // Combine partial scores
        let mut betweenness = vec![0.0; num_nodes];
        for partial in partial_scores {
            for (i, score) in partial.into_iter().enumerate() {
                betweenness[i] += score;
            }
        }

        betweenness
    }

    /// Calculate severity based on betweenness percentile and complexity
    fn calculate_severity(
        &self,
        betweenness: f64,
        max_betweenness: f64,
        complexity: u32,
    ) -> Severity {
        let percentile = if max_betweenness > 0.0 {
            (betweenness / max_betweenness) * 100.0
        } else {
            0.0
        };

        if percentile >= 99.0 && complexity > self.high_complexity_threshold {
            Severity::Critical
        } else if percentile >= 99.0
            || (percentile >= 95.0 && complexity > self.high_complexity_threshold)
        {
            Severity::High
        } else if percentile >= 95.0 || complexity > self.high_complexity_threshold {
            Severity::Medium
        } else {
            Severity::Low
        }
    }

    /// Create a finding from a bottleneck
    fn create_finding(
        &self,
        name: &str,
        qualified_name: &str,
        file_path: &str,
        line_number: Option<u32>,
        betweenness: f64,
        max_betweenness: f64,
        avg_betweenness: f64,
        complexity: u32,
    ) -> Finding {
        let severity = self.calculate_severity(betweenness, max_betweenness, complexity);
        let percentile = if max_betweenness > 0.0 {
            (betweenness / max_betweenness) * 100.0
        } else {
            0.0
        };

        let title = if severity == Severity::Critical || severity == Severity::High {
            if complexity > self.high_complexity_threshold {
                format!(
                    "Critical architectural bottleneck with high complexity: {}",
                    name
                )
            } else {
                format!("Critical architectural bottleneck: {}", name)
            }
        } else if complexity > self.high_complexity_threshold {
            format!("Architectural bottleneck with high complexity: {}", name)
        } else {
            format!("Architectural bottleneck: {}", name)
        };

        let mut description = format!(
            "Function `{}` has high betweenness centrality \
            (score: {:.4}, {:.1}th percentile). \
            This indicates it sits on many execution paths between other functions, \
            making it a critical architectural component.\n\n\
            **Risk factors:**\n\
            - High blast radius: Changes here affect many code paths\n\
            - Single point of failure: If this breaks, cascading failures likely\n\
            - Refactoring risk: Difficult to change safely",
            name, betweenness, percentile
        );

        if complexity > self.high_complexity_threshold {
            description.push_str(&format!(
                "\n\n**Additional concern:** High complexity ({}) makes this bottleneck especially risky.",
                complexity
            ));
        }

        let suggested_fix = format!(
            "**Immediate actions:**\n\
            1. Ensure comprehensive test coverage for `{}`\n\
            2. Add defensive error handling and logging\n\
            3. Consider circuit breaker pattern for failure isolation\n\n\
            **Long-term refactoring:**\n\
            1. Analyze why so many paths flow through this function\n\
            2. Consider splitting into multiple specialized functions\n\
            3. Introduce abstraction layers to reduce coupling\n\
            4. Evaluate if functionality can be distributed\n\n\
            **Monitoring:**\n\
            - Add performance monitoring (this is a hot path)\n\
            - Track error rates (failures here cascade)\n\
            - Alert on anomalies",
            name
        );

        let estimated_effort = match severity {
            Severity::Critical => "Large (1-2 days)",
            Severity::High => "Large (4-8 hours)",
            _ => "Medium (2-4 hours)",
        };

        Finding {
            id: Uuid::new_v4().to_string(),
            detector: "ArchitecturalBottleneckDetector".to_string(),
            severity,
            title,
            description,
            affected_files: vec![file_path.into()],
            line_start: line_number,
            line_end: None,
            suggested_fix: Some(suggested_fix),
            estimated_effort: Some(estimated_effort.to_string()),
            category: Some("architecture".to_string()),
            cwe_id: None,
            why_it_matters: Some(
                "Architectural bottlenecks are critical points where failures cascade. \
                High betweenness means many code paths depend on this function, \
                making it risky to change and a potential performance hotspot."
                    .to_string(),
            ),
        }
    }
}

impl Default for ArchitecturalBottleneckDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl Detector for ArchitecturalBottleneckDetector {
    fn name(&self) -> &'static str {
        "ArchitecturalBottleneckDetector"
    }

    fn description(&self) -> &'static str {
        "Detects architectural bottlenecks using betweenness centrality"
    }

    fn category(&self) -> &'static str {
        "architecture"
    }

    fn config(&self) -> Option<&DetectorConfig> {
        Some(&self.config)
    }

    fn detect(&self, graph: &GraphClient) -> Result<Vec<Finding>> {
        debug!("Starting architectural bottleneck detection");

        // Get all functions
        let functions_query = r#"
            MATCH (f:Function)
            RETURN f.qualifiedName AS qualified_name,
                   f.name AS name,
                   f.filePath AS file_path,
                   f.lineStart AS line_number,
                   coalesce(f.complexity, 0) AS complexity
            ORDER BY qualified_name
        "#;
        let functions_result = graph.execute(functions_query)?;

        if functions_result.is_empty() {
            debug!("No functions found in graph");
            return Ok(vec![]);
        }

        // Build function index
        let mut func_to_idx: HashMap<String, usize> = HashMap::new();
        let mut func_data: Vec<(String, String, String, Option<u32>, u32)> = Vec::new();

        for (idx, row) in functions_result.iter().enumerate() {
            if let Some(qname) = row.get("qualified_name").and_then(|v| v.as_str()) {
                func_to_idx.insert(qname.to_string(), idx);
                func_data.push((
                    qname.to_string(),
                    row.get("name")
                        .and_then(|v| v.as_str())
                        .unwrap_or("unknown")
                        .to_string(),
                    row.get("file_path")
                        .and_then(|v| v.as_str())
                        .unwrap_or("unknown")
                        .to_string(),
                    row.get("line_number")
                        .and_then(|v| v.as_i64())
                        .map(|n| n as u32),
                    row.get("complexity").and_then(|v| v.as_i64()).unwrap_or(0) as u32,
                ));
            }
        }

        let num_nodes = func_data.len();
        debug!("Found {} functions", num_nodes);

        // Get call edges
        let edges_query = r#"
            MATCH (caller:Function)-[:CALLS]->(callee:Function)
            RETURN caller.qualifiedName AS src, callee.qualifiedName AS dst
        "#;
        let edges_result = graph.execute(edges_query)?;

        // Build adjacency list
        let mut adj: Vec<Vec<usize>> = vec![vec![]; num_nodes];
        for row in edges_result {
            if let (Some(src), Some(dst)) = (
                row.get("src").and_then(|v| v.as_str()),
                row.get("dst").and_then(|v| v.as_str()),
            ) {
                if let (Some(&src_idx), Some(&dst_idx)) =
                    (func_to_idx.get(src), func_to_idx.get(dst))
                {
                    adj[src_idx].push(dst_idx);
                }
            }
        }

        debug!("Built adjacency list");

        // Calculate betweenness centrality
        let betweenness = self.calculate_betweenness(&adj, num_nodes);

        if betweenness.is_empty() {
            return Ok(vec![]);
        }

        // Calculate statistics
        let max_betweenness = betweenness.iter().cloned().fold(0.0_f64, f64::max);
        let avg_betweenness = betweenness.iter().sum::<f64>() / num_nodes as f64;
        let stdev = if num_nodes > 1 {
            let variance = betweenness
                .iter()
                .map(|&b| (b - avg_betweenness).powi(2))
                .sum::<f64>()
                / num_nodes as f64;
            variance.sqrt()
        } else {
            0.0
        };

        // Threshold: mean + 2*stdev (top ~5%)
        let threshold = avg_betweenness + 2.0 * stdev;

        info!(
            "Betweenness stats: max={:.4}, avg={:.4}, stdev={:.4}, threshold={:.4}",
            max_betweenness, avg_betweenness, stdev, threshold
        );

        // Find bottlenecks (above threshold)
        let mut findings: Vec<Finding> = Vec::new();

        for (idx, &score) in betweenness.iter().enumerate() {
            if score >= threshold && score > 0.0 {
                let (qualified_name, name, file_path, line_number, complexity) = &func_data[idx];
                
                // Skip parser files - they are designed to be central/orchestrating
                if file_path.contains("/parsers/") || file_path.contains("\\parsers\\") {
                    continue;
                }
                
                let finding = self.create_finding(
                    name,
                    qualified_name,
                    file_path,
                    *line_number,
                    score,
                    max_betweenness,
                    avg_betweenness,
                    *complexity,
                );
                findings.push(finding);
            }
        }

        // Sort by severity (highest first)
        findings.sort_by(|a, b| b.severity.cmp(&a.severity));

        // Limit findings
        if let Some(max) = self.config.max_findings {
            findings.truncate(max);
        }

        info!(
            "ArchitecturalBottleneckDetector found {} bottlenecks",
            findings.len()
        );

        Ok(findings)
    }
}

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

    #[test]
    fn test_betweenness_simple_chain() {
        let detector = ArchitecturalBottleneckDetector::new();
        // Chain: 0 -> 1 -> 2 -> 3
        let adj = vec![
            vec![1], // 0
            vec![2], // 1
            vec![3], // 2
            vec![],  // 3
        ];
        let betweenness = detector.calculate_betweenness(&adj, 4);

        // Node 1 and 2 should have highest betweenness (they're in the middle)
        assert!(betweenness[1] > betweenness[0]);
        assert!(betweenness[2] > betweenness[3]);
    }

    #[test]
    fn test_betweenness_star() {
        let detector = ArchitecturalBottleneckDetector::new();
        // Star: 0 is center, connects to 1, 2, 3
        let adj = vec![
            vec![1, 2, 3], // 0 (center)
            vec![0],       // 1
            vec![0],       // 2
            vec![0],       // 3
        ];
        let betweenness = detector.calculate_betweenness(&adj, 4);

        // Center should have highest betweenness
        assert!(betweenness[0] >= betweenness[1]);
        assert!(betweenness[0] >= betweenness[2]);
        assert!(betweenness[0] >= betweenness[3]);
    }

    #[test]
    fn test_severity_calculation() {
        let detector = ArchitecturalBottleneckDetector::new();

        // Very high percentile + high complexity = Critical
        assert_eq!(
            detector.calculate_severity(99.0, 100.0, 25),
            Severity::Critical
        );

        // High percentile alone = High
        assert_eq!(detector.calculate_severity(99.0, 100.0, 10), Severity::High);

        // Moderate percentile + high complexity = Medium
        assert_eq!(detector.calculate_severity(96.0, 100.0, 25), Severity::High);

        // Low percentile, low complexity = Low
        assert_eq!(detector.calculate_severity(50.0, 100.0, 5), Severity::Low);
    }
}