Files
lmxopcua/scripts/validation/grpc-data/probe/ProbeEngine.cs
T
Joseph Doherty 8c28506d96 fix(dataconn): #1026 name every origin reset cause; stop binding checks invalidating live sources; renew cohort leases in batches
Gate #1026 (2048 projected items, rig seed --scale 2048) still failed after #1115. Three defects, found by
first making the origin and the consumer say why:

Diagnostics (origin + consumer)
- SourceInvalidationReason (bounded enum, classified from the publisher's reason constants): counted per
  reason (`otopcua.dataconn.source.invalidations{reason}`, `Invalidate.<Reason>` in SourceIngressDiagnostics),
  recorded on the source and logged at Debug (PartitionedSampleHub.Logger).
- An interest lease records why it stopped; the origin Subscribe stream's Reset text names it ("Source
  invalidated (<reason>).", "Source retired.", "Source interest released.", "Source routing changed.",
  "Source partition reset.", "Source binding replaced.") instead of always "Source change history expired.";
  logged at Information (Released at Debug). The texts are for people/counters only: the consumer classifies
  them into ResetSourceInvalidated / ResetInterestLost (no peer branches on them; the rig probe whitelist is
  updated).
- Consumer: renewal started/succeeded/failed/budget/slot counters, RenewalFail.<point> and
  AttemptEnd.<reason> (bounded, constant keys).

1. Origin: a binding check invalidated live sources. The driver actor's source-binding retry re-walks every
   desired reference (offset 0, every <= 30 s once any one failed); for an already-bound reference it took the
   source's serialization gate, and when the poll thread was publishing that source both sides invalidated it
   (BindingContention / SerializationContention) and reset every origin stream holding it. Live s1026-c: the
   only invalidation reasons were those two (5+5 during the open, recurring every ~30 s). EnsureDriverBinding now
   answers an already-bound, current source without the gate. Live after: 0 BindingContention.

2. Consumer: per-item metadata lease renewal could not keep up. Each projected item renewed its 15 s lease with
   its own capabilities + GetMetadata pair holding a 256 KiB unary reservation; at the default 1 MiB budget four
   ran at once and the rest retried on the next 250 ms tick (~16 items/s). Live s1026-d: 155 703 renewals
   started, 153 019 refused by the unary budget, 2 564 committed; ~1900 of 2048 items stood down
   BadUserAccessDenied; 0 recovered after the origin restart. RemoteNamespaceResolver.RenewExactBatchAsync renews
   many items with one capabilities call and one GetMetadata per origin MaxBatchItems (the single-item renewal is
   now the batch of one: same checks, lease bound and commit); a cohort renews every due item of a tick in
   batches of 128, and the between-attempt renewal (every item after an origin restart) is batched too.

3. Consumer: two demands of one node in one cohort deadlocked the batch: the second joined (#969) the first's
   claim, and the batch waited for the joiner before publishing its verdict. The batch now publishes first.

Live (OrbStack rig, 160 + 1888 items, 4 Hz churn, SOURCE pair restart): s1026-f run 1 open 10.2 s, recovery
1.5 s, 0 resets of any kind; s1026-h run 2 PASS (open 3.1 s, recovery 3.6 s, 0 resets, no history-expired or
source-invalidated log line). Remaining (not fixed here): s1026-h run 1 recovered only 852 of 1888 large-mapping
items after the restart: their renewals fail in the catalog cache's predecessor-chain bound
(RenewalFail.Cache.PredecessorChain 81 163).

Tests: GrpcData1026BindingContentionTests (fails without the fast path), GrpcData1026RenewalBatchWireTests
(one tick renews all due items in one metadata call - fails with per-item renewals; two demands of one node -
fails without the ordering fix), GrpcData1026ResetReasonTests.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-05 05:43:03 -05:00

378 lines
25 KiB
C#

using System.Text.Json;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace GrpcDataProbe;
// Shared by the external wire client and the fixture-only in-process caller.
public sealed record ProbeCommand(string Id, string ConnectionId, string Operation, string Realm = "Raw",
string OriginCluster = "SOURCE", string NamespaceUri = "", string Path = "", string? Subject = null,
int TimeoutSeconds = 30, int Value = 42, string? OperationId = null, string? ExpectedNodeId = null,
string? ExpectedRole = null, string? ExpectedState = null, string? Continuation = null,
long? ExpectedCatalogRevision = null, string? ExpectedIncarnation = null, long? ExpectedGeneration = null,
WorkloadOptions? Workload = null, string? WorkloadUnsNamespaceUri = null,
IReadOnlyDictionary<string, string>? WorkloadBrowseRoots = null, int? MaximumAgeMilliseconds = 5000,
DateTimeOffset? HistoryStartUtc = null, DateTimeOffset? HistoryEndUtc = null, uint HistoryNumValues = 5);
public sealed record ProbeResult(string Id, string Operation, bool Passed, int Assertions,
Dictionary<string, object?> Observations, string? Failure = null);
public static class ProbeEngine
{
private sealed class ProbeAssertionException(string name) : Exception(name) { }
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { WriteIndented = true };
public static async Task<ProbeResult> RunAsync(IDataConnection connection, ProbeCommand command, CancellationToken stop)
{
if (command.Operation == "workload") return await WorkloadEngine.RunAsync(connection, command, stop);
var observations = new Dictionary<string, object?>();
var assertions = 0;
var phase = ProbeFailurePhase.ValidateCommand;
DataCapabilities? validatedCapabilities = null;
void Check(bool condition, string name)
{
if (!condition) throw new ProbeAssertionException(name);
assertions++;
}
try
{
if (command.TimeoutSeconds is < 1 or > 120) throw new InvalidOperationException("invalid deadline");
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(stop);
deadline.CancelAfter(TimeSpan.FromSeconds(command.TimeoutSeconds));
var ct = deadline.Token;
var budgetSeconds = command.Operation is "write" or "dedup" or "mixed-write" ? 30 : 10;
var budget = new DataBudget(TimeSpan.FromSeconds(Math.Min(command.TimeoutSeconds, budgetSeconds)), 32, 1024 * 1024);
phase = ProbeFailurePhase.GetCapabilities;
var caps = await connection.GetCapabilitiesAsync(budget, ct);
caps.Validate();
Check(caps.ProtocolMajor == 1, "protocol major");
Check(caps.ProtocolMinor >= 3 && caps.ResponseServingIdentity && caps.SubscriptionAgeReadiness, "negotiated serving and age protocol");
Check(!caps.CompactBatches || caps.CompactCodecVersion == 1, "compact negotiation");
observations["serving"] = caps.Serving;
observations["readiness"] = caps.Readiness.ToString();
observations["operations"] = caps.Operations.ToString();
observations["compact"] = caps.CompactBatches;
observations["limits"] = caps.Limits;
if (command.ExpectedNodeId is { } expectedNode) Check(caps.Serving.NodeId == expectedNode, "serving node");
if (command.ExpectedRole is { } expectedRole) Check(caps.Serving.Role == expectedRole, "serving role");
if (command.Operation == "capabilities")
{
if (command.ExpectedState is { } state) Check(caps.Readiness.ToString() == state, "expected readiness");
return new(command.Id, command.Operation, true, assertions, observations);
}
Check(caps.Readiness == DataReadiness.Ready
|| command.Operation == "read" && command.ExpectedState == "UnavailableData", "connection ready");
validatedCapabilities = caps;
var realm = Enum.Parse<DataRealm>(command.Realm, ignoreCase: true);
var view = new DataView(new(command.OriginCluster, command.NamespaceUri, "string", command.Path),
realm, null, 0, command.Subject ?? command.Path);
view.Validate();
if (command.Operation is "browse" or "continuation")
{
phase = ProbeFailurePhase.Metadata;
view = await CanonicalBrowseViewAsync(connection, view, budget, ct);
observations["browseView"] = view;
Check(view.Address.Identifier == command.Path, "canonical browse container identity");
phase = ProbeFailurePhase.Browse;
var branch = await connection.BrowseAsync(new(view, null, command.Continuation, budget with { MaxItems = 1 }), ct);
observations["status"] = branch.Status.ToString();
observations["complete"] = branch.Complete;
observations["continuation"] = branch.Continuation;
observations["items"] = branch.Items;
observations["lease"] = branch.Lease;
Check(branch.Status.ToString() == (command.ExpectedState ?? "Good"), "browse status");
Check(branch.Items.Count <= 1, "page bound");
var bytes = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.DataProtoMapper.EncodeBrowseResponse(branch).CalculateSize();
Check(bytes <= budget.MaxBytes, "browse byte budget");
observations["serializedBytes"] = bytes;
if (branch.Lease is { } lease) Check(lease.Duration > TimeSpan.Zero && lease.Duration <= caps.Limits.MaxMetadataLease, "bounded metadata lease");
if (!branch.Complete && branch.Status == DataItemStatus.Good) Check(!string.IsNullOrEmpty(branch.Continuation), "cursor present");
}
else if (command.Operation == "metadata")
{
phase = ProbeFailurePhase.Metadata;
var metadata = await connection.GetMetadataAsync(new([view], budget), ct);
Check(metadata.Count == 1, "metadata cardinality");
Check(metadata[0].Status.ToString() == (command.ExpectedState ?? "Good"), "metadata status");
observations["metadata"] = metadata[0].Value;
}
else if (command.Operation == "read")
{
phase = ProbeFailurePhase.Read;
Check(command.MaximumAgeMilliseconds is null or >= 0 and <= 30000, "bounded requested read freshness");
var maximumAge = command.MaximumAgeMilliseconds is { } milliseconds ? TimeSpan.FromMilliseconds(milliseconds) : (TimeSpan?)null;
var items = await connection.ReadAsync(new([new("one", view, maximumAge)], budget), ct);
try
{
Check(items.Count == 1 && items[0].CorrelationId == "one", "ordered read cardinality");
observations["status"] = items[0].Status.ToString();
observations["resultReadiness"] = items[0].Readiness.ToString();
observations["maximumAgeMilliseconds"] = command.MaximumAgeMilliseconds;
observations["ageBounds"] = new { lowerMilliseconds = items[0].AgeBounds.Lower?.TotalMilliseconds,
upperMilliseconds = items[0].AgeBounds.Upper?.TotalMilliseconds };
observations["sample"] = items[0].Sample is { } observedSample
? new { observedSample.StatusCode, observedSample.SourceTimestampUtc, observedSample.ServerTimestampUtc,
observedSample.Serving, observedSample.Version,
value = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.TypedValueCodec.Encode(observedSample.Value).ToString() }
: null;
if (command.ExpectedState == "UnavailableData")
{
Check(items[0].Status is DataItemStatus.WaitingForInitialData or DataItemStatus.Unavailable,
"unavailable data status");
Check(items[0].Readiness != DataReadiness.Ready, "unavailable data must not be ready");
Check(items[0].Sample is null, "unavailable data must not carry a sample");
}
else
Check(items[0].Status.ToString() == (command.ExpectedState ?? "Good"), "read status");
if (command.ExpectedState is null or "Good")
{
Check(items[0].Readiness == DataReadiness.Ready, "read result readiness");
if (maximumAge is { } boundedAge)
Check(items[0].AgeBounds.Lower is { } lower && items[0].AgeBounds.Upper is { } upper
&& lower >= TimeSpan.Zero && upper >= lower && upper <= boundedAge, "finite read age within requested bound");
Check(items[0].Sample is not null, "read sample");
var sample = items[0].Sample!;
Check(sample.StatusCode == 0, "sample quality");
Check(sample.SourceTimestampUtc != default && sample.ServerTimestampUtc != default, "sample timestamps");
}
}
finally { foreach (var item in items) item.Dispose(); }
}
else if (command.Operation is "write" or "dedup" or "mixed-write")
{
phase = ProbeFailurePhase.Metadata;
var metadata = await connection.GetMetadataAsync(new([view], budget), ct);
Check(metadata.Count == 1 && metadata[0].Value is not null, "write metadata");
var meta = metadata[0].Value!;
using var value = Scalar(meta.ValueKind, command.Value);
var item = new WriteItem("one", command.OperationId ?? Guid.NewGuid().ToString("N"), view, value,
command.ExpectedCatalogRevision ?? meta.CatalogRevision, command.ExpectedIncarnation ?? caps.Serving.Incarnation,
budget.Timeout, command.ExpectedGeneration ?? caps.Serving.ServingGeneration);
var batch = command.Operation == "mixed-write"
? new WriteBatch([item, item with { CorrelationId = "two", OperationId = Guid.NewGuid().ToString("N"),
View = view with { Address = view.Address with { Identifier = command.Path + "/absent" }, Subject = command.Path + "/absent" } }], budget)
: new WriteBatch([item], budget);
phase = ProbeFailurePhase.Write;
var outcomes = await connection.WriteAsync(batch, ct);
// Preserve bounded, non-secret outcome evidence even if an assertion below fails.
observations["outcomes"] = outcomes.Select(result => new
{
result.CorrelationId,
Outcome = new { result.Outcome.State, result.Outcome.StatusCode },
}).ToArray();
Check(outcomes.Count == batch.Items.Count, "write cardinality");
Check(outcomes[0].CorrelationId == "one", "write order");
Check(outcomes[0].Outcome.State.ToString() == (command.ExpectedState ?? "DriverConfirmedSuccess"), "write outcome");
if (command.Operation == "mixed-write") Check(outcomes[1].Outcome.State == DataWriteState.RejectedBeforeDispatch, "undispatched item");
if (command.Operation == "dedup")
{
var duplicate = await connection.WriteAsync(batch, ct);
Check(duplicate.Count == 1 && duplicate[0].Outcome.State == outcomes[0].Outcome.State, "duplicate stable outcome");
}
observations["outcomes"] = outcomes;
observations["operationId"] = item.OperationId;
}
else if (command.Operation == "subscribe")
{
phase = ProbeFailurePhase.Subscribe;
await using var subscription = await connection.SubscribeAsync(ct);
var id = Guid.NewGuid().ToString("N");
await subscription.SendAsync(new OpenSubscription(id, 1, "open", TimeSpan.FromSeconds(5),
[new("one", view, new(TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(200), DataChangeTrigger.StatusValue, null))],
false, TimeSpan.FromSeconds(command.TimeoutSeconds), budget), ct);
var acknowledged = false;
var snapshot = false;
long lastSequence = 0;
var values = new HashSet<string>(StringComparer.Ordinal);
DataItemHandle? handle = null;
var controls = new List<object>();
var controlCounts = new Dictionary<string, int>(StringComparer.Ordinal);
var streamEvidence = new Dictionary<string, object?>
{
["frames"] = 0, ["acknowledged"] = false, ["snapshotValue"] = false,
["distinctValues"] = 0, ["lastSequence"] = 0L,
["controlCounts"] = controlCounts, ["controls"] = controls,
};
observations["stream"] = streamEvidence;
await foreach (var frame in subscription.ReadAllAsync(ct))
{
streamEvidence["frames"] = (int)streamEvidence["frames"]! + 1;
streamEvidence["lastFrame"] = frame.GetType().Name;
streamEvidence["lastSequence"] = frame.Sequence;
if (frame is DataSubscriptionControl control)
{
var kind = control.Kind.ToString();
controlCounts[kind] = controlCounts.GetValueOrDefault(kind) + 1;
if (controls.Count < 32)
controls.Add(new { Kind = kind, Reason = SafeControlReason(control.Diagnostic) });
}
Check(frame.SubscriptionId == id && frame.StreamEpoch == 1 && frame.Sequence > lastSequence, "stream ordering");
lastSequence = frame.Sequence;
if (frame is DataSubscriptionAck ack)
{
streamEvidence["ackStatuses"] = ack.Items.Take(32).Select(item => item.Status.ToString()).ToArray();
Check(ack.CommandId == "open" && ack.Items.Count == 1 && ack.Items[0].Status == DataItemStatus.Good && ack.Items[0].Handle is not null, "open acknowledgement");
handle = ack.Items[0].Handle;
acknowledged = true;
streamEvidence["acknowledged"] = true;
}
if (frame is DataSubscriptionValues update)
{
using (update)
{
snapshot |= update.IsSnapshot;
streamEvidence["snapshotValue"] = snapshot;
foreach (var entry in update.Items)
{
Check(acknowledged && entry.Handle == handle, "acknowledged handle revision");
Check(entry.Sample.StatusCode == 0 && entry.Readiness == DataReadiness.Ready, "stream quality and readiness");
values.Add(ZB.MOM.WW.OtOpcUa.Commons.DataConnections.TypedValueCodec.Encode(entry.Sample.Value).ToString());
streamEvidence["distinctValues"] = values.Count;
}
}
}
if (acknowledged && snapshot && values.Count >= 2) break;
}
Check(acknowledged && snapshot && values.Count >= 2, "changing snapshot and updates");
observations["distinctValues"] = values.Count;
observations["lastSequence"] = lastSequence;
}
else if (command.Operation == "history")
{
// H2 smoke: a Raw HistoryRead through whatever IDataConnection the caller holds (the deployed lease on a
// consumer node, or a probe-built GrpcDataConnection). ExpectedState: Good (default) | Unsupported.
phase = ProbeFailurePhase.Read;
Check(connection is IDataHistoryService, "connection serves history");
var history = (IDataHistoryService)connection;
observations["historyCapabilities"] = caps.History;
observations["historyReadAdvertised"] = caps.Operations.HasFlag(DataOperations.HistoryRead);
var details = new DataHistoryRawDetails(command.HistoryStartUtc, command.HistoryEndUtc ?? DateTimeOffset.UtcNow,
command.HistoryNumValues, false);
var historyBudget = budget with { MaxBytes = 4 * 1024 * 1024 };
static object Page(DataHistoryReadResult result) => new
{
statusCode = "0x" + result.StatusCode.ToString("X8"), result.Diagnostic, hasContinuation = result.Continuation is not null,
samples = result.Samples.Select(sample => new
{
value = ZB.MOM.WW.OtOpcUa.Commons.DataConnections.TypedValueCodec.Encode(sample.Value).ToString(),
statusCode = "0x" + sample.StatusCode.ToString("X8"), sourceTimestampUtc = sample.SourceTimestampUtc?.ToString("O"),
serverTimestampUtc = sample.ServerTimestampUtc?.ToString("O"),
}).ToArray(),
};
var pages = new List<object>();
observations["pages"] = pages;
var first = await history.ReadAsync(new(details, [new("one", view)], historyBudget), ct);
try
{
Check(first.Count == 1 && first[0].CorrelationId == "one", "history cardinality");
pages.Add(Page(first[0]));
if (command.ExpectedState == "Unsupported")
{
Check(first[0].StatusCode == 0x80720000u && first[0].Samples.Count == 0 && first[0].Continuation is null, "history unsupported");
}
else
{
Check(first[0].StatusCode >> 30 == 0, "history status Good");
Check(first[0].Samples.Count > 0 && (command.HistoryNumValues == 0 || first[0].Samples.Count <= command.HistoryNumValues), "history page bound");
if (command.HistoryStartUtc is null)
Check(first[0].Samples.Zip(first[0].Samples.Skip(1)).All(pair => pair.First.SourceTimestampUtc > pair.Second.SourceTimestampUtc), "end-only read newest first");
if (first[0].Continuation is { } token)
{
var second = await history.ReadAsync(new(details, [new("one", view, null, token)], historyBudget), ct);
try
{
Check(second.Count == 1, "resumed cardinality");
pages.Add(Page(second[0]));
Check(second[0].StatusCode >> 30 == 0 && second[0].Samples.Count > 0, "resumed page Good");
if (command.HistoryStartUtc is null)
Check(second[0].Samples[0].SourceTimestampUtc < first[0].Samples[^1].SourceTimestampUtc, "resumed page continues older");
if (second[0].Continuation is { } rest) await history.ReleaseAsync([rest], ct);
}
finally { foreach (var item in second) item.Dispose(); }
}
}
}
finally { foreach (var item in first) item.Dispose(); }
}
else throw new InvalidOperationException("unsupported operation");
return new(command.Id, command.Operation, true, assertions, observations);
}
catch (Exception error) when (error is not OutOfMemoryException)
{
var failure = ProbeFailureClassifier.Capture(error, phase);
observations["failurePhase"] = failure.Phase;
observations["failureEvidence"] = failure;
if (command.Operation == "read" && command.ExpectedState == "Denied" && phase == ProbeFailurePhase.Read
&& ProbeFailureClassifier.IsPinnedReadPermissionDenied(connection.Target, validatedCapabilities, failure))
{
observations["status"] = "Denied";
observations["reason"] = "pinned origin Read RPC explicitly denied the unadvertised operation";
observations["denialBoundary"] = "origin Read RPC";
return new(command.Id, command.Operation, true, assertions + 1, observations);
}
if (command.ExpectedState == "TargetIneligible" && phase == ProbeFailurePhase.GetCapabilities
&& failure.Category == "TargetIneligible" && !failure.Truncated)
{
observations["readiness"] = "Unavailable";
observations["selectionRejection"] = "TargetIneligible";
return new(command.Id, command.Operation, true, assertions + 1, observations);
}
if (command.Operation == "capabilities" && command.ExpectedState == "Unavailable"
&& error is InvalidOperationException { Message: "No ready authenticated data endpoint." or "Data endpoint discovery is backing off." })
{
observations["readiness"] = "Unavailable";
observations["reason"] = "authenticated endpoint selection failed";
return new(command.Id, command.Operation, true, assertions + 1, observations);
}
if (command.ExpectedState == "Denied" && (error is UnauthorizedAccessException
|| error is Grpc.Core.RpcException { StatusCode: Grpc.Core.StatusCode.PermissionDenied }))
{
observations["status"] = "Denied";
observations["reason"] = "explicit permission rejection";
return new(command.Id, command.Operation, true, assertions + 1, observations);
}
// Only fixed local assertion names and classifier codes cross the evidence boundary.
return new(command.Id, command.Operation, false, assertions, observations,
error is ProbeAssertionException ? error.Message : failure.Category);
}
}
private static string? SafeControlReason(string? diagnostic) => diagnostic switch
{
null => null,
"Source change history expired." or "Source became unavailable." or
"Snapshot catch-up expired; retry later." or "Snapshot lifetime expired; retry later." or
"Snapshot admission exhausted; retry later." or "Freshness snapshot admission exhausted; retry later." or
"Pending snapshot memory exhausted." or "Pending value memory exhausted." or
"Pending value capacity exhausted." or "Pending control capacity exhausted." or
"Transport capacity exhausted." or
"Source interest released." or "Source routing changed." or "Source partition reset." or "Source binding replaced." or "Source retired." => diagnostic,
// #1026: the suffix is a bounded SourceInvalidationReason name.
_ when diagnostic.StartsWith("Source invalidated (", StringComparison.Ordinal) && diagnostic.Length <= 64 => diagnostic,
_ when diagnostic.StartsWith("Snapshot pacing; retry after ", StringComparison.Ordinal) => "Snapshot pacing",
_ => "Other server control reason",
};
internal static async Task<DataView> CanonicalBrowseViewAsync(IDataConnection connection, DataView requested,
DataBudget budget, CancellationToken stop)
{
// Container IDs and physical authorization subjects are separate in UNS.
// Metadata resolves the authoritative subject without altering Read's
// deliberate forged-subject negative scenario.
var metadata = await connection.GetMetadataAsync(new([requested], budget), stop);
if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } parent
|| parent.View.Address != requested.Address || parent.View.Realm != requested.Realm || parent.View.MappingId is not null)
throw new InvalidOperationException("Canonical browse parent metadata unavailable.");
parent.View.Validate();
return parent.View;
}
private static DataValue Scalar(DataValueKind kind, int value) => DataValue.FromScalar(kind, kind switch
{
DataValueKind.Int8 => (object)checked((sbyte)value), DataValueKind.UInt8 => checked((byte)value),
DataValueKind.Int16 => checked((short)value), DataValueKind.UInt16 => checked((ushort)value),
DataValueKind.Int32 => value, DataValueKind.UInt32 => checked((uint)value),
DataValueKind.Int64 => (long)value, DataValueKind.UInt64 => checked((ulong)value),
DataValueKind.Float => (float)value, DataValueKind.Double => (double)value,
_ => throw new InvalidOperationException("fixture writable scalar type")
});
}