Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedStreamDiagnostics.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

65 lines
4.3 KiB
C#

using System.Collections.Concurrent;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>Bounded aggregate observations of projected stream admission and delivery.</summary>
public static class ProjectedStreamDiagnostics
{
internal enum Event { AcquireInvalid, AcquireDefinition, AcquireAuthorization, AcquirePin, AcquireCapacity, AcquireStale, AcquireAccepted, AcquireException,
Attempt, Frame, Reset, SnapshotEnd, Value, UnknownAge, StaleAge, FreshAge, PublishDemand, PublishStale, PublishVersion, PublishProof, PublishSink, PublishAccepted,
AttemptCanceled, AttemptInvalidData, AttemptOther, ResetHistory, ResetUnavailable, ResetSnapshot, ResetOther,
// #1026: an origin interest reset that is not history loss (see InterestResetDiagnostics).
ResetSourceInvalidated, ResetInterestLost,
// #1026: a cohort's per-item metadata lease renewals (started, committed, not committed, refused by the unary budget).
RenewalStarted, RenewalSucceeded, RenewalFailed, RenewalBudget, RenewalSlots }
/// <summary>#1026: classifies an origin Reset diagnostic (human text) into a bounded counter; never drives behaviour.</summary>
internal static Event ClassifyReset(string? diagnostic) => diagnostic switch
{
InterestResetDiagnostics.HistoryExpired => Event.ResetHistory,
"Source became unavailable." => Event.ResetUnavailable,
"Snapshot catch-up expired; retry later." or "Snapshot lifetime expired; retry later." => Event.ResetSnapshot,
InterestResetDiagnostics.Released or InterestResetDiagnostics.RoutingChanged or InterestResetDiagnostics.PartitionReset or
InterestResetDiagnostics.BindingReplaced or InterestResetDiagnostics.Retired => Event.ResetInterestLost,
_ when diagnostic?.StartsWith(InterestResetDiagnostics.SourceInvalidatedPrefix, StringComparison.Ordinal) == true => Event.ResetSourceInvalidated,
_ => Event.ResetOther
};
private static readonly long[] Counts = new long[Enum.GetValues<Event>().Length];
private const int MaxAttemptEndKinds = 32;
private static readonly ConcurrentDictionary<string, long> AttemptEnds = new(StringComparer.Ordinal);
internal static void Count(Event value) => Interlocked.Increment(ref Counts[(int)value]);
/// <summary>
/// #1026: why a cohort attempt ended, keyed by exception type (and an InvalidDataException's constant message), at most
/// <see cref="MaxAttemptEndKinds"/> distinct keys; never an identifier or payload.
/// </summary>
internal static void CountAttemptEnd(Exception ex)
{
// Only this runtime's own InvalidDataException messages are constants; any other exception is keyed by its type alone.
var message = ex is InvalidDataException ? ": " + (ex.Message.Length > 96 ? ex.Message[..96] : ex.Message) : "";
var key = "AttemptEnd." + ex.GetType().Name + message;
if (!AttemptEnds.ContainsKey(key) && AttemptEnds.Count >= MaxAttemptEndKinds) key = "AttemptEnd.(other)";
AttemptEnds.AddOrUpdate(key, 1, static (_, count) => count + 1);
}
/// <summary>#1026: a constant-named point where a subscription lease renewal did not commit (bounded like attempt ends).</summary>
internal static void CountRenewalFailure(string point, int count = 1)
{
if (count <= 0) return;
var key = "RenewalFail." + point;
if (!AttemptEnds.ContainsKey(key) && AttemptEnds.Count >= 2 * MaxAttemptEndKinds) key = "RenewalFail.(other)";
AttemptEnds.AddOrUpdate(key, count, (_, value) => value + count);
}
/// <summary>#1026: a constant-named reason a cohort attempt ended without an exception.</summary>
internal static void CountAttemptEnd(string reason)
{
var key = "AttemptEnd." + reason;
if (!AttemptEnds.ContainsKey(key) && AttemptEnds.Count >= 2 * MaxAttemptEndKinds) key = "AttemptEnd.(other)";
AttemptEnds.AddOrUpdate(key, 1, static (_, value) => value + 1);
}
/// <summary>Captures process-wide counters without source identifiers or payloads.</summary>
public static IReadOnlyDictionary<string, long> Capture()
{
var result = Enum.GetValues<Event>().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x]));
foreach (var pair in AttemptEnds) result[pair.Key] = pair.Value;
return result;
}
}