using System.Diagnostics; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace GrpcDataProbe; // Limits apply to the experiment itself, independently of production admission. public sealed record WorkloadSource(string Id, string RawPath, string UnsPath, string ExpectedKind = "UInt16", int ExpectedRank = -1, bool RequireChanges = false); public sealed record WorkloadOptions(string ProfileId, IReadOnlyList Sources, int Clients = 1, int RegistrationsPerClient = 1, int ViewsPerSource = 1, int DurationSeconds = 8, int SamplingMilliseconds = 100, int PublishingMilliseconds = 100, double? Deadband = null, int SlowClientCount = 0, int SlowClientMilliseconds = 0, int BrowseBurst = 0, int BrowseWorkers = 1, bool Overlap = true, bool RequireAllAdmitted = true, int HubPartitions = 4, bool CompactBatches = true); /// Measures real facade streams; it never synthesizes sources or values. public static class WorkloadEngine { public static async Task RunAsync(IDataConnection connection, ProbeCommand command, CancellationToken stop, Func? captureDiagnostics = null) { var observations = new Dictionary(); var assertions = 0; var phase = "configuration"; void Check(bool condition, string name) { if (!condition) { observations["failedCheck"] = name; throw new InvalidOperationException(name); } assertions++; } try { var options = command.Workload ?? throw new InvalidOperationException("missing workload"); Check(options.ProfileId.Length is > 0 and <= 64 && options.Sources.Count is > 0 and <= 64 && options.Sources.Select(source => source.Id).Distinct().Count() == options.Sources.Count, "bounded sources"); Check(options.Clients is > 0 and <= 64 && options.RegistrationsPerClient is > 0 and <= 256 && options.Clients * options.RegistrationsPerClient <= 4096 && options.ViewsPerSource is 1 or 2 && options.DurationSeconds is >= 2 and <= 90 && command.TimeoutSeconds >= options.DurationSeconds + 10 && options.SamplingMilliseconds is >= 0 and <= 10000 && options.PublishingMilliseconds is >= 0 and <= 10000 && options.SlowClientCount >= 0 && options.SlowClientCount <= options.Clients && options.SlowClientMilliseconds is >= 0 and <= 5000 && options.BrowseBurst is >= 0 and <= 1024 && options.BrowseWorkers is > 0 and <= 32 && options.HubPartitions is > 0 and <= 16 && options.RegistrationsPerClient * (options.Overlap ? 1 : options.Clients) >= options.Sources.Count * options.ViewsPerSource && (options.Overlap || options.Clients * options.RegistrationsPerClient <= options.Sources.Count * options.ViewsPerSource), "bounded experiment"); var budget = new DataBudget(TimeSpan.FromSeconds(5), 256, 1024 * 1024); phase = "capabilities"; var capabilities = await connection.GetCapabilitiesAsync(budget, stop); Check(capabilities.Readiness == DataReadiness.Ready, "ready workload target"); Check(!options.CompactBatches || capabilities.CompactBatches, "requested compact codec is supported"); var views = new List<(WorkloadSource Source, DataView View)>(); foreach (var source in options.Sources) { views.Add((source, new(new(command.OriginCluster, command.NamespaceUri, "string", source.RawPath), DataRealm.Raw, null, 0, source.RawPath))); if (options.ViewsPerSource == 2) { // UNS URI is a public fixture value passed explicitly, never inferred from an index. var unsUri = command.WorkloadUnsNamespaceUri ?? throw new InvalidOperationException("UNS namespace required"); views.Add((source, new(new(command.OriginCluster, unsUri, "string", source.UnsPath), DataRealm.Uns, null, 0, source.UnsPath))); } } phase = "metadata"; foreach (var chunk in views.Chunk(256)) { var metadata = await connection.GetMetadataAsync(new(chunk.Select(item => item.View).ToArray(), budget), stop); Check(metadata.Count == chunk.Length, "metadata cardinality"); for (var i = 0; i < chunk.Length; i++) Check(metadata[i].Status == DataItemStatus.Good && metadata[i].Value is { } value && value.ValueKind.ToString() == chunk[i].Source.ExpectedKind && value.ValueRank == chunk[i].Source.ExpectedRank, "observed payload kind and rank"); } phase = "browse-parent"; var browseViews = new List(); if (options.BrowseBurst > 0) foreach (var leaf in views.Select(item => item.View).DistinctBy(view => view.Realm)) { var realm = leaf.Realm.ToString().ToLowerInvariant(); if (command.WorkloadBrowseRoots is null || !command.WorkloadBrowseRoots.TryGetValue(realm, out var root) || string.IsNullOrWhiteSpace(root)) throw new InvalidOperationException("Explicit workload browse container required."); var requested = leaf with { Address = leaf.Address with { Identifier = root }, Subject = root }; browseViews.Add(await ProbeEngine.CanonicalBrowseViewAsync(connection, requested, budget, stop)); } phase = "measurement"; observations["profile"] = options; observations["serving"] = capabilities.Serving; observations["capabilities"] = new { capabilities.CompactBatches, capabilities.Limits }; observations["processBefore"] = CaptureProcess(); observations["diagnosticsBefore"] = captureDiagnostics?.Invoke(); var watch = Stopwatch.StartNew(); using var measurement = new CancellationTokenSource(TimeSpan.FromSeconds(options.DurationSeconds)); using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(stop, measurement.Token); bool MeasurementEnded() => measurement.IsCancellationRequested && !stop.IsCancellationRequested; var clients = Enumerable.Range(0, options.Clients).Select(index => RunClient(index)).ToArray(); var browse = RunBrowse(); var samples = new List(); while (!lifetime.IsCancellationRequested) { samples.Add(new { process = CaptureProcess(), diagnostics = captureDiagnostics?.Invoke() }); try { await Task.Delay(500, lifetime.Token); } catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { } } var results = await Task.WhenAll(clients); observations["clients"] = results; phase = "browse-completion"; var browseResult = await browse; phase = "reconciliation"; watch.Stop(); observations["elapsedSeconds"] = watch.Elapsed.TotalSeconds; observations["browse"] = browseResult; observations["processSamples"] = samples; observations["processAfter"] = CaptureProcess(); observations["diagnosticsAfter"] = captureDiagnostics?.Invoke(); observations["bytesDefinition"] = "serialized typed-value protobuf bytes only; excludes frame, HTTP/2 and TLS overhead"; observations["schedulingDefinition"] = "monotonic client inter-delivery gaps and first-snapshot latency; source age is reported separately"; Check(results.All(result => result.Failure is null), "all workload tasks completed"); Check(results.All(result => result.UnreadySamples == 0), "steady workload retains source readiness"); if (options.RequireAllAdmitted) { Check(results.Sum(result => result.Acknowledged) == options.Clients * options.RegistrationsPerClient, "actual acknowledged registrations"); Check(results.All(result => result.Snapshots == result.Acknowledged && result.Acknowledged > 0 && result.Controls.GetValueOrDefault("SnapshotEnd") > 0), "every registration initialized in a completed snapshot"); Check(results.All(result => result.RequiredChangingItems.All(item => item.Changes > 0)), "hot registrations progress"); Check(results.Where(result => result.Client >= options.SlowClientCount).All(result => result.RequiredChangingItems.All(item => item.ChangesAfterMidpoint > 0 && item.HotTailMilliseconds <= budget.Timeout.TotalMilliseconds)), "healthy registrations progress through final half within snapshot budget"); } else { Check(results.Any(result => result.RejectedBeforeStream), "independent bounded stream admission rejection observed"); Check(results.Any(result => result.Acknowledged > 0 && result.Snapshots == result.Acknowledged), "admitted peers retain initialized service"); } Check(browseResult.Completed == options.BrowseBurst, "concurrent browse completion"); return new(command.Id, command.Operation, true, assertions, observations); async Task RunClient(int client) { var result = new ClientResult(client); var items = new Dictionary(StringComparer.Ordinal); var handles = new Dictionary(); var id = command.Id + "-c" + client; var timer = Stopwatch.StartNew(); long sequence = 0; var snapshotOpen = false; var clientPhase = "subscribe"; try { await using var stream = await connection.SubscribeAsync(lifetime.Token); var definitions = Enumerable.Range(0, options.RegistrationsPerClient).Select(index => { var selected = views[(options.Overlap ? index : client * options.RegistrationsPerClient + index) % views.Count]; var key = "r" + index; items.Add(key, new(key, selected.Source.Id, selected.View.Realm.ToString(), selected.Source.RequireChanges)); return new DataSubscriptionItem(key, selected.View, new(TimeSpan.FromMilliseconds(options.SamplingMilliseconds), TimeSpan.FromMilliseconds(options.PublishingMilliseconds), DataChangeTrigger.StatusValue, options.Deadband)); }).ToArray(); clientPhase = "open"; await stream.SendAsync(new OpenSubscription(id, 1, "open", TimeSpan.FromSeconds(5), definitions, false, TimeSpan.FromSeconds(options.DurationSeconds + 5), budget), lifetime.Token); clientPhase = "receive"; await foreach (var frame in stream.ReadAllAsync(lifetime.Token)) { clientPhase = "frame"; result.LastFrame = new(frame.Sequence, frame.StreamEpoch, frame.GetType().Name, frame is DataSubscriptionControl marker ? marker.Kind.ToString() : null, frame is DataSubscriptionValues batch ? batch.Items.Count : null); if (frame.SubscriptionId != id || frame.StreamEpoch != 1 || frame.Sequence <= sequence) throw new InvalidOperationException("stream order"); sequence = frame.Sequence; if (frame is DataSubscriptionAck ack) { if (ack.CommandId != "open" || ack.Items.Count != definitions.Length) throw new InvalidOperationException("ack cardinality"); foreach (var entry in ack.Items) { if (!items.TryGetValue(entry.ClientItemId, out var item)) throw new InvalidOperationException("unknown ack item"); if (entry.Status == DataItemStatus.Good && entry.Handle is { } handle) { handles.Add(handle.Handle, item); item.HandleRevision = handle.ItemRevision; result.Acknowledged++; } else { result.Rejected++; result.RejectionStatuses.Add(entry.Status.ToString()); } } } else if (frame is DataSubscriptionControl control) { result.Controls[control.Kind.ToString()] = result.Controls.GetValueOrDefault(control.Kind.ToString()) + 1; if (control.Kind == DataStreamControlKind.Reset) foreach (var item in items.Values) item.Initialized = false; if (control.Kind == DataStreamControlKind.SnapshotBegin) { if (snapshotOpen) throw new InvalidOperationException("nested snapshot"); snapshotOpen = true; } if (control.Kind == DataStreamControlKind.SnapshotEnd) { if (!snapshotOpen || handles.Values.Any(item => !item.Initialized)) throw new InvalidOperationException("incomplete snapshot"); snapshotOpen = false; } } else if (frame is DataSubscriptionValues update) { using (update) { foreach (var entry in update.Items) { if (!handles.TryGetValue(entry.Handle.Handle, out var item) || entry.Handle.ItemRevision != item.HandleRevision) throw new InvalidOperationException("unacknowledged revision"); if (entry.Readiness != DataReadiness.Ready || entry.Sample.StatusCode != 0) { result.UnreadySamples++; continue; } if (!item.Initialized && !update.IsSnapshot) throw new InvalidOperationException("delta before snapshot"); if (update.IsSnapshot && !snapshotOpen) throw new InvalidOperationException("unbracketed snapshot"); var elapsed = timer.Elapsed.TotalMilliseconds; if (update.IsSnapshot && !item.Initialized) { item.Initialized = true; if (item.FirstSnapshotMilliseconds is null) { item.FirstSnapshotMilliseconds = elapsed; result.Snapshots++; } } var encoded = TypedValueCodec.Encode(entry.Sample.Value); var fingerprint = encoded.ToString(); if (item.LastFingerprint is { } previous && previous != fingerprint) { item.Changes++; if (elapsed >= options.DurationSeconds * 500) item.ChangesAfterMidpoint++; } item.LastFingerprint = fingerprint; if (item.LastDeliveryMilliseconds is { } last) item.DeliveryGaps.Observe(elapsed - last); item.LastDeliveryMilliseconds = elapsed; if (entry.AgeBounds.Upper is { } age) item.SourceAge.Observe(age.TotalMilliseconds); item.Samples++; item.TypedValueBytes += encoded.CalculateSize(); } } if (client < options.SlowClientCount && options.SlowClientMilliseconds > 0) await Task.Delay(options.SlowClientMilliseconds, lifetime.Token); } clientPhase = "receive"; } clientPhase = "end"; if (!MeasurementEnded()) throw new InvalidOperationException("Stream ended before the scheduled measurement deadline."); } catch (OperationCanceledException) when (MeasurementEnded()) { } catch (Grpc.Core.RpcException error) when (error.StatusCode == Grpc.Core.StatusCode.Cancelled && MeasurementEnded()) { } catch (InvalidOperationException error) when (!options.RequireAllAdmitted && error.Message == "Stream capacity exhausted.") { result.RejectedBeforeStream = true; } catch (Exception error) when (error is not OutOfMemoryException) { result.Failure = FailureCode(error); result.FailurePhase = clientPhase; result.FailureMilliseconds = timer.Elapsed.TotalMilliseconds; } foreach (var item in items.Values) item.HotTailMilliseconds = item.LastDeliveryMilliseconds is { } last ? timer.Elapsed.TotalMilliseconds - last : timer.Elapsed.TotalMilliseconds; result.Items = items.Values.ToArray(); return result; } async Task RunBrowse() { var completed = 0; var latency = new BoundedHistogram(); using var slots = new SemaphoreSlim(options.BrowseWorkers); await Task.WhenAll(Enumerable.Range(0, options.BrowseBurst).Select(async index => { await slots.WaitAsync(stop); try { var timer = Stopwatch.StartNew(); var view = browseViews[index % browseViews.Count]; var branch = await connection.BrowseAsync(new(view, null, null, budget), stop); if (branch.Status != DataItemStatus.Good) throw new BrowseResponseFailure(branch.Status, view.Realm); lock (latency) { latency.Observe(timer.Elapsed.TotalMilliseconds); completed++; } } finally { slots.Release(); } })); return new(completed, latency); } } catch (Exception error) when (error is not OutOfMemoryException) { observations["failurePhase"] = phase; if (error is BrowseResponseFailure browse) observations["browseFailure"] = new { status = browse.Status.ToString(), realm = browse.Realm.ToString() }; return new(command.Id, command.Operation, false, assertions, observations, FailureCode(error)); } } // Emit only fixed local reasons and the enum transport status. private static string FailureCode(Exception error) => error switch { Grpc.Core.RpcException rpc => "rpc:" + rpc.StatusCode, BrowseResponseFailure => "workload-browse-status", InvalidOperationException invalid => invalid.Message switch { "Stream ended before the scheduled measurement deadline." => "early-stream-end", "Unexpected stream epoch or sequence." => "remote-order", "Response serving identity changed." => "serving-identity", "Duplicate handle or sample version regression." => "remote-version-or-handle", "Canonical browse parent metadata unavailable." => "browse-parent-metadata", "No ready authenticated data endpoint." => "no-ready-endpoint", "No ready subscription endpoint." => "no-ready-subscription-endpoint", "Data endpoint discovery is backing off." => "endpoint-backoff", "Unknown acknowledgement." => "remote-ack", "Acknowledgement expired." => "remote-ack-expired", "stream order" => "workload-order", "ack cardinality" => "workload-ack-cardinality", "unknown ack item" => "workload-ack-item", "nested snapshot" => "workload-nested-snapshot", "incomplete snapshot" => "workload-incomplete-snapshot", "unacknowledged revision" => "workload-handle", "delta before snapshot" => "workload-delta-before-snapshot", "unbracketed snapshot" => "workload-unbracketed-snapshot", _ => nameof(InvalidOperationException) }, _ => error.GetType().Name }; private sealed class BrowseResponseFailure(DataItemStatus status, DataRealm realm) : Exception { internal DataItemStatus Status { get; } = status; internal DataRealm Realm { get; } = realm; } public static object CaptureProcess() { using var process = Process.GetCurrentProcess(); var gc = GC.GetGCMemoryInfo(); return new { atUtc = DateTimeOffset.UtcNow, processId = Environment.ProcessId, process.WorkingSet64, process.PrivateMemorySize64, totalProcessorMilliseconds = process.TotalProcessorTime.TotalMilliseconds, managedBytes = GC.GetTotalMemory(false), gc.HeapSizeBytes, gc.FragmentedBytes, gc.TotalCommittedBytes, gc.MemoryLoadBytes, collections = new[] { GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2) }, threadCount = process.Threads.Count }; } public sealed class ClientResult(int client) { public int Client { get; } = client; public int Acknowledged { get; set; } public int Rejected { get; set; } public bool RejectedBeforeStream { get; set; } public int Snapshots { get; set; } public long UnreadySamples { get; set; } public HashSet RejectionStatuses { get; } = new(); public Dictionary Controls { get; } = new(); public IReadOnlyList Items { get; set; } = []; public IEnumerable RequiredChangingItems => Items.Where(item => item.RequireChanges); public string? Failure { get; set; } public string? FailurePhase { get; set; } public double? FailureMilliseconds { get; set; } public FrameReceipt? LastFrame { get; set; } } public sealed record FrameReceipt(long Sequence, long Epoch, string Kind, string? Control, int? Items); public sealed class ItemResult(string id, string sourceId, string realm, bool requireChanges) { public string Id { get; } = id; public string SourceId { get; } = sourceId; public string Realm { get; } = realm; public bool RequireChanges { get; } = requireChanges; public long HandleRevision { get; set; } public bool Initialized { get; set; } public long Samples { get; set; } public long Changes { get; set; } public long ChangesAfterMidpoint { get; set; } public double HotTailMilliseconds { get; set; } public long TypedValueBytes { get; set; } public double? FirstSnapshotMilliseconds { get; set; } public BoundedHistogram DeliveryGaps { get; } = new(); public BoundedHistogram SourceAge { get; } = new(); [System.Text.Json.Serialization.JsonIgnore] public string? LastFingerprint { get; set; } [System.Text.Json.Serialization.JsonIgnore] public double? LastDeliveryMilliseconds { get; set; } } public sealed record BrowseResult(int Completed, BoundedHistogram Latency); // Fixed logarithmic buckets bound memory regardless of delivery rate. public sealed class BoundedHistogram { private readonly long[] _buckets = new long[256]; public long Count { get; private set; } public double Maximum { get; private set; } public double? P95 => Quantile(.95); public double? P99 => Quantile(.99); public void Observe(double value) { if (!double.IsFinite(value) || value < 0) throw new ArgumentOutOfRangeException(nameof(value)); _buckets[Math.Min(255, (int)(Math.Log2(value + 1) * 16))]++; Count++; Maximum = Math.Max(Maximum, value); } private double? Quantile(double fraction) { if (Count == 0) return null; var target = (long)Math.Ceiling(Count * fraction); long seen = 0; for (var i = 0; i < _buckets.Length; i++) { seen += _buckets[i]; if (seen >= target) return Math.Min(Maximum, Math.Pow(2, (i + 1) / 16d) - 1); } return Maximum; } } }