magellan 3.1.9

Deterministic codebase mapping tool for local development
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
//! Metrics operations for CodeGraph
//!
//! Pre-computed metrics (fan-in, fan-out, LOC, complexity) enable fast debug tool queries.
//!
//! # Thread Safety
//!
//! **This module is NOT thread-safe.**
//!
//! `MetricsOps` is designed for single-threaded use only:
//! - All methods require `&mut self` (exclusive access)
//! - Uses separate rusqlite connection to same database file
//! - No `Send` or `Sync` impls
//!
//! # Usage Pattern
//!
//! `MetricsOps` is accessed exclusively through `CodeGraph`, which
//! enforces single-threaded access. The parent `CodeGraph` instance
//! must not be shared across threads.

use anyhow::Result;
use rusqlite::{params, OptionalExtension};
use std::path::Path;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

pub mod backfill;
pub mod compute;
pub mod compute_v3;
pub mod schema;

pub use backfill::BackfillResult;
pub use schema::{FileMetrics, SymbolMetrics};

/// Backend storage for MetricsOps
enum MetricsOpsBackend {
    /// SQLite database path
    Sqlite(std::path::PathBuf),
    /// Shared connection from CodeGraph (avoids opening new connections)
    Shared(Arc<std::sync::Mutex<rusqlite::Connection>>),
    /// SideTables abstraction (V3 backend)
    SideTables(Arc<dyn super::side_tables::SideTables>),
}

/// Metrics operations for CodeGraph
///
/// Uses either:
/// - SQLite connection to database file (legacy)
/// - SideTables trait abstraction (V3 backend)
pub struct MetricsOps {
    backend: MetricsOpsBackend,
}

impl MetricsOps {
    /// Create a new MetricsOps with the given database path
    pub fn new(db_path: &Path) -> Self {
        Self {
            backend: MetricsOpsBackend::Sqlite(db_path.to_path_buf()),
        }
    }

    /// Create a MetricsOps using the SideTables abstraction.
    ///
    /// This constructor is used for V3 backend where we want to avoid SQLite
    /// entirely for side tables.
    pub fn with_side_tables(side_tables: Arc<dyn super::side_tables::SideTables>) -> Self {
        Self {
            backend: MetricsOpsBackend::SideTables(side_tables),
        }
    }

    /// Create a MetricsOps using a shared connection.
    ///
    /// This avoids opening a separate connection to the same database,
    /// reducing connection overhead and WAL contention.
    pub fn with_connection(conn: Arc<std::sync::Mutex<rusqlite::Connection>>) -> Self {
        let metrics = Self {
            backend: MetricsOpsBackend::Shared(conn),
        };
        if let Err(e) = metrics.ensure_schema() {
            eprintln!("Warning: Failed to ensure MetricsOps schema: {}", e);
        }
        metrics
    }

    /// Create an in-memory MetricsOps for testing/stub usage.
    ///
    /// Uses a temporary file so that new connections can access the same data.
    pub fn in_memory() -> Self {
        let temp_dir = std::env::temp_dir();
        let unique_id = format!(
            "{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let db_path = temp_dir.join(format!("magellan_metrics_ops_stub_{}.db", unique_id));

        let metrics = Self {
            backend: MetricsOpsBackend::Sqlite(db_path),
        };

        // Ensure schema exists
        if let Err(e) = metrics.ensure_schema() {
            eprintln!("Warning: Failed to ensure MetricsOps schema: {}", e);
        }

        metrics
    }

    /// Ensure metrics tables exist (creates if new DB)
    pub fn ensure_schema(&self) -> Result<()> {
        match &self.backend {
            MetricsOpsBackend::Sqlite(_) => {
                let conn = self.connect()?;
                crate::graph::db_compat::ensure_metrics_schema(&conn)
                    .map_err(|e| anyhow::anyhow!("Failed to ensure metrics schema: {}", e))
            }
            MetricsOpsBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock().unwrap();
                crate::graph::db_compat::ensure_metrics_schema(&conn)
                    .map_err(|e| anyhow::anyhow!("Failed to ensure metrics schema: {}", e))
            }
            MetricsOpsBackend::SideTables(_) => Ok(()),
        }
    }

    /// Open a connection to the database (SQLite backend only)
    fn connect(&self) -> Result<rusqlite::Connection, rusqlite::Error> {
        match &self.backend {
            MetricsOpsBackend::Sqlite(path) => rusqlite::Connection::open(path),
            MetricsOpsBackend::Shared(_) => Err(rusqlite::Error::InvalidParameterName(
                "Direct SQLite connection not available for shared backend".to_string(),
            )),
            MetricsOpsBackend::SideTables(_) => Err(rusqlite::Error::InvalidParameterName(
                "Metrics not available with V3 backend".to_string(),
            )),
        }
    }

    /// Execute a closure with a connection reference, handling all backends.
    fn with_conn<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce(&rusqlite::Connection) -> Result<R>,
    {
        match &self.backend {
            MetricsOpsBackend::Sqlite(_) => {
                let conn = self.connect()?;
                f(&conn)
            }
            MetricsOpsBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock().unwrap();
                f(&conn)
            }
            MetricsOpsBackend::SideTables(_) => {
                Err(anyhow::anyhow!("Metrics not available with V3 backend"))
            }
        }
    }

    /// Get current Unix timestamp in seconds
    ///
    /// Reserved for future timestamp tracking in metrics operations.
    #[allow(dead_code)]
    fn now() -> i64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64
    }

    /// Upsert file metrics (insert or replace)
    pub fn upsert_file_metrics(&self, metrics: &FileMetrics) -> Result<()> {
        match &self.backend {
            MetricsOpsBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::upsert_file_metrics_conn(&conn, metrics)
            }
            MetricsOpsBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock().unwrap();
                Self::upsert_file_metrics_conn(&conn, metrics)
            }
            MetricsOpsBackend::SideTables(side_tables) => side_tables.store_file_metrics(metrics),
        }
    }

    fn upsert_file_metrics_conn(conn: &rusqlite::Connection, metrics: &FileMetrics) -> Result<()> {
        conn.execute(
            "INSERT OR REPLACE INTO file_metrics (
                file_path, symbol_count, loc, estimated_loc,
                fan_in, fan_out, complexity_score, last_updated
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
            params![
                &metrics.file_path,
                metrics.symbol_count,
                metrics.loc,
                metrics.estimated_loc,
                metrics.fan_in,
                metrics.fan_out,
                metrics.complexity_score,
                metrics.last_updated,
            ],
        )
        .map_err(|e| anyhow::anyhow!("Failed to upsert file metrics: {}", e))?;
        Ok(())
    }

    /// Upsert symbol metrics (insert or replace)
    pub fn upsert_symbol_metrics(&self, metrics: &SymbolMetrics) -> Result<()> {
        match &self.backend {
            MetricsOpsBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::upsert_symbol_metrics_conn(&conn, metrics)
            }
            MetricsOpsBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock().unwrap();
                Self::upsert_symbol_metrics_conn(&conn, metrics)
            }
            MetricsOpsBackend::SideTables(side_tables) => side_tables.store_symbol_metrics(metrics),
        }
    }

    fn upsert_symbol_metrics_conn(
        conn: &rusqlite::Connection,
        metrics: &SymbolMetrics,
    ) -> Result<()> {
        conn.execute(
            "INSERT OR REPLACE INTO symbol_metrics (
                symbol_id, symbol_name, kind, file_path,
                loc, estimated_loc, fan_in, fan_out,
                cyclomatic_complexity, last_updated
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
            params![
                metrics.symbol_id,
                &metrics.symbol_name,
                &metrics.kind,
                &metrics.file_path,
                metrics.loc,
                metrics.estimated_loc,
                metrics.fan_in,
                metrics.fan_out,
                metrics.cyclomatic_complexity,
                metrics.last_updated,
            ],
        )
        .map_err(|e| anyhow::anyhow!("Failed to upsert symbol metrics: {}", e))?;
        Ok(())
    }

    /// Delete all metrics for a file (both file_metrics and symbol_metrics rows)
    pub fn delete_file_metrics(&self, file_path: &str) -> Result<usize> {
        match &self.backend {
            MetricsOpsBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::delete_file_metrics_conn(&conn, file_path)
            }
            MetricsOpsBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock().unwrap();
                Self::delete_file_metrics_conn(&conn, file_path)
            }
            MetricsOpsBackend::SideTables(side_tables) => {
                side_tables.delete_metrics_for_file(file_path)
            }
        }
    }

    fn delete_file_metrics_conn(conn: &rusqlite::Connection, file_path: &str) -> Result<usize> {
        let symbol_count = conn
            .execute(
                "DELETE FROM symbol_metrics WHERE file_path = ?1",
                params![file_path],
            )
            .map_err(|e| anyhow::anyhow!("Failed to delete symbol metrics: {}", e))?;

        conn.execute(
            "DELETE FROM file_metrics WHERE file_path = ?1",
            params![file_path],
        )
        .map_err(|e| anyhow::anyhow!("Failed to delete file metrics: {}", e))?;

        Ok(symbol_count)
    }

    /// Get file metrics by path
    pub fn get_file_metrics(&self, file_path: &str) -> Result<Option<FileMetrics>> {
        match &self.backend {
            MetricsOpsBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::get_file_metrics_conn(&conn, file_path)
            }
            MetricsOpsBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock().unwrap();
                Self::get_file_metrics_conn(&conn, file_path)
            }
            MetricsOpsBackend::SideTables(side_tables) => side_tables.get_file_metrics(file_path),
        }
    }

    fn get_file_metrics_conn(
        conn: &rusqlite::Connection,
        file_path: &str,
    ) -> Result<Option<FileMetrics>> {
        let result = conn
            .query_row(
                "SELECT file_path, symbol_count, loc, estimated_loc,
                        fan_in, fan_out, complexity_score, last_updated
                 FROM file_metrics
                 WHERE file_path = ?1",
                params![file_path],
                |row| {
                    Ok(FileMetrics {
                        file_path: row.get(0)?,
                        symbol_count: row.get(1)?,
                        loc: row.get(2)?,
                        estimated_loc: row.get(3)?,
                        fan_in: row.get(4)?,
                        fan_out: row.get(5)?,
                        complexity_score: row.get(6)?,
                        last_updated: row.get(7)?,
                    })
                },
            )
            .optional()
            .map_err(|e| anyhow::anyhow!("Failed to get file metrics: {}", e))?;

        Ok(result)
    }

    /// Get symbol metrics by symbol_id
    pub fn get_symbol_metrics(&self, symbol_id: i64) -> Result<Option<SymbolMetrics>> {
        match &self.backend {
            MetricsOpsBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::get_symbol_metrics_conn(&conn, symbol_id)
            }
            MetricsOpsBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock().unwrap();
                Self::get_symbol_metrics_conn(&conn, symbol_id)
            }
            MetricsOpsBackend::SideTables(side_tables) => side_tables.get_symbol_metrics(symbol_id),
        }
    }

    fn get_symbol_metrics_conn(
        conn: &rusqlite::Connection,
        symbol_id: i64,
    ) -> Result<Option<SymbolMetrics>> {
        let result = conn
            .query_row(
                "SELECT symbol_id, symbol_name, kind, file_path,
                        loc, estimated_loc, fan_in, fan_out,
                        cyclomatic_complexity, last_updated
                 FROM symbol_metrics
                 WHERE symbol_id = ?1",
                params![symbol_id],
                |row| {
                    Ok(SymbolMetrics {
                        symbol_id: row.get(0)?,
                        symbol_name: row.get(1)?,
                        kind: row.get(2)?,
                        file_path: row.get(3)?,
                        loc: row.get(4)?,
                        estimated_loc: row.get(5)?,
                        fan_in: row.get(6)?,
                        fan_out: row.get(7)?,
                        cyclomatic_complexity: row.get(8)?,
                        last_updated: row.get(9)?,
                    })
                },
            )
            .optional()
            .map_err(|e| anyhow::anyhow!("Failed to get symbol metrics: {}", e))?;

        Ok(result)
    }

    /// Get hotspots (files with highest complexity scores)
    ///
    /// Returns files ordered by complexity_score DESC, optionally filtered by thresholds.
    pub fn get_hotspots(
        &self,
        limit: Option<u32>,
        min_loc: Option<i64>,
        min_fan_in: Option<i64>,
        min_fan_out: Option<i64>,
    ) -> Result<Vec<FileMetrics>> {
        match &self.backend {
            MetricsOpsBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::get_hotspots_conn(&conn, limit, min_loc, min_fan_in, min_fan_out)
            }
            MetricsOpsBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock().unwrap();
                Self::get_hotspots_conn(&conn, limit, min_loc, min_fan_in, min_fan_out)
            }
            MetricsOpsBackend::SideTables(side_tables) => {
                side_tables.get_hotspots(limit, min_loc, min_fan_in, min_fan_out)
            }
        }
    }

    fn get_hotspots_conn(
        conn: &rusqlite::Connection,
        limit: Option<u32>,
        min_loc: Option<i64>,
        min_fan_in: Option<i64>,
        min_fan_out: Option<i64>,
    ) -> Result<Vec<FileMetrics>> {
        let mut query = String::from(
            "SELECT file_path, symbol_count, loc, estimated_loc,
                    fan_in, fan_out, complexity_score, last_updated
             FROM file_metrics
             WHERE 1=1",
        );
        let mut param_count = 0;

        if min_loc.is_some() {
            param_count += 1;
            query.push_str(&format!(" AND loc >= ?{param_count}"));
        }
        if min_fan_in.is_some() {
            param_count += 1;
            query.push_str(&format!(" AND fan_in >= ?{param_count}"));
        }
        if min_fan_out.is_some() {
            param_count += 1;
            query.push_str(&format!(" AND fan_out >= ?{param_count}"));
        }

        param_count += 1;
        query.push_str(&format!(
            " ORDER BY complexity_score DESC LIMIT ?{param_count}"
        ));

        let mut stmt = conn.prepare(&query)?;

        let mut query_params: Vec<Box<dyn rusqlite::types::ToSql>> = Vec::new();

        if let Some(min_loc) = min_loc {
            query_params.push(Box::new(min_loc));
        }
        if let Some(min_fi) = min_fan_in {
            query_params.push(Box::new(min_fi));
        }
        if let Some(min_fo) = min_fan_out {
            query_params.push(Box::new(min_fo));
        }
        query_params.push(Box::new(limit.unwrap_or(20) as i64));

        let param_refs: Vec<&dyn rusqlite::types::ToSql> =
            query_params.iter().map(|p| p.as_ref()).collect();

        let mut rows = stmt.query(&*param_refs)?;

        let mut results = Vec::new();
        while let Some(row) = rows.next()? {
            results.push(FileMetrics {
                file_path: row.get(0)?,
                symbol_count: row.get(1)?,
                loc: row.get(2)?,
                estimated_loc: row.get(3)?,
                fan_in: row.get(4)?,
                fan_out: row.get(5)?,
                complexity_score: row.get(6)?,
                last_updated: row.get(7)?,
            });
        }

        Ok(results)
    }
}

impl MetricsOps {
    /// Compute metrics for a file using V3 graph backend
    ///
    /// This is a V3-specific method that uses graph traversal APIs instead of SQL.
    /// It's separate from the SQLite-based `compute_for_file` to keep both backends working.
    ///
    /// # Arguments
    /// * `backend` - Graph backend for traversing entities and edges
    /// * `file_path` - Path to the file
    /// * `source` - File contents as bytes
    /// * `symbol_facts` - Vector of SymbolNode data for all symbols in the file
    pub fn compute_for_file_v3(
        &self,
        backend: std::sync::Arc<dyn sqlitegraph::GraphBackend>,
        file_path: &str,
        source: &[u8],
        symbol_facts: &[crate::graph::schema::SymbolNode],
    ) -> anyhow::Result<()> {
        use compute_v3::V3MetricsCompute;

        let v3_compute = V3MetricsCompute::new(backend);

        // Create storage callbacks that use SideTables
        let store_fn = |metrics: &FileMetrics| -> anyhow::Result<()> {
            match &self.backend {
                MetricsOpsBackend::SideTables(side_tables) => {
                    side_tables.store_file_metrics(metrics)
                }
                _ => Err(anyhow::anyhow!("V3 compute called with non-V3 backend")),
            }
        };

        let store_symbol_fn = |metrics: &SymbolMetrics| -> anyhow::Result<()> {
            match &self.backend {
                MetricsOpsBackend::SideTables(side_tables) => {
                    side_tables.store_symbol_metrics(metrics)
                }
                _ => Err(anyhow::anyhow!("V3 compute called with non-V3 backend")),
            }
        };

        v3_compute.compute_for_file(file_path, source, symbol_facts, store_fn, store_symbol_fn)
    }
}

pub mod query {
    //! Public query functions for metrics

    use super::schema::{FileMetrics, SymbolMetrics};
    use super::MetricsOps;
    use anyhow::Result;

    /// Get file metrics by path (public wrapper)
    pub fn get_file_metrics(metrics: &MetricsOps, file_path: &str) -> Result<Option<FileMetrics>> {
        metrics.get_file_metrics(file_path)
    }

    /// Get symbol metrics by symbol_id (public wrapper)
    pub fn get_symbol_metrics(
        metrics: &MetricsOps,
        symbol_id: i64,
    ) -> Result<Option<SymbolMetrics>> {
        metrics.get_symbol_metrics(symbol_id)
    }

    /// Get hotspots with optional filters (public wrapper)
    pub fn get_hotspots(
        metrics: &MetricsOps,
        limit: Option<u32>,
        min_loc: Option<i64>,
        min_fan_in: Option<i64>,
        min_fan_out: Option<i64>,
    ) -> Result<Vec<FileMetrics>> {
        metrics.get_hotspots(limit, min_loc, min_fan_in, min_fan_out)
    }
}

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