From 2eb31f62d2620820d89a9748b1cd75949a945c09 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 10:56:23 -0500 Subject: [PATCH 1/7] fix(grpc-data): bound the unknown-mapping hold of imported conditions (#933) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A key no known mapping lists was kept stale for as long as ANY mapping of the connection was unknown; a durably Denied/Unavailable mapping therefore kept retired conditions forever. Scoping the hold to mappings that could list the key is not provable on the consumer (placements are origin deploy-time config; a dropped key may have moved into the unknown mapping's root), so the hold is time-boxed per key: ProjectedConditionOptions.MaxUnknownHold (20 min) — past it the key is removed (+ RefreshRequired at the sink), never known-inactive. The since-time survives stream ends and hand-overs; the earliest expiry shares the loop's retry timer. DataConnections.md: lifetime rule + troubleshooting row. --- docs/DataConnections.md | 7 +++ .../ProjectedConditionAccess.Runner.cs | 50 ++++++++++++++++--- .../ProjectedConditionAccess.cs | 13 +++++ .../GrpcDataProjectedConditionAccessTests.cs | 37 ++++++++++++++ 4 files changed, 100 insertions(+), 7 deletions(-) diff --git a/docs/DataConnections.md b/docs/DataConnections.md index b5f6f2363..5f70815c2 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -453,6 +453,12 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar - An in-stream re-snapshot is buffered. The live set and the nodes stay untouched until `snapshot_complete`. - A condition is removed only when a **complete** snapshot no longer lists it (and no other mapping lists it), or when a `removed` record arrives. An incomplete snapshot removes nothing. It marks the unlisted keys stale (`BadNoCommunication`). + - That hold is bounded per key (#933). A key no known mapping lists, kept stale because another mapping of the connection + is unknown (`Unavailable`, `Denied`, retrying), is removed after `ProjectedConditionOptions.MaxUnknownHold` (20 min, + fixed): a removal with `RefreshRequired`, never "known inactive". If the unknown mapping later lists it, it is re-created + (new EventIds). The hold cannot be narrowed to "mappings whose scope could list the key": an origin deploy can move a + condition's placements into the unknown mapping's root, so the consumer cannot prove it. 20 min outlasts the transient + retry cycle (snapshot timeout × 8) and the first two re-checks of a definitive refusal (`LongRetryDelay` 5 min, then 10). 7. **Known state (T2 invariant).** *The consumer never retires or clears an alarm that is active at the origin.* - A record with `state_known = false` never changes the consumer's last state. - A condition first seen unknown is materialised with `Quality = UncertainInitialValue` until a known record arrives. @@ -631,6 +637,7 @@ status and diagnostic), and each snapshot barrier (per-mapping status, record co | `ConditionCapacity` | The listing's `total` against the mapping's or export's `MaxConditions`, and the host caps. Narrow the remote root or raise the limits. | | Conditions `Uncertain` | The origin has not established their state: a scripted alarm has not completed an evaluation; a native driver has not signalled (see `…conditions.unsignalled`). | | Conditions `BadNoCommunication` | Stream down longer than `ConditionStaleTimeoutMilliseconds`, or the mapping was incomplete at the last barrier. | +| A retired condition stays `BadNoCommunication` while another mapping of the connection is `Unavailable` / `Denied` | Expected for up to `MaxUnknownHold` (20 min, #933): the unknown mapping might still list it, so it is held (T2). After that it is removed with `RefreshRequired` (logged Warning "held past MaxUnknownHold", naming the unknown mappings). Fix the unknown mapping (its refusal is on the AdminUI mappings line) to settle it sooner. | | Ack answers `BadEventIdUnknown` | The client holds an old EventId (superseded occurrence, or an origin restart that re-announced a different time). ConditionRefresh and ack with the new EventId. | | Ack answers "OutcomeUnknown" | Check the origin's audit log (`ZB.MOM.WW.OtOpcUa.DataConnections.Audit`) for the operation and watch the condition's events. Never replay blindly. | | All `ConditionId`s changed | `ConditionKeySecret` was rotated or differs between the origin pair members, or the connection was re-created under a new id. | diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs index bad73b90c..9cae12c79 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs @@ -254,6 +254,9 @@ public sealed partial class ProjectedConditionAccess private Dictionary> _lastListed = new(StringComparer.OrdinalIgnoreCase); /// A4 review r1 S4: per materialised key, the mapping that chose its SourceName and that name. Owned by the loop. private Dictionary _sourceNames = new(StringComparer.Ordinal); + /// #933: materialised keys no known mapping lists, held stale while another mapping is unknown → since when + /// (kept across stream ends and hand-overs, so a flapping stream cannot restart the bound). Owned by the loop. + private Dictionary _heldSince = new(StringComparer.Ordinal); /// /// A4 review r2 S3: this runner took over a set HELD across an undecided deploy. During the hold nothing imported was @@ -340,6 +343,9 @@ public sealed partial class ProjectedConditionAccess _sourceNames = previous._sourceNames; previous._sourceNames = new Dictionary(StringComparer.Ordinal); foreach (var key in _sourceNames.Keys.Where(k => !_materialised.Contains(k)).ToArray()) _sourceNames.Remove(key); + _heldSince = previous._heldSince; + previous._heldSince = new Dictionary(StringComparer.Ordinal); + foreach (var key in _heldSince.Keys.Where(k => !_materialised.Contains(k)).ToArray()) _heldSince.Remove(key); Volatile.Write(ref _materialisedCount, _materialised.Count); Volatile.Write(ref _unknownCount, _unknownKeys.Count); _predecessor = null; @@ -415,6 +421,7 @@ public sealed partial class ProjectedConditionAccess _unknownKeys.Clear(); _lastListed.Clear(); _sourceNames.Clear(); + _heldSince.Clear(); Volatile.Write(ref _materialisedCount, 0); Volatile.Write(ref _unknownCount, 0); _owner._ledger.ResetClaims(ConnectionId); @@ -550,12 +557,14 @@ public sealed partial class ProjectedConditionAccess retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); retryArmedFor = null; await RetryDueAsync(connection, states, context, snapshotTimeout).ConfigureAwait(false); + ExpireHeld(states); } foreach (var s in states) if (s.RetryDue is null && s.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity) ScheduleRetry(s, snapshotTimeout); - var due = states.Where(x => x.RetryDue is not null).Select(x => x.RetryDue!.Value).DefaultIfEmpty().Min(); - DateTimeOffset? wanted = states.Any(x => x.RetryDue is not null) ? due : null; + // #933: the earliest held-key expiry shares the retry timer (the loop re-checks both when it fires). + DateTimeOffset? wanted = states.Where(x => x.RetryDue is not null).Select(x => (DateTimeOffset?)x.RetryDue!.Value) + .Append(HeldExpiry()).Where(x => x is not null).Min(); if (wanted != retryArmedFor) { retryTimer?.Dispose(); retryTimer = null; @@ -717,6 +726,20 @@ public sealed partial class ProjectedConditionAccess } } + /// #933: when the oldest held key reaches MaxUnknownHold (null when nothing is held). + private DateTimeOffset? HeldExpiry() => _heldSince.Count == 0 ? null : _heldSince.Values.Min() + _owner._options.MaxUnknownHold; + + /// #933 (on the loop): re-decides the held keys whose bound passed — removed if still unlisted. + private void ExpireHeld(MappingState[] states) + { + if (_heldSince.Count == 0) return; + var now = _owner._clock.GetUtcNow(); + var keys = _heldSince.Where(x => now - x.Value >= _owner._options.MaxUnknownHold).Select(x => x.Key).ToHashSet(StringComparer.Ordinal); + // Never leave an expired entry behind (it would re-arm the shared timer at once): a key no longer materialised goes. + foreach (var key in keys.Where(k => !_materialised.Contains(k)).ToArray()) { _heldSince.Remove(key); keys.Remove(key); } + if (keys.Count > 0) Reconcile(states, keys, full: false); + } + private void CountItem(MappingState state, bool open) { if (state.ItemCounted == open) return; @@ -950,7 +973,8 @@ public sealed partial class ProjectedConditionAccess /// Publishes across the connection's committed sets. also re-diffs /// everything materialised against the union (the barrier, a swap, a capacity reset, a late completion). /// A key no contributing mapping lists is removed only when every mapping's set is known; while any is unknown - /// (Unavailable, not yet complete) it is kept with BadNoCommunication (unknown ≠ gone, §5.1 T2, B2). + /// (Unavailable, not yet complete) it is kept with BadNoCommunication (unknown ≠ gone, §5.1 T2, B2) — for at + /// most MaxUnknownHold per key (#933), then removed. /// /// How many conditions were removed (#931 N7: a removal already carries RefreshRequired to their holders). private int Reconcile(MappingState[] states, HashSet keys, bool full) @@ -963,22 +987,34 @@ public sealed partial class ProjectedConditionAccess foreach (var key in _materialised) if (!listed.Contains(key)) keys.Add(key); } var unknown = states.Any(x => !x.Known); + var now = _owner._clock.GetUtcNow(); var updates = new List(); var removals = new List(); var stale = new List(); + var expired = 0; foreach (var key in keys) { var update = Merge(states, key); if (update is not null) { - updates.Add(update); _materialised.Add(key); + updates.Add(update); _materialised.Add(key); _heldSince.Remove(key); if (update.State.StateKnown) _unknownKeys.Remove(key); else _unknownKeys.Add(key); continue; } if (!_materialised.Contains(key)) continue; - if (unknown) stale.Add(key); - else { _materialised.Remove(key); _unknownKeys.Remove(key); _sourceNames.Remove(key); removals.Add(key); } + if (unknown) + { + // #933: the hold is bounded per key (MaxUnknownHold) — a durably Unavailable / Denied mapping no longer + // keeps a retired condition forever. Past the bound it is removed (+ RefreshRequired), never known-inactive. + if (!_heldSince.TryGetValue(key, out var since)) _heldSince[key] = since = now; + if (now - since < _owner._options.MaxUnknownHold) { stale.Add(key); continue; } + expired++; + } + _materialised.Remove(key); _unknownKeys.Remove(key); _sourceNames.Remove(key); _heldSince.Remove(key); removals.Add(key); } + if (expired > 0) + _owner._log.LogWarning("Imported conditions: connection {Connection} removed {Count} condition(s) held past MaxUnknownHold ({Hold}) while mapping(s) {Mappings} stayed unknown", + ConnectionId, expired, _owner._options.MaxUnknownHold, string.Join(", ", states.Where(x => !x.Known).Select(x => x.MappingId + "=" + x.Status))); Volatile.Write(ref _unknownCount, _unknownKeys.Count); Volatile.Write(ref _materialisedCount, _materialised.Count); if (removals.Count > 0) { sink.RemoveConditions(ConnectionId, removals); _owner.Diagnostics.ConsumerRefreshRequired(ConnectionId); } @@ -986,7 +1022,7 @@ public sealed partial class ProjectedConditionAccess if (updates.Count > 0) sink.ApplyConditions(updates); // #931 N5: the held keys no contributing mapping lists are charged on top of the claims (counted on a full re-diff). if (full) _unlisted = _materialised.Count(k => !listed!.Contains(k)); - else _unlisted = Math.Min(_unlisted, _materialised.Count); + else _unlisted = Math.Max(0, Math.Min(_unlisted - expired, _materialised.Count)); // #933: expired keys were unlisted if (!_owner._ledger.SetMaterialised(ConnectionId, _materialised.Count, _unlisted)) _owner._log.LogWarning("Imported conditions: connection {Connection} holds {Count} condition(s) and the node is over its host condition caps", ConnectionId, _materialised.Count); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index f20c51587..cdb5bd793 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -124,6 +124,19 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC /// public TimeSpan MaxHold { get; init; } = TimeSpan.FromMinutes(5); + /// + /// #933: the longest a materialised condition that no KNOWN mapping lists is kept (BadNoCommunication) because + /// another mapping of the connection is unknown (Unavailable, Denied, retrying). Past it the condition is removed — a + /// removal with RefreshRequired, never "known inactive" (§5.1 T2) — and re-created if the unknown mapping lists it again. + /// Scoping the hold to "mappings that could list the key" is not provable on the consumer: a mapping lists a key when the + /// origin's CURRENT catalog places the condition under that mapping's root, and placements are origin deploy-time + /// configuration (a dropped key may have moved into the unknown mapping's scope). The default (20 min) is ~4× the longest + /// transient retry cycle at the default 30 s snapshot timeout (× 8 = 4 min, + the retry's own timeout) and spans the first + /// two in-stream re-checks of a definitive refusal ( 5 min, then 10 min), so a transient + /// outage or a corrected grant never removes anything; only a durable one does. + /// + public TimeSpan MaxUnknownHold { get; init; } = TimeSpan.FromMinutes(20); + public static ProjectedConditionOptions Default { get; } = new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1)); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs index 6c1fb219d..aaa6b1f75 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs @@ -1097,6 +1097,43 @@ public sealed class GrpcDataProjectedConditionAccessTests await f.WaitAsync(() => f.Access.ChargedConditions == 0); } + // --------------------------------------------------------------------------------------------------------------------- + // Follow-ups #933 / #934 (A4 review) + // --------------------------------------------------------------------------------------------------------------------- + + [Fact] + public async Task Issue933_a_key_held_for_a_durably_denied_mapping_is_removed_past_MaxUnknownHold_not_kept_forever() + { + var hold = TimeSpan.FromSeconds(1.5); + await using var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold }, + ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(DataItemStatus.Denied, "map-b"); // durable: retried only on the 5 min long timer + stream.Begin("map-a", total: 1); + stream.Records("map-a", Record(Key("x"), 3)); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); + + // map-a retires x; map-b is unknown, so x is held stale (T2) — the stale mark is the must-arrive control. + stream.Records("map-a", Record(Key("x"), 4, removed: true)); + await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x"))); + var heldAt = DateTime.UtcNow; + f.Sink.Removed.ShouldBeEmpty("within the bound an unknown mapping still holds the key"); + + // …and past the bound it is removed (+ RefreshRequired at the sink), on the open stream, with no frame to prompt it. + await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x"))); + (DateTime.UtcNow - heldAt).ShouldBeGreaterThan(hold - TimeSpan.FromMilliseconds(200), "not before MaxUnknownHold"); + f.Sink.Removed.Count(k => k == Key("x")).ShouldBe(1); + f.Sink.Live.ShouldNotContain(Key("x")); + f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Unavailable, "still unknown"); + (await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(200))).ShouldBeNull("the stream is kept"); + + // A later listing re-creates it (the removal was a removal, not a verdict on the condition's state). + stream.Records("map-a", Record(Key("x"), 5, message: "back")); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); + } + private sealed class Fixture : IAsyncDisposable { internal static readonly DataView DefaultRawPlacement = From 5d946fde557ded28de62d286ec861310f6773e92 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 10:58:28 -0500 Subject: [PATCH 2/7] fix(grpc-data): move the in-stream root re-resolve off the condition frame loop (#934) RetryDueAsync awaited the root metadata request (10 s budget) inside the frame loop, stalling every mapping's frames on that connection while the origin's metadata was slow. The request now runs as a task (FetchRootsAsync reads only the immutable root views); the task joins the loop's wake set beside the retry timer, and its answer is applied on the loop (ApplyResolvedAsync: RootView or MarkRefused, then the re-add). All runner state stays loop-owned. While resolving the mapping is Unavailable (unknown, T2) and is not re-scheduled. Test: a hung second metadata call no longer blocks another mapping's delta; releasing it re-adds the item exactly once. --- docs/DataConnections.md | 4 +- .../ProjectedConditionAccess.Runner.cs | 117 +++++++++++++----- .../GrpcDataProjectedConditionAccessTests.cs | 53 +++++++- 3 files changed, 142 insertions(+), 32 deletions(-) diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 5f70815c2..d38a6b63c 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -424,7 +424,9 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar - A mapping that completes late is merged in. - An `Unavailable` mapping (item refused, root metadata failed, snapshot timed out) or a `ConditionCapacity` mapping is **retried on the open stream** (#930). Its root is re-resolved if it never resolved, any item it still holds is removed, - and a new item is added. The stream is not ended for it, so the healthy mappings are never re-snapshotted and their + and a new item is added. The root re-resolve (metadata, 10 s budget) runs off the stream's frame loop (#934): frames of + the other mappings keep flowing meanwhile, the mapping stays `Unavailable` until the answer is applied on the loop, and + its item is re-added then. The stream is not ended for it, so the healthy mappings are never re-snapshotted and their methods are never answered `BadNoCommunication` because of it. - Retry delay, per mapping. A **definitive** refusal (`Denied`, `NotFound` or `Unsupported`, for the item or the root metadata) or `ConditionCapacity` waits `LongRetryDelay` (5 min) × 2ⁿ, capped at 4× (20 min). Any other refusal or a diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs index 9cae12c79..69895fa90 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs @@ -199,6 +199,8 @@ public sealed partial class ProjectedConditionAccess public DateTimeOffset? RetryDue { get; set; } /// #930: a re-added item awaits its ack / snapshot. public bool Retrying { get; set; } + /// #934: an in-stream root re-resolve (metadata) is in flight off the loop; the mapping stays Unavailable. + public bool Resolving { get; set; } /// #930: consecutive in-stream retries (reset by a completed snapshot); drives the backoff. public int Retries { get; set; } /// A4 diagnostics: the last count the origin reported or listed (a snapshot total, or the committed set). @@ -502,7 +504,7 @@ public sealed partial class ProjectedConditionAccess // The remote root's origin subject: placement addresses are made relative to it (SourceName, folder subject). // S6: a root whose metadata fails is Unavailable (its item is not opened — a root item without the origin's own // view is refused, and placements made relative to a missing root subject would be wrong). - await ResolveRootsAsync(connection, states, token).ConfigureAwait(false); + ApplyRoots(states, await FetchRootsAsync(connection, states, token).ConfigureAwait(false)); var open = states.Where(x => !x.Refused).ToArray(); if (open.Length == 0) throw new InvalidOperationException("No condition-bearing mapping root resolved."); @@ -552,6 +554,8 @@ public sealed partial class ProjectedConditionAccess // #930 (N2/N3): an Unavailable or over-capacity mapping is retried ON THIS STREAM (its item re-added) on // its own backoff — the stream is no longer ended for it, so the healthy mappings are not re-snapshotted // and clients are not sent RefreshRequired every cycle. + // #934: root re-resolves run off the loop; their results are applied (and the items re-added) HERE. + await ApplyResolvedAsync(context, snapshotTimeout).ConfigureAwait(false); if (retry.Task.IsCompleted) { retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -560,7 +564,7 @@ public sealed partial class ProjectedConditionAccess ExpireHeld(states); } foreach (var s in states) - if (s.RetryDue is null && s.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity) + if (s.RetryDue is null && !s.Resolving && s.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity) ScheduleRetry(s, snapshotTimeout); // #933: the earliest held-key expiry shares the retry timer (the loop re-checks both when it fires). DateTimeOffset? wanted = states.Where(x => x.RetryDue is not null).Select(x => (DateTimeOffset?)x.RetryDue!.Value) @@ -582,7 +586,9 @@ public sealed partial class ProjectedConditionAccess next ??= frames.MoveNextAsync().AsTask(); if (!next.IsCompleted) { - var wake = barrierPassed ? retry.Task : timeout.Task; + var wake = !barrierPassed ? timeout.Task + : context.Resolves.Count == 0 ? retry.Task + : Task.WhenAny(context.Resolves.Select(x => (Task)x.Fetch).Append(retry.Task)); if (await Task.WhenAny(next, wake).ConfigureAwait(false) != next) continue; } if (!await next.ConfigureAwait(false)) return; @@ -611,34 +617,71 @@ public sealed partial class ProjectedConditionAccess new(state.MappingId, state.RootView ?? state.Root, new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null), new DataConditionScope(IncludeInfo: true)); - /// Resolves the roots of (metadata); a root that fails is refused (Unavailable). - private async Task ResolveRootsAsync(IDataConnection connection, MappingState[] targets, CancellationToken token) + /// The origin's answer to a root metadata request: the results, or the failure (never thrown, except cancellation). + private sealed record RootFetch(IReadOnlyList>? Metadata, Exception? Error); + + /// #934: a root re-resolve in flight off the loop (its targets are ). + private sealed record PendingRoots(MappingState[] Targets, Task Fetch); + + /// + /// The metadata request for the roots of . It reads only the targets' immutable + /// views, so it may run off the loop (#934); applies the answer + /// on the loop. + /// + private static async Task FetchRootsAsync(IDataConnection connection, MappingState[] targets, CancellationToken token) { - if (targets.Length == 0) return; + if (targets.Length == 0) return new RootFetch([], null); try { var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, targets.Length), 1024 * 1024); - var metadata = await connection.GetMetadataAsync(new MetadataRequest(targets.Select(x => x.Root).ToArray(), budget), token) - .ConfigureAwait(false); - for (var i = 0; i < targets.Length; i++) - { - if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root }) - { - targets[i].RootSubject = root.View.Subject; - targets[i].RootView = root.View; - continue; - } - var status = i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable; - MarkRefused(targets[i], status); - _owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried in-stream", - targets[i].MappingId, status); - } + return new RootFetch(await connection.GetMetadataAsync(new MetadataRequest(targets.Select(x => x.Root).ToArray(), budget), token) + .ConfigureAwait(false), null); } - catch (Exception ex) when (ex is not OperationCanceledException) + catch (Exception ex) when (ex is not OperationCanceledException) { return new RootFetch(null, ex); } + } + + /// On the loop: a resolved root sets the view; a root that failed is refused (Unavailable). + private void ApplyRoots(MappingState[] targets, RootFetch fetched) + { + if (targets.Length == 0) return; + if (fetched.Metadata is not { } metadata) { foreach (var state in targets) MarkRefused(state, DataItemStatus.Unavailable); - _owner._log.LogWarning(ex, "Imported conditions: connection {Connection} root metadata failed — {Count} mapping(s) Unavailable", + _owner._log.LogWarning(fetched.Error, "Imported conditions: connection {Connection} root metadata failed — {Count} mapping(s) Unavailable", ConnectionId, targets.Length); + return; + } + for (var i = 0; i < targets.Length; i++) + { + if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root }) + { + targets[i].RootSubject = root.View.Subject; + targets[i].RootView = root.View; + continue; + } + var status = i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable; + MarkRefused(targets[i], status); + _owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried in-stream", + targets[i].MappingId, status); + } + } + + /// + /// #934 (on the loop): applies every finished root re-resolve and re-adds the mappings whose root resolved. A root + /// that failed again is refused and re-scheduled on its backoff by the loop. + /// + private async Task ApplyResolvedAsync(StreamContext context, TimeSpan snapshotTimeout) + { + for (var i = 0; i < context.Resolves.Count;) + { + var pending = context.Resolves[i]; + if (!pending.Fetch.IsCompleted) { i++; continue; } + context.Resolves.RemoveAt(i); + var fetched = pending.Fetch.IsCompletedSuccessfully ? pending.Fetch.Result + : new RootFetch(null, pending.Fetch.Exception?.GetBaseException() ?? new OperationCanceledException()); + foreach (var state in pending.Targets) state.Resolving = false; + ApplyRoots(pending.Targets, fetched); + await ReAddAsync(pending.Targets.Where(x => x.RootView is not null).ToArray(), context, snapshotTimeout).ConfigureAwait(false); } } @@ -661,8 +704,8 @@ public sealed partial class ProjectedConditionAccess /// #930: runs the in-stream retries that are due. A retry whose snapshot has not completed by its deadline becomes /// Unavailable again; its buffer and claim are kept, so a late completion of that item is still taken (review r1 S1) /// until the next retry removes the item. A due Unavailable or - /// ConditionCapacity mapping has its root re-resolved when it never resolved, any still-open item removed, and its item - /// re-added with a fresh command id. While a retry runs the mapping is Pending — unknown, so nothing it might list is + /// ConditionCapacity mapping has its root re-resolved when it never resolved (#934: off the loop — it is re-added when + /// the answer is applied on the loop), any still-open item removed, and its item re-added with a fresh command id. While a retry runs the mapping is Pending — unknown, so nothing it might list is /// removed or marked known-inactive meanwhile (§5.1 T2). /// private async Task RetryDueAsync(IDataConnection connection, MappingState[] states, StreamContext context, TimeSpan snapshotTimeout) @@ -690,8 +733,22 @@ public sealed partial class ProjectedConditionAccess } if (due.Count == 0) return; foreach (var state in due) state.Retries++; - await ResolveRootsAsync(connection, due.Where(x => x.RootView is null).ToArray(), context.Token).ConfigureAwait(false); - var ready = due.Where(x => x.RootView is not null).ToArray(); + // #934: a root that never resolved is re-resolved OFF the loop (metadata has a 10 s budget; frames for every other + // mapping keep flowing meanwhile). The mapping stays Unavailable — unknown, so nothing it might list is removed or + // marked known-inactive (§5.1 T2) — and is re-added when the answer is applied on the loop (ApplyResolvedAsync). + var unresolved = due.Where(x => x.RootView is null).ToArray(); + if (unresolved.Length > 0) + { + foreach (var state in unresolved) state.Resolving = true; + context.Resolves.Add(new PendingRoots(unresolved, FetchRootsAsync(connection, unresolved, context.Token))); + } + await ReAddAsync(due.Where(x => x.RootView is not null).ToArray(), context, snapshotTimeout).ConfigureAwait(false); + } + + /// #930: removes a still-open item of each of and re-adds it with a fresh command id. + private async Task ReAddAsync(MappingState[] ready, StreamContext context, TimeSpan snapshotTimeout) + { + if (ready.Length == 0) return; // An Unavailable mapping whose snapshot timed out still has its item open: remove it before re-adding (one per root). var stillOpen = ready.Where(x => x.ItemHandle is not null).ToArray(); foreach (var state in stillOpen) CountItem(state, open: false); @@ -753,7 +810,11 @@ public sealed partial class ProjectedConditionAccess _owner._sink()?.RequireRefresh(ConnectionId); } - private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token); + private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token) + { + /// #934: root re-resolves in flight (loop-owned list; each fetch completes off the loop). + public List Resolves { get; } = []; + } private sealed record FrameOutcome(HashSet Changed, bool Reconcile, bool Refresh); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs index aaa6b1f75..10cde6f93 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs @@ -1134,6 +1134,43 @@ public sealed class GrpcDataProjectedConditionAccessTests await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); } + [Fact] + public async Task Issue934_a_slow_in_stream_root_re_resolve_does_not_stall_frames_of_the_other_mappings() + { + await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + f.Connections.MetadataFails.Add(0); // map-a's root fails at the open: Unavailable, its item is not opened + f.Connections.MetadataBlockCall = 2; // …and its in-stream re-resolve (the 2nd metadata call) hangs until released + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Mappings.ShouldBe(["map-b"]); + stream.Ack(); + stream.Begin("map-b", total: 1); + stream.Records("map-b", Record(Key("x"), 3)); + stream.Complete("map-b"); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); + f.Connections.MetadataFails.Clear(); + await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) == 2); // the re-resolve is in flight + + // The frame loop is not blocked by it: map-b's delta is applied while the metadata call is still pending. + stream.Records("map-b", Record(Key("y"), 3)); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("y"))); + f.Connections.MetadataRelease.Task.IsCompleted.ShouldBeFalse(); + stream.AddsOf("map-a").ShouldBe(0, "not re-added before its root resolved"); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable, "unknown while resolving (T2)"); + + // Positive control: once the answer arrives it is applied on the loop and the item is re-added — exactly once. + f.Connections.MetadataRelease.SetResult(); + await f.WaitAsync(() => stream.AddsOf("map-a") == 1); + stream.AckAdd("map-a"); + stream.Begin("map-a", total: 1); + stream.SnapshotRecords("map-a", Record(Key("w"), 3)); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("w"))); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete); + stream.AddsOf("map-a").ShouldBe(1); + Volatile.Read(ref f.Connections.MetadataCalls).ShouldBe(2); + } + private sealed class Fixture : IAsyncDisposable { internal static readonly DataView DefaultRawPlacement = @@ -1281,6 +1318,9 @@ public sealed class GrpcDataProjectedConditionAccessTests public HashSet MetadataFails { get; } = []; /// #931 N4: metadata requests made (one per stream attempt, plus in-stream root retries). public int MetadataCalls; + /// #934: when set, the metadata call with this 1-based number waits for . + public int? MetadataBlockCall; + public TaskCompletionSource MetadataRelease { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); /// The serving roles of the next streams (Primary when empty). public Queue Roles { get; } = new(); public int PrimarySubscribes; @@ -1307,11 +1347,18 @@ public sealed class GrpcDataProjectedConditionAccessTests public TimeProvider Clock => TimeProvider.System; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); - public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => - Interlocked.Increment(ref owner.MetadataCalls) < 0 ? throw new InvalidOperationException() : Task.FromResult>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i) + public async Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref owner.MetadataCalls) == owner.MetadataBlockCall) + await owner.MetadataRelease.Task.WaitAsync(cancellationToken); // #934: a slow origin metadata answer + return Answer(request); + } + + private IReadOnlyList> Answer(MetadataRequest request) => + request.Views.Select((v, i) => owner.MetadataFails.Contains(i) ? new DataItemResult("0", DataItemStatus.Unavailable, null, null) : new DataItemResult("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false, - DataOperations.Browse, 1, null, null, false), null)).ToArray()); + DataOperations.Browse, 1, null, null, false), null)).ToArray(); public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task SubscribeAsync(CancellationToken cancellationToken) From 18154eeff487709654f4c1371752af597dbf36a0 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 11:01:01 -0500 Subject: [PATCH 3/7] fix(grpc-data): removal RefreshRequired reaches the holders after their mapping left the deployed set (#936) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QueueRefreshRequired decided per item with the CURRENT gate (CanSee over the current mapping set), so when a deploy removed the mapping or its connection nobody passed and the §5.2 removal + RefreshRequired was never delivered. Each imported condition instance now records (weakly, per identity) every identity the §5.4 gate admitted to it — the verdict cache's compute is the only place a positive verdict is made, and every delivery, refresh replay and Read/Browse goes through it. A removal's RefreshRequired goes to the collected targets whose identity was admitted to the removed instance. The event carries no condition data (SourceNode=Server); a never-admitted session still gets nothing. OI test pins both: holders told after the gate admits nobody, the ungranted session not (with a must-arrive RefreshEnd control). --- docs/AlarmTracking.md | 7 ++- .../ProjectedConditionRegistry.cs | 42 ++++++++++++++---- .../ImportedConditionEventWireTests.cs | 43 +++++++++++++++++++ 3 files changed, 83 insertions(+), 9 deletions(-) diff --git a/docs/AlarmTracking.md b/docs/AlarmTracking.md index ecb22b25b..8904ae7b1 100644 --- a/docs/AlarmTracking.md +++ b/docs/AlarmTracking.md @@ -863,7 +863,12 @@ This section is what an OPC UA client of the **consumer** sees. Code: `OpcUaServ mappings differs from the previous barrier's (#930: a mapping that stays refused across streams does not repeat it; one that completes leaves the set, so a relapse is announced again); - an imported condition is removed (a complete re-snapshot no longer lists it, a `removed` record, a capacity - eviction, or a secret rotation). Removal emits **no** `NodeDeleted` model change; + eviction, a secret rotation, its mapping or connection leaving the deployed set, a demand linger, or #933's + `MaxUnknownHold`). Removal emits **no** `NodeDeleted` model change. For a removal, "may see" means "its identity was + admitted by the gate to that condition instance" (a delivery, a refresh replay or a Read/Browse of it), recorded per + instance — not the current mapping set, which no longer admits anybody once the removal was caused by the mapping + leaving it (#936). The event carries no condition field (`SourceNode = Server`, `Message = "RefreshRequired"`), and a + session never admitted to the condition is not sent one; - a resync leaves retained EventIds un-re-bindable (see EventIds below). - **Before the first barrier, a refresh returns nothing imported**, because nothing is materialised yet. Conditions appear as their records apply. A RefreshRequired follows only if that barrier is incomplete; a refresh that merely preceded a diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index cf76bfe5e..4a3d7fd06 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -54,6 +55,17 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec public long PlacementVersion { get; set; } /// Native (driver-fed) at the origin: Confirm / shelve / enable have no upstream path. public bool IsNative { get; init; } + + /// + /// #936: every identity that passed the §5.4 gate for THIS condition instance (each delivery, refresh replay and + /// Read/Browse of it is gated, so any client that may hold it is here). Weak keys: a closed session's identity is + /// collected with it. Lets the removal RefreshRequired reach the holders even after the mapping that admitted them + /// left the deployed set — the current gate then admits nobody. + /// + private readonly ConditionalWeakTable _admitted = new(); + private static readonly object AdmittedMark = new(); + public void Admit(object identity) => _admitted.AddOrUpdate(identity, AdmittedMark); + public bool WasAdmitted(object identity) => _admitted.TryGetValue(identity, out _); } /// @@ -216,8 +228,12 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink if (ProjectedConditionAccess is not { } access || identity is not RoleCarryingUserIdentity caller) return false; var generation = access.AuthorityGeneration; var placements = condition.Placements; - return _importedConditions.Verdict(caller, condition, generation, DateTimeOffset.UtcNow, caller.CredentialExpiresUtc, - () => access.CanSee(caller, placements)); + return _importedConditions.Verdict(caller, condition, generation, DateTimeOffset.UtcNow, caller.CredentialExpiresUtc, () => + { + var allowed = access.CanSee(caller, placements); + if (allowed) condition.Admit(caller); // #936: a cached positive verdict was computed (and recorded) here first + return allowed; + }); } /// The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4). @@ -336,8 +352,9 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink } } // §5.2 "removal + RefreshRequired": a client holding a removed (e.g. Active/Retain) condition is told to refresh, after - // which it no longer lists it. Outside Lock. - if (removed.Count > 0) QueueRefreshRequired(targets, removed); + // which it no longer lists it. Outside Lock. #936: decided by who was ADMITTED to the condition, not by the current + // mapping set — a removal caused by the mapping (or its connection) leaving the deployed set must still tell them. + if (removed.Count > 0) QueueRefreshRequired(targets, removed, removal: true); } /// @@ -412,14 +429,23 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink QueueRefreshRequired(targets, conditions); } - /// Off Lock: one RefreshRequired per item that may see at least one of the conditions (§5.4 gate). - private void QueueRefreshRequired(RefreshTargets targets, IReadOnlyList conditions) + /// + /// Off Lock: one RefreshRequired per item that may see at least one of the conditions (§5.4 gate). For a + /// (#936) the test is instead "its identity was admitted to the removed instance" — the + /// current gate cannot answer once the mapping is gone. The event carries no condition data (EventType + /// RefreshRequired, SourceNode = Server, SourceName "Server", Message "RefreshRequired", Severity Low), and it still + /// goes only to identities that could see the condition, so an ungranted session learns nothing. + /// + private void QueueRefreshRequired(RefreshTargets targets, IReadOnlyList conditions, bool removal = false) { + Func holds = removal + ? (item, c) => item.EffectiveIdentity is { } identity && c.WasAdmitted(identity) + : ImportedVisibleTo; var send = new List(); foreach (var item in targets.ServerItems) - if (conditions.Any(c => ImportedVisibleTo(item, c))) send.Add(item); + if (conditions.Any(c => holds(item, c))) send.Add(item); foreach (var (item, candidates) in targets.Direct) - if (!targets.ServerItems.Contains(item) && candidates.Any(c => ImportedVisibleTo(item, c))) send.Add(item); + if (!targets.ServerItems.Contains(item) && candidates.Any(c => holds(item, c))) send.Add(item); foreach (var item in send) { var e = new RefreshRequiredEventState(null); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs index 086e3407c..162fb35da 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs @@ -403,6 +403,49 @@ public sealed class ImportedConditionEventWireTests events.Of(other).Any(IsRefreshRequired).ShouldBeFalse("an item that never saw the removed condition is not told to refresh"); } + [Fact] + public async Task Issue936_a_removal_after_the_mapping_left_the_deployed_set_still_tells_its_holders_and_only_them() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("fu-936-remove", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var granted = await rig.ConnectAsync(anonymous: false, ct); + using var denied = await rig.ConnectAsync(anonymous: true, ct); + var events = new Events(); + var deniedEvents = new Events(); + var grantedSub = await SubscribeAsync(granted, events, ct); + var deniedSub = await SubscribeAsync(denied, deniedEvents, ct); + var server = AddItem(grantedSub, ObjectIds.Server); + var device = AddItem(grantedSub, f.DeviceFolder); + var deniedServer = AddItem(deniedSub, ObjectIds.Server); + await grantedSub.ApplyChangesAsync(ct); + await deniedSub.ApplyChangesAsync(ct); + f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "held")); + await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "held") && events.Of(device).Any(e => Message(e) == "held")); + + // The deploy removed the mapping: the CURRENT gate now admits nobody (as CanSee does with the mapping gone). + f.Access.Allowed.Clear(); + Interlocked.Increment(ref f.Access.Generation); + var before = rig.Nm.ImportedRefreshRequiredQueued; + rig.Nm.RemoveConditions(Connection, [Key1]); + rig.Nm.ImportedConditionCount.ShouldBe(0); + await Events.WaitUntilAsync(() => events.Of(server).Any(IsRefreshRequired) && events.Of(device).Any(IsRefreshRequired)); + (rig.Nm.ImportedRefreshRequiredQueued - before).ShouldBe(2, "one per item that held it"); + // Content-free: the event is the Server's, with no condition field. + var refresh = events.Of(server).First(IsRefreshRequired); + refresh[SourceNodeF].GetNodeId().ShouldBe(ObjectIds.Server); + refresh[ConditionNameF].TryGetValue(out string _).ShouldBeFalse("no ConditionName"); + refresh[ActiveF].TryGetValue(out bool _).ShouldBeFalse("no ActiveState"); + refresh[AckedF].TryGetValue(out bool _).ShouldBeFalse("no AckedState"); + refresh[ConditionIdF].TryGetValue(out NodeId _).ShouldBeFalse("no ConditionId"); + + // Must-arrive control on the never-admitted session, queued after the removal: its own refresh's RefreshEnd. + await deniedSub.ConditionRefreshAsync(ct); + await Events.WaitUntilAsync(() => deniedEvents.Of(deniedServer).Any(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType)); + deniedEvents.Of(deniedServer).Any(IsRefreshRequired).ShouldBeFalse("an identity never admitted to the condition is not told"); + } + [Fact] public async Task Deviation8_ConditionRefresh_replays_hundreds_of_imported_conditions_in_chunks_between_RefreshStart_and_RefreshEnd() { From 939ad2337d474e647519d279cf913574713adc44 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 11:51:03 -0500 Subject: [PATCH 4/7] =?UTF-8?q?docs(grpc-data):=20A4=20evidence=20?= =?UTF-8?q?=E2=80=94=20follow-ups=20#933/#934/#936=20decisions,=20red/gree?= =?UTF-8?q?n,=20gates,=20live=20fu933-1=208/8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/A4.md | 109 ++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/docs/plans/evidence/grpc-data-ext/A4.md b/docs/plans/evidence/grpc-data-ext/A4.md index bb6047753..262d7e358 100644 --- a/docs/plans/evidence/grpc-data-ext/A4.md +++ b/docs/plans/evidence/grpc-data-ext/A4.md @@ -674,3 +674,112 @@ in `artifacts/grpc-data/runs/a4s-7/evidence/` (`A4S-results.md`). **A4 exit gate | A06 | PASS | 11/11 | | | A07 | PASS | 8/8 | | | A08 | PASS | 10/10 | | + +## Follow-ups #933/#934/#936 (consumer side, branch `fu-consumer-933`) + +"Red" = that one change reverted in place (file restored afterwards), the named test re-run alone; it failed at the stated +assertion and passed again once restored. + +### #933 — a durably unknown mapping no longer blocks removals forever + +**Decision: a bounded per-key hold, not scoping.** Scoping the unknown check to "mappings whose placements could list the +key" would need a proof that the unknown mapping cannot list it. The consumer has none: a mapping lists a key when the +origin's *current* catalog places the condition under that mapping's root in its realm +(`LocalExportCatalog.Compilation.cs` builds condition placements at origin deploy time; raw placements by device scope, UNS +placements by `UnsTagReference` / equipment). An origin deploy can add a UNS reference or move a tag, so the very drop that +made a known mapping stop listing a key may be a move into the unknown mapping's root. Neither a disjoint root nor a +different realm is provable from the consumer's last-known placements. + +- `ProjectedConditionOptions.MaxUnknownHold` (default **20 min**, fixed like `LongRetryDelay`). A materialised key that no + known mapping lists, held `BadNoCommunication` because another mapping is unknown, records when the hold began + (`_heldSince`, loop-owned, kept across stream ends and hand-overs so a flapping stream cannot restart it). Past the bound + `Reconcile` removes it: a removal with RefreshRequired (the sink's §5.2 path), never "known inactive". A later listing + re-creates it (new EventIds). Logged Warning "held past MaxUnknownHold" with the unknown mappings and their status. +- Why 20 min: about 4× the longest transient retry cycle at the default 30 s snapshot timeout (× 8 = 4 min, plus the + retry's own timeout), and it spans the first two in-stream re-checks of a definitive refusal (`LongRetryDelay` 5 min, + then 10 min). A transient outage or a grant corrected within that window removes nothing; only a durable one does. +- The earliest expiry shares the loop's retry timer (`HeldExpiry` in the wanted deadline), and `ExpireHeld` runs on the + loop when it fires, so no frame is needed to settle it. An expiry entry for a key no longer materialised is dropped, + so the timer cannot re-arm at zero. +- Docs: `DataConnections.md` lifetime rule (step 6) and a troubleshooting row. + +| Test | Red on revert | +|---|---| +| Runtime `Issue933_a_key_held_for_a_durably_denied_mapping_is_removed_past_MaxUnknownHold_not_kept_forever`: map-b `Denied`, map-a retires x ⇒ stale mark arrives (must-arrive control), nothing removed; past 1.5 s x is removed once, with no frame, stream kept, map-b still Unavailable; a later listing re-creates x | **red** with the bound disabled (`< TimeSpan.MaxValue`): fails at the removal wait. Also **red** with only the timer-driven `ExpireHeld` removed (the expiry then waits for a frame that never comes) | + +### #934 — the in-stream root re-resolve no longer runs on the frame loop + +- `ResolveRootsAsync` was split. `FetchRootsAsync` (static, reads only the immutable `MappingState.Root` views, never + throws except cancellation) issues the metadata request. `ApplyRoots` sets `RootView` or calls `MarkRefused`, on the loop. +- `RetryDueAsync` starts the fetch for due mappings whose root never resolved, marks them `Resolving`, and records it in + the stream's `Resolves` list. The loop's wake set is `WhenAny(retry timer, pending fetches)` after the barrier. + `ApplyResolvedAsync` (on the loop, each iteration) applies every finished fetch and re-adds the resolved mappings + (`ReAddAsync`, the old re-add body unchanged). +- While resolving, the mapping stays `Unavailable` (unknown, T2: nothing it may list is removed or marked inactive), and + `ScheduleRetry` skips it, so it is not retried twice. A failed answer re-schedules it on its backoff. A fetch outliving + its stream is abandoned (cancelled with the stream's token; the next stream has fresh states). +- The stream-open resolve still awaits (no frames exist yet). All runner state stays loop-owned. + +| Test | Red on revert | +|---|---| +| Runtime `Issue934_a_slow_in_stream_root_re_resolve_does_not_stall_frames_of_the_other_mappings`: map-a's root fails at open; its in-stream re-resolve (2nd metadata call) hangs; map-b's delta y is applied meanwhile, map-a not re-added and Unavailable; released ⇒ re-added exactly once and Complete (positive control), 2 metadata calls | **red** with the fetch awaited inline in `RetryDueAsync` (the old shape): fails at the y wait (10 s) | + +### #936 — the removal RefreshRequired reaches holders after their mapping left the deployed set + +**Decision: visibility for a removal is "this identity was admitted to this condition instance", recorded at admission.** +Not "send to every collected target without a check": the targets include every Server-object item of every session, so an +ungranted session would learn that an imported condition it never saw was removed (and A05's "denied session sees nothing" +would no longer hold). + +- `ImportedCondition` keeps a `ConditionalWeakTable` of admitted identities (weak keys: a closed session's identity is + collected). `ImportedVisibleTo` records the caller inside the verdict-cache compute when `CanSee` is true. That compute + is the only place a positive verdict is made, and every delivery (publish-time marker), refresh replay and Read/Browse + of an imported condition goes through it. Cached positives were recorded when computed; `Remove` clears the NodeId's + verdicts, so a re-created instance (same NodeId) is admitted afresh. +- `RemoveConditions` → `QueueRefreshRequired(…, removal: true)`: a collected target (Server-object item, or direct item at + a folder the condition was wired to) is sent one RefreshRequired when its identity was admitted to a removed instance. + The non-removal paths (incomplete barrier, un-re-bindable resync, takeover) keep the current gate. +- **What the event carries:** `RefreshRequiredEventState` with `SourceNode = Server`, `SourceName = "Server"`, + `Message = "RefreshRequired"`, Severity Low, a fresh EventId and times. It has no ConditionId, ConditionName, + Active/Acked state or any origin data (asserted on the wire). It goes only to identities that could see the condition. + Residual: an identity admitted earlier and revoked by an ACL edit since is still told (content-free, about a condition it + saw). +- Docs: `AlarmTracking.md` §ConditionRefresh and RefreshRequired. + +| Test | Red on revert | +|---|---| +| OI `Issue936_a_removal_after_the_mapping_left_the_deployed_set_still_tells_its_holders_and_only_them`: the granted session holds the condition (server + device items); then the gate admits nobody (`Allowed.Clear()`, generation bumped — what `CanSee` does with the mapping gone) and the condition is removed ⇒ both items get RefreshRequired (count 2), with no condition fields; the anonymous session's Server item gets none, after a must-arrive control (its own ConditionRefresh's RefreshEnd) | **red** with `removal: false` (the old current-gate check): fails at the RefreshRequired wait. **Red** the other way too: an unconditional send fails at the count (3, the ungranted session was told). `Deviation6_…` still green | + +Commits: `2eb31f62` (#933), `5d946fde` (#934), `18154eef` (#936), plus this evidence commit. + +### Gates (`fu-consumer-933` at `18154eef`) + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors | +| `run-unit-phase.py A4` / `A3` / `A2` | all exit 0 (`20261125T160154…`, `…160249…`, `…160447…`) | +| Host.Tests `DataConnections` | 207 passed | +| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2085 passed, 3 skipped, 0 failed (#920 did not fire) | +| OpcUaServer.Tests full | 1458 passed, 2 skipped | +| OI combined (`Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral / ImportedConditionEventWireTests), once | 141 passed, 1 skipped (opt-in L2 harness) | +| `git diff master -- '*Goldens.cs'` | empty | + +### Full A01–A08 run — run `fu933-1` (after #933/#934/#936) + +The sequence was `rig.py up --run-id fu933-1 --conditions` → `seed` → 85 s → `deploy --timeout 300` → +`conditions_a3_smoke.py` (`passed: true`) → `conditions_scenarios.py` (all eight, one session) → `rig.py down` (exit 0, +0 run containers left). Evidence is in `artifacts/grpc-data/runs/fu933-1/evidence/`. **8/8 PASS.** + +| Scenario | Result | Checks | Notes | +|---|---|---|---| +| A01 | PASS | 13/13 | | +| A02 | PASS | 10/10 | | +| A03 | PASS | 20/20 | `p1_exactly_one_refresh_required_after_held_takeover` still exactly one; phase 2 RefreshRequired + new-EventId ack Good | +| A04 | PASS | 16/16 | | +| A05 | PASS | 4/4 | The denied session still saw zero imported events (the #936 removal path sends only to admitted identities) | +| A06 | PASS | 11/11 | | +| A07 | PASS | 8/8 | | +| A08 | PASS | 10/10 | | + +The live scenarios do not exercise a 20 min unknown hold, a slow origin metadata answer, or a mapping removal while a +client holds a condition. Those three behaviours are pinned by the unit/OI tests above; the live run shows no regression. From 9d969c4724b4a12786b94d95478362d0c9f26c92 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 12:02:33 -0500 Subject: [PATCH 5/7] =?UTF-8?q?fix(grpc-data):=20follow-ups=20review=20r1?= =?UTF-8?q?=20=E2=80=94=20the=20unknown-mapping=20hold=20spares=20a=20tran?= =?UTF-8?q?sient=20mapping's=20own=20keys=20and=20pauses=20with=20no=20liv?= =?UTF-8?q?e=20stream=20(#933);=20cancel=20abandoned=20root=20fetches=20(#?= =?UTF-8?q?934)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit S1: a held key that a transiently unknown mapping listed itself (_lastListed) is held without a bound; only a definitive refusal of that mapping (Denied / NotFound / Unsupported / ConditionCapacity, remembered across retries and stream ends) starts its MaxUnknownHold clock. Consistent with a never-opening stream. S2: the hold clock runs only while a stream is past its barrier (paused at the stream end, shifted at the next barrier). N1: in-stream root re-resolves run under a per-stream source cancelled when the stream ends. N2: no held-expiry timer without a sink (spin). N3: MaxUnknownHold must be positive. N5: #933 test lower bound taken before the hold starts; tests for S1, S2, N1, N2, N3 and a second failed re-resolve — each red on revert. --- .../ProjectedConditionAccess.Runner.cs | 95 +++++++++- .../ProjectedConditionAccess.cs | 3 + .../GrpcDataProjectedConditionAccessTests.cs | 175 +++++++++++++++++- 3 files changed, 262 insertions(+), 11 deletions(-) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs index 69895fa90..482f0f26a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs @@ -259,6 +259,16 @@ public sealed partial class ProjectedConditionAccess /// #933: materialised keys no known mapping lists, held stale while another mapping is unknown → since when /// (kept across stream ends and hand-overs, so a flapping stream cannot restart the bound). Owned by the loop. private Dictionary _heldSince = new(StringComparer.Ordinal); + /// #933 review r1 S2: the hold clock runs only while a stream is past its barrier — set when such a stream ends + /// (the clock pauses), cleared at the next barrier, which shifts every by the paused time. So a + /// connection outage never counts toward MaxUnknownHold. Owned by the loop; handed over. + private DateTimeOffset? _heldPausedAt; + /// #933 review r1 S1: mappings whose latest refusal was DEFINITIVE (Denied / NotFound / Unsupported / + /// ConditionCapacity), kept across in-stream retries and stream ends until the mapping completes a snapshot. Only a + /// definitively refused mapping's own last-listed keys are subject to MaxUnknownHold. Owned by the loop; handed over. + private HashSet _definitiveRefused = new(StringComparer.OrdinalIgnoreCase); + /// #933 review r1 S1: the transiently-unknown mappings the held keys were last decided against (loop-owned). + private readonly HashSet _transientSeen = new(StringComparer.OrdinalIgnoreCase); /// /// A4 review r2 S3: this runner took over a set HELD across an undecided deploy. During the hold nothing imported was @@ -348,6 +358,10 @@ public sealed partial class ProjectedConditionAccess _heldSince = previous._heldSince; previous._heldSince = new Dictionary(StringComparer.Ordinal); foreach (var key in _heldSince.Keys.Where(k => !_materialised.Contains(k)).ToArray()) _heldSince.Remove(key); + _heldPausedAt = previous._heldPausedAt; + previous._heldPausedAt = null; + _definitiveRefused = previous._definitiveRefused; + previous._definitiveRefused = new HashSet(StringComparer.OrdinalIgnoreCase); Volatile.Write(ref _materialisedCount, _materialised.Count); Volatile.Write(ref _unknownCount, _unknownKeys.Count); _predecessor = null; @@ -424,6 +438,8 @@ public sealed partial class ProjectedConditionAccess _lastListed.Clear(); _sourceNames.Clear(); _heldSince.Clear(); + _heldPausedAt = null; + _definitiveRefused.Clear(); Volatile.Write(ref _materialisedCount, 0); Volatile.Write(ref _unknownCount, 0); _owner._ledger.ResetClaims(ConnectionId); @@ -530,7 +546,10 @@ public sealed partial class ProjectedConditionAccess var retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); ITimer? retryTimer = null; DateTimeOffset? retryArmedFor = null; - var context = new StreamContext(subscription, subscriptionId, epoch, token); + // #934 review r1 N1: root re-resolves run under their own source, CANCELLED (not just disposed) when the stream ends + // however it ends — an abandoned fetch must not run on to its 10 s budget against a released lease. + using var fetches = CancellationTokenSource.CreateLinkedTokenSource(token); + var context = new StreamContext(subscription, subscriptionId, epoch, token, fetches.Token); try { await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false, @@ -566,9 +585,12 @@ public sealed partial class ProjectedConditionAccess foreach (var s in states) if (s.RetryDue is null && !s.Resolving && s.Status is ProjectedConditionMappingStatus.Unavailable or ProjectedConditionMappingStatus.ConditionCapacity) ScheduleRetry(s, snapshotTimeout); - // #933: the earliest held-key expiry shares the retry timer (the loop re-checks both when it fires). + // #933 review r1 S1: a mapping became (or stopped being) transiently unknown — re-decide the held keys. + if (TransientChanged(states)) ReconcileUnlisted(states); + // #933: the earliest held-key expiry shares the retry timer (the loop re-checks both when it fires). Review + // r1 N2: with no sink nothing can expire (Reconcile returns early), so an expiry is not armed — it would spin. DateTimeOffset? wanted = states.Where(x => x.RetryDue is not null).Select(x => (DateTimeOffset?)x.RetryDue!.Value) - .Append(HeldExpiry()).Where(x => x is not null).Min(); + .Append(_owner._sink() is null ? null : HeldExpiry()).Where(x => x is not null).Min(); if (wanted != retryArmedFor) { retryTimer?.Dispose(); retryTimer = null; @@ -605,6 +627,9 @@ public sealed partial class ProjectedConditionAccess finally { retryTimer?.Dispose(); + fetches.Cancel(); + // #933 review r1 S2: the hold clock pauses while no stream is past its barrier. + if (barrierPassed && _heldPausedAt is null) _heldPausedAt = _owner._clock.GetUtcNow(); foreach (var s in states) { CountItem(s, open: false); @@ -740,7 +765,7 @@ public sealed partial class ProjectedConditionAccess if (unresolved.Length > 0) { foreach (var state in unresolved) state.Resolving = true; - context.Resolves.Add(new PendingRoots(unresolved, FetchRootsAsync(connection, unresolved, context.Token))); + context.Resolves.Add(new PendingRoots(unresolved, FetchRootsAsync(connection, unresolved, context.FetchToken))); } await ReAddAsync(due.Where(x => x.RootView is not null).ToArray(), context, snapshotTimeout).ConfigureAwait(false); } @@ -797,6 +822,50 @@ public sealed partial class ProjectedConditionAccess if (keys.Count > 0) Reconcile(states, keys, full: false); } + /// #933 review r1 S1: unknown, and not definitively refused (a pending first snapshot, Unavailable, retrying). + private bool Transient(MappingState state) => !state.Known && !_definitiveRefused.Contains(state.MappingId); + + /// + /// #933 review r1 S1: the held keys a transiently unknown mapping listed itself when last known (its re-listing will + /// decide them); null when there are none. Only these escape MaxUnknownHold — a key held because ANOTHER + /// mapping is unknown, or whose own mapping is definitively refused, is bounded. + /// + private HashSet? TransientOwnedKeys(MappingState[] states) + { + HashSet? exempt = null; + foreach (var state in states) + if (Transient(state) && _lastListed.TryGetValue(state.MappingId, out var listed) && listed.Count > 0) + (exempt ??= new HashSet(StringComparer.Ordinal)).UnionWith(listed); + return exempt; + } + + /// #933 review r1 S1: whether the set of transiently unknown mappings changed since last decided (and records it). + private bool TransientChanged(MappingState[] states) + { + var count = 0; + var changed = false; + foreach (var state in states) + { + if (!Transient(state)) continue; + count++; + if (!_transientSeen.Contains(state.MappingId)) changed = true; + } + if (!changed && count == _transientSeen.Count) return false; + _transientSeen.Clear(); + foreach (var state in states) if (Transient(state)) _transientSeen.Add(state.MappingId); + return true; + } + + /// #933 review r1 S1: re-decides every held (materialised, unlisted) key — exempt keys drop their clock, the + /// others start it (or are removed when every mapping is known). + private void ReconcileUnlisted(MappingState[] states) + { + var keys = new HashSet(StringComparer.Ordinal); + foreach (var key in _materialised) + if (!states.Any(x => x.Contributes && x.Live!.Records.ContainsKey(key))) keys.Add(key); + if (keys.Count > 0) Reconcile(states, keys, full: false); + } + private void CountItem(MappingState state, bool open) { if (state.ItemCounted == open) return; @@ -810,7 +879,8 @@ public sealed partial class ProjectedConditionAccess _owner._sink()?.RequireRefresh(ConnectionId); } - private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token) + private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token, + CancellationToken FetchToken) { /// #934: root re-resolves in flight (loop-owned list; each fetch completes off the loop). public List Resolves { get; } = []; @@ -826,6 +896,7 @@ public sealed partial class ProjectedConditionAccess state.Refusal = status; if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable; } + if (Definitive(state)) _definitiveRefused.Add(state.MappingId); else _definitiveRefused.Remove(state.MappingId); state.Retrying = false; state.RetryDue = null; // re-scheduled (with its backoff) once past the barrier CountItem(state, open: false); @@ -839,6 +910,14 @@ public sealed partial class ProjectedConditionAccess Interlocked.Exchange(ref _snapshotAtTicks, _owner._clock.GetUtcNow().UtcTicks); _barrierThisStream = true; DisarmStale(); + // #933 review r1 S2: the hold clock resumes — the time no stream was past its barrier does not count. + if (_heldPausedAt is { } paused) + { + var gap = _owner._clock.GetUtcNow() - paused; + if (gap > TimeSpan.Zero) foreach (var key in _heldSince.Keys.ToArray()) _heldSince[key] += gap; + _heldPausedAt = null; + } + TransientChanged(states); // S1: the full re-diff below decides against this set var incompleteSet = states.Where(x => !x.Known).Select(x => x.MappingId).ToHashSet(StringComparer.OrdinalIgnoreCase); var incomplete = incompleteSet.Count > 0; // #930 N2: the same incomplete set as the last barrier ⇒ the clients were already told; a permanently refused @@ -952,6 +1031,7 @@ public sealed partial class ProjectedConditionAccess mapping.Live = done; mapping.Buffer = null; _lastListed.Remove(mapping.MappingId); + _definitiveRefused.Remove(mapping.MappingId); lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete; _owner._ledger.Commit(ConnectionId, mapping.MappingId, done.Records.Count); // ≤ the admitted total // #930: a completed (re)snapshot ends any retry; the mapping is known again. @@ -1011,6 +1091,7 @@ public sealed partial class ProjectedConditionAccess mapping.Live = null; mapping.Buffer = null; mapping.Observed = observed; + _definitiveRefused.Add(mapping.MappingId); // #930 N3: re-added in-stream on the long timer (ConditionCapacity is definitive), not left empty until the stream ends. mapping.Retrying = false; mapping.RetryDue = null; @@ -1048,6 +1129,7 @@ public sealed partial class ProjectedConditionAccess foreach (var key in _materialised) if (!listed.Contains(key)) keys.Add(key); } var unknown = states.Any(x => !x.Known); + var exempt = unknown ? TransientOwnedKeys(states) : null; var now = _owner._clock.GetUtcNow(); var updates = new List(); var removals = new List(); @@ -1065,6 +1147,9 @@ public sealed partial class ProjectedConditionAccess if (!_materialised.Contains(key)) continue; if (unknown) { + // #933 review r1 S1: a key a TRANSIENTLY unknown mapping listed itself is held without a bound — its origin + // may well still list it (T2); only a definitive refusal of that mapping starts its clock. + if (exempt is not null && exempt.Contains(key)) { _heldSince.Remove(key); stale.Add(key); continue; } // #933: the hold is bounded per key (MaxUnknownHold) — a durably Unavailable / Denied mapping no longer // keeps a retired condition forever. Past the bound it is removed (+ RefreshRequired), never known-inactive. if (!_heldSince.TryGetValue(key, out var since)) _heldSince[key] = since = now; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index cdb5bd793..18292622f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -205,6 +205,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess _sink = sink ?? (() => Sink); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); _options = options ?? ProjectedConditionOptions.Default; + // #933 review r1 N3: zero or negative would remove every held key at once — the bound must be a real duration. + if (_options.MaxUnknownHold <= TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(options), _options.MaxUnknownHold, "MaxUnknownHold must be positive."); _log = logger ?? NullLogger.Instance; _ledger = new ConditionLedger(_options); _mappings.Changed += OnMappingsChanged; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs index 10cde6f93..b427d04f6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs @@ -1115,15 +1115,16 @@ public sealed class GrpcDataProjectedConditionAccessTests stream.Complete("map-a"); await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); - // map-a retires x; map-b is unknown, so x is held stale (T2) — the stale mark is the must-arrive control. + // map-a retires x; map-b is unknown, so x is held stale (T2) — the stale mark is the must-arrive control. Review r1 N5: + // the runner's hold clock starts after this instant, so it is a true lower bound (no tolerance for a slow poll). + var beforeHeld = DateTime.UtcNow; stream.Records("map-a", Record(Key("x"), 4, removed: true)); await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x"))); - var heldAt = DateTime.UtcNow; f.Sink.Removed.ShouldBeEmpty("within the bound an unknown mapping still holds the key"); // …and past the bound it is removed (+ RefreshRequired at the sink), on the open stream, with no frame to prompt it. await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x"))); - (DateTime.UtcNow - heldAt).ShouldBeGreaterThan(hold - TimeSpan.FromMilliseconds(200), "not before MaxUnknownHold"); + (DateTime.UtcNow - beforeHeld).ShouldBeGreaterThanOrEqualTo(hold, "not before MaxUnknownHold"); f.Sink.Removed.Count(k => k == Key("x")).ShouldBe(1); f.Sink.Live.ShouldNotContain(Key("x")); f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Unavailable, "still unknown"); @@ -1171,6 +1172,158 @@ public sealed class GrpcDataProjectedConditionAccessTests Volatile.Read(ref f.Connections.MetadataCalls).ShouldBe(2); } + private static Fixture HoldFixture(int timeoutMs, TimeSpan hold, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) + { + var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold }, mappings); + foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs; + return f; + } + + [Fact] + public async Task Issue933_r1_S1_a_key_its_own_transiently_unknown_mapping_listed_is_held_past_the_bound_until_that_mapping_is_definitively_refused() + { + var hold = TimeSpan.FromSeconds(1); + await using var f = HoldFixture(300, hold, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var first = await f.NextStreamAsync(); + first.Ack(); + first.Begin("map-a", total: 0); + first.Complete("map-a"); + first.Begin("map-b", total: 1); + first.SnapshotRecords("map-b", Record(Key("x"), 3)); + first.Complete("map-b"); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); + + // map-b listed x; on the next stream its item is refused TRANSIENTLY (Unavailable) and its retries keep timing out. + first.End(); + var second = await f.NextStreamAsync(); + second.Ack(DataItemStatus.Unavailable, "map-b"); + second.Begin("map-a", total: 0); + second.Complete("map-a"); + await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x"))); + await Task.Delay(hold * 2.5, TestContext.Current.CancellationToken); + f.Sink.Removed.ShouldNotContain(Key("x"), "map-b's own key: its origin may still list it (T2) — no bound while map-b is transient"); + f.Sink.Live.ShouldContain(Key("x")); + + // Positive control: map-b's retry is refused DEFINITIVELY — now the bound runs, from then. + // Ack a FRESH re-add at once (its command stays current until the next re-add, ≥ 600 ms later on the backoff). + var adds = second.AddsOf("map-b"); + await f.WaitAsync(() => second.AddsOf("map-b") > adds); + var beforeDefinitive = DateTime.UtcNow; + second.AckAdd("map-b", DataItemStatus.Denied); + await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x"))); + (DateTime.UtcNow - beforeDefinitive).ShouldBeGreaterThanOrEqualTo(hold, "the clock starts at the definitive refusal"); + f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); + } + + [Fact] + public async Task Issue933_r1_S2_time_with_no_stream_past_its_barrier_does_not_count_toward_MaxUnknownHold() + { + var hold = TimeSpan.FromSeconds(1.5); + await using var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold }, + ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var first = await f.NextStreamAsync(); + first.Ack(DataItemStatus.Denied, "map-b"); // definitive: map-a's retired key is bounded + first.Begin("map-a", total: 1); + first.Records("map-a", Record(Key("x"), 3)); + first.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); + first.Records("map-a", Record(Key("x"), 4, removed: true)); + await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x"))); + + // The stream ends and the next one sits before its barrier (snapshot slow) for longer than the whole bound. + first.End(); + var second = await f.NextStreamAsync(); + await Task.Delay(hold * 2, TestContext.Current.CancellationToken); + f.Sink.Removed.ShouldBeEmpty("nothing is decided before a barrier"); + second.Ack(DataItemStatus.Denied, "map-b"); + second.Begin("map-a", total: 0); + second.Complete("map-a"); + await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.Complete); + await Task.Delay(300, TestContext.Current.CancellationToken); + f.Sink.Removed.ShouldBeEmpty("the outage did not count: x has been held well under the bound while a stream was live"); + + // Positive control: the remaining bound runs out on the live stream. + await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x"))); + (await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(100))).ShouldBeNull(); + } + + [Fact] + public async Task Issue933_r1_N2_with_no_sink_an_expired_hold_does_not_spin_the_loop() + { + var hold = TimeSpan.FromMilliseconds(300); + await using var f = new Fixture(Fixture.DefaultOptions with { LongRetryDelay = TimeSpan.FromMinutes(5), MaxUnknownHold = hold }, + ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(DataItemStatus.Denied, "map-b"); + stream.Begin("map-a", total: 1); + stream.Records("map-a", Record(Key("x"), 3)); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Sink.Live.Contains(Key("x"))); + stream.Records("map-a", Record(Key("x"), 4, removed: true)); + await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x"))); + f.SinkDetached = true; + stream.Records("map-a", Record(Key("y"), 1)); // one frame so the loop re-arms its timer without a sink + await Task.Delay(hold * 2, TestContext.Current.CancellationToken); + var before = Volatile.Read(ref f.SinkLookups); + await Task.Delay(500, TestContext.Current.CancellationToken); + (Volatile.Read(ref f.SinkLookups) - before).ShouldBeLessThan(50, "an expiry that cannot be applied must not re-arm the timer at zero"); + f.SinkDetached = false; + } + + [Fact] + public async Task Issue934_r1_N1_a_root_re_resolve_in_flight_is_cancelled_when_the_stream_ends() + { + await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + f.Connections.MetadataFails.Add(0); + f.Connections.MetadataBlockCall = 2; + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-b", total: 0); + stream.Complete("map-b"); + await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) == 2); // the re-resolve is in flight + f.Connections.MetadataCancelled.ShouldBe(0); + + stream.End(); // a natural end (no consumer cancellation) + await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCancelled) == 1); + f.Connections.MetadataFails.Clear(); + var next = await f.NextStreamAsync(); // positive control: the next stream resolves map-a at its open + next.Mappings.ShouldBe(["map-a", "map-b"]); + stream.AddsOf("map-a").ShouldBe(0, "the abandoned answer was never applied"); + } + + [Fact] + public async Task Issue934_r1_a_second_failed_in_stream_re_resolve_is_rescheduled_and_a_later_success_re_adds_once() + { + await using var f = TimedFixture(200, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10)); + f.Connections.MetadataFails.Add(0); // map-a's root keeps failing: at the open, and on the first two re-resolves + using var demand = f.Access.AcquireEventDemand(null); + var stream = await f.NextStreamAsync(); + stream.Ack(); + stream.Begin("map-b", total: 0); + stream.Complete("map-b"); + await f.WaitAsync(() => Volatile.Read(ref f.Connections.MetadataCalls) >= 3); + stream.AddsOf("map-a").ShouldBe(0); + f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable); + f.Connections.MetadataFails.Clear(); + await f.WaitAsync(() => stream.AddsOf("map-a") == 1); + stream.AckAdd("map-a"); + stream.Begin("map-a", total: 0); + stream.Complete("map-a"); + await f.WaitAsync(() => f.Access.MappingStatuses(Connection)!["map-a"] == ProjectedConditionMappingStatus.Complete); + stream.AddsOf("map-a").ShouldBe(1); + (await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(100))).ShouldBeNull("handled in-stream"); + } + + [Fact] + public void Issue933_r1_N3_a_non_positive_MaxUnknownHold_is_refused() + { + Should.Throw(() => new Fixture(Fixture.DefaultOptions with { MaxUnknownHold = TimeSpan.Zero }, ("map-a", DataRealm.Raw, 10))); + } + private sealed class Fixture : IAsyncDisposable { internal static readonly DataView DefaultRawPlacement = @@ -1185,6 +1338,11 @@ public sealed class GrpcDataProjectedConditionAccessTests public FakeSink Sink { get; } = new(); public FakeConnections Connections { get; } = new(); public ProjectedConditionAccess Access { get; } + /// #933 review r1 N2: when set, the sink is gone (the access sees null). + public volatile bool SinkDetached; + /// #933 review r1 N2: how often the access asked for the sink (a spinning loop asks continuously). + public int SinkLookups; + private IProjectedConditionSink? CurrentSink() { Interlocked.Increment(ref SinkLookups); return SinkDetached ? null : Sink; } public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings) : this(DefaultOptions, mappings) { } @@ -1200,7 +1358,7 @@ public sealed class GrpcDataProjectedConditionAccessTests Grant(NodePermissions.Browse | NodePermissions.Subscribe); Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions, m.Connection)).ToList()); var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System); - Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance); + Access = new ProjectedConditionAccess(Mappings, Connections, policy, CurrentSink, TimeProvider.System, options, NullLogger.Instance); } /// A4 review r2: over a real mapping source (e.g. ); is unset. @@ -1209,7 +1367,7 @@ public sealed class GrpcDataProjectedConditionAccessTests Grant(NodePermissions.Browse | NodePermissions.Subscribe); Mappings = null!; var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System); - Access = new ProjectedConditionAccess(mappings, Connections, policy, () => Sink, TimeProvider.System, options ?? DefaultOptions, NullLogger.Instance); + Access = new ProjectedConditionAccess(mappings, Connections, policy, CurrentSink, TimeProvider.System, options ?? DefaultOptions, NullLogger.Instance); } public void Grant(NodePermissions permissions) => @@ -1321,6 +1479,8 @@ public sealed class GrpcDataProjectedConditionAccessTests /// #934: when set, the metadata call with this 1-based number waits for . public int? MetadataBlockCall; public TaskCompletionSource MetadataRelease { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + /// #934 review r1 N1: blocked metadata calls whose token was cancelled. + public int MetadataCancelled; /// The serving roles of the next streams (Primary when empty). public Queue Roles { get; } = new(); public int PrimarySubscribes; @@ -1350,7 +1510,10 @@ public sealed class GrpcDataProjectedConditionAccessTests public async Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) { if (Interlocked.Increment(ref owner.MetadataCalls) == owner.MetadataBlockCall) - await owner.MetadataRelease.Task.WaitAsync(cancellationToken); // #934: a slow origin metadata answer + { + try { await owner.MetadataRelease.Task.WaitAsync(cancellationToken); } // #934: a slow origin metadata answer + catch (OperationCanceledException) { Interlocked.Increment(ref owner.MetadataCancelled); throw; } + } return Answer(request); } From e61db0168673a998c253fb64f8c533d0b4d74ee0 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 12:06:02 -0500 Subject: [PATCH 6/7] fix(grpc-data): removal admission keyed on the credential, lazy + bounded, no stale verdict write-back (#936 review r1) S3: the SDK installs a new identity object on every ActivateSession (decompiled Opc.Ua.Server 2.0.1: Session.UpdateUserIdentity assigns EffectiveIdentity; MonitoredItem/Subscription.EffectiveIdentity read the current session's), so an object-keyed admission forgot a re-activated or transferred session. Admission is now keyed on RoleCarryingUserIdentity.AdmissionKey (principal + api key id), and a removal also tells an item that passes the current gate (uncached). S4: the per-condition record is a lazily allocated locked HashSet (no ConditionalWeakTable per condition), one entry per credential, capped at 1024, dropped after the removal's RefreshRequired is decided. N4: Verdict writes back only while that instance is still live. Tests: OI re-activation (red on revert), unit S3/S4 + N4 (red on revert); docs. Also DataConnections.md for #933 r1 S1/S2. --- docs/AlarmTracking.md | 5 +- docs/DataConnections.md | 11 ++- .../ProjectedConditionRegistry.cs | 68 ++++++++++++++++--- .../Security/RoleCarryingUserIdentity.cs | 8 +++ .../ImportedConditionEventWireTests.cs | 32 +++++++++ .../ImportedConditionClassifierTests.cs | 48 +++++++++++++ 6 files changed, 159 insertions(+), 13 deletions(-) diff --git a/docs/AlarmTracking.md b/docs/AlarmTracking.md index 8904ae7b1..3bbdd4920 100644 --- a/docs/AlarmTracking.md +++ b/docs/AlarmTracking.md @@ -867,7 +867,10 @@ This section is what an OPC UA client of the **consumer** sees. Code: `OpcUaServ `MaxUnknownHold`). Removal emits **no** `NodeDeleted` model change. For a removal, "may see" means "its identity was admitted by the gate to that condition instance" (a delivery, a refresh replay or a Read/Browse of it), recorded per instance — not the current mapping set, which no longer admits anybody once the removal was caused by the mapping - leaving it (#936). The event carries no condition field (`SourceNode = Server`, `Message = "RefreshRequired"`), and a + leaving it (#936) — or "passes the current gate". The record is keyed on the credential (principal + API key id), not + the SDK identity object, because the SDK installs a new identity object on every ActivateSession: a session re-activated + on a new channel, or a transferred subscription, is still told. It is allocated on first admission, holds one entry per + credential (capped at 1024 per condition), and is dropped with the condition. The event carries no condition field (`SourceNode = Server`, `Message = "RefreshRequired"`), and a session never admitted to the condition is not sent one; - a resync leaves retained EventIds un-re-bindable (see EventIds below). - **Before the first barrier, a refresh returns nothing imported**, because nothing is materialised yet. Conditions appear diff --git a/docs/DataConnections.md b/docs/DataConnections.md index d38a6b63c..07fc7c2db 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -461,6 +461,15 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar (new EventIds). The hold cannot be narrowed to "mappings whose scope could list the key": an origin deploy can move a condition's placements into the unknown mapping's root, so the consumer cannot prove it. 20 min outlasts the transient retry cycle (snapshot timeout × 8) and the first two re-checks of a definitive refusal (`LongRetryDelay` 5 min, then 10). + - **A mapping's own keys are not bounded while it is only transiently unknown** (review r1 S1). A key the unknown mapping + itself listed when it was last known (its previous stream, or before a capacity reset) is held with no bound while that + mapping is `Pending` / `Unavailable` / retrying — its origin may well still list it, exactly as when the connection's + stream never opens at all (held stale indefinitely). Its clock starts only when that mapping's refusal is + **definitive** (`Denied` / `NotFound` / `Unsupported` / `ConditionCapacity`); that verdict is remembered across its + retries and stream ends until it completes a snapshot, so a durably denied mapping's retries do not restart the bound. + - **The clock runs only while a stream is past its barrier** (review r1 S2): it pauses when that stream ends and resumes + at the next barrier, so a connection outage never counts and a merely slow snapshot after one removes nothing. + - `MaxUnknownHold` must be positive (the access refuses zero or negative at construction). 7. **Known state (T2 invariant).** *The consumer never retires or clears an alarm that is active at the origin.* - A record with `state_known = false` never changes the consumer's last state. - A condition first seen unknown is materialised with `Quality = UncertainInitialValue` until a known record arrives. @@ -639,7 +648,7 @@ status and diagnostic), and each snapshot barrier (per-mapping status, record co | `ConditionCapacity` | The listing's `total` against the mapping's or export's `MaxConditions`, and the host caps. Narrow the remote root or raise the limits. | | Conditions `Uncertain` | The origin has not established their state: a scripted alarm has not completed an evaluation; a native driver has not signalled (see `…conditions.unsignalled`). | | Conditions `BadNoCommunication` | Stream down longer than `ConditionStaleTimeoutMilliseconds`, or the mapping was incomplete at the last barrier. | -| A retired condition stays `BadNoCommunication` while another mapping of the connection is `Unavailable` / `Denied` | Expected for up to `MaxUnknownHold` (20 min, #933): the unknown mapping might still list it, so it is held (T2). After that it is removed with `RefreshRequired` (logged Warning "held past MaxUnknownHold", naming the unknown mappings). Fix the unknown mapping (its refusal is on the AdminUI mappings line) to settle it sooner. | +| A retired condition stays `BadNoCommunication` while another mapping of the connection is `Unavailable` / `Denied` | Expected for up to `MaxUnknownHold` (20 min, #933) of live-stream time (an outage does not count): the unknown mapping might still list it, so it is held (T2). A key the unknown mapping listed itself is held with no bound until that mapping is refused definitively (Denied / NotFound / Unsupported / capacity). After that it is removed with `RefreshRequired` (logged Warning "held past MaxUnknownHold", naming the unknown mappings). Fix the unknown mapping (its refusal is on the AdminUI mappings line) to settle it sooner. | | Ack answers `BadEventIdUnknown` | The client holds an old EventId (superseded occurrence, or an origin restart that re-announced a different time). ConditionRefresh and ack with the new EventId. | | Ack answers "OutcomeUnknown" | Check the origin's audit log (`ZB.MOM.WW.OtOpcUa.DataConnections.Audit`) for the operation and watch the condition's events. Never replay blindly. | | All `ConditionId`s changed | `ConditionKeySecret` was rotated or differs between the origin pair members, or the connection was re-created under a new id. | diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index 4a3d7fd06..bfe7290fb 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -1,5 +1,4 @@ using System.Collections.Concurrent; -using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; @@ -57,15 +56,48 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec public bool IsNative { get; init; } /// - /// #936: every identity that passed the §5.4 gate for THIS condition instance (each delivery, refresh replay and - /// Read/Browse of it is gated, so any client that may hold it is here). Weak keys: a closed session's identity is - /// collected with it. Lets the removal RefreshRequired reach the holders even after the mapping that admitted them - /// left the deployed set — the current gate then admits nobody. + /// #936: the credentials (: principal + key id) that passed the §5.4 + /// gate for THIS condition instance — each delivery, refresh replay and Read/Browse of it is gated, so any client that + /// may hold it is here. Lets the removal RefreshRequired reach the holders even after the mapping that admitted them + /// left the deployed set (the current gate then admits nobody). + /// Review r1 S3: keyed on the credential, not the identity OBJECT — the SDK installs a new identity object on every + /// ActivateSession (verified: Session.UpdateUserIdentity assigns EffectiveIdentity, and + /// MonitoredItem.EffectiveIdentity reads it through the subscription's CURRENT session), so a re-activated or + /// transferred session would otherwise be forgotten. + /// Review r1 S4: allocated on the first admission only (most conditions are never admitted to anyone), a plain locked + /// set of strings shared with the identity — no finalizable containers, no dependent handles. Bounded: one entry per + /// distinct credential admitted (≤ deployed API keys + anonymous; NOT per session — a Server-object ConditionRefresh by + /// S sessions of K keys adds ≤ C × K entries), capped at ; past the cap a holder + /// falls back to the current gate at removal. Dropped when the condition is removed. /// - private readonly ConditionalWeakTable _admitted = new(); - private static readonly object AdmittedMark = new(); - public void Admit(object identity) => _admitted.AddOrUpdate(identity, AdmittedMark); - public bool WasAdmitted(object identity) => _admitted.TryGetValue(identity, out _); + private HashSet? _admitted; + + /// #936 review r1 S4: the per-condition cap on recorded credentials (far above any real key count). + internal const int MaxAdmittedCredentials = 1024; + + public void Admit(RoleCarryingUserIdentity identity) + { + var set = Volatile.Read(ref _admitted); + if (set is null) + { + var fresh = new HashSet(StringComparer.Ordinal); + set = Interlocked.CompareExchange(ref _admitted, fresh, null) ?? fresh; + } + lock (set) if (set.Count < MaxAdmittedCredentials) set.Add(identity.AdmissionKey); + } + + public bool WasAdmitted(object? identity) + { + if (identity is not RoleCarryingUserIdentity caller || Volatile.Read(ref _admitted) is not { } set) return false; + lock (set) return set.Contains(caller.AdmissionKey); + } + + /// Test/diagnostic observation: credentials recorded (0 when never admitted — the set is not allocated). + internal int AdmittedCount { get { var set = Volatile.Read(ref _admitted); if (set is null) return 0; lock (set) return set.Count; } } + internal bool AdmittedAllocated => Volatile.Read(ref _admitted) is not null; + + /// #936 review r1 S4: the removal's RefreshRequired has been decided — the record goes with the instance. + public void ForgetAdmitted() => Volatile.Write(ref _admitted, null); } /// @@ -156,6 +188,10 @@ internal sealed class ProjectedConditionRegistry : credentialExpires is { } expires && expires < now + PositiveVerdictTtl ? expires : now + PositiveVerdictTtl; lock (_verdictGate) { + // #936 review r1 N4: computed off the gate — a Remove may have purged this NodeId's verdicts meanwhile. Written back + // only while THIS instance is still the live one (Remove drops it from _byInstance before purging under this gate), + // so a same-NodeId re-creation never inherits a verdict computed for the removed instance. + if (!_byInstance.ContainsKey(condition.Alarm)) return allowed; if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation _verdicts[key] = (generation, condition.PlacementVersion, allowed, validUntil); } @@ -236,6 +272,10 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink }); } + /// #936 review r1 S3: the current §5.4 gate, uncached (a removed instance's removal decision). + private bool ImportedVisibleNow(object identity, ImportedCondition condition) => + ProjectedConditionAccess is { } access && identity is RoleCarryingUserIdentity caller && access.CanSee(caller, condition.Placements); + /// The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4). private ProjectedEventMarker ImportedMarker(IEventMonitoredItem item, ImportedCondition condition) { @@ -354,7 +394,11 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink // §5.2 "removal + RefreshRequired": a client holding a removed (e.g. Active/Retain) condition is told to refresh, after // which it no longer lists it. Outside Lock. #936: decided by who was ADMITTED to the condition, not by the current // mapping set — a removal caused by the mapping (or its connection) leaving the deployed set must still tell them. - if (removed.Count > 0) QueueRefreshRequired(targets, removed, removal: true); + if (removed.Count > 0) + { + QueueRefreshRequired(targets, removed, removal: true); + foreach (var c in removed) c.ForgetAdmitted(); + } } /// @@ -438,8 +482,10 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink /// private void QueueRefreshRequired(RefreshTargets targets, IReadOnlyList conditions, bool removal = false) { + // #936 review r1 S3: admitted under this credential, OR passes the current gate now (a holder past the per-condition + // cap, or anything the record missed) — uncached, so no verdict is written back for the removed instance. Func holds = removal - ? (item, c) => item.EffectiveIdentity is { } identity && c.WasAdmitted(identity) + ? (item, c) => item.EffectiveIdentity is { } identity && (c.WasAdmitted(identity) || ImportedVisibleNow(identity, c)) : ImportedVisibleTo; var send = new List(); foreach (var item in targets.ServerItems) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/RoleCarryingUserIdentity.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/RoleCarryingUserIdentity.cs index 53a95b869..25fc1a4ae 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/RoleCarryingUserIdentity.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/RoleCarryingUserIdentity.cs @@ -52,6 +52,7 @@ public sealed class RoleCarryingUserIdentity : RoleBasedIdentity Roles = [.. roles]; Principal = principal ?? string.Empty; ApiKeyId = apiKeyId; + AdmissionKey = Principal + "\u0000" + (apiKeyId ?? string.Empty); CredentialVersion = credentialVersion; CredentialExpiresUtc = credentialExpiresUtc; } @@ -84,6 +85,13 @@ public sealed class RoleCarryingUserIdentity : RoleBasedIdentity /// public string? ApiKeyId { get; } + /// + /// #936 review r1 S3: what stays the same across this credential's activations — principal + key id. The SDK builds a NEW + /// identity object on every ActivateSession (re-activation on a new channel, a transferred subscription), so anything + /// keyed on the object forgets the session. Sessions sharing one key share its grants, so they share this key. + /// + internal string AdmissionKey { get; } + /// Authenticated credential version captured at activation, never the secret. public string? CredentialVersion { get; } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs index 162fb35da..e071f81c0 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs @@ -446,6 +446,38 @@ public sealed class ImportedConditionEventWireTests deniedEvents.Of(deniedServer).Any(IsRefreshRequired).ShouldBeFalse("an identity never admitted to the condition is not told"); } + [Fact] + public async Task Issue936_r1_S3_a_session_re_activated_on_a_new_channel_is_still_told_of_the_removal() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("fu-936-reactivate", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var granted = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var sub = await SubscribeAsync(granted, events, ct); + var server = AddItem(sub, ObjectIds.Server); + await sub.ApplyChangesAsync(ct); + f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "held")); + await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "held")); + var sessionId = granted.SessionId; + object IdentityOnServer() => rig.Server.CurrentInstance.SessionManager.GetSessions().Single(x => x.Id == sessionId).EffectiveIdentity; + var admittedAs = IdentityOnServer(); + + // The client re-activates the SAME session on a new channel: the SDK installs a NEW identity object (SDK evidence). + await granted.ReconnectAsync(null, null, ct); + granted.SessionId.ShouldBe(sessionId); + IdentityOnServer().ShouldNotBeSameAs(admittedAs, "Session.UpdateUserIdentity replaces EffectiveIdentity on every ActivateSession"); + + // The condition stays quiet (no verdict for the new object), then the deploy removes its mapping and it. + f.Access.Allowed.Clear(); + Interlocked.Increment(ref f.Access.Generation); + var before = rig.Nm.ImportedRefreshRequiredQueued; + rig.Nm.RemoveConditions(Connection, [Key1]); + await Events.WaitUntilAsync(() => events.Of(server).Any(IsRefreshRequired)); + (rig.Nm.ImportedRefreshRequiredQueued - before).ShouldBe(1, "the re-activated holder is told — admission is per credential"); + } + [Fact] public async Task Deviation8_ConditionRefresh_replays_hundreds_of_imported_conditions_in_chunks_between_RefreshStart_and_RefreshEnd() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs index 7625958b1..69bc0356f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs @@ -182,6 +182,7 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable { var registry = new ProjectedConditionRegistry(); var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k"); + registry.Add(condition); // #936 review r1 N4: verdicts are cached only for a live instance var computes = 0; bool Allow() { computes++; return true; } var now = DateTimeOffset.UtcNow; @@ -198,6 +199,53 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable computes.ShouldBe(4, "a positive verdict lives at most the TTL"); } + [Fact] + public void Issue936_r1_N4_a_verdict_computed_while_its_condition_was_removed_is_not_served_to_a_same_NodeId_re_creation() + { + var registry = new ProjectedConditionRegistry(); + var id = new NodeId("c", 9); + var removed = new ImportedCondition(new AlarmConditionState(null) { NodeId = id }, "conn", "k"); + registry.Add(removed); + var caller = new object(); + // The compute runs off the verdict gate; the condition is removed while it runs (Remove purges this NodeId's verdicts). + registry.Verdict(caller, removed, 1, DateTimeOffset.UtcNow, null, () => { registry.Remove(removed); return true; }).ShouldBeTrue(); + + var recreated = new ImportedCondition(new AlarmConditionState(null) { NodeId = id }, "conn", "k"); + registry.Add(recreated); + var computes = 0; + registry.Verdict(caller, recreated, 1, DateTimeOffset.UtcNow, null, () => { computes++; return false; }) + .ShouldBeFalse("the new instance is decided (and admitted) afresh, not served the removed instance's verdict"); + computes.ShouldBe(1); + // Positive control: a live instance's verdict IS cached. + registry.Verdict(caller, recreated, 1, DateTimeOffset.UtcNow, null, () => { computes++; return true; }).ShouldBeFalse(); + computes.ShouldBe(1); + } + + [Fact] + public void Issue936_r1_S3_S4_admission_is_recorded_lazily_per_credential_and_survives_a_new_identity_object() + { + var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k"); + condition.AdmittedAllocated.ShouldBeFalse("nothing is allocated for a condition nobody was admitted to"); + RoleCarryingUserIdentity Identity(string principal, string? key) => + new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, key); + var first = Identity("reader", "key-a"); + condition.WasAdmitted(first).ShouldBeFalse(); + condition.Admit(first); + // The SDK builds a NEW identity object on every ActivateSession (re-activation, transfer): still admitted. + condition.WasAdmitted(Identity("reader", "key-a")).ShouldBeTrue(); + condition.WasAdmitted(Identity("reader", "key-b")).ShouldBeFalse("another key is another credential"); + condition.WasAdmitted(Identity("other", "key-a")).ShouldBeFalse(); + condition.WasAdmitted(new object()).ShouldBeFalse(); + // Bounded by credentials, not sessions: many sessions of one key are one entry. + for (var i = 0; i < 50; i++) condition.Admit(Identity("reader", "key-a")); + condition.AdmittedCount.ShouldBe(1); + for (var i = 0; i < ImportedCondition.MaxAdmittedCredentials + 10; i++) condition.Admit(Identity("p" + i, "k" + i)); + condition.AdmittedCount.ShouldBe(ImportedCondition.MaxAdmittedCredentials, "capped per condition"); + condition.ForgetAdmitted(); + condition.AdmittedAllocated.ShouldBeFalse("dropped with the removal"); + condition.WasAdmitted(first).ShouldBeFalse(); + } + private async Task BootAsync() { var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions From 9929ded66cb867cc65afe1a3847ab85838c50bac Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 12:36:33 -0500 Subject: [PATCH 7/7] =?UTF-8?q?docs(grpc-data):=20A4=20evidence=20?= =?UTF-8?q?=E2=80=94=20follow-ups=20review=20round=201=20(#933/#934/#936):?= =?UTF-8?q?=20outcomes,=20red/green,=20S3=20SDK=20evidence,=20gates,=20liv?= =?UTF-8?q?e=20fu933-2=208/8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/plans/evidence/grpc-data-ext/A4.md | 128 ++++++++++++++++++++++++ 1 file changed, 128 insertions(+) diff --git a/docs/plans/evidence/grpc-data-ext/A4.md b/docs/plans/evidence/grpc-data-ext/A4.md index 262d7e358..f867e0303 100644 --- a/docs/plans/evidence/grpc-data-ext/A4.md +++ b/docs/plans/evidence/grpc-data-ext/A4.md @@ -783,3 +783,131 @@ The sequence was `rig.py up --run-id fu933-1 --conditions` → `seed` → 85 s The live scenarios do not exercise a 20 min unknown hold, a slow origin metadata answer, or a mapping removal while a client holds a condition. Those three behaviours are pinned by the unit/OI tests above; the live run shows no regression. + +## Follow-ups review round 1 (#933/#934/#936) + +The review (approve-with-changes) found two gaps in #933, two in #936 and five NITs. Every fix below has a test that was +run red with the fix reverted and green with it restored. + +### S1 (#933) — the bound removed the unknown mapping's own conditions + +A key held because ANOTHER mapping is unknown is still bounded by `MaxUnknownHold`. A key the unknown mapping listed +itself the last time it was known (`_lastListed`: its previous stream, or before a capacity reset) is held with no bound +while that mapping is only transiently unknown (`Pending`, `Unavailable`, retrying). Its clock starts only when the +mapping's refusal is definitive (`Denied` / `NotFound` / `Unsupported` / `ConditionCapacity`). + +- The definitive verdict is kept in a runner set (`_definitiveRefused`). It survives in-stream retries (a retry resets + `Refusal` to null), stream ends and hand-overs, and is cleared when the mapping completes a snapshot. Without it, each + long retry of a durably denied mapping would make it transient again, restart its keys' clocks, and they would never + expire, because the retry backoff tops out at 20 min. +- When the set of transient mappings changes, the loop re-decides the held keys (`ReconcileUnlisted`). Exempt keys drop + their clock; the others start it. +- **The single-mapping and never-opening-stream cases are now consistent.** A connection whose stream never opens holds + its keys stale indefinitely. A mapping that is only transiently unknown now does the same with its own keys. Only a + definitive refusal leads to the bounded removal. + +### S2 (#933) — the hold clock counted time when no stream was open + +The clock now runs only while a stream is past its barrier. The stream's `finally` records `_heldPausedAt` if that stream +passed its barrier. The next barrier shifts every `_heldSince` forward by the paused time before its full re-diff. +`_heldPausedAt` is handed over with `_heldSince`. + +### S3 (#936) — admission was keyed on the identity object + +SDK evidence comes from `Opc.Ua.Server` 2.0.1 `lib/net9.0`, decompiled with ilspycmd: + +- `Session.UpdateUserIdentity`, which runs on every ActivateSession, assigns `Identity` and `EffectiveIdentity` the new + objects. +- `MonitoredItem.EffectiveIdentity` returns `m_subscription?.EffectiveIdentity`. +- `Subscription.EffectiveIdentity` returns `Session.EffectiveIdentity`, or the saved owner identity when it has no session. + +So a re-activated session, or a subscription transferred to another session, presents a new `RoleCarryingUserIdentity` +object. `OpcUaApplicationHost` builds that object per activation. The OI test also asserts directly that +`EffectiveIdentity` is a different object after `ReconnectAsync`. + +- **Decision:** admission is keyed on `RoleCarryingUserIdentity.AdmissionKey` = principal + `\0` + API key id. It is + computed once per identity object, and the set references the identity's string. + - The session id was rejected because it does not survive a subscription transfer to a new session. + - Sessions sharing one key share its grants, so they also share the record. A sibling session of an admitted key may + receive a content-free RefreshRequired. That is the same audience the old current-gate check had. +- A removal now sends RefreshRequired when `WasAdmitted(identity) || ImportedVisibleNow(identity, c)`. `ImportedVisibleNow` + is the current gate, uncached, so nothing is cached for the removed instance. + +### S4 (#936) — one ConditionalWeakTable per condition + +`ImportedCondition` now holds a `HashSet?`. + +- It is allocated by CAS on the first admission and locked on itself. A condition nobody was admitted to allocates + nothing. There are no finalizable containers and no dependent handles. +- **Bound:** one entry per distinct credential admitted, capped at `MaxAdmittedCredentials` = 1024 per condition. Past the + cap, a holder falls back to the current gate at removal. A Server-object ConditionRefresh by S sessions of K keys adds at + most C × K entries, where K ≤ deployed API keys + anonymous. The old structure grew S × C. +- The record is dropped (`ForgetAdmitted`) once the removal's RefreshRequired has been decided. Other removal paths drop + the instance itself. + +### NITs + +- **N1 (#934):** in-stream root re-resolves run under a per-stream `fetches` source. It is linked to the stream token and + cancelled in the stream's `finally` however the stream ends. Cancelling the stream token itself was rejected: it would + also abort the subscription's graceful dispose. +- **N2 (#933):** no held-key expiry is armed when there is no sink. +- **N3 (#933):** a `MaxUnknownHold` of zero or less makes the `ProjectedConditionAccess` constructor throw + `ArgumentOutOfRangeException`. +- **N4 (#936):** `Verdict` writes back only while `_byInstance` still holds that instance. `Remove` drops the instance from + `_byInstance` before purging under the same gate. + - The existing S2 TTL unit test now `Add`s its condition first. Verdicts are only cached for live instances. +- **N5:** the #933 test's lower bound is taken BEFORE the record that starts the hold. It is asserted `≥ hold` with no + tolerance. + +### Tests (red on revert → green) + +| Test | Revert used | Red | +|---|---|---| +| `Issue933_r1_S1_…held_past_the_bound_until_that_mapping_is_definitively_refused` (map-b listed x, then transiently refused on the next stream ⇒ x not removed after 2.5 × hold; positive control: a Denied re-add ack ⇒ removed ≥ hold after it) | exemption disabled | **red** (x removed while map-b transient) | +| `Issue933_r1_S2_time_with_no_stream_past_its_barrier_does_not_count…` (held, stream ends, next stream sits 2 × hold before its barrier ⇒ not removed at the barrier; removed later on the live stream) | gap shift disabled | **red** ("Removed should be empty") | +| `Issue933_r1_N2_with_no_sink_an_expired_hold_does_not_spin_the_loop` (sink lookups in 500 ms after expiry < 50) | `HeldExpiry()` armed without a sink | **red** | +| `Issue933_r1_N3_a_non_positive_MaxUnknownHold_is_refused` | guard removed | **red** | +| `Issue934_r1_N1_a_root_re_resolve_in_flight_is_cancelled_when_the_stream_ends` (natural end ⇒ the blocked metadata call observes cancellation; next stream resolves; the abandoned answer is never applied) | `fetches.Cancel()` removed | **red** (10 s wait) | +| `Issue934_r1_a_second_failed_in_stream_re_resolve_is_rescheduled…` | — (new coverage, no fix) | green | +| OI `Issue936_r1_S3_a_session_re_activated_on_a_new_channel_is_still_told_of_the_removal` | `AdmissionKey` = a per-object GUID (object keying) | **red** | +| unit `Issue936_r1_S3_S4_admission_is_recorded_lazily_per_credential…` | GUID key / eager allocation | **red** for each | +| unit `Issue936_r1_N4_a_verdict_computed_while_its_condition_was_removed…` | write-back guard removed | **red** | + +The `|| ImportedVisibleNow` removal fallback has no test of its own. Once admission is keyed on the credential, the +fallback is reachable only past the 1024-credential cap, or for an identity the gate admits now but never admitted +before. + +Commits: `9d969c47` (#933 S1/S2/N2/N3/N5, #934 N1), `e61db016` (#936 S3/S4/N4 + docs), plus this evidence commit. + +### Gates (`fu-consumer-933` at `e61db016`) + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors | +| `run-unit-phase.py A4` / `A3` / `A2` | all `passed`: A4 Runtime 90 + AdminUI 14; A3 Runtime 90 + OpcUaServer 33 + Host 82; A2 157 + 83 + 32 + 30 + 12 + 12 + 5 (`20261125T170708…`, `…170812…`, `…170934…`) | +| Host.Tests `DataConnections` | 207 passed | +| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2091 passed, 3 skipped, 0 failed (#920 did not fire) | +| OpcUaServer.Tests full | 1460 passed, 2 skipped | +| OI combined (`Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral / ImportedConditionEventWireTests), once | 142 passed, 1 skipped (opt-in L2 harness) | +| `git diff master -- '*Goldens.cs'` | empty | + +### Full A01–A08 run — run `fu933-2` (after review round 1) + +The run was taken under the shared rig lock. The sequence was `rig.py up --run-id fu933-2 --conditions` → `seed` → 85 s → +`deploy --timeout 300` → `conditions_a3_smoke.py` (`passed: true`) → `conditions_scenarios.py` (all eight, one session) +→ `rig.py down` (exit 0, 0 run containers left, lock released). Evidence is in `artifacts/grpc-data/runs/fu933-2/evidence/`. +**8/8 PASS.** + +| Scenario | Result | Checks | Notes | +|---|---|---|---| +| A01 | PASS | 13/13 | | +| A02 | PASS | 10/10 | | +| A03 | PASS | 20/20 | `p1_exactly_one_refresh_required_after_held_takeover` and `p2_refresh_required_received` pass | +| A04 | PASS | 16/16 | | +| A05 | PASS | 4/4 | The denied session still sees no imported event (removal now = admitted credential OR the current gate) | +| A06 | PASS | 11/11 | | +| A07 | PASS | 8/8 | | +| A08 | PASS | 10/10 | | + +As in `fu933-1`, the live scenarios do not exercise a 20 min hold, a stream outage during a hold, a session re-activation +before a removal, or a slow metadata answer. The unit and OI tests above pin those.