knishio-cli 0.1.4

KnishIO validator orchestration CLI — Docker control, cell management, benchmarks, and health checks
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//! Benchmark plan execution — reads a SQLite plan and injects molecules
//! into validator endpoint(s) via GraphQL, measuring latency and throughput.

use anyhow::{Context, Result};
use indicatif::{ProgressBar, ProgressStyle};
use rusqlite::Connection;
use std::collections::HashMap;
use std::time::{Instant, SystemTime, UNIX_EPOCH};

use super::plot;

// ═══════════════════════════════════════════════════════════════
// Public Args & Types
// ═══════════════════════════════════════════════════════════════

/// Arguments for the `execute` subcommand.
pub struct ExecuteArgs {
    pub plan: String,
    pub endpoint: Option<String>,
    pub endpoints: Option<Vec<String>>,
    pub strategy: Strategy,
    pub concurrency: usize,
    pub cell_slug: Option<String>,
    pub csv: Option<String>,
    pub plot: Option<String>,
    pub insecure_tls: bool,
}

#[derive(Clone)]
pub enum Strategy {
    RoundRobin,
    Random,
}

// ═══════════════════════════════════════════════════════════════
// Internal Types
// ═══════════════════════════════════════════════════════════════

pub(crate) struct ExecResult {
    pub mol_type: String,
    pub phase: i32,
    pub endpoint: String,
    pub http_status: u16,
    pub validator_status: String,
    pub reason: Option<String>,
    pub latency_ms: u64,
    pub dag_index: usize,
}

struct Stats {
    count: usize,
    accepted: usize,
    rejected: usize,
    errors: usize,
    latencies: Vec<u64>,
    total_ms: u64,
}

impl Stats {
    fn new() -> Self {
        Stats {
            count: 0,
            accepted: 0,
            rejected: 0,
            errors: 0,
            latencies: Vec::new(),
            total_ms: 0,
        }
    }

    fn record(&mut self, result: &ExecResult) {
        self.count += 1;
        self.latencies.push(result.latency_ms);
        match result.validator_status.as_str() {
            "accepted" => self.accepted += 1,
            "rejected" => self.rejected += 1,
            _ => self.errors += 1,
        }
    }

    fn percentile(&self, p: f64) -> u64 {
        if self.latencies.is_empty() {
            return 0;
        }
        let mut sorted = self.latencies.clone();
        sorted.sort();
        let idx = ((sorted.len() as f64 * p / 100.0) as usize).min(sorted.len() - 1);
        sorted[idx]
    }

    fn min(&self) -> u64 {
        self.latencies.iter().copied().min().unwrap_or(0)
    }

    fn max(&self) -> u64 {
        self.latencies.iter().copied().max().unwrap_or(0)
    }

    fn avg(&self) -> f64 {
        if self.latencies.is_empty() {
            return 0.0;
        }
        self.latencies.iter().sum::<u64>() as f64 / self.latencies.len() as f64
    }

    fn throughput(&self) -> f64 {
        if self.total_ms == 0 {
            return 0.0;
        }
        self.count as f64 * 1000.0 / self.total_ms as f64
    }

    /// Throughput based on sum of individual latencies (for endpoint-level stats
    /// where wall-clock total_ms isn't tracked).
    fn throughput_from_latencies(&self) -> f64 {
        let sum: u64 = self.latencies.iter().sum();
        if sum == 0 {
            return 0.0;
        }
        self.count as f64 * 1000.0 / sum as f64
    }

    fn print_latency_line(&self) {
        println!(
            "   Latency:   min={}ms  avg={:.0}ms  p50={}ms  p95={}ms  p99={}ms  max={}ms",
            self.min(),
            self.avg(),
            self.percentile(50.0),
            self.percentile(95.0),
            self.percentile(99.0),
            self.max()
        );
    }
}

// ═══════════════════════════════════════════════════════════════
// HTTP Injection
// ═══════════════════════════════════════════════════════════════

async fn inject_molecule(
    client: &reqwest::Client,
    endpoint: &str,
    mol_json: serde_json::Value,
    mol_type: String,
    phase: i32,
) -> ExecResult {
    let gql_url = format!("{endpoint}/graphql");

    let query = serde_json::json!({
        "query": "mutation ProposeMolecule($molecule: MoleculeInput!) { ProposeMolecule(molecule: $molecule) { status molecularHash reason payload } }",
        "variables": { "molecule": mol_json }
    });

    let start = Instant::now();
    let resp = client.post(&gql_url).json(&query).send().await;
    let latency_ms = start.elapsed().as_millis() as u64;

    match resp {
        Ok(response) => {
            let http_status = response.status().as_u16();
            let body: serde_json::Value = response.json().await.unwrap_or_default();

            let status = body
                .pointer("/data/ProposeMolecule/status")
                .and_then(|v| v.as_str())
                .unwrap_or("error")
                .to_string();
            let reason = body
                .pointer("/data/ProposeMolecule/reason")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .or_else(|| {
                    body.pointer("/errors/0/message")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string())
                });

            ExecResult {
                mol_type,
                phase,
                endpoint: endpoint.to_string(),
                http_status,
                validator_status: status,
                reason,
                latency_ms,
                dag_index: 0,
            }
        }
        Err(e) => ExecResult {
            mol_type,
            phase,
            endpoint: endpoint.to_string(),
            http_status: 0,
            validator_status: "error".to_string(),
            reason: {
                let mut msg = e.to_string();
                let mut source = std::error::Error::source(&e);
                while let Some(cause) = source {
                    msg.push_str(": ");
                    msg.push_str(&cause.to_string());
                    source = std::error::Error::source(cause);
                }
                Some(msg)
            },
            latency_ms,
            dag_index: 0,
        },
    }
}

fn select_endpoint<'a>(endpoints: &'a [String], strategy: &Strategy, idx: usize) -> &'a str {
    match strategy {
        Strategy::RoundRobin => &endpoints[idx % endpoints.len()],
        Strategy::Random => {
            use rand::Rng;
            let i = rand::thread_rng().gen_range(0..endpoints.len());
            &endpoints[i]
        }
    }
}

// ═══════════════════════════════════════════════════════════════
// Execute Command
// ═══════════════════════════════════════════════════════════════

pub async fn execute(args: ExecuteArgs) -> Result<()> {
    // Resolve endpoints
    let endpoints: Vec<String> = if let Some(ref ep) = args.endpoint {
        vec![ep.clone()]
    } else if let Some(ref eps) = args.endpoints {
        eps.clone()
    } else {
        anyhow::bail!("Either --endpoint or --endpoints must be provided");
    };

    // Cell slug
    let cell_slug = args.cell_slug.unwrap_or_else(|| {
        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        format!("BENCH_CLI_{ts}")
    });

    // Open plan
    let conn = Connection::open(&args.plan)
        .with_context(|| format!("Failed to open plan file: {}", args.plan))?;

    // Read config
    let total_molecules: i64 = conn
        .query_row("SELECT COUNT(*) FROM molecules", [], |r| r.get(0))
        .context("Failed to count molecules in plan")?;

    println!();
    println!("═══════════════════════════════════════════════════════════════");
    println!(" KnishIO Benchmark Executor");
    println!("═══════════════════════════════════════════════════════════════");
    println!(" Plan:              {}", args.plan);
    println!(" Molecules:         {total_molecules}");
    println!(" Endpoints:         {}", endpoints.join(", "));
    println!(
        " Strategy:          {:?}",
        match args.strategy {
            Strategy::RoundRobin => "round-robin",
            Strategy::Random => "random",
        }
    );
    println!(" Concurrency:       {}", args.concurrency);
    println!(" Cell slug:         {cell_slug}");
    println!("═══════════════════════════════════════════════════════════════");
    println!();

    let mut client_builder =
        reqwest::Client::builder().timeout(std::time::Duration::from_secs(30));
    if args.insecure_tls {
        client_builder = client_builder.danger_accept_invalid_certs(true);
    }
    let client = client_builder
        .build()
        .context("Failed to build HTTP client")?;

    // Progress bar
    let pb = ProgressBar::new(total_molecules as u64);
    pb.set_style(
        ProgressStyle::with_template(
            " {spinner:.green} [{bar:40.cyan/blue}] {pos}/{len} ({per_sec}) {msg}",
        )
        .unwrap()
        .progress_chars("=>-"),
    );

    let mut all_results: Vec<ExecResult> = Vec::new();
    let mut phase_stats: HashMap<i32, Stats> = HashMap::new();
    let mut type_stats: HashMap<String, Stats> = HashMap::new();
    let mut endpoint_stats: HashMap<String, Stats> = HashMap::new();
    let mut rejected_details: Vec<(String, String, String)> = Vec::new();
    let mut error_details: Vec<(String, String, String, String, u16)> = Vec::new();
    let mut dag_accepted: usize = 0;

    // Phase 0 + Phase 1: sequential injection
    for phase in 0..=1 {
        let phase_name = if phase == 0 { "Auth" } else { "Setup" };
        let mut stmt = conn
            .prepare(
                "SELECT id, identity_idx, mol_type, molecular_hash, payload_json
                 FROM molecules WHERE phase = ?1 ORDER BY global_order ASC",
            )
            .context("Failed to prepare phase query")?;

        let rows: Vec<(i64, i64, String, String, String)> = stmt
            .query_map([phase], |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                ))
            })
            .context("Failed to query phase rows")?
            .filter_map(|r| r.ok())
            .collect();

        if rows.is_empty() {
            continue;
        }

        pb.set_message(format!("Phase {phase} ({phase_name})"));
        let phase_start = Instant::now();

        for (idx, (_id, _identity_idx, mol_type, mol_hash, payload_json)) in
            rows.iter().enumerate()
        {
            let mut mol_json: serde_json::Value =
                serde_json::from_str(payload_json).context("Failed to parse payload JSON")?;
            mol_json["cellSlug"] = serde_json::json!(cell_slug);

            let ep = select_endpoint(&endpoints, &args.strategy, idx);
            let mut result =
                inject_molecule(&client, ep, mol_json, mol_type.clone(), phase).await;

            if result.validator_status == "accepted" {
                dag_accepted += 1;
            }
            result.dag_index = dag_accepted;

            if result.validator_status == "rejected" {
                rejected_details.push((
                    mol_hash.clone(),
                    mol_type.clone(),
                    result.reason.clone().unwrap_or_default(),
                ));
            } else if result.validator_status != "accepted" {
                error_details.push((
                    mol_hash.clone(),
                    mol_type.clone(),
                    result.reason.clone().unwrap_or_default(),
                    result.endpoint.clone(),
                    result.http_status,
                ));
            }

            phase_stats
                .entry(phase)
                .or_insert_with(Stats::new)
                .record(&result);
            type_stats
                .entry(mol_type.clone())
                .or_insert_with(Stats::new)
                .record(&result);
            endpoint_stats
                .entry(ep.to_string())
                .or_insert_with(Stats::new)
                .record(&result);

            all_results.push(result);
            pb.inc(1);
        }

        let phase_elapsed = phase_start.elapsed().as_millis() as u64;
        if let Some(stats) = phase_stats.get_mut(&phase) {
            stats.total_ms = phase_elapsed;
        }
    }

    // Phase 2: concurrent injection
    let mut stmt = conn
        .prepare(
            "SELECT id, identity_idx, mol_type, molecular_hash, payload_json
             FROM molecules WHERE phase = 2 ORDER BY chain_order ASC, identity_idx ASC",
        )
        .context("Failed to prepare phase 2 query")?;

    let phase2_rows: Vec<(i64, i64, String, String, String)> = stmt
        .query_map([], |row| {
            Ok((
                row.get(0)?,
                row.get(1)?,
                row.get(2)?,
                row.get(3)?,
                row.get(4)?,
            ))
        })
        .context("Failed to query phase 2 rows")?
        .filter_map(|r| r.ok())
        .collect();

    // Cap concurrency to identity count
    let num_identities: usize = conn
        .query_row(
            "SELECT COUNT(DISTINCT identity_idx) FROM molecules WHERE phase = 2",
            [],
            |row| row.get(0),
        )
        .unwrap_or(args.concurrency);
    let effective_concurrency = args.concurrency.min(num_identities);

    if effective_concurrency < args.concurrency {
        eprintln!(
            " Note: concurrency capped to {} (= identity count) to preserve ContinuID chain ordering",
            effective_concurrency
        );
    }

    if !phase2_rows.is_empty() {
        pb.set_message("Phase 2 (Test)");
        let phase2_start = Instant::now();

        for chunk in phase2_rows.chunks(effective_concurrency) {
            let mut futures = Vec::new();

            for (idx, (_id, _identity_idx, mol_type, mol_hash, payload_json)) in
                chunk.iter().enumerate()
            {
                let mut mol_json: serde_json::Value =
                    serde_json::from_str(payload_json).context("Failed to parse payload JSON")?;
                mol_json["cellSlug"] = serde_json::json!(cell_slug);

                let ep = select_endpoint(
                    &endpoints,
                    &args.strategy,
                    all_results.len() + idx,
                )
                .to_string();
                let client = client.clone();
                let mol_type = mol_type.clone();
                let mol_hash = mol_hash.clone();

                futures.push(async move {
                    let result = inject_molecule(&client, &ep, mol_json, mol_type, 2).await;
                    (result, mol_hash)
                });
            }

            let results: Vec<(ExecResult, String)> =
                futures_util::future::join_all(futures).await;

            for (mut result, mol_hash) in results {
                if result.validator_status == "accepted" {
                    dag_accepted += 1;
                }
                result.dag_index = dag_accepted;

                if result.validator_status == "rejected" {
                    rejected_details.push((
                        mol_hash,
                        result.mol_type.clone(),
                        result.reason.clone().unwrap_or_default(),
                    ));
                } else if result.validator_status != "accepted" {
                    error_details.push((
                        mol_hash,
                        result.mol_type.clone(),
                        result.reason.clone().unwrap_or_default(),
                        result.endpoint.clone(),
                        result.http_status,
                    ));
                }

                phase_stats
                    .entry(2)
                    .or_insert_with(Stats::new)
                    .record(&result);
                type_stats
                    .entry(result.mol_type.clone())
                    .or_insert_with(Stats::new)
                    .record(&result);
                endpoint_stats
                    .entry(result.endpoint.clone())
                    .or_insert_with(Stats::new)
                    .record(&result);

                all_results.push(result);
                pb.inc(1);
            }
        }

        let phase2_elapsed = phase2_start.elapsed().as_millis() as u64;
        if let Some(stats) = phase_stats.get_mut(&2) {
            stats.total_ms = phase2_elapsed;
        }
    }

    pb.finish_with_message("done");

    // ── Print execution report ──
    let overall_start_to_end: u64 = phase_stats.values().map(|s| s.total_ms).sum();

    println!();
    println!("═══════════════════════════════════════════════════════════════");
    println!(" KnishIO Benchmark Execution Report");
    println!("═══════════════════════════════════════════════════════════════");
    println!(" Plan:              {}", args.plan);
    println!(" Endpoints:         {}", endpoints.join(", "));
    if effective_concurrency < args.concurrency {
        println!(
            " Concurrency:       {} (capped from {} to match identity count)",
            effective_concurrency, args.concurrency
        );
    } else {
        println!(" Concurrency:       {}", args.concurrency);
    }
    println!(" Cell slug:         {cell_slug}");
    println!();

    for (phase, label) in [
        (0, "Auth (sequential)"),
        (1, "Setup (sequential)"),
        (
            2,
            &format!("Test (concurrency={})", effective_concurrency),
        ),
    ] {
        if let Some(stats) = phase_stats.get(&phase) {
            println!(" Phase {phase} -- {label}");
            println!(
                "   Submitted: {}   Accepted: {}   Rejected: {}   Errors: {}",
                stats.count, stats.accepted, stats.rejected, stats.errors
            );
            stats.print_latency_line();
            println!("   Throughput: {:.1} mol/s", stats.throughput());
            println!();
        }
    }

    // By type breakdown
    if type_stats.len() > 1 {
        println!(" By molecule type:");
        println!(
            " {:<18} {:>6} {:>6} {:>6} {:>6} {:>6} {:>6}",
            "Type", "Count", "Avg", "P50", "P95", "P99", "Max"
        );
        println!(" {}", "-".repeat(72));
        for mol_type in &[
            "auth",
            "token-create",
            "token-request",
            "meta",
            "value-transfer",
            "rule",
            "burn",
        ] {
            if let Some(stats) = type_stats.get(*mol_type) {
                println!(
                    " {:<18} {:>6} {:>5}ms {:>5}ms {:>5}ms {:>5}ms {:>5}ms",
                    mol_type,
                    stats.count,
                    stats.avg() as u64,
                    stats.percentile(50.0),
                    stats.percentile(95.0),
                    stats.percentile(99.0),
                    stats.max()
                );
            }
        }
        println!();
    }

    // By endpoint breakdown (if multi-endpoint)
    if endpoint_stats.len() > 1 {
        println!(" By endpoint:");
        println!(
            " {:<30} {:>6} {:>6} {:>12}",
            "Endpoint", "Count", "Avg", "Throughput"
        );
        println!(" {}", "-".repeat(60));
        for (ep, stats) in &endpoint_stats {
            println!(
                " {:<30} {:>6} {:>5}ms {:>10.1} mol/s",
                ep,
                stats.count,
                stats.avg() as u64,
                stats.throughput_from_latencies()
            );
        }
        println!();
    }

    // Rejected molecules (first 20)
    if !rejected_details.is_empty() {
        println!(
            " Rejected molecules ({} total):",
            rejected_details.len()
        );
        for (hash, mol_type, reason) in rejected_details.iter().take(20) {
            let short_hash = if hash.len() > 12 {
                &hash[..12]
            } else {
                hash
            };
            println!("   hash={short_hash}... type={mol_type} reason=\"{reason}\"");
        }
        if rejected_details.len() > 20 {
            println!("   ... and {} more", rejected_details.len() - 20);
        }
        println!();
    }

    // Error molecules (first 20)
    if !error_details.is_empty() {
        println!(" Error molecules ({} total):", error_details.len());
        for (hash, mol_type, reason, endpoint, http_status) in error_details.iter().take(20) {
            let short_hash = if hash.len() > 12 {
                &hash[..12]
            } else {
                hash
            };
            println!("   hash={short_hash}... type={mol_type} endpoint={endpoint} http={http_status} reason=\"{reason}\"");
        }
        if error_details.len() > 20 {
            println!("   ... and {} more", error_details.len() - 20);
        }
        println!();
    }

    let total_accepted: usize = phase_stats.values().map(|s| s.accepted).sum();
    let total_rejected: usize = phase_stats.values().map(|s| s.rejected).sum();
    let total_errors: usize = phase_stats.values().map(|s| s.errors).sum();
    let total_count: usize = phase_stats.values().map(|s| s.count).sum();
    let overall_throughput = if overall_start_to_end > 0 {
        total_count as f64 * 1000.0 / overall_start_to_end as f64
    } else {
        0.0
    };

    if total_errors > 0 {
        println!(
            " Overall: {} molecules in {:.1}s ({:.1} mol/s) — {} accepted, {} rejected, {} errors",
            total_count,
            overall_start_to_end as f64 / 1000.0,
            overall_throughput,
            total_accepted,
            total_rejected,
            total_errors
        );
    } else {
        println!(
            " Overall: {} molecules in {:.1}s ({:.1} mol/s) — {} accepted, {} rejected",
            total_count,
            overall_start_to_end as f64 / 1000.0,
            overall_throughput,
            total_accepted,
            total_rejected
        );
    }
    println!("═══════════════════════════════════════════════════════════════");

    // Write JSON report
    let report_path = format!(
        "bench-report-{}.json",
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
    );

    let json_report = serde_json::json!({
        "plan": args.plan,
        "endpoints": endpoints,
        "concurrency": args.concurrency,
        "cell_slug": cell_slug,
        "summary": {
            "total_molecules": total_count,
            "accepted": total_accepted,
            "rejected": total_rejected,
            "errors": total_errors,
            "total_time_ms": overall_start_to_end,
            "throughput_mol_per_sec": overall_throughput,
        },
        "phases": phase_stats.iter().map(|(phase, stats)| {
            (phase.to_string(), serde_json::json!({
                "count": stats.count,
                "accepted": stats.accepted,
                "rejected": stats.rejected,
                "errors": stats.errors,
                "total_ms": stats.total_ms,
                "throughput": stats.throughput(),
                "latency": {
                    "min": stats.min(),
                    "avg": stats.avg(),
                    "p50": stats.percentile(50.0),
                    "p95": stats.percentile(95.0),
                    "p99": stats.percentile(99.0),
                    "max": stats.max(),
                }
            }))
        }).collect::<serde_json::Map<String, serde_json::Value>>(),
        "by_type": type_stats.iter().map(|(mol_type, stats)| {
            (mol_type.clone(), serde_json::json!({
                "count": stats.count,
                "accepted": stats.accepted,
                "rejected": stats.rejected,
                "avg_ms": stats.avg(),
                "p50_ms": stats.percentile(50.0),
                "p95_ms": stats.percentile(95.0),
                "p99_ms": stats.percentile(99.0),
                "max_ms": stats.max(),
            }))
        }).collect::<serde_json::Map<String, serde_json::Value>>(),
        "rejected": rejected_details.iter().map(|(hash, mol_type, reason)| {
            serde_json::json!({
                "hash": hash,
                "type": mol_type,
                "reason": reason,
            })
        }).collect::<Vec<serde_json::Value>>(),
        "errors": error_details.iter().map(|(hash, mol_type, reason, endpoint, http_status)| {
            serde_json::json!({
                "hash": hash,
                "type": mol_type,
                "reason": reason,
                "endpoint": endpoint,
                "http_status": http_status,
            })
        }).collect::<Vec<serde_json::Value>>(),
    });

    std::fs::write(
        &report_path,
        serde_json::to_string_pretty(&json_report)
            .context("Failed to serialize JSON report")?,
    )
    .with_context(|| format!("Failed to write JSON report to {report_path}"))?;

    println!();
    println!(" Report written to: {report_path}");

    // Write per-molecule latency CSV
    let csv_path = args.csv.unwrap_or_else(|| {
        report_path
            .replace("bench-report-", "bench-latency-")
            .replace(".json", ".csv")
    });
    let mut csv = String::from("dag_index,latency_ms,mol_type,phase,status\n");
    for r in &all_results {
        csv.push_str(&format!(
            "{},{},{},{},{}\n",
            r.dag_index, r.latency_ms, r.mol_type, r.phase, r.validator_status
        ));
    }
    std::fs::write(&csv_path, &csv)
        .with_context(|| format!("Failed to write latency CSV to {csv_path}"))?;
    println!(" Latency CSV written to: {csv_path}");

    // Render latency plot PNG
    let plot_path = args
        .plot
        .unwrap_or_else(|| csv_path.replace(".csv", "-plot.png"));
    match plot::render_latency_plot(&all_results, &plot_path) {
        Ok(()) => println!(" Latency plot written to: {plot_path}"),
        Err(e) => eprintln!(" Warning: failed to render plot: {e}"),
    }

    Ok(())
}