const std = @import("std"); const abi = @import("../abi.zig"); const config = @import("../config.zig"); const contracts = @import("../contracts.zig"); const transport = @import("../protocol/transport.zig"); pub const TimeoutPhase = transport.TimeoutPhase; pub const Sample = struct { duration_nanos: u64, bytes_sent: u64, bytes_received: u64, success: bool, checks_passed: u32 = 0, checks_failed: u32 = 0, transport_code: abi.TransportCode = .none, timeout_phase: TimeoutPhase = .none, grpc_status: ?u8 = null, grpc_deadline_exceeded: bool = false, request_name: ?[]const u8 = null, }; // A fixed log-scale histogram keeps percentile tracking allocation-free during long runs. // The base of 1.02 bounds percentile overestimation to roughly 2% while still covering a // very large dynamic range with 2048 buckets. const duration_histogram_bucket_count = 2048; const duration_histogram_base: f64 = 1.02; const DurationHistogram = struct { counts: [duration_histogram_bucket_count]u64 = [_]u64{0} ** duration_histogram_bucket_count, samples: u64 = 0, fn record(self: *DurationHistogram, value: u64) void { self.counts[durationBucketIndex(value)] += 1; self.samples += 1; } fn percentile(self: *const DurationHistogram, percent: usize) u64 { if (self.samples == 0) return 0; const target: u64 = @intCast(((self.samples - 1) * percent) / 100 + 1); var cumulative: u64 = 0; for (self.counts, 0..) |count, index| { cumulative += count; if (cumulative >= target) return durationBucketUpperBound(index); } return durationBucketUpperBound(duration_histogram_bucket_count - 1); } fn mergeFrom(self: *DurationHistogram, other: *const DurationHistogram) void { for (&self.counts, other.counts) |*count, other_count| { count.* += other_count; } self.samples += other.samples; } }; const RequestMetricsWindow = struct { histogram: DurationHistogram = .{}, requests_total: u64 = 0, requests_failed: u64 = 0, transport_errors_total: u64 = 0, transport_errors_timeout: u64 = 0, transport_errors_connect_timeout: u64 = 0, transport_errors_io_timeout: u64 = 0, grpc_status_counts: [17]u64 = [_]u64{0} ** 17, grpc_deadline_exceeded_total: u64 = 0, checks_passed_total: u64 = 0, checks_failed_total: u64 = 0, duration_total_nanos: u128 = 0, duration_min_nanos: u64 = 0, duration_max_nanos: u64 = 0, fn deinit(self: *RequestMetricsWindow, allocator: std.mem.Allocator) void { _ = allocator; self.* = .{}; } fn appendRequest(self: *RequestMetricsWindow, allocator: std.mem.Allocator, sample: Sample) !void { _ = allocator; self.histogram.record(sample.duration_nanos); self.requests_total += 1; self.duration_total_nanos += sample.duration_nanos; if (self.duration_min_nanos == 0 or sample.duration_nanos < self.duration_min_nanos) { self.duration_min_nanos = sample.duration_nanos; } if (sample.duration_nanos > self.duration_max_nanos) { self.duration_max_nanos = sample.duration_nanos; } if (!sample.success) self.requests_failed += 1; if (sample.transport_code != .none) { self.transport_errors_total += 1; if (sample.transport_code == .timeout) { self.transport_errors_timeout += 1; switch (sample.timeout_phase) { .none => {}, .connect => self.transport_errors_connect_timeout += 1, .io => self.transport_errors_io_timeout += 1, } } } if (sample.grpc_status) |grpc_status| { if (grpc_status < self.grpc_status_counts.len) { self.grpc_status_counts[grpc_status] += 1; } } if (sample.grpc_deadline_exceeded) { self.grpc_deadline_exceeded_total += 1; } self.checks_passed_total += sample.checks_passed; self.checks_failed_total += sample.checks_failed; } fn mergeFrom(self: *RequestMetricsWindow, other: *const RequestMetricsWindow) void { self.histogram.mergeFrom(&other.histogram); self.requests_total += other.requests_total; self.requests_failed += other.requests_failed; self.transport_errors_total += other.transport_errors_total; self.transport_errors_timeout += other.transport_errors_timeout; self.transport_errors_connect_timeout += other.transport_errors_connect_timeout; self.transport_errors_io_timeout += other.transport_errors_io_timeout; for (&self.grpc_status_counts, other.grpc_status_counts) |*count, other_count| { count.* += other_count; } self.grpc_deadline_exceeded_total += other.grpc_deadline_exceeded_total; self.checks_passed_total += other.checks_passed_total; self.checks_failed_total += other.checks_failed_total; self.duration_total_nanos += other.duration_total_nanos; self.duration_min_nanos = mergeMinDuration(self.duration_min_nanos, other.duration_min_nanos); self.duration_max_nanos = @max(self.duration_max_nanos, other.duration_max_nanos); } }; pub const MetricsWindow = struct { histogram: DurationHistogram = .{}, request_windows: std.StringHashMapUnmanaged(RequestMetricsWindow) = .empty, requests_total: u64 = 0, requests_failed: u64 = 0, iterations_total: u64 = 0, iterations_failed: u64 = 0, dropped_iterations: u64 = 0, bytes_sent: u64 = 0, bytes_received: u64 = 0, duration_total_nanos: u128 = 0, duration_min_nanos: u64 = 0, duration_max_nanos: u64 = 0, scheduler_lag_samples: u64 = 0, scheduler_lag_total_nanos: u128 = 0, scheduler_lag_max_nanos: u64 = 0, transport_errors_total: u64 = 0, transport_errors_dns: u64 = 0, transport_errors_connect: u64 = 0, transport_errors_tls: u64 = 0, transport_errors_write: u64 = 0, transport_errors_read: u64 = 0, transport_errors_timeout: u64 = 0, transport_errors_connect_timeout: u64 = 0, transport_errors_io_timeout: u64 = 0, transport_errors_protocol: u64 = 0, grpc_status_counts: [17]u64 = [_]u64{0} ** 17, grpc_deadline_exceeded_total: u64 = 0, checks_passed_total: u64 = 0, checks_failed_total: u64 = 0, script_errors_total: u64 = 0, script_timeouts_total: u64 = 0, hard_timeouts_total: u64 = 0, poisoned_workers_total: u64 = 0, vus_recreated_total: u64 = 0, unhealthy_vus_total: u64 = 0, spare_vus_activated_total: u64 = 0, pub fn deinit(self: *MetricsWindow, allocator: std.mem.Allocator) void { var request_iter = self.request_windows.iterator(); while (request_iter.next()) |entry| { allocator.free(entry.key_ptr.*); entry.value_ptr.deinit(allocator); } self.request_windows.deinit(allocator); self.* = .{}; } pub fn appendRequest(self: *MetricsWindow, allocator: std.mem.Allocator, sample: Sample) !void { self.histogram.record(sample.duration_nanos); self.requests_total += 1; self.bytes_sent += sample.bytes_sent; self.bytes_received += sample.bytes_received; self.duration_total_nanos += sample.duration_nanos; if (self.duration_min_nanos == 0 or sample.duration_nanos < self.duration_min_nanos) { self.duration_min_nanos = sample.duration_nanos; } if (sample.duration_nanos > self.duration_max_nanos) { self.duration_max_nanos = sample.duration_nanos; } if (!sample.success) { self.requests_failed += 1; } if (sample.transport_code != .none) { self.transport_errors_total += 1; switch (sample.transport_code) { .none => {}, .dns => self.transport_errors_dns += 1, .connect => self.transport_errors_connect += 1, .tls => self.transport_errors_tls += 1, .write => self.transport_errors_write += 1, .read => self.transport_errors_read += 1, .timeout => { self.transport_errors_timeout += 1; switch (sample.timeout_phase) { .none => {}, .connect => self.transport_errors_connect_timeout += 1, .io => self.transport_errors_io_timeout += 1, } }, .protocol => self.transport_errors_protocol += 1, } } if (sample.request_name) |request_name| { try self.appendRequestWindow(allocator, request_name, sample); } if (sample.grpc_status) |grpc_status| { if (grpc_status < self.grpc_status_counts.len) { self.grpc_status_counts[grpc_status] += 1; } } if (sample.grpc_deadline_exceeded) { self.grpc_deadline_exceeded_total += 1; } self.checks_passed_total += sample.checks_passed; self.checks_failed_total += sample.checks_failed; } fn appendRequestWindow(self: *MetricsWindow, allocator: std.mem.Allocator, request_name: []const u8, sample: Sample) !void { if (self.request_windows.getPtr(request_name)) |window| { try window.appendRequest(allocator, sample); return; } const owned_name = try allocator.dupe(u8, request_name); errdefer allocator.free(owned_name); var window = RequestMetricsWindow{}; errdefer window.deinit(allocator); try window.appendRequest(allocator, sample); try self.request_windows.put(allocator, owned_name, window); } pub fn addDropped(self: *MetricsWindow, count: u64) void { self.dropped_iterations += count; } pub fn recordSchedulerLag(self: *MetricsWindow, lag_nanos: u64) void { self.scheduler_lag_samples += 1; self.scheduler_lag_total_nanos += lag_nanos; if (lag_nanos > self.scheduler_lag_max_nanos) { self.scheduler_lag_max_nanos = lag_nanos; } } pub fn recordIteration(self: *MetricsWindow, success: bool) void { self.iterations_total += 1; if (!success) self.iterations_failed += 1; } pub fn recordScriptError(self: *MetricsWindow) void { self.script_errors_total += 1; } pub fn recordScriptTimeout(self: *MetricsWindow) void { self.script_timeouts_total += 1; } pub fn recordHardTimeout(self: *MetricsWindow) void { self.hard_timeouts_total += 1; } pub fn recordPoisonedWorker(self: *MetricsWindow) void { self.poisoned_workers_total += 1; } pub fn recordVuRecreated(self: *MetricsWindow) void { self.vus_recreated_total += 1; } pub fn recordUnhealthyVu(self: *MetricsWindow) void { self.unhealthy_vus_total += 1; } pub fn recordSpareVuActivated(self: *MetricsWindow) void { self.spare_vus_activated_total += 1; } pub fn mergeFrom(self: *MetricsWindow, allocator: std.mem.Allocator, other: *const MetricsWindow) !void { self.histogram.mergeFrom(&other.histogram); self.requests_total += other.requests_total; self.requests_failed += other.requests_failed; self.iterations_total += other.iterations_total; self.iterations_failed += other.iterations_failed; self.dropped_iterations += other.dropped_iterations; self.bytes_sent += other.bytes_sent; self.bytes_received += other.bytes_received; self.duration_total_nanos += other.duration_total_nanos; self.duration_min_nanos = mergeMinDuration(self.duration_min_nanos, other.duration_min_nanos); self.duration_max_nanos = @max(self.duration_max_nanos, other.duration_max_nanos); self.scheduler_lag_samples += other.scheduler_lag_samples; self.scheduler_lag_total_nanos += other.scheduler_lag_total_nanos; self.scheduler_lag_max_nanos = @max(self.scheduler_lag_max_nanos, other.scheduler_lag_max_nanos); self.transport_errors_total += other.transport_errors_total; self.transport_errors_dns += other.transport_errors_dns; self.transport_errors_connect += other.transport_errors_connect; self.transport_errors_tls += other.transport_errors_tls; self.transport_errors_write += other.transport_errors_write; self.transport_errors_read += other.transport_errors_read; self.transport_errors_timeout += other.transport_errors_timeout; self.transport_errors_connect_timeout += other.transport_errors_connect_timeout; self.transport_errors_io_timeout += other.transport_errors_io_timeout; self.transport_errors_protocol += other.transport_errors_protocol; for (&self.grpc_status_counts, other.grpc_status_counts) |*count, other_count| { count.* += other_count; } self.grpc_deadline_exceeded_total += other.grpc_deadline_exceeded_total; self.checks_passed_total += other.checks_passed_total; self.checks_failed_total += other.checks_failed_total; self.script_errors_total += other.script_errors_total; self.script_timeouts_total += other.script_timeouts_total; self.hard_timeouts_total += other.hard_timeouts_total; self.poisoned_workers_total += other.poisoned_workers_total; self.vus_recreated_total += other.vus_recreated_total; self.unhealthy_vus_total += other.unhealthy_vus_total; self.spare_vus_activated_total += other.spare_vus_activated_total; var request_iter = other.request_windows.iterator(); while (request_iter.next()) |entry| { if (self.request_windows.getPtr(entry.key_ptr.*)) |existing| { existing.mergeFrom(entry.value_ptr); continue; } const owned_name = try allocator.dupe(u8, entry.key_ptr.*); errdefer allocator.free(owned_name); try self.request_windows.put(allocator, owned_name, entry.value_ptr.*); } } }; pub const HistogramSnapshot = struct { counts: []u64, samples: u64, pub fn deinit(self: *HistogramSnapshot, allocator: std.mem.Allocator) void { allocator.free(self.counts); self.* = undefined; } }; pub const RequestMetricsWindowSnapshot = struct { name: []const u8, histogram: HistogramSnapshot, requests_total: u64 = 0, requests_failed: u64 = 0, transport_errors_total: u64 = 0, transport_errors_timeout: u64 = 0, transport_errors_connect_timeout: u64 = 0, transport_errors_io_timeout: u64 = 0, grpc_status_counts: [17]u64 = [_]u64{0} ** 17, grpc_deadline_exceeded_total: u64 = 0, checks_passed_total: u64 = 0, checks_failed_total: u64 = 0, duration_total_nanos: u128 = 0, duration_min_nanos: u64 = 0, duration_max_nanos: u64 = 0, pub fn deinit(self: *RequestMetricsWindowSnapshot, allocator: std.mem.Allocator) void { allocator.free(self.name); self.histogram.deinit(allocator); self.* = undefined; } }; pub const MetricsWindowSnapshot = struct { histogram: HistogramSnapshot, request_windows: []RequestMetricsWindowSnapshot = &.{}, requests_total: u64 = 0, requests_failed: u64 = 0, iterations_total: u64 = 0, iterations_failed: u64 = 0, dropped_iterations: u64 = 0, bytes_sent: u64 = 0, bytes_received: u64 = 0, duration_total_nanos: u128 = 0, duration_min_nanos: u64 = 0, duration_max_nanos: u64 = 0, scheduler_lag_samples: u64 = 0, scheduler_lag_total_nanos: u128 = 0, scheduler_lag_max_nanos: u64 = 0, transport_errors_total: u64 = 0, transport_errors_dns: u64 = 0, transport_errors_connect: u64 = 0, transport_errors_tls: u64 = 0, transport_errors_write: u64 = 0, transport_errors_read: u64 = 0, transport_errors_timeout: u64 = 0, transport_errors_connect_timeout: u64 = 0, transport_errors_io_timeout: u64 = 0, transport_errors_protocol: u64 = 0, grpc_status_counts: [17]u64 = [_]u64{0} ** 17, grpc_deadline_exceeded_total: u64 = 0, checks_passed_total: u64 = 0, checks_failed_total: u64 = 0, script_errors_total: u64 = 0, script_timeouts_total: u64 = 0, hard_timeouts_total: u64 = 0, poisoned_workers_total: u64 = 0, vus_recreated_total: u64 = 0, unhealthy_vus_total: u64 = 0, spare_vus_activated_total: u64 = 0, pub fn deinit(self: *MetricsWindowSnapshot, allocator: std.mem.Allocator) void { self.histogram.deinit(allocator); for (self.request_windows) |*entry| entry.deinit(allocator); if (self.request_windows.len != 0) allocator.free(self.request_windows); self.* = undefined; } }; pub const AggregatorSnapshot = struct { warmup: MetricsWindowSnapshot, measured: MetricsWindowSnapshot, interrupted: bool, pub fn deinit(self: *AggregatorSnapshot, allocator: std.mem.Allocator) void { self.warmup.deinit(allocator); self.measured.deinit(allocator); self.* = undefined; } }; pub const WindowSummary = struct { requests_total: u64, requests_failed: u64, iterations_total: u64, iterations_failed: u64, dropped_iterations: u64, bytes_sent: u64, bytes_received: u64, scheduler_lag_avg_nanos: u64, scheduler_lag_max_nanos: u64, error_rate: f64, success_rate: f64, duration_min_nanos: u64, duration_max_nanos: u64, duration_avg_nanos: u64, duration_p50_nanos: u64, duration_p90_nanos: u64, duration_p99_nanos: u64, transport_errors_total: u64, transport_errors_dns: u64, transport_errors_connect: u64, transport_errors_tls: u64, transport_errors_write: u64, transport_errors_read: u64, transport_errors_timeout: u64, transport_errors_connect_timeout: u64, transport_errors_io_timeout: u64, transport_errors_protocol: u64, grpc_deadline_exceeded_total: u64, grpc_status_counts: []const StatusCount = &.{}, checks_passed_total: u64 = 0, checks_failed_total: u64 = 0, check_pass_rate: f64 = 0, script_errors_total: u64, script_timeouts_total: u64, hard_timeouts_total: u64, poisoned_workers_total: u64, vus_recreated_total: u64, unhealthy_vus_total: u64, spare_vus_activated_total: u64, request_summaries: []const NamedRequestSummary = &.{}, pub fn deinit(self: *WindowSummary, allocator: std.mem.Allocator) void { if (self.grpc_status_counts.len != 0) allocator.free(self.grpc_status_counts); for (self.request_summaries) |request_summary| { allocator.free(request_summary.name); if (request_summary.summary.grpc_status_counts.len != 0) { allocator.free(request_summary.summary.grpc_status_counts); } } if (self.request_summaries.len != 0) allocator.free(self.request_summaries); self.* = undefined; } }; pub const StatusCount = struct { status: u8, count: u64, }; pub const RequestSummary = struct { requests_total: u64, requests_failed: u64, error_rate: f64, duration_p50_nanos: u64, duration_p90_nanos: u64, duration_p99_nanos: u64, transport_errors_total: u64, transport_errors_timeout: u64, transport_errors_connect_timeout: u64, transport_errors_io_timeout: u64, grpc_deadline_exceeded_total: u64, grpc_status_counts: []const StatusCount = &.{}, checks_passed_total: u64 = 0, checks_failed_total: u64 = 0, check_pass_rate: f64 = 0, transport_error_rate: f64, transport_timeout_rate: f64, transport_connect_timeout_rate: f64, transport_io_timeout_rate: f64, }; pub const NamedRequestSummary = struct { name: []const u8, summary: RequestSummary, }; pub const FinalSummary = struct { allocator: std.mem.Allocator, output: Output, threshold_failed: bool, pub const Output = struct { schema_version: u32, scenario_name: []const u8, scenario_mode: []const u8, wasm_backend: []const u8, interrupted: bool, measured: WindowSummary, warmup: WindowSummary, thresholds_failed: bool, }; pub fn deinit(self: *FinalSummary) void { self.output.measured.deinit(self.allocator); self.output.warmup.deinit(self.allocator); self.* = undefined; } }; pub const MetricsAggregator = struct { allocator: std.mem.Allocator, mutex: std.Thread.Mutex = .{}, warmup: MetricsWindow = .{}, measured: MetricsWindow = .{}, pub fn deinit(self: *MetricsAggregator) void { self.warmup.deinit(self.allocator); self.measured.deinit(self.allocator); } pub fn recordRequest(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128, sample: Sample) !void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; try window.appendRequest(self.allocator, sample); } pub fn recordIteration(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128, success: bool) void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; window.recordIteration(success); } pub fn recordDrop(self: *MetricsAggregator, warmup: bool, count: u64) void { self.mutex.lock(); defer self.mutex.unlock(); if (warmup) { self.warmup.addDropped(count); } else { self.measured.addDropped(count); } } pub fn recordSchedulerLag(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128, lag_nanos: u64) void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; window.recordSchedulerLag(lag_nanos); } pub fn recordScriptError(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128) void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; window.recordScriptError(); } pub fn recordScriptTimeout(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128) void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; window.recordScriptTimeout(); } pub fn recordHardTimeout(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128) void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; window.recordHardTimeout(); } pub fn recordPoisonedWorker(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128) void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; window.recordPoisonedWorker(); } pub fn recordVuRecreated(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128) void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; window.recordVuRecreated(); } pub fn recordUnhealthyVu(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128) void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; window.recordUnhealthyVu(); } pub fn recordSpareVuActivated(self: *MetricsAggregator, started_nanos: i128, warmup_end_nanos: i128) void { self.mutex.lock(); defer self.mutex.unlock(); const window = if (started_nanos < warmup_end_nanos) &self.warmup else &self.measured; window.recordSpareVuActivated(); } pub fn finalize(self: *MetricsAggregator, allocator: std.mem.Allocator, scenario: *const config.ScenarioConfig, interrupted: bool) !FinalSummary { return self.finalizeWithOptions(allocator, scenario, interrupted, true); } pub fn finalizeWithOptions( self: *MetricsAggregator, allocator: std.mem.Allocator, scenario: *const config.ScenarioConfig, interrupted: bool, evaluate_thresholds: bool, ) !FinalSummary { self.mutex.lock(); defer self.mutex.unlock(); const warmup_summary = try summarizeWindow(allocator, &self.warmup); const measured_summary = try summarizeWindow(allocator, &self.measured); const threshold_failed = if (evaluate_thresholds) try evaluateThresholds(allocator, measured_summary, &self.measured, scenario) else false; return .{ .allocator = allocator, .output = .{ .schema_version = contracts.summary_schema_version, .scenario_name = scenario.scenario.name, .scenario_mode = scenario.scenario.mode().label(), .wasm_backend = scenario.scenario.wasm_backend.label(), .interrupted = interrupted, .measured = measured_summary, .warmup = warmup_summary, .thresholds_failed = threshold_failed, }, .threshold_failed = threshold_failed, }; } pub fn shouldAbortOnFail(self: *MetricsAggregator, scenario: *const config.ScenarioConfig) !bool { self.mutex.lock(); defer self.mutex.unlock(); var summary = try summarizeWindow(self.allocator, &self.measured); defer summary.deinit(self.allocator); for (scenario.thresholds) |threshold| { if (!threshold.abort_on_fail) continue; if (!thresholdAppliesToScenario(threshold, scenario)) continue; if (!try thresholdMatches(self.allocator, threshold, summary, &self.measured)) return true; } return false; } pub fn mergeFrom(self: *MetricsAggregator, other: *MetricsAggregator) !void { self.mutex.lock(); defer self.mutex.unlock(); other.mutex.lock(); defer other.mutex.unlock(); try self.warmup.mergeFrom(self.allocator, &other.warmup); try self.measured.mergeFrom(self.allocator, &other.measured); } pub fn snapshot(self: *MetricsAggregator, allocator: std.mem.Allocator, interrupted: bool) !AggregatorSnapshot { self.mutex.lock(); defer self.mutex.unlock(); return .{ .warmup = try snapshotWindow(allocator, &self.warmup), .measured = try snapshotWindow(allocator, &self.measured), .interrupted = interrupted, }; } pub fn mergeSnapshot(self: *MetricsAggregator, snapshot_value: *const AggregatorSnapshot) !void { self.mutex.lock(); defer self.mutex.unlock(); try mergeWindowSnapshot(&self.warmup, self.allocator, &snapshot_value.warmup); try mergeWindowSnapshot(&self.measured, self.allocator, &snapshot_value.measured); } }; pub fn summarizeWindow(allocator: std.mem.Allocator, window: *const MetricsWindow) !WindowSummary { const request_summaries = try summarizeRequestWindows(allocator, window); const grpc_status_counts = try summarizeGrpcStatusCounts(allocator, &window.grpc_status_counts); return .{ .requests_total = window.requests_total, .requests_failed = window.requests_failed, .iterations_total = window.iterations_total, .iterations_failed = window.iterations_failed, .dropped_iterations = window.dropped_iterations, .bytes_sent = window.bytes_sent, .bytes_received = window.bytes_received, .scheduler_lag_avg_nanos = if (window.scheduler_lag_samples == 0) 0 else @intCast(window.scheduler_lag_total_nanos / window.scheduler_lag_samples), .scheduler_lag_max_nanos = window.scheduler_lag_max_nanos, .error_rate = ratio(window.requests_failed, window.requests_total), .success_rate = ratio(window.iterations_total - window.iterations_failed, window.iterations_total), .duration_min_nanos = window.duration_min_nanos, .duration_max_nanos = window.duration_max_nanos, .duration_avg_nanos = if (window.requests_total == 0) 0 else @intCast(window.duration_total_nanos / window.requests_total), .duration_p50_nanos = window.histogram.percentile(50), .duration_p90_nanos = window.histogram.percentile(90), .duration_p99_nanos = window.histogram.percentile(99), .transport_errors_total = window.transport_errors_total, .transport_errors_dns = window.transport_errors_dns, .transport_errors_connect = window.transport_errors_connect, .transport_errors_tls = window.transport_errors_tls, .transport_errors_write = window.transport_errors_write, .transport_errors_read = window.transport_errors_read, .transport_errors_timeout = window.transport_errors_timeout, .transport_errors_connect_timeout = window.transport_errors_connect_timeout, .transport_errors_io_timeout = window.transport_errors_io_timeout, .transport_errors_protocol = window.transport_errors_protocol, .grpc_deadline_exceeded_total = window.grpc_deadline_exceeded_total, .grpc_status_counts = grpc_status_counts, .checks_passed_total = window.checks_passed_total, .checks_failed_total = window.checks_failed_total, .check_pass_rate = ratio(window.checks_passed_total, window.checks_passed_total + window.checks_failed_total), .script_errors_total = window.script_errors_total, .script_timeouts_total = window.script_timeouts_total, .hard_timeouts_total = window.hard_timeouts_total, .poisoned_workers_total = window.poisoned_workers_total, .vus_recreated_total = window.vus_recreated_total, .unhealthy_vus_total = window.unhealthy_vus_total, .spare_vus_activated_total = window.spare_vus_activated_total, .request_summaries = request_summaries, }; } fn durationBucketIndex(value: u64) usize { if (value == 0) return 0; const raw_index = @log(@as(f64, @floatFromInt(value))) / @log(duration_histogram_base); const bounded = @min( @as(usize, @intFromFloat(@floor(raw_index))) + 1, duration_histogram_bucket_count - 1, ); return bounded; } fn mergeMinDuration(current: u64, candidate: u64) u64 { if (current == 0) return candidate; if (candidate == 0) return current; return @min(current, candidate); } fn durationBucketUpperBound(index: usize) u64 { if (index == 0) return 0; if (index >= duration_histogram_bucket_count - 1) return std.math.maxInt(u64); const upper = @exp(@log(duration_histogram_base) * @as(f64, @floatFromInt(index))); return @max(@as(u64, 1), @as(u64, @intFromFloat(@ceil(upper)))); } fn snapshotWindow(allocator: std.mem.Allocator, window: *const MetricsWindow) !MetricsWindowSnapshot { return .{ .histogram = .{ .counts = try allocator.dupe(u64, &window.histogram.counts), .samples = window.histogram.samples, }, .request_windows = try snapshotRequestWindows(allocator, window), .requests_total = window.requests_total, .requests_failed = window.requests_failed, .iterations_total = window.iterations_total, .iterations_failed = window.iterations_failed, .dropped_iterations = window.dropped_iterations, .bytes_sent = window.bytes_sent, .bytes_received = window.bytes_received, .duration_total_nanos = window.duration_total_nanos, .duration_min_nanos = window.duration_min_nanos, .duration_max_nanos = window.duration_max_nanos, .scheduler_lag_samples = window.scheduler_lag_samples, .scheduler_lag_total_nanos = window.scheduler_lag_total_nanos, .scheduler_lag_max_nanos = window.scheduler_lag_max_nanos, .transport_errors_total = window.transport_errors_total, .transport_errors_dns = window.transport_errors_dns, .transport_errors_connect = window.transport_errors_connect, .transport_errors_tls = window.transport_errors_tls, .transport_errors_write = window.transport_errors_write, .transport_errors_read = window.transport_errors_read, .transport_errors_timeout = window.transport_errors_timeout, .transport_errors_connect_timeout = window.transport_errors_connect_timeout, .transport_errors_io_timeout = window.transport_errors_io_timeout, .transport_errors_protocol = window.transport_errors_protocol, .grpc_status_counts = window.grpc_status_counts, .grpc_deadline_exceeded_total = window.grpc_deadline_exceeded_total, .checks_passed_total = window.checks_passed_total, .checks_failed_total = window.checks_failed_total, .script_errors_total = window.script_errors_total, .script_timeouts_total = window.script_timeouts_total, .hard_timeouts_total = window.hard_timeouts_total, .poisoned_workers_total = window.poisoned_workers_total, .vus_recreated_total = window.vus_recreated_total, .unhealthy_vus_total = window.unhealthy_vus_total, .spare_vus_activated_total = window.spare_vus_activated_total, }; } fn snapshotRequestWindows(allocator: std.mem.Allocator, window: *const MetricsWindow) ![]RequestMetricsWindowSnapshot { if (window.request_windows.count() == 0) return &.{}; var entries = try allocator.alloc(RequestMetricsWindowSnapshot, window.request_windows.count()); errdefer { for (entries[0..window.request_windows.count()]) |*entry| { if (entry.name.len != 0) entry.deinit(allocator); } allocator.free(entries); } var index: usize = 0; var iterator = window.request_windows.iterator(); while (iterator.next()) |entry| { entries[index] = .{ .name = try allocator.dupe(u8, entry.key_ptr.*), .histogram = .{ .counts = try allocator.dupe(u64, &entry.value_ptr.histogram.counts), .samples = entry.value_ptr.histogram.samples, }, .requests_total = entry.value_ptr.requests_total, .requests_failed = entry.value_ptr.requests_failed, .transport_errors_total = entry.value_ptr.transport_errors_total, .transport_errors_timeout = entry.value_ptr.transport_errors_timeout, .transport_errors_connect_timeout = entry.value_ptr.transport_errors_connect_timeout, .transport_errors_io_timeout = entry.value_ptr.transport_errors_io_timeout, .grpc_status_counts = entry.value_ptr.grpc_status_counts, .grpc_deadline_exceeded_total = entry.value_ptr.grpc_deadline_exceeded_total, .checks_passed_total = entry.value_ptr.checks_passed_total, .checks_failed_total = entry.value_ptr.checks_failed_total, .duration_total_nanos = entry.value_ptr.duration_total_nanos, .duration_min_nanos = entry.value_ptr.duration_min_nanos, .duration_max_nanos = entry.value_ptr.duration_max_nanos, }; index += 1; } std.sort.block(RequestMetricsWindowSnapshot, entries, {}, struct { fn lessThan(_: void, left: RequestMetricsWindowSnapshot, right: RequestMetricsWindowSnapshot) bool { return std.mem.lessThan(u8, left.name, right.name); } }.lessThan); return entries; } fn mergeWindowSnapshot(window: *MetricsWindow, allocator: std.mem.Allocator, snapshot: *const MetricsWindowSnapshot) !void { if (snapshot.histogram.counts.len != duration_histogram_bucket_count) return error.InvalidMetricsSnapshot; for (&window.histogram.counts, snapshot.histogram.counts) |*count, other_count| { count.* += other_count; } window.histogram.samples += snapshot.histogram.samples; window.requests_total += snapshot.requests_total; window.requests_failed += snapshot.requests_failed; window.iterations_total += snapshot.iterations_total; window.iterations_failed += snapshot.iterations_failed; window.dropped_iterations += snapshot.dropped_iterations; window.bytes_sent += snapshot.bytes_sent; window.bytes_received += snapshot.bytes_received; window.duration_total_nanos += snapshot.duration_total_nanos; window.duration_min_nanos = mergeMinDuration(window.duration_min_nanos, snapshot.duration_min_nanos); window.duration_max_nanos = @max(window.duration_max_nanos, snapshot.duration_max_nanos); window.scheduler_lag_samples += snapshot.scheduler_lag_samples; window.scheduler_lag_total_nanos += snapshot.scheduler_lag_total_nanos; window.scheduler_lag_max_nanos = @max(window.scheduler_lag_max_nanos, snapshot.scheduler_lag_max_nanos); window.transport_errors_total += snapshot.transport_errors_total; window.transport_errors_dns += snapshot.transport_errors_dns; window.transport_errors_connect += snapshot.transport_errors_connect; window.transport_errors_tls += snapshot.transport_errors_tls; window.transport_errors_write += snapshot.transport_errors_write; window.transport_errors_read += snapshot.transport_errors_read; window.transport_errors_timeout += snapshot.transport_errors_timeout; window.transport_errors_connect_timeout += snapshot.transport_errors_connect_timeout; window.transport_errors_io_timeout += snapshot.transport_errors_io_timeout; window.transport_errors_protocol += snapshot.transport_errors_protocol; for (&window.grpc_status_counts, snapshot.grpc_status_counts) |*count, other_count| { count.* += other_count; } window.grpc_deadline_exceeded_total += snapshot.grpc_deadline_exceeded_total; window.checks_passed_total += snapshot.checks_passed_total; window.checks_failed_total += snapshot.checks_failed_total; window.script_errors_total += snapshot.script_errors_total; window.script_timeouts_total += snapshot.script_timeouts_total; window.hard_timeouts_total += snapshot.hard_timeouts_total; window.poisoned_workers_total += snapshot.poisoned_workers_total; window.vus_recreated_total += snapshot.vus_recreated_total; window.unhealthy_vus_total += snapshot.unhealthy_vus_total; window.spare_vus_activated_total += snapshot.spare_vus_activated_total; for (snapshot.request_windows) |request_window| { try mergeRequestWindowSnapshot(window, allocator, &request_window); } } fn mergeRequestWindowSnapshot(window: *MetricsWindow, allocator: std.mem.Allocator, snapshot: *const RequestMetricsWindowSnapshot) !void { if (snapshot.histogram.counts.len != duration_histogram_bucket_count) return error.InvalidMetricsSnapshot; if (window.request_windows.getPtr(snapshot.name)) |existing| { mergeRequestWindowSnapshotInto(existing, snapshot); return; } const owned_name = try allocator.dupe(u8, snapshot.name); errdefer allocator.free(owned_name); var request_window = RequestMetricsWindow{}; mergeRequestWindowSnapshotInto(&request_window, snapshot); try window.request_windows.put(allocator, owned_name, request_window); } fn mergeRequestWindowSnapshotInto(window: *RequestMetricsWindow, snapshot: *const RequestMetricsWindowSnapshot) void { for (&window.histogram.counts, snapshot.histogram.counts) |*count, other_count| { count.* += other_count; } window.histogram.samples += snapshot.histogram.samples; window.requests_total += snapshot.requests_total; window.requests_failed += snapshot.requests_failed; window.transport_errors_total += snapshot.transport_errors_total; window.transport_errors_timeout += snapshot.transport_errors_timeout; window.transport_errors_connect_timeout += snapshot.transport_errors_connect_timeout; window.transport_errors_io_timeout += snapshot.transport_errors_io_timeout; for (&window.grpc_status_counts, snapshot.grpc_status_counts) |*count, other_count| { count.* += other_count; } window.grpc_deadline_exceeded_total += snapshot.grpc_deadline_exceeded_total; window.checks_passed_total += snapshot.checks_passed_total; window.checks_failed_total += snapshot.checks_failed_total; window.duration_total_nanos += snapshot.duration_total_nanos; window.duration_min_nanos = mergeMinDuration(window.duration_min_nanos, snapshot.duration_min_nanos); window.duration_max_nanos = @max(window.duration_max_nanos, snapshot.duration_max_nanos); } fn ratio(numerator: u64, denominator: u64) f64 { if (denominator == 0) return 0; return @as(f64, @floatFromInt(numerator)) / @as(f64, @floatFromInt(denominator)); } fn evaluateThresholds( allocator: std.mem.Allocator, summary: WindowSummary, measured_window: *const MetricsWindow, scenario: *const config.ScenarioConfig, ) !bool { for (scenario.thresholds) |threshold| { if (!thresholdAppliesToScenario(threshold, scenario)) continue; if (!try thresholdMatches(allocator, threshold, summary, measured_window)) return true; } return false; } fn thresholdAppliesToScenario(threshold: config.Threshold, scenario: *const config.ScenarioConfig) bool { if (threshold.scope.scenario) |scenario_name| { if (!std.mem.eql(u8, scenario_name, scenario.scenario.name)) return false; } if (threshold.scope.protocol) |protocol| { if (protocol != scenario.scenario.protocol) return false; } return true; } fn resolveThresholdActual( allocator: std.mem.Allocator, threshold: config.Threshold, summary: WindowSummary, measured_window: ?*const MetricsWindow, ) !config.ThresholdValue { if (threshold.scope.request) |request_name| { const window = measured_window.?; const request_summary = summarizeRequestScope(allocator, window, request_name).?; return switch (threshold.metric) { .http_request_duration_p50 => .{ .duration = .{ .nanos = request_summary.duration_p50_nanos } }, .http_request_duration_p90 => .{ .duration = .{ .nanos = request_summary.duration_p90_nanos } }, .http_request_duration_p99 => .{ .duration = .{ .nanos = request_summary.duration_p99_nanos } }, .http_error_rate => .{ .ratio = request_summary.error_rate }, .http_transport_error_total => .{ .integer = request_summary.transport_errors_total }, .http_transport_error_rate => .{ .ratio = request_summary.transport_error_rate }, .http_transport_timeout_total => .{ .integer = request_summary.transport_errors_timeout }, .http_transport_timeout_rate => .{ .ratio = request_summary.transport_timeout_rate }, .http_transport_connect_timeout_total => .{ .integer = request_summary.transport_errors_connect_timeout }, .http_transport_connect_timeout_rate => .{ .ratio = request_summary.transport_connect_timeout_rate }, .http_transport_io_timeout_total => .{ .integer = request_summary.transport_errors_io_timeout }, .http_transport_io_timeout_rate => .{ .ratio = request_summary.transport_io_timeout_rate }, .check_failed_total => .{ .integer = request_summary.checks_failed_total }, .check_pass_rate => .{ .ratio = request_summary.check_pass_rate }, else => unreachable, }; } return switch (threshold.metric) { .http_request_duration_p50 => .{ .duration = .{ .nanos = summary.duration_p50_nanos } }, .http_request_duration_p90 => .{ .duration = .{ .nanos = summary.duration_p90_nanos } }, .http_request_duration_p99 => .{ .duration = .{ .nanos = summary.duration_p99_nanos } }, .http_error_rate => .{ .ratio = summary.error_rate }, .http_transport_error_total => .{ .integer = summary.transport_errors_total }, .http_transport_error_rate => .{ .ratio = ratio(summary.transport_errors_total, summary.requests_total) }, .http_transport_timeout_total => .{ .integer = summary.transport_errors_timeout }, .http_transport_timeout_rate => .{ .ratio = ratio(summary.transport_errors_timeout, summary.requests_total) }, .http_transport_connect_timeout_total => .{ .integer = summary.transport_errors_connect_timeout }, .http_transport_connect_timeout_rate => .{ .ratio = ratio(summary.transport_errors_connect_timeout, summary.requests_total) }, .http_transport_io_timeout_total => .{ .integer = summary.transport_errors_io_timeout }, .http_transport_io_timeout_rate => .{ .ratio = ratio(summary.transport_errors_io_timeout, summary.requests_total) }, .check_failed_total => .{ .integer = summary.checks_failed_total }, .check_pass_rate => .{ .ratio = summary.check_pass_rate }, .scheduler_lag_avg => .{ .duration = .{ .nanos = summary.scheduler_lag_avg_nanos } }, .scheduler_lag_max => .{ .duration = .{ .nanos = summary.scheduler_lag_max_nanos } }, .iteration_dropped => .{ .integer = summary.dropped_iterations }, .iteration_success_rate => .{ .ratio = summary.success_rate }, }; } fn thresholdMatches( allocator: std.mem.Allocator, threshold: config.Threshold, summary: WindowSummary, measured_window: *const MetricsWindow, ) !bool { if (threshold.expression_clauses.len == 0) { const actual = try resolveThresholdActual(allocator, threshold, summary, measured_window); return compareThreshold(actual, threshold.op, threshold.value); } return switch (threshold.expression_mode.?) { .all_of => blk: { for (threshold.expression_clauses) |clause| { const actual = try resolveThresholdClauseActual(allocator, threshold.scope, clause, summary, measured_window); if (!compareThreshold(actual, clause.op, clause.value)) break :blk false; } break :blk true; }, .any_of => blk: { for (threshold.expression_clauses) |clause| { const actual = try resolveThresholdClauseActual(allocator, threshold.scope, clause, summary, measured_window); if (compareThreshold(actual, clause.op, clause.value)) break :blk true; } break :blk false; }, }; } fn resolveThresholdClauseActual( allocator: std.mem.Allocator, scope: config.ThresholdScope, clause: config.ThresholdClause, summary: WindowSummary, measured_window: *const MetricsWindow, ) !config.ThresholdValue { return try resolveThresholdActual(allocator, .{ .metric = clause.metric, .scope = scope, .op = clause.op, .value = clause.value, }, summary, measured_window); } fn summarizeRequestScope(allocator: std.mem.Allocator, window: *const MetricsWindow, request_name: []const u8) ?RequestSummary { const request_window = window.request_windows.get(request_name) orelse return null; const grpc_status_counts = summarizeGrpcStatusCounts(allocator, &request_window.grpc_status_counts) catch return null; return .{ .requests_total = request_window.requests_total, .requests_failed = request_window.requests_failed, .error_rate = ratio(request_window.requests_failed, request_window.requests_total), .duration_p50_nanos = request_window.histogram.percentile(50), .duration_p90_nanos = request_window.histogram.percentile(90), .duration_p99_nanos = request_window.histogram.percentile(99), .transport_errors_total = request_window.transport_errors_total, .transport_errors_timeout = request_window.transport_errors_timeout, .transport_errors_connect_timeout = request_window.transport_errors_connect_timeout, .transport_errors_io_timeout = request_window.transport_errors_io_timeout, .grpc_deadline_exceeded_total = request_window.grpc_deadline_exceeded_total, .grpc_status_counts = grpc_status_counts, .checks_passed_total = request_window.checks_passed_total, .checks_failed_total = request_window.checks_failed_total, .check_pass_rate = ratio(request_window.checks_passed_total, request_window.checks_passed_total + request_window.checks_failed_total), .transport_error_rate = ratio(request_window.transport_errors_total, request_window.requests_total), .transport_timeout_rate = ratio(request_window.transport_errors_timeout, request_window.requests_total), .transport_connect_timeout_rate = ratio(request_window.transport_errors_connect_timeout, request_window.requests_total), .transport_io_timeout_rate = ratio(request_window.transport_errors_io_timeout, request_window.requests_total), }; } fn summarizeRequestWindows(allocator: std.mem.Allocator, window: *const MetricsWindow) ![]const NamedRequestSummary { var out = std.ArrayList(NamedRequestSummary).empty; defer { for (out.items) |item| { if (item.summary.grpc_status_counts.len != 0) { allocator.free(item.summary.grpc_status_counts); } } out.deinit(allocator); } var iter = window.request_windows.iterator(); while (iter.next()) |entry| { const summary = summarizeRequestScope(allocator, window, entry.key_ptr.*) orelse continue; try out.append(allocator, .{ .name = try allocator.dupe(u8, entry.key_ptr.*), .summary = summary, }); } std.sort.block(NamedRequestSummary, out.items, {}, struct { fn lessThan(_: void, lhs: NamedRequestSummary, rhs: NamedRequestSummary) bool { return std.mem.lessThan(u8, lhs.name, rhs.name); } }.lessThan); return try out.toOwnedSlice(allocator); } fn summarizeGrpcStatusCounts(allocator: std.mem.Allocator, counts: *const [17]u64) ![]const StatusCount { var out = std.ArrayList(StatusCount).empty; defer out.deinit(allocator); for (counts, 0..) |count, index| { if (count == 0) continue; try out.append(allocator, .{ .status = @intCast(index), .count = count, }); } return try out.toOwnedSlice(allocator); } test "summarize window duplicates request names from metrics storage" { var window = MetricsWindow{}; defer window.deinit(std.testing.allocator); try window.appendRequest(std.testing.allocator, .{ .duration_nanos = 1, .bytes_sent = 1, .bytes_received = 1, .success = true, .request_name = "health", }); var iterator = window.request_windows.iterator(); const stored_name = iterator.next().?.key_ptr.*; var summary = try summarizeWindow(std.testing.allocator, &window); defer summary.deinit(std.testing.allocator); try std.testing.expectEqualStrings("health", summary.request_summaries[0].name); try std.testing.expect(summary.request_summaries[0].name.ptr != stored_name.ptr); } fn compareThreshold(actual: config.ThresholdValue, op: config.ThresholdOperator, expected: config.ThresholdValue) bool { const lhs = thresholdScalar(actual); const rhs = thresholdScalar(expected); return switch (op) { .lt => lhs < rhs, .lte => lhs <= rhs, .gt => lhs > rhs, .gte => lhs >= rhs, .eq => lhs == rhs, }; } fn thresholdScalar(value: config.ThresholdValue) f64 { return switch (value) { .duration => |duration| @floatFromInt(duration.nanos), .ratio => |ratio_value| ratio_value, .integer => |integer| @floatFromInt(integer), .float => |float_value| float_value, }; }