llm-optimizer-processor 0.1.1

Data processing and transformation pipeline
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
//! Type definitions for the analyzer framework
//!
//! This module contains all the core data structures used by analyzers,
//! including events, results, insights, recommendations, and alerts.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

/// Events that analyzers can process
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum AnalyzerEvent {
    /// Metric event (latency, throughput, cost, etc.)
    Metric {
        timestamp: DateTime<Utc>,
        name: String,
        value: f64,
        unit: String,
        labels: HashMap<String, String>,
    },

    /// Request event (LLM API request)
    Request {
        timestamp: DateTime<Utc>,
        request_id: String,
        model: String,
        prompt_tokens: u32,
        max_tokens: u32,
        temperature: f64,
        metadata: HashMap<String, String>,
    },

    /// Response event (LLM API response)
    Response {
        timestamp: DateTime<Utc>,
        request_id: String,
        model: String,
        completion_tokens: u32,
        total_tokens: u32,
        latency_ms: u64,
        success: bool,
        error: Option<String>,
        metadata: HashMap<String, String>,
    },

    /// Feedback event (user feedback on quality)
    Feedback {
        timestamp: DateTime<Utc>,
        request_id: String,
        rating: f64, // 0.0-1.0
        feedback_type: FeedbackType,
        comment: Option<String>,
        metadata: HashMap<String, String>,
    },

    /// Cost event (billing/cost information)
    Cost {
        timestamp: DateTime<Utc>,
        model: String,
        tokens: u32,
        cost_usd: f64,
        metadata: HashMap<String, String>,
    },

    /// Alert event (external alerts to process)
    Alert {
        timestamp: DateTime<Utc>,
        alert_type: String,
        severity: Severity,
        message: String,
        metadata: HashMap<String, String>,
    },

    /// Custom event (extensibility)
    Custom {
        timestamp: DateTime<Utc>,
        event_type: String,
        data: serde_json::Value,
    },
}

impl AnalyzerEvent {
    /// Get the timestamp of the event
    pub fn timestamp(&self) -> DateTime<Utc> {
        match self {
            AnalyzerEvent::Metric { timestamp, .. } => *timestamp,
            AnalyzerEvent::Request { timestamp, .. } => *timestamp,
            AnalyzerEvent::Response { timestamp, .. } => *timestamp,
            AnalyzerEvent::Feedback { timestamp, .. } => *timestamp,
            AnalyzerEvent::Cost { timestamp, .. } => *timestamp,
            AnalyzerEvent::Alert { timestamp, .. } => *timestamp,
            AnalyzerEvent::Custom { timestamp, .. } => *timestamp,
        }
    }

    /// Get metadata if available
    pub fn metadata(&self) -> Option<&HashMap<String, String>> {
        match self {
            AnalyzerEvent::Metric { labels, .. } => Some(labels),
            AnalyzerEvent::Request { metadata, .. } => Some(metadata),
            AnalyzerEvent::Response { metadata, .. } => Some(metadata),
            AnalyzerEvent::Feedback { metadata, .. } => Some(metadata),
            AnalyzerEvent::Cost { metadata, .. } => Some(metadata),
            AnalyzerEvent::Alert { metadata, .. } => Some(metadata),
            AnalyzerEvent::Custom { .. } => None,
        }
    }
}

/// Type of user feedback
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FeedbackType {
    /// Positive feedback (thumbs up)
    Positive,
    /// Negative feedback (thumbs down)
    Negative,
    /// Rating (1-5 stars)
    Rating,
    /// Quality assessment
    Quality,
    /// Custom feedback
    Custom,
}

/// Severity levels for insights and alerts
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// Informational message
    Info,
    /// Warning that should be reviewed
    Warning,
    /// Error that needs attention
    Error,
    /// Critical issue requiring immediate action
    Critical,
}

impl Severity {
    /// Check if this severity requires immediate action
    pub fn is_urgent(&self) -> bool {
        matches!(self, Severity::Critical | Severity::Error)
    }
}

/// Confidence level for analysis results
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct Confidence(f64);

impl Confidence {
    /// Create a new confidence value (0.0-1.0)
    pub fn new(value: f64) -> Self {
        Self(value.clamp(0.0, 1.0))
    }

    /// Get the confidence value
    pub fn value(&self) -> f64 {
        self.0
    }

    /// Check if confidence is high (>= 0.8)
    pub fn is_high(&self) -> bool {
        self.0 >= 0.8
    }

    /// Check if confidence is medium (0.5 - 0.8)
    pub fn is_medium(&self) -> bool {
        self.0 >= 0.5 && self.0 < 0.8
    }

    /// Check if confidence is low (< 0.5)
    pub fn is_low(&self) -> bool {
        self.0 < 0.5
    }
}

/// An insight discovered by an analyzer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Insight {
    /// Unique identifier for this insight
    pub id: String,

    /// Analyzer that generated this insight
    pub analyzer: String,

    /// Timestamp when the insight was generated
    pub timestamp: DateTime<Utc>,

    /// Severity of the insight
    pub severity: Severity,

    /// Confidence in the insight (0.0-1.0)
    pub confidence: Confidence,

    /// Title of the insight
    pub title: String,

    /// Detailed description
    pub description: String,

    /// Category of the insight
    pub category: InsightCategory,

    /// Evidence supporting the insight
    pub evidence: Vec<Evidence>,

    /// Related metrics
    pub metrics: HashMap<String, f64>,

    /// Tags for categorization
    pub tags: Vec<String>,
}

/// Category of an insight
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InsightCategory {
    /// Performance-related insight
    Performance,
    /// Cost-related insight
    Cost,
    /// Quality-related insight
    Quality,
    /// Pattern or trend insight
    Pattern,
    /// Anomaly or outlier
    Anomaly,
    /// Optimization opportunity
    Optimization,
    /// Risk or concern
    Risk,
    /// General observation
    General,
}

/// Evidence supporting an insight
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Evidence {
    /// Type of evidence
    pub evidence_type: EvidenceType,

    /// Description of the evidence
    pub description: String,

    /// Data supporting the evidence
    pub data: serde_json::Value,

    /// Timestamp of the evidence
    pub timestamp: DateTime<Utc>,
}

/// Type of evidence
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceType {
    /// Statistical analysis
    Statistical,
    /// Time series data
    TimeSeries,
    /// Comparison data
    Comparison,
    /// Threshold violation
    Threshold,
    /// Pattern match
    Pattern,
    /// Anomaly detection
    Anomaly,
    /// User feedback
    Feedback,
    /// Historical data
    Historical,
}

/// A recommendation for optimization or action
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Recommendation {
    /// Unique identifier for this recommendation
    pub id: String,

    /// Analyzer that generated this recommendation
    pub analyzer: String,

    /// Timestamp when generated
    pub timestamp: DateTime<Utc>,

    /// Priority of the recommendation
    pub priority: Priority,

    /// Title of the recommendation
    pub title: String,

    /// Detailed description
    pub description: String,

    /// Action to take
    pub action: Action,

    /// Expected impact
    pub expected_impact: Impact,

    /// Confidence in the recommendation (0.0-1.0)
    pub confidence: Confidence,

    /// Related insights
    pub related_insights: Vec<String>,

    /// Tags for categorization
    pub tags: Vec<String>,
}

/// Priority level for recommendations
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Priority {
    /// Low priority
    Low,
    /// Medium priority
    Medium,
    /// High priority
    High,
    /// Urgent (immediate action)
    Urgent,
}

/// Action to take based on a recommendation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
    /// Type of action
    pub action_type: ActionType,

    /// Detailed instructions
    pub instructions: String,

    /// Parameters for the action
    pub parameters: HashMap<String, serde_json::Value>,

    /// Estimated effort (hours)
    pub estimated_effort: Option<f64>,

    /// Risk level of taking this action
    pub risk_level: RiskLevel,
}

/// Type of action
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionType {
    /// Adjust configuration
    ConfigChange,
    /// Scale resources
    Scale,
    /// Optimize code or query
    Optimize,
    /// Investigate issue
    Investigate,
    /// Add monitoring
    Monitor,
    /// Alert on threshold
    Alert,
    /// Review and decide
    Review,
    /// Take no action
    NoAction,
}

impl ActionType {
    /// Convert the action type to a lowercase string representation
    pub fn to_lowercase(&self) -> String {
        match self {
            ActionType::ConfigChange => "configchange".to_string(),
            ActionType::Scale => "scale".to_string(),
            ActionType::Optimize => "optimize".to_string(),
            ActionType::Investigate => "investigate".to_string(),
            ActionType::Monitor => "monitor".to_string(),
            ActionType::Alert => "alert".to_string(),
            ActionType::Review => "review".to_string(),
            ActionType::NoAction => "noaction".to_string(),
        }
    }
}

/// Risk level of an action
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RiskLevel {
    /// No risk
    None,
    /// Low risk
    Low,
    /// Medium risk
    Medium,
    /// High risk
    High,
}

/// Expected impact of a recommendation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Impact {
    /// Performance impact (latency reduction, throughput increase)
    pub performance: Option<ImpactMetric>,

    /// Cost impact (cost savings or increase)
    pub cost: Option<ImpactMetric>,

    /// Quality impact (quality improvement)
    pub quality: Option<ImpactMetric>,

    /// Description of the impact
    pub description: String,
}

/// Quantified impact metric
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImpactMetric {
    /// Metric name
    pub name: String,

    /// Current value
    pub current: f64,

    /// Expected value after change
    pub expected: f64,

    /// Unit of measurement
    pub unit: String,

    /// Percentage improvement
    pub improvement_pct: f64,
}

/// An alert triggered by an analyzer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Alert {
    /// Unique identifier for this alert
    pub id: String,

    /// Analyzer that triggered the alert
    pub analyzer: String,

    /// Timestamp when triggered
    pub timestamp: DateTime<Utc>,

    /// Severity of the alert
    pub severity: Severity,

    /// Title of the alert
    pub title: String,

    /// Detailed message
    pub message: String,

    /// Alert status
    pub status: AlertStatus,

    /// Threshold that was violated (if applicable)
    pub threshold: Option<Threshold>,

    /// Related insights
    pub related_insights: Vec<String>,

    /// Tags for routing and filtering
    pub tags: Vec<String>,

    /// Alert metadata
    pub metadata: HashMap<String, String>,
}

/// Status of an alert
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AlertStatus {
    /// Alert just triggered
    Firing,
    /// Alert condition resolved
    Resolved,
    /// Alert acknowledged but not resolved
    Acknowledged,
    /// Alert silenced
    Silenced,
}

/// Threshold configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Threshold {
    /// Metric name
    pub metric: String,

    /// Threshold value
    pub value: f64,

    /// Comparison operator
    pub operator: ThresholdOperator,

    /// Duration over which condition must hold
    pub duration: Duration,

    /// Actual value that triggered
    pub actual_value: f64,
}

/// Threshold comparison operators
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ThresholdOperator {
    /// Greater than
    GreaterThan,
    /// Greater than or equal
    GreaterThanOrEqual,
    /// Less than
    LessThan,
    /// Less than or equal
    LessThanOrEqual,
    /// Equal to
    Equal,
    /// Not equal to
    NotEqual,
}

impl ThresholdOperator {
    /// Check if a value meets the threshold condition
    pub fn compare(&self, actual: f64, threshold: f64) -> bool {
        match self {
            ThresholdOperator::GreaterThan => actual > threshold,
            ThresholdOperator::GreaterThanOrEqual => actual >= threshold,
            ThresholdOperator::LessThan => actual < threshold,
            ThresholdOperator::LessThanOrEqual => actual <= threshold,
            ThresholdOperator::Equal => (actual - threshold).abs() < f64::EPSILON,
            ThresholdOperator::NotEqual => (actual - threshold).abs() >= f64::EPSILON,
        }
    }
}

/// Complete analysis report from an analyzer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisReport {
    /// Analyzer name
    pub analyzer: String,

    /// Report generation timestamp
    pub timestamp: DateTime<Utc>,

    /// Time period covered by this report
    pub period_start: DateTime<Utc>,
    pub period_end: DateTime<Utc>,

    /// Summary statistics
    pub summary: ReportSummary,

    /// Insights discovered
    pub insights: Vec<Insight>,

    /// Recommendations generated
    pub recommendations: Vec<Recommendation>,

    /// Alerts triggered
    pub alerts: Vec<Alert>,

    /// Raw metrics data
    pub metrics: HashMap<String, f64>,
}

/// Summary statistics for a report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportSummary {
    /// Total events processed
    pub events_processed: u64,

    /// Events per second
    pub events_per_second: f64,

    /// Number of insights generated
    pub insights_count: u64,

    /// Number of recommendations generated
    pub recommendations_count: u64,

    /// Number of alerts triggered
    pub alerts_count: u64,

    /// Analysis duration
    pub analysis_duration_ms: u64,

    /// Key highlights
    pub highlights: Vec<String>,
}

/// Statistics about an analyzer's operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyzerStats {
    /// Analyzer name
    pub analyzer: String,

    /// Total events processed
    pub events_processed: u64,

    /// Total events dropped (sampling or errors)
    pub events_dropped: u64,

    /// Total insights generated
    pub insights_generated: u64,

    /// Total recommendations generated
    pub recommendations_generated: u64,

    /// Total alerts triggered
    pub alerts_triggered: u64,

    /// Total analysis time (milliseconds)
    pub analysis_time_ms: u64,

    /// Average analysis time per event (microseconds)
    pub avg_analysis_time_us: f64,

    /// Current memory usage (bytes)
    pub memory_usage_bytes: usize,

    /// Error count
    pub error_count: u64,

    /// Last error message
    pub last_error: Option<String>,

    /// Uptime in seconds
    pub uptime_seconds: u64,
}

impl Default for AnalyzerStats {
    fn default() -> Self {
        Self {
            analyzer: String::new(),
            events_processed: 0,
            events_dropped: 0,
            insights_generated: 0,
            recommendations_generated: 0,
            alerts_triggered: 0,
            analysis_time_ms: 0,
            avg_analysis_time_us: 0.0,
            memory_usage_bytes: 0,
            error_count: 0,
            last_error: None,
            uptime_seconds: 0,
        }
    }
}

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

    #[test]
    fn test_confidence_creation() {
        let conf = Confidence::new(0.75);
        assert_eq!(conf.value(), 0.75);
        assert!(conf.is_medium());

        let conf = Confidence::new(1.5); // Should clamp to 1.0
        assert_eq!(conf.value(), 1.0);

        let conf = Confidence::new(-0.5); // Should clamp to 0.0
        assert_eq!(conf.value(), 0.0);
    }

    #[test]
    fn test_confidence_levels() {
        assert!(Confidence::new(0.9).is_high());
        assert!(!Confidence::new(0.9).is_medium());
        assert!(!Confidence::new(0.9).is_low());

        assert!(Confidence::new(0.6).is_medium());
        assert!(!Confidence::new(0.6).is_high());
        assert!(!Confidence::new(0.6).is_low());

        assert!(Confidence::new(0.3).is_low());
        assert!(!Confidence::new(0.3).is_medium());
        assert!(!Confidence::new(0.3).is_high());
    }

    #[test]
    fn test_severity_is_urgent() {
        assert!(!Severity::Info.is_urgent());
        assert!(!Severity::Warning.is_urgent());
        assert!(Severity::Error.is_urgent());
        assert!(Severity::Critical.is_urgent());
    }

    #[test]
    fn test_threshold_operator_compare() {
        assert!(ThresholdOperator::GreaterThan.compare(10.0, 5.0));
        assert!(!ThresholdOperator::GreaterThan.compare(5.0, 10.0));

        assert!(ThresholdOperator::LessThan.compare(5.0, 10.0));
        assert!(!ThresholdOperator::LessThan.compare(10.0, 5.0));

        assert!(ThresholdOperator::Equal.compare(5.0, 5.0));
        assert!(!ThresholdOperator::Equal.compare(5.0, 6.0));
    }

    #[test]
    fn test_analyzer_event_timestamp() {
        let now = Utc::now();
        let event = AnalyzerEvent::Metric {
            timestamp: now,
            name: "test".to_string(),
            value: 1.0,
            unit: "ms".to_string(),
            labels: HashMap::new(),
        };

        assert_eq!(event.timestamp(), now);
    }
}