dynamo-mocker 1.7.0

Mock LLM scheduler and KV manager for testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

mod agentic;
mod artifacts;
mod entrypoints;
pub(crate) mod offline;
mod online;
mod router_controls;
mod router_shared;
mod validate;

use std::collections::VecDeque;
use std::sync::Arc;

use crate::common::protocols::{DirectRequest, MockerConfig};
use dynamo_kv_router::PrefillLoadEstimator;

pub use agentic::AgenticReplayOptions;
/// Backward-compatible Dynamo Mocker name for [`aisimulate_core::ReplayReport`].
pub use aisimulate_core::ReplayReport as TraceSimulationReport;
pub(crate) use aisimulate_core::replay::TraceCollector;
pub use aisimulate_core::replay::{
    CanonicalReplayCoverage, CanonicalReplayRecord, LifecycleOperation, OfflineRuntimeEvidence,
    PerRequestRecord, ReplayCaptureOptions, ReplayDeterminism, ReplayTerminalStatus, SlaThresholds,
    TraceDistributionStats, TraceGoodputStats, TraceInterTokenLatencyStats, TraceLatencyStats,
    TraceRequestCounts, TraceThroughputStats,
};
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub use artifacts::native_g1_parent_chain_artifact;
pub use artifacts::{
    ReplayTimedKvEvent, ReplayTimedOutputSignal, ReplayTimedRequest, ReplayWorkerArtifacts,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReplayRouterMode {
    RoundRobin,
    KvRouter,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReplayArgsMode {
    Aggregated,
    Disagg,
}

pub type ReplayPrefillLoadEstimator = Arc<dyn PrefillLoadEstimator>;

#[derive(Clone, Debug)]
pub struct OfflineDisaggReplayConfig {
    pub prefill_args: MockerConfig,
    pub decode_args: MockerConfig,
    pub num_prefill_workers: usize,
    pub num_decode_workers: usize,
}

impl OfflineDisaggReplayConfig {
    pub fn normalized(self) -> anyhow::Result<Self> {
        Ok(Self {
            prefill_args: self.prefill_args.normalized()?,
            decode_args: self.decode_args.normalized()?,
            num_prefill_workers: self.num_prefill_workers,
            num_decode_workers: self.num_decode_workers,
        })
    }
}

pub use aisimulate_core::replay::TrafficStats;
pub use aisimulate_core::replay::{
    ReplayScalingDecision, ReplayScalingPolicy, ReplayScalingSnapshot,
    ReplaySchedulerIntervalMetrics, ReplaySchedulerMetricsSnapshot, ReplayTelemetryObserver,
    ReplayTelemetrySampleKind, ReplayTelemetrySnapshot, ReplayTrafficMetricsSnapshot,
};

/// Optional policy-neutral telemetry sink for one offline replay.
///
/// Telemetry is deliberately configured independently from
/// [`ReplayScalingPolicy`]: observing a replay must not change the planner
/// callback contract or its decision cadence.
pub struct ReplayTelemetryOptions {
    pub sample_interval_ms: f64,
    pub observer: Box<dyn ReplayTelemetryObserver>,
}

/// Optional replay observers installed for one invocation.
///
/// Scaling and telemetry share an invocation without coupling their callback
/// contracts or sampling cadence.
#[derive(Default)]
pub struct ReplayRuntimeObservers {
    pub scaling_policy: Option<Box<dyn ReplayScalingPolicy>>,
    pub telemetry: Option<ReplayTelemetryOptions>,
}
pub use entrypoints::{
    ReplayKvEventVisibility, generate_trace_worker_artifacts_offline,
    generate_trace_worker_artifacts_offline_with_kv_event_visibility,
    simulate_agentic_trace_live_workload_with_router_mode_and_options,
    simulate_agentic_trace_workload_disagg_with_options,
    simulate_agentic_trace_workload_disagg_with_router_mode,
    simulate_agentic_trace_workload_disagg_with_router_mode_and_runtime_observers,
    simulate_agentic_trace_workload_disagg_with_router_mode_and_telemetry,
    simulate_agentic_trace_workload_with_options, simulate_agentic_trace_workload_with_router_mode,
    simulate_agentic_trace_workload_with_router_mode_and_runtime_observers,
    simulate_agentic_trace_workload_with_router_mode_and_telemetry, simulate_concurrency_file,
    simulate_concurrency_file_disagg_with_router_mode,
    simulate_concurrency_file_disagg_with_router_mode_and_format,
    simulate_concurrency_file_disagg_with_router_mode_and_format_and_runtime_observers,
    simulate_concurrency_file_with_router_mode,
    simulate_concurrency_file_with_router_mode_and_format,
    simulate_concurrency_file_with_router_mode_and_format_and_runtime_observers,
    simulate_concurrency_live_file, simulate_concurrency_live_file_with_router_mode,
    simulate_concurrency_live_file_with_router_mode_and_format,
    simulate_concurrency_live_file_with_router_mode_and_format_and_options,
    simulate_concurrency_live_requests, simulate_concurrency_live_requests_with_router_mode,
    simulate_concurrency_live_requests_with_router_mode_and_options,
    simulate_concurrency_live_workload, simulate_concurrency_live_workload_with_router_mode,
    simulate_concurrency_live_workload_with_router_mode_and_options, simulate_concurrency_requests,
    simulate_concurrency_requests_disagg_with_router_mode,
    simulate_concurrency_requests_disagg_with_router_mode_and_runtime_observers,
    simulate_concurrency_requests_with_router_mode,
    simulate_concurrency_requests_with_router_mode_and_runtime_observers,
    simulate_concurrency_workload, simulate_concurrency_workload_disagg_with_router_mode,
    simulate_concurrency_workload_disagg_with_router_mode_and_options,
    simulate_concurrency_workload_disagg_with_router_mode_and_options_and_runtime_observers,
    simulate_concurrency_workload_with_router_mode,
    simulate_concurrency_workload_with_router_mode_and_options,
    simulate_concurrency_workload_with_router_mode_and_options_and_runtime_observers,
    simulate_loaded_trace_disagg_with_router_mode_and_capture_options,
    simulate_loaded_trace_disagg_with_router_mode_and_options,
    simulate_loaded_trace_disagg_with_router_mode_and_options_and_runtime_observers,
    simulate_loaded_trace_live_with_router_mode,
    simulate_loaded_trace_live_with_router_mode_and_options,
    simulate_loaded_trace_with_router_mode_and_capture_options,
    simulate_loaded_trace_with_router_mode_and_options,
    simulate_loaded_trace_with_router_mode_and_options_and_runtime_observers, simulate_trace_file,
    simulate_trace_file_disagg_with_router_mode,
    simulate_trace_file_disagg_with_router_mode_and_format,
    simulate_trace_file_disagg_with_router_mode_and_format_and_runtime_observers,
    simulate_trace_file_with_router_mode, simulate_trace_file_with_router_mode_and_format,
    simulate_trace_file_with_router_mode_and_format_and_runtime_observers,
    simulate_trace_live_file, simulate_trace_live_file_with_router_mode,
    simulate_trace_live_file_with_router_mode_and_format,
    simulate_trace_live_file_with_router_mode_and_format_and_options, simulate_trace_live_requests,
    simulate_trace_live_requests_with_router_mode,
    simulate_trace_live_requests_with_router_mode_and_options, simulate_trace_live_workload,
    simulate_trace_live_workload_with_router_mode,
    simulate_trace_live_workload_with_router_mode_and_options, simulate_trace_requests,
    simulate_trace_requests_disagg_with_router_mode,
    simulate_trace_requests_disagg_with_router_mode_and_runtime_observers,
    simulate_trace_requests_with_router_mode,
    simulate_trace_requests_with_router_mode_and_runtime_observers, simulate_trace_workload,
    simulate_trace_workload_disagg_with_router_mode,
    simulate_trace_workload_disagg_with_router_mode_and_options_and_runtime_observers,
    simulate_trace_workload_with_router_mode,
    simulate_trace_workload_with_router_mode_and_options_and_runtime_observers,
};
#[doc(hidden)]
pub use offline::run_offline_handoff_conformance;
pub use router_controls::{
    ReplayRouterControls, ReplayRouterParameters, apply_router_parameters, parse_router_worker_type,
};
pub use validate::validate_replay_args_mode;

/// Conversation grouping used by native session affinity in offline replay.
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConversationAffinityMode {
    #[default]
    Session,
    SiblingGroup,
}

/// Optional native binding policy; its TTL follows virtual replay time.
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ConversationAffinityConfig {
    pub mode: ConversationAffinityMode,
    pub ttl_seconds: f64,
}

impl Default for ConversationAffinityConfig {
    fn default() -> Self {
        Self {
            mode: ConversationAffinityMode::Session,
            ttl_seconds: 300.0,
        }
    }
}

impl ConversationAffinityConfig {
    pub fn validate(self) -> anyhow::Result<()> {
        use dynamo_kv_router::services::selection::affinity::MAX_SESSION_AFFINITY_TTL_SECS;
        anyhow::ensure!(
            self.ttl_seconds.is_finite()
                && (1.0..=MAX_SESSION_AFFINITY_TTL_SECS as f64).contains(&self.ttl_seconds),
            "conversation affinity TTL must be between 1 and {MAX_SESSION_AFFINITY_TTL_SECS} seconds"
        );
        Ok(())
    }
}

/// Settings for the offline replays a host runs on one thread, installed by [`with_replay_scope`].
///
/// They reach replay internals that the entrypoint signatures do not carry. The default scope is
/// the behavior outside any [`with_replay_scope`].
#[derive(Clone, Debug, Default)]
pub struct ReplayScope {
    /// Native session/sibling affinity, independently scoped to each worker pool.
    pub conversation_affinity: Option<ConversationAffinityConfig>,
    /// Delays the KV cache events (blocks stored and removed) the router's indexer observes by this
    /// much simulated time. Prefill and request completions stay immediate, as a live router
    /// observes them in-band on the response path. `0.0` keeps synchronous updates. Offline
    /// KV-router replay only.
    pub kv_event_lag_ms: f64,
    /// Registry in which each offline KV-router placement registers its selector, so the host can
    /// change router policy parameters during the replay. `None` registers nothing.
    pub router_controls: Option<ReplayRouterControls>,
    /// Request identity and KV-router selection semantics of offline replays that do not pass
    /// their own [`ReplayCaptureOptions`]. [`ReplayDeterminism::CanonicalV1`] assigns ordinal
    /// request IDs and seeds every KV-router selector, so two replays of the same input and
    /// configuration produce the same report.
    pub determinism: ReplayDeterminism,
}

thread_local! {
    static REPLAY_SCOPE: std::cell::RefCell<ReplayScope> = const {
        std::cell::RefCell::new(ReplayScope {
            conversation_affinity: None,
            kv_event_lag_ms: 0.0,
            router_controls: None,
            determinism: ReplayDeterminism::Random,
        })
    };
}

/// Run `replay` with `scope` installed for the offline replays constructed on this thread.
///
/// The scope replaces any outer scope entirely, so a nested replay never registers into a router
/// control registry it does not own. The previous scope is restored when `replay` returns or
/// unwinds.
pub fn with_replay_scope<T>(scope: ReplayScope, replay: impl FnOnce() -> T) -> anyhow::Result<T> {
    if let Some(config) = scope.conversation_affinity {
        config.validate()?;
    }
    let lag_ms = scope.kv_event_lag_ms;
    anyhow::ensure!(
        lag_ms.is_finite() && lag_ms >= 0.0,
        "kv_event_lag_ms must be finite and non-negative, got {lag_ms}"
    );
    struct Restore(ReplayScope);
    impl Drop for Restore {
        fn drop(&mut self) {
            let previous = std::mem::take(&mut self.0);
            REPLAY_SCOPE.with(|current| *current.borrow_mut() = previous);
        }
    }
    let _restore = Restore(REPLAY_SCOPE.with(|current| current.replace(scope)));
    Ok(replay())
}

/// Run `replay` with a simulated KV event lag for offline KV-router replay.
///
/// [`with_replay_scope`] with only [`ReplayScope::kv_event_lag_ms`] set; like it, this replaces
/// any outer scope.
pub fn with_kv_event_lag_ms<T>(lag_ms: f64, replay: impl FnOnce() -> T) -> anyhow::Result<T> {
    let scope = ReplayScope {
        kv_event_lag_ms: lag_ms,
        ..ReplayScope::default()
    };
    with_replay_scope(scope, replay)
}

/// The scope installed by the innermost [`with_replay_scope`] on this thread.
pub(crate) fn replay_scope() -> ReplayScope {
    REPLAY_SCOPE.with(|current| current.borrow().clone())
}

pub(crate) fn normalize_trace_requests(
    mut requests: Vec<DirectRequest>,
    arrival_speedup_ratio: f64,
) -> anyhow::Result<VecDeque<DirectRequest>> {
    if !arrival_speedup_ratio.is_finite() || arrival_speedup_ratio <= 0.0 {
        anyhow::bail!(
            "arrival_speedup_ratio must be a finite positive number, got {arrival_speedup_ratio}"
        );
    }

    requests.sort_by(|left, right| {
        let left_ts = left
            .arrival_timestamp_ms
            .expect("trace replay requests must have an arrival timestamp");
        let right_ts = right
            .arrival_timestamp_ms
            .expect("trace replay requests must have an arrival timestamp");
        left_ts.total_cmp(&right_ts)
    });

    let first_arrival_ms = requests
        .first()
        .and_then(|request| request.arrival_timestamp_ms)
        .ok_or_else(|| anyhow::anyhow!("trace replay requires at least one timestamped request"))?;

    Ok(VecDeque::from(
        requests
            .into_iter()
            .map(|mut request| {
                let arrival_timestamp_ms = request
                    .arrival_timestamp_ms
                    .expect("trace replay requests must have an arrival timestamp")
                    - first_arrival_ms;
                let arrival_timestamp_ms = arrival_timestamp_ms / arrival_speedup_ratio;
                request.arrival_timestamp_ms = Some(arrival_timestamp_ms);
                request
            })
            .collect::<Vec<_>>(),
    ))
}

pub(crate) fn effective_agentic_lanes(
    requested_lanes: Option<usize>,
    play_count: usize,
) -> Option<usize> {
    requested_lanes.map(|lane_count| lane_count.min(play_count))
}

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

    #[test]
    fn replay_scope_is_validated_replaced_and_restored() {
        let lag_scope = |kv_event_lag_ms| ReplayScope {
            kv_event_lag_ms,
            ..Default::default()
        };
        assert!(with_replay_scope(lag_scope(f64::INFINITY), || ()).is_err());
        assert!(with_replay_scope(lag_scope(-1.0), || ()).is_err());
        let is_default = |scope: ReplayScope| {
            scope.kv_event_lag_ms == 0.0
                && scope.router_controls.is_none()
                && scope.conversation_affinity.is_none()
                && scope.determinism == ReplayDeterminism::Random
        };
        assert!(is_default(replay_scope()));

        let outer = ReplayScope {
            kv_event_lag_ms: 25.0,
            router_controls: Some(ReplayRouterControls::new()),
            determinism: ReplayDeterminism::CanonicalV1,
            ..Default::default()
        };
        with_replay_scope(outer, || {
            let current = replay_scope();
            assert_eq!(current.kv_event_lag_ms, 25.0);
            assert!(current.router_controls.is_some());
            assert_eq!(current.determinism, ReplayDeterminism::CanonicalV1);
            // A nested scope replaces every setting, so a nested replay registers nowhere.
            with_replay_scope(ReplayScope::default(), || {
                assert!(is_default(replay_scope()))
            })
            .unwrap();
            let restored = replay_scope();
            assert_eq!(restored.kv_event_lag_ms, 25.0);
            assert!(restored.router_controls.is_some());
        })
        .unwrap();
        assert!(is_default(replay_scope()));

        // A replay that unwinds also restores the previous scope.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            with_replay_scope(lag_scope(5.0), || panic!("replay failed"))
        }));
        assert!(result.is_err());
        assert!(is_default(replay_scope()));
    }

    #[test]
    fn test_normalize_trace_requests_applies_arrival_speedup_ratio() {
        let requests = vec![
            DirectRequest {
                tokens: vec![1; 4],
                max_output_tokens: 1,
                output_token_ids: None,
                uuid: Some(Uuid::from_u128(1)),
                dp_rank: 0,
                arrival_timestamp_ms: Some(100.0),
                ..Default::default()
            },
            DirectRequest {
                tokens: vec![2; 4],
                max_output_tokens: 1,
                output_token_ids: None,
                uuid: Some(Uuid::from_u128(2)),
                dp_rank: 0,
                arrival_timestamp_ms: Some(200.0),
                ..Default::default()
            },
        ];

        let normalized = normalize_trace_requests(requests, 10.0).unwrap();
        let arrivals = normalized
            .into_iter()
            .map(|request| request.arrival_timestamp_ms.unwrap())
            .collect::<Vec<_>>();

        assert_eq!(arrivals, vec![0.0, 10.0]);
    }

    #[test]
    fn test_effective_agentic_lanes_are_bounded_by_play_count() {
        assert_eq!(effective_agentic_lanes(None, 3), None);
        assert_eq!(effective_agentic_lanes(Some(2), 3), Some(2));
        assert_eq!(effective_agentic_lanes(Some(usize::MAX), 3), Some(3));
    }
}