magellan 4.12.3

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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! Telemetry operations for tracking performance metrics
//!
//! Records fine-grained timing events (phase start/end), counters, and gauges
//! associated with execution IDs. Provides both historical querying (SQLite)
//! and real-time access (in-memory ring buffer).

use anyhow::Result;
use rusqlite::{params, OptionalExtension};
use std::collections::VecDeque;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

/// Best-effort telemetry guard: once a telemetry write fails, we warn exactly
/// once per process. Telemetry is non-essential instrumentation — it must never
/// abort a read/query command (see B-1). This flag suppresses log spam while
/// keeping every subsequent write attempt best-effort (cheap atomic load).
static TELEMETRY_WARNED: AtomicBool = AtomicBool::new(false);

/// Telemetry event types
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum TelemetryEventType {
    PhaseStart,
    PhaseEnd,
    Counter,
    Gauge,
}

impl TelemetryEventType {
    pub fn as_str(&self) -> &'static str {
        match self {
            TelemetryEventType::PhaseStart => "phase_start",
            TelemetryEventType::PhaseEnd => "phase_end",
            TelemetryEventType::Counter => "counter",
            TelemetryEventType::Gauge => "gauge",
        }
    }
}

impl std::str::FromStr for TelemetryEventType {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "phase_start" => Ok(TelemetryEventType::PhaseStart),
            "phase_end" => Ok(TelemetryEventType::PhaseEnd),
            "counter" => Ok(TelemetryEventType::Counter),
            "gauge" => Ok(TelemetryEventType::Gauge),
            _ => Err(format!("Unknown telemetry event type: {}", s)),
        }
    }
}

/// A single telemetry event
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TelemetryEvent {
    pub id: i64,
    pub execution_id: String,
    pub event_type: TelemetryEventType,
    pub event_name: String,
    pub timestamp_ns: i64,
    pub duration_ns: Option<i64>,
    pub value: Option<f64>,
    pub unit: Option<String>,
    pub metadata: Option<serde_json::Value>,
}

/// Default ring buffer capacity for real-time telemetry
const DEFAULT_RING_BUFFER_CAPACITY: usize = 10_000;

/// Backend storage for TelemetryOps
enum TelemetryBackend {
    /// SQLite database path (opens new connection per operation)
    Sqlite(std::path::PathBuf),
    /// Shared connection from CodeGraph (avoids opening new connections)
    Shared(Arc<parking_lot::Mutex<rusqlite::Connection>>),
}

/// Telemetry operations for tracking performance metrics
///
/// Uses either:
/// - SQLite connection to database file
/// - Shared connection from CodeGraph
pub struct TelemetryOps {
    backend: TelemetryBackend,
    /// In-memory ring buffer for real-time access to recent events
    ring_buffer: Arc<parking_lot::Mutex<VecDeque<TelemetryEvent>>>,
    /// Maximum number of events to keep in the ring buffer
    ring_capacity: usize,
}

impl TelemetryOps {
    /// Create a new TelemetryOps with the given database path
    pub fn new(db_path: &Path) -> Self {
        Self {
            backend: TelemetryBackend::Sqlite(db_path.to_path_buf()),
            ring_buffer: Arc::new(parking_lot::Mutex::new(VecDeque::with_capacity(
                DEFAULT_RING_BUFFER_CAPACITY,
            ))),
            ring_capacity: DEFAULT_RING_BUFFER_CAPACITY,
        }
    }

    /// Create a TelemetryOps using a shared connection
    ///
    /// This eliminates redundant connection opens by reusing CodeGraph's side_conn
    pub fn with_connection(conn: Arc<parking_lot::Mutex<rusqlite::Connection>>) -> Self {
        let ops = Self {
            backend: TelemetryBackend::Shared(conn),
            ring_buffer: Arc::new(parking_lot::Mutex::new(VecDeque::with_capacity(
                DEFAULT_RING_BUFFER_CAPACITY,
            ))),
            ring_capacity: DEFAULT_RING_BUFFER_CAPACITY,
        };
        if let Err(e) = ops.ensure_schema() {
            eprintln!("Warning: Failed to ensure TelemetryOps schema: {}", e);
        }
        ops
    }

    /// Create an in-memory TelemetryOps for testing/stub usage
    #[cfg(test)]
    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)
                .expect("SystemTime before UNIX_EPOCH")
                .as_nanos()
        );
        let db_path = temp_dir.join(format!("magellan_telemetry_stub_{}.db", unique_id));

        let ops = Self {
            backend: TelemetryBackend::Sqlite(db_path),
            ring_buffer: Arc::new(parking_lot::Mutex::new(VecDeque::with_capacity(
                DEFAULT_RING_BUFFER_CAPACITY,
            ))),
            ring_capacity: DEFAULT_RING_BUFFER_CAPACITY,
        };

        if let Err(e) = ops.ensure_schema() {
            eprintln!("Warning: Failed to ensure TelemetryOps schema: {}", e);
        }

        ops
    }

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

    fn ensure_schema_sqlite(conn: &rusqlite::Connection) -> Result<(), anyhow::Error> {
        conn.execute(
            "CREATE TABLE IF NOT EXISTS telemetry_events (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                execution_id TEXT NOT NULL,
                event_type TEXT NOT NULL,
                event_name TEXT NOT NULL,
                timestamp_ns INTEGER NOT NULL,
                duration_ns INTEGER,
                value REAL,
                unit TEXT,
                metadata TEXT
            )",
            [],
        )
        .map_err(|e| anyhow::anyhow!("Failed to create telemetry_events table: {}", e))?;

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_telemetry_events_execution
             ON telemetry_events(execution_id)",
            [],
        )
        .map_err(|e| anyhow::anyhow!("Failed to create execution index: {}", e))?;

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_telemetry_events_type_name
             ON telemetry_events(event_type, event_name)",
            [],
        )
        .map_err(|e| anyhow::anyhow!("Failed to create type_name index: {}", e))?;

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_telemetry_events_timestamp
             ON telemetry_events(timestamp_ns)",
            [],
        )
        .map_err(|e| anyhow::anyhow!("Failed to create timestamp index: {}", e))?;

        Ok(())
    }

    pub fn ensure_schema(&self) -> Result<()> {
        match &self.backend {
            TelemetryBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::ensure_schema_sqlite(&conn)
            }
            TelemetryBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock();
                Self::ensure_schema_sqlite(&conn)
            }
        }
    }

    fn now_ns() -> i64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos() as i64
    }

    fn push_to_ring(&self, event: TelemetryEvent) {
        let mut buf = self.ring_buffer.lock();
        if buf.len() >= self.ring_capacity {
            buf.pop_front();
        }
        buf.push_back(event);
    }

    #[allow(
        clippy::too_many_arguments,
        reason = "event insertion mirrors telemetry_events table columns"
    )]
    fn insert_event_sqlite(
        conn: &rusqlite::Connection,
        execution_id: &str,
        event_type: TelemetryEventType,
        event_name: &str,
        timestamp_ns: i64,
        duration_ns: Option<i64>,
        value: Option<f64>,
        unit: Option<&str>,
        metadata: Option<&serde_json::Value>,
    ) -> Result<i64> {
        let metadata_str = metadata.map(|m| m.to_string());
        conn.execute(
            "INSERT INTO telemetry_events
                (execution_id, event_type, event_name, timestamp_ns, duration_ns, value, unit, metadata)
                VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
            params![
                execution_id,
                event_type.as_str(),
                event_name,
                timestamp_ns,
                duration_ns,
                value,
                unit,
                metadata_str.as_deref(),
            ],
        )
        .map_err(|e| anyhow::anyhow!("Failed to insert telemetry event: {}", e))?;

        Ok(conn.last_insert_rowid())
    }

    #[allow(
        clippy::too_many_arguments,
        reason = "public helper forwards telemetry_events fields to the backend"
    )]
    fn insert_event(
        &self,
        execution_id: &str,
        event_type: TelemetryEventType,
        event_name: &str,
        timestamp_ns: i64,
        duration_ns: Option<i64>,
        value: Option<f64>,
        unit: Option<&str>,
        metadata: Option<&serde_json::Value>,
    ) -> Result<i64> {
        // B-1: Telemetry is best-effort instrumentation. A corrupted telemetry_events
        // table, locked WAL, or full disk must NEVER abort the host command. All five
        // public record_* methods funnel through here, so catching the failure at this
        // single chokepoint fixes the entire class (130+ call sites) at once.
        let row_id = match &self.backend {
            TelemetryBackend::Sqlite(_) => match self.connect() {
                Ok(conn) => match Self::insert_event_sqlite(
                    &conn,
                    execution_id,
                    event_type,
                    event_name,
                    timestamp_ns,
                    duration_ns,
                    value,
                    unit,
                    metadata,
                ) {
                    Ok(id) => id,
                    Err(e) => return Ok(Self::swallow_telemetry_error(e)),
                },
                Err(e) => return Ok(Self::swallow_telemetry_error(anyhow::anyhow!(e))),
            },
            TelemetryBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock();
                match Self::insert_event_sqlite(
                    &conn,
                    execution_id,
                    event_type,
                    event_name,
                    timestamp_ns,
                    duration_ns,
                    value,
                    unit,
                    metadata,
                ) {
                    Ok(id) => id,
                    Err(e) => return Ok(Self::swallow_telemetry_error(e)),
                }
            }
        };

        // Push to ring buffer for real-time access
        self.push_to_ring(TelemetryEvent {
            id: row_id,
            execution_id: execution_id.to_string(),
            event_type,
            event_name: event_name.to_string(),
            timestamp_ns,
            duration_ns,
            value,
            unit: unit.map(|s| s.to_string()),
            metadata: metadata.cloned(),
        });

        Ok(row_id)
    }

    /// Swallow a telemetry write failure: warn once per process, return sentinel
    /// row id 0. Callers propagate `Ok(0)` so their `?` is a no-op — telemetry
    /// never aborts the host command.
    fn swallow_telemetry_error(e: anyhow::Error) -> i64 {
        if !TELEMETRY_WARNED.swap(true, Ordering::Relaxed) {
            eprintln!(
                "Warning: telemetry write failed (subsequent failures suppressed): {}",
                e
            );
        }
        0
    }

    /// Record the start of a phase
    pub fn record_phase_start(&self, execution_id: &str, phase: &str) -> Result<i64> {
        self.insert_event(
            execution_id,
            TelemetryEventType::PhaseStart,
            phase,
            Self::now_ns(),
            None,
            None,
            None,
            None,
        )
    }

    /// Record the end of a phase
    ///
    /// Computes duration by looking up the matching phase_start event.
    /// The duration lookup is best-effort: if it fails (corrupted table,
    /// connection error), duration is recorded as `None` rather than aborting.
    pub fn record_phase_end(&self, execution_id: &str, phase: &str) -> Result<i64> {
        let end_ns = Self::now_ns();

        // Find the matching phase_start to compute duration. Best-effort: a
        // failure here means we lose the duration value, not the whole event.
        let start_ns = match &self.backend {
            TelemetryBackend::Sqlite(_) => match self.connect() {
                Ok(conn) => conn
                    .query_row(
                        "SELECT timestamp_ns FROM telemetry_events
                         WHERE execution_id = ?1 AND event_type = 'phase_start' AND event_name = ?2
                         ORDER BY timestamp_ns DESC LIMIT 1",
                        params![execution_id, phase],
                        |row| row.get::<_, i64>(0),
                    )
                    .optional()
                    .unwrap_or(None),
                Err(_) => None,
            },
            TelemetryBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock();
                conn.query_row(
                    "SELECT timestamp_ns FROM telemetry_events
                     WHERE execution_id = ?1 AND event_type = 'phase_start' AND event_name = ?2
                     ORDER BY timestamp_ns DESC LIMIT 1",
                    params![execution_id, phase],
                    |row| row.get::<_, i64>(0),
                )
                .optional()
                .unwrap_or(None)
            }
        };

        let duration_ns = start_ns.map(|s| end_ns - s);

        self.insert_event(
            execution_id,
            TelemetryEventType::PhaseEnd,
            phase,
            end_ns,
            duration_ns,
            None,
            duration_ns.map(|_| "ns"),
            None,
        )
    }

    /// Record a counter increment
    pub fn record_counter(
        &self,
        execution_id: &str,
        name: &str,
        value: f64,
        unit: &str,
    ) -> Result<i64> {
        self.insert_event(
            execution_id,
            TelemetryEventType::Counter,
            name,
            Self::now_ns(),
            None,
            Some(value),
            Some(unit),
            None,
        )
    }

    /// Record a gauge value
    pub fn record_gauge(
        &self,
        execution_id: &str,
        name: &str,
        value: f64,
        unit: &str,
    ) -> Result<i64> {
        self.insert_event(
            execution_id,
            TelemetryEventType::Gauge,
            name,
            Self::now_ns(),
            None,
            Some(value),
            Some(unit),
            None,
        )
    }

    /// Record a telemetry event with custom metadata
    pub fn record_event(
        &self,
        execution_id: &str,
        event_type: TelemetryEventType,
        event_name: &str,
        value: Option<f64>,
        unit: Option<&str>,
        metadata: Option<&serde_json::Value>,
    ) -> Result<i64> {
        self.insert_event(
            execution_id,
            event_type,
            event_name,
            Self::now_ns(),
            None,
            value,
            unit,
            metadata,
        )
    }

    fn row_to_event(row: &rusqlite::Row) -> Result<TelemetryEvent, rusqlite::Error> {
        let event_type_str: String = row.get(2)?;
        let event_type = match event_type_str.as_str() {
            "phase_start" => TelemetryEventType::PhaseStart,
            "phase_end" => TelemetryEventType::PhaseEnd,
            "counter" => TelemetryEventType::Counter,
            "gauge" => TelemetryEventType::Gauge,
            _ => {
                return Err(rusqlite::Error::FromSqlConversionFailure(
                    2,
                    rusqlite::types::Type::Text,
                    Box::new(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("Unknown telemetry event type: {}", event_type_str),
                    )),
                ));
            }
        };

        let metadata_str: Option<String> = row.get(8)?;
        let metadata = metadata_str.and_then(|s| serde_json::from_str(&s).ok());

        Ok(TelemetryEvent {
            id: row.get(0)?,
            execution_id: row.get(1)?,
            event_type,
            event_name: row.get(3)?,
            timestamp_ns: row.get(4)?,
            duration_ns: row.get(5)?,
            value: row.get(6)?,
            unit: row.get(7)?,
            metadata,
        })
    }

    /// Get all telemetry events for an execution
    pub fn get_events_for_execution(&self, execution_id: &str) -> Result<Vec<TelemetryEvent>> {
        let sql = "SELECT id, execution_id, event_type, event_name, timestamp_ns,
                          duration_ns, value, unit, metadata
                   FROM telemetry_events
                   WHERE execution_id = ?1
                   ORDER BY timestamp_ns ASC";

        match &self.backend {
            TelemetryBackend::Sqlite(_) => {
                let conn = self.connect()?;
                let mut stmt = conn.prepare(sql)?;
                let events = stmt
                    .query_map(params![execution_id], Self::row_to_event)?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect telemetry events: {}", e))?;
                Ok(events)
            }
            TelemetryBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock();
                let mut stmt = conn.prepare(sql)?;
                let events = stmt
                    .query_map(params![execution_id], Self::row_to_event)?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect telemetry events: {}", e))?;
                Ok(events)
            }
        }
    }

    /// Get phase durations for an execution
    ///
    /// Returns (phase_name, duration_ns) pairs from phase_end events
    pub fn get_phase_durations(&self, execution_id: &str) -> Result<Vec<(String, i64)>> {
        let sql = "SELECT event_name, duration_ns
                   FROM telemetry_events
                   WHERE execution_id = ?1 AND event_type = 'phase_end' AND duration_ns IS NOT NULL
                   ORDER BY timestamp_ns ASC";

        match &self.backend {
            TelemetryBackend::Sqlite(_) => {
                let conn = self.connect()?;
                let mut stmt = conn.prepare(sql)?;
                let rows = stmt
                    .query_map(params![execution_id], |row| {
                        Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
                    })?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect phase durations: {}", e))?;
                Ok(rows)
            }
            TelemetryBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock();
                let mut stmt = conn.prepare(sql)?;
                let rows = stmt
                    .query_map(params![execution_id], |row| {
                        Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
                    })?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect phase durations: {}", e))?;
                Ok(rows)
            }
        }
    }

    /// Get recent events across all executions
    pub fn get_recent_events(&self, limit: usize) -> Result<Vec<TelemetryEvent>> {
        let sql = format!(
            "SELECT id, execution_id, event_type, event_name, timestamp_ns,
                    duration_ns, value, unit, metadata
             FROM telemetry_events
             ORDER BY timestamp_ns DESC
             LIMIT {}",
            limit
        );

        match &self.backend {
            TelemetryBackend::Sqlite(_) => {
                let conn = self.connect()?;
                let mut stmt = conn.prepare(&sql)?;
                let events = stmt
                    .query_map([], Self::row_to_event)?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect recent events: {}", e))?;
                Ok(events)
            }
            TelemetryBackend::Shared(conn_arc) => {
                let conn = conn_arc.lock();
                let mut stmt = conn.prepare(&sql)?;
                let events = stmt
                    .query_map([], Self::row_to_event)?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect recent events: {}", e))?;
                Ok(events)
            }
        }
    }

    /// Get a snapshot of the in-memory ring buffer
    ///
    /// This is the real-time API — no database query, just memory access
    pub fn snapshot_ring_buffer(&self) -> Vec<TelemetryEvent> {
        let buf = self.ring_buffer.lock();
        buf.iter().cloned().collect()
    }
}

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

    #[test]
    fn test_telemetry_schema() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let telemetry = TelemetryOps::new(&db_path);

        telemetry.ensure_schema().unwrap();

        let conn = telemetry.connect().unwrap();
        let table_exists: bool = conn
            .query_row(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name='telemetry_events'",
                [],
                |_| Ok(true),
            )
            .optional()
            .unwrap()
            .unwrap_or(false);

        assert!(table_exists, "telemetry_events table should exist");
    }

    #[test]
    fn test_record_phase_timing() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let telemetry = TelemetryOps::new(&db_path);

        telemetry.ensure_schema().unwrap();

        let exec_id = "test-exec-001";

        // Record phase start
        let start_id = telemetry.record_phase_start(exec_id, "parse").unwrap();
        assert!(start_id > 0);

        // Small delay
        std::thread::sleep(std::time::Duration::from_millis(10));

        // Record phase end
        let end_id = telemetry.record_phase_end(exec_id, "parse").unwrap();
        assert!(end_id > 0);

        // Query phase durations
        let durations = telemetry.get_phase_durations(exec_id).unwrap();
        assert_eq!(durations.len(), 1);
        assert_eq!(durations[0].0, "parse");
        assert!(
            durations[0].1 >= 10_000_000,
            "Duration should be at least 10ms in ns"
        );
    }

    #[test]
    fn test_record_counter_and_gauge() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let telemetry = TelemetryOps::new(&db_path);

        telemetry.ensure_schema().unwrap();

        let exec_id = "test-exec-002";

        telemetry
            .record_counter(exec_id, "files_indexed", 150.0, "count")
            .unwrap();
        telemetry
            .record_gauge(exec_id, "memory_mb", 512.0, "mb")
            .unwrap();

        let events = telemetry.get_events_for_execution(exec_id).unwrap();
        assert_eq!(events.len(), 2);

        let counter = &events[0];
        assert_eq!(counter.event_type, TelemetryEventType::Counter);
        assert_eq!(counter.event_name, "files_indexed");
        assert_eq!(counter.value, Some(150.0));
        assert_eq!(counter.unit.as_deref(), Some("count"));

        let gauge = &events[1];
        assert_eq!(gauge.event_type, TelemetryEventType::Gauge);
        assert_eq!(gauge.event_name, "memory_mb");
        assert_eq!(gauge.value, Some(512.0));
        assert_eq!(gauge.unit.as_deref(), Some("mb"));
    }

    #[test]
    fn test_ring_buffer() {
        let telemetry = TelemetryOps::in_memory();

        let exec_id = "test-exec-003";
        for i in 0..5 {
            telemetry
                .record_counter(exec_id, "iteration", i as f64, "count")
                .unwrap();
        }

        let snapshot = telemetry.snapshot_ring_buffer();
        assert_eq!(snapshot.len(), 5);

        // Verify order (oldest first in VecDeque)
        assert_eq!(snapshot[0].value, Some(0.0));
        assert_eq!(snapshot[4].value, Some(4.0));
    }

    #[test]
    fn test_get_recent_events() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let telemetry = TelemetryOps::new(&db_path);

        telemetry.ensure_schema().unwrap();

        for i in 0..10 {
            let exec_id = format!("test-exec-{}", i);
            telemetry
                .record_counter(&exec_id, "test", i as f64, "count")
                .unwrap();
        }

        let recent = telemetry.get_recent_events(5).unwrap();
        assert_eq!(recent.len(), 5);
        // Most recent first
        assert_eq!(recent[0].execution_id, "test-exec-9");
        assert_eq!(recent[4].execution_id, "test-exec-5");
    }

    /// Regression for B-1: telemetry insert failures must NOT propagate.
    ///
    /// Before this fix, every read/query command (status, find, refs, context,
    /// ...) called `record_phase_start(...)?` which propagated the SQLite insert
    /// error. On a corrupted telemetry_events table this aborted the whole
    /// command before any real data was queried — instrumentation on the
    /// critical path of a read-only operation.
    ///
    /// This test corrupts the telemetry table (renames it so INSERT fails) and
    /// asserts that record_phase_start / record_phase_end / record_counter return
    /// Ok instead of Err. Telemetry is best-effort instrumentation; it must
    /// never take down a command that has nothing to do with telemetry.
    #[test]
    fn test_telemetry_best_effort_on_insert_failure() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let telemetry = TelemetryOps::new(&db_path);
        telemetry.ensure_schema().unwrap();

        // Corrupt: rename the table so every INSERT into telemetry_events fails
        // with "no such table". This emulates the real-world corrupted-DB scenario
        // where the telemetry_events b-tree is malformed.
        {
            let conn = telemetry.connect().unwrap();
            conn.execute(
                "ALTER TABLE telemetry_events RENAME TO telemetry_events_broken",
                [],
            )
            .unwrap();
        }

        // All record_* methods must return Ok (best-effort), NOT propagate the error.
        let phase_start = telemetry.record_phase_start("exec-best-effort", "query_counts");
        assert!(
            phase_start.is_ok(),
            "record_phase_start must be best-effort (got {:?})",
            phase_start
        );

        let phase_end = telemetry.record_phase_end("exec-best-effort", "query_counts");
        assert!(
            phase_end.is_ok(),
            "record_phase_end must be best-effort (got {:?})",
            phase_end
        );

        let counter = telemetry.record_counter("exec-best-effort", "files_indexed", 42.0, "count");
        assert!(
            counter.is_ok(),
            "record_counter must be best-effort (got {:?})",
            counter
        );

        let gauge = telemetry.record_gauge("exec-best-effort", "memory_mb", 128.0, "mb");
        assert!(
            gauge.is_ok(),
            "record_gauge must be best-effort (got {:?})",
            gauge
        );
    }
}