kv.rs 42.2 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::ffi::OsString;
7
use std::sync::Arc;
8
use std::sync::atomic::AtomicU32;
9
use std::sync::mpsc;
10
use tokio_stream::StreamExt;
11

12
use super::*;
13
use crate::Endpoint;
14
15
#[cfg(feature = "kv-indexer")]
use clap::Parser;
16
17
18
use dynamo_kv_router::config::{KvRouterConfig, RouterConfigOverride};
use dynamo_kv_router::protocols::compute_block_hash_for_seq;
use dynamo_kv_router::protocols::*;
19
20
21
22
#[cfg(feature = "kv-indexer-runtime")]
use dynamo_kv_router::standalone_indexer::RuntimeConfig;
#[cfg(feature = "kv-indexer")]
use dynamo_kv_router::standalone_indexer::{self, IndexerConfig};
Yan Ru Pei's avatar
Yan Ru Pei committed
23
use rs::pipeline::{AsyncEngine, SingleIn};
24
use rs::protocols::annotated::Annotated as RsAnnotated;
25
use tracing;
26

27
use llm_rs::kv_router::KvPushRouter as RsKvPushRouter;
28
use llm_rs::kv_router::publisher::{KvEventSourceConfig, create_stored_blocks};
29
use llm_rs::protocols::common::timing::RequestTracker;
30
use llm_rs::protocols::common::{OutputOptions, SamplingOptions, StopConditions};
31
use serde_json::json;
32

33
34
35
use super::aic_callback::create_aic_prefill_load_estimator;
use super::entrypoint::AicPerfConfig;

36
37
38
39
fn depythonize_block_mm_infos(obj: &Bound<'_, PyAny>) -> PyResult<Vec<Option<BlockExtraInfo>>> {
    depythonize(obj).map_err(to_pyerr)
}

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#[cfg(feature = "kv-indexer")]
#[derive(Parser)]
#[command(
    name = "python -m dynamo.indexer",
    about = "Standalone KV cache indexer"
)]
struct KvIndexerCli {
    /// KV cache block size for initial workers registered via --workers
    #[arg(long)]
    block_size: Option<u32>,

    /// HTTP server port
    #[arg(long, default_value_t = 8090)]
    port: u16,

    /// Number of indexer threads (1 = single-threaded KvIndexer, >1 = ThreadPoolIndexer)
    #[arg(long, default_value_t = 4)]
    threads: usize,

    /// Initial workers as "worker_id[:dp_rank]=zmq_address,..." (e.g. "1=tcp://host:5557,1:1=tcp://host:5558")
    #[arg(long)]
    workers: Option<String>,

    /// Model name for initial workers registered via --workers
    #[arg(long, default_value = "default")]
    model_name: String,

    /// Tenant ID for initial workers registered via --workers
    #[arg(long, default_value = "default")]
    tenant_id: String,

    /// Comma-separated peer URLs for P2P recovery (e.g. "http://host1:8090,http://host2:8091")
    #[arg(long)]
    peers: Option<String>,

    /// Enable Dynamo runtime integration (discovery, event plane, request plane).
    #[cfg(feature = "kv-indexer-runtime")]
    #[arg(long)]
    dynamo_runtime: bool,

    /// Dynamo namespace to register the indexer component under.
    #[cfg(feature = "kv-indexer-runtime")]
    #[arg(long, default_value = "default")]
    namespace: String,

    /// Component name for this indexer in the Dynamo runtime.
    #[cfg(feature = "kv-indexer-runtime")]
    #[arg(long, default_value = "kv-indexer")]
    component_name: String,

    /// Component name that workers register under.
    #[cfg(feature = "kv-indexer-runtime")]
    #[arg(long, default_value = "backend")]
    worker_component: String,
}

pub fn run_kv_indexer_cli<I, T>(args: I) -> anyhow::Result<()>
where
    I: IntoIterator<Item = T>,
    T: Into<OsString>,
{
    #[cfg(feature = "kv-indexer")]
    {
        let cli = KvIndexerCli::try_parse_from(
            std::iter::once(OsString::from("python -m dynamo.indexer"))
                .chain(args.into_iter().map(Into::into)),
        )?;

        #[cfg(feature = "kv-indexer-runtime")]
        if cli.dynamo_runtime {
            dynamo_runtime::logging::init();
            let worker = dynamo_runtime::Worker::from_settings()?;
            return worker.execute(move |runtime| {
                standalone_indexer::run_with_runtime(
                    runtime,
                    IndexerConfig {
                        block_size: cli.block_size,
                        port: cli.port,
                        threads: cli.threads,
                        workers: cli.workers,
                        model_name: cli.model_name,
                        tenant_id: cli.tenant_id,
                        peers: cli.peers,
                    },
                    RuntimeConfig {
                        namespace: cli.namespace,
                        component_name: cli.component_name,
                        worker_component: cli.worker_component,
                    },
                )
            });
        }

        init_standalone_logging();

        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(standalone_indexer::run_server(IndexerConfig {
            block_size: cli.block_size,
            port: cli.port,
            threads: cli.threads,
            workers: cli.workers,
            model_name: cli.model_name,
            tenant_id: cli.tenant_id,
            peers: cli.peers,
        }))
    }

    #[cfg(not(feature = "kv-indexer"))]
    {
        let _ = args;
        anyhow::bail!(
            "dynamo.indexer is not available in this build; reinstall with --features kv-indexer"
        )
    }
}

#[cfg(feature = "kv-indexer")]
fn init_standalone_logging() {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .try_init();
}

Yan Ru Pei's avatar
Yan Ru Pei committed
166
#[pyfunction]
167
#[pyo3(name = "compute_block_hash_for_seq", signature = (tokens, kv_block_size, block_mm_infos=None, lora_name=None, is_eagle=None))]
168
169
170
171
172
pub fn compute_block_hash_for_seq_py(
    _py: Python,
    tokens: Vec<u32>,
    kv_block_size: usize,
    block_mm_infos: Option<Bound<PyAny>>,
173
    lora_name: Option<String>,
174
    is_eagle: Option<bool>,
175
) -> PyResult<Vec<u64>> {
Yan Ru Pei's avatar
Yan Ru Pei committed
176
    if kv_block_size == 0 {
177
178
179
        return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
            "kv_block_size cannot be 0",
        ));
Yan Ru Pei's avatar
Yan Ru Pei committed
180
181
    }

182
    let mm_infos = block_mm_infos
183
        .as_ref()
184
        .map(depythonize_block_mm_infos)
185
186
        .transpose()?;

187
188
189
    let hashes = compute_block_hash_for_seq(
        &tokens,
        kv_block_size as u32,
190
191
192
193
194
        BlockHashOptions {
            block_mm_infos: mm_infos.as_deref(),
            lora_name: lora_name.as_deref(),
            is_eagle,
        },
195
    );
196

Yan Ru Pei's avatar
Yan Ru Pei committed
197
198
199
    Ok(hashes.into_iter().map(|h| h.0).collect())
}

GuanLuo's avatar
GuanLuo committed
200
#[pyclass]
201
202
pub(crate) struct WorkerMetricsPublisher {
    inner: Arc<llm_rs::kv_router::publisher::WorkerMetricsPublisher>,
GuanLuo's avatar
GuanLuo committed
203
204
205
}

#[pymethods]
206
impl WorkerMetricsPublisher {
GuanLuo's avatar
GuanLuo committed
207
208
    #[new]
    fn new() -> PyResult<Self> {
209
210
        let inner =
            llm_rs::kv_router::publisher::WorkerMetricsPublisher::new().map_err(to_pyerr)?;
GuanLuo's avatar
GuanLuo committed
211
212
213
214
215
        Ok(Self {
            inner: inner.into(),
        })
    }

216
    #[pyo3(signature = (endpoint))]
Alec's avatar
Alec committed
217
    fn create_endpoint<'p>(
GuanLuo's avatar
GuanLuo committed
218
219
        &self,
        py: Python<'p>,
220
        endpoint: Endpoint,
GuanLuo's avatar
GuanLuo committed
221
222
    ) -> PyResult<Bound<'p, PyAny>> {
        let rs_publisher = self.inner.clone();
223
        let rs_component = endpoint.inner.component().clone();
GuanLuo's avatar
GuanLuo committed
224
        pyo3_async_runtimes::tokio::future_into_py(py, async move {
225
            rs_publisher
226
                .create_endpoint(rs_component)
GuanLuo's avatar
GuanLuo committed
227
228
229
230
231
232
                .await
                .map_err(to_pyerr)?;
            Ok(())
        })
    }

233
234
235
236
237
238
239
    /// 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
240
        self.inner
241
            .publish(dp_rank, active_decode_blocks)
GuanLuo's avatar
GuanLuo committed
242
243
244
            .map_err(to_pyerr)
    }
}
245

246
247
248
#[pyclass]
pub(crate) struct KvEventPublisher {
    inner: Arc<llm_rs::kv_router::publisher::KvEventPublisher>,
249
    kv_block_size: usize,
Yan Ru Pei's avatar
Yan Ru Pei committed
250
    dp_rank: DpRank,
251
    warning_count: Arc<AtomicU32>,
252
253
254
255
}

#[pymethods]
impl KvEventPublisher {
256
257
258
259
260
261
262
263
264
265
266
267
    /// Create a KV event publisher that batches raw engine events before forwarding
    /// them to NATS / the event plane.
    ///
    /// Args:
    ///     endpoint: The Dynamo component endpoint for this worker.
    ///     worker_id: Identifier of this worker (default 0).
    ///     kv_block_size: KV cache block size in tokens; must be > 0.
    ///     dp_rank: Data-parallel rank of this worker (default 0).
    ///     enable_local_indexer: When True, a local KV indexer is kept in-process
    ///         so that routers can recover events directly from this worker.
    ///     zmq_endpoint: Optional ZMQ SUB endpoint to read raw engine events from.
    ///     zmq_topic: ZMQ topic filter (default "").
268
    ///     batching_timeout_ms: Maximum time (in **milliseconds**) to accumulate
269
    ///         events into a single batch before flushing.
270
271
272
273
    ///         ``None`` disables batching: every event is published immediately.
    ///         ``50`` to enable batching with a 50 ms window.
    ///         ``0`` is treated as ``None`` (also disables batching).
    ///         Maximum allowed is 15_000 (15 seconds); larger values are capped.
274
    #[new]
275
    #[pyo3(signature = (endpoint, worker_id=0, kv_block_size=0, dp_rank=0, enable_local_indexer=false, zmq_endpoint=None, zmq_topic=None, batching_timeout_ms=llm_rs::kv_router::publisher::DEFAULT_BATCHING_TIMEOUT_MS))]
276
    #[allow(clippy::too_many_arguments)]
277
    fn new(
278
        endpoint: Endpoint,
279
280
281
        worker_id: WorkerId,
        kv_block_size: usize,
        dp_rank: DpRank,
282
        enable_local_indexer: bool,
283
284
        zmq_endpoint: Option<String>,
        zmq_topic: Option<String>,
285
        batching_timeout_ms: Option<u64>,
286
    ) -> PyResult<Self> {
287
288
        let _ = worker_id;

289
290
        let source_config = zmq_endpoint.map(|ep| KvEventSourceConfig::Zmq {
            endpoint: ep,
291
292
            topic: zmq_topic.unwrap_or_default(),
        });
293

Yan Ru Pei's avatar
Yan Ru Pei committed
294
295
296
297
        if kv_block_size == 0 {
            return Err(to_pyerr(anyhow::anyhow!("kv_block_size cannot be 0")));
        }

298
299
300
        // Extract component from endpoint
        let component = endpoint.inner.component().clone();

301
        let inner = llm_rs::kv_router::publisher::KvEventPublisher::new_with_local_indexer(
302
            component,
303
            kv_block_size as u32,
304
            source_config,
305
            enable_local_indexer,
306
            dp_rank,
307
            batching_timeout_ms,
308
309
        )
        .map_err(to_pyerr)?;
310

311
312
        Ok(Self {
            inner: inner.into(),
313
            kv_block_size,
Yan Ru Pei's avatar
Yan Ru Pei committed
314
            dp_rank,
315
            warning_count: Arc::new(AtomicU32::new(0)),
316
317
318
319
        })
    }

    #[allow(clippy::too_many_arguments)]
320
    #[pyo3(signature = (token_ids, num_block_tokens, block_hashes, parent_hash=None, block_mm_infos=None, lora_name=None, is_eagle=None))]
321
    fn publish_stored(
322
        &self,
323
        py: Python,
324
325
        token_ids: Vec<u32>,
        num_block_tokens: Vec<u64>,
326
327
        block_hashes: Vec<i64>,
        parent_hash: Option<i64>,
328
        block_mm_infos: Option<Bound<PyAny>>,
329
        lora_name: Option<String>,
330
        is_eagle: Option<bool>,
331
    ) -> PyResult<()> {
332
333
334
335
336
        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();

337
338
        let event_id = inner.next_event_id();

339
        let mm_infos = block_mm_infos
340
            .as_ref()
341
            .map(depythonize_block_mm_infos)
342
343
            .transpose()?;

344
345
346
347
348
349
350
351
352
353
354
        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,
355
                        lora_name.as_deref(),
356
                        &warning_count,
357
                        mm_infos.as_deref(),
358
                        is_eagle,
359
360
361
362
363
364
365
                    ),
                }),
                dp_rank,
            };

            inner.publish(event).map_err(to_pyerr)
        })
366
367
    }

368
    fn publish_removed(&self, py: Python, block_hashes: Vec<i64>) -> PyResult<()> {
369
370
371
        let dp_rank = self.dp_rank;
        let inner = self.inner.clone();

372
373
374
        // Use shared monotonic event_id counter from the inner publisher
        let event_id = inner.next_event_id();

375
376
377
378
379
380
381
382
383
384
385
386
387
        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)
        })
388
    }
389
390
391
392
393
394
395
396

    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();
        }
    }
397
398
}

399
400
401
#[pyclass]
#[derive(Clone)]
pub(crate) struct OverlapScores {
402
    inner: dynamo_kv_router::protocols::OverlapScores,
403
404
405
406
407
}

#[pymethods]
impl OverlapScores {
    #[getter]
408
    fn scores(&self) -> HashMap<(u64, u32), u32> {
Yan Ru Pei's avatar
Yan Ru Pei committed
409
410
411
412
413
414
        // 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()
415
416
417
418
419
420
421
422
    }

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

423
424
425
#[derive(Debug)]
enum RadixTreeRequest {
    FindMatches {
426
        local_block_hashes: Vec<LocalBlockHash>,
427
        early_exit: bool,
428
        response_tx: mpsc::SyncSender<dynamo_kv_router::protocols::OverlapScores>,
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    },
    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 {
444
        response_tx: mpsc::SyncSender<Vec<RouterEvent>>,
445
446
447
448
449
450
    },
    Shutdown,
}

// NOTE: RadixTree is now thread-safe with pure sync patterns
#[pyclass]
Yan Ru Pei's avatar
Yan Ru Pei committed
451
pub(crate) struct RadixTree {
452
    request_tx: mpsc::Sender<RadixTreeRequest>,
Yan Ru Pei's avatar
Yan Ru Pei committed
453
454
455
456
457
458
459
460
}

#[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);
461
462
463
464
465
466

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

        // Spawn dedicated thread with simplified sync processing
        std::thread::spawn(move || {
            let mut radix_tree =
467
                dynamo_kv_router::indexer::RadixTree::new_with_frequency(expiration_duration);
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486

            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
487
488
489
490
491
    }

    #[pyo3(signature = (sequence, early_exit=false))]
    fn find_matches(
        &self,
492
        py: Python,
Yan Ru Pei's avatar
Yan Ru Pei committed
493
494
495
        sequence: Vec<u64>,
        early_exit: bool,
    ) -> PyResult<OverlapScores> {
496
497
        let (response_tx, response_rx) = mpsc::sync_channel(1);

498
499
        let local_block_hashes =
            py.allow_threads(|| sequence.into_iter().map(LocalBlockHash).collect());
500
501
502
503
504
505

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

507
508
509
510
511
512
513
514
515
516
517
518
519
520
        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
521
522
523
    }

    fn apply_event(
524
525
        &self,
        py: Python,
Yan Ru Pei's avatar
Yan Ru Pei committed
526
        worker_id: WorkerId,
Yan Ru Pei's avatar
Yan Ru Pei committed
527
528
        kv_cache_event_bytes: &[u8],
    ) -> PyResult<()> {
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
        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
594

595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
    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
627
    }
628
}
Yan Ru Pei's avatar
Yan Ru Pei committed
629

630
631
impl RadixTree {
    fn handle_request(
632
        radix_tree: &mut dynamo_kv_router::indexer::RadixTree,
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
        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,
            } => {
649
                let result = match serde_json::from_slice::<KvCacheEvent>(&kv_cache_event_bytes) {
650
                    Ok(kv_cache_event) => {
651
                        let router_event = RouterEvent::new(worker_id, kv_cache_event);
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
                        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
688
    }
689
}
Yan Ru Pei's avatar
Yan Ru Pei committed
690

691
692
693
694
695
// 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
696
697
698
    }
}

699
/// Helper function to create a KV router from an endpoint using the ModelManager
700
701
702
703
704
/// 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
705
706
707
async fn create_kv_router_from_endpoint(
    endpoint: &Endpoint,
    block_size: usize,
708
    kv_router_config: Option<KvRouterConfig>,
709
    prefill_load_estimator: Option<Arc<dyn dynamo_kv_router::PrefillLoadEstimator>>,
710
) -> Result<Arc<llm_rs::kv_router::KvRouter>, PyErr> {
711
    // Create ModelManager and use it to create KvRouter (ensures registration)
712
    let model_manager = Arc::new(llm_rs::discovery::ModelManager::new());
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
    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
    };
728

729
730
    // Query discovery once so we can derive both model_name (for remote indexer)
    // and Eagle routing semantics from the model card.
731
732
733
734
    let needs_model_name = kv_router_config
        .as_ref()
        .map(|cfg| cfg.remote_indexer_component.is_some())
        .unwrap_or(false);
735
    let (model_name, enable_eagle) = {
736
737
738
739
740
741
742
743
744
745
        let discovery = endpoint.inner.component().drt().discovery();
        let instances = discovery
            .list(rs::discovery::DiscoveryQuery::EndpointModels {
                namespace: endpoint_id.namespace.clone(),
                component: endpoint_id.component.clone(),
                endpoint: endpoint_id.name.clone(),
            })
            .await
            .map_err(to_pyerr)?;

746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
        let maybe_card = instances.into_iter().find_map(|inst| {
            inst.deserialize_model::<llm_rs::model_card::ModelDeploymentCard>()
                .ok()
        });

        match maybe_card {
            Some(card) => {
                let model_name = needs_model_name.then(|| card.display_name.clone());
                (model_name, card.runtime_config.enable_eagle)
            }
            None => {
                tracing::warn!(
                    namespace = %endpoint_id.namespace,
                    component = %endpoint_id.component,
                    endpoint = %endpoint_id.name,
                    "No model card found in discovery; defaulting to non-Eagle routing semantics"
                );
                (None, false)
            }
        }
766
767
    };

768
    let kv_router = model_manager
769
770
771
772
        .kv_chooser_for(
            &endpoint.inner,
            block_size as u32,
            kv_router_config,
773
            prefill_load_estimator,
774
            worker_type,
775
            model_name,
776
            enable_eagle,
777
        )
778
779
780
781
782
783
        .await
        .map_err(to_pyerr)?;

    Ok(kv_router)
}

784
#[pyclass]
785
786
pub(crate) struct KvRouter {
    inner: Arc<RsKvPushRouter>,
Yan Ru Pei's avatar
Yan Ru Pei committed
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
/// 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
814
// TODO: can this reuse the stream conversion method in Client bindings?
815
impl KvRouter {
Yan Ru Pei's avatar
Yan Ru Pei committed
816
817
818
    /// Helper method to process a request and create a Python async generator
    fn process_request_to_stream<'p>(
        py: Python<'p>,
819
        inner: Arc<RsKvPushRouter>,
Yan Ru Pei's avatar
Yan Ru Pei committed
820
        request: llm_rs::protocols::common::preprocessor::PreprocessedRequest,
821
        tracker: Option<Arc<RequestTracker>>,
Yan Ru Pei's avatar
Yan Ru Pei committed
822
823
824
825
    ) -> 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)?;
826
            let (tx, rx) = tokio::sync::mpsc::channel::<RsAnnotated<PyObject>>(100);
Yan Ru Pei's avatar
Yan Ru Pei committed
827
828
829

            tokio::spawn(async move {
                let mut stream = stream;
830
                let mut first_item = true;
831
                let mut first_token_gauges_observed = false;
832
833
834
835
836
837
838
839
840

                while let Some(mut response) = stream.next().await {
                    if first_item {
                        first_item = false;
                        if let (Some(tracker), Some(data)) = (&tracker, &mut response.data) {
                            inject_worker_id_from_tracker(data, tracker);
                        }
                    }

841
842
843
844
845
846
847
848
849
850
851
852
853
854
                    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
855
856
857
858
859
860
861
862
                    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) => {
863
864
                            if tx.send(RsAnnotated::from_data(obj)).await.is_err() {
                                break;
Yan Ru Pei's avatar
Yan Ru Pei committed
865
866
867
868
869
870
871
872
                            }
                        }
                        Err(e) => {
                            tracing::error!("Failed to pythonize response: {}", e);
                            break;
                        }
                    }
                }
873
874
875
876

                if let Some(ref tracker) = tracker {
                    tracker.observe_finish_gauges();
                }
Yan Ru Pei's avatar
Yan Ru Pei committed
877
878
            });

879
            Ok(crate::AsyncResponseStream::new(rx, false))
Yan Ru Pei's avatar
Yan Ru Pei committed
880
881
        })
    }
882
883
884
}

#[pymethods]
885
886
impl KvRouter {
    /// Create a new KvRouter for KV-aware routing to workers.
887
888
889
890
891
892
893
894
    ///
    /// # 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.
895
    #[new]
896
    #[pyo3(signature = (endpoint, block_size, kv_router_config, aic_perf_config=None))]
897
898
899
900
    fn new(
        endpoint: &Endpoint,
        block_size: usize,
        kv_router_config: &super::entrypoint::KvRouterConfig,
901
        aic_perf_config: Option<&AicPerfConfig>,
902
    ) -> PyResult<Self> {
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
        let prefill_load_estimator = aic_perf_config
            .map(|config| {
                Python::with_gil(|py| {
                    create_aic_prefill_load_estimator(
                        py,
                        config.backend_name(),
                        config.system(),
                        config.model_path(),
                        config.tp_size(),
                        config.backend_version(),
                    )
                })
            })
            .transpose()
            .map_err(to_pyerr)?;

919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
        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)?;

936
937
938
939
940
            // Create KvRouter using helper function (ensures etcd registration)
            let kv_router = create_kv_router_from_endpoint(
                endpoint,
                block_size,
                Some(kv_router_config.inner()),
941
                prefill_load_estimator,
942
943
            )
            .await?;
944

945
            let kv_push_router = RsKvPushRouter::new(push_router, kv_router);
946
947
948
949
950
951
952
953

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

    #[allow(clippy::too_many_arguments)]
954
    #[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, block_mm_infos=None, multi_modal_data=None, mm_routing_info=None))]
955
956
957
958
959
960
961
962
963
    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
964
965
        worker_id: Option<WorkerId>,
        dp_rank: Option<DpRank>,
966
        extra_args: Option<PyObject>,
967
968
969
        block_mm_infos: Option<PyObject>,
        multi_modal_data: Option<PyObject>,
        mm_routing_info: Option<PyObject>,
970
971
    ) -> PyResult<Bound<'p, PyAny>> {
        // Depythonize the options with defaults
972
973
974
975
976
        let stop_conditions: StopConditions = if let Some(obj) = stop_conditions {
            depythonize(obj.bind(py)).map_err(to_pyerr)?
        } else {
            StopConditions::default()
        };
977

978
979
980
981
982
        let sampling_options: SamplingOptions = if let Some(obj) = sampling_options {
            depythonize(obj.bind(py)).map_err(to_pyerr)?
        } else {
            SamplingOptions::default()
        };
983

984
985
986
987
988
        let output_options: OutputOptions = if let Some(obj) = output_options {
            depythonize(obj.bind(py)).map_err(to_pyerr)?
        } else {
            OutputOptions::default()
        };
989

990
        let router_config_override: Option<RouterConfigOverride> =
991
992
993
994
995
            if let Some(obj) = router_config_override {
                Some(depythonize(obj.bind(py)).map_err(to_pyerr)?)
            } else {
                None
            };
996

997
998
999
1000
1001
        let extra_args: Option<serde_json::Value> = if let Some(obj) = extra_args {
            Some(depythonize(obj.bind(py)).map_err(to_pyerr)?)
        } else {
            None
        };
1002

1003
1004
1005
        let block_mm_infos = block_mm_infos
            .map(|obj| depythonize_block_mm_infos(obj.bind(py)))
            .transpose()?;
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025

        let multi_modal_data: Option<llm_rs::protocols::common::preprocessor::MultimodalDataMap> =
            if let Some(obj) = multi_modal_data {
                Some(depythonize(obj.bind(py)).map_err(to_pyerr)?)
            } else {
                None
            };

        let mm_routing_info: Option<llm_rs::protocols::common::preprocessor::MmRoutingInfo> =
            if let Some(obj) = mm_routing_info {
                Some(depythonize(obj.bind(py)).map_err(to_pyerr)?)
            } else {
                block_mm_infos.map(
                    |infos| llm_rs::protocols::common::preprocessor::MmRoutingInfo {
                        routing_token_ids: token_ids.clone(),
                        block_mm_infos: infos,
                    },
                )
            };

1026
1027
1028
        // Create tracker to capture worker routing info from KvRouter
        let tracker = Arc::new(RequestTracker::new());

1029
        // Build the PreprocessedRequest
1030
1031
1032
        let mut request_builder =
            llm_rs::protocols::common::preprocessor::PreprocessedRequest::builder();
        request_builder
1033
1034
1035
1036
1037
            .model(model)
            .token_ids(token_ids)
            .stop_conditions(stop_conditions)
            .sampling_options(sampling_options)
            .output_options(output_options)
1038
            .router_config_override(router_config_override)
1039
1040
            .multi_modal_data(multi_modal_data)
            .mm_routing_info(mm_routing_info)
1041
1042
            .extra_args(extra_args)
            .tracker(Some(tracker.clone()));
1043

1044
1045
1046
1047
1048
1049
1050
1051
        // 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));
1052
1053
1054
        }

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

Yan Ru Pei's avatar
Yan Ru Pei committed
1056
        // Use the helper method to process the request
1057
        Self::process_request_to_stream(py, self.inner.clone(), request, Some(tracker))
Yan Ru Pei's avatar
Yan Ru Pei committed
1058
    }
1059

Yan Ru Pei's avatar
Yan Ru Pei committed
1060
1061
1062
1063
1064
1065
    fn generate_from_request<'p>(
        &self,
        py: Python<'p>,
        request: PyObject,
    ) -> PyResult<Bound<'p, PyAny>> {
        // Depythonize the request directly into PreprocessedRequest
1066
        let mut request: llm_rs::protocols::common::preprocessor::PreprocessedRequest =
1067
            depythonize(request.bind(py)).map_err(to_pyerr)?;
1068

1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
        // 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
1079
        // Use the helper method to process the request
1080
        Self::process_request_to_stream(py, self.inner.clone(), request, Some(tracker))
1081
    }
1082

1083
1084
    #[allow(clippy::too_many_arguments)]
    #[pyo3(signature = (token_ids, router_config_override=None, request_id=None, update_indexer=false, block_mm_infos=None, lora_name=None))]
Yan Ru Pei's avatar
Yan Ru Pei committed
1085
1086
1087
1088
1089
1090
    fn best_worker<'p>(
        &self,
        py: Python<'p>,
        token_ids: Vec<u32>,
        router_config_override: Option<PyObject>,
        request_id: Option<String>,
1091
        update_indexer: bool,
1092
        block_mm_infos: Option<PyObject>,
1093
        lora_name: Option<String>,
Yan Ru Pei's avatar
Yan Ru Pei committed
1094
1095
    ) -> PyResult<Bound<'p, PyAny>> {
        let router_config_override = if let Some(obj) = router_config_override {
1096
            let override_config: RouterConfigOverride =
1097
1098
                depythonize(obj.bind(py)).map_err(to_pyerr)?;
            Some(override_config)
Yan Ru Pei's avatar
Yan Ru Pei committed
1099
1100
1101
1102
        } else {
            None
        };

1103
1104
1105
        let block_mm_infos = block_mm_infos
            .map(|obj| depythonize_block_mm_infos(obj.bind(py)))
            .transpose()?;
1106

Yan Ru Pei's avatar
Yan Ru Pei committed
1107
1108
1109
1110
1111
1112
1113
1114
        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,
1115
                    block_mm_infos.as_deref(),
Yan Ru Pei's avatar
Yan Ru Pei committed
1116
1117
                    router_config_override.as_ref(),
                    update_states,
1118
                    lora_name.clone(),
1119
                    0.0,
1120
                    None,
1121
                    None, // allowed_worker_ids: pass via RoutingHints in PreprocessedRequest path
Yan Ru Pei's avatar
Yan Ru Pei committed
1122
1123
1124
1125
                )
                .await
                .map_err(to_pyerr)?;

1126
            if update_indexer && !chooser.kv_router_config().use_kv_events {
1127
1128
1129
1130
1131
1132
1133
1134
1135
                let mut tokens_with_hashes =
                    TokensWithHashes::new(token_ids.clone(), chooser.block_size())
                        .with_is_eagle(chooser.is_eagle());
                if let Some(infos) = block_mm_infos.as_ref() {
                    tokens_with_hashes = tokens_with_hashes.with_mm_infos(infos.clone());
                }
                if let Some(lora_name) = lora_name.as_ref() {
                    tokens_with_hashes = tokens_with_hashes.with_lora_name(lora_name.clone());
                }
1136
                chooser
1137
                    .record_routing_decision(tokens_with_hashes, best_worker)
1138
1139
1140
1141
                    .await
                    .map_err(to_pyerr)?;
            }

Yan Ru Pei's avatar
Yan Ru Pei committed
1142
1143
1144
1145
            Ok((best_worker.worker_id, best_worker.dp_rank, overlap_blocks))
        })
    }

1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
    /// 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(())
        })
    }

1173
    #[pyo3(signature = (token_ids, block_mm_infos=None, lora_name=None))]
1174
1175
1176
1177
    fn get_potential_loads<'p>(
        &self,
        py: Python<'p>,
        token_ids: Vec<u32>,
1178
        block_mm_infos: Option<PyObject>,
1179
        lora_name: Option<String>,
1180
    ) -> PyResult<Bound<'p, PyAny>> {
1181
1182
1183
        let block_mm_infos = block_mm_infos
            .map(|obj| depythonize_block_mm_infos(obj.bind(py)))
            .transpose()?;
1184
        let chooser = self.inner.chooser.clone();
1185
1186

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
1187
            let loads = chooser
1188
1189
1190
1191
1192
1193
                .get_potential_loads(
                    &token_ids,
                    None,
                    block_mm_infos.as_deref(),
                    lora_name.as_deref(),
                )
1194
1195
1196
                .await
                .map_err(to_pyerr)?;

Yan Ru Pei's avatar
Yan Ru Pei committed
1197
            // Return loads without aggregation - each (worker_id, dp_rank) pair is a separate entry
1198
1199
1200
1201
1202
1203
1204
1205
1206
            // 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)
            })
        })
    }

1207
1208
    /// 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>> {
1209
        let chooser = self.inner.chooser.clone();
1210
1211

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
1212
            let events = chooser.dump_events().await.map_err(to_pyerr)?;
1213
1214
1215
1216
1217
1218
            // Serialize to JSON string
            let json_str = serde_json::to_string(&events).map_err(to_pyerr)?;
            Ok(json_str)
        })
    }
}