metrics.rs 90.8 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
// SPDX-License-Identifier: Apache-2.0

4
5
6
7
8
9
10
use axum::{
    Router,
    extract::State,
    http::StatusCode,
    response::{IntoResponse, sse::Event},
    routing::get,
};
11
12
13
14
15
use dynamo_runtime::{
    config::environment_names::llm::metrics as env_metrics,
    metrics::prometheus_names::{
        frontend_service, name_prefix, sanitize_frontend_prometheus_prefix,
    },
16
};
17
18
19
use prometheus::{
    Encoder, GaugeVec, HistogramOpts, HistogramVec, IntCounterVec, IntGaugeVec, Opts,
};
20
use serde::Serialize;
21
use std::{
22
    sync::{Arc, LazyLock},
23
24
    time::{Duration, Instant},
};
25

26
use crate::local_model::runtime_config::ModelRuntimeConfig;
27
use crate::model_card::ModelDeploymentCard;
28
29
use dynamo_runtime::metrics::prometheus_names::clamp_u64_to_i64;

30
31
32
33
34
35
36
37
38
use dynamo_runtime::error::ErrorType as DynamoErrorType;

/// Check whether an error chain indicates the request was rejected.
pub fn request_was_rejected(err: &(dyn std::error::Error + 'static)) -> bool {
    const REJECTION: &[DynamoErrorType] = &[DynamoErrorType::ResourceExhausted];
    const NON_REJECTION: &[DynamoErrorType] = &[];
    dynamo_runtime::error::match_error_chain(err, REJECTION, NON_REJECTION)
}

39
40
41
42
43
44
45
/// Check whether an error chain indicates the request was cancelled.
pub fn request_was_cancelled(err: &(dyn std::error::Error + 'static)) -> bool {
    const CANCELLATION: &[DynamoErrorType] = &[DynamoErrorType::Cancelled];
    const NON_CANCELLATION: &[DynamoErrorType] = &[];
    dynamo_runtime::error::match_error_chain(err, CANCELLATION, NON_CANCELLATION)
}

46
47
pub use prometheus::Registry;

48
use super::RouteDoc;
49

50
51
/// Worker type label values for Prometheus timing metrics
pub use crate::discovery::{WORKER_TYPE_DECODE, WORKER_TYPE_PREFILL};
52
const UNSET_DP_RANK_LABEL: &str = "none";
53
54
55
56
57
58
59

/// Global Prometheus gauge for last observed TTFT per worker (in seconds)
/// Labels: worker_id, dp_rank, worker_type
pub static WORKER_LAST_TIME_TO_FIRST_TOKEN_GAUGE: LazyLock<GaugeVec> = LazyLock::new(|| {
    GaugeVec::new(
        Opts::new(
            format!(
60
61
                "{}_{}",
                name_prefix::FRONTEND,
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
                frontend_service::WORKER_LAST_TIME_TO_FIRST_TOKEN_SECONDS
            ),
            "Last observed time to first token per worker (seconds)",
        ),
        &["worker_id", "dp_rank", "worker_type"],
    )
    .expect("Failed to create worker_last_time_to_first_token gauge")
});

/// Global Prometheus gauge for last observed input sequence tokens per worker
/// Labels: worker_id, dp_rank, worker_type
/// Updated atomically with TTFT - represents the input token count from the same request
pub static WORKER_LAST_INPUT_SEQUENCE_TOKENS_GAUGE: LazyLock<IntGaugeVec> = LazyLock::new(|| {
    IntGaugeVec::new(
        Opts::new(
            format!(
78
79
                "{}_{}",
                name_prefix::FRONTEND,
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
                frontend_service::WORKER_LAST_INPUT_SEQUENCE_TOKENS
            ),
            "Last observed input sequence tokens per worker",
        ),
        &["worker_id", "dp_rank", "worker_type"],
    )
    .expect("Failed to create worker_last_input_sequence_tokens gauge")
});

/// Global Prometheus gauge for last observed ITL per worker (in seconds)
/// Labels: worker_id, dp_rank, worker_type
pub static WORKER_LAST_INTER_TOKEN_LATENCY_GAUGE: LazyLock<GaugeVec> = LazyLock::new(|| {
    GaugeVec::new(
        Opts::new(
            format!(
95
96
                "{}_{}",
                name_prefix::FRONTEND,
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
                frontend_service::WORKER_LAST_INTER_TOKEN_LATENCY_SECONDS
            ),
            "Last observed inter-token latency per worker (seconds)",
        ),
        &["worker_id", "dp_rank", "worker_type"],
    )
    .expect("Failed to create worker_last_inter_token_latency gauge")
});

/// Register the global per-worker TTFT/ITL/input-tokens Prometheus metrics with the given registry.
///
/// This should be called once during HTTP service setup to expose the metrics
/// via the `/metrics` endpoint.
///
/// # Errors
/// Returns an error if the metrics are already registered with the registry.
pub fn register_worker_timing_metrics(registry: &Registry) -> Result<(), prometheus::Error> {
    registry.register(Box::new(WORKER_LAST_TIME_TO_FIRST_TOKEN_GAUGE.clone()))?;
    registry.register(Box::new(WORKER_LAST_INPUT_SEQUENCE_TOKENS_GAUGE.clone()))?;
    registry.register(Box::new(WORKER_LAST_INTER_TOKEN_LATENCY_GAUGE.clone()))?;
    Ok(())
}

120
121
122
123
124
125
126
127
128
129
130
131
132
133
/// Generate log-spaced histogram buckets with values rounded to 2 significant figures.
///
/// # Arguments
/// * `min` - Minimum value for the buckets (must be > 0 for log spacing)
/// * `max` - Maximum value for the buckets (must be > min)
/// * `count` - Number of buckets to generate
///
/// # Returns
/// A vector of log-spaced values, always starting with 0.0 and ending with the rounded max value.
/// Duplicates created by rounding are removed, so the final count may be less than requested.
///
/// # Note
/// With 2 significant figures, there are roughly 90 unique values per order of magnitude.
/// Requesting more buckets than can be uniquely represented will result in deduplication.
134
pub fn generate_log_buckets(min: f64, max: f64, count: usize) -> Vec<f64> {
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
    if count == 0 {
        return vec![];
    }
    if count == 1 {
        return vec![0.0];
    }

    let requested_count = count;
    let mut buckets = Vec::with_capacity(count);
    buckets.push(0.0);

    // Generate log-spaced values from min to max
    for i in 1..count {
        let log_min = min.ln();
        let log_max = max.ln();
        let log_value = log_min + (log_max - log_min) * (i as f64) / ((count - 1) as f64);
        let value = log_value.exp();
        buckets.push(round_to_sig_figs(value, 2));
    }

    // Remove consecutive duplicates (buckets are already sorted)
    let original_len = buckets.len();
    buckets.dedup();

    // Warn if significant deduplication occurred
    if buckets.len() < original_len && (original_len - buckets.len()) > original_len / 10 {
        tracing::warn!(
            requested = requested_count,
            unique = buckets.len(),
            duplicates = original_len - buckets.len(),
            min = min,
            max = max,
            "Histogram bucket generation: Significant duplicate values after rounding to 2 sig figs. \
             Consider reducing bucket count or increasing range."
        );
    }

    buckets
}

/// Round a number to a specified number of significant figures
176
pub fn round_to_sig_figs(value: f64, sig_figs: u32) -> f64 {
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
    if value == 0.0 {
        return 0.0;
    }

    let magnitude = value.abs().log10().floor();
    let scale = 10_f64.powf(sig_figs as f64 - 1.0 - magnitude);
    (value * scale).round() / scale
}

const MAX_BUCKET_COUNT: usize = 512;

fn validate_bucket_config(min: f64, max: f64, count: usize) -> bool {
    min.is_finite()
        && max.is_finite()
        && min > 0.0
        && min < max
        && count > 0
        && count <= MAX_BUCKET_COUNT
}

/// Parse histogram bucket configuration from environment variables
/// Returns (min, max, count) with defaults if not specified
fn parse_bucket_config(
    env_prefix: &str,
    default_min: f64,
    default_max: f64,
    default_count: usize,
) -> (f64, f64, usize) {
    if !validate_bucket_config(default_min, default_max, default_count) {
        tracing::error!(
            default_min,
            default_max,
            default_count,
            "Invalid default histogram configuration"
        );
        return (1.0, 10.0, 10);
    }
214
    let env_prefix = format!("{}{}", env_metrics::HISTOGRAM_PREFIX, env_prefix);
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
    let mut min = std::env::var(format!("{env_prefix}_MIN"))
        .ok()
        .and_then(|s| s.parse::<f64>().ok())
        .unwrap_or(default_min);
    let mut max = std::env::var(format!("{env_prefix}_MAX"))
        .ok()
        .and_then(|s| s.parse::<f64>().ok())
        .unwrap_or(default_max);
    let mut count = std::env::var(format!("{env_prefix}_COUNT"))
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .unwrap_or(default_count);

    if !validate_bucket_config(min, max, count) {
        tracing::warn!(
            min=%min,
            max=%max,
            count=%count,
            "Invalid histogram configuration given, using defaults"
        );
        min = default_min;
        max = default_max;
        count = default_count;
    }

    (min, max, count)
}

243
244
245
246
/// State for metrics handler.
/// Optionally holds a reference to the DRT's [`MetricsRegistry`] so that
/// metrics created via `metrics().create*()` anywhere in the process are
/// automatically included in the `/metrics` response.
247
248
struct MetricsHandlerState {
    registry: Arc<Registry>,
249
    drt_metrics: Option<dynamo_runtime::metrics::MetricsRegistry>,
250
251
}

252
253
pub struct Metrics {
    request_counter: IntCounterVec,
254
    /// Deprecated: use `active_requests_gauge`. Kept for backwards compatibility until Phase 3.
255
    inflight_gauge: IntGaugeVec,
256
    active_requests_gauge: IntGaugeVec,
257
    client_disconnect_gauge: prometheus::IntGauge,
258
    http_queue_gauge: IntGaugeVec,
259
    request_duration: HistogramVec,
260
261
    input_sequence_length: HistogramVec,
    output_sequence_length: HistogramVec,
262
    cached_tokens: HistogramVec,
263
    tokenizer_latency: HistogramVec,
264
    output_tokens_counter: IntCounterVec,
265
266
    time_to_first_token: HistogramVec,
    inter_token_latency: HistogramVec,
267
268
269
270
271
272
273
274
275
276

    // Runtime configuration metrics. Note: Some of these metrics represent counter-like values from
    // source systems, but are implemented as gauges because they are copied/synchronized from upstream
    // counter values rather than being directly incremented.
    model_total_kv_blocks: IntGaugeVec,
    model_max_num_seqs: IntGaugeVec,
    model_max_num_batched_tokens: IntGaugeVec,
    model_context_length: IntGaugeVec,
    model_kv_cache_block_size: IntGaugeVec,
    model_migration_limit: IntGaugeVec,
277
    model_migration_total: IntCounterVec,
278
    model_migration_max_seq_len_exceeded_total: IntCounterVec,
279
    model_cancellation_total: IntCounterVec,
280
    model_rejection_total: IntCounterVec,
281
282
}

283
284
285
286
287
288
289
290
291
292
293
294
// Inflight tracks requests from HTTP handler start until complete response is finished.
// HTTP queue tracks requests from HTTP handler start until first token generation begins (including prefill time).
// HTTP queue time is a subset of inflight time. For detailed explanation, see:
// deploy/metrics/README.md - "Request Processing Flow" section

/// RAII object for HTTP queue gauge
/// Tracks requests from HTTP handler start until metrics processing begins
pub struct HttpQueueGuard {
    metrics: Arc<Metrics>,
    model: String,
}

295
296
/// RAII object for inflight gauge and request counters
/// If this object is dropped without calling `mark_ok`, then the request will increment
297
298
/// the request counter with the `status` label with [`frontend_service::status::ERROR`]; otherwise, it will increment
/// the counter with `status` label [`frontend_service::status::SUCCESS`]
299
300
301
302
303
304
pub struct InflightGuard {
    metrics: Arc<Metrics>,
    model: String,
    endpoint: Endpoint,
    request_type: RequestType,
    status: Status,
305
    error_type: ErrorType,
306
    timer: Instant,
307
    request_id: String,
308
    span: tracing::Span,
309
310
311
312
}

/// Requests will be logged by the type of endpoint hit
/// This will include llamastack in the future
313
#[derive(Clone, Copy)]
314
315
316
317
318
319
pub enum Endpoint {
    /// OAI Completions
    Completions,

    /// OAI Chat Completions
    ChatCompletions,
320
321
322

    /// OAI Embeddings
    Embeddings,
323

324
325
326
    /// OAI Images
    Images,

327
328
329
    /// OAI Videos
    Videos,

330
331
332
    /// OAI Audio Speech
    Audios,

333
334
    /// OAI Responses
    Responses,
335

336
337
338
    /// Anthropic Messages
    AnthropicMessages,

339
340
    /// Tensor
    Tensor,
341
342
343
344
345
346
347
348
349
350
351
}

/// Metrics for the HTTP service
pub enum RequestType {
    /// SingleIn / SingleOut
    Unary,

    /// SingleIn / ManyOut
    Stream,
}

352
353
354
355
356
357
358
/// Labels for cancellation metrics
pub struct CancellationLabels {
    pub model: String,
    pub endpoint: String,
    pub request_type: String,
}

359
/// Status
360
#[derive(PartialEq)]
361
362
363
364
365
pub enum Status {
    Success,
    Error,
}

366
367
368
369
370
371
372
373
374
375
376
377
378
/// Error type classification for fine-grained observability
#[derive(PartialEq, Clone, Debug)]
pub enum ErrorType {
    /// No error (for successful requests)
    None,
    /// Client validation error (4xx with "Validation:" prefix)
    Validation,
    /// Model or resource not found (404)
    NotFound,
    /// Service overloaded, too many requests (503)
    Overload,
    /// Request cancelled by client or timeout
    Cancelled,
379
380
    /// Backend accepted the request but stopped responding (response inactivity timeout)
    ResponseTimeout,
381
382
383
384
385
386
    /// Internal server error (500 and other unexpected errors)
    Internal,
    /// Feature not implemented (501)
    NotImplemented,
}

387
388
389
390
391
392
393
394
395
396
397
398
/// Track response-specific metrics
pub struct ResponseMetricCollector {
    metrics: Arc<Metrics>,
    model: String,
    start_time: Instant,
    // we use is_first_token to distinguish TTFT from ITL. It is true by default and
    // flipped to false when the first token is returned and TTFT is published.
    is_first_token: bool,
    // we track the last response time so that ITL for the newly returned tokens can
    // be computed.
    last_response_time: Option<Duration>,
    osl: usize,
399
400
401
402
    isl: usize,
    ttft_ms: Option<f64>,
    itl_sum_secs: f64,
    itl_count: u64,
403
404
    // we track if cached_tokens has been observed to ensure we only increment once per request
    cached_tokens_observed: bool,
405
406
407
408
409
    // we track if tokenize latency has been observed to ensure we only increment once per request
    tokenize_latency_observed: bool,
    // latest accumulated detokenize latency and sample count reported by tracker
    detokenize_latency_total: Duration,
    detokenize_count_total: u64,
410
411
412
413
414
415
416
417
418
419
    // Prefill worker info for TTFT attribution (set from LLMMetricAnnotation)
    prefill_worker_id: Option<u64>,
    prefill_dp_rank: Option<u32>,
    // Prefill worker type for Prometheus labeling - stored at routing time to avoid MDC lookup
    prefill_worker_type: Option<String>,
    // Decode worker info for ITL attribution (set from LLMMetricAnnotation)
    decode_worker_id: Option<u64>,
    decode_dp_rank: Option<u32>,
    // Decode worker type for Prometheus labeling - stored at routing time to avoid MDC lookup
    decode_worker_type: Option<String>,
420
421
}

422
423
impl Default for Metrics {
    fn default() -> Self {
424
        Self::new()
425
426
427
428
    }
}

impl Metrics {
429
    /// Create Metrics with the standard prefix defined by [`name_prefix::FRONTEND`] or specify custom prefix via the following environment variable:
430
431
432
433
    /// - `DYN_METRICS_PREFIX`: Override the default metrics prefix
    ///
    /// The following metrics will be created with the configured prefix:
    /// - `{prefix}_requests_total` - IntCounterVec for the total number of requests processed
434
435
    /// - `{prefix}_inflight_requests` - IntGaugeVec for the number of inflight/concurrent requests
    /// - `{prefix}_disconnected_clients` - IntGauge for the number of disconnected clients
436
437
438
    /// - `{prefix}_request_duration_seconds` - HistogramVec for the duration of requests
    /// - `{prefix}_input_sequence_tokens` - HistogramVec for input sequence length in tokens
    /// - `{prefix}_output_sequence_tokens` - HistogramVec for output sequence length in tokens
439
    /// - `{prefix}_tokenizer_latency_ms` - HistogramVec for tokenizer latency in milliseconds
440
    /// - `{prefix}_output_tokens_total` - IntCounterVec for total output tokens generated (real-time updates)
441
442
    /// - `{prefix}_time_to_first_token_seconds` - HistogramVec for time to first token in seconds
    /// - `{prefix}_inter_token_latency_seconds` - HistogramVec for inter-token latency in seconds
443
    ///
444
445
446
447
448
449
450
451
452
453
454
    /// ## Histogram Bucket Configuration
    ///
    /// All histograms use log-spaced buckets rounded to 2 significant figures. Bucket configuration
    /// can be customized via environment variables (MIN: minimum value, MAX: maximum value, COUNT: number of buckets):
    ///
    /// - `DYN_METRICS_REQUEST_DURATION_{MIN,MAX,COUNT}` - Request duration histogram (defaults: 1.0, 256.0, 10)
    /// - `DYN_METRICS_INPUT_SEQUENCE_{MIN,MAX,COUNT}` - Input sequence length histogram (defaults: 50.0, 128000.0, 12)
    /// - `DYN_METRICS_OUTPUT_SEQUENCE_{MIN,MAX,COUNT}` - Output sequence length histogram (defaults: 50.0, 32000.0, 10)
    /// - `DYN_METRICS_TTFT_{MIN,MAX,COUNT}` - Time to first token histogram (defaults: 0.001, 480.0, 18)
    /// - `DYN_METRICS_ITL_{MIN,MAX,COUNT}` - Inter-token latency histogram (defaults: 0.001, 2.0, 13)
    ///
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
    /// ## Model Configuration Metrics
    ///
    /// Runtime config metrics (from ModelRuntimeConfig):
    /// - `{prefix}_model_total_kv_blocks` - IntGaugeVec for total KV cache blocks available for a worker serving the model
    /// - `{prefix}_model_max_num_seqs` - IntGaugeVec for maximum sequences for a worker serving the model
    /// - `{prefix}_model_max_num_batched_tokens` - IntGaugeVec for maximum batched tokens for a worker serving the model
    ///
    /// MDC metrics (from ModelDeploymentCard):
    /// - `{prefix}_model_context_length` - IntGaugeVec for maximum context length for a worker serving the model
    /// - `{prefix}_model_kv_cache_block_size` - IntGaugeVec for KV cache block size for a worker serving the model
    /// - `{prefix}_model_migration_limit` - IntGaugeVec for request migration limit for a worker serving the model
    ///
    /// ## Runtime Config Polling Configuration
    ///
    /// The polling behavior can be configured via environment variables:
    /// - `DYN_HTTP_SVC_CONFIG_METRICS_POLL_INTERVAL_SECS`: Poll interval in seconds (must be > 0, supports fractional seconds, defaults to 8)
    ///
    /// Metrics are never removed to preserve historical data. Runtime config and MDC
    /// metrics are updated when models are discovered and their configurations are available.
474
    pub fn new() -> Self {
475
476
477
        // TODO: Remove DYN_METRICS_PREFIX env-var override (added in PR #2432 for
        // NIM compatibility with the old "nv_llm_http_service_" prefix). No longer
        // needed — hardcode name_prefix::FRONTEND and drop the sanitize function.
478
        let raw_prefix = std::env::var(env_metrics::DYN_METRICS_PREFIX)
479
480
            .unwrap_or_else(|_| name_prefix::FRONTEND.to_string());
        let prefix = sanitize_frontend_prometheus_prefix(&raw_prefix);
481
482
483
484
        if prefix != raw_prefix {
            tracing::warn!(
                raw=%raw_prefix,
                sanitized=%prefix,
485
                env=%frontend_service::METRICS_PREFIX_ENV,
486
487
488
489
490
                "Sanitized HTTP metrics prefix"
            );
        }
        let frontend_metric_name = |suffix: &str| format!("{}_{}", &prefix, suffix);

491
492
        let request_counter = IntCounterVec::new(
            Opts::new(
493
                frontend_metric_name(frontend_service::REQUESTS_TOTAL),
494
495
                "Total number of LLM requests processed",
            ),
496
            &["model", "endpoint", "request_type", "status", "error_type"],
497
498
499
500
501
        )
        .unwrap();

        let inflight_gauge = IntGaugeVec::new(
            Opts::new(
502
                frontend_metric_name(frontend_service::INFLIGHT_REQUESTS),
503
504
505
506
507
508
                "Number of inflight requests",
            ),
            &["model"],
        )
        .unwrap();

509
510
511
512
513
514
515
516
517
        let active_requests_gauge = IntGaugeVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::ACTIVE_REQUESTS),
                "Number of requests currently being handled by the frontend, from HTTP handler entry to response completion",
            ),
            &["model"],
        )
        .unwrap();

518
        let client_disconnect_gauge = prometheus::IntGauge::new(
519
520
            frontend_metric_name(frontend_service::DISCONNECTED_CLIENTS),
            "Number of disconnected clients",
521
522
523
        )
        .unwrap();

524
525
        let http_queue_gauge = IntGaugeVec::new(
            Opts::new(
526
                frontend_metric_name(frontend_service::QUEUED_REQUESTS),
527
528
529
530
531
532
                "Number of requests in HTTP processing queue",
            ),
            &["model"],
        )
        .unwrap();

533
534
        // Request duration buckets: configurable via DYN_METRICS_REQUEST_DURATION_{MIN,MAX,COUNT}
        let (req_dur_min, req_dur_max, req_dur_count) =
535
            parse_bucket_config("DYN_METRICS_REQUEST_DURATION", 1.0, 512.0, 10);
536
537
        let request_duration_buckets =
            generate_log_buckets(req_dur_min, req_dur_max, req_dur_count);
538
539
540

        let request_duration = HistogramVec::new(
            HistogramOpts::new(
541
                frontend_metric_name(frontend_service::REQUEST_DURATION_SECONDS),
542
543
                "Duration of LLM requests",
            )
544
            .buckets(request_duration_buckets),
545
546
547
548
            &["model"],
        )
        .unwrap();

549
550
551
552
553
        // Input sequence length buckets: configurable via DYN_METRICS_INPUT_SEQUENCE_{MIN,MAX,COUNT}
        let (isl_min, isl_max, isl_count) =
            parse_bucket_config("DYN_METRICS_INPUT_SEQUENCE", 50.0, 128000.0, 12);
        let input_sequence_buckets = generate_log_buckets(isl_min, isl_max, isl_count);

554
555
        let input_sequence_length = HistogramVec::new(
            HistogramOpts::new(
556
                frontend_metric_name(frontend_service::INPUT_SEQUENCE_TOKENS),
557
558
                "Input sequence length in tokens",
            )
559
            .buckets(input_sequence_buckets.clone()),
560
561
562
563
            &["model"],
        )
        .unwrap();

564
565
566
567
568
        // Output sequence length buckets: configurable via DYN_METRICS_OUTPUT_SEQUENCE_{MIN,MAX,COUNT}
        let (osl_min, osl_max, osl_count) =
            parse_bucket_config("DYN_METRICS_OUTPUT_SEQUENCE", 50.0, 32000.0, 10);
        let output_sequence_buckets = generate_log_buckets(osl_min, osl_max, osl_count);

569
570
        let output_sequence_length = HistogramVec::new(
            HistogramOpts::new(
571
                frontend_metric_name(frontend_service::OUTPUT_SEQUENCE_TOKENS),
572
573
                "Output sequence length in tokens",
            )
574
            .buckets(output_sequence_buckets),
575
576
577
578
            &["model"],
        )
        .unwrap();

579
580
581
582
583
584
585
586
587
        let output_tokens_counter = IntCounterVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::OUTPUT_TOKENS_TOTAL),
                "Total number of output tokens generated (updates in real-time)",
            ),
            &["model"],
        )
        .unwrap();

588
589
590
591
592
        // Time to first token buckets: configurable via DYN_METRICS_TTFT_{MIN,MAX,COUNT}
        let (ttft_min, ttft_max, ttft_count) =
            parse_bucket_config("DYN_METRICS_TTFT", 0.001, 480.0, 18);
        let time_to_first_token_buckets = generate_log_buckets(ttft_min, ttft_max, ttft_count);

593
594
        let time_to_first_token = HistogramVec::new(
            HistogramOpts::new(
595
                frontend_metric_name(frontend_service::TIME_TO_FIRST_TOKEN_SECONDS),
596
597
                "Time to first token in seconds",
            )
598
            .buckets(time_to_first_token_buckets),
599
600
601
602
            &["model"],
        )
        .unwrap();

603
604
605
606
        // Inter-token latency buckets: configurable via DYN_METRICS_ITL_{MIN,MAX,COUNT}
        let (itl_min, itl_max, itl_count) = parse_bucket_config("DYN_METRICS_ITL", 0.001, 2.0, 13);
        let inter_token_latency_buckets = generate_log_buckets(itl_min, itl_max, itl_count);

607
608
        let inter_token_latency = HistogramVec::new(
            HistogramOpts::new(
609
                frontend_metric_name(frontend_service::INTER_TOKEN_LATENCY_SECONDS),
610
611
                "Inter-token latency in seconds",
            )
612
            .buckets(inter_token_latency_buckets),
613
614
615
616
            &["model"],
        )
        .unwrap();

617
618
619
620
621
622
623
624
625
626
        let cached_tokens = HistogramVec::new(
            HistogramOpts::new(
                frontend_metric_name(frontend_service::CACHED_TOKENS),
                "Number of cached tokens (prefix cache hits) per request",
            )
            .buckets(input_sequence_buckets.clone()),
            &["model"],
        )
        .unwrap();

627
628
629
630
631
632
633
634
635
636
637
638
        let tokenizer_latency = HistogramVec::new(
            HistogramOpts::new(
                frontend_metric_name(frontend_service::TOKENIZER_LATENCY_MS),
                "Tokenizer latency in milliseconds",
            )
            .buckets(vec![
                0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0,
            ]),
            &[frontend_service::OPERATION_LABEL],
        )
        .unwrap();

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
        // Runtime configuration metrics
        // Note: Some of these metrics represent counter-like values from source systems,
        // but are implemented as gauges because they are copied/synchronized from upstream
        // counter values rather than being directly incremented.
        let model_total_kv_blocks = IntGaugeVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_TOTAL_KV_BLOCKS),
                "Total KV cache blocks available for a worker serving the model",
            ),
            &["model"],
        )
        .unwrap();

        let model_max_num_seqs = IntGaugeVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_MAX_NUM_SEQS),
                "Maximum number of sequences for a worker serving the model",
            ),
            &["model"],
        )
        .unwrap();

        let model_max_num_batched_tokens = IntGaugeVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_MAX_NUM_BATCHED_TOKENS),
                "Maximum number of batched tokens for a worker serving the model",
            ),
            &["model"],
        )
        .unwrap();

        let model_context_length = IntGaugeVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_CONTEXT_LENGTH),
                "Maximum context length in tokens for a worker serving the model",
            ),
            &["model"],
        )
        .unwrap();

        let model_kv_cache_block_size = IntGaugeVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_KV_CACHE_BLOCK_SIZE),
                "KV cache block size in tokens for a worker serving the model",
            ),
            &["model"],
        )
        .unwrap();

        let model_migration_limit = IntGaugeVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_MIGRATION_LIMIT),
                "Maximum number of request migrations allowed for the model",
            ),
            &["model"],
        )
        .unwrap();

697
698
699
700
701
702
703
704
705
        let model_migration_total = IntCounterVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_MIGRATION_TOTAL),
                "Total number of request migrations due to worker unavailability",
            ),
            &["model", frontend_service::MIGRATION_TYPE_LABEL],
        )
        .unwrap();

706
707
708
709
710
711
712
713
714
        let model_migration_max_seq_len_exceeded_total = IntCounterVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_MIGRATION_MAX_SEQ_LEN_EXCEEDED_TOTAL),
                "Total number of times migration was disabled by max_seq_len limit",
            ),
            &["model"],
        )
        .unwrap();

715
716
717
718
719
720
721
722
723
        let model_cancellation_total = IntCounterVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_CANCELLATION_TOTAL),
                "Total number of request cancellations",
            ),
            &["model", "endpoint", "request_type"],
        )
        .unwrap();

724
725
726
727
728
729
730
731
732
        let model_rejection_total = IntCounterVec::new(
            Opts::new(
                frontend_metric_name(frontend_service::MODEL_REJECTION_TOTAL),
                "Total number of requests rejected due to resource exhaustion",
            ),
            &["model", "endpoint"],
        )
        .unwrap();

733
734
735
        Metrics {
            request_counter,
            inflight_gauge,
736
            active_requests_gauge,
737
            client_disconnect_gauge,
738
            http_queue_gauge,
739
            request_duration,
740
741
            input_sequence_length,
            output_sequence_length,
742
            cached_tokens,
743
            tokenizer_latency,
744
            output_tokens_counter,
745
746
            time_to_first_token,
            inter_token_latency,
747
748
749
750
751
752
            model_total_kv_blocks,
            model_max_num_seqs,
            model_max_num_batched_tokens,
            model_context_length,
            model_kv_cache_block_size,
            model_migration_limit,
753
            model_migration_total,
754
            model_migration_max_seq_len_exceeded_total,
755
            model_cancellation_total,
756
            model_rejection_total,
757
758
759
760
761
762
763
764
765
766
767
768
769
770
        }
    }

    /// Get the number of successful requests for the given dimensions:
    /// - model
    /// - endpoint (completions/chat_completions)
    /// - request type (unary/stream)
    /// - status (success/error)
    pub fn get_request_counter(
        &self,
        model: &str,
        endpoint: &Endpoint,
        request_type: &RequestType,
        status: &Status,
771
        error_type: &ErrorType,
772
773
774
775
776
777
778
    ) -> u64 {
        self.request_counter
            .with_label_values(&[
                model,
                endpoint.as_str(),
                request_type.as_str(),
                status.as_str(),
779
                error_type.as_str(),
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
            ])
            .get()
    }

    /// Increment the counter for requests for the given dimensions:
    /// - model
    /// - endpoint (completions/chat_completions)
    /// - request type (unary/stream)
    /// - status (success/error)
    fn inc_request_counter(
        &self,
        model: &str,
        endpoint: &Endpoint,
        request_type: &RequestType,
        status: &Status,
795
        error_type: &ErrorType,
796
797
798
799
800
801
802
    ) {
        self.request_counter
            .with_label_values(&[
                model,
                endpoint.as_str(),
                request_type.as_str(),
                status.as_str(),
803
                error_type.as_str(),
804
805
806
807
808
809
810
811
812
813
            ])
            .inc()
    }

    /// Get the number if inflight requests for the given model
    pub fn get_inflight_count(&self, model: &str) -> i64 {
        self.inflight_gauge.with_label_values(&[model]).get()
    }

    fn inc_inflight_gauge(&self, model: &str) {
814
815
        self.inflight_gauge.with_label_values(&[model]).inc();
        self.active_requests_gauge.with_label_values(&[model]).inc();
816
817
818
    }

    fn dec_inflight_gauge(&self, model: &str) {
819
820
        self.inflight_gauge.with_label_values(&[model]).dec();
        self.active_requests_gauge.with_label_values(&[model]).dec();
821
822
    }

823
824
825
826
827
828
829
830
831
832
    /// Increment the gauge for client disconnections
    pub fn inc_client_disconnect(&self) {
        self.client_disconnect_gauge.inc();
    }

    /// Get the count of client disconnections
    pub fn get_client_disconnect_count(&self) -> i64 {
        self.client_disconnect_gauge.get()
    }

833
834
835
836
837
838
839
840
    fn inc_http_queue_gauge(&self, model: &str) {
        self.http_queue_gauge.with_label_values(&[model]).inc()
    }

    fn dec_http_queue_gauge(&self, model: &str) {
        self.http_queue_gauge.with_label_values(&[model]).dec()
    }

841
842
843
    pub fn register(&self, registry: &Registry) -> Result<(), prometheus::Error> {
        registry.register(Box::new(self.request_counter.clone()))?;
        registry.register(Box::new(self.inflight_gauge.clone()))?;
844
        registry.register(Box::new(self.active_requests_gauge.clone()))?;
845
        registry.register(Box::new(self.client_disconnect_gauge.clone()))?;
846
        registry.register(Box::new(self.http_queue_gauge.clone()))?;
847
        registry.register(Box::new(self.request_duration.clone()))?;
848
849
        registry.register(Box::new(self.input_sequence_length.clone()))?;
        registry.register(Box::new(self.output_sequence_length.clone()))?;
850
        registry.register(Box::new(self.cached_tokens.clone()))?;
851
        registry.register(Box::new(self.tokenizer_latency.clone()))?;
852
        registry.register(Box::new(self.output_tokens_counter.clone()))?;
853
854
        registry.register(Box::new(self.time_to_first_token.clone()))?;
        registry.register(Box::new(self.inter_token_latency.clone()))?;
855
856
857
858
859
860
861
862

        // Register runtime configuration metrics
        registry.register(Box::new(self.model_total_kv_blocks.clone()))?;
        registry.register(Box::new(self.model_max_num_seqs.clone()))?;
        registry.register(Box::new(self.model_max_num_batched_tokens.clone()))?;
        registry.register(Box::new(self.model_context_length.clone()))?;
        registry.register(Box::new(self.model_kv_cache_block_size.clone()))?;
        registry.register(Box::new(self.model_migration_limit.clone()))?;
863
        registry.register(Box::new(self.model_migration_total.clone()))?;
864
865
866
        registry.register(Box::new(
            self.model_migration_max_seq_len_exceeded_total.clone(),
        ))?;
867
        registry.register(Box::new(self.model_cancellation_total.clone()))?;
868
        registry.register(Box::new(self.model_rejection_total.clone()))?;
869

870
871
872
        Ok(())
    }

873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
    /// Update runtime configuration metrics for a model
    /// This should be called when model runtime configuration is available or updated
    pub fn update_runtime_config_metrics(
        &self,
        model_name: &str,
        runtime_config: &ModelRuntimeConfig,
    ) {
        if let Some(total_kv_blocks) = runtime_config.total_kv_blocks {
            self.model_total_kv_blocks
                .with_label_values(&[model_name])
                .set(clamp_u64_to_i64(total_kv_blocks));
        }

        if let Some(max_num_seqs) = runtime_config.max_num_seqs {
            self.model_max_num_seqs
                .with_label_values(&[model_name])
                .set(clamp_u64_to_i64(max_num_seqs));
        }

        if let Some(max_batched_tokens) = runtime_config.max_num_batched_tokens {
            self.model_max_num_batched_tokens
                .with_label_values(&[model_name])
                .set(clamp_u64_to_i64(max_batched_tokens));
        }
    }

899
    /// Update metrics from a ModelDeploymentCard
900
    /// This updates both runtime config metrics and MDC-specific metrics
901
902
    pub fn update_metrics_from_mdc(&self, card: &ModelDeploymentCard) -> anyhow::Result<()> {
        self.update_runtime_config_metrics(&card.display_name, &card.runtime_config);
903

904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
        self.model_context_length
            .with_label_values(&[&card.display_name])
            .set(card.context_length as i64);

        self.model_kv_cache_block_size
            .with_label_values(&[&card.display_name])
            .set(card.kv_cache_block_size as i64);

        self.model_migration_limit
            .with_label_values(&[&card.display_name])
            .set(card.migration_limit as i64);

        tracing::debug!(
            model = %card.display_name,
            "Successfully updated MDC metrics"
        );
920
921
922
923

        Ok(())
    }

924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
    /// Increment the migration counter for a new request migration
    pub fn inc_migration_new_request(&self, model: &str) {
        self.model_migration_total
            .with_label_values(&[model, frontend_service::migration_type::NEW_REQUEST])
            .inc();
    }

    /// Increment the migration counter for an ongoing request migration
    pub fn inc_migration_ongoing_request(&self, model: &str) {
        self.model_migration_total
            .with_label_values(&[model, frontend_service::migration_type::ONGOING_REQUEST])
            .inc();
    }

    /// Get the current count of new request migrations for a model
    pub fn get_migration_new_request_count(&self, model: &str) -> u64 {
        self.model_migration_total
            .with_label_values(&[model, frontend_service::migration_type::NEW_REQUEST])
            .get()
    }

    /// Get the current count of ongoing request migrations for a model
    pub fn get_migration_ongoing_request_count(&self, model: &str) -> u64 {
        self.model_migration_total
            .with_label_values(&[model, frontend_service::migration_type::ONGOING_REQUEST])
            .get()
    }

952
953
954
955
956
957
958
959
960
961
962
963
964
965
    /// Increment the counter for migrations disabled by max_seq_len being exceeded
    pub fn inc_migration_max_seq_len_exceeded(&self, model: &str) {
        self.model_migration_max_seq_len_exceeded_total
            .with_label_values(&[model])
            .inc();
    }

    /// Get the current count of migrations disabled by max_seq_len being exceeded
    pub fn get_migration_max_seq_len_exceeded_count(&self, model: &str) -> u64 {
        self.model_migration_max_seq_len_exceeded_total
            .with_label_values(&[model])
            .get()
    }

966
967
968
969
970
971
972
973
974
975
976
977
978
979
    /// Increment the cancellation counter
    pub fn inc_cancellation(&self, labels: &CancellationLabels) {
        self.model_cancellation_total
            .with_label_values(&[&labels.model, &labels.endpoint, &labels.request_type])
            .inc();
    }

    /// Get the current cancellation count
    pub fn get_cancellation_count(&self, labels: &CancellationLabels) -> u64 {
        self.model_cancellation_total
            .with_label_values(&[&labels.model, &labels.endpoint, &labels.request_type])
            .get()
    }

980
981
982
983
984
985
986
987
988
989
990
991
992
993
    /// Increment the rejection counter for a request rejected due to resource exhaustion
    pub fn inc_rejection(&self, model: &str, endpoint: Endpoint) {
        self.model_rejection_total
            .with_label_values(&[model, &endpoint.to_string()])
            .inc();
    }

    /// Get the current rejection count for a model and endpoint
    pub fn get_rejection_count(&self, model: &str, endpoint: Endpoint) -> u64 {
        self.model_rejection_total
            .with_label_values(&[model, &endpoint.to_string()])
            .get()
    }

994
995
996
997
998
    /// Create a new [`InflightGuard`] for the given model and annotate if its a streaming request,
    /// and the kind of endpoint that was hit
    ///
    /// The [`InflightGuard`] is an RAII object will handle incrementing the inflight gauge and
    /// request counters.
999
1000
1001
1002
1003
1004
1005
    ///
    /// # Metrics Distinction
    ///
    /// This method creates an inflight guard  t tracks requests actively being processed by the LLM engine.
    /// This is distinct from [`HttpQueueGuard`] which tracks requests from HTTP handler start until
    /// first token generation (including prefill time). The separation allows monitoring both HTTP processing queue time
    /// and actual LLM processing time.
1006
    pub fn create_inflight_guard(
1007
        self: Arc<Self>,
1008
1009
1010
        model: &str,
        endpoint: Endpoint,
        streaming: bool,
1011
        request_id: &str,
1012
1013
1014
1015
1016
1017
1018
    ) -> InflightGuard {
        let request_type = if streaming {
            RequestType::Stream
        } else {
            RequestType::Unary
        };

1019
1020
1021
1022
1023
        InflightGuard::new(
            self.clone(),
            model.to_string().to_lowercase(),
            endpoint,
            request_type,
1024
            request_id.to_string(),
1025
1026
1027
1028
1029
1030
        )
    }

    /// Create a new [`ResponseMetricCollector`] for collecting per-response metrics (i.e., TTFT, ITL)
    pub fn create_response_collector(self: Arc<Self>, model: &str) -> ResponseMetricCollector {
        ResponseMetricCollector::new(self, model.to_string().to_lowercase())
1031
    }
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055

    /// Create a new [`HttpQueueGuard`] for tracking HTTP processing queue
    ///
    /// This guard tracks requests from HTTP handler start until first token generation,
    /// providing visibility into HTTP processing queue time before actual LLM processing begins.
    pub fn create_http_queue_guard(self: Arc<Self>, model: &str) -> HttpQueueGuard {
        HttpQueueGuard::new(self, model.to_string().to_lowercase())
    }
}

impl HttpQueueGuard {
    fn new(metrics: Arc<Metrics>, model: String) -> Self {
        // Increment the HTTP queue gauge when the guard is created
        metrics.inc_http_queue_gauge(&model);

        HttpQueueGuard { metrics, model }
    }
}

impl Drop for HttpQueueGuard {
    fn drop(&mut self) {
        // Decrement the HTTP queue gauge when the guard is dropped
        self.metrics.dec_http_queue_gauge(&self.model);
    }
1056
1057
1058
1059
1060
1061
1062
1063
}

impl InflightGuard {
    fn new(
        metrics: Arc<Metrics>,
        model: String,
        endpoint: Endpoint,
        request_type: RequestType,
1064
        request_id: String,
1065
1066
1067
1068
    ) -> Self {
        let timer = Instant::now();
        metrics.inc_inflight_gauge(&model);

1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
        tracing::Span::current().record("model", model.as_str());

        tracing::info!(
            request_id = %request_id,
            model = %model,
            endpoint = %endpoint,
            request_type = %request_type,
            "request received"
        );

1079
1080
1081
1082
1083
1084
        InflightGuard {
            metrics,
            model,
            endpoint,
            request_type,
            status: Status::Error,
1085
            error_type: ErrorType::Internal,
1086
            timer,
1087
            request_id,
1088
            span: tracing::Span::current(),
1089
1090
1091
        }
    }

1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
    pub fn request_id(&self) -> &str {
        &self.request_id
    }
    pub fn model(&self) -> &str {
        &self.model
    }
    pub fn endpoint(&self) -> &Endpoint {
        &self.endpoint
    }
    pub fn request_type(&self) -> &RequestType {
        &self.request_type
    }
    pub fn error_type(&self) -> &ErrorType {
        &self.error_type
    }
    pub fn elapsed_ms(&self) -> u128 {
        self.timer.elapsed().as_millis()
    }

1111
1112
    pub(crate) fn mark_ok(&mut self) {
        self.status = Status::Success;
1113
1114
1115
1116
1117
1118
        self.error_type = ErrorType::None;
    }

    pub(crate) fn mark_error(&mut self, error_type: ErrorType) {
        self.status = Status::Error;
        self.error_type = error_type;
1119
1120
1121
1122
1123
    }
}

impl Drop for InflightGuard {
    fn drop(&mut self) {
1124
        let _enter = self.span.enter();
1125
        let duration = self.timer.elapsed().as_secs_f64();
1126
1127
1128
1129
1130
1131
        self.metrics.dec_inflight_gauge(&self.model);
        self.metrics.inc_request_counter(
            &self.model,
            &self.endpoint,
            &self.request_type,
            &self.status,
1132
            &self.error_type,
1133
1134
1135
1136
        );
        self.metrics
            .request_duration
            .with_label_values(&[&self.model])
1137
            .observe(duration);
1138

1139
        let elapsed_ms = (duration * 1000.0) as u64;
1140
1141
1142
1143
1144
        let status_str = self.status.as_str();
        match self.status {
            Status::Error => {
                let detail = match self.error_type {
                    ErrorType::Cancelled => "cancelled before completion",
1145
                    ErrorType::ResponseTimeout => "backend stream inactivity timeout",
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
                    ErrorType::Internal => "internal server error during processing",
                    ErrorType::Validation => "invalid request parameters",
                    ErrorType::NotFound => "model or resource not found",
                    ErrorType::Overload => "service overloaded or rate limited",
                    ErrorType::NotImplemented => "requested feature not implemented",
                    ErrorType::None => "unknown error",
                };
                tracing::error!(
                    request_id = %self.request_id,
                    model = %self.model,
                    endpoint = %self.endpoint,
                    request_type = %self.request_type,
                    status = %status_str,
                    error_type = %self.error_type,
                    error_detail = %detail,
                    elapsed_ms = %elapsed_ms,
                    "request completed"
                );
            }
            Status::Success => {
                tracing::info!(
                    request_id = %self.request_id,
                    model = %self.model,
                    endpoint = %self.endpoint,
                    request_type = %self.request_type,
                    status = %status_str,
                    elapsed_ms = %elapsed_ms,
                    "request completed"
                );
            }
        }
1177
1178
1179
1180
1181
1182
1183
1184
    }
}

impl std::fmt::Display for Endpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Endpoint::Completions => write!(f, "completions"),
            Endpoint::ChatCompletions => write!(f, "chat_completions"),
1185
            Endpoint::Embeddings => write!(f, "embeddings"),
1186
            Endpoint::Images => write!(f, "images"),
1187
            Endpoint::Videos => write!(f, "videos"),
1188
            Endpoint::Audios => write!(f, "audios"),
1189
            Endpoint::Responses => write!(f, "responses"),
1190
            Endpoint::AnthropicMessages => write!(f, "anthropic_messages"),
1191
            Endpoint::Tensor => write!(f, "tensor"),
1192
1193
1194
1195
1196
1197
1198
1199
1200
        }
    }
}

impl Endpoint {
    pub fn as_str(&self) -> &'static str {
        match self {
            Endpoint::Completions => "completions",
            Endpoint::ChatCompletions => "chat_completions",
1201
            Endpoint::Embeddings => "embeddings",
1202
            Endpoint::Images => "images",
1203
            Endpoint::Videos => "videos",
1204
            Endpoint::Audios => "audios",
1205
            Endpoint::Responses => "responses",
1206
            Endpoint::AnthropicMessages => "anthropic_messages",
1207
            Endpoint::Tensor => "tensor",
1208
1209
1210
1211
1212
1213
1214
        }
    }
}

impl RequestType {
    pub fn as_str(&self) -> &'static str {
        match self {
1215
1216
            RequestType::Unary => frontend_service::request_type::UNARY,
            RequestType::Stream => frontend_service::request_type::STREAM,
1217
1218
1219
1220
        }
    }
}

1221
1222
1223
1224
1225
1226
impl std::fmt::Display for RequestType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

1227
1228
1229
impl Status {
    pub fn as_str(&self) -> &'static str {
        match self {
1230
1231
            Status::Success => frontend_service::status::SUCCESS,
            Status::Error => frontend_service::status::ERROR,
1232
1233
1234
1235
        }
    }
}

1236
1237
1238
1239
1240
1241
1242
1243
impl ErrorType {
    pub fn as_str(&self) -> &'static str {
        match self {
            ErrorType::None => frontend_service::error_type::NONE,
            ErrorType::Validation => frontend_service::error_type::VALIDATION,
            ErrorType::NotFound => frontend_service::error_type::NOT_FOUND,
            ErrorType::Overload => frontend_service::error_type::OVERLOAD,
            ErrorType::Cancelled => frontend_service::error_type::CANCELLED,
1244
            ErrorType::ResponseTimeout => frontend_service::error_type::RESPONSE_TIMEOUT,
1245
1246
1247
1248
1249
1250
            ErrorType::Internal => frontend_service::error_type::INTERNAL,
            ErrorType::NotImplemented => frontend_service::error_type::NOT_IMPLEMENTED,
        }
    }
}

1251
1252
1253
1254
1255
1256
impl std::fmt::Display for ErrorType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

1257
1258
1259
1260
1261
1262
1263
1264
1265
impl ResponseMetricCollector {
    fn new(metrics: Arc<Metrics>, model: String) -> Self {
        ResponseMetricCollector {
            metrics,
            model,
            is_first_token: true,
            last_response_time: None,
            start_time: Instant::now(),
            osl: 0,
1266
1267
1268
1269
            isl: 0,
            ttft_ms: None,
            itl_sum_secs: 0.0,
            itl_count: 0,
1270
            cached_tokens_observed: false,
1271
1272
1273
            tokenize_latency_observed: false,
            detokenize_latency_total: Duration::ZERO,
            detokenize_count_total: 0,
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
            prefill_worker_id: None,
            prefill_dp_rank: None,
            prefill_worker_type: None,
            decode_worker_id: None,
            decode_dp_rank: None,
            decode_worker_type: None,
        }
    }

    /// Set the worker info for per-worker TTFT/ITL metrics.
    /// In disaggregated mode, TTFT is attributed to prefill worker, ITL to decode worker.
    /// Worker types are stored at routing time to avoid expensive MDC lookup when updating metrics.
    pub fn set_worker_info(
        &mut self,
        prefill_worker_id: Option<u64>,
        prefill_dp_rank: Option<u32>,
        prefill_worker_type: Option<String>,
        decode_worker_id: Option<u64>,
        decode_dp_rank: Option<u32>,
        decode_worker_type: Option<String>,
    ) {
        if self.prefill_worker_id.is_none() {
            self.prefill_worker_id = prefill_worker_id;
        }
        if self.prefill_dp_rank.is_none() {
            self.prefill_dp_rank = prefill_dp_rank;
        }
        if self.prefill_worker_type.is_none() {
            self.prefill_worker_type = prefill_worker_type;
        }
        if self.decode_worker_id.is_none() {
            self.decode_worker_id = decode_worker_id;
        }
        if self.decode_dp_rank.is_none() {
            self.decode_dp_rank = decode_dp_rank;
        }
        if self.decode_worker_type.is_none() {
            self.decode_worker_type = decode_worker_type;
1312
1313
1314
1315
1316
1317
1318
1319
        }
    }

    /// Observe the current output sequence length
    pub fn observe_current_osl(&mut self, osl: usize) {
        self.osl = osl;
    }

1320
1321
1322
1323
1324
    /// Check if this will be the first token (before calling observe_response)
    pub fn is_first_token(&self) -> bool {
        self.is_first_token
    }

1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
    /// Observe cached tokens (prefix cache hits), observing only once per request when value is available
    pub fn observe_cached_tokens(&mut self, cached_tokens: Option<usize>) {
        if let Some(tokens) = cached_tokens
            && !self.cached_tokens_observed
        {
            self.cached_tokens_observed = true;
            self.metrics
                .cached_tokens
                .with_label_values(&[&self.model])
                .observe(tokens as f64);
        }
    }

1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
    /// Observe tokenize/detokenize latencies in milliseconds.
    /// Tokenize is observed once per request; detokenize is accumulated and observed at request end.
    pub fn observe_tokenize_latencies(
        &mut self,
        tokenize_latency: Option<Duration>,
        detokenize_latency: Option<Duration>,
        detokenize_count: Option<u64>,
    ) {
        if let Some(latency) = tokenize_latency
            && !self.tokenize_latency_observed
1348
        {
1349
            self.tokenize_latency_observed = true;
1350
1351
1352
1353
1354
            self.metrics
                .tokenizer_latency
                .with_label_values(&[frontend_service::operation::TOKENIZE])
                .observe(latency.as_secs_f64() * 1000.0);
        }
1355
1356
1357
1358
1359
1360
1361

        if let Some(latency) = detokenize_latency {
            self.detokenize_latency_total = latency;
        }
        if let Some(count) = detokenize_count {
            self.detokenize_count_total = count;
        }
1362
1363
    }

1364
1365
1366
1367
1368
1369
    /// Observe a response with input sequence length and number of new tokens
    pub fn observe_response(&mut self, isl: usize, num_tokens: usize) {
        if num_tokens == 0 {
            return;
        }

1370
1371
1372
        // Store ISL for span recording on drop
        self.isl = isl;

1373
1374
1375
1376
1377
1378
        // Increment the real-time output tokens counter
        self.metrics
            .output_tokens_counter
            .with_label_values(&[&self.model])
            .inc_by(num_tokens as u64);

1379
1380
1381
1382
1383
        if self.is_first_token {
            // NOTE: when there are multiple tokens in the first response,
            // we use the full response time as TTFT and ignore the ITL
            self.is_first_token = false;

1384
            // Publish TTFT and store for span recording
1385
            let ttft = self.start_time.elapsed().as_secs_f64();
1386
            self.ttft_ms = Some(ttft * 1000.0);
1387
1388
1389
1390
1391
            self.metrics
                .time_to_first_token
                .with_label_values(&[&self.model])
                .observe(ttft);

1392
1393
1394
1395
1396
1397
1398
1399
            // Update per-worker TTFT and input sequence tokens gauges - attributed to prefill worker.
            // Both gauges are updated atomically from the same request to correlate latency with input size.
            // Use stored worker_type (from routing time) to avoid MDC lookup.
            // Falls back to WORKER_TYPE_PREFILL if not available.
            if let Some(worker_id) = self.prefill_worker_id {
                let worker_id_str = worker_id.to_string();
                let dp_rank_str = self
                    .prefill_dp_rank
1400
                    .map_or(UNSET_DP_RANK_LABEL.to_string(), |r| r.to_string());
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
                let worker_type = self
                    .prefill_worker_type
                    .as_deref()
                    .unwrap_or(WORKER_TYPE_PREFILL);
                let labels = &[worker_id_str.as_str(), dp_rank_str.as_str(), worker_type];
                WORKER_LAST_TIME_TO_FIRST_TOKEN_GAUGE
                    .with_label_values(labels)
                    .set(ttft);
                WORKER_LAST_INPUT_SEQUENCE_TOKENS_GAUGE
                    .with_label_values(labels)
                    .set(isl as i64);
            }

1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
            // Publish ISL
            // TODO: publish ISL as soon as the tokenization process completes
            self.metrics
                .input_sequence_length
                .with_label_values(&[&self.model])
                .observe(isl as f64);
        }

        let current_duration = self.start_time.elapsed();

        if let Some(last_response_time) = self.last_response_time {
            let response_duration = current_duration - last_response_time;
            let itl = response_duration.as_secs_f64() / num_tokens as f64;
1427
1428
            self.itl_sum_secs += itl * num_tokens as f64;
            self.itl_count += num_tokens as u64;
1429
1430
1431
1432
1433
1434
            for _ in 0..num_tokens {
                self.metrics
                    .inter_token_latency
                    .with_label_values(&[&self.model])
                    .observe(itl);
            }
1435
1436
1437
1438
1439
1440
1441
1442

            // Update per-worker ITL gauge - attributed to decode worker.
            // Use stored worker_type (from routing time) to avoid MDC lookup.
            // Falls back to WORKER_TYPE_DECODE if not available.
            if let Some(worker_id) = self.decode_worker_id {
                let worker_id_str = worker_id.to_string();
                let dp_rank_str = self
                    .decode_dp_rank
1443
                    .map_or(UNSET_DP_RANK_LABEL.to_string(), |r| r.to_string());
1444
1445
1446
1447
1448
1449
1450
1451
                let worker_type = self
                    .decode_worker_type
                    .as_deref()
                    .unwrap_or(WORKER_TYPE_DECODE);
                WORKER_LAST_INTER_TOKEN_LATENCY_GAUGE
                    .with_label_values(&[worker_id_str.as_str(), dp_rank_str.as_str(), worker_type])
                    .set(itl);
            }
1452
1453
1454
1455
1456
1457
1458
1459
        }

        self.last_response_time = Some(current_duration);
    }
}

impl Drop for ResponseMetricCollector {
    fn drop(&mut self) {
1460
1461
1462
1463
1464
1465
1466
1467
1468
        if !self.detokenize_latency_total.is_zero() && self.detokenize_count_total > 0 {
            let avg_detokenize_latency_ms = (self.detokenize_latency_total.as_secs_f64() * 1000.0)
                / self.detokenize_count_total as f64;
            self.metrics
                .tokenizer_latency
                .with_label_values(&[frontend_service::operation::DETOKENIZE])
                .observe(avg_detokenize_latency_ms);
        }

1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
        // Publish final OSL when the collector is dropped, but only for
        // requests that actually produced output tokens. Recording zero for
        // failed/cancelled requests would corrupt histogram averages (sum/count)
        // and percentiles. Failures are already tracked by requests_total with
        // status and error_type labels.
        if self.osl > 0 {
            self.metrics
                .output_sequence_length
                .with_label_values(&[&self.model])
                .observe(self.osl as f64);
        }
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498

        // Record request summary on the enclosing span.
        // InflightGuard::Drop and on_response logs will inherit these.
        let span = tracing::Span::current();
        span.record("input_tokens", self.isl as u32);
        span.record("output_tokens", self.osl as u32);
        if let Some(ttft_ms) = self.ttft_ms {
            span.record("ttft_ms", format!("{:.2}", ttft_ms).as_str());
        }
        if self.itl_count > 0 {
            let avg_ms = (self.itl_sum_secs / self.itl_count as f64) * 1000.0;
            span.record("avg_itl_ms", format!("{:.2}", avg_ms).as_str());
        }
        if let Some(worker_id) = self.prefill_worker_id {
            span.record("prefill_worker_id", worker_id);
        }
        if let Some(worker_id) = self.decode_worker_id {
            span.record("decode_worker_id", worker_id);
        }
1499
1500
1501
    }
}

1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
/// Process streaming metrics for annotated responses
///
/// This function handles metrics collection and http_queue_guard management for streaming responses.
/// It observes the current output sequence length, drops the http_queue_guard on the first token,
/// and records response metrics.
pub fn process_response_and_observe_metrics<T>(
    annotated: &crate::types::Annotated<T>,
    response_collector: &mut ResponseMetricCollector,
    http_queue_guard: &mut Option<HttpQueueGuard>,
) {
    use crate::preprocessor::LLMMetricAnnotation;

    // update metrics
    if let Ok(Some(metrics)) = LLMMetricAnnotation::from_annotation(annotated) {
        response_collector.observe_current_osl(metrics.output_tokens);
1517
        response_collector.observe_cached_tokens(metrics.cached_tokens);
1518
1519
1520
1521
1522
        response_collector.observe_tokenize_latencies(
            metrics.tokenize_latency,
            metrics.detokenize_total_latency,
            metrics.detokenize_count,
        );
1523
1524
1525
1526
1527
1528
1529
1530
        response_collector.set_worker_info(
            metrics.prefill_worker_id,
            metrics.prefill_dp_rank,
            metrics.prefill_worker_type,
            metrics.decode_worker_id,
            metrics.decode_dp_rank,
            metrics.decode_worker_type,
        );
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556

        // Drop http_queue_guard on first token for non-streaming (same as streaming)
        if response_collector.is_first_token()
            && metrics.chunk_tokens > 0
            && let Some(guard) = http_queue_guard.take()
        {
            drop(guard);
        }

        response_collector.observe_response(metrics.input_tokens, metrics.chunk_tokens);
    }
}

/// Event converter wrapper for streaming responses
pub struct EventConverter<T>(pub crate::types::Annotated<T>);

impl<T> From<crate::types::Annotated<T>> for EventConverter<T> {
    fn from(annotated: crate::types::Annotated<T>) -> Self {
        EventConverter(annotated)
    }
}

/// Process streaming response with event conversion for SSE
///
/// This function handles metrics collection, http_queue_guard management, and converts
/// annotated responses to SSE events for streaming responses.
1557
1558
///
/// Returns None for metrics annotation events (events without SSE data payload).
1559
1560
1561
1562
pub fn process_response_using_event_converter_and_observe_metrics<T: Serialize>(
    annotated: EventConverter<T>,
    response_collector: &mut ResponseMetricCollector,
    http_queue_guard: &mut Option<HttpQueueGuard>,
1563
) -> Result<Option<Event>, axum::Error> {
1564
1565
1566
1567
1568
1569
1570
    use crate::preprocessor::LLMMetricAnnotation;

    let mut annotated = annotated.0;

    // update metrics
    if let Ok(Some(metrics)) = LLMMetricAnnotation::from_annotation(&annotated) {
        response_collector.observe_current_osl(metrics.output_tokens);
1571
        response_collector.observe_cached_tokens(metrics.cached_tokens);
1572
1573
1574
1575
1576
        response_collector.observe_tokenize_latencies(
            metrics.tokenize_latency,
            metrics.detokenize_total_latency,
            metrics.detokenize_count,
        );
1577
1578
1579
1580
1581
1582
1583
1584
        response_collector.set_worker_info(
            metrics.prefill_worker_id,
            metrics.prefill_dp_rank,
            metrics.prefill_worker_type,
            metrics.decode_worker_id,
            metrics.decode_dp_rank,
            metrics.decode_worker_type,
        );
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605

        // Drop http_queue_guard on first token for streaming
        if response_collector.is_first_token()
            && metrics.chunk_tokens > 0
            && let Some(guard) = http_queue_guard.take()
        {
            drop(guard);
        }

        response_collector.observe_response(metrics.input_tokens, metrics.chunk_tokens);

        // Chomp the LLMMetricAnnotation so it's not returned in the response stream
        // TODO: add a flag to control what is returned in the SSE stream
        if annotated.event.as_deref() == Some(crate::preprocessor::ANNOTATION_LLM_METRICS) {
            annotated.event = None;
            annotated.comment = None;
        }
    }

    let mut event = Event::default();

1606
    if let Some(ref data) = annotated.data {
1607
1608
1609
        event = event.json_data(data)?;
    }

1610
    if let Some(ref msg) = annotated.event {
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
        if msg == "error" {
            let msgs = annotated
                .comment
                .unwrap_or_else(|| vec!["unspecified error".to_string()]);
            return Err(axum::Error::new(msgs.join(" -- ")));
        }
        event = event.event(msg);
    }

    if let Some(comments) = annotated.comment {
        for comment in comments {
            event = event.comment(comment);
        }
    }

1626
1627
1628
1629
1630
1631
    // Filter out metrics annotation events (events without SSE data payload)
    if annotated.data.is_none() && annotated.event.is_none() {
        Ok(None)
    } else {
        Ok(Some(event))
    }
1632
1633
}

1634
1635
1636
1637
1638
1639
1640
1641
1642
/// Create a new router with optional DRT metrics integration.
///
/// When `drt_metrics` is provided, the `/metrics` handler will also include
/// metrics from the DRT's registry tree (anything created via `metrics().create*()`).
pub fn router(
    registry: Registry,
    path: Option<String>,
    drt_metrics: Option<dynamo_runtime::metrics::MetricsRegistry>,
) -> (Vec<RouteDoc>, Router) {
1643
1644
    let path = path.unwrap_or_else(|| "/metrics".to_string());
    let doc = RouteDoc::new(axum::http::Method::GET, &path);
1645
1646
1647

    let metrics_state = MetricsHandlerState {
        registry: Arc::new(registry),
1648
        drt_metrics,
1649
1650
    };

1651
1652
    let route = Router::new()
        .route(&path, get(handler_metrics))
1653
        .with_state(Arc::new(metrics_state));
1654
1655
1656
    (vec![doc], route)
}

1657
1658
1659
1660
/// Unified metrics handler.
///
/// Gathers from the local HTTP-service registry first, then appends any
/// metrics from the DRT's registry tree (if configured).
1661
async fn handler_metrics(State(state): State<Arc<MetricsHandlerState>>) -> impl IntoResponse {
1662
    let encoder = prometheus::TextEncoder::new();
1663
    let metric_families = state.registry.gather();
1664
1665
1666
1667
1668
1669
1670
1671
1672
    let mut buffer = vec![];
    if encoder.encode(&metric_families, &mut buffer).is_err() {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to encode metrics",
        )
            .into_response();
    }

1673
    let mut metrics = match String::from_utf8(buffer) {
1674
1675
1676
1677
1678
1679
        Ok(metrics) => metrics,
        Err(_) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to encode metrics",
            )
1680
                .into_response();
1681
1682
1683
        }
    };

1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
    // Append DRT registry tree metrics (anything created via metrics().create*()).
    if let Some(ref drt_metrics) = state.drt_metrics {
        match drt_metrics.prometheus_expfmt_combined() {
            Ok(drt_text) => {
                if !drt_text.is_empty() {
                    if !metrics.is_empty() && !metrics.ends_with('\n') {
                        metrics.push('\n');
                    }
                    metrics.push_str(&drt_text);
                }
            }
            Err(e) => {
                tracing::warn!("Failed to gather DRT metrics: {}", e);
            }
        }
    }

1701
1702
    (StatusCode::OK, metrics).into_response()
}
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869

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

    #[test]
    fn test_round_to_sig_figs() {
        // Test rounding to 2 significant figures
        assert_eq!(round_to_sig_figs(0.0026, 2), 0.0026);
        assert_eq!(round_to_sig_figs(0.26, 2), 0.26);
        assert_eq!(round_to_sig_figs(0.2356, 2), 0.24);
        assert_eq!(round_to_sig_figs(1.234, 2), 1.2);
        assert_eq!(round_to_sig_figs(12.34, 2), 12.0);
        assert_eq!(round_to_sig_figs(123.4, 2), 120.0);
        assert_eq!(round_to_sig_figs(1234.0, 2), 1200.0);
        assert_eq!(round_to_sig_figs(0.0, 2), 0.0);

        // Test edge cases
        assert_eq!(round_to_sig_figs(0.999, 2), 1.0);
        assert_eq!(round_to_sig_figs(9.99, 2), 10.0);
        assert_eq!(round_to_sig_figs(99.9, 2), 100.0);
    }

    #[test]
    fn test_generate_log_buckets_basic() {
        // Test basic properties
        let buckets = generate_log_buckets(1.0, 100.0, 5);

        // Check length
        assert_eq!(buckets.len(), 5);

        // Check first value is 0
        assert_eq!(buckets[0], 0.0);

        // Check last value is approximately max (rounded to 2 sig figs)
        assert_eq!(buckets[buckets.len() - 1], 100.0);

        // Check values are increasing
        for i in 1..buckets.len() {
            assert!(
                buckets[i] > buckets[i - 1],
                "Bucket values should be increasing: {} <= {}",
                buckets[i - 1],
                buckets[i]
            );
        }
    }

    #[test]
    fn test_generate_log_buckets_edge_cases() {
        // Test empty buckets
        let buckets = generate_log_buckets(1.0, 100.0, 0);
        assert_eq!(buckets.len(), 0);

        // Test single bucket
        let buckets = generate_log_buckets(1.0, 100.0, 1);
        assert_eq!(buckets.len(), 1);
        assert_eq!(buckets[0], 0.0);

        // Test two buckets
        let buckets = generate_log_buckets(1.0, 100.0, 2);
        assert_eq!(buckets.len(), 2);
        assert_eq!(buckets[0], 0.0);
        assert_eq!(buckets[1], 100.0);
    }

    #[test]
    fn test_generate_log_buckets_always_includes_zero() {
        // Test various configurations
        for count in 1..=20 {
            let buckets = generate_log_buckets(0.1, 1000.0, count);
            assert_eq!(
                buckets[0], 0.0,
                "First bucket should always be 0.0 for count={}",
                count
            );
        }
    }

    #[test]
    fn test_all_buckets_are_two_sig_figs() {
        let test_cases = vec![
            (1.0, 256.0, 10),
            (50.0, 128000.0, 12),
            (50.0, 32000.0, 10),
            (0.001, 480.0, 18),
            (0.001, 2.0, 13),
        ];

        for (min, max, count) in test_cases {
            let buckets = generate_log_buckets(min, max, count);
            for &value in buckets.iter().skip(1) {
                let rounded = round_to_sig_figs(value, 2);
                assert_eq!(
                    value, rounded,
                    "Value {} should be rounded to 2 sig figs (min={}, max={}, count={})",
                    value, min, max, count
                );
            }
        }
    }

    #[test]
    fn test_sig_fig_limitation_with_many_buckets() {
        // This test demonstrates that 2 sig figs limits the number of unique bucket values
        // With 1000 requested buckets but only 2 sig figs, we'll get automatic deduplication
        let buckets = generate_log_buckets(0.0001, 1.0, 1000);

        println!(
            "Requested 1000 buckets, got {} total values (including 0.0)",
            buckets.len()
        );

        // With 2 sig figs across 4 orders of magnitude (0.0001 to 1.0),
        // we can have roughly 90 unique values per order of magnitude
        // So we expect around 360 unique values maximum
        assert!(
            buckets.len() < 500,
            "Expected fewer than 500 unique buckets due to 2 sig fig limitation, got {}",
            buckets.len()
        );

        // Verify all values are unique (no duplicates remain after deduplication)
        let mut sorted_buckets = buckets.clone();
        sorted_buckets.sort_by(|a, b| a.partial_cmp(b).unwrap());
        sorted_buckets.dedup();
        assert_eq!(
            buckets.len(),
            sorted_buckets.len(),
            "All buckets should be unique after deduplication"
        );

        // Verify first is still 0.0
        assert_eq!(buckets[0], 0.0);

        // Verify values are still in increasing order
        for i in 1..buckets.len() {
            assert!(
                buckets[i] > buckets[i - 1],
                "Buckets should be in increasing order"
            );
        }
    }

    #[test]
    fn test_deduplication_preserves_order() {
        // Test that deduplication maintains increasing order
        let buckets = generate_log_buckets(0.01, 1.0, 50);

        // Verify all values are unique
        let mut unique_check = std::collections::HashSet::new();
        for &bucket in &buckets {
            assert!(
                unique_check.insert(bucket.to_bits()),
                "Duplicate value {} found after deduplication",
                bucket
            );
        }

        // Verify order is maintained
        for i in 1..buckets.len() {
            assert!(
                buckets[i] > buckets[i - 1],
                "Bucket values should be in increasing order after deduplication"
            );
        }
    }
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016

    #[test]
    fn test_output_tokens_counter_increments() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";

        // Create response collector
        let mut collector = metrics.clone().create_response_collector(model);

        // Simulate first chunk (5 tokens)
        collector.observe_response(100, 5);

        // Verify counter incremented by 5
        let counter_value = metrics
            .output_tokens_counter
            .with_label_values(&[model])
            .get();
        assert_eq!(counter_value, 5);

        // Simulate second chunk (10 tokens)
        collector.observe_response(100, 10);

        // Verify counter incremented to 15
        let counter_value = metrics
            .output_tokens_counter
            .with_label_values(&[model])
            .get();
        assert_eq!(counter_value, 15);

        // Simulate third chunk (7 tokens)
        collector.observe_response(100, 7);

        // Verify counter incremented to 22
        let counter_value = metrics
            .output_tokens_counter
            .with_label_values(&[model])
            .get();
        assert_eq!(counter_value, 22);
    }

    #[test]
    fn test_output_tokens_counter_zero_tokens() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";
        let mut collector = metrics.clone().create_response_collector(model);

        // Simulate chunk with zero tokens (should not increment)
        collector.observe_response(100, 0);

        // Verify counter remains 0
        let counter_value = metrics
            .output_tokens_counter
            .with_label_values(&[model])
            .get();
        assert_eq!(counter_value, 0);

        // Add some tokens
        collector.observe_response(100, 5);
        assert_eq!(
            metrics
                .output_tokens_counter
                .with_label_values(&[model])
                .get(),
            5
        );

        // Try zero tokens again (should not change counter)
        collector.observe_response(100, 0);
        assert_eq!(
            metrics
                .output_tokens_counter
                .with_label_values(&[model])
                .get(),
            5
        );
    }

    #[test]
    fn test_output_tokens_counter_multiple_models() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model1 = "model-1";
        let model2 = "model-2";

        // Create collectors for different models
        let mut collector1 = metrics.clone().create_response_collector(model1);
        let mut collector2 = metrics.clone().create_response_collector(model2);

        // Increment model1
        collector1.observe_response(100, 10);
        assert_eq!(
            metrics
                .output_tokens_counter
                .with_label_values(&[model1])
                .get(),
            10
        );
        assert_eq!(
            metrics
                .output_tokens_counter
                .with_label_values(&[model2])
                .get(),
            0
        );

        // Increment model2
        collector2.observe_response(200, 20);
        assert_eq!(
            metrics
                .output_tokens_counter
                .with_label_values(&[model1])
                .get(),
            10
        );
        assert_eq!(
            metrics
                .output_tokens_counter
                .with_label_values(&[model2])
                .get(),
            20
        );

        // Increment model1 again
        collector1.observe_response(100, 5);
        assert_eq!(
            metrics
                .output_tokens_counter
                .with_label_values(&[model1])
                .get(),
            15
        );
        assert_eq!(
            metrics
                .output_tokens_counter
                .with_label_values(&[model2])
                .get(),
            20
        );
    }
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084

    #[test]
    fn test_cached_tokens_once_per_request() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";
        let expected_metric_name = "dynamo_frontend_cached_tokens";
        let mut collector = metrics.clone().create_response_collector(model);

        // Create histogram handle first
        let _histogram = metrics.cached_tokens.with_label_values(&[model]);

        // First call should observe and record 1 sample
        collector.observe_cached_tokens(Some(100));
        let metric_families = registry.gather();
        let histogram_family = metric_families
            .iter()
            .find(|mf| mf.name() == expected_metric_name)
            .expect("histogram should be registered");
        assert_eq!(
            histogram_family.get_metric()[0]
                .get_histogram()
                .get_sample_count(),
            1
        );

        // Second call with same collector should not observe again (idempotent)
        collector.observe_cached_tokens(Some(50));
        let metric_families = registry.gather();
        let histogram_family = metric_families
            .iter()
            .find(|mf| mf.name() == expected_metric_name)
            .expect("histogram should be registered");
        assert_eq!(
            histogram_family.get_metric()[0]
                .get_histogram()
                .get_sample_count(),
            1
        );

        // Third call with different value should still be idempotent
        collector.observe_cached_tokens(Some(75));
        let metric_families = registry.gather();
        let histogram_family = metric_families
            .iter()
            .find(|mf| mf.name() == expected_metric_name)
            .expect("histogram should be registered");
        assert_eq!(
            histogram_family.get_metric()[0]
                .get_histogram()
                .get_sample_count(),
            1
        );
    }

    #[test]
    fn test_metrics_annotation_event_handling() {
        use crate::preprocessor::LLMMetricAnnotation;
        use crate::types::Annotated;

        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";
        let expected_metric_name = "dynamo_frontend_cached_tokens";
2085
        let expected_tokenizer_metric_name = "dynamo_frontend_tokenizer_latency_ms";
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
        let mut collector = metrics.clone().create_response_collector(model);

        // Create a metrics annotation event (event without SSE data payload)
        let mut annotated = Annotated::<
            crate::protocols::openai::chat_completions::NvCreateChatCompletionStreamResponse,
        > {
            id: None,
            data: None,
            event: Some(crate::preprocessor::ANNOTATION_LLM_METRICS.to_string()),
            comment: None,
2096
            error: None,
2097
2098
2099
2100
2101
2102
2103
2104
        };

        // Add metrics annotation with cached_tokens
        let llm_metrics = LLMMetricAnnotation {
            input_tokens: 10,
            output_tokens: 20,
            chunk_tokens: 5,
            cached_tokens: Some(15),
2105
2106
2107
2108
2109
2110
            prefill_worker_id: None,
            prefill_dp_rank: None,
            prefill_worker_type: None,
            decode_worker_id: None,
            decode_dp_rank: None,
            decode_worker_type: None,
2111
2112
2113
            tokenize_latency: Some(Duration::from_millis(8)),
            detokenize_total_latency: Some(Duration::from_micros(100)),
            detokenize_count: Some(2),
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
        };

        let annotation = llm_metrics.to_annotation::<()>().unwrap();
        annotated.event = annotation.event;
        annotated.comment = annotation.comment;

        // Process the event
        let mut http_queue_guard = None;
        let result = process_response_using_event_converter_and_observe_metrics(
            EventConverter::from(annotated),
            &mut collector,
            &mut http_queue_guard,
        );

        // Should return Ok(None) for metrics annotation events
        assert!(matches!(result, Ok(None)));

2131
2132
2133
        // Drop collector so the detokenize observation fires in Drop
        drop(collector);

2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
        // Should have observed the cached tokens from the metrics annotation event
        let metric_families = registry.gather();
        let histogram_family = metric_families
            .iter()
            .find(|mf| mf.name() == expected_metric_name)
            .expect("histogram should be registered");
        assert_eq!(
            histogram_family.get_metric()[0]
                .get_histogram()
                .get_sample_count(),
            1
        );
2146
2147
2148
2149
2150

        let histogram_family = metric_families
            .iter()
            .find(|mf| mf.name() == expected_tokenizer_metric_name)
            .expect("histogram should be registered");
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175

        // Find the tokenize and detokenize observations by label
        let tokenize_metric = histogram_family
            .get_metric()
            .iter()
            .find(|m| m.get_label().iter().any(|l| l.value() == "tokenize"))
            .expect("tokenize metric should exist");
        assert_eq!(tokenize_metric.get_histogram().get_sample_count(), 1);
        // 8ms
        assert!(
            (tokenize_metric.get_histogram().get_sample_sum() - 8.0).abs() < 0.001,
            "tokenize latency should be 8.0ms"
        );

        let detokenize_metric = histogram_family
            .get_metric()
            .iter()
            .find(|m| m.get_label().iter().any(|l| l.value() == "detokenize"))
            .expect("detokenize metric should exist");
        assert_eq!(detokenize_metric.get_histogram().get_sample_count(), 1);
        // Average: 100us total / 2 samples = 50us = 0.05ms
        assert!(
            (detokenize_metric.get_histogram().get_sample_sum() - 0.05).abs() < 0.001,
            "detokenize average latency should be 0.05ms, got {}",
            detokenize_metric.get_histogram().get_sample_sum()
2176
        );
2177
    }
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189

    #[test]
    fn test_non_streaming_path_observes_cached_tokens() {
        use crate::preprocessor::LLMMetricAnnotation;
        use crate::types::Annotated;

        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";
        let expected_metric_name = "dynamo_frontend_cached_tokens";
2190
        let expected_tokenizer_metric_name = "dynamo_frontend_tokenizer_latency_ms";
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
        let mut collector = metrics.clone().create_response_collector(model);

        // Create a metrics annotation event
        let mut annotated = Annotated::<
            crate::protocols::openai::chat_completions::NvCreateChatCompletionStreamResponse,
        > {
            id: None,
            data: None,
            event: Some(crate::preprocessor::ANNOTATION_LLM_METRICS.to_string()),
            comment: None,
2201
            error: None,
2202
2203
2204
2205
2206
2207
2208
        };

        let llm_metrics = LLMMetricAnnotation {
            input_tokens: 10,
            output_tokens: 20,
            chunk_tokens: 5,
            cached_tokens: Some(15),
2209
2210
2211
2212
2213
2214
            prefill_worker_id: None,
            prefill_dp_rank: None,
            prefill_worker_type: None,
            decode_worker_id: None,
            decode_dp_rank: None,
            decode_worker_type: None,
2215
2216
2217
            tokenize_latency: Some(Duration::from_millis(8)),
            detokenize_total_latency: Some(Duration::from_micros(100)),
            detokenize_count: Some(2),
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
        };

        let annotation = llm_metrics.to_annotation::<()>().unwrap();
        annotated.event = annotation.event;
        annotated.comment = annotation.comment;

        // Process via the non-streaming metrics hook
        let mut http_queue_guard = None;
        process_response_and_observe_metrics(&annotated, &mut collector, &mut http_queue_guard);

2228
2229
2230
        // Drop collector so the detokenize observation fires in Drop
        drop(collector);

2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
        // Should have observed the cached tokens from the metrics annotation event
        let metric_families = registry.gather();
        let histogram_family = metric_families
            .iter()
            .find(|mf| mf.name() == expected_metric_name)
            .expect("histogram should be registered");
        assert_eq!(
            histogram_family.get_metric()[0]
                .get_histogram()
                .get_sample_count(),
            1
        );
2243
2244
2245
2246
2247

        let histogram_family = metric_families
            .iter()
            .find(|mf| mf.name() == expected_tokenizer_metric_name)
            .expect("histogram should be registered");
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267

        // Find the tokenize and detokenize observations by label
        let tokenize_metric = histogram_family
            .get_metric()
            .iter()
            .find(|m| m.get_label().iter().any(|l| l.value() == "tokenize"))
            .expect("tokenize metric should exist");
        assert_eq!(tokenize_metric.get_histogram().get_sample_count(), 1);

        let detokenize_metric = histogram_family
            .get_metric()
            .iter()
            .find(|m| m.get_label().iter().any(|l| l.value() == "detokenize"))
            .expect("detokenize metric should exist");
        assert_eq!(detokenize_metric.get_histogram().get_sample_count(), 1);
        // Average: 100us total / 2 samples = 50us = 0.05ms
        assert!(
            (detokenize_metric.get_histogram().get_sample_sum() - 0.05).abs() < 0.001,
            "detokenize average latency should be 0.05ms, got {}",
            detokenize_metric.get_histogram().get_sample_sum()
2268
        );
2269
    }
2270
2271
2272
2273
2274
2275
2276
2277

    #[test]
    fn test_error_type_as_str() {
        assert_eq!(ErrorType::None.as_str(), "");
        assert_eq!(ErrorType::Validation.as_str(), "validation");
        assert_eq!(ErrorType::NotFound.as_str(), "not_found");
        assert_eq!(ErrorType::Overload.as_str(), "overload");
        assert_eq!(ErrorType::Cancelled.as_str(), "cancelled");
2278
        assert_eq!(ErrorType::ResponseTimeout.as_str(), "response_timeout");
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
        assert_eq!(ErrorType::Internal.as_str(), "internal");
        assert_eq!(ErrorType::NotImplemented.as_str(), "not_implemented");
    }

    #[test]
    fn test_inflight_guard_marks_success_with_correct_error_type() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";

        {
            let mut guard =
                metrics
                    .clone()
2295
                    .create_inflight_guard(model, Endpoint::ChatCompletions, false, "");
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
            guard.mark_ok();
        } // guard drops here

        // Verify counter incremented with status=success, error_type=""
        let counter_value = metrics
            .request_counter
            .with_label_values(&[
                model,
                Endpoint::ChatCompletions.as_str(),
                RequestType::Unary.as_str(),
                Status::Success.as_str(),
                ErrorType::None.as_str(),
            ])
            .get();
        assert_eq!(counter_value, 1);
    }

    #[test]
    fn test_inflight_guard_marks_validation_error() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";

        {
            let mut guard =
                metrics
                    .clone()
2325
                    .create_inflight_guard(model, Endpoint::ChatCompletions, false, "");
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
            guard.mark_error(ErrorType::Validation);
        } // guard drops here

        // Verify counter incremented with status=error, error_type=validation
        let counter_value = metrics
            .request_counter
            .with_label_values(&[
                model,
                Endpoint::ChatCompletions.as_str(),
                RequestType::Unary.as_str(),
                Status::Error.as_str(),
                ErrorType::Validation.as_str(),
            ])
            .get();
        assert_eq!(counter_value, 1);
    }

    #[test]
    fn test_inflight_guard_defaults_to_internal_error_on_drop() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";

        {
            let _guard =
                metrics
                    .clone()
2355
                    .create_inflight_guard(model, Endpoint::ChatCompletions, false, "");
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
            // Don't call mark_ok() or mark_error() - simulate panic/unhandled error
        } // guard drops with default error_type=Internal

        // Verify counter incremented with status=error, error_type=internal
        let counter_value = metrics
            .request_counter
            .with_label_values(&[
                model,
                Endpoint::ChatCompletions.as_str(),
                RequestType::Unary.as_str(),
                Status::Error.as_str(),
                ErrorType::Internal.as_str(),
            ])
            .get();
        assert_eq!(counter_value, 1);
    }

2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
    #[test]
    fn test_active_requests_tracks_inflight_guard() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model-active";

        // Both gauges start at 0
        assert_eq!(metrics.inflight_gauge.with_label_values(&[model]).get(), 0);
        assert_eq!(
            metrics
                .active_requests_gauge
                .with_label_values(&[model])
                .get(),
            0
        );

        {
            let _guard = metrics.clone().create_inflight_guard(
                model,
                Endpoint::ChatCompletions,
                true,
                "req-1",
            );

            // Both gauges increment together
            assert_eq!(metrics.inflight_gauge.with_label_values(&[model]).get(), 1);
            assert_eq!(
                metrics
                    .active_requests_gauge
                    .with_label_values(&[model])
                    .get(),
                1
            );

            {
                let _guard2 = metrics.clone().create_inflight_guard(
                    model,
                    Endpoint::ChatCompletions,
                    true,
                    "req-2",
                );
                assert_eq!(metrics.inflight_gauge.with_label_values(&[model]).get(), 2);
                assert_eq!(
                    metrics
                        .active_requests_gauge
                        .with_label_values(&[model])
                        .get(),
                    2
                );
            }
            // guard2 dropped
            assert_eq!(metrics.inflight_gauge.with_label_values(&[model]).get(), 1);
            assert_eq!(
                metrics
                    .active_requests_gauge
                    .with_label_values(&[model])
                    .get(),
                1
            );
        }
        // guard dropped — both back to 0
        assert_eq!(metrics.inflight_gauge.with_label_values(&[model]).get(), 0);
        assert_eq!(
            metrics
                .active_requests_gauge
                .with_label_values(&[model])
                .get(),
            0
        );
    }

2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
    #[test]
    fn test_all_error_types_recorded_correctly() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";
        let endpoint = Endpoint::ChatCompletions;

        // Test each error type
        let error_types = vec![
            ErrorType::Validation,
            ErrorType::NotFound,
            ErrorType::Overload,
            ErrorType::Cancelled,
2461
            ErrorType::ResponseTimeout,
2462
2463
2464
2465
2466
2467
2468
            ErrorType::Internal,
            ErrorType::NotImplemented,
        ];

        for error_type in &error_types {
            let mut guard = metrics
                .clone()
2469
                .create_inflight_guard(model, endpoint, false, "");
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
            guard.mark_error(error_type.clone());
            drop(guard);
        }

        // Verify each error type recorded correctly
        for error_type in &error_types {
            let counter_value = metrics
                .request_counter
                .with_label_values(&[
                    model,
                    endpoint.as_str(),
                    RequestType::Unary.as_str(),
                    Status::Error.as_str(),
                    error_type.as_str(),
                ])
                .get();
            assert_eq!(
                counter_value,
                1,
                "Should have 1 request for error_type={}",
                error_type.as_str()
            );
        }
    }

    #[test]
    fn test_multiple_requests_different_error_types() {
        let metrics = Arc::new(Metrics::new());
        let registry = prometheus::Registry::new();
        metrics.register(&registry).unwrap();

        let model = "test-model";

        // Record 2 validation errors, 3 internal errors, 1 success
        for _ in 0..2 {
            let mut guard =
                metrics
                    .clone()
2508
                    .create_inflight_guard(model, Endpoint::ChatCompletions, false, "");
2509
2510
2511
2512
2513
2514
2515
2516
            guard.mark_error(ErrorType::Validation);
            drop(guard);
        }

        for _ in 0..3 {
            let mut guard =
                metrics
                    .clone()
2517
                    .create_inflight_guard(model, Endpoint::Completions, false, "");
2518
2519
2520
2521
2522
2523
2524
2525
            guard.mark_error(ErrorType::Internal);
            drop(guard);
        }

        {
            let mut guard =
                metrics
                    .clone()
2526
                    .create_inflight_guard(model, Endpoint::Embeddings, false, "");
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
            guard.mark_ok();
            drop(guard);
        }

        // Check validation errors (2 from ChatCompletions)
        let validation_count = metrics
            .request_counter
            .with_label_values(&[
                model,
                Endpoint::ChatCompletions.as_str(),
                RequestType::Unary.as_str(),
                Status::Error.as_str(),
                ErrorType::Validation.as_str(),
            ])
            .get();
        assert_eq!(validation_count, 2);

        // Check internal errors (3 from Completions)
        let internal_count = metrics
            .request_counter
            .with_label_values(&[
                model,
                Endpoint::Completions.as_str(),
                RequestType::Unary.as_str(),
                Status::Error.as_str(),
                ErrorType::Internal.as_str(),
            ])
            .get();
        assert_eq!(internal_count, 3);

        // Check success (1 from Embeddings)
        let success_count = metrics
            .request_counter
            .with_label_values(&[
                model,
                Endpoint::Embeddings.as_str(),
                RequestType::Unary.as_str(),
                Status::Success.as_str(),
                ErrorType::None.as_str(),
            ])
            .get();
        assert_eq!(success_count, 1);
    }
2570
}