mooncake_bench.rs 24.2 KB
Newer Older
Yan Ru Pei's avatar
Yan Ru Pei committed
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
5
6
7
#[path = "common/mod.rs"]
mod common;
use common::*;

Yan Ru Pei's avatar
Yan Ru Pei committed
8
9
10
11
12
use clap::{Parser, Subcommand};
use dynamo_kv_router::LocalBlockHash;
use dynamo_kv_router::indexer::{
    KvIndexer, KvIndexerInterface, KvIndexerMetrics, KvIndexerSharded,
};
13
use dynamo_kv_router::protocols::{KvCacheEvent, KvCacheEventData, RouterEvent};
14
15
16
use dynamo_kv_router::{
    ConcurrentRadixTree, InvertedIndex, NaiveNestedMap, PositionalIndexer, ThreadPoolIndexer,
};
17
use serde::Serialize;
Yan Ru Pei's avatar
Yan Ru Pei committed
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
use std::sync::Arc;
use tokio::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;

/// Indexer backend selection and its backend-specific parameters.
#[derive(Subcommand, Debug, Clone)]
enum IndexerArgs {
    /// Single-threaded radix tree indexer.
    RadixTree {},

    /// Sharded radix tree indexer that partitions workers across independent shards.
    RadixTreeSharded {
        /// Number of independent shards to split workers across.
        #[clap(long, default_value = "4")]
        num_shards: usize,
    },

    /// Position-based nested map indexer with jump search.
    NestedMap {
        /// Number of positions to skip during jump search before scanning back.
        #[clap(long, default_value = "8")]
        jump_size: usize,

        /// Number of OS threads that consume and apply KV cache events.
        #[clap(long, default_value = "16")]
        num_event_workers: usize,
    },

    /// Lock-based concurrent radix tree indexer.
    ConcurrentRadixTree {
        /// Number of OS threads that consume and apply KV cache events.
        #[clap(long, default_value = "16")]
        num_event_workers: usize,
    },
52
53
54
55
56
57
58
59
60
61
62

    /// Naive per-worker nested HashMap indexer behind a single-threaded actor
    /// (blog section 2).
    NaiveNestedMap {},

    /// Inverted index keyed by local_hash (blog section 3).
    InvertedIndex {
        /// Number of OS threads that consume and apply KV cache events.
        #[clap(long, default_value = "16")]
        num_event_workers: usize,
    },
Yan Ru Pei's avatar
Yan Ru Pei committed
63
64
65
66
}

impl IndexerArgs {
    /// Construct the concrete indexer from the parsed CLI args.
67
    fn build(self, block_size: u32) -> Arc<dyn KvIndexerInterface + Send + Sync> {
Yan Ru Pei's avatar
Yan Ru Pei committed
68
69
70
71
        let cancel_token = CancellationToken::new();
        let metrics = Arc::new(KvIndexerMetrics::new_unregistered());
        match self {
            IndexerArgs::RadixTree {} => {
72
                Arc::new(KvIndexer::new(cancel_token, block_size, metrics))
Yan Ru Pei's avatar
Yan Ru Pei committed
73
74
75
76
            }
            IndexerArgs::RadixTreeSharded { num_shards } => Arc::new(KvIndexerSharded::new(
                cancel_token,
                num_shards,
77
                block_size,
Yan Ru Pei's avatar
Yan Ru Pei committed
78
79
80
81
82
83
84
85
                metrics,
            )),
            IndexerArgs::NestedMap {
                jump_size,
                num_event_workers,
            } => Arc::new(ThreadPoolIndexer::new(
                PositionalIndexer::new(jump_size),
                num_event_workers,
86
                block_size,
Yan Ru Pei's avatar
Yan Ru Pei committed
87
            )),
88
89
90
            IndexerArgs::ConcurrentRadixTree { num_event_workers } => Arc::new(
                ThreadPoolIndexer::new(ConcurrentRadixTree::new(), num_event_workers, block_size),
            ),
91
92
            IndexerArgs::NaiveNestedMap {} => Arc::new(NaiveNestedMap::new()),
            IndexerArgs::InvertedIndex { .. } => Arc::new(InvertedIndex::new()),
Yan Ru Pei's avatar
Yan Ru Pei committed
93
94
        }
    }
95

96
97
98
99
100
101
102
103
    fn supports_remove(name: &str) -> bool {
        !matches!(name, "naive-nested-map" | "inverted-index")
    }

    fn is_multi_threaded(name: &str) -> bool {
        matches!(name, "nested-map" | "concurrent-radix-tree")
    }

104
    /// Construct an indexer from a short name string.
105
106
    fn from_name(
        name: &str,
107
108
        block_size: u32,
        num_event_workers: usize,
109
    ) -> anyhow::Result<Arc<dyn KvIndexerInterface + Send + Sync>> {
110
        let nw = num_event_workers;
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
        let indexer_args = match name {
            "radix-tree" => IndexerArgs::RadixTree {},
            "radix-tree-sharded" => IndexerArgs::RadixTreeSharded { num_shards: 4 },
            "nested-map" => IndexerArgs::NestedMap {
                jump_size: 8,
                num_event_workers: nw,
            },
            "concurrent-radix-tree" => IndexerArgs::ConcurrentRadixTree {
                num_event_workers: nw,
            },
            "naive-nested-map" => IndexerArgs::NaiveNestedMap {},
            "inverted-index" => IndexerArgs::InvertedIndex {
                num_event_workers: 0,
            },
            _ => anyhow::bail!(
                "Unknown indexer '{}'. Valid names: radix-tree, radix-tree-sharded, \
                 nested-map, concurrent-radix-tree, naive-nested-map, inverted-index",
                name
            ),
        };
131
        Ok(indexer_args.build(block_size))
132
    }
Yan Ru Pei's avatar
Yan Ru Pei committed
133
134
135
136
137
}

#[derive(Parser, Debug)]
#[clap(version, about, long_about = None)]
struct Args {
138
139
    #[clap(flatten)]
    common: CommonArgs,
Yan Ru Pei's avatar
Yan Ru Pei committed
140

141
    /// Output path for the sweep plot SVG.
142
    #[clap(long, default_value = "sweep_plot.svg")]
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    sweep_output: String,

    /// Comma-separated list of indexer names to benchmark and compare on the
    /// same plot. Overrides the subcommand indexer when present. Valid names:
    /// radix-tree, radix-tree-sharded, nested-map, concurrent-radix-tree,
    /// naive-nested-map, inverted-index.
    #[clap(long, value_delimiter = ',')]
    compare: Vec<String>,

    /// Number of OS threads for event processing in compare mode. Applies to
    /// indexers that use a thread pool (nested-map, concurrent-radix-tree,
    /// inverted-index). Ignored by radix-tree, radix-tree-sharded, and
    /// naive-nested-map.
    #[clap(long, default_value = "16")]
    num_event_workers: usize,

Yan Ru Pei's avatar
Yan Ru Pei committed
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
    /// Indexer backend to benchmark (defaults to radix-tree if not specified).
    #[clap(subcommand)]
    indexer: Option<IndexerArgs>,
}

impl Args {
    /// Return the indexer config, falling back to RadixTree if none was specified.
    fn get_indexer(&self) -> IndexerArgs {
        self.indexer.clone().unwrap_or(IndexerArgs::RadixTree {})
    }
}

/// A single entry in a worker's merged benchmark timeline.
#[derive(Clone)]
enum WorkerTraceEntry {
    /// A find_matches request with pre-computed block hashes.
    Request(Vec<LocalBlockHash>),
    /// A KV cache event (store/remove/clear) to apply to the indexer.
    Event(KvCacheEvent),
}

/// A timestamped entry in a worker's benchmark trace, used to replay requests
/// and events at the correct relative timing.
#[derive(Clone)]
struct WorkerTrace {
    entry: WorkerTraceEntry,
    timestamp_us: u64,
}

/// Merge each worker's request trace and event trace into a single
/// time-ordered sequence of `WorkerTrace` entries suitable for benchmark
/// replay.
///
/// Timestamps are rescaled from the original trace / simulation durations
/// into the benchmark duration (microseconds).
fn prepare_worker_traces(
    traces: Vec<Vec<MooncakeRequest>>,
    events: Vec<Vec<(KvCacheEvent, Instant)>>,
197
198
199
    block_size: u32,
    benchmark_duration_ms: u64,
    trace_simulation_duration_ms: u64,
Yan Ru Pei's avatar
Yan Ru Pei committed
200
201
202
203
204
205
) -> Vec<Vec<WorkerTrace>> {
    assert!(traces.len() == events.len());

    let scaled_request_traces: Vec<_> = traces
        .into_iter()
        .map(|trace| {
206
207
208
209
210
            let Some(first) = trace.first() else {
                return Vec::new();
            };
            let first_ts = first.timestamp;
            let trace_duration_ms = trace.last().unwrap().timestamp - first_ts;
Yan Ru Pei's avatar
Yan Ru Pei committed
211
212
213
            trace
                .into_iter()
                .map(|request| WorkerTrace {
214
215
216
217
218
219
                    timestamp_us: if trace_duration_ms == 0 {
                        0
                    } else {
                        (request.timestamp - first_ts) * 1000 * benchmark_duration_ms
                            / trace_duration_ms
                    },
Yan Ru Pei's avatar
Yan Ru Pei committed
220
221
222
223
                    entry: WorkerTraceEntry::Request(
                        request
                            .hash_ids
                            .iter()
224
                            .map(|id| local_block_hash_from_id(*id, block_size))
Yan Ru Pei's avatar
Yan Ru Pei committed
225
226
227
228
229
230
231
232
233
234
                            .collect(),
                    ),
                })
                .collect::<Vec<_>>()
        })
        .collect();

    let scaled_event_traces: Vec<_> = events
        .into_iter()
        .map(|worker_events| {
235
236
237
            let Some(&(_, start_instant)) = worker_events.first() else {
                return Vec::new();
            };
Yan Ru Pei's avatar
Yan Ru Pei committed
238
239
240
241
            worker_events
                .into_iter()
                .map(|(event, timestamp)| WorkerTrace {
                    timestamp_us: (timestamp - start_instant).as_micros() as u64
242
243
                        * benchmark_duration_ms
                        / trace_simulation_duration_ms,
Yan Ru Pei's avatar
Yan Ru Pei committed
244
245
246
247
248
249
250
251
                    entry: WorkerTraceEntry::Event(event),
                })
                .collect::<Vec<_>>()
        })
        .collect();

    scaled_request_traces
        .into_iter()
252
        .zip(scaled_event_traces)
Yan Ru Pei's avatar
Yan Ru Pei committed
253
        .map(|(request_trace, event_trace)| {
254
255
            let mut merged: Vec<WorkerTrace> =
                request_trace.into_iter().chain(event_trace).collect();
Yan Ru Pei's avatar
Yan Ru Pei committed
256
257
258
259
260
261
            merged.sort_by_key(|entry| entry.timestamp_us);
            merged
        })
        .collect()
}

262
263
264
265
266
267
268
#[derive(Serialize)]
struct SweepStepResult {
    duration_ms: u64,
    #[serde(flatten)]
    results: BenchmarkResults,
}

Yan Ru Pei's avatar
Yan Ru Pei committed
269
270
271
272
273
274
275
276
277
278
279
/// Run the benchmark: replay each worker's merged trace against the indexer,
/// measuring find_matches latency and event processing throughput.
///
/// Workers are spawned as tokio tasks, each replaying its trace at the
/// original inter-entry timing. After all workers finish, the event queue is
/// flushed and latency percentiles / throughput stats are printed.
async fn run_benchmark(
    indexer: Arc<dyn KvIndexerInterface + Send + Sync>,
    traces: Vec<Vec<MooncakeRequest>>,
    events: Vec<Vec<(KvCacheEvent, Instant)>>,
    args: &Args,
280
    benchmark_duration_ms: u64,
281
    count_events: bool,
282
283
284
285
) -> anyhow::Result<BenchmarkResults> {
    let worker_traces = prepare_worker_traces(
        traces,
        events,
286
        args.common.block_size,
287
        benchmark_duration_ms,
288
        args.common.trace_simulation_duration_ms,
289
    );
290
    let worker_traces = worker_traces.into_iter().map(Arc::new).collect::<Vec<_>>();
Yan Ru Pei's avatar
Yan Ru Pei committed
291
292
293
294
295
296

    let progress = make_progress_bar(Some(
        worker_traces
            .iter()
            .map(|trace| trace.len() as u64)
            .sum::<u64>()
297
            * args.common.inference_worker_duplication_factor as u64,
Yan Ru Pei's avatar
Yan Ru Pei committed
298
299
300
    ));

    let mut tasks = Vec::new();
301
    for replica in 0..args.common.inference_worker_duplication_factor {
Yan Ru Pei's avatar
Yan Ru Pei committed
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
        for (worker_id, worker_trace) in worker_traces.iter().enumerate() {
            let indexer = indexer.clone();
            let trace = worker_trace.clone();
            let progress = progress.clone();
            let worker_id = worker_id + replica * worker_traces.len();
            tasks.push(tokio::spawn(async move {
                let mut request_latencies = Vec::with_capacity(trace.len());

                let submit = |entry: WorkerTrace| async {
                    match entry.entry {
                        WorkerTraceEntry::Request(request) => {
                            let start = minstant::Instant::now();
                            indexer.find_matches(request).await?;
                            Ok::<Option<u64>, anyhow::Error>(
                                Some(start.elapsed().as_nanos() as u64),
                            )
                        }
                        WorkerTraceEntry::Event(event) => {
                            indexer
                                .apply_event(RouterEvent {
                                    worker_id: worker_id as u64,
                                    event,
                                })
                                .await;
                            Ok(None)
                        }
                    }
                };

                let mut target = Instant::now();

                let mut trace = trace.iter().peekable();

                let mut local_count = 0;

                while let Some(entry) = trace.next() {
                    let mut processed = 1;
                    let entry_timestamp_us = entry.timestamp_us;

                    if let Some(latency) = submit(entry.clone()).await? {
                        request_latencies.push(latency);
                    }

                    while let Some(next) = trace.peek() {
                        if next.timestamp_us == entry_timestamp_us {
                            if let Some(latency) = submit(trace.next().unwrap().clone()).await? {
                                request_latencies.push(latency);
                            }
                            processed += 1;
                        } else {
                            break;
                        }
                    }

                    if let Some(next) = trace.peek() {
                        target += Duration::from_micros(next.timestamp_us - entry_timestamp_us);
                    }

                    if target > Instant::now() {
                        tokio::time::sleep_until(target).await;
                    }

                    local_count += processed;

                    if local_count > 100 {
                        progress.inc(local_count);
                        local_count = 0;
                    }
                }

                progress.inc(local_count);

                Ok::<_, anyhow::Error>(request_latencies)
            }));
        }
    }

    let mut latencies = Vec::new();

    for task in tasks {
        latencies.extend(task.await??);
    }

385
    if progress.elapsed() > Duration::from_millis(benchmark_duration_ms * 11 / 10) {
Yan Ru Pei's avatar
Yan Ru Pei committed
386
387
388
389
390
        eprintln!(
            "WARNING: The benchmarker is unable to keep up with the request/event generation rate. Rerun with a larger --benchmark-duration-ms."
        )
    }

391
    let total_duration = progress.elapsed();
Yan Ru Pei's avatar
Yan Ru Pei committed
392
393
394
395
396
397
398
399
400
401

    let total_events = worker_traces
        .iter()
        .map(|trace| {
            trace
                .iter()
                .filter(|trace| matches!(trace.entry, WorkerTraceEntry::Event(_)))
                .count()
        })
        .sum::<usize>()
402
        * args.common.inference_worker_duplication_factor;
Yan Ru Pei's avatar
Yan Ru Pei committed
403
404

    let total_requests = worker_traces.iter().map(|trace| trace.len()).sum::<usize>()
405
        * args.common.inference_worker_duplication_factor
Yan Ru Pei's avatar
Yan Ru Pei committed
406
407
        - total_events;

408
409
410
411
412
413
414
415
    let total_request_blocks: usize = worker_traces
        .iter()
        .flat_map(|t| t.iter())
        .filter_map(|entry| match &entry.entry {
            WorkerTraceEntry::Request(hashes) => Some(hashes.len()),
            _ => None,
        })
        .sum::<usize>()
416
        * args.common.inference_worker_duplication_factor;
Yan Ru Pei's avatar
Yan Ru Pei committed
417

418
419
420
421
422
423
424
425
426
427
428
    let total_event_blocks: usize = worker_traces
        .iter()
        .flat_map(|t| t.iter())
        .filter_map(|entry| match &entry.entry {
            WorkerTraceEntry::Event(ev) => match &ev.data {
                KvCacheEventData::Stored(s) => Some(s.blocks.len()),
                _ => Some(0),
            },
            _ => None,
        })
        .sum::<usize>()
429
        * args.common.inference_worker_duplication_factor;
Yan Ru Pei's avatar
Yan Ru Pei committed
430

431
432
    let counted_events = if count_events { total_events } else { 0 };
    let counted_event_blocks = if count_events { total_event_blocks } else { 0 };
Yan Ru Pei's avatar
Yan Ru Pei committed
433

434
435
    let total_blocks = total_request_blocks + counted_event_blocks;
    let total_ops = total_requests + counted_events;
436
437
438
439
    let offered_ops_throughput = total_ops as f32 / benchmark_duration_ms as f32 * 1000.0;
    let ops_throughput = total_ops as f32 / total_duration.as_millis() as f32 * 1000.0;
    let offered_block_throughput = total_blocks as f32 / benchmark_duration_ms as f32 * 1000.0;
    let block_throughput = total_blocks as f32 / total_duration.as_millis() as f32 * 1000.0;
Yan Ru Pei's avatar
Yan Ru Pei committed
440
441

    latencies.sort_unstable();
442
443
444
445
446
    let latency_p99_us = if latencies.is_empty() {
        0.0
    } else {
        latencies[latencies.len() * 99 / 100] as f32 / 1000.0
    };
447

Yan Ru Pei's avatar
Yan Ru Pei committed
448
    println!(
449
450
        "Ops Throughput: {} ops/s (requests + events)",
        ops_throughput
Yan Ru Pei's avatar
Yan Ru Pei committed
451
    );
452
453
454
455
456
457
458
459
460
461
462
    println!("Block Throughput: {} block ops/s", block_throughput);
    println!("Latency p99: {}us", latency_p99_us);

    Ok(BenchmarkResults {
        offered_ops_throughput,
        ops_throughput,
        offered_block_throughput,
        block_throughput,
        latency_p99_us,
    })
}
Yan Ru Pei's avatar
Yan Ru Pei committed
463

464
465
fn run_tests() -> anyhow::Result<()> {
    use std::collections::HashSet;
466
    use std::fs::File;
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
    use std::io::Write;

    let path =
        std::env::temp_dir().join(format!("mooncake_bench_test_{}.jsonl", std::process::id()));
    {
        let mut f = File::create(&path)?;
        for (i, (hash_ids, output_length)) in
            [(&[0u64, 1, 2] as &[u64], 10u64), (&[0, 1, 3, 4], 10)]
                .iter()
                .enumerate()
        {
            writeln!(
                f,
                "{}",
                serde_json::json!({
                    "timestamp": i as u64,
                    "hash_ids": hash_ids,
                    "output_length": output_length,
                })
            )?;
        }
    }

490
    let traces = process_mooncake_trace(path.to_str().unwrap(), 2, 2, 2, 42)?;
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
    std::fs::remove_file(&path).ok();

    let mut all_hashes: Vec<Vec<u64>> = traces
        .into_iter()
        .flat_map(|w| w.into_iter().map(|r| r.hash_ids))
        .collect();
    all_hashes.sort();

    // expand(2): [0,1,2] → [0,1,2,3,4,5], [0,1,3,4] → [0,1,2,3,6,7,8,9]
    // duplicate(2): max=9, offset=10
    let mut expected = vec![
        vec![0, 1, 2, 3, 4, 5],
        vec![10, 11, 12, 13, 14, 15],
        vec![0, 1, 2, 3, 6, 7, 8, 9],
        vec![10, 11, 12, 13, 16, 17, 18, 19],
    ];
    expected.sort();
    assert_eq!(all_hashes, expected, "hash_ids mismatch");

    // Verify prefix structure within each copy.
    let copy0: Vec<&Vec<u64>> = all_hashes.iter().filter(|h| h[0] == 0).collect();
    let copy1: Vec<&Vec<u64>> = all_hashes.iter().filter(|h| h[0] == 10).collect();
    assert_eq!(copy0.len(), 2);
    assert_eq!(copy1.len(), 2);
    assert_eq!(copy0[0][..4], copy0[1][..4], "copy 0 shared prefix broken");
    assert_eq!(copy1[0][..4], copy1[1][..4], "copy 1 shared prefix broken");

    // Verify disjointness between copies.
    let set0: HashSet<u64> = copy0.iter().flat_map(|h| h.iter().copied()).collect();
    let set1: HashSet<u64> = copy1.iter().flat_map(|h| h.iter().copied()).collect();
    assert!(set0.is_disjoint(&set1), "copies are not hash-disjoint");

    println!("All tests passed.");
    Ok(())
}

Yan Ru Pei's avatar
Yan Ru Pei committed
527
528
529
530
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let args = Args::parse();

531
    if args.common.test {
532
533
534
        return run_tests();
    }

535
536
537
538
539
540
541
    let path = match args.common.mooncake_trace_path.as_deref() {
        Some(p) => p,
        None => {
            eprintln!("No mooncake_trace_path provided, skipping benchmark");
            return Ok(());
        }
    };
542
543
544
545
546
547
548
549
550
551
552
553
554
555
    let traces = process_mooncake_trace(
        path,
        args.common.trace_length_factor,
        args.common.trace_duplication_factor,
        args.common.num_unique_inference_workers,
        args.common.seed,
    )?;
    let events = generate_kv_events(
        &traces,
        args.common.num_gpu_blocks,
        args.common.block_size,
        args.common.trace_simulation_duration_ms,
    )
    .await?;
Yan Ru Pei's avatar
Yan Ru Pei committed
556

557
558
559
560
561
562
563
564
565
566
567
568
569
570
    let indexer_names: Vec<String> = if args.compare.is_empty() {
        let name = match args.get_indexer() {
            IndexerArgs::RadixTree {} => "radix-tree",
            IndexerArgs::RadixTreeSharded { .. } => "radix-tree-sharded",
            IndexerArgs::NestedMap { .. } => "nested-map",
            IndexerArgs::ConcurrentRadixTree { .. } => "concurrent-radix-tree",
            IndexerArgs::NaiveNestedMap {} => "naive-nested-map",
            IndexerArgs::InvertedIndex { .. } => "inverted-index",
        };
        vec![name.to_string()]
    } else {
        args.compare.clone()
    };

571
572
573
574
575
576
    if args.common.sweep {
        let durations_low_to_high = compute_sweep_durations(
            args.common.sweep_min_ms,
            args.common.sweep_max_ms,
            args.common.sweep_steps,
        );
577
        let durations_high_to_low: Vec<u64> = durations_low_to_high.iter().copied().rev().collect();
578
579
580
581
582
583
584
585

        let mut all_results: Vec<(&str, Vec<(u64, BenchmarkResults)>)> = Vec::new();

        for name in &indexer_names {
            println!("\n{}", "=".repeat(60));
            println!("Benchmarking indexer: {}", name);
            println!("{}", "=".repeat(60));

586
587
588
589
590
591
592
            let multi_threaded = IndexerArgs::is_multi_threaded(name);
            let durations = if multi_threaded {
                &durations_high_to_low
            } else {
                &durations_low_to_high
            };

593
            let mut results: Vec<(u64, BenchmarkResults)> = Vec::new();
594
            let mut consecutive_keeping_up = 0u32;
595

596
            for &dur_ms in durations {
597
598
                println!("\n=== Sweep: benchmark_duration_ms = {} ===", dur_ms);
                let indexer = if args.compare.is_empty() {
599
                    args.get_indexer().build(args.common.block_size)
600
                } else {
601
                    IndexerArgs::from_name(name, args.common.block_size, args.num_event_workers)?
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
627
628
629
630
631
632
                let count_events = IndexerArgs::supports_remove(name);
                let result = run_benchmark(
                    indexer,
                    traces.clone(),
                    events.clone(),
                    &args,
                    dur_ms,
                    count_events,
                )
                .await?;

                if multi_threaded {
                    if result.block_throughput >= result.offered_block_throughput * 0.95 {
                        consecutive_keeping_up += 1;
                    } else {
                        consecutive_keeping_up = 0;
                    }
                    results.push((dur_ms, result));
                    if consecutive_keeping_up >= 5 {
                        println!("Early stop: achieved >= 95% offered for 5 consecutive steps");
                        break;
                    }
                } else {
                    let saturated = result.offered_block_throughput > result.block_throughput * 5.0;
                    results.push((dur_ms, result));
                    if saturated {
                        println!("Early stop: offered throughput >5x achieved throughput");
                        break;
                    }
                }
633
634
            }

635
            results.sort_by_key(|(dur, _)| std::cmp::Reverse(*dur));
636
            print_sweep_summary(name, &results);
Yan Ru Pei's avatar
Yan Ru Pei committed
637

638
639
640
641
            all_results.push((name, results));
        }

        plot_sweep(&all_results, &args.sweep_output)?;
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667

        let json_path = args
            .sweep_output
            .replace(".png", ".json")
            .replace(".svg", ".json");
        let json_map: std::collections::BTreeMap<&str, Vec<SweepStepResult>> = all_results
            .iter()
            .map(|(name, results)| {
                let steps = results
                    .iter()
                    .map(|(dur, r)| SweepStepResult {
                        duration_ms: *dur,
                        results: BenchmarkResults {
                            offered_ops_throughput: r.offered_ops_throughput,
                            ops_throughput: r.ops_throughput,
                            offered_block_throughput: r.offered_block_throughput,
                            block_throughput: r.block_throughput,
                            latency_p99_us: r.latency_p99_us,
                        },
                    })
                    .collect();
                (*name, steps)
            })
            .collect();
        std::fs::write(&json_path, serde_json::to_string_pretty(&json_map)?)?;
        println!("Sweep results saved to {}", json_path);
668
669
670
671
    } else {
        for name in &indexer_names {
            println!("\nBenchmarking indexer: {}", name);
            let indexer = if args.compare.is_empty() {
672
                args.get_indexer().build(args.common.block_size)
673
            } else {
674
                IndexerArgs::from_name(name, args.common.block_size, args.num_event_workers)?
675
            };
676
            let count_events = IndexerArgs::supports_remove(name);
677
678
679
680
681
            run_benchmark(
                indexer,
                traces.clone(),
                events.clone(),
                &args,
682
                args.common.benchmark_duration_ms,
683
                count_events,
684
685
686
687
            )
            .await?;
        }
    }
Yan Ru Pei's avatar
Yan Ru Pei committed
688
689
690

    Ok(())
}