vectorless 0.1.30

Reasoning-native document intelligence engine for AI
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
// Copyright (c) 2026 vectorless developers
// SPDX-License-Identifier: Apache-2.0

//! Central metrics hub for unified collection.

use std::sync::Arc;

use super::llm::{LlmMetrics, LlmMetricsReport};
use super::pilot::{InterventionPoint, PilotMetrics, PilotMetricsReport};
use super::retrieval::{RetrievalMetrics, RetrievalMetricsReport};
use crate::config::MetricsConfig;

/// Central metrics hub for unified collection.
///
/// Provides a single point for all metrics collection across:
/// - LLM operations (tokens, latency, cost)
/// - Pilot decisions (accuracy, confidence, feedback)
/// - Retrieval operations (paths, scores, cache)
///
/// # Thread Safety
///
/// All metrics use atomic operations and are safe to use from multiple threads.
///
/// # Example
///
/// ```rust
/// use vectorless::metrics::{MetricsHub, MetricsConfig, InterventionPoint};
///
/// let config = MetricsConfig::default();
/// let hub = MetricsHub::new(config);
///
/// // Record LLM call
/// hub.record_llm_call(100, 50, 150, true);
///
/// // Record Pilot decision
/// hub.record_pilot_decision(0.85, InterventionPoint::Fork);
///
/// // Get report
/// let report = hub.generate_report();
/// ```
#[derive(Debug)]
pub struct MetricsHub {
    config: MetricsConfig,
    llm: LlmMetrics,
    pilot: PilotMetrics,
    retrieval: RetrievalMetrics,
}

impl MetricsHub {
    /// Create a new metrics hub.
    pub fn new(config: MetricsConfig) -> Self {
        Self {
            config,
            llm: LlmMetrics::new(),
            pilot: PilotMetrics::new(),
            retrieval: RetrievalMetrics::new(),
        }
    }

    /// Create a new metrics hub with defaults.
    pub fn with_defaults() -> Self {
        Self::new(MetricsConfig::default())
    }

    /// Create an Arc-wrapped metrics hub.
    pub fn shared() -> Arc<Self> {
        Arc::new(Self::with_defaults())
    }

    /// Create an Arc-wrapped metrics hub with config.
    pub fn shared_with_config(config: MetricsConfig) -> Arc<Self> {
        Arc::new(Self::new(config))
    }

    /// Check if metrics are enabled.
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Get the configuration.
    pub fn config(&self) -> &MetricsConfig {
        &self.config
    }

    // ========================================================================
    // LLM Metrics
    // ========================================================================

    /// Record an LLM call.
    pub fn record_llm_call(
        &self,
        input_tokens: u64,
        output_tokens: u64,
        latency_ms: u64,
        success: bool,
    ) {
        if !self.config.enabled || !self.config.llm.track_tokens {
            return;
        }
        self.llm.record_call(
            input_tokens,
            output_tokens,
            latency_ms,
            success,
            &self.config.llm,
        );
    }

    /// Record an LLM rate limit error.
    pub fn record_llm_rate_limit(&self) {
        if self.config.enabled {
            self.llm.record_rate_limit();
        }
    }

    /// Record an LLM timeout error.
    pub fn record_llm_timeout(&self) {
        if self.config.enabled {
            self.llm.record_timeout();
        }
    }

    /// Record an LLM fallback trigger.
    pub fn record_llm_fallback(&self) {
        if self.config.enabled {
            self.llm.record_fallback();
        }
    }

    /// Get LLM metrics report.
    pub fn llm_report(&self) -> LlmMetricsReport {
        self.llm.generate_report()
    }

    // ========================================================================
    // Pilot Metrics
    // ========================================================================

    /// Record a Pilot decision.
    pub fn record_pilot_decision(&self, confidence: f64, point: InterventionPoint) {
        if !self.config.enabled || !self.config.pilot.track_decisions {
            return;
        }
        self.pilot
            .record_decision(confidence, point, &self.config.pilot);
    }

    /// Record feedback on a Pilot decision.
    pub fn record_pilot_feedback(&self, was_correct: bool) {
        if !self.config.enabled || !self.config.pilot.track_feedback {
            return;
        }
        self.pilot.record_feedback(was_correct, &self.config.pilot);
    }

    /// Record a Pilot LLM call.
    pub fn record_pilot_llm_call(&self) {
        if self.config.enabled {
            self.pilot.record_llm_call();
        }
    }

    /// Record a Pilot intervention.
    pub fn record_pilot_intervention(&self) {
        if self.config.enabled {
            self.pilot.record_intervention();
        }
    }

    /// Record a skipped Pilot intervention.
    pub fn record_pilot_intervention_skipped(&self) {
        if self.config.enabled {
            self.pilot.record_skipped_intervention();
        }
    }

    /// Record Pilot budget exhausted.
    pub fn record_pilot_budget_exhausted(&self) {
        if self.config.enabled {
            self.pilot.record_budget_exhausted();
        }
    }

    /// Record Pilot fallback to algorithm.
    pub fn record_pilot_algorithm_fallback(&self) {
        if self.config.enabled {
            self.pilot.record_algorithm_fallback();
        }
    }

    /// Get Pilot metrics report.
    pub fn pilot_report(&self) -> PilotMetricsReport {
        self.pilot.generate_report()
    }

    // ========================================================================
    // Retrieval Metrics
    // ========================================================================

    /// Record a retrieval query.
    pub fn record_retrieval_query(&self, iterations: u64, nodes_visited: u64, latency_ms: u64) {
        if !self.config.enabled {
            return;
        }
        self.retrieval.record_query(
            iterations,
            nodes_visited,
            latency_ms,
            &self.config.retrieval,
        );
    }

    /// Record a found path.
    pub fn record_retrieval_path(&self, length: u64, score: f64) {
        if !self.config.enabled {
            return;
        }
        self.retrieval
            .record_path(length, score, &self.config.retrieval);
    }

    /// Record a cache hit.
    pub fn record_cache_hit(&self) {
        if !self.config.enabled || !self.config.retrieval.track_cache {
            return;
        }
        self.retrieval.record_cache_hit(&self.config.retrieval);
    }

    /// Record a cache miss.
    pub fn record_cache_miss(&self) {
        if !self.config.enabled || !self.config.retrieval.track_cache {
            return;
        }
        self.retrieval.record_cache_miss(&self.config.retrieval);
    }

    /// Record a backtrack.
    pub fn record_backtrack(&self) {
        if self.config.enabled {
            self.retrieval.record_backtrack();
        }
    }

    /// Record a sufficiency check.
    pub fn record_sufficiency_check(&self, was_sufficient: bool) {
        if self.config.enabled {
            self.retrieval.record_sufficiency_check(was_sufficient);
        }
    }

    /// Get retrieval metrics report.
    pub fn retrieval_report(&self) -> RetrievalMetricsReport {
        self.retrieval.generate_report()
    }

    // ========================================================================
    // General Operations
    // ========================================================================

    /// Reset all metrics.
    pub fn reset(&self) {
        self.llm.reset();
        self.pilot.reset();
        self.retrieval.reset();
    }

    /// Generate a complete report.
    pub fn generate_report(&self) -> MetricsReport {
        MetricsReport {
            llm: self.llm_report(),
            pilot: self.pilot_report(),
            retrieval: self.retrieval_report(),
        }
    }
}

impl Default for MetricsHub {
    fn default() -> Self {
        Self::with_defaults()
    }
}

/// Complete metrics report.
#[derive(Debug, Clone)]
pub struct MetricsReport {
    /// LLM metrics.
    pub llm: LlmMetricsReport,
    /// Pilot metrics.
    pub pilot: PilotMetricsReport,
    /// Retrieval metrics.
    pub retrieval: RetrievalMetricsReport,
}

impl MetricsReport {
    /// Calculate total estimated cost in USD.
    pub fn total_cost_usd(&self) -> f64 {
        self.llm.estimated_cost_usd
    }
}

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

    #[test]
    fn test_metrics_hub_recording() {
        let hub = MetricsHub::with_defaults();

        // Record various metrics
        hub.record_llm_call(100, 50, 150, true);
        hub.record_pilot_decision(0.9, InterventionPoint::Fork);
        hub.record_retrieval_query(5, 10, 100);

        let report = hub.generate_report();

        assert_eq!(report.llm.total_calls, 1);
        assert_eq!(report.pilot.total_decisions, 1);
        assert_eq!(report.retrieval.total_queries, 1);
    }

    #[test]
    fn test_metrics_hub_disabled() {
        let config = MetricsConfig::disabled();
        let hub = MetricsHub::new(config);

        hub.record_llm_call(100, 50, 150, true);
        hub.record_pilot_decision(0.9, InterventionPoint::Fork);

        let report = hub.generate_report();

        assert_eq!(report.llm.total_calls, 0);
        assert_eq!(report.pilot.total_decisions, 0);
    }

    #[test]
    fn test_metrics_hub_reset() {
        let hub = MetricsHub::with_defaults();

        hub.record_llm_call(100, 50, 150, true);
        hub.reset();

        let report = hub.generate_report();
        assert_eq!(report.llm.total_calls, 0);
    }

    #[test]
    fn test_llm_metrics_success_and_failure() {
        let hub = MetricsHub::with_defaults();

        // Record successes
        hub.record_llm_call(100, 50, 150, true);
        hub.record_llm_call(200, 100, 300, true);

        // Record failure
        hub.record_llm_call(0, 0, 50, false);

        let report = hub.llm_report();
        assert_eq!(report.total_calls, 3);
        assert_eq!(report.successful_calls, 2);
        assert_eq!(report.failed_calls, 1);
        assert!((report.success_rate - 0.666).abs() < 0.01);
        assert_eq!(report.total_input_tokens, 300);
        assert_eq!(report.total_output_tokens, 150);
    }

    #[test]
    fn test_llm_error_events() {
        let hub = MetricsHub::with_defaults();

        hub.record_llm_rate_limit();
        hub.record_llm_rate_limit();
        hub.record_llm_timeout();
        hub.record_llm_fallback();

        let report = hub.llm_report();
        assert_eq!(report.rate_limit_errors, 2);
        assert_eq!(report.timeout_errors, 1);
        assert_eq!(report.fallback_triggers, 1);
    }

    #[test]
    fn test_shared_arc_metrics() {
        let hub = MetricsHub::shared();

        // Clone the Arc — both references point to the same hub
        let hub2 = hub.clone();
        hub.record_llm_call(100, 50, 100, true);
        hub2.record_llm_call(200, 100, 200, true);

        let report = hub.generate_report();
        assert_eq!(report.llm.total_calls, 2);
        assert_eq!(report.llm.total_input_tokens, 300);
    }

    #[test]
    fn test_metrics_report_cost() {
        let hub = MetricsHub::with_defaults();

        hub.record_llm_call(1000, 500, 200, true);

        let report = hub.generate_report();
        // Cost should be positive (exact value depends on config pricing)
        assert!(report.total_cost_usd() >= 0.0);
    }
}