replay.rs 53.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::path::PathBuf;
use std::sync::Arc;

use dynamo_mocker::common::perf_model::PerfModel;
use dynamo_mocker::common::protocols::{
    DirectRequest, EngineType as RsMockerEngineType, MockEngineArgs as RsMockEngineArgs,
    PreemptionMode as RsPreemptionMode, ReasoningConfig as RsReasoningConfig,
    SglangArgs as RsSglangArgs, WorkerType as RsWorkerType,
};
13
14
15
use dynamo_mocker::loadgen::{
    ArrivalSpec, DelaySpec, LengthSpec, SyntheticTraceSpec, Trace as RsTrace,
};
16
use dynamo_mocker::replay::ReplayArgsMode;
17
18
use pyo3::{exceptions::PyException, prelude::*};
use pythonize::pythonize;
19
use serde_json::json;
20
21
use uuid::Uuid;

22
23
use super::aic_callback::{create_aic_callback, create_aic_prefill_load_estimator};
use super::entrypoint::{AicPerfConfig, KvRouterConfig, to_pyerr};
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

fn parse_mocker_engine_type(engine_type: &str) -> PyResult<RsMockerEngineType> {
    match engine_type {
        "vllm" => Ok(RsMockerEngineType::Vllm),
        "sglang" => Ok(RsMockerEngineType::Sglang),
        other => Err(PyException::new_err(format!(
            "engine_type must be either 'vllm' or 'sglang', got '{other}'"
        ))),
    }
}

fn parse_worker_type(worker_type: &str) -> PyResult<RsWorkerType> {
    match worker_type {
        "aggregated" => Ok(RsWorkerType::Aggregated),
        "prefill" => Ok(RsWorkerType::Prefill),
        "decode" => Ok(RsWorkerType::Decode),
        other => Err(PyException::new_err(format!(
            "worker_type must be one of 'aggregated', 'prefill', or 'decode', got '{other}'"
        ))),
    }
}

fn parse_preemption_mode(preemption_mode: &str) -> PyResult<RsPreemptionMode> {
    match preemption_mode {
        "lifo" => Ok(RsPreemptionMode::Lifo),
        "fifo" => Ok(RsPreemptionMode::Fifo),
        other => Err(PyException::new_err(format!(
            "preemption_mode must be either 'lifo' or 'fifo', got '{other}'"
        ))),
    }
}

#[pyclass]
#[derive(Clone, Debug)]
pub struct ReasoningConfig {
    inner: RsReasoningConfig,
}

impl ReasoningConfig {
    pub fn inner(&self) -> RsReasoningConfig {
        self.inner.clone()
    }
}

#[pymethods]
impl ReasoningConfig {
    #[new]
    fn new(
        start_thinking_token_id: u32,
        end_thinking_token_id: u32,
        thinking_ratio: f64,
    ) -> PyResult<Self> {
        let inner = RsReasoningConfig {
            start_thinking_token_id,
            end_thinking_token_id,
            thinking_ratio,
        };
        Ok(Self { inner })
    }
}

#[pyclass]
#[derive(Clone, Debug, Default)]
pub struct SglangArgs {
    inner: RsSglangArgs,
}

impl SglangArgs {
    pub fn inner(&self) -> RsSglangArgs {
        self.inner.clone()
    }
}

#[pymethods]
impl SglangArgs {
    #[new]
    #[pyo3(signature = (schedule_policy=None, page_size=None, max_prefill_tokens=None, chunked_prefill_size=None, clip_max_new_tokens=None, schedule_conservativeness=None))]
    fn new(
        schedule_policy: Option<String>,
        page_size: Option<usize>,
        max_prefill_tokens: Option<usize>,
        chunked_prefill_size: Option<usize>,
        clip_max_new_tokens: Option<usize>,
        schedule_conservativeness: Option<f64>,
    ) -> PyResult<Self> {
        let inner = RsSglangArgs {
            schedule_policy,
            page_size,
            max_prefill_tokens,
            chunked_prefill_size,
            clip_max_new_tokens,
            schedule_conservativeness,
        };
        Ok(Self { inner })
    }
}

#[pyclass]
#[derive(Clone, Debug, Default)]
pub struct MockEngineArgs {
    inner: RsMockEngineArgs,
}

impl MockEngineArgs {
    pub fn inner(&self) -> RsMockEngineArgs {
        self.inner.clone()
    }
}

#[pymethods]
impl MockEngineArgs {
    #[new]
136
    #[pyo3(signature = (engine_type="vllm", num_gpu_blocks=16384, block_size=0, max_num_seqs=Some(256), max_num_batched_tokens=Some(8192), enable_prefix_caching=true, enable_chunked_prefill=true, speedup_ratio=1.0, decode_speedup_ratio=1.0, dp_size=1, startup_time=None, worker_type="aggregated", planner_profile_data=None, aic_backend=None, aic_system=None, aic_backend_version=None, aic_tp_size=None, aic_model_path=None, aic_moe_tp_size=None, aic_moe_ep_size=None, aic_attention_dp_size=None, enable_local_indexer=false, bootstrap_port=None, kv_bytes_per_token=None, kv_transfer_bandwidth=None, reasoning=None, zmq_kv_events_port=None, zmq_replay_port=None, preemption_mode="lifo", router_queue_policy=None, sglang=None))]
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    #[allow(clippy::too_many_arguments)]
    fn new(
        engine_type: &str,
        num_gpu_blocks: usize,
        block_size: usize,
        max_num_seqs: Option<usize>,
        max_num_batched_tokens: Option<usize>,
        enable_prefix_caching: bool,
        enable_chunked_prefill: bool,
        speedup_ratio: f64,
        decode_speedup_ratio: f64,
        dp_size: u32,
        startup_time: Option<f64>,
        worker_type: &str,
151
        planner_profile_data: Option<PathBuf>,
152
153
154
155
156
        aic_backend: Option<String>,
        aic_system: Option<String>,
        aic_backend_version: Option<String>,
        aic_tp_size: Option<usize>,
        aic_model_path: Option<String>,
157
158
159
        aic_moe_tp_size: Option<usize>,
        aic_moe_ep_size: Option<usize>,
        aic_attention_dp_size: Option<usize>,
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
        enable_local_indexer: bool,
        bootstrap_port: Option<u16>,
        kv_bytes_per_token: Option<usize>,
        kv_transfer_bandwidth: Option<f64>,
        reasoning: Option<ReasoningConfig>,
        zmq_kv_events_port: Option<u16>,
        zmq_replay_port: Option<u16>,
        preemption_mode: &str,
        router_queue_policy: Option<&str>,
        sglang: Option<SglangArgs>,
    ) -> PyResult<Self> {
        let engine_type = parse_mocker_engine_type(engine_type)?;
        let worker_type = parse_worker_type(worker_type)?;
        let preemption_mode = parse_preemption_mode(preemption_mode)?;
        let router_queue_policy = router_queue_policy
            .map(|value| {
                value.parse().map_err(|e: String| {
                    PyException::new_err(format!("invalid router_queue_policy {value:?}: {e}"))
                })
            })
            .transpose()?;

182
        let mut builder = RsMockEngineArgs::builder()
183
184
185
186
187
188
189
190
191
192
193
194
            .engine_type(engine_type)
            .num_gpu_blocks(num_gpu_blocks)
            .block_size(block_size)
            .max_num_seqs(max_num_seqs)
            .max_num_batched_tokens(max_num_batched_tokens)
            .enable_prefix_caching(enable_prefix_caching)
            .enable_chunked_prefill(enable_chunked_prefill)
            .speedup_ratio(speedup_ratio)
            .decode_speedup_ratio(decode_speedup_ratio)
            .dp_size(dp_size)
            .startup_time(startup_time)
            .worker_type(worker_type)
195
            .planner_profile_data(planner_profile_data.clone())
196
197
198
199
200
            .aic_backend(aic_backend)
            .aic_system(aic_system)
            .aic_backend_version(aic_backend_version)
            .aic_tp_size(aic_tp_size)
            .aic_model_path(aic_model_path)
201
202
203
            .aic_moe_tp_size(aic_moe_tp_size)
            .aic_moe_ep_size(aic_moe_ep_size)
            .aic_attention_dp_size(aic_attention_dp_size)
204
205
206
207
208
209
210
211
212
            .enable_local_indexer(enable_local_indexer)
            .bootstrap_port(bootstrap_port)
            .kv_bytes_per_token(kv_bytes_per_token)
            .kv_transfer_bandwidth(kv_transfer_bandwidth)
            .reasoning(reasoning.map(|config| config.inner()))
            .zmq_kv_events_port(zmq_kv_events_port)
            .zmq_replay_port(zmq_replay_port)
            .preemption_mode(preemption_mode)
            .router_queue_policy(router_queue_policy)
213
214
215
216
217
218
219
220
221
222
223
224
225
            .sglang(sglang.map(|config| config.inner()));

        if let Some(npz_path) = planner_profile_data {
            let perf_model = PerfModel::from_npz(&npz_path).map_err(|e| {
                PyException::new_err(format!(
                    "Failed to load planner_profile_data from {:?}: {e}",
                    npz_path
                ))
            })?;
            builder = builder.perf_model(Arc::new(perf_model));
        }

        let inner = builder
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
            .build()
            .map_err(|e| PyException::new_err(format!("Failed to build MockEngineArgs: {e}")))?
            .normalized()
            .map_err(|e| {
                PyException::new_err(format!("Failed to normalize MockEngineArgs: {e}"))
            })?;

        Ok(Self { inner })
    }

    #[staticmethod]
    fn from_json(config_json: &str) -> PyResult<Self> {
        RsMockEngineArgs::from_json_str(config_json)
            .map(|inner| Self { inner })
            .map_err(|e| PyException::new_err(format!("Failed to parse MockEngineArgs JSON: {e}")))
    }

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    fn dump_json(&self) -> PyResult<String> {
        let worker_type = match self.inner.worker_type {
            RsWorkerType::Aggregated => "aggregated",
            RsWorkerType::Prefill => "prefill",
            RsWorkerType::Decode => "decode",
        };
        let engine_type = match self.inner.engine_type {
            RsMockerEngineType::Vllm => "vllm",
            RsMockerEngineType::Sglang => "sglang",
        };
        let preemption_mode = match self.inner.preemption_mode {
            RsPreemptionMode::Lifo => "lifo",
            RsPreemptionMode::Fifo => "fifo",
        };
        let router_queue_policy = self
            .inner
            .router_queue_policy
            .as_ref()
            .map(|policy| policy.to_string());
        let payload = json!({
            "engine_type": engine_type,
            "num_gpu_blocks": self.inner.num_gpu_blocks,
            "block_size": self.inner.block_size,
            "max_num_seqs": self.inner.max_num_seqs,
            "max_num_batched_tokens": self.inner.max_num_batched_tokens,
            "enable_prefix_caching": self.inner.enable_prefix_caching,
            "enable_chunked_prefill": self.inner.enable_chunked_prefill,
            "speedup_ratio": self.inner.speedup_ratio,
            "decode_speedup_ratio": self.inner.decode_speedup_ratio,
            "dp_size": self.inner.dp_size,
            "startup_time": self.inner.startup_time,
            "worker_type": worker_type,
            "planner_profile_data": self.inner.planner_profile_data,
            "aic_backend": self.inner.aic_backend,
            "aic_system": self.inner.aic_system,
            "aic_backend_version": self.inner.aic_backend_version,
            "aic_tp_size": self.inner.aic_tp_size,
            "aic_model_path": self.inner.aic_model_path,
281
282
283
            "aic_moe_tp_size": self.inner.aic_moe_tp_size,
            "aic_moe_ep_size": self.inner.aic_moe_ep_size,
            "aic_attention_dp_size": self.inner.aic_attention_dp_size,
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
            "enable_local_indexer": self.inner.enable_local_indexer,
            "bootstrap_port": self.inner.bootstrap_port,
            "kv_bytes_per_token": self.inner.kv_bytes_per_token,
            "kv_transfer_bandwidth": self.inner.kv_transfer_bandwidth,
            "reasoning": self.inner.reasoning,
            "zmq_kv_events_port": self.inner.zmq_kv_events_port,
            "zmq_replay_port": self.inner.zmq_replay_port,
            "preemption_mode": preemption_mode,
            "router_queue_policy": router_queue_policy,
            "sglang": self.inner.sglang,
        });
        serde_json::to_string_pretty(&payload)
            .map_err(|e| PyException::new_err(format!("Failed to serialize MockEngineArgs: {e}")))
    }

299
300
301
302
    fn copy(&self) -> Self {
        self.clone()
    }

303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
    #[getter]
    fn block_size(&self) -> usize {
        self.inner.block_size
    }

    #[getter]
    fn num_gpu_blocks(&self) -> usize {
        self.inner.num_gpu_blocks
    }

    #[getter]
    fn max_num_seqs(&self) -> Option<usize> {
        self.inner.max_num_seqs
    }

    #[getter]
    fn max_num_batched_tokens(&self) -> Option<usize> {
        self.inner.max_num_batched_tokens
    }

323
324
325
326
327
328
329
330
331
332
    #[getter]
    fn enable_prefix_caching(&self) -> bool {
        self.inner.enable_prefix_caching
    }

    #[setter]
    fn set_enable_prefix_caching(&mut self, value: bool) {
        self.inner.enable_prefix_caching = value;
    }

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
    #[getter]
    fn enable_local_indexer(&self) -> bool {
        self.inner.enable_local_indexer
    }

    #[getter]
    fn dp_size(&self) -> u32 {
        self.inner.dp_size
    }

    #[getter]
    fn bootstrap_port(&self) -> Option<u16> {
        self.inner.bootstrap_port
    }

348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
    #[getter]
    fn aic_backend(&self) -> Option<String> {
        self.inner.aic_backend.clone()
    }

    #[setter]
    fn set_aic_backend(&mut self, value: Option<String>) {
        self.inner.aic_backend = value;
    }

    #[getter]
    fn aic_system(&self) -> Option<String> {
        self.inner.aic_system.clone()
    }

    #[setter]
    fn set_aic_system(&mut self, value: Option<String>) {
        self.inner.aic_system = value;
    }

    #[getter]
    fn aic_backend_version(&self) -> Option<String> {
        self.inner.aic_backend_version.clone()
    }

    #[setter]
    fn set_aic_backend_version(&mut self, value: Option<String>) {
        self.inner.aic_backend_version = value;
    }

    #[getter]
    fn aic_tp_size(&self) -> Option<usize> {
        self.inner.aic_tp_size
    }

    #[setter]
    fn set_aic_tp_size(&mut self, value: Option<usize>) {
        self.inner.aic_tp_size = value;
    }

    #[getter]
    fn aic_model_path(&self) -> Option<String> {
        self.inner.aic_model_path.clone()
    }

    #[setter]
    fn set_aic_model_path(&mut self, value: Option<String>) {
        self.inner.aic_model_path = value;
    }

398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
    #[getter]
    fn aic_moe_tp_size(&self) -> Option<usize> {
        self.inner.aic_moe_tp_size
    }

    #[setter]
    fn set_aic_moe_tp_size(&mut self, value: Option<usize>) {
        self.inner.aic_moe_tp_size = value;
    }

    #[getter]
    fn aic_moe_ep_size(&self) -> Option<usize> {
        self.inner.aic_moe_ep_size
    }

    #[setter]
    fn set_aic_moe_ep_size(&mut self, value: Option<usize>) {
        self.inner.aic_moe_ep_size = value;
    }

    #[getter]
    fn aic_attention_dp_size(&self) -> Option<usize> {
        self.inner.aic_attention_dp_size
    }

    #[setter]
    fn set_aic_attention_dp_size(&mut self, value: Option<usize>) {
        self.inner.aic_attention_dp_size = value;
    }

428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
    #[getter]
    fn worker_type(&self) -> &'static str {
        match self.inner.worker_type {
            RsWorkerType::Aggregated => "aggregated",
            RsWorkerType::Prefill => "prefill",
            RsWorkerType::Decode => "decode",
        }
    }

    #[setter]
    fn set_worker_type(&mut self, value: &str) -> PyResult<()> {
        self.inner.worker_type = parse_worker_type(value)?;
        Ok(())
    }

    #[setter]
    fn set_num_gpu_blocks(&mut self, value: usize) {
        self.inner.num_gpu_blocks = value;
    }

448
449
450
451
452
453
454
455
    fn is_prefill(&self) -> bool {
        self.inner.is_prefill()
    }

    fn is_decode(&self) -> bool {
        self.inner.is_decode()
    }

456
    #[allow(clippy::too_many_arguments)]
457
    #[pyo3(signature = (bootstrap_port=None, zmq_kv_events_port=None, zmq_replay_port=None, kv_bytes_per_token=None, num_gpu_blocks=None, aic_backend=None, aic_system=None, aic_backend_version=None, aic_tp_size=None, aic_model_path=None, aic_moe_tp_size=None, aic_moe_ep_size=None, aic_attention_dp_size=None, enable_prefix_caching=None, worker_type=None))]
458
459
460
461
462
463
    fn with_overrides(
        &self,
        bootstrap_port: Option<u16>,
        zmq_kv_events_port: Option<u16>,
        zmq_replay_port: Option<u16>,
        kv_bytes_per_token: Option<usize>,
464
465
466
467
468
469
        num_gpu_blocks: Option<usize>,
        aic_backend: Option<String>,
        aic_system: Option<String>,
        aic_backend_version: Option<String>,
        aic_tp_size: Option<usize>,
        aic_model_path: Option<String>,
470
471
472
        aic_moe_tp_size: Option<usize>,
        aic_moe_ep_size: Option<usize>,
        aic_attention_dp_size: Option<usize>,
473
474
        enable_prefix_caching: Option<bool>,
        worker_type: Option<String>,
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    ) -> PyResult<Self> {
        let mut inner = self.inner.clone();
        if let Some(port) = bootstrap_port {
            inner.bootstrap_port = Some(port);
        }
        if let Some(port) = zmq_kv_events_port {
            inner.zmq_kv_events_port = Some(port);
        }
        if let Some(port) = zmq_replay_port {
            inner.zmq_replay_port = Some(port);
        }
        if let Some(bytes_per_token) = kv_bytes_per_token {
            inner.kv_bytes_per_token = Some(bytes_per_token);
        }
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
        if let Some(blocks) = num_gpu_blocks {
            inner.num_gpu_blocks = blocks;
        }
        if let Some(backend) = aic_backend {
            inner.aic_backend = Some(backend);
        }
        if let Some(system) = aic_system {
            inner.aic_system = Some(system);
        }
        if let Some(version) = aic_backend_version {
            inner.aic_backend_version = Some(version);
        }
        if let Some(tp_size) = aic_tp_size {
            inner.aic_tp_size = Some(tp_size);
        }
        if let Some(model_path) = aic_model_path {
            inner.aic_model_path = Some(model_path);
        }
507
508
509
510
511
512
513
514
515
        if let Some(moe_tp_size) = aic_moe_tp_size {
            inner.aic_moe_tp_size = Some(moe_tp_size);
        }
        if let Some(moe_ep_size) = aic_moe_ep_size {
            inner.aic_moe_ep_size = Some(moe_ep_size);
        }
        if let Some(attention_dp_size) = aic_attention_dp_size {
            inner.aic_attention_dp_size = Some(attention_dp_size);
        }
516
517
518
519
520
521
        if let Some(enable_prefix_caching) = enable_prefix_caching {
            inner.enable_prefix_caching = enable_prefix_caching;
        }
        if let Some(worker_type) = worker_type {
            inner.worker_type = parse_worker_type(&worker_type)?;
        }
522
523
524
525
526
527
528
        inner.normalized().map(|inner| Self { inner }).map_err(|e| {
            PyException::new_err(format!("Failed to normalize MockEngineArgs overrides: {e}"))
        })
    }
}

#[pyfunction]
529
#[pyo3(signature = (trace_file, extra_engine_args=None, prefill_engine_args=None, decode_engine_args=None, router_config=None, aic_perf_config=None, num_workers=1, num_prefill_workers=1, num_decode_workers=1, replay_concurrency=None, replay_mode="offline", router_mode="round_robin", arrival_speedup_ratio=1.0, trace_block_size=512, trace_format="mooncake", trace_shared_prefix_ratio=0.0, trace_num_prefix_groups=0))]
530
531
532
533
534
#[allow(clippy::too_many_arguments)]
pub fn run_mocker_trace_replay(
    py: Python<'_>,
    trace_file: PathBuf,
    extra_engine_args: Option<MockEngineArgs>,
535
536
    prefill_engine_args: Option<MockEngineArgs>,
    decode_engine_args: Option<MockEngineArgs>,
537
    router_config: Option<KvRouterConfig>,
538
    aic_perf_config: Option<&AicPerfConfig>,
539
    num_workers: usize,
540
541
    num_prefill_workers: usize,
    num_decode_workers: usize,
542
543
544
545
    replay_concurrency: Option<isize>,
    replay_mode: &str,
    router_mode: &str,
    arrival_speedup_ratio: f64,
546
    trace_block_size: usize,
547
548
549
    trace_format: &str,
    trace_shared_prefix_ratio: f64,
    trace_num_prefix_groups: usize,
550
) -> PyResult<PyObject> {
551
552
553
554
555
556
557
558
559
    let args_selection = load_replay_args_selection(
        py,
        extra_engine_args,
        prefill_engine_args,
        decode_engine_args,
        num_workers,
        num_prefill_workers,
        num_decode_workers,
    )?;
560
    let router_mode = parse_replay_router_mode(router_mode)?;
561
    let trace_format = parse_trace_file_format(trace_format)?;
562
563
564
565
566
567
    let prefill_load_estimator = load_replay_prefill_load_estimator(
        py,
        router_mode,
        router_config.as_ref(),
        aic_perf_config,
    )?;
568
569
570
571
    let router_config = load_replay_router_config(router_config);
    let replay_mode = replay_mode.to_owned();
    let report = py.allow_threads(move || {
        let replay_concurrency = parse_replay_concurrency(replay_concurrency)?;
572
573
574
575
576
577
578
        if trace_format == dynamo_mocker::loadgen::TraceFileFormat::AppliedComputeAgentic
            && replay_concurrency.is_none()
        {
            anyhow::bail!(
                "trace_format='applied_compute_agentic' requires replay_concurrency because source traces do not contain first-turn timestamps"
            );
        }
579

580
581
582
583
        match args_selection {
            ReplayArgsSelection::Aggregated(args) => {
                match (replay_mode.as_str(), replay_concurrency) {
                    ("offline", Some(max_in_flight)) => {
584
                        dynamo_mocker::replay::simulate_concurrency_file_with_router_mode_and_format(
585
586
                            *args,
                            router_config.clone(),
587
                            prefill_load_estimator.clone(),
588
                            &trace_file,
589
                            trace_block_size,
590
591
592
                            max_in_flight,
                            num_workers,
                            router_mode,
593
594
595
                            trace_format,
                            trace_shared_prefix_ratio,
                            trace_num_prefix_groups,
596
597
598
                        )
                    }
                    ("offline", None) => {
599
                        dynamo_mocker::replay::simulate_trace_file_with_router_mode_and_format(
600
601
                            *args,
                            router_config.clone(),
602
                            prefill_load_estimator.clone(),
603
                            &trace_file,
604
                            trace_block_size,
605
606
607
                            num_workers,
                            arrival_speedup_ratio,
                            router_mode,
608
609
610
                            trace_format,
                            trace_shared_prefix_ratio,
                            trace_num_prefix_groups,
611
612
613
                        )
                    }
                    ("online", Some(max_in_flight)) => {
614
                        dynamo_mocker::replay::simulate_concurrency_live_file_with_router_mode_and_format(
615
616
                            *args,
                            router_config.clone(),
617
                            prefill_load_estimator.clone(),
618
                            &trace_file,
619
                            trace_block_size,
620
621
622
                            max_in_flight,
                            num_workers,
                            router_mode,
623
624
625
                            trace_format,
                            trace_shared_prefix_ratio,
                            trace_num_prefix_groups,
626
627
628
                        )
                    }
                    ("online", None) => {
629
                        dynamo_mocker::replay::simulate_trace_live_file_with_router_mode_and_format(
630
631
                            *args,
                            router_config.clone(),
632
                            prefill_load_estimator.clone(),
633
                            &trace_file,
634
                            trace_block_size,
635
636
637
                            num_workers,
                            arrival_speedup_ratio,
                            router_mode,
638
639
640
                            trace_format,
                            trace_shared_prefix_ratio,
                            trace_num_prefix_groups,
641
642
643
644
645
646
647
                        )
                    }
                    (other, _) => anyhow::bail!(
                        "replay_mode must be either 'offline' or 'online', got '{}'",
                        other
                    ),
                }
648
            }
649
650
651
            ReplayArgsSelection::Disagg(config) => match (replay_mode.as_str(), replay_concurrency)
            {
                ("offline", Some(max_in_flight)) => {
652
                    dynamo_mocker::replay::simulate_concurrency_file_disagg_with_router_mode_and_format(
653
654
                        *config,
                        router_config.clone(),
655
                        prefill_load_estimator.clone(),
656
                        &trace_file,
657
                        trace_block_size,
658
659
                        max_in_flight,
                        router_mode,
660
661
662
                        trace_format,
                        trace_shared_prefix_ratio,
                        trace_num_prefix_groups,
663
664
665
                    )
                }
                ("offline", None) => {
666
                    dynamo_mocker::replay::simulate_trace_file_disagg_with_router_mode_and_format(
667
668
                        *config,
                        router_config.clone(),
669
                        prefill_load_estimator.clone(),
670
                        &trace_file,
671
                        trace_block_size,
672
673
                        arrival_speedup_ratio,
                        router_mode,
674
675
676
                        trace_format,
                        trace_shared_prefix_ratio,
                        trace_num_prefix_groups,
677
678
679
680
681
682
683
684
                    )
                }
                ("online", _) => anyhow::bail!("disagg replay only supports replay_mode='offline'"),
                (other, _) => anyhow::bail!(
                    "replay_mode must be either 'offline' or 'online', got '{}'",
                    other
                ),
            },
685
686
687
688
689
690
691
692
693
        }
    });
    let report = report.map_err(to_pyerr)?;
    pythonize(py, &report)
        .map_err(to_pyerr)
        .map(|obj| obj.unbind())
}

#[pyfunction]
694
#[pyo3(signature = (input_tokens, output_tokens, request_count, extra_engine_args=None, prefill_engine_args=None, decode_engine_args=None, router_config=None, aic_perf_config=None, num_workers=1, num_prefill_workers=1, num_decode_workers=1, replay_concurrency=None, replay_mode="offline", router_mode="round_robin", arrival_speedup_ratio=1.0, arrival_interval_ms=1.0, turns_per_session=1, shared_prefix_ratio=0.0, num_prefix_groups=0, inter_turn_delay_ms=0.0))]
695
696
697
698
699
700
701
#[allow(clippy::too_many_arguments)]
pub fn run_mocker_synthetic_trace_replay(
    py: Python<'_>,
    input_tokens: usize,
    output_tokens: usize,
    request_count: usize,
    extra_engine_args: Option<MockEngineArgs>,
702
703
    prefill_engine_args: Option<MockEngineArgs>,
    decode_engine_args: Option<MockEngineArgs>,
704
    router_config: Option<KvRouterConfig>,
705
    aic_perf_config: Option<&AicPerfConfig>,
706
    num_workers: usize,
707
708
    num_prefill_workers: usize,
    num_decode_workers: usize,
709
710
711
712
713
    replay_concurrency: Option<isize>,
    replay_mode: &str,
    router_mode: &str,
    arrival_speedup_ratio: f64,
    arrival_interval_ms: f64,
714
715
716
717
    turns_per_session: usize,
    shared_prefix_ratio: f64,
    num_prefix_groups: usize,
    inter_turn_delay_ms: f64,
718
) -> PyResult<PyObject> {
719
720
721
722
723
724
725
726
727
    let args_selection = load_replay_args_selection(
        py,
        extra_engine_args,
        prefill_engine_args,
        decode_engine_args,
        num_workers,
        num_prefill_workers,
        num_decode_workers,
    )?;
728
729
730
731
732
733
734
    let router_mode = parse_replay_router_mode(router_mode)?;
    let prefill_load_estimator = load_replay_prefill_load_estimator(
        py,
        router_mode,
        router_config.as_ref(),
        aic_perf_config,
    )?;
735
736
    let router_config = load_replay_router_config(router_config);
    let replay_mode = replay_mode.to_owned();
737
738
739
740
    let block_size = match &args_selection {
        ReplayArgsSelection::Aggregated(args) => args.block_size.max(1),
        ReplayArgsSelection::Disagg(config) => config.prefill_args.block_size.max(1),
    };
741
742
    let report = py.allow_threads(move || {
        let replay_concurrency = parse_replay_concurrency(replay_concurrency)?;
743
744
745
746
747
748
749
        let use_workload = turns_per_session > 1
            || shared_prefix_ratio > 0.0
            || num_prefix_groups > 0
            || inter_turn_delay_ms > 0.0;

        if use_workload {
            let mut trace = build_synthetic_workload(
750
                block_size,
751
752
753
754
755
756
757
758
759
760
761
762
763
                input_tokens,
                output_tokens,
                request_count,
                arrival_interval_ms,
                turns_per_session,
                shared_prefix_ratio,
                num_prefix_groups,
                inter_turn_delay_ms,
            )?;
            if replay_concurrency.is_none() {
                trace = trace.speed_up_timing(arrival_speedup_ratio)?;
            }

764
765
766
767
768
769
770
            return match args_selection {
                ReplayArgsSelection::Aggregated(args) => match (replay_mode.as_str(), replay_concurrency)
                {
                    ("offline", Some(max_in_flight)) => {
                        dynamo_mocker::replay::simulate_concurrency_workload_with_router_mode(
                            *args,
                            router_config.clone(),
771
                            prefill_load_estimator.clone(),
772
773
774
775
776
777
778
779
780
781
                            trace,
                            max_in_flight,
                            num_workers,
                            router_mode,
                        )
                    }
                    ("offline", None) => {
                        dynamo_mocker::replay::simulate_trace_workload_with_router_mode(
                            *args,
                            router_config.clone(),
782
                            prefill_load_estimator.clone(),
783
784
785
786
787
788
789
790
791
                            trace,
                            num_workers,
                            router_mode,
                        )
                    }
                    ("online", Some(max_in_flight)) => {
                        dynamo_mocker::replay::simulate_concurrency_live_workload_with_router_mode(
                            *args,
                            router_config.clone(),
792
                            prefill_load_estimator.clone(),
793
794
795
796
797
798
799
800
801
802
                            trace,
                            max_in_flight,
                            num_workers,
                            router_mode,
                        )
                    }
                    ("online", None) => {
                        dynamo_mocker::replay::simulate_trace_live_workload_with_router_mode(
                            *args,
                            router_config.clone(),
803
                            prefill_load_estimator.clone(),
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
                            trace,
                            num_workers,
                            router_mode,
                        )
                    }
                    (other, _) => anyhow::bail!(
                        "replay_mode must be either 'offline' or 'online', got '{}'",
                        other
                    ),
                },
                ReplayArgsSelection::Disagg(config) => {
                    match (replay_mode.as_str(), replay_concurrency) {
                        ("offline", Some(max_in_flight)) => dynamo_mocker::replay::simulate_concurrency_workload_disagg_with_router_mode(
                            *config,
                            router_config.clone(),
819
                            prefill_load_estimator.clone(),
820
821
822
823
824
825
826
                            trace,
                            max_in_flight,
                            router_mode,
                        ),
                        ("offline", None) => dynamo_mocker::replay::simulate_trace_workload_disagg_with_router_mode(
                            *config,
                            router_config.clone(),
827
                            prefill_load_estimator.clone(),
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
                            trace,
                            router_mode,
                        ),
                        ("online", _) => anyhow::bail!(
                            "disagg replay only supports replay_mode='offline'"
                        ),
                        (other, _) => anyhow::bail!(
                            "replay_mode must be either 'offline' or 'online', got '{}'",
                            other
                        ),
                    }
                }
            };
        }

        let requests = build_synthetic_requests(
            input_tokens,
            output_tokens,
            request_count,
            arrival_interval_ms,
            replay_concurrency.is_none(),
        )?;

        match args_selection {
            ReplayArgsSelection::Aggregated(args) => match (replay_mode.as_str(), replay_concurrency)
            {
854
                ("offline", Some(max_in_flight)) => {
855
856
                    dynamo_mocker::replay::simulate_concurrency_requests_with_router_mode(
                        *args,
857
                        router_config.clone(),
858
                        prefill_load_estimator.clone(),
859
                        requests,
860
861
862
863
864
                        max_in_flight,
                        num_workers,
                        router_mode,
                    )
                }
865
866
867
                ("offline", None) => dynamo_mocker::replay::simulate_trace_requests_with_router_mode(
                    *args,
                    router_config.clone(),
868
                    prefill_load_estimator.clone(),
869
870
871
872
873
874
875
876
                    requests,
                    num_workers,
                    arrival_speedup_ratio,
                    router_mode,
                ),
                ("online", Some(max_in_flight)) => {
                    dynamo_mocker::replay::simulate_concurrency_live_requests_with_router_mode(
                        *args,
877
                        router_config.clone(),
878
                        prefill_load_estimator.clone(),
879
880
                        requests,
                        max_in_flight,
881
882
883
884
                        num_workers,
                        router_mode,
                    )
                }
885
886
887
                ("online", None) => {
                    dynamo_mocker::replay::simulate_trace_live_requests_with_router_mode(
                        *args,
888
                        router_config.clone(),
889
                        prefill_load_estimator.clone(),
890
                        requests,
891
                        num_workers,
892
                        arrival_speedup_ratio,
893
894
895
                        router_mode,
                    )
                }
896
897
898
899
900
901
902
903
904
905
                (other, _) => anyhow::bail!(
                    "replay_mode must be either 'offline' or 'online', got '{}'",
                    other
                ),
            },
            ReplayArgsSelection::Disagg(config) => match (replay_mode.as_str(), replay_concurrency)
            {
                ("offline", Some(max_in_flight)) => {
                    dynamo_mocker::replay::simulate_concurrency_requests_disagg_with_router_mode(
                        *config,
906
                        router_config.clone(),
907
                        prefill_load_estimator.clone(),
908
909
                        requests,
                        max_in_flight,
910
911
912
                        router_mode,
                    )
                }
913
914
915
916
                ("offline", None) => {
                    dynamo_mocker::replay::simulate_trace_requests_disagg_with_router_mode(
                        *config,
                        router_config.clone(),
917
                        prefill_load_estimator.clone(),
918
919
920
921
922
923
                        requests,
                        arrival_speedup_ratio,
                        router_mode,
                    )
                }
                ("online", _) => anyhow::bail!("disagg replay only supports replay_mode='offline'"),
924
925
926
927
                (other, _) => anyhow::bail!(
                    "replay_mode must be either 'offline' or 'online', got '{}'",
                    other
                ),
928
            },
929
930
931
932
933
934
935
936
        }
    });
    let report = report.map_err(to_pyerr)?;
    pythonize(py, &report)
        .map_err(to_pyerr)
        .map(|obj| obj.unbind())
}

937
938
939
940
941
942
enum ReplayArgsSelection {
    Aggregated(Box<RsMockEngineArgs>),
    Disagg(Box<dynamo_mocker::replay::OfflineDisaggReplayConfig>),
}

fn load_replay_args_selection(
943
944
    py: Python<'_>,
    extra_engine_args: Option<MockEngineArgs>,
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
    prefill_engine_args: Option<MockEngineArgs>,
    decode_engine_args: Option<MockEngineArgs>,
    num_workers: usize,
    num_prefill_workers: usize,
    num_decode_workers: usize,
) -> PyResult<ReplayArgsSelection> {
    let aggregated_args = load_optional_replay_mocker_args(py, extra_engine_args)?;
    let prefill_args = load_optional_replay_mocker_args(py, prefill_engine_args)?;
    let decode_args = load_optional_replay_mocker_args(py, decode_engine_args)?;

    let replay_args_mode = dynamo_mocker::replay::validate_replay_args_mode(
        aggregated_args.as_ref(),
        prefill_args.as_ref(),
        decode_args.as_ref(),
        num_workers,
        num_prefill_workers,
        num_decode_workers,
    )
    .map_err(to_pyerr)?;

    match replay_args_mode {
        ReplayArgsMode::Aggregated => Ok(ReplayArgsSelection::Aggregated(Box::new(
            aggregated_args.unwrap_or_default(),
        ))),
        ReplayArgsMode::Disagg => Ok(ReplayArgsSelection::Disagg(Box::new(
            dynamo_mocker::replay::OfflineDisaggReplayConfig {
                prefill_args: prefill_args.expect("validated disagg prefill args"),
                decode_args: decode_args.expect("validated disagg decode args"),
                num_prefill_workers,
                num_decode_workers,
            },
        ))),
    }
}
979

980
981
982
983
984
985
986
987
988
989
990
991
992
fn load_optional_replay_mocker_args(
    py: Python<'_>,
    extra_engine_args: Option<MockEngineArgs>,
) -> PyResult<Option<RsMockEngineArgs>> {
    extra_engine_args
        .map(|extra_args| materialize_replay_mocker_args(py, extra_args.inner()))
        .transpose()
}

fn materialize_replay_mocker_args(
    py: Python<'_>,
    mut args: RsMockEngineArgs,
) -> PyResult<RsMockEngineArgs> {
993
994
995
996
997
998
999
1000
1001
    if let Some(ref backend_name) = args.aic_backend.clone() {
        let backend = backend_name.clone();
        let system = args.aic_system.as_deref().unwrap_or("h200_sxm").to_string();
        let model_name = args
            .aic_model_path
            .clone()
            .ok_or_else(|| PyException::new_err("--aic-perf-model requires --model-path"))?;
        let backend_version = args.aic_backend_version.clone();
        let tp_size = args.aic_tp_size.unwrap_or(1);
1002
1003
1004
        let moe_tp_size = args.aic_moe_tp_size;
        let moe_ep_size = args.aic_moe_ep_size;
        let attention_dp_size = args.aic_attention_dp_size;
1005
1006
1007
1008
1009
1010
1011
        let callback = create_aic_callback(
            py,
            &backend,
            &system,
            &model_name,
            tp_size,
            backend_version.as_deref(),
1012
1013
1014
            moe_tp_size,
            moe_ep_size,
            attention_dp_size,
1015
1016
1017
1018
1019
1020
1021
        )
        .map_err(|e| {
            PyException::new_err(format!(
                "Failed to create AIC callback (--aic-perf-model was requested): {}",
                e
            ))
        })?;
1022
        tracing::debug!(
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
            "AIC perf model: backend={}, gpu={}, model={}, version={:?}",
            backend,
            system,
            model_name,
            backend_version
        );
        args.perf_model = Arc::new(PerfModel::from_aic_callback(callback));
    }

    Ok(args)
}

fn load_replay_router_config(
    router_config: Option<KvRouterConfig>,
) -> Option<dynamo_kv_router::config::KvRouterConfig> {
    router_config.map(|config| config.inner())
}

1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
fn load_replay_prefill_load_estimator(
    py: Python<'_>,
    router_mode: dynamo_mocker::replay::ReplayRouterMode,
    router_config: Option<&KvRouterConfig>,
    aic_perf_config: Option<&AicPerfConfig>,
) -> PyResult<Option<dynamo_mocker::replay::ReplayPrefillLoadEstimator>> {
    if router_mode != dynamo_mocker::replay::ReplayRouterMode::KvRouter {
        if aic_perf_config.is_some() {
            return Err(PyException::new_err(
                "aic_perf_config requires router_mode='kv_router'",
            ));
        }
        return Ok(None);
    }

    let Some(router_config) = router_config else {
        if aic_perf_config.is_some() {
            return Err(PyException::new_err(
                "aic_perf_config requires router_config with router_prefill_load_model='aic'",
            ));
        }
        return Ok(None);
    };

    let router_config = router_config.inner();
    if !router_config.router_prefill_load_model.is_enabled() {
        if aic_perf_config.is_some() {
            return Err(PyException::new_err(
                "aic_perf_config requires router_prefill_load_model='aic'",
            ));
        }
        return Ok(None);
    }

    let Some(aic_perf_config) = aic_perf_config else {
        return Err(PyException::new_err(
            "router_prefill_load_model='aic' requires aic_perf_config",
        ));
    };

    create_aic_prefill_load_estimator(
        py,
        aic_perf_config.backend_name(),
        aic_perf_config.system(),
        aic_perf_config.model_path(),
        aic_perf_config.tp_size(),
        aic_perf_config.backend_version(),
    )
    .map(Some)
}

1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
fn parse_replay_router_mode(
    router_mode: &str,
) -> PyResult<dynamo_mocker::replay::ReplayRouterMode> {
    match router_mode {
        "round_robin" => Ok(dynamo_mocker::replay::ReplayRouterMode::RoundRobin),
        "kv_router" => Ok(dynamo_mocker::replay::ReplayRouterMode::KvRouter),
        other => Err(PyException::new_err(format!(
            "router_mode must be either 'round_robin' or 'kv_router', got '{}'",
            other
        ))),
    }
}

1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
fn parse_trace_file_format(
    trace_format: &str,
) -> PyResult<dynamo_mocker::loadgen::TraceFileFormat> {
    match trace_format {
        "mooncake" => Ok(dynamo_mocker::loadgen::TraceFileFormat::Mooncake),
        "applied_compute_agentic" => {
            Ok(dynamo_mocker::loadgen::TraceFileFormat::AppliedComputeAgentic)
        }
        other => Err(PyException::new_err(format!(
            "trace_format must be either 'mooncake' or 'applied_compute_agentic', got '{}'",
            other
        ))),
    }
}

1120
1121
1122
1123
1124
1125
1126
1127
fn parse_replay_concurrency(replay_concurrency: Option<isize>) -> anyhow::Result<Option<usize>> {
    match replay_concurrency {
        Some(value) if value < 1 => anyhow::bail!("replay_concurrency must be at least 1"),
        Some(value) => Ok(Some(value as usize)),
        None => Ok(None),
    }
}

1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
#[allow(clippy::too_many_arguments)]
fn build_synthetic_workload(
    block_size: usize,
    input_tokens: usize,
    output_tokens: usize,
    request_count: usize,
    arrival_interval_ms: f64,
    turns_per_session: usize,
    shared_prefix_ratio: f64,
    num_prefix_groups: usize,
    inter_turn_delay_ms: f64,
) -> anyhow::Result<RsTrace> {
    if input_tokens == 0 {
        anyhow::bail!("input_tokens must be at least 1");
    }
    if output_tokens == 0 {
        anyhow::bail!("output_tokens must be at least 1");
    }
    if request_count == 0 {
        anyhow::bail!("request_count must be at least 1");
    }
    if turns_per_session == 0 {
        anyhow::bail!("turns_per_session must be at least 1");
    }
    if !arrival_interval_ms.is_finite() || arrival_interval_ms < 0.0 {
        anyhow::bail!("arrival_interval_ms must be a finite non-negative number");
    }
    if !inter_turn_delay_ms.is_finite() || inter_turn_delay_ms < 0.0 {
        anyhow::bail!("inter_turn_delay_ms must be a finite non-negative number");
    }

    let first_turn_arrivals = if arrival_interval_ms == 0.0 {
        ArrivalSpec::Burst
    } else {
        ArrivalSpec::ConstantQps {
            qps: 1000.0 / arrival_interval_ms,
        }
    };

    RsTrace::synthetic(SyntheticTraceSpec {
        block_size,
        num_sessions: request_count,
        turns_per_session,
        input_tokens: LengthSpec {
            mean: input_tokens,
            stddev: 0.0,
        },
        output_tokens: LengthSpec {
            mean: output_tokens,
            stddev: 0.0,
        },
        shared_prefix_ratio,
        num_prefix_groups,
        first_turn_arrivals,
        inter_turn_delays: if inter_turn_delay_ms == 0.0 {
            DelaySpec::None
        } else {
            DelaySpec::ConstantMs(inter_turn_delay_ms)
        },
        seed: 42,
    })
}

1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
fn build_synthetic_requests(
    input_tokens: usize,
    output_tokens: usize,
    request_count: usize,
    arrival_interval_ms: f64,
    include_arrival_timestamps: bool,
) -> anyhow::Result<Vec<DirectRequest>> {
    if input_tokens == 0 {
        anyhow::bail!("input_tokens must be at least 1");
    }
    if output_tokens == 0 {
        anyhow::bail!("output_tokens must be at least 1");
    }
    if request_count == 0 {
        anyhow::bail!("request_count must be at least 1");
    }
    if !arrival_interval_ms.is_finite() || arrival_interval_ms < 0.0 {
        anyhow::bail!(
            "arrival_interval_ms must be a finite non-negative number, got {}",
            arrival_interval_ms
        );
    }

    let mut requests = Vec::with_capacity(request_count);
    for request_idx in 0..request_count {
        let tokens = (0..input_tokens)
            .map(|token_idx| synthetic_token_id(request_idx, token_idx))
            .collect();
        requests.push(DirectRequest {
            tokens,
            max_output_tokens: output_tokens,
            uuid: Some(Uuid::from_u128((request_idx as u128) + 1)),
            dp_rank: 0,
            arrival_timestamp_ms: include_arrival_timestamps
                .then_some(request_idx as f64 * arrival_interval_ms),
        });
    }

    Ok(requests)
}

fn synthetic_token_id(request_idx: usize, token_idx: usize) -> u32 {
    let mut value =
        (((request_idx as u64) << 32) ^ (token_idx as u64)).wrapping_add(0x9E37_79B9_7F4A_7C15);
    value ^= value >> 30;
    value = value.wrapping_mul(0xBF58_476D_1CE4_E5B9);
    value ^= value >> 27;
    value = value.wrapping_mul(0x94D0_49BB_1331_11EB);
    value ^= value >> 31;
    let token = value as u32;
    if token == 0 { 1 } else { token }
}
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363

// ---------------------------------------------------------------------------
// Planner-in-the-loop replay bridge
// ---------------------------------------------------------------------------

fn fpm_snapshots_to_json(
    snapshots: Vec<(usize, dynamo_mocker::common::protocols::ForwardPassSnapshot)>,
) -> Vec<serde_json::Value> {
    snapshots
        .into_iter()
        .map(|(worker_id, fpm)| {
            json!({
                "worker_id": worker_id,
                "wall_time": fpm.wall_time_secs,
                "num_prefill_requests": fpm.num_prefill_requests,
                "sum_prefill_tokens": fpm.sum_prefill_tokens,
                "var_prefill_length": fpm.var_prefill_length,
                "sum_prefill_kv_tokens": fpm.sum_prefill_kv_tokens,
                "num_decode_requests": fpm.num_decode_requests,
                "sum_decode_kv_tokens": fpm.sum_decode_kv_tokens,
                "var_decode_kv_tokens": fpm.var_decode_kv_tokens,
                "num_queued_prefill": fpm.num_queued_prefill,
                "sum_queued_prefill_tokens": fpm.sum_queued_prefill_tokens,
                "var_queued_prefill_length": fpm.var_queued_prefill_length,
                "num_queued_decode": fpm.num_queued_decode,
                "sum_queued_decode_kv_tokens": fpm.sum_queued_decode_kv_tokens,
                "var_queued_decode_kv_tokens": fpm.var_queued_decode_kv_tokens,
            })
        })
        .collect()
}

/// Step-based bridge for driving an offline replay with a Python planner.
///
/// Supports both aggregated and disaggregated topologies. The Python adapter
/// calls `advance_to()` to run the simulation forward, collects FPM/traffic
/// metrics, feeds them to the planner state machine, then calls
/// `apply_scaling()` to resize worker pools.
#[pyclass(unsendable)]
pub struct PlannerReplayBridge {
    handle: Option<dynamo_mocker::replay::PlannerReplayHandle>,
}

#[pymethods]
impl PlannerReplayBridge {
    /// Create a bridge for an aggregated Mooncake-style JSONL trace replay.
    #[new]
    #[pyo3(signature = (trace_file, extra_engine_args, num_workers, router_mode="round_robin", router_config=None, arrival_speedup_ratio=1.0, trace_block_size=512))]
    fn new(
        trace_file: PathBuf,
        extra_engine_args: &MockEngineArgs,
        num_workers: usize,
        router_mode: &str,
        router_config: Option<KvRouterConfig>,
        arrival_speedup_ratio: f64,
        trace_block_size: usize,
    ) -> PyResult<Self> {
        let args = extra_engine_args.inner();
        let router_mode = parse_replay_router_mode(router_mode)?;
        let router_config = load_replay_router_config(router_config);

        let handle = dynamo_mocker::replay::PlannerReplayHandle::from_trace_file(
            args,
            router_config,
            None,
            &trace_file,
            trace_block_size,
            num_workers,
            arrival_speedup_ratio,
            router_mode,
        )
        .map_err(to_pyerr)?;

        Ok(Self {
            handle: Some(handle),
        })
    }

    /// Create a bridge for a disaggregated Mooncake-style JSONL trace replay.
    #[staticmethod]
    #[pyo3(signature = (trace_file, prefill_engine_args, decode_engine_args, num_prefill_workers, num_decode_workers, router_mode="round_robin", router_config=None, arrival_speedup_ratio=1.0, trace_block_size=512))]
    #[allow(clippy::too_many_arguments)]
    fn create_disagg(
        trace_file: PathBuf,
        prefill_engine_args: &MockEngineArgs,
        decode_engine_args: &MockEngineArgs,
        num_prefill_workers: usize,
        num_decode_workers: usize,
        router_mode: &str,
        router_config: Option<KvRouterConfig>,
        arrival_speedup_ratio: f64,
        trace_block_size: usize,
    ) -> PyResult<Self> {
        let config = dynamo_mocker::replay::OfflineDisaggReplayConfig {
            prefill_args: prefill_engine_args.inner(),
            decode_args: decode_engine_args.inner(),
            num_prefill_workers,
            num_decode_workers,
        };
        let router_mode = parse_replay_router_mode(router_mode)?;
        let router_config = load_replay_router_config(router_config);

        let handle = dynamo_mocker::replay::PlannerReplayHandle::from_trace_file_disagg(
            config,
            router_config,
            None,
            &trace_file,
            trace_block_size,
            arrival_speedup_ratio,
            router_mode,
        )
        .map_err(to_pyerr)?;

        Ok(Self {
            handle: Some(handle),
        })
    }

    /// Advance the simulation to `until_ms` simulated time.
    ///
    /// Returns a dict with separate prefill/decode worker counts and FPM snapshots.
1364
1365
    /// Traffic metrics are NOT included — call `drain_traffic()` explicitly on
    /// throughput-scaling ticks only.
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
    fn advance_to(&mut self, py: Python<'_>, until_ms: f64) -> PyResult<PyObject> {
        let handle = self
            .handle
            .as_mut()
            .ok_or_else(|| PyException::new_err("bridge has been finalized"))?;

        let tick_data = handle.advance_to(until_ms).map_err(to_pyerr)?;

        let result = json!({
            "now_ms": tick_data.now_ms,
            "is_done": tick_data.is_done,
            "prefill_fpm_snapshots": fpm_snapshots_to_json(tick_data.prefill_fpm_snapshots),
            "decode_fpm_snapshots": fpm_snapshots_to_json(tick_data.decode_fpm_snapshots),
            "active_prefill_count": tick_data.active_prefill_count,
            "active_decode_count": tick_data.active_decode_count,
            "total_prefill_count": tick_data.total_prefill_count,
            "total_decode_count": tick_data.total_decode_count,
        });

        pythonize(py, &result)
1386
1387
1388
1389
1390
1391
            .map_err(to_pyerr)
            .map(|obj| obj.unbind())
    }

    /// Drain accumulated traffic metrics since the last drain.
    ///
1392
    /// Returns a dict with:
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
    ///   - `duration_s`      (f64): window length in seconds
    ///   - `num_req`         (usize): completed requests in the window
    ///   - `avg_isl`         (f64): mean input sequence length (tokens)
    ///   - `avg_osl`         (f64): mean output sequence length (tokens)
    ///   - `avg_ttft_ms`     (f64): mean time-to-first-token in milliseconds,
    ///                              averaged only over requests that reported
    ///                              a TTFT sample (0.0 when no samples)
    ///   - `avg_itl_ms`      (f64): mean inter-token latency in milliseconds,
    ///                              averaged only over requests that generated
    ///                              at least one token gap (0.0 when no samples)
    ///   - `avg_kv_hit_rate` (f64): arithmetic mean of per-request
    ///                              ``overlap_blocks / isl_blocks`` ratios
    ///                              across router admissions in the window
    ///                              (one sample per request, not weighted
    ///                              by ISL), matching the real router's
    ///                              `dynamo_component_router_kv_hit_rate`
    ///                              histogram semantics
1410
    ///
1411
1412
1413
1414
1415
1416
1417
1418
    /// Call this only on throughput-scaling ticks so the observation window
    /// covers the full `throughput_adjustment_interval`.
    fn drain_traffic(&mut self, py: Python<'_>) -> PyResult<PyObject> {
        let handle = self
            .handle
            .as_mut()
            .ok_or_else(|| PyException::new_err("bridge has been finalized"))?;

1419
        let stats = handle.drain_traffic();
1420
1421

        let result = json!({
1422
1423
1424
1425
1426
1427
            "duration_s": stats.duration_s,
            "num_req": stats.num_req,
            "avg_isl": stats.avg_isl,
            "avg_osl": stats.avg_osl,
            "avg_ttft_ms": stats.avg_ttft_ms,
            "avg_itl_ms": stats.avg_itl_ms,
1428
            "avg_kv_hit_rate": stats.avg_kv_hit_rate,
1429
1430
1431
        });

        pythonize(py, &result)
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
            .map_err(to_pyerr)
            .map(|obj| obj.unbind())
    }

    /// Apply a scaling decision with separate prefill and decode targets.
    /// For agg mode, `target_prefill` is ignored (pass 0).
    fn apply_scaling(&mut self, target_prefill: usize, target_decode: usize) -> PyResult<()> {
        let handle = self
            .handle
            .as_mut()
            .ok_or_else(|| PyException::new_err("bridge has been finalized"))?;
        handle
            .apply_scaling(target_prefill, target_decode)
            .map_err(to_pyerr)
    }

    /// Finalize the replay and return the trace simulation report.
    fn finalize(&mut self, py: Python<'_>) -> PyResult<PyObject> {
        let handle = self
            .handle
            .take()
            .ok_or_else(|| PyException::new_err("bridge has already been finalized"))?;
        let report = handle.finalize();
        pythonize(py, &report)
            .map_err(to_pyerr)
            .map(|obj| obj.unbind())
    }
}