diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 82a3ed310..ae21b2f88 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -610,7 +610,10 @@ An origin streams its alarm condition state to a peer that negotiated `condition empty and the held conditions are removed. (Browse anchors still stay retained until a successful activation.) - An attempt that never completes is bounded. The held conditions go `BadNoCommunication` on the connection's stale timeout, as for any stream gap, and are removed past `ProjectedConditionOptions.MaxHold` (5 min, 2.5× the deploy apply - deadline). Until then they stay charged to the host caps and diagnostics show the connection as `held`. + deadline). Until then they stay charged to the host caps and diagnostics show the connection as `held`. Both clocks + run from the start of the hold (#1080). The stale mark still waits for the held runner's loop to unwind, so no late + Good from that loop can follow it. A mark that falls due before the unwind lands at the unwind. It used to be armed + only at the unwind, so under load it came late, or the MaxHold release ended the hold first and it never came. - The runner that takes a held set over sends **RefreshRequired once** at its first barrier. While the set was held nothing imported was visible, so an event queued then was dropped and a ConditionRefresh replayed nothing. RefreshRequired is a Server-object event, not a condition event: EventIds are kept and no condition event is added. 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 ef836c82b..a946f8cf8 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 @@ -395,27 +395,32 @@ public sealed partial class ProjectedConditionAccess /// /// A4 review r2 S2 (under the owner's _gate, right after without removal): the hold is bounded. - /// fires at MaxHold (the owner releases); after the loop has stopped, the held - /// conditions go BadNoCommunication on the connection's stale timeout — a hold is a stream gap (§5.1 T2: unknown, - /// never known-inactive). (takeover / release) disarms both. + /// fires at MaxHold (the owner releases); the held conditions go + /// BadNoCommunication on the connection's stale timeout — a hold is a stream gap (§5.1 T2: unknown, never + /// known-inactive). (takeover / release) disarms both. + /// + /// #1080: the stale timeout runs from the hold's START, as MaxHold does. It used to be armed only once the loop had + /// unwound, so under load (a slow unwind) the mark came late, or the MaxHold release ended the hold first and the + /// mark never came. The mark still never lands before the unwind (a late Good from that loop could follow it): one + /// due earlier waits for the unwind and lands then. + /// /// public void Hold(ITimer release) { - lock (_staleGate) { _holding = true; _holdRelease = release; } - _ = _stopped.ContinueWith(_ => + var stopped = _stopped; + var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds))); + lock (_staleGate) { - lock (_staleGate) + _holding = true; _holdRelease = release; + _holdStale = _owner._clock.CreateTimer(_ => _ = stopped.ContinueWith(_ => { - if (!_holding || _materialised.Count == 0) return; - var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds))); - _holdStale = _owner._clock.CreateTimer(_ => - { - // Under the same gate EndHold takes before any takeover, so a mark never lands after the successor began. - lock (_staleGate) - if (_holding) _owner._sink()?.MarkConnectionStale(ConnectionId); - }, null, timeout, Timeout.InfiniteTimeSpan); - } - }, TaskScheduler.Default); + // Under the same gate EndHold takes before any takeover, so a mark never lands after the successor began. + // The loop has unwound here, so its materialised set is settled; nothing held ⇒ nothing to mark. + lock (_staleGate) + if (_holding && _materialised.Count > 0) _owner._sink()?.MarkConnectionStale(ConnectionId); + }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default), + null, timeout, Timeout.InfiniteTimeSpan); + } } /// A4 review r2 S2: the hold ended (taken over, released, disposed) — no stale mark or release fires after this. 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 7e023176a..68b689111 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 @@ -1039,6 +1039,8 @@ public sealed class GrpcDataProjectedConditionAccessTests // (as in a full parallel Runtime.Tests run): the stale mark landed ~1.9 s after the hold while the release fired at // ~0.9 s — the release ends the hold first, so the stale mark is skipped (or the test's later check sees the removal). // Production keeps minutes of margin (MaxHold 5 min). 5 s keeps the ordering under that load (~3 s of margin). + // #1080: the stale timeout now runs from the hold's start (a mark due before the unwind lands at the unwind), so only + // an unwind slower than MaxHold could still reorder them; the fake-clock Issue1080_* tests pin that timing exactly. await using var f = new Fixture(Fixture.DefaultOptions with { MaxHold = TimeSpan.FromSeconds(5) }, ("map-a", DataRealm.Raw, 10)); using var demand = f.Access.AcquireEventDemand(null); await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); @@ -1059,6 +1061,66 @@ public sealed class GrpcDataProjectedConditionAccessTests f.Access.Diagnostics.CaptureConsumer(Connection).ShouldBeNull(); } + /// + /// #1080: the held set's stale mark is timed from the HOLD's start, as MaxHold is — not from the loop's unwind. Here the + /// held runner's loop cannot unwind (its connection lease release is gated) until fake time is 50 ms short of MaxHold. + /// The mark waits for the unwind (no late Good from that loop can follow it), then lands at once. It used to be armed + /// only at the unwind, a further stale timeout later — past MaxHold here, so the release ended the hold first and the + /// held conditions never went stale. + /// + [Fact] + public async Task Issue1080_a_held_sets_stale_mark_is_timed_from_the_hold_not_from_the_loop_unwind() + { + var clock = new Harness.ManualTimeProvider(); + var maxHold = TimeSpan.FromSeconds(1); + await using var f = new Fixture(clock, Fixture.DefaultOptions with { MaxHold = maxHold }, ("map-a", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); + await f.WaitAsync(() => f.Sink.Live.Count == 1); + + var unwind = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + f.Connections.LeaseReleaseGate = unwind; + ((List)f.Mappings.Current).Clear(); f.Mappings.Suspended = true; f.Mappings.Raise(); + await f.WaitAsync(() => f.Access.Diagnostics.CaptureConsumer(Connection)?.StreamState == "held"); + + // Past the stale timeout (100 ms), loop still unwinding: no mark yet — it must not precede the unwind. + clock.Advance(maxHold - TimeSpan.FromMilliseconds(50)); + await Task.Delay(200, TestContext.Current.CancellationToken); + f.Sink.Stale.ShouldBeEmpty("a stale mark must not land before the held runner's loop has unwound"); + + // The unwind completes: the mark, due since the hold's start + 100 ms, lands now — the clock does not move. + unwind.SetResult(); + await f.WaitAsync(() => f.Sink.Stale.Contains(Connection)); + f.Sink.Removed.ShouldBeEmpty("stale, not removed, before MaxHold"); + + // MaxHold (from the hold's start) still releases the set. + clock.Advance(TimeSpan.FromMilliseconds(50)); + await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x"))); + f.Sink.Live.ShouldBeEmpty(); + f.Sink.Stale.Count(x => x == Connection).ShouldBe(1); + } + + /// #1080: with a prompt unwind the stale mark lands exactly at hold start + the stale timeout (fake clock). + [Fact] + public async Task Issue1080_a_held_sets_stale_mark_lands_at_the_stale_timeout_after_the_hold() + { + var clock = new Harness.ManualTimeProvider(); + await using var f = new Fixture(clock, Fixture.DefaultOptions with { MaxHold = TimeSpan.FromSeconds(1) }, ("map-a", DataRealm.Raw, 10)); + using var demand = f.Access.AcquireEventDemand(null); + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); + await f.WaitAsync(() => f.Sink.Live.Count == 1); + + ((List)f.Mappings.Current).Clear(); f.Mappings.Suspended = true; f.Mappings.Raise(); + await f.WaitAsync(() => f.Access.Diagnostics.CaptureConsumer(Connection)?.StreamState == "held"); + + clock.Advance(TimeSpan.FromMilliseconds(99)); + await Task.Delay(100, TestContext.Current.CancellationToken); + f.Sink.Stale.ShouldBeEmpty("not before the stale timeout"); + clock.Advance(TimeSpan.FromMilliseconds(1)); + await f.WaitAsync(() => f.Sink.Stale.Contains(Connection)); // must-arrive: the timeout from the hold's start + f.Sink.Removed.ShouldBeEmpty(); + } + /// S3: the takeover's RefreshRequired is sent once — a later stream end with a complete re-snapshot sends none. [Fact] public async Task R2_S3_a_runner_taking_over_a_held_set_sends_RefreshRequired_once_at_its_first_barrier() @@ -1363,11 +1425,18 @@ public sealed class GrpcDataProjectedConditionAccessTests : this(options, mappings.Select(m => (m.Id, m.Realm, m.MaxConditions, Connection)).ToArray()) { } public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions, string Connection)[] mappings) + : this(TimeProvider.System, options, mappings) { } + + /// #1080: the access runs on (its timers: hold, stale, linger, snapshot, reconnect). + public Fixture(TimeProvider clock, ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions)[] mappings) + : this(clock, options, mappings.Select(m => (m.Id, m.Realm, m.MaxConditions, Connection)).ToArray()) { } + + private Fixture(TimeProvider clock, ProjectedConditionOptions options, (string Id, DataRealm Realm, int MaxConditions, string Connection)[] mappings) { 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, CurrentSink, TimeProvider.System, options, NullLogger.Instance); + Access = new ProjectedConditionAccess(Mappings, Connections, policy, CurrentSink, clock, options, NullLogger.Instance); } /// A4 review r2: over a real mapping source (e.g. ); is unset. @@ -1493,14 +1562,16 @@ public sealed class GrpcDataProjectedConditionAccessTests /// The serving roles of the next streams (Primary when empty). public Queue Roles { get; } = new(); public int PrimarySubscribes; + /// #1080: when set, a runner's connection lease is released only once this completes (a slow loop unwind). + public volatile TaskCompletionSource? LeaseReleaseGate; public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => - ValueTask.FromResult(new Lease(new FakeConnection(this))); + ValueTask.FromResult(new Lease(this, new FakeConnection(this))); - private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + private sealed class Lease(FakeConnections owner, IDataConnection connection) : IGrpcDataAdapterConnectionLease { public IDataConnection Connection => connection; public CancellationToken CancellationToken => CancellationToken.None; - public ValueTask DisposeAsync() => ValueTask.CompletedTask; + public ValueTask DisposeAsync() => owner.LeaseReleaseGate is { } gate ? new ValueTask(gate.Task) : ValueTask.CompletedTask; } }