"deploy/vscode:/vscode.git/clone" did not exist on "740130eb65b947ca09fc5ba5d2336d77eceb3e55"
kv.rs 37.5 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
use pythonize::{depythonize, pythonize};
5
use std::collections::HashMap;
6
use std::sync::Arc;
7
use std::sync::atomic::AtomicU32;
8
use std::sync::mpsc;
9
use tokio_stream::StreamExt;
10

11
use super::*;
12
use crate::Component;
13
use llm_rs::kv_router::protocols::compute_block_hash_for_seq;
Yan Ru Pei's avatar
Yan Ru Pei committed
14
use rs::pipeline::{AsyncEngine, SingleIn};
15
use tracing;
16

17
use llm_rs::kv_router::protocols::*;
18
use llm_rs::kv_router::publisher::{KvEventSourceConfig, create_stored_blocks, start_zmq_listener};
19
use llm_rs::protocols::common::timing::RequestTracker;
20
use llm_rs::protocols::common::{OutputOptions, SamplingOptions, StopConditions};
21
use serde_json::json;
22

Yan Ru Pei's avatar
Yan Ru Pei committed
23
#[pyfunction]
24
25
26
27
28
29
30
#[pyo3(signature = (tokens, kv_block_size, block_mm_infos=None))]
pub fn compute_block_hash_for_seq_py(
    _py: Python,
    tokens: Vec<u32>,
    kv_block_size: usize,
    block_mm_infos: Option<Bound<PyAny>>,
) -> PyResult<Vec<u64>> {
Yan Ru Pei's avatar
Yan Ru Pei committed
31
    if kv_block_size == 0 {
32
33
34
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "kv_block_size cannot be 0",
        ));
Yan Ru Pei's avatar
Yan Ru Pei committed
35
36
    }

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    // Convert Python block_mm_infos to Rust Vec<Option<BlockExtraInfo>>
    let mm_infos_rust: Option<Vec<Option<BlockExtraInfo>>> = block_mm_infos
        .as_ref()
        .map(|infos_py| {
            depythonize::<Vec<Option<BlockExtraInfo>>>(infos_py).map_err(|e| {
                PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                    "Failed to convert block_mm_infos: {}",
                    e
                ))
            })
        })
        .transpose()?;

    let hashes =
        compute_block_hash_for_seq(&tokens, kv_block_size as u32, mm_infos_rust.as_deref());

Yan Ru Pei's avatar
Yan Ru Pei committed
53
54
55
    Ok(hashes.into_iter().map(|h| h.0).collect())
}

GuanLuo's avatar
GuanLuo committed
56
#[pyclass]
57
58
pub(crate) struct WorkerMetricsPublisher {
    inner: Arc<llm_rs::kv_router::publisher::WorkerMetricsPublisher>,
GuanLuo's avatar
GuanLuo committed
59
60
61
}

#[pymethods]
62
impl WorkerMetricsPublisher {
GuanLuo's avatar
GuanLuo committed
63
64
    #[new]
    fn new() -> PyResult<Self> {
65
66
        let inner =
            llm_rs::kv_router::publisher::WorkerMetricsPublisher::new().map_err(to_pyerr)?;
GuanLuo's avatar
GuanLuo committed
67
68
69
70
71
        Ok(Self {
            inner: inner.into(),
        })
    }

72
    #[pyo3(signature = (component))]
Alec's avatar
Alec committed
73
    fn create_endpoint<'p>(
GuanLuo's avatar
GuanLuo committed
74
75
76
77
78
79
80
        &self,
        py: Python<'p>,
        component: Component,
    ) -> PyResult<Bound<'p, PyAny>> {
        let rs_publisher = self.inner.clone();
        let rs_component = component.inner.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
81
            rs_publisher
82
                .create_endpoint(rs_component)
GuanLuo's avatar
GuanLuo committed
83
84
85
86
87
88
                .await
                .map_err(to_pyerr)?;
            Ok(())
        })
    }

89
90
91
92
93
94
95
    /// Publish worker metrics for load monitoring.
    ///
    /// # Arguments
    /// * `dp_rank` - Data parallel rank of the worker (None defaults to 0)
    /// * `active_decode_blocks` - Number of active KV cache blocks
    #[pyo3(signature = (dp_rank, active_decode_blocks))]
    fn publish(&self, dp_rank: Option<u32>, active_decode_blocks: u64) -> PyResult<()> {
GuanLuo's avatar
GuanLuo committed
96
        self.inner
97
            .publish(dp_rank, active_decode_blocks)
GuanLuo's avatar
GuanLuo committed
98
99
100
            .map_err(to_pyerr)
    }
}
101

102
103
#[pyclass]
#[derive(Clone)]
104
pub struct ZmqKvEventPublisherConfig {
105
    #[pyo3(get, set)]
Yan Ru Pei's avatar
Yan Ru Pei committed
106
    pub worker_id: WorkerId,
107
108
109
110
111
112
    #[pyo3(get, set)]
    pub kv_block_size: usize,
    #[pyo3(get, set)]
    pub zmq_endpoint: String,
    #[pyo3(get, set)]
    pub zmq_topic: String,
113
114
    #[pyo3(get, set)]
    pub enable_local_indexer: bool, // whether the underlying KvEventPublisher publishes to
115
116
117
    // both global and worker-local KvIndexers
    #[pyo3(get, set)]
    pub dp_rank: DpRank, // data parallel rank for this publisher
118
119
120
}

#[pymethods]
121
impl ZmqKvEventPublisherConfig {
122
123
124
125
126
    #[new]
    #[pyo3(signature = (
        worker_id,
        kv_block_size,
        zmq_endpoint = "tcp://127.0.0.1:5557".to_string(),
127
        zmq_topic = "".to_string(),
128
        enable_local_indexer = true,
129
        dp_rank = 0
130
131
    ))]
    pub fn new(
Yan Ru Pei's avatar
Yan Ru Pei committed
132
        worker_id: WorkerId,
133
134
135
        kv_block_size: usize,
        zmq_endpoint: String,
        zmq_topic: String,
136
        enable_local_indexer: bool,
137
        dp_rank: DpRank,
138
139
140
141
142
143
    ) -> Self {
        Self {
            worker_id,
            kv_block_size,
            zmq_endpoint,
            zmq_topic,
144
            enable_local_indexer,
145
            dp_rank,
146
147
148
149
        }
    }
}

Yan Ru Pei's avatar
Yan Ru Pei committed
150
151
152
153
154
155
156
157
158
159
160
/// A ZMQ-based key-value cache event listener that operates independently
/// of the dynamo runtime or event plane infrastructure.
#[pyclass]
pub(crate) struct ZmqKvEventListener {
    event_receiver: Arc<tokio::sync::Mutex<tokio::sync::mpsc::UnboundedReceiver<KvCacheEvent>>>,
    shutdown_token: tokio_util::sync::CancellationToken,
}

#[pymethods]
impl ZmqKvEventListener {
    #[new]
161
    #[pyo3(signature = (zmq_endpoint, zmq_topic, kv_block_size))]
Yan Ru Pei's avatar
Yan Ru Pei committed
162
163
164
165
166
167
168
169
170
    fn new(zmq_endpoint: String, zmq_topic: String, kv_block_size: usize) -> PyResult<Self> {
        if kv_block_size == 0 {
            return Err(to_pyerr(anyhow::anyhow!("kv_block_size cannot be 0")));
        }

        let runtime = pyo3_async_runtimes::tokio::get_runtime();
        runtime.block_on(async {
            let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<KvCacheEvent>();
            let shutdown_token = tokio_util::sync::CancellationToken::new();
171
172
            // Standalone listener needs its own event ID counter
            let next_event_id = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
Yan Ru Pei's avatar
Yan Ru Pei committed
173

174
            tokio::spawn(start_zmq_listener(
Yan Ru Pei's avatar
Yan Ru Pei committed
175
176
177
178
                zmq_endpoint,
                zmq_topic,
                tx,
                shutdown_token.clone(),
179
                kv_block_size as u32,
180
                next_event_id,
Yan Ru Pei's avatar
Yan Ru Pei committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
            ));

            Ok(Self {
                event_receiver: Arc::new(tokio::sync::Mutex::new(rx)),
                shutdown_token,
            })
        })
    }

    fn get_events<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> {
        let receiver = self.event_receiver.clone();
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let mut rx = receiver.lock().await;
            let mut events = Vec::new();

            // Drain all available events
            while let Ok(event) = rx.try_recv() {
                events.push(event);
            }

            // Convert events to JSON strings
            let json_events: Result<Vec<String>, _> =
                events.iter().map(serde_json::to_string).collect();

            match json_events {
                Ok(json_strings) => Ok(json_strings),
                Err(e) => Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                    "Failed to serialize events to JSON: {}",
                    e
                ))),
            }
        })
    }
}

// manual shutdown needed as it's not tied to the dynamo DRT
impl Drop for ZmqKvEventListener {
    fn drop(&mut self) {
        self.shutdown_token.cancel();
    }
}

223
224
225
#[pyclass]
pub(crate) struct KvEventPublisher {
    inner: Arc<llm_rs::kv_router::publisher::KvEventPublisher>,
226
    kv_block_size: usize,
Yan Ru Pei's avatar
Yan Ru Pei committed
227
    dp_rank: DpRank,
228
    warning_count: Arc<AtomicU32>,
229
230
231
232
233
}

#[pymethods]
impl KvEventPublisher {
    #[new]
234
    #[pyo3(signature = (component, worker_id=0, kv_block_size=0, dp_rank=0, enable_local_indexer=false, zmq_config=None))]
235
236
237
238
239
    fn new(
        component: Component,
        worker_id: WorkerId,
        kv_block_size: usize,
        dp_rank: DpRank,
240
        enable_local_indexer: bool,
241
        zmq_config: Option<ZmqKvEventPublisherConfig>,
242
    ) -> PyResult<Self> {
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
        // worker_id is not used; connection_id is inferred from the component.
        let _ = worker_id;

        // When zmq_config is provided, use its fields for kv_block_size/dp_rank/enable_local_indexer
        let (kv_block_size, dp_rank, enable_local_indexer, source_config) =
            if let Some(ref cfg) = zmq_config {
                (
                    cfg.kv_block_size,
                    cfg.dp_rank,
                    cfg.enable_local_indexer,
                    Some(KvEventSourceConfig::Zmq {
                        endpoint: cfg.zmq_endpoint.clone(),
                        topic: cfg.zmq_topic.clone(),
                    }),
                )
            } else {
                (kv_block_size, dp_rank, enable_local_indexer, None)
            };

Yan Ru Pei's avatar
Yan Ru Pei committed
262
263
264
265
        if kv_block_size == 0 {
            return Err(to_pyerr(anyhow::anyhow!("kv_block_size cannot be 0")));
        }

266
        let inner = llm_rs::kv_router::publisher::KvEventPublisher::new_with_local_indexer(
267
            component.inner,
268
            kv_block_size as u32,
269
            source_config,
270
            enable_local_indexer,
271
            dp_rank,
272
273
        )
        .map_err(to_pyerr)?;
274

275
276
        Ok(Self {
            inner: inner.into(),
277
            kv_block_size,
Yan Ru Pei's avatar
Yan Ru Pei committed
278
            dp_rank,
279
            warning_count: Arc::new(AtomicU32::new(0)),
280
281
282
283
        })
    }

    #[allow(clippy::too_many_arguments)]
284
    #[pyo3(signature = (token_ids, num_block_tokens, block_hashes, lora_id, parent_hash=None, block_mm_infos=None))]
285
    fn publish_stored(
286
        &self,
287
        py: Python,
288
289
        token_ids: Vec<u32>,
        num_block_tokens: Vec<u64>,
290
        block_hashes: Vec<i64>,
291
        lora_id: u64,
292
        parent_hash: Option<i64>,
293
        block_mm_infos: Option<Bound<PyAny>>,
294
    ) -> PyResult<()> {
295
296
297
298
299
        let kv_block_size = self.kv_block_size as u32;
        let dp_rank = self.dp_rank;
        let warning_count = self.warning_count.clone();
        let inner = self.inner.clone();

300
301
302
        // Use shared monotonic event_id counter from the inner publisher
        let event_id = inner.next_event_id();

303
304
305
306
307
308
309
310
311
312
313
314
315
        // Convert Python block_mm_infos to Rust Vec<Option<BlockExtraInfo>>
        let mm_infos_rust: Option<Vec<Option<BlockExtraInfo>>> = block_mm_infos
            .as_ref()
            .map(|infos_py| {
                depythonize::<Vec<Option<BlockExtraInfo>>>(infos_py).map_err(|e| {
                    PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                        "Failed to convert block_mm_infos: {}",
                        e
                    ))
                })
            })
            .transpose()?;

316
317
318
319
320
321
322
323
324
325
326
327
328
        py.allow_threads(|| {
            let block_hashes_u64: Vec<u64> = block_hashes.iter().map(|&h| h as u64).collect();
            let event = KvCacheEvent {
                event_id,
                data: KvCacheEventData::Stored(KvCacheStoreData {
                    parent_hash: parent_hash.map(ExternalSequenceBlockHash::from),
                    blocks: create_stored_blocks(
                        kv_block_size,
                        &token_ids,
                        &num_block_tokens,
                        &block_hashes_u64,
                        lora_id,
                        &warning_count,
329
                        mm_infos_rust.as_deref(),
330
331
332
333
334
335
336
                    ),
                }),
                dp_rank,
            };

            inner.publish(event).map_err(to_pyerr)
        })
337
338
    }

339
    fn publish_removed(&self, py: Python, block_hashes: Vec<i64>) -> PyResult<()> {
340
341
342
        let dp_rank = self.dp_rank;
        let inner = self.inner.clone();

343
344
345
        // Use shared monotonic event_id counter from the inner publisher
        let event_id = inner.next_event_id();

346
347
348
349
350
351
352
353
354
355
356
357
358
        py.allow_threads(|| {
            let block_hashes: Vec<ExternalSequenceBlockHash> = block_hashes
                .into_iter()
                .map(ExternalSequenceBlockHash::from)
                .collect();
            let event = KvCacheEvent {
                event_id,
                data: KvCacheEventData::Removed(KvCacheRemoveData { block_hashes }),
                dp_rank,
            };

            inner.publish(event).map_err(to_pyerr)
        })
359
    }
360
361
362
363
364
365
366
367

    fn shutdown(&mut self) {
        // If no other Arc clones exist, shut down eagerly.
        // Otherwise the Drop impl handles cleanup when the last reference is freed.
        if let Some(inner) = Arc::get_mut(&mut self.inner) {
            inner.shutdown();
        }
    }
368
369
}

370
371
372
#[pyclass]
#[derive(Clone)]
pub(crate) struct OverlapScores {
373
    inner: llm_rs::kv_router::protocols::OverlapScores,
374
375
376
377
378
}

#[pymethods]
impl OverlapScores {
    #[getter]
379
    fn scores(&self) -> HashMap<(u64, u32), u32> {
Yan Ru Pei's avatar
Yan Ru Pei committed
380
381
382
383
384
385
        // Return scores with full WorkerWithDpRank granularity as (worker_id, dp_rank) tuples
        self.inner
            .scores
            .iter()
            .map(|(worker, score)| ((worker.worker_id, worker.dp_rank), *score))
            .collect()
386
387
388
389
390
391
392
393
    }

    #[getter]
    fn frequencies(&self) -> Vec<usize> {
        self.inner.frequencies.clone()
    }
}

394
395
396
397
398
#[derive(Debug)]
enum RadixTreeRequest {
    FindMatches {
        local_block_hashes: Vec<llm_rs::kv_router::protocols::LocalBlockHash>,
        early_exit: bool,
399
        response_tx: mpsc::SyncSender<llm_rs::kv_router::protocols::OverlapScores>,
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
    },
    ApplyEvent {
        worker_id: WorkerId,
        kv_cache_event_bytes: Vec<u8>,
        response_tx: mpsc::SyncSender<PyResult<()>>,
    },
    RemoveWorker {
        worker_id: WorkerId,
        response_tx: mpsc::SyncSender<()>,
    },
    ClearAllBlocks {
        worker_id: WorkerId,
        response_tx: mpsc::SyncSender<()>,
    },
    DumpTreeAsEvents {
415
        response_tx: mpsc::SyncSender<Vec<llm_rs::kv_router::protocols::RouterEvent>>,
416
417
418
419
420
421
    },
    Shutdown,
}

// NOTE: RadixTree is now thread-safe with pure sync patterns
#[pyclass]
Yan Ru Pei's avatar
Yan Ru Pei committed
422
pub(crate) struct RadixTree {
423
    request_tx: mpsc::Sender<RadixTreeRequest>,
Yan Ru Pei's avatar
Yan Ru Pei committed
424
425
426
427
428
429
430
431
}

#[pymethods]
impl RadixTree {
    #[new]
    #[pyo3(signature = (expiration_duration_secs=None))]
    fn new(expiration_duration_secs: Option<f64>) -> PyResult<Self> {
        let expiration_duration = expiration_duration_secs.map(std::time::Duration::from_secs_f64);
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457

        let (request_tx, request_rx) = mpsc::channel::<RadixTreeRequest>();

        // Spawn dedicated thread with simplified sync processing
        std::thread::spawn(move || {
            let mut radix_tree =
                llm_rs::kv_router::indexer::RadixTree::new_with_frequency(expiration_duration);

            loop {
                match request_rx.recv() {
                    Ok(RadixTreeRequest::Shutdown) => {
                        tracing::debug!("RadixTree thread received shutdown request");
                        break;
                    }
                    Ok(request) => {
                        Self::handle_request(&mut radix_tree, request);
                    }
                    Err(mpsc::RecvError) => {
                        tracing::debug!("RadixTree request channel disconnected");
                        break;
                    }
                }
            }
        });

        Ok(Self { request_tx })
Yan Ru Pei's avatar
Yan Ru Pei committed
458
459
460
461
462
    }

    #[pyo3(signature = (sequence, early_exit=false))]
    fn find_matches(
        &self,
463
        py: Python,
Yan Ru Pei's avatar
Yan Ru Pei committed
464
465
466
        sequence: Vec<u64>,
        early_exit: bool,
    ) -> PyResult<OverlapScores> {
467
468
469
470
471
472
473
474
475
476
477
478
479
480
        let (response_tx, response_rx) = mpsc::sync_channel(1);

        let local_block_hashes = py.allow_threads(|| {
            sequence
                .into_iter()
                .map(llm_rs::kv_router::protocols::LocalBlockHash)
                .collect()
        });

        let request = RadixTreeRequest::FindMatches {
            local_block_hashes,
            early_exit,
            response_tx,
        };
Yan Ru Pei's avatar
Yan Ru Pei committed
481

482
483
484
485
486
487
488
489
490
491
492
493
494
495
        self.request_tx.send(request).map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                "RadixTree background task has shut down",
            )
        })?;

        // Release GIL while waiting for response
        let result = py.allow_threads(move || {
            response_rx.recv().map_err(|_| {
                PyErr::new::<pyo3::exceptions::PyRuntimeError, _>("RadixTree request was cancelled")
            })
        })?;

        Ok(OverlapScores { inner: result })
Yan Ru Pei's avatar
Yan Ru Pei committed
496
497
498
    }

    fn apply_event(
499
500
        &self,
        py: Python,
Yan Ru Pei's avatar
Yan Ru Pei committed
501
        worker_id: WorkerId,
Yan Ru Pei's avatar
Yan Ru Pei committed
502
503
        kv_cache_event_bytes: &[u8],
    ) -> PyResult<()> {
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
        let (response_tx, response_rx) = mpsc::sync_channel(1);

        let request = RadixTreeRequest::ApplyEvent {
            worker_id,
            kv_cache_event_bytes: kv_cache_event_bytes.to_vec(),
            response_tx,
        };

        self.request_tx.send(request).map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                "RadixTree background task has shut down",
            )
        })?;

        // Release GIL while waiting for response
        let result = py.allow_threads(move || response_rx.recv());

        result.map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyRuntimeError, _>("RadixTree request was cancelled")
        })?
    }

    fn remove_worker(&self, py: Python, worker_id: WorkerId) -> PyResult<()> {
        let (response_tx, response_rx) = mpsc::sync_channel(1);

        let request = RadixTreeRequest::RemoveWorker {
            worker_id,
            response_tx,
        };

        self.request_tx.send(request).map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                "RadixTree background task has shut down",
            )
        })?;

        // Release GIL while waiting for response
        py.allow_threads(move || {
            response_rx.recv().map_err(|_| {
                PyErr::new::<pyo3::exceptions::PyRuntimeError, _>("RadixTree request was cancelled")
            })
        })
    }

    fn clear_all_blocks(&self, py: Python, worker_id: WorkerId) -> PyResult<()> {
        let (response_tx, response_rx) = mpsc::sync_channel(1);

        let request = RadixTreeRequest::ClearAllBlocks {
            worker_id,
            response_tx,
        };

        self.request_tx.send(request).map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                "RadixTree background task has shut down",
            )
        })?;

        // Release GIL while waiting for response
        py.allow_threads(move || {
            response_rx.recv().map_err(|_| {
                PyErr::new::<pyo3::exceptions::PyRuntimeError, _>("RadixTree request was cancelled")
            })
        })
    }
Yan Ru Pei's avatar
Yan Ru Pei committed
569

570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
    fn dump_tree_as_events(&self, py: Python) -> PyResult<Vec<String>> {
        let (response_tx, response_rx) = mpsc::sync_channel(1);

        let request = RadixTreeRequest::DumpTreeAsEvents { response_tx };

        self.request_tx.send(request).map_err(|_| {
            PyErr::new::<pyo3::exceptions::PyRuntimeError, _>("Failed to send dump tree request")
        })?;

        // Release GIL while waiting for response from dedicated thread
        let events = py.allow_threads(move || {
            response_rx.recv().map_err(|_| {
                PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                    "Failed to receive dump tree response",
                )
            })
        })?;

        // Serialize RouterEvent structs to JSON strings with GIL released
        py.allow_threads(move || {
            events
                .into_iter()
                .map(|event| {
                    serde_json::to_string(&event).map_err(|e| {
                        PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                            "Failed to serialize event to JSON: {}",
                            e
                        ))
                    })
                })
                .collect::<Result<Vec<String>, PyErr>>()
        })
Yan Ru Pei's avatar
Yan Ru Pei committed
602
    }
603
}
Yan Ru Pei's avatar
Yan Ru Pei committed
604

605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
impl RadixTree {
    fn handle_request(
        radix_tree: &mut llm_rs::kv_router::indexer::RadixTree,
        request: RadixTreeRequest,
    ) {
        match request {
            RadixTreeRequest::FindMatches {
                local_block_hashes,
                early_exit,
                response_tx,
            } => {
                let result = radix_tree.find_matches(local_block_hashes, early_exit);
                let _ = response_tx.send(result);
            }
            RadixTreeRequest::ApplyEvent {
                worker_id,
                kv_cache_event_bytes,
                response_tx,
            } => {
                let result = match serde_json::from_slice::<
                    llm_rs::kv_router::protocols::KvCacheEvent,
                >(&kv_cache_event_bytes)
                {
                    Ok(kv_cache_event) => {
629
630
631
632
                        let router_event = llm_rs::kv_router::protocols::RouterEvent::new(
                            worker_id,
                            kv_cache_event,
                        );
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
                        match radix_tree.apply_event(router_event) {
                            Ok(_) => Ok(()),
                            Err(e) => Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                                format!("Failed to apply event: {}", e),
                            )),
                        }
                    }
                    Err(e) => Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
                        "Failed to deserialize KvCacheEvent: {}",
                        e
                    ))),
                };
                let _ = response_tx.send(result);
            }
            RadixTreeRequest::RemoveWorker {
                worker_id,
                response_tx,
            } => {
                radix_tree.remove_worker(worker_id);
                let _ = response_tx.send(());
            }
            RadixTreeRequest::ClearAllBlocks {
                worker_id,
                response_tx,
            } => {
                radix_tree.clear_all_blocks(worker_id);
                let _ = response_tx.send(());
            }
            RadixTreeRequest::DumpTreeAsEvents { response_tx } => {
                let events = radix_tree.dump_tree_as_events();
                let _ = response_tx.send(events);
            }
            RadixTreeRequest::Shutdown => {
                // This is handled in the main loop
            }
        }
Yan Ru Pei's avatar
Yan Ru Pei committed
669
    }
670
}
Yan Ru Pei's avatar
Yan Ru Pei committed
671

672
673
674
675
676
// Cleanup when RadixTree is dropped
impl Drop for RadixTree {
    fn drop(&mut self) {
        // Only need graceful shutdown via RadixTreeRequest::Shutdown
        let _ = self.request_tx.send(RadixTreeRequest::Shutdown);
Yan Ru Pei's avatar
Yan Ru Pei committed
677
678
679
    }
}

680
/// Helper function to create a KV router from an endpoint using the ModelManager
681
682
683
684
685
/// to ensure proper etcd registration.
/// Infers worker type using endpoint naming and router config:
/// - If endpoint name/component contains "prefill", treat as prefill
/// - If router_track_active_blocks is disabled, treat as prefill
/// - Otherwise, default to decode
686
687
688
689
690
async fn create_kv_router_from_endpoint(
    endpoint: &Endpoint,
    block_size: usize,
    kv_router_config: Option<llm_rs::kv_router::KvRouterConfig>,
) -> Result<Arc<llm_rs::kv_router::KvRouter>, PyErr> {
691
    // Create ModelManager and use it to create KvRouter (ensures registration)
692
    let model_manager = Arc::new(llm_rs::discovery::ModelManager::new());
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
    let endpoint_id = endpoint.inner.id();
    let namespace = endpoint_id.namespace.to_lowercase();
    let component = endpoint_id.component.to_lowercase();
    let name = endpoint_id.name.to_lowercase();
    let endpoint_is_prefill =
        namespace.contains("prefill") || component.contains("prefill") || name.contains("prefill");
    let track_active_blocks = kv_router_config
        .as_ref()
        .map(|cfg| cfg.router_track_active_blocks)
        .unwrap_or(true);
    let worker_type = if endpoint_is_prefill || !track_active_blocks {
        llm_rs::discovery::WORKER_TYPE_PREFILL
    } else {
        llm_rs::discovery::WORKER_TYPE_DECODE
    };
708
    let kv_router = model_manager
709
710
711
712
713
714
        .kv_chooser_for(
            &endpoint.inner,
            block_size as u32,
            kv_router_config,
            worker_type,
        )
715
716
717
718
719
720
        .await
        .map_err(to_pyerr)?;

    Ok(kv_router)
}

721
722
723
#[pyclass]
pub(crate) struct KvPushRouter {
    inner: Arc<llm_rs::kv_router::KvPushRouter>,
Yan Ru Pei's avatar
Yan Ru Pei committed
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
/// Inject worker_id info from tracker into response's disaggregated_params.
/// This is needed for Python bindings to expose worker routing info since
/// the raw LLMEngineOutput doesn't go through DeltaGenerator (which adds nvext).
fn inject_worker_id_from_tracker(
    data: &mut llm_rs::protocols::common::llm_backend::LLMEngineOutput,
    tracker: &RequestTracker,
) {
    let Some(worker_info) = tracker.get_worker_info() else {
        return;
    };

    let worker_id_json =
        serde_json::to_value(&worker_info).expect("WorkerIdInfo serialization should not fail");

    if let Some(obj) = data
        .disaggregated_params
        .as_mut()
        .and_then(|p| p.as_object_mut())
    {
        obj.insert("worker_id".to_string(), worker_id_json);
    } else {
        data.disaggregated_params = Some(json!({"worker_id": worker_id_json}));
    }
}

Yan Ru Pei's avatar
Yan Ru Pei committed
751
752
753
754
755
756
757
// TODO: can this reuse the stream conversion method in Client bindings?
impl KvPushRouter {
    /// Helper method to process a request and create a Python async generator
    fn process_request_to_stream<'p>(
        py: Python<'p>,
        inner: Arc<llm_rs::kv_router::KvPushRouter>,
        request: llm_rs::protocols::common::preprocessor::PreprocessedRequest,
758
        tracker: Option<Arc<RequestTracker>>,
Yan Ru Pei's avatar
Yan Ru Pei committed
759
760
761
762
763
764
765
766
767
    ) -> PyResult<Bound<'p, PyAny>> {
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let single_in = SingleIn::new(request);
            let stream = inner.generate(single_in).await.map_err(to_pyerr)?;
            let (tx, rx) = tokio::sync::mpsc::channel(100);

            // Spawn a task to process the stream
            tokio::spawn(async move {
                let mut stream = stream;
768
                let mut first_item = true;
769
                let mut first_token_gauges_observed = false;
770
771
772
773
774
775
776
777
778
779

                while let Some(mut response) = stream.next().await {
                    // Inject worker_id into first response if tracker is available
                    if first_item {
                        first_item = false;
                        if let (Some(tracker), Some(data)) = (&tracker, &mut response.data) {
                            inject_worker_id_from_tracker(data, tracker);
                        }
                    }

780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
                    // Observe per-worker TTFT/ISL gauges on first response with actual tokens
                    if !first_token_gauges_observed {
                        let has_tokens = response
                            .data
                            .as_ref()
                            .map(|d| !d.token_ids.is_empty())
                            .unwrap_or(false);
                        if has_tokens {
                            if let Some(ref tracker) = tracker {
                                tracker.observe_first_token_gauges();
                            }
                            first_token_gauges_observed = true;
                        }
                    }

Yan Ru Pei's avatar
Yan Ru Pei committed
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
                    // Convert LLMEngineOutput to PyObject
                    let py_response = Python::with_gil(|py| {
                        pythonize(py, &response.data)
                            .map(|obj| obj.unbind())
                            .map_err(|e| e.to_string())
                    });

                    match py_response {
                        Ok(obj) => {
                            if tx.send(obj).await.is_err() {
                                break; // Receiver dropped
                            }
                        }
                        Err(e) => {
                            tracing::error!("Failed to pythonize response: {}", e);
                            break;
                        }
                    }
                }
814
815
816
817
818

                // Observe per-worker ITL gauge at stream end
                if let Some(ref tracker) = tracker {
                    tracker.observe_finish_gauges();
                }
Yan Ru Pei's avatar
Yan Ru Pei committed
819
820
821
822
823
824
825
826
            });

            // Return a Python async generator wrapper
            Ok(KvPushRouterStream {
                rx: Arc::new(tokio::sync::Mutex::new(rx)),
            })
        })
    }
827
828
829
830
}

#[pymethods]
impl KvPushRouter {
831
832
833
834
835
836
837
838
839
    /// Create a new KvPushRouter for KV-aware routing to workers.
    ///
    /// # Arguments
    /// * `endpoint` - The endpoint to route requests to
    /// * `block_size` - KV cache block size for routing decisions
    /// * `kv_router_config` - Configuration for the KV router
    ///
    /// Note: Worker type for Prometheus metrics is inferred from the endpoint name/component
    /// (contains "prefill") or by `router_track_active_blocks` being disabled.
840
    #[new]
841
    #[pyo3(signature = (endpoint, block_size, kv_router_config))]
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
    fn new(
        endpoint: &Endpoint,
        block_size: usize,
        kv_router_config: &super::entrypoint::KvRouterConfig,
    ) -> PyResult<Self> {
        let runtime = pyo3_async_runtimes::tokio::get_runtime();
        runtime.block_on(async move {
            let client = endpoint.inner.client().await.map_err(to_pyerr)?;

            // Create PushRouter with KV router mode
            let push_router = rs::pipeline::PushRouter::<
                llm_rs::protocols::common::preprocessor::PreprocessedRequest,
                rs::protocols::annotated::Annotated<
                    llm_rs::protocols::common::llm_backend::LLMEngineOutput,
                >,
            >::from_client(
                client,
                rs::pipeline::network::egress::push_router::RouterMode::KV,
            )
            .await
            .map_err(to_pyerr)?;

864
865
866
867
868
869
870
            // Create KvRouter using helper function (ensures etcd registration)
            let kv_router = create_kv_router_from_endpoint(
                endpoint,
                block_size,
                Some(kv_router_config.inner()),
            )
            .await?;
871

872
873
            // Create KvPushRouter (kv_router is already Arc<KvRouter>)
            let kv_push_router = llm_rs::kv_router::KvPushRouter::new(push_router, kv_router);
874
875
876
877
878
879
880
881

            Ok(Self {
                inner: Arc::new(kv_push_router),
            })
        })
    }

    #[allow(clippy::too_many_arguments)]
Yan Ru Pei's avatar
Yan Ru Pei committed
882
    #[pyo3(signature = (token_ids, model, stop_conditions=None, sampling_options=None, output_options=None, router_config_override=None, worker_id=None, dp_rank=None, extra_args=None))]
883
884
885
886
887
888
889
890
891
    fn generate<'p>(
        &self,
        py: Python<'p>,
        token_ids: Vec<u32>,
        model: String,
        stop_conditions: Option<PyObject>,
        sampling_options: Option<PyObject>,
        output_options: Option<PyObject>,
        router_config_override: Option<PyObject>,
Yan Ru Pei's avatar
Yan Ru Pei committed
892
893
        worker_id: Option<WorkerId>,
        dp_rank: Option<DpRank>,
894
        extra_args: Option<PyObject>,
895
896
    ) -> PyResult<Bound<'p, PyAny>> {
        // Depythonize the options with defaults
897
898
899
900
901
        let stop_conditions: StopConditions = if let Some(obj) = stop_conditions {
            depythonize(obj.bind(py)).map_err(to_pyerr)?
        } else {
            StopConditions::default()
        };
902

903
904
905
906
907
        let sampling_options: SamplingOptions = if let Some(obj) = sampling_options {
            depythonize(obj.bind(py)).map_err(to_pyerr)?
        } else {
            SamplingOptions::default()
        };
908

909
910
911
912
913
        let output_options: OutputOptions = if let Some(obj) = output_options {
            depythonize(obj.bind(py)).map_err(to_pyerr)?
        } else {
            OutputOptions::default()
        };
914

915
916
917
918
919
920
        let router_config_override: Option<llm_rs::kv_router::RouterConfigOverride> =
            if let Some(obj) = router_config_override {
                Some(depythonize(obj.bind(py)).map_err(to_pyerr)?)
            } else {
                None
            };
921

922
923
924
925
926
        let extra_args: Option<serde_json::Value> = if let Some(obj) = extra_args {
            Some(depythonize(obj.bind(py)).map_err(to_pyerr)?)
        } else {
            None
        };
927

928
929
930
        // Create tracker to capture worker routing info from KvRouter
        let tracker = Arc::new(RequestTracker::new());

931
        // Build the PreprocessedRequest
932
933
934
        let mut request_builder =
            llm_rs::protocols::common::preprocessor::PreprocessedRequest::builder();
        request_builder
935
936
937
938
939
            .model(model)
            .token_ids(token_ids)
            .stop_conditions(stop_conditions)
            .sampling_options(sampling_options)
            .output_options(output_options)
940
            .router_config_override(router_config_override)
941
942
            .extra_args(extra_args)
            .tracker(Some(tracker.clone()));
943

944
945
946
947
948
949
950
951
        // Set routing hints if worker_id or dp_rank is provided
        if worker_id.is_some() || dp_rank.is_some() {
            let routing = llm_rs::protocols::common::preprocessor::RoutingHints {
                backend_instance_id: worker_id,
                dp_rank,
                ..Default::default()
            };
            request_builder.routing(Some(routing));
952
953
954
        }

        let request = request_builder.build().map_err(to_pyerr)?;
955

Yan Ru Pei's avatar
Yan Ru Pei committed
956
        // Use the helper method to process the request
957
        Self::process_request_to_stream(py, self.inner.clone(), request, Some(tracker))
Yan Ru Pei's avatar
Yan Ru Pei committed
958
    }
959

Yan Ru Pei's avatar
Yan Ru Pei committed
960
961
962
963
964
965
    fn generate_from_request<'p>(
        &self,
        py: Python<'p>,
        request: PyObject,
    ) -> PyResult<Bound<'p, PyAny>> {
        // Depythonize the request directly into PreprocessedRequest
966
        let mut request: llm_rs::protocols::common::preprocessor::PreprocessedRequest =
967
            depythonize(request.bind(py)).map_err(to_pyerr)?;
968

969
970
971
972
973
974
975
976
977
978
        // Create tracker if not already set, to capture worker routing info
        let tracker = match request.tracker {
            Some(ref t) => t.clone(),
            None => {
                let t = Arc::new(RequestTracker::new());
                request.tracker = Some(t.clone());
                t
            }
        };

Yan Ru Pei's avatar
Yan Ru Pei committed
979
        // Use the helper method to process the request
980
        Self::process_request_to_stream(py, self.inner.clone(), request, Some(tracker))
981
    }
982

Yan Ru Pei's avatar
Yan Ru Pei committed
983
984
985
986
987
988
989
990
991
    #[pyo3(signature = (token_ids, router_config_override=None, request_id=None))]
    fn best_worker<'p>(
        &self,
        py: Python<'p>,
        token_ids: Vec<u32>,
        router_config_override: Option<PyObject>,
        request_id: Option<String>,
    ) -> PyResult<Bound<'p, PyAny>> {
        let router_config_override = if let Some(obj) = router_config_override {
992
993
994
            let override_config: llm_rs::kv_router::RouterConfigOverride =
                depythonize(obj.bind(py)).map_err(to_pyerr)?;
            Some(override_config)
Yan Ru Pei's avatar
Yan Ru Pei committed
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
        } else {
            None
        };

        let chooser = self.inner.chooser.clone();
        let update_states = request_id.is_some();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let (best_worker, overlap_blocks) = chooser
                .find_best_match(
                    request_id.as_deref(),
                    &token_ids,
                    router_config_override.as_ref(),
                    update_states,
1009
                    None, // lora_name not exposed in Python API yet
1010
                    0.0,
Yan Ru Pei's avatar
Yan Ru Pei committed
1011
1012
1013
1014
1015
1016
1017
1018
                )
                .await
                .map_err(to_pyerr)?;

            Ok((best_worker.worker_id, best_worker.dp_rank, overlap_blocks))
        })
    }

1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
    /// Mark prefill as completed for a request
    fn mark_prefill_complete<'p>(
        &self,
        py: Python<'p>,
        request_id: String,
    ) -> PyResult<Bound<'p, PyAny>> {
        let chooser = self.inner.chooser.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            chooser
                .mark_prefill_completed(&request_id)
                .await
                .map_err(to_pyerr)?;
            Ok(())
        })
    }

    /// Free a request by its ID, signaling the router to release resources
    fn free<'p>(&self, py: Python<'p>, request_id: String) -> PyResult<Bound<'p, PyAny>> {
        let chooser = self.inner.chooser.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            chooser.free(&request_id).await.map_err(to_pyerr)?;
            Ok(())
        })
    }

1046
1047
1048
1049
1050
    fn get_potential_loads<'p>(
        &self,
        py: Python<'p>,
        token_ids: Vec<u32>,
    ) -> PyResult<Bound<'p, PyAny>> {
1051
        let chooser = self.inner.chooser.clone();
1052
1053

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
1054
            let loads = chooser
1055
                .get_potential_loads(&token_ids, None)
1056
1057
1058
                .await
                .map_err(to_pyerr)?;

Yan Ru Pei's avatar
Yan Ru Pei committed
1059
            // Return loads without aggregation - each (worker_id, dp_rank) pair is a separate entry
1060
1061
1062
1063
1064
1065
1066
1067
1068
            // Use pythonize to convert Vec<PotentialLoad> to Python list of dicts
            Python::with_gil(|py| {
                pythonize(py, &loads)
                    .map(|obj| obj.unbind())
                    .map_err(to_pyerr)
            })
        })
    }

1069
1070
    /// Dump all events from the KV router's indexer as a JSON string
    fn dump_events<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> {
1071
        let chooser = self.inner.chooser.clone();
1072
1073

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
1074
            let events = chooser.dump_events().await.map_err(to_pyerr)?;
1075
1076
1077
1078
1079
1080
1081
            // Serialize to JSON string
            let json_str = serde_json::to_string(&events).map_err(to_pyerr)?;
            Ok(json_str)
        })
    }
}

1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
// Python async generator wrapper for the stream
#[pyclass]
pub(crate) struct KvPushRouterStream {
    rx: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<PyObject>>>,
}

#[pymethods]
impl KvPushRouterStream {
    #[pyo3(name = "__aiter__")]
    fn aiter(slf: Bound<'_, Self>) -> PyResult<Py<PyAny>> {
        Ok(slf.clone().into_any().unbind())
    }

    #[pyo3(name = "__anext__")]
    fn anext<'p>(&self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> {
        let rx = self.rx.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let mut rx = rx.lock().await;
            match rx.recv().await {
                Some(obj) => Ok(obj),
                None => Err(pyo3::exceptions::PyStopAsyncIteration::new_err(
                    "Stream exhausted",
                )),
            }
        })
    }
}