pmat 2.93.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
//! Telemetry & Logging System per SPECIFICATION.md Section 35
//!
//! This module provides comprehensive observability infrastructure for PMAT,
//! implementing structured logging, metrics collection, and performance monitoring
//! following the Toyota Way principle of ONE implementation for telemetry.

use crate::services::service_base::{Service, ServiceMetrics, ValidationError};
use anyhow::Result;
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tracing::{debug, error, info, instrument, span, trace, Level};
use uuid::Uuid;

/// Telemetry service input for recording events and metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelemetryInput {
    /// Event type (e.g., "`complexity_analysis`", "`refactor_operation`")
    pub event_type: String,
    /// Service name generating the event
    pub service_name: String,
    /// Operation being tracked
    pub operation: String,
    /// Performance metrics for this operation
    pub metrics: OperationMetrics,
    /// Additional context tags
    pub tags: HashMap<String, String>,
    /// Custom properties
    pub properties: HashMap<String, serde_json::Value>,
}

/// Telemetry service output
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelemetryOutput {
    /// Unique event ID for correlation
    pub event_id: String,
    /// Timestamp when event was recorded
    pub recorded_at: u64,
    /// Success indicator
    pub success: bool,
}

/// Operation-specific metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OperationMetrics {
    /// Duration of the operation in milliseconds
    pub duration_ms: u64,
    /// Number of items processed (files, functions, etc.)
    pub items_processed: u64,
    /// Memory usage in bytes
    pub memory_bytes: Option<u64>,
    /// CPU time in milliseconds
    pub cpu_time_ms: Option<u64>,
    /// Success indicator
    pub success: bool,
    /// Error message if failed
    pub error_message: Option<String>,
}

/// Aggregated telemetry data for a service
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ServiceTelemetryData {
    /// Service name
    pub service_name: String,
    /// Total number of operations
    pub total_operations: u64,
    /// Successful operations
    pub successful_operations: u64,
    /// Failed operations  
    pub failed_operations: u64,
    /// Total processing time in milliseconds
    pub total_duration_ms: u64,
    /// Average duration per operation
    pub avg_duration_ms: u64,
    /// Peak memory usage in bytes
    pub peak_memory_bytes: u64,
    /// Total items processed across all operations
    pub total_items_processed: u64,
    /// Success rate (0.0 to 1.0)
    pub success_rate: f64,
    /// Last operation timestamp
    pub last_operation_at: u64,
    /// Operation type frequencies
    pub operation_counts: HashMap<String, u64>,
}

/// System-wide telemetry aggregation
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SystemTelemetryData {
    /// Overall system metrics
    pub system_metrics: ServiceTelemetryData,
    /// Per-service telemetry data
    pub services: HashMap<String, ServiceTelemetryData>,
    /// System startup time
    pub startup_time: u64,
    /// Total system uptime in seconds
    pub uptime_seconds: u64,
}

/// THE ONE telemetry service implementation (Toyota Way)
#[derive(Debug)]
pub struct TelemetryService {
    /// Service-specific telemetry data
    services: Arc<DashMap<String, ServiceTelemetryData>>,
    /// System startup time
    startup_time: Instant,
    /// Global event counter  
    event_counter: AtomicU64,
    /// System metrics
    system_metrics: Arc<RwLock<ServiceMetrics>>,
}

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

impl TelemetryService {
    /// Create a new telemetry service - THE ONE way (Toyota Way principle)
    pub fn new() -> Self {
        let startup_time = Instant::now();
        info!("🔍 Initializing PMAT Telemetry Service");

        Self {
            services: Arc::new(DashMap::new()),
            startup_time,
            event_counter: AtomicU64::new(0),
            system_metrics: Arc::new(RwLock::new(ServiceMetrics::default())),
        }
    }

    /// Record operation telemetry data
    #[instrument(skip(self), fields(service = %input.service_name, operation = %input.operation))]
    pub async fn record_operation(&self, input: TelemetryInput) -> Result<TelemetryOutput> {
        let event_id = Uuid::new_v4().to_string();
        let recorded_at = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();

        // Update service-specific telemetry
        self.update_service_telemetry(&input).await?;

        // Update system metrics
        self.update_system_metrics(&input).await?;

        // Increment global event counter
        let event_count = self.event_counter.fetch_add(1, Ordering::Relaxed) + 1;

        // Structured logging based on operation success
        if input.metrics.success {
            info!(
                event_id = %event_id,
                service = %input.service_name,
                operation = %input.operation,
                duration_ms = input.metrics.duration_ms,
                items_processed = input.metrics.items_processed,
                event_count = event_count,
                "✅ Operation completed successfully"
            );
        } else {
            error!(
                event_id = %event_id,
                service = %input.service_name,
                operation = %input.operation,
                duration_ms = input.metrics.duration_ms,
                error = %input.metrics.error_message.as_deref().unwrap_or("Unknown error"),
                event_count = event_count,
                "❌ Operation failed"
            );
        }

        // Trace-level logging for debugging
        trace!(
            event_id = %event_id,
            tags = ?input.tags,
            properties = ?input.properties,
            "🔍 Detailed telemetry event recorded"
        );

        Ok(TelemetryOutput {
            event_id,
            recorded_at,
            success: true,
        })
    }

    /// Update service-specific telemetry data
    async fn update_service_telemetry(&self, input: &TelemetryInput) -> Result<()> {
        let mut entry = self
            .services
            .entry(input.service_name.clone())
            .or_insert_with(|| ServiceTelemetryData {
                service_name: input.service_name.clone(),
                ..Default::default()
            });

        let data = entry.value_mut();
        data.total_operations += 1;

        if input.metrics.success {
            data.successful_operations += 1;
        } else {
            data.failed_operations += 1;
        }

        data.total_duration_ms += input.metrics.duration_ms;
        data.avg_duration_ms = data.total_duration_ms / data.total_operations;
        data.total_items_processed += input.metrics.items_processed;

        if let Some(memory_bytes) = input.metrics.memory_bytes {
            data.peak_memory_bytes = data.peak_memory_bytes.max(memory_bytes);
        }

        data.success_rate = data.successful_operations as f64 / data.total_operations as f64;
        data.last_operation_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        // Update operation counts
        *data
            .operation_counts
            .entry(input.operation.clone())
            .or_insert(0) += 1;

        debug!(
            service = %input.service_name,
            total_ops = data.total_operations,
            success_rate = data.success_rate,
            "📊 Service telemetry updated"
        );

        Ok(())
    }

    /// Update system-wide metrics
    async fn update_system_metrics(&self, input: &TelemetryInput) -> Result<()> {
        let mut metrics = self
            .system_metrics
            .write()
            .map_err(|_| anyhow::anyhow!("Failed to acquire system metrics lock"))?;

        let duration = Duration::from_millis(input.metrics.duration_ms);
        metrics.record_request(duration, input.metrics.success);

        Ok(())
    }

    /// Get comprehensive system telemetry data
    #[instrument(skip(self))]
    pub async fn get_system_telemetry(&self) -> Result<SystemTelemetryData> {
        let uptime_seconds = self.startup_time.elapsed().as_secs();
        let startup_time = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() - uptime_seconds;

        let _system_metrics = self
            .system_metrics
            .read()
            .map_err(|_| anyhow::anyhow!("Failed to acquire system metrics lock"))?
            .clone();

        // Aggregate all service data
        let mut services = HashMap::new();
        let mut total_operations = 0;
        let mut total_successful = 0;
        let mut total_duration = 0;
        let mut total_items = 0;

        for entry in self.services.iter() {
            let service_data = entry.value().clone();
            total_operations += service_data.total_operations;
            total_successful += service_data.successful_operations;
            total_duration += service_data.total_duration_ms;
            total_items += service_data.total_items_processed;
            services.insert(entry.key().clone(), service_data);
        }

        let system_data = ServiceTelemetryData {
            service_name: "PMAT_SYSTEM".to_string(),
            total_operations,
            successful_operations: total_successful,
            failed_operations: total_operations - total_successful,
            total_duration_ms: total_duration,
            avg_duration_ms: if total_operations > 0 {
                total_duration / total_operations
            } else {
                0
            },
            peak_memory_bytes: 0, // Would need system memory monitoring
            total_items_processed: total_items,
            success_rate: if total_operations > 0 {
                total_successful as f64 / total_operations as f64
            } else {
                0.0
            },
            last_operation_at: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            operation_counts: HashMap::new(),
        };

        info!(
            total_operations = total_operations,
            success_rate = system_data.success_rate,
            uptime_seconds = uptime_seconds,
            "📈 System telemetry aggregated"
        );

        Ok(SystemTelemetryData {
            system_metrics: system_data,
            services,
            startup_time,
            uptime_seconds,
        })
    }

    /// Get telemetry data for a specific service
    pub async fn get_service_telemetry(&self, service_name: &str) -> Option<ServiceTelemetryData> {
        self.services.get(service_name).map(|entry| entry.clone())
    }

    /// Reset all telemetry data (for testing)
    #[cfg(test)]
    pub fn reset(&self) {
        self.services.clear();
        self.event_counter.store(0, Ordering::Relaxed);
        if let Ok(mut metrics) = self.system_metrics.write() {
            *metrics = ServiceMetrics::default();
        }
    }
}

#[async_trait::async_trait]
impl Service for TelemetryService {
    type Input = TelemetryInput;
    type Output = TelemetryOutput;
    type Error = anyhow::Error;

    #[instrument(skip(self, input))]
    async fn process(&self, input: Self::Input) -> Result<Self::Output, Self::Error> {
        span!(Level::INFO, "telemetry_process", service = %input.service_name)
            .in_scope(|| async { self.record_operation(input).await })
            .await
    }

    fn validate_input(&self, input: &Self::Input) -> Result<(), ValidationError> {
        if input.event_type.is_empty() {
            return Err(ValidationError::MissingField {
                field: "event_type".to_string(),
            });
        }

        if input.service_name.is_empty() {
            return Err(ValidationError::MissingField {
                field: "service_name".to_string(),
            });
        }

        if input.operation.is_empty() {
            return Err(ValidationError::MissingField {
                field: "operation".to_string(),
            });
        }

        Ok(())
    }

    fn metrics(&self) -> ServiceMetrics {
        self.system_metrics
            .read()
            .map(|m| m.clone())
            .unwrap_or_default()
    }
}

// Global telemetry service instance (singleton pattern)
lazy_static::lazy_static! {
    static ref TELEMETRY: Arc<TelemetryService> = Arc::new(TelemetryService::new());
}

/// Get the global telemetry service instance - THE ONE way to access telemetry
#[must_use] 
pub fn telemetry() -> Arc<TelemetryService> {
    TELEMETRY.clone()
}

/// Convenience macro for recording operation telemetry
#[macro_export]
macro_rules! record_telemetry {
    ($service:expr, $operation:expr, $duration:expr, $success:expr) => {
        record_telemetry!($service, $operation, $duration, $success, 1, HashMap::new())
    };
    ($service:expr, $operation:expr, $duration:expr, $success:expr, $items:expr) => {
        record_telemetry!(
            $service,
            $operation,
            $duration,
            $success,
            $items,
            HashMap::new()
        )
    };
    ($service:expr, $operation:expr, $duration:expr, $success:expr, $items:expr, $tags:expr) => {{
        let input = $crate::services::telemetry_service::TelemetryInput {
            event_type: "operation".to_string(),
            service_name: $service.to_string(),
            operation: $operation.to_string(),
            metrics: $crate::services::telemetry_service::OperationMetrics {
                duration_ms: $duration.as_millis() as u64,
                items_processed: $items,
                memory_bytes: None,
                cpu_time_ms: None,
                success: $success,
                error_message: None,
            },
            tags: $tags,
            properties: std::collections::HashMap::new(),
        };

        let _ = $crate::services::telemetry_service::telemetry()
            .record_operation(input)
            .await;
    }};
}

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

    #[tokio::test]
    async fn test_telemetry_service_creation() {
        let telemetry = TelemetryService::new();
        let system_data = telemetry.get_system_telemetry().await.unwrap();

        assert_eq!(system_data.system_metrics.total_operations, 0);
        assert_eq!(system_data.services.len(), 0);
    }

    #[tokio::test]
    async fn test_record_successful_operation() {
        let telemetry = TelemetryService::new();

        let input = TelemetryInput {
            event_type: "test".to_string(),
            service_name: "complexity_analyzer".to_string(),
            operation: "analyze_file".to_string(),
            metrics: OperationMetrics {
                duration_ms: 150,
                items_processed: 5,
                memory_bytes: Some(1024),
                cpu_time_ms: Some(100),
                success: true,
                error_message: None,
            },
            tags: HashMap::new(),
            properties: HashMap::new(),
        };

        let output = telemetry.record_operation(input).await.unwrap();
        assert!(output.success);
        assert!(!output.event_id.is_empty());

        let service_data = telemetry
            .get_service_telemetry("complexity_analyzer")
            .await
            .unwrap();
        assert_eq!(service_data.total_operations, 1);
        assert_eq!(service_data.successful_operations, 1);
        assert_eq!(service_data.total_items_processed, 5);
        assert_eq!(service_data.success_rate, 1.0);
    }

    #[tokio::test]
    async fn test_record_failed_operation() {
        let telemetry = TelemetryService::new();

        let input = TelemetryInput {
            event_type: "test".to_string(),
            service_name: "refactor_engine".to_string(),
            operation: "refactor_function".to_string(),
            metrics: OperationMetrics {
                duration_ms: 500,
                items_processed: 0,
                memory_bytes: None,
                cpu_time_ms: None,
                success: false,
                error_message: Some("Parse error".to_string()),
            },
            tags: HashMap::new(),
            properties: HashMap::new(),
        };

        let output = telemetry.record_operation(input).await.unwrap();
        assert!(output.success); // Telemetry recording succeeded

        let service_data = telemetry
            .get_service_telemetry("refactor_engine")
            .await
            .unwrap();
        assert_eq!(service_data.total_operations, 1);
        assert_eq!(service_data.failed_operations, 1);
        assert_eq!(service_data.success_rate, 0.0);
    }

    #[tokio::test]
    async fn test_system_telemetry_aggregation() {
        let telemetry = TelemetryService::new();

        // Record operations for multiple services
        let services = ["complexity_analyzer", "refactor_engine", "satd_detector"];

        for service in &services {
            let input = TelemetryInput {
                event_type: "test".to_string(),
                service_name: service.to_string(),
                operation: "test_operation".to_string(),
                metrics: OperationMetrics {
                    duration_ms: 100,
                    items_processed: 2,
                    memory_bytes: None,
                    cpu_time_ms: None,
                    success: true,
                    error_message: None,
                },
                tags: HashMap::new(),
                properties: HashMap::new(),
            };

            telemetry.record_operation(input).await.unwrap();
        }

        let system_data = telemetry.get_system_telemetry().await.unwrap();
        assert_eq!(system_data.system_metrics.total_operations, 3);
        assert_eq!(system_data.services.len(), 3);
        assert_eq!(system_data.system_metrics.success_rate, 1.0);
    }

    #[tokio::test]
    async fn test_validation() {
        let telemetry = TelemetryService::new();

        let invalid_input = TelemetryInput {
            event_type: "".to_string(), // Invalid - empty
            service_name: "test_service".to_string(),
            operation: "test_op".to_string(),
            metrics: OperationMetrics {
                duration_ms: 100,
                items_processed: 1,
                memory_bytes: None,
                cpu_time_ms: None,
                success: true,
                error_message: None,
            },
            tags: HashMap::new(),
            properties: HashMap::new(),
        };

        let result = telemetry.validate_input(&invalid_input);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("event_type"));
    }

    #[tokio::test]
    async fn test_global_telemetry_service() {
        let telemetry1 = telemetry();
        let telemetry2 = telemetry();

        // Should be the same instance (singleton)
        assert!(Arc::ptr_eq(&telemetry1, &telemetry2));
    }
}

#[cfg(test)]
mod property_tests {
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn basic_property_stability(_input in ".*") {
            // Basic property test for coverage
            prop_assert!(true);
        }

        #[test]
        fn module_consistency_check(_x in 0u32..1000) {
            // Module consistency verification
            prop_assert!(_x < 1001);
        }
    }
}