//! `bench-read-bulk` command: ReadBulk stress benchmark and latency statistics. use std::time::{Duration, Instant}; use serde_json::json; use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::{ CloseSessionRequest, OpenSessionRequest, }; use zb_mom_ww_mxgateway_client::{next_correlation_id, Error}; use crate::cli::*; use crate::connect::*; /// Drive the cross-language ReadBulk stress benchmark from Rust: opens its /// own session, subscribes to `bulk_size` tags so the worker's per-session /// value cache populates from real OnDataChange events, hammers ReadBulk in /// a tight loop for `duration_seconds` with per-call latency capture, and /// emits the shared JSON stats schema the `scripts/bench-read-bulk.ps1` /// driver collates across all five clients. #[allow(clippy::too_many_arguments)] pub(crate) async fn run_bench_read_bulk( connection: ConnectionArgs, client_name: String, duration_seconds: u64, warmup_seconds: u64, bulk_size: usize, tag_start: i32, tag_prefix: String, tag_attribute: String, timeout_ms: u32, json: bool, ) -> Result<(), Error> { if bulk_size == 0 { return Err(Error::InvalidArgument { name: "bulk-size".to_owned(), detail: "bulk-size must be positive".to_owned(), }); } if duration_seconds == 0 { return Err(Error::InvalidArgument { name: "duration-seconds".to_owned(), detail: "duration-seconds must be positive".to_owned(), }); } // Build TestMachine_NNN. tags with three-digit machine numbers // matching the existing cross-language tag-discovery convention. let tags: Vec = (0..bulk_size) .map(|index| { format!( "{prefix}{number:03}.{attr}", prefix = tag_prefix, number = tag_start + index as i32, attr = tag_attribute, ) }) .collect(); let endpoint = connection.endpoint.clone(); let client = connect(connection).await?; let session = client .open_session(OpenSessionRequest { client_session_name: client_name.clone(), ..OpenSessionRequest::default() }) .await?; let session_id = session.id().to_owned(); // Subscribe so the worker's MxAccessValueCache populates from real // OnDataChange events before the measurement window opens. Any per-tag // failures fall through silently; the bench is still meaningful for the // successfully-subscribed subset. let bench_outcome = async { let server_handle = session.register(&client_name).await?; let subscribe_results = session.subscribe_bulk(server_handle, tags.clone()).await?; let tags_ref: &[String] = &tags; let item_handles: Vec = subscribe_results .iter() .filter(|r| r.was_successful) .map(|r| r.item_handle) .collect(); let timeout_ms_param = timeout_ms; // Warm-up: drive identical calls so any connection-pool / channel // setup is amortised before the measurement window opens. let warmup_deadline = Instant::now() + Duration::from_secs(warmup_seconds); while Instant::now() < warmup_deadline { let _ = session .read_bulk(server_handle, tags_ref, timeout_ms_param) .await; } // Steady-state measurement window: capture per-call latency as // sub-millisecond f64 deltas from Instant::now() so the histogram // resolution matches the .NET Stopwatch / Go time.Now path. let mut latencies_ms: Vec = Vec::with_capacity(65_536); let mut total_read_results: i64 = 0; let mut cached_read_results: i64 = 0; let mut successful_calls: u64 = 0; let mut failed_calls: u64 = 0; let steady_start = Instant::now(); let steady_deadline = steady_start + Duration::from_secs(duration_seconds); while Instant::now() < steady_deadline { let call_start = Instant::now(); let result = session .read_bulk(server_handle, tags_ref, timeout_ms_param) .await; let elapsed = call_start.elapsed(); latencies_ms.push(elapsed.as_secs_f64() * 1000.0); match result { Ok(results) => { successful_calls += 1; for r in &results { total_read_results += 1; if r.was_cached { cached_read_results += 1; } } } Err(_) => failed_calls += 1, } } let steady_elapsed = steady_start.elapsed(); // Best-effort cleanup: unsubscribe so the worker can release cache slots. if !item_handles.is_empty() { let _ = session.unsubscribe_bulk(server_handle, item_handles).await; } let total_calls = successful_calls + failed_calls; let calls_per_second = if steady_elapsed.as_secs_f64() > 0.0 { total_calls as f64 / steady_elapsed.as_secs_f64() } else { 0.0 }; Ok::<_, Error>(BenchStats { endpoint, client_name, bulk_size, duration_seconds, warmup_seconds, duration_ms: steady_elapsed.as_millis() as u64, tags: tags.clone(), total_calls, successful_calls, failed_calls, total_read_results, cached_read_results, calls_per_second, latencies_ms, }) } .await; // Always close the session, even if the bench loop returned an error. let close_result = client .close_session_raw(CloseSessionRequest { session_id: session_id.clone(), client_correlation_id: next_correlation_id("cli-bench-read-bulk-close"), }) .await; let stats = bench_outcome?; // Closing the session is best-effort; never let it mask a real bench error. let _ = close_result; if json { let latency = percentile_summary(&stats.latencies_ms); let payload = json!({ "language": "rust", "command": "bench-read-bulk", "endpoint": stats.endpoint, "clientName": stats.client_name, "bulkSize": stats.bulk_size, "durationSeconds": stats.duration_seconds, "warmupSeconds": stats.warmup_seconds, "durationMs": stats.duration_ms, "tags": stats.tags, "totalCalls": stats.total_calls, "successfulCalls": stats.successful_calls, "failedCalls": stats.failed_calls, "totalReadResults": stats.total_read_results, "cachedReadResults": stats.cached_read_results, "callsPerSecond": round_to(stats.calls_per_second, 2), "latencyMs": { "p50": round_to(latency.p50, 3), "p95": round_to(latency.p95, 3), "p99": round_to(latency.p99, 3), "max": round_to(latency.max, 3), "mean": round_to(latency.mean, 3), }, }); println!("{payload}"); } else { println!("{}", stats.calls_per_second); } Ok(()) } /// Collected bench-read-bulk measurements; carried in one struct so the /// async block can finish cleanup (unsubscribe, close-session) before the /// caller renders the JSON / plain output. pub(crate) struct BenchStats { endpoint: String, client_name: String, bulk_size: usize, duration_seconds: u64, warmup_seconds: u64, duration_ms: u64, tags: Vec, total_calls: u64, successful_calls: u64, failed_calls: u64, total_read_results: i64, cached_read_results: i64, calls_per_second: f64, latencies_ms: Vec, } /// The same `{ p50, p95, p99, max, mean }` shape every language bench emits. /// `p50`/`p95`/`p99` use nearest-rank with linear interpolation, matching the /// .NET / Go implementations so cross-language comparisons are apples-to-apples. pub(crate) struct LatencySummary { pub(crate) p50: f64, pub(crate) p95: f64, pub(crate) p99: f64, pub(crate) max: f64, pub(crate) mean: f64, } pub(crate) fn percentile_summary(sample: &[f64]) -> LatencySummary { if sample.is_empty() { return LatencySummary { p50: 0.0, p95: 0.0, p99: 0.0, max: 0.0, mean: 0.0, }; } let mut sorted: Vec = sample.to_vec(); sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); let max = sorted[sorted.len() - 1]; let mean: f64 = sample.iter().copied().sum::() / sample.len() as f64; LatencySummary { p50: percentile(&sorted, 0.50), p95: percentile(&sorted, 0.95), p99: percentile(&sorted, 0.99), max, mean, } } pub(crate) fn percentile(sorted: &[f64], quantile: f64) -> f64 { if sorted.is_empty() { return 0.0; } if sorted.len() == 1 { return sorted[0]; } let rank = quantile * (sorted.len() - 1) as f64; let lower = rank.floor() as usize; let upper = lower + 1; if upper >= sorted.len() { return sorted[lower]; } let fraction = rank - lower as f64; sorted[lower] + (sorted[upper] - sorted[lower]) * fraction } pub(crate) fn round_to(value: f64, digits: u32) -> f64 { let shift = 10f64.powi(digits as i32); (value * shift).round() / shift } /// Run the `bench` command group. pub(crate) async fn run(command: Command) -> Result<(), Error> { match command { Command::BenchReadBulk { connection, client_name, duration_seconds, warmup_seconds, bulk_size, tag_start, tag_prefix, tag_attribute, timeout_ms, json, } => { run_bench_read_bulk( connection, client_name, duration_seconds, warmup_seconds, bulk_size, tag_start, tag_prefix, tag_attribute, timeout_ms, json, ) .await?; } _ => unreachable!("command routed to the wrong group"), } Ok(()) }