worker_monitor.rs 43 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
use std::collections::HashMap;
use std::sync::Arc;
6
use std::sync::RwLock;
7
use std::sync::atomic::{AtomicBool, Ordering};
8
9

use tokio::sync::Notify;
10
11

use dashmap::DashMap;
12
use dynamo_kv_router::protocols::ActiveLoad;
13
use serde::{Deserialize, Serialize};
14

15
16
17
18
use crate::http::service::metrics::{
    WORKER_LAST_INPUT_SEQUENCE_TOKENS_GAUGE, WORKER_LAST_INTER_TOKEN_LATENCY_GAUGE,
    WORKER_LAST_TIME_TO_FIRST_TOKEN_GAUGE,
};
19
use crate::kv_router::KV_METRICS_SUBJECT;
20
use crate::kv_router::metrics::WORKER_LOAD_METRICS;
21
use crate::model_card::ModelDeploymentCard;
22
use dynamo_runtime::component::Client;
23
use dynamo_runtime::discovery::{DiscoveryQuery, watch_and_extract_field};
24
25
use dynamo_runtime::pipeline::{WorkerLoadMonitor, async_trait};
use dynamo_runtime::traits::DistributedRuntimeProvider;
26
use dynamo_runtime::transports::event_plane::EventSubscriber;
27

28
29
// Re-export worker type constants from timing.rs (single source of truth)
pub use crate::protocols::common::timing::{WORKER_TYPE_DECODE, WORKER_TYPE_PREFILL};
30
const UNSET_DP_RANK_LABEL: &str = "none";
31
32
33
34
35
36
37

/// Clean up all Prometheus metrics for a worker across the specified dp_ranks.
///
/// This removes metrics with the given worker_id, dp_rank, and worker_type label combination.
/// Called when workers are removed to prevent stale metrics from accumulating.
fn cleanup_worker_metrics(worker_id: u64, dp_ranks: &[u32], worker_type: &str) {
    let worker_id_str = worker_id.to_string();
38
    let m = &*WORKER_LOAD_METRICS;
39
40
41
    for dp_rank in dp_ranks {
        let dp_rank_str = dp_rank.to_string();
        let labels = &[worker_id_str.as_str(), dp_rank_str.as_str(), worker_type];
42
43
        let _ = m.active_decode_blocks.remove_label_values(labels);
        let _ = m.active_prefill_tokens.remove_label_values(labels);
44
45
46
47
        let _ = WORKER_LAST_TIME_TO_FIRST_TOKEN_GAUGE.remove_label_values(labels);
        let _ = WORKER_LAST_INPUT_SEQUENCE_TOKENS_GAUGE.remove_label_values(labels);
        let _ = WORKER_LAST_INTER_TOKEN_LATENCY_GAUGE.remove_label_values(labels);
    }
48
49
50
51
52

    let unset_labels = &[worker_id_str.as_str(), UNSET_DP_RANK_LABEL, worker_type];
    let _ = WORKER_LAST_TIME_TO_FIRST_TOKEN_GAUGE.remove_label_values(unset_labels);
    let _ = WORKER_LAST_INPUT_SEQUENCE_TOKENS_GAUGE.remove_label_values(unset_labels);
    let _ = WORKER_LAST_INTER_TOKEN_LATENCY_GAUGE.remove_label_values(unset_labels);
53
54
}

55
56
57
/// Default value for `max_num_batched_tokens` when the runtime config does not
/// report it. Set high enough that the frac-based busy check (which multiplies
/// this value by the threshold fraction) can never fire with realistic loads.
58
59
60
61
const DEFAULT_MAX_TOKENS: u64 = 10_000_000;

/// Configuration for worker load thresholds used in busy detection.
///
62
63
64
/// All thresholds are opt-in. An unset (`None`) field means the corresponding
/// check is skipped entirely — it never contributes to a worker being marked
/// busy. If all three are `None`, busy-based rejection is fully disabled.
65
66
67
68
69
70
71
72
73
74
75
76
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct LoadThresholdConfig {
    /// KV cache block utilization threshold (0.0-1.0).
    /// Worker is busy when `active_decode_blocks / total_blocks > threshold`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_decode_blocks_threshold: Option<f64>,

    /// Absolute prefill token count threshold.
    /// Worker is busy when `active_prefill_tokens > threshold`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_prefill_tokens_threshold: Option<u64>,

77
    /// Fraction of max_num_batched_tokens.
78
79
80
81
82
83
84
85
86
87
88
89
90
91
    /// Worker is busy when `active_prefill_tokens > frac * max_num_batched_tokens`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_prefill_tokens_threshold_frac: Option<f64>,
}

impl LoadThresholdConfig {
    /// Returns true if any threshold is configured.
    pub fn is_configured(&self) -> bool {
        self.active_decode_blocks_threshold.is_some()
            || self.active_prefill_tokens_threshold.is_some()
            || self.active_prefill_tokens_threshold_frac.is_some()
    }
}

Yan Ru Pei's avatar
Yan Ru Pei committed
92
/// Worker load monitoring state per dp_rank
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#[derive(Clone, Debug)]
struct DecodeBusyLatchState {
    latched_busy: bool,
    kv_used_blocks_cleared: bool,
    active_decode_blocks_cleared: bool,
}

impl Default for DecodeBusyLatchState {
    fn default() -> Self {
        Self {
            latched_busy: false,
            kv_used_blocks_cleared: true,
            active_decode_blocks_cleared: true,
        }
    }
}

Yan Ru Pei's avatar
Yan Ru Pei committed
110
#[derive(Clone, Debug, Default)]
111
pub struct WorkerLoadState {
112
    pub active_decode_blocks: HashMap<u32, u64>,
113
    pub kv_used_blocks: HashMap<u32, u64>,
Yan Ru Pei's avatar
Yan Ru Pei committed
114
    pub kv_total_blocks: HashMap<u32, u64>,
115
    pub active_prefill_tokens: HashMap<u32, u64>,
116
117
    /// max_num_batched_tokens from runtime config (same for all dp_ranks)
    pub max_num_batched_tokens: HashMap<u32, u64>,
118
    decode_busy_latches: HashMap<u32, DecodeBusyLatchState>,
119
120
121
}

impl WorkerLoadState {
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
    fn is_decode_signal_busy(
        used_blocks: u64,
        total_blocks: u64,
        active_decode_blocks_threshold: f64,
    ) -> bool {
        total_blocks > 0
            && (used_blocks as f64) > (active_decode_blocks_threshold * total_blocks as f64)
    }

    fn current_decode_busy(&self, dp_rank: u32, active_decode_blocks_threshold: f64) -> bool {
        let Some(&total_blocks) = self.kv_total_blocks.get(&dp_rank) else {
            return false;
        };

        self.kv_used_blocks
            .get(&dp_rank)
            .is_some_and(|&used_blocks| {
                Self::is_decode_signal_busy(
                    used_blocks,
                    total_blocks,
                    active_decode_blocks_threshold,
                )
            })
            || self
                .active_decode_blocks
                .get(&dp_rank)
                .is_some_and(|&active_blocks| {
                    Self::is_decode_signal_busy(
                        active_blocks,
                        total_blocks,
                        active_decode_blocks_threshold,
                    )
                })
    }

    fn update_decode_busy_latch(
        &mut self,
        dp_rank: u32,
        active_decode_blocks: Option<u64>,
        kv_used_blocks: Option<u64>,
        active_decode_blocks_threshold: f64,
    ) {
        let Some(&total_blocks) = self.kv_total_blocks.get(&dp_rank) else {
            return;
        };
        if total_blocks == 0 {
            return;
        }

        let active_decode_busy = active_decode_blocks.is_some_and(|value| {
            Self::is_decode_signal_busy(value, total_blocks, active_decode_blocks_threshold)
        });
        let kv_used_busy = kv_used_blocks.is_some_and(|value| {
            Self::is_decode_signal_busy(value, total_blocks, active_decode_blocks_threshold)
        });

        let latch = self.decode_busy_latches.entry(dp_rank).or_default();
        if active_decode_busy || kv_used_busy {
            latch.latched_busy = true;
        }
        if let Some(value) = active_decode_blocks {
            latch.active_decode_blocks_cleared =
                !Self::is_decode_signal_busy(value, total_blocks, active_decode_blocks_threshold);
        }
        if let Some(value) = kv_used_blocks {
            latch.kv_used_blocks_cleared =
                !Self::is_decode_signal_busy(value, total_blocks, active_decode_blocks_threshold);
        }
        if latch.latched_busy && latch.kv_used_blocks_cleared && latch.active_decode_blocks_cleared
        {
            latch.latched_busy = false;
        }
    }

    fn update_from_active_load(
        &mut self,
        active_load: &ActiveLoad,
199
        active_decode_blocks_threshold: Option<f64>,
200
201
202
203
204
205
206
207
208
209
210
    ) {
        let dp_rank = active_load.dp_rank;
        if let Some(active_blocks) = active_load.active_decode_blocks {
            self.active_decode_blocks.insert(dp_rank, active_blocks);
        }
        if let Some(kv_used_blocks) = active_load.kv_used_blocks {
            self.kv_used_blocks.insert(dp_rank, kv_used_blocks);
        }
        if let Some(active_tokens) = active_load.active_prefill_tokens {
            self.active_prefill_tokens.insert(dp_rank, active_tokens);
        }
211
212
213
214
215
216
217
218
        if let Some(threshold) = active_decode_blocks_threshold {
            self.update_decode_busy_latch(
                dp_rank,
                active_load.active_decode_blocks,
                active_load.kv_used_blocks,
                threshold,
            );
        }
219
220
    }

221
222
    /// Returns true if ALL dp_ranks are considered busy based on the threshold logic.
    ///
223
224
225
    /// Each threshold is `Option<T>`. A `None` threshold means that check is
    /// skipped entirely — it cannot contribute to a dp_rank being busy. If all
    /// three thresholds are `None`, no dp_rank is ever busy.
226
    ///
227
228
229
230
    /// For each dp_rank, a dp_rank is busy if ANY of these conditions is met (OR logic):
    /// 1. `active_prefill_tokens > active_prefill_tokens_threshold` (absolute, if set)
    /// 2. `active_prefill_tokens > frac * max_num_batched_tokens` (fractional, if set)
    /// 3. decode busy latch set by either `kv_used_blocks` or `active_decode_blocks` (if set)
231
232
233
234
    ///
    /// The worker is busy only if ALL dp_ranks are busy.
    pub fn is_busy(
        &self,
235
236
237
        active_decode_blocks_threshold: Option<f64>,
        active_prefill_tokens_threshold: Option<u64>,
        active_prefill_tokens_threshold_frac: Option<f64>,
238
    ) -> bool {
239
240
241
242
243
244
245
246
        // Short-circuit if all thresholds are unset (i.e. no busy check can fire)
        if active_decode_blocks_threshold.is_none()
            && active_prefill_tokens_threshold.is_none()
            && active_prefill_tokens_threshold_frac.is_none()
        {
            return false;
        }

247
248
249
        // Get all dp_ranks we know about
        let all_dp_ranks: std::collections::HashSet<_> = self
            .active_decode_blocks
Yan Ru Pei's avatar
Yan Ru Pei committed
250
            .keys()
251
252
            .chain(self.kv_used_blocks.keys())
            .chain(self.decode_busy_latches.keys())
253
254
            .chain(self.active_prefill_tokens.keys())
            .copied()
Yan Ru Pei's avatar
Yan Ru Pei committed
255
256
            .collect();

257
258
        // If no dp_ranks known, not busy
        if all_dp_ranks.is_empty() {
Yan Ru Pei's avatar
Yan Ru Pei committed
259
            return false;
260
        }
Yan Ru Pei's avatar
Yan Ru Pei committed
261

262
263
        // Check if ALL dp_ranks are busy
        all_dp_ranks.iter().all(|&dp_rank| {
264
265
            // Check 1: prefill tokens threshold (absolute token count)
            if let Some(&active_tokens) = self.active_prefill_tokens.get(&dp_rank) {
266
267
268
                if let Some(abs_threshold) = active_prefill_tokens_threshold
                    && active_tokens > abs_threshold
                {
269
270
271
272
                    return true; // This dp_rank is busy due to absolute token threshold
                }

                // Check 2: prefill tokens threshold (fraction of max_num_batched_tokens)
273
274
275
276
277
278
279
280
281
282
                if let Some(frac) = active_prefill_tokens_threshold_frac {
                    let max_batched = self
                        .max_num_batched_tokens
                        .get(&dp_rank)
                        .copied()
                        .unwrap_or(DEFAULT_MAX_TOKENS);
                    let frac_threshold = (frac * max_batched as f64) as u64;
                    if active_tokens > frac_threshold {
                        return true;
                    }
283
                }
284
285
            }

286
287
288
289
290
291
292
293
            // Check 3: decode busy latch (OR-ed from kv_used_blocks and active_decode_blocks)
            if let Some(decode_threshold) = active_decode_blocks_threshold {
                let is_busy = self
                    .decode_busy_latches
                    .get(&dp_rank)
                    .map(|latch| latch.latched_busy)
                    .unwrap_or_else(|| self.current_decode_busy(dp_rank, decode_threshold));
                if is_busy {
294
295
                    return true;
                }
Yan Ru Pei's avatar
Yan Ru Pei committed
296
            }
297

298
            // If we can't perform any check or no threshold exceeded, this dp_rank is free
299
            false
Yan Ru Pei's avatar
Yan Ru Pei committed
300
        })
301
302
303
    }
}

304
305
/// Worker monitor for tracking KV cache usage and busy states.
///
306
/// Cloning shares state via internal Arc-wrapped fields. This allows multiple pipelines
307
/// (e.g., chat and completions) to share the same monitor instance.
308
///
309
310
311
/// Prometheus metrics are exposed via [`WORKER_LOAD_METRICS`] (defined in `kv_router::sequence`),
/// which should be registered with the HTTP service's Prometheus registry using
/// [`register_worker_load_metrics`](crate::kv_router::metrics::register_worker_load_metrics).
312
313
314
///
/// In disaggregated mode, use `set_prefill_client` to register the prefill endpoint for
/// proper TTFT metric cleanup when prefill workers are removed.
315
#[derive(Clone)]
316
pub struct KvWorkerMonitor {
317
    /// Decode endpoint client (used for ITL cleanup and busy detection)
318
    client: Client,
319
320
321
322
    /// Optional prefill endpoint client (used for TTFT cleanup in disaggregated mode)
    prefill_client: Arc<RwLock<Option<Client>>>,
    /// Notifies the monitoring task when a prefill client is registered
    prefill_client_notify: Arc<Notify>,
323
    worker_load_states: Arc<DashMap<u64, WorkerLoadState>>,
324
325
326
327
    /// Load thresholds for busy detection. Each field is `Option<T>` — unset
    /// means the corresponding check in `is_busy` is skipped. If all three are
    /// `None`, rejection is fully disabled.
    thresholds: Arc<RwLock<LoadThresholdConfig>>,
328
329
    /// Guard to ensure start_monitoring() only runs once across clones
    started: Arc<AtomicBool>,
330
331
}

332
impl KvWorkerMonitor {
333
    /// Create a new worker monitor with the given threshold configuration.
334
    ///
335
336
337
338
    /// Unset thresholds (`None`) remain unset and their corresponding checks
    /// in `is_busy` are skipped. Thresholds can be updated at runtime via
    /// [`set_load_threshold_config`](Self::set_load_threshold_config) or the
    /// individual setters.
339
    ///
340
341
342
    /// Prometheus metrics are exposed via [`WORKER_LOAD_METRICS`] and should be registered
    /// using [`register_worker_load_metrics`](crate::kv_router::metrics::register_worker_load_metrics)
    /// during HTTP service setup.
343
344
345
    ///
    /// For disaggregated mode, call `set_prefill_client` after creation to enable
    /// proper TTFT metric cleanup when prefill workers are removed.
346
    pub fn new(client: Client, config: LoadThresholdConfig) -> Self {
347
348
        Self {
            client,
349
350
            prefill_client: Arc::new(RwLock::new(None)),
            prefill_client_notify: Arc::new(Notify::new()),
351
            worker_load_states: Arc::new(DashMap::new()),
352
            thresholds: Arc::new(RwLock::new(config)),
353
            started: Arc::new(AtomicBool::new(false)),
354
355
356
        }
    }

357
358
359
360
361
362
363
364
365
    /// Returns true iff the user explicitly configured at least one threshold.
    ///
    /// When false, all three per-field checks are skipped in `is_busy` and
    /// rejection is fully disabled. Callers that gate 503 responses on busy
    /// detection should check this before enabling the gate.
    pub fn is_configured(&self) -> bool {
        self.thresholds.read().unwrap().is_configured()
    }

366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
    /// Set the prefill client for disaggregated mode.
    ///
    /// This enables monitoring of prefill endpoint instances for TTFT metric cleanup.
    /// In disaggregated mode, TTFT metrics are attributed to prefill workers, so we need
    /// to watch the prefill endpoint to clean up TTFT gauges when prefill workers disappear.
    ///
    /// This method can be called after `start_monitoring` - the monitoring loop will
    /// be immediately notified and start watching the prefill endpoint.
    pub fn set_prefill_client(&self, prefill_client: Client) {
        let mut guard = self.prefill_client.write().unwrap();
        *guard = Some(prefill_client);
        self.prefill_client_notify.notify_one();
        tracing::debug!("KvWorkerMonitor: prefill client registered for TTFT cleanup");
    }

381
382
383
384
385
386
    /// Get the current active decode blocks threshold, if configured.
    pub fn active_decode_blocks_threshold(&self) -> Option<f64> {
        self.thresholds
            .read()
            .unwrap()
            .active_decode_blocks_threshold
387
388
    }

389
    /// Set the active decode blocks threshold.
390
    pub fn set_active_decode_blocks_threshold(&self, threshold: f64) {
391
392
393
394
        self.thresholds
            .write()
            .unwrap()
            .active_decode_blocks_threshold = Some(threshold);
395
396
    }

397
398
399
400
401
402
    /// Get the current active prefill tokens threshold, if configured.
    pub fn active_prefill_tokens_threshold(&self) -> Option<u64> {
        self.thresholds
            .read()
            .unwrap()
            .active_prefill_tokens_threshold
403
404
    }

405
    /// Set the active prefill tokens threshold.
406
    pub fn set_active_prefill_tokens_threshold(&self, threshold: u64) {
407
408
409
410
        self.thresholds
            .write()
            .unwrap()
            .active_prefill_tokens_threshold = Some(threshold);
411
412
    }

413
414
415
416
417
418
    /// Get the current active prefill tokens threshold frac, if configured.
    pub fn active_prefill_tokens_threshold_frac(&self) -> Option<f64> {
        self.thresholds
            .read()
            .unwrap()
            .active_prefill_tokens_threshold_frac
419
420
    }

421
    /// Set the active prefill tokens threshold frac.
422
    pub fn set_active_prefill_tokens_threshold_frac(&self, frac: f64) {
423
424
425
426
        self.thresholds
            .write()
            .unwrap()
            .active_prefill_tokens_threshold_frac = Some(frac);
427
428
    }

429
430
    /// Get the current load threshold configuration. Unset fields are returned
    /// as `None` (no spurious fallback values).
431
    pub fn load_threshold_config(&self) -> LoadThresholdConfig {
432
        self.thresholds.read().unwrap().clone()
433
434
    }

435
436
437
    /// Update thresholds from a `LoadThresholdConfig`. Only fields that are
    /// `Some` in the input overwrite their counterparts; `None` fields leave
    /// the existing value untouched.
438
    pub fn set_load_threshold_config(&self, config: &LoadThresholdConfig) {
439
440
441
        let mut guard = self.thresholds.write().unwrap();
        if let Some(v) = config.active_decode_blocks_threshold {
            guard.active_decode_blocks_threshold = Some(v);
442
        }
443
444
        if let Some(v) = config.active_prefill_tokens_threshold {
            guard.active_prefill_tokens_threshold = Some(v);
445
        }
446
447
        if let Some(v) = config.active_prefill_tokens_threshold_frac {
            guard.active_prefill_tokens_threshold_frac = Some(v);
448
        }
449
    }
450
}
451

452
453
#[async_trait]
impl WorkerLoadMonitor for KvWorkerMonitor {
454
455
456
457
    /// Start background monitoring of worker KV cache usage.
    ///
    /// This is safe to call multiple times (e.g., from cloned monitors shared across
    /// pipelines) - only the first call spawns the background task.
458
    async fn start_monitoring(&self) -> anyhow::Result<()> {
459
460
461
462
463
464
        // Guard: only start once across all clones
        if self.started.swap(true, Ordering::SeqCst) {
            tracing::debug!("Worker monitoring already started, skipping");
            return Ok(());
        }

465
466
467
        let endpoint = &self.client.endpoint;
        let component = endpoint.component();

468
469
470
471
        let cancellation_token = component.drt().child_token();

        // Watch for runtime config updates from model deployment cards via discovery interface
        let discovery = component.drt().discovery();
472
        let discovery_stream = match discovery
473
            .list_and_watch(DiscoveryQuery::AllModels, Some(cancellation_token.clone()))
474
475
476
477
478
479
480
481
482
483
            .await
        {
            Ok(stream) => stream,
            Err(e) => {
                tracing::error!("KvWorkerMonitor: failed to create discovery stream: {}", e);
                // Reset started flag so retry can work
                self.started.store(false, Ordering::SeqCst);
                return Err(e);
            }
        };
484
485
486
487
        let mut config_events_rx =
            watch_and_extract_field(discovery_stream, |card: ModelDeploymentCard| {
                card.runtime_config
            });
488

489
        // Subscribe to KV metrics events using EventSubscriber (Msgpack payloads)
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
        // This is optional - if NATS isn't available, we skip KV metrics but still do TTFT/ITL cleanup
        let kv_metrics_rx = match EventSubscriber::for_namespace(
            component.namespace(),
            KV_METRICS_SUBJECT,
        )
        .await
        {
            Ok(sub) => Some(sub.typed::<ActiveLoad>()),
            Err(e) => {
                tracing::warn!(
                    "KvWorkerMonitor: KV metrics subscriber not available ({}), skipping load metrics.",
                    e
                );
                None
            }
        };

        // Watch decode endpoint instances for cleanup (ITL metrics)
        let mut decode_instances_rx = self.client.instance_avail_watcher();
509
510
511

        let worker_load_states = self.worker_load_states.clone();
        let client = self.client.clone();
512
513
        let prefill_client_holder = self.prefill_client.clone();
        let prefill_client_notify = self.prefill_client_notify.clone();
514
        let thresholds = self.thresholds.clone();
515
516
517

        // Spawn background monitoring task
        tokio::spawn(async move {
518
            let mut kv_metrics_rx = kv_metrics_rx; // Move into async block
519
520
            let mut previous_busy_instances = Vec::new(); // Track previous state

521
522
523
524
525
526
527
528
529
530
531
532
            // Track decode worker IDs (for ITL cleanup)
            let mut known_decode_workers: std::collections::HashSet<u64> =
                decode_instances_rx.borrow().iter().copied().collect();

            // Track prefill worker IDs (for TTFT cleanup in disaggregated mode)
            let mut known_prefill_workers: std::collections::HashSet<u64> =
                std::collections::HashSet::new();
            let mut prefill_instances_rx: Option<tokio::sync::watch::Receiver<Vec<u64>>> = None;

            let mut known_worker_dp_ranks: HashMap<u64, std::collections::HashSet<u32>> =
                HashMap::new();

533
            loop {
534
535
536
537
538
539
540
541
542
543
                // Create a future that either reads from kv_metrics or pends forever if unavailable
                let kv_event_future = async {
                    if let Some(ref mut rx) = kv_metrics_rx {
                        rx.next().await
                    } else {
                        // If no subscriber, pend forever (this branch is effectively disabled)
                        std::future::pending().await
                    }
                };

544
545
546
547
548
549
                tokio::select! {
                    _ = cancellation_token.cancelled() => {
                        tracing::debug!("Worker monitoring cancelled");
                        break;
                    }

550
                    // Handle runtime config updates
551
552
553
                    _ = config_events_rx.changed() => {
                        let runtime_configs = config_events_rx.borrow().clone();

554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
                        // Find workers that are being removed (not in runtime_configs anymore)
                        let removed_workers: Vec<u64> = known_worker_dp_ranks
                            .keys()
                            .filter(|id| !runtime_configs.contains_key(id))
                            .copied()
                            .collect();

                        // Clean up Prometheus metrics for removed workers
                        for worker_id in &removed_workers {
                            if let Some(dp_ranks) = known_worker_dp_ranks.remove(worker_id) {
                                let dp_ranks_vec: Vec<u32> = dp_ranks.into_iter().collect();
                                // Clean up metrics for both worker types since we don't know which type this worker was
                                cleanup_worker_metrics(*worker_id, &dp_ranks_vec, WORKER_TYPE_DECODE);
                                cleanup_worker_metrics(*worker_id, &dp_ranks_vec, WORKER_TYPE_PREFILL);
                                tracing::debug!(
                                    "Removed Prometheus metrics for worker {}",
                                    worker_id
                                );
                            }
                        }

575
                        worker_load_states.retain(|lease_id, _| runtime_configs.contains_key(lease_id));
576

577
                        // Update worker load states with runtime config values for all dp_ranks
578
                        // This ensures we track workers from MDCs even if they don't publish ActiveLoad
Yan Ru Pei's avatar
Yan Ru Pei committed
579
                        for (lease_id, runtime_config) in runtime_configs.iter() {
580
                            let mut state = worker_load_states.entry(*lease_id).or_default();
Yan Ru Pei's avatar
Yan Ru Pei committed
581

582
583
584
                            let dp_start = runtime_config.data_parallel_start_rank;
                            let dp_end = dp_start + runtime_config.data_parallel_size;

585
586
                            // Track dp_ranks for this worker (for cleanup when worker disappears)
                            let dp_ranks_set = known_worker_dp_ranks.entry(*lease_id).or_default();
587
                            for dp_rank in dp_start..dp_end {
588
589
590
                                dp_ranks_set.insert(dp_rank);
                            }

Yan Ru Pei's avatar
Yan Ru Pei committed
591
592
                            // Populate total_blocks for all dp_ranks (they share the same total)
                            if let Some(total_blocks) = runtime_config.total_kv_blocks {
593
                                for dp_rank in dp_start..dp_end {
Yan Ru Pei's avatar
Yan Ru Pei committed
594
595
596
                                    state.kv_total_blocks.insert(dp_rank, total_blocks);
                                }
                            }
597
598
599

                            // Populate max_num_batched_tokens for all dp_ranks
                            if let Some(max_batched) = runtime_config.max_num_batched_tokens {
600
                                for dp_rank in dp_start..dp_end {
601
602
603
                                    state.max_num_batched_tokens.insert(dp_rank, max_batched);
                                }
                            }
604
605
606
                        }
                    }

607
608
609
610
                    // Handle KV metrics updates (ActiveLoad) - only if subscriber is available
                    // Note: Prometheus gauges are updated directly by sequence.rs (router's own bookkeeping)
                    // This branch only updates WorkerLoadState for busy detection thresholds
                    kv_event = kv_event_future => {
611
                        let Some(event_result) = kv_event else {
612
613
614
615
                            tracing::debug!("KV metrics stream closed");
                            break;
                        };

616
617
                        let Ok((_envelope, active_load)) = event_result else {
                            tracing::error!("Error receiving KV metrics event: {event_result:?}");
618
619
620
621
622
623
                            continue;
                        };

                        let worker_id = active_load.worker_id;
                        let dp_rank = active_load.dp_rank;

624
625
626
627
628
629
                        // Track known worker/dp_rank combinations for cleanup
                        known_worker_dp_ranks
                            .entry(worker_id)
                            .or_default()
                            .insert(dp_rank);

630
631
632
                        // Snapshot thresholds once per event — rare writes (HTTP endpoint)
                        // mean RwLock contention is effectively zero.
                        let cfg = thresholds.read().unwrap().clone();
633

634
635
636
637
638
639
                        // Update worker load state per dp_rank (for busy detection only)
                        // Note: Prometheus gauges are updated directly by sequence.rs
                        {
                            let mut state = worker_load_states.entry(worker_id).or_default();
                            state.update_from_active_load(
                                &active_load,
640
                                cfg.active_decode_blocks_threshold,
641
642
643
                            );
                        }

644
                        // Recalculate all busy instances and update
645
                        let busy_instances: Vec<u64> = worker_load_states
646
                            .iter()
647
648
649
650
                            .filter_map(|entry| {
                                entry
                                    .value()
                                    .is_busy(
651
652
653
                                        cfg.active_decode_blocks_threshold,
                                        cfg.active_prefill_tokens_threshold,
                                        cfg.active_prefill_tokens_threshold_frac,
654
655
                                    )
                                    .then_some(*entry.key())
656
657
658
659
660
661
662
663
                            })
                            .collect();

                        // Only update if busy_instances has changed
                        if busy_instances != previous_busy_instances {
                            tracing::debug!("Busy instances changed: {:?}", busy_instances);
                            client.update_free_instances(&busy_instances);
                            previous_busy_instances = busy_instances;
664
665
                        }
                    }
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758

                    // Handle decode endpoint instance changes (for ITL and decode metrics cleanup)
                    _ = decode_instances_rx.changed() => {
                        let current_instances: std::collections::HashSet<u64> =
                            decode_instances_rx.borrow().iter().copied().collect();

                        // Find decode workers that disappeared
                        let removed_workers: Vec<u64> = known_decode_workers
                            .difference(&current_instances)
                            .copied()
                            .collect();

                        if !removed_workers.is_empty() {
                            // Clean up metrics for removed decode workers (with worker_type=decode label)
                            for worker_id in &removed_workers {
                                // Get dp_ranks from known_worker_dp_ranks if available, otherwise use [0]
                                let dp_ranks: Vec<u32> = known_worker_dp_ranks
                                    .get(worker_id)
                                    .map(|ranks| ranks.iter().copied().collect())
                                    .unwrap_or_else(|| vec![0]);
                                cleanup_worker_metrics(*worker_id, &dp_ranks, WORKER_TYPE_DECODE);
                                tracing::debug!(
                                    "Cleaned up metrics for removed decode worker {}",
                                    worker_id
                                );
                            }
                        }

                        known_decode_workers = current_instances;
                    }

                    // Handle prefill endpoint instance changes (for TTFT and prefill metrics cleanup in disaggregated mode)
                    result = async {
                        if let Some(ref mut rx) = prefill_instances_rx {
                            rx.changed().await
                        } else {
                            // No prefill watcher yet, pend forever
                            std::future::pending().await
                        }
                    } => {
                        // Handle channel closure (e.g., all prefill workers went down)
                        let Ok(()) = result else {
                            // Prefill endpoint closed - stop watching to avoid busy loop
                            prefill_instances_rx = None;
                            tracing::info!("Prefill endpoint watcher closed, will re-activate when client is set");
                            continue;
                        };

                        let Some(ref rx) = prefill_instances_rx else {
                            continue;
                        };

                        let current_instances: std::collections::HashSet<u64> =
                            rx.borrow().iter().copied().collect();

                        // Find prefill workers that disappeared
                        let removed_workers: Vec<u64> = known_prefill_workers
                            .difference(&current_instances)
                            .copied()
                            .collect();

                        if !removed_workers.is_empty() {
                            // Clean up metrics for removed prefill workers (with worker_type=prefill label)
                            for worker_id in &removed_workers {
                                // Get dp_ranks from known_worker_dp_ranks if available, otherwise use [0]
                                let dp_ranks: Vec<u32> = known_worker_dp_ranks
                                    .get(worker_id)
                                    .map(|ranks| ranks.iter().copied().collect())
                                    .unwrap_or_else(|| vec![0]);
                                cleanup_worker_metrics(*worker_id, &dp_ranks, WORKER_TYPE_PREFILL);
                                tracing::debug!(
                                    "Cleaned up metrics for removed prefill worker {}",
                                    worker_id
                                );
                            }
                        }

                        known_prefill_workers = current_instances;
                    }

                    // Wait for prefill client to be registered (push-based notification)
                    _ = prefill_client_notify.notified(), if prefill_instances_rx.is_none() => {
                        let guard = prefill_client_holder.read().unwrap();
                        if let Some(ref prefill_client) = *guard {
                            let rx = prefill_client.instance_avail_watcher();
                            known_prefill_workers = rx.borrow().iter().copied().collect();
                            prefill_instances_rx = Some(rx);
                            tracing::info!(
                                "KvWorkerMonitor: prefill endpoint watcher activated, tracking {} workers",
                                known_prefill_workers.len()
                            );
                        }
                    }
759
760
761
762
763
764
765
766
767
                }
            }

            tracing::info!("Worker monitoring task exiting");
        });

        Ok(())
    }
}
768
769
770

#[cfg(test)]
mod tests {
771
    use super::{LoadThresholdConfig, WorkerLoadState};
772
773
    use dynamo_kv_router::protocols::ActiveLoad;

774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
    #[test]
    fn load_threshold_config_default_is_not_configured() {
        assert!(!LoadThresholdConfig::default().is_configured());
    }

    #[test]
    fn load_threshold_config_decode_only_is_configured() {
        let config = LoadThresholdConfig {
            active_decode_blocks_threshold: Some(0.85),
            ..Default::default()
        };
        assert!(config.is_configured());
    }

    #[test]
    fn load_threshold_config_prefill_tokens_only_is_configured() {
        let config = LoadThresholdConfig {
            active_prefill_tokens_threshold: Some(10_000),
            ..Default::default()
        };
        assert!(config.is_configured());
    }

    #[test]
    fn load_threshold_config_prefill_frac_only_is_configured() {
        let config = LoadThresholdConfig {
            active_prefill_tokens_threshold_frac: Some(0.9),
            ..Default::default()
        };
        assert!(config.is_configured());
    }

    #[test]
    fn load_threshold_config_all_set_is_configured() {
        let config = LoadThresholdConfig {
            active_decode_blocks_threshold: Some(0.85),
            active_prefill_tokens_threshold: Some(10_000),
            active_prefill_tokens_threshold_frac: Some(0.9),
        };
        assert!(config.is_configured());
    }

816
817
818
819
820
821
822
    #[test]
    fn is_busy_prefers_kv_used_blocks_over_active_decode_blocks() {
        let mut state = WorkerLoadState::default();
        state.active_decode_blocks.insert(0, 10);
        state.kv_used_blocks.insert(0, 90);
        state.kv_total_blocks.insert(0, 100);

823
        assert!(state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
824
825
826
827
828
829
830
831
    }

    #[test]
    fn is_busy_falls_back_to_active_decode_blocks_when_kv_used_missing() {
        let mut state = WorkerLoadState::default();
        state.active_decode_blocks.insert(0, 90);
        state.kv_total_blocks.insert(0, 100);

832
        assert!(state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
833
834
835
836
837
838
839
840
    }

    #[test]
    fn is_busy_recognizes_dp_rank_known_only_from_kv_used_blocks() {
        let mut state = WorkerLoadState::default();
        state.kv_used_blocks.insert(0, 90);
        state.kv_total_blocks.insert(0, 100);

841
        assert!(state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
842
843
844
845
846
847
848
849
850
851
852
853
854
855
    }

    #[test]
    fn decode_busy_latch_sets_busy_if_any_signal_is_busy() {
        let mut state = WorkerLoadState::default();
        state.kv_total_blocks.insert(0, 100);
        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: None,
                active_prefill_tokens: None,
                kv_used_blocks: Some(90),
            },
856
            Some(0.6),
857
858
        );

859
        assert!(state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
    }

    #[test]
    fn decode_busy_latch_only_clears_after_both_signals_report_nonbusy() {
        let mut state = WorkerLoadState::default();
        state.kv_total_blocks.insert(0, 100);

        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: None,
                active_prefill_tokens: None,
                kv_used_blocks: Some(90),
            },
875
            Some(0.6),
876
        );
877
        assert!(state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
878
879
880
881
882
883
884
885
886

        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: Some(10),
                active_prefill_tokens: None,
                kv_used_blocks: None,
            },
887
            Some(0.6),
888
        );
889
        assert!(state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
890
891
892
893
894
895
896
897
898

        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: None,
                active_prefill_tokens: None,
                kv_used_blocks: Some(10),
            },
899
            Some(0.6),
900
        );
901
        assert!(!state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
    }

    #[test]
    fn decode_busy_latch_clears_with_only_kv_used_blocks_signal() {
        let mut state = WorkerLoadState::default();
        state.kv_total_blocks.insert(0, 100);

        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: None,
                active_prefill_tokens: None,
                kv_used_blocks: Some(90),
            },
917
            Some(0.6),
918
        );
919
        assert!(state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
920
921
922
923
924
925
926
927
928

        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: None,
                active_prefill_tokens: None,
                kv_used_blocks: Some(10),
            },
929
            Some(0.6),
930
        );
931
        assert!(!state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
    }

    #[test]
    fn decode_busy_latch_clears_with_only_active_decode_blocks_signal() {
        let mut state = WorkerLoadState::default();
        state.kv_total_blocks.insert(0, 100);

        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: Some(90),
                active_prefill_tokens: None,
                kv_used_blocks: None,
            },
947
            Some(0.6),
948
        );
949
        assert!(state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
950
951
952
953
954
955
956
957
958

        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: Some(10),
                active_prefill_tokens: None,
                kv_used_blocks: None,
            },
959
            Some(0.6),
960
        );
961
        assert!(!state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
    }

    #[test]
    fn decode_busy_latch_clears_when_both_signals_are_nonbusy_in_same_event() {
        let mut state = WorkerLoadState::default();
        state.kv_total_blocks.insert(0, 100);

        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: Some(90),
                active_prefill_tokens: None,
                kv_used_blocks: None,
            },
977
            Some(0.6),
978
        );
979
        assert!(state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
980
981
982
983
984
985
986
987
988

        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: Some(10),
                active_prefill_tokens: None,
                kv_used_blocks: Some(10),
            },
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
            Some(0.6),
        );
        assert!(!state.is_busy(Some(0.6), Some(u64::MAX), Some(2.0)));
    }

    #[test]
    fn is_busy_returns_false_when_all_thresholds_are_none() {
        let mut state = WorkerLoadState::default();
        state.kv_total_blocks.insert(0, 100);
        state.active_decode_blocks.insert(0, 99);
        state.kv_used_blocks.insert(0, 99);
        state.active_prefill_tokens.insert(0, u64::MAX / 2);
        state.max_num_batched_tokens.insert(0, 1_000);

        assert!(!state.is_busy(None, None, None));
    }

    #[test]
    fn is_busy_with_only_decode_threshold_ignores_prefill_signals() {
        let mut state = WorkerLoadState::default();
        state.max_num_batched_tokens.insert(0, 1_000);
        state.active_prefill_tokens.insert(0, 5_000);

        assert!(!state.is_busy(Some(0.6), None, None));
    }

    #[test]
    fn is_busy_with_only_prefill_abs_ignores_decode_latch() {
        let mut state = WorkerLoadState::default();
        state.kv_total_blocks.insert(0, 100);
        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: Some(90),
                active_prefill_tokens: None,
                kv_used_blocks: Some(90),
            },
            Some(0.6),
1028
        );
1029
1030
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
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065

        assert!(!state.is_busy(None, Some(u64::MAX), None));
    }

    #[test]
    fn is_busy_with_only_prefill_frac_ignores_decode_latch() {
        let mut state = WorkerLoadState::default();
        state.kv_total_blocks.insert(0, 100);
        state.update_from_active_load(
            &ActiveLoad {
                worker_id: 1,
                dp_rank: 0,
                active_decode_blocks: Some(90),
                active_prefill_tokens: None,
                kv_used_blocks: Some(90),
            },
            Some(0.6),
        );

        assert!(!state.is_busy(None, None, Some(2.0)));
    }

    #[test]
    fn is_busy_with_only_prefill_abs_fires_when_tokens_exceed_threshold() {
        let mut state = WorkerLoadState::default();
        state.active_prefill_tokens.insert(0, 5_000);

        assert!(state.is_busy(None, Some(1_000), None));
    }

    #[test]
    fn is_busy_with_only_prefill_frac_fires_when_fraction_exceeded() {
        let mut state = WorkerLoadState::default();
        state.max_num_batched_tokens.insert(0, 1_000);
        state.active_prefill_tokens.insert(0, 2_500);

        assert!(state.is_busy(None, None, Some(2.0)));
1066
1067
    }
}