From 6b19f4add6ef01bb6475541cae8031f7ee91b016 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:20:02 -0500 Subject: [PATCH] feat(resilience): #1047 non-retrying AcquisitionSubscribe capability wraps SubscribeAcquisitionAsync (breaker + /hosts telemetry), OTOPCUA0001 suppression removed New DriverCapability.AcquisitionSubscribe (appended): RetryCount 0 in every tier and forced 0 by the parser, 30 s timeout (outlasts the actor's 10 s acquisition timeout), breaker 5 (Tier C none). PendingAcquisition.Start routes through the invoker keyed on the driver instance; an open breaker fails fast and the capacity reservation is released. Co-Authored-By: Claude --- docs/DriverLifecycle.md | 7 + .../DriverCapability.cs | 10 ++ .../Resilience/DriverResilienceOptions.cs | 6 + .../DriverResilienceOptionsParser.cs | 9 ++ .../Drivers/DriverInstanceActor.cs | 26 ++-- .../DriverResilienceOptionsParserTests.cs | 12 ++ .../DriverResilienceOptionsTests.cs | 16 ++ .../GrpcDataAcquisitionResilienceTests.cs | 146 ++++++++++++++++++ 8 files changed, 219 insertions(+), 13 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionResilienceTests.cs diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index c0538c9a8..6a0a83ca2 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -634,6 +634,13 @@ before touching it: the pipeline timeout is counted once by `OnTimeout`), and any success resets it. A Tier A Read that fails 4 attempts now reads 4, not 3. The non-idempotent write pipeline (cached under `host::non-idempotent`) records its failures and breaker on the CALLER's host, where its success already reset them — it used to show a phantom `::non-idempotent` row. +- **Acknowledged acquisition has its own capability, `AcquisitionSubscribe` (#1047).** gRPC-data acquisition + (`IAcknowledgedAcquisitionSource.SubscribeAcquisitionAsync`) used to call the source unwrapped (OTOPCUA0001 suppressed), + because the Subscribe pipeline retries and a retry would orphan a physical handle `PendingAcquisition` alone owns. It now runs + through the invoker on `AcquisitionSubscribe`: never retries (the parser forces 0), tier timeout 30 s — deliberately longer than + the actor's 10 s acquisition timeout, which stays the effective bound — breaker 5 (Tier C: none). Polly's timeout awaits the + call and passes a completed result through, so the handle contract is unchanged; an open breaker fails the acquisition fast + without calling the source and the reservation is released like any failure. Keyed on the driver instance. - **The pipeline's own timeout is a failure (#999 / review K-6).** A call that outlasts its capability timeout (a blackholed device that never answers) used to reach the breaker as an `OperationCanceledException`, which both predicates excluded — every call burned the full timeout diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DriverCapability.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DriverCapability.cs index 9ce94616e..da9315e42 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DriverCapability.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DriverCapability.cs @@ -47,4 +47,14 @@ public enum DriverCapability /// window, so a Read-sized threshold of 5 could never open on connect failures. /// Initialize, + + /// + /// — establishing an acknowledged gRPC-data + /// acquisition (lmxopcua#1047). Does NOT retry (the parser forces 0): a cancelled or superseded attempt can still + /// complete with a physical handle the runtime's pending acquisition alone owns, so a pipeline retry would orphan it. + /// The tier-default timeout (30 s) is deliberately longer than the runtime's own acquisition timeout (10 s by + /// default), which stays the effective bound; the pipeline adds the breaker and the /hosts telemetry. + /// Appended last so the existing members keep their numeric values. + /// + AcquisitionSubscribe, } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptions.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptions.cs index 6a207da5c..0283bd770 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptions.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptions.cs @@ -86,6 +86,8 @@ public sealed record DriverResilienceOptions // timer fires every 10 s, so at most three init attempts fit one window; a threshold of 5 // could never open on connect failures. [DriverCapability.Initialize] = new(TimeoutSeconds: 5, RetryCount: 0, BreakerFailureThreshold: 2), + // #1047: never retries (a retry would orphan an acquisition handle); 30 s outlasts the runtime's 10 s acquisition timeout. + [DriverCapability.AcquisitionSubscribe] = new(TimeoutSeconds: 30, RetryCount: 0, BreakerFailureThreshold: 5), }, DriverTier.B => new Dictionary { @@ -98,6 +100,8 @@ public sealed record DriverResilienceOptions [DriverCapability.AlarmAcknowledge] = new(TimeoutSeconds: 8, RetryCount: 0, BreakerFailureThreshold: 5), // See the Tier A Initialize note: threshold 2 is cadence-reachability, not a tuning choice. [DriverCapability.Initialize] = new(TimeoutSeconds: 8, RetryCount: 0, BreakerFailureThreshold: 2), + // #1047: never retries (a retry would orphan an acquisition handle); 30 s outlasts the runtime's 10 s acquisition timeout. + [DriverCapability.AcquisitionSubscribe] = new(TimeoutSeconds: 30, RetryCount: 0, BreakerFailureThreshold: 5), }, DriverTier.C => new Dictionary { @@ -110,6 +114,8 @@ public sealed record DriverResilienceOptions [DriverCapability.AlarmAcknowledge] = new(TimeoutSeconds: 15, RetryCount: 0, BreakerFailureThreshold: 0), // Tier C stays breaker-less like every other Tier C capability (process-level supervision). [DriverCapability.Initialize] = new(TimeoutSeconds: 15, RetryCount: 0, BreakerFailureThreshold: 0), + // #1047: never retries (a retry would orphan an acquisition handle); 30 s outlasts the runtime's 10 s acquisition timeout. + [DriverCapability.AcquisitionSubscribe] = new(TimeoutSeconds: 30, RetryCount: 0, BreakerFailureThreshold: 0), }, _ => throw new ArgumentOutOfRangeException(nameof(tier), tier, $"No default policy table defined for tier {tier}."), }; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs index f1ad841e7..ed69d2c09 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs @@ -200,6 +200,15 @@ public static class DriverResilienceOptionsParser retry = 0; } + // #1047: an acquisition attempt that is cancelled or superseded can still complete with a physical handle that + // only the runtime's pending acquisition may release; a pipeline retry would orphan it. + if (capability == DriverCapability.AcquisitionSubscribe && retry > 0) + { + AppendDiagnostic(ref diagnostic, + $"{capability} never retries (a retry would orphan an acquisition handle); retryCount override ignored."); + retry = 0; + } + var breaker = merged.BreakerFailureThreshold; if (breaker < ResiliencePolicyRanges.MinBreakerFailureThreshold) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index d1dc07942..eafdec723 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -2246,19 +2246,19 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers _finished.TrySetResult(true); } - // OTOPCUA0001 (#1001/S-11) is suppressed here ON PURPOSE, not overlooked. The stock Subscribe - // pipeline cannot wrap this call safely: it retries (3x on tiers A/B) and times out per attempt - // (5-8 s, shorter than the actor's 10 s acquisition timeout), but a SubscribeAcquisitionAsync - // attempt that is cancelled or superseded may still complete later with a physical handle, and - // the contract makes THIS class (PendingAcquisition) the sole owner of releasing it. A Polly - // retry/timeout would orphan those handles and desync the capacity reservation. Establishment - // is already bounded by the actor's own acquisition timeout + the _stop token. Follow-up: give - // the invoker a non-retrying acquisition capability so breaker/telemetry cover it too. + // #1047 (#1001/S-11 follow-up): wrapped on its OWN capability, AcquisitionSubscribe, which never retries + // (the parser forces 0) and whose 30 s tier timeout outlasts the actor's 10 s acquisition timeout. The stock + // Subscribe pipeline could not wrap this: it retries, and a SubscribeAcquisitionAsync attempt that is cancelled + // or superseded may still complete with a physical handle THIS class alone must release — a retry would orphan + // it. With no retry the pipeline is transparent to that contract (Polly's timeout awaits the call and passes a + // completed result through; only an OCE becomes TimeoutRejectedException, an ordinary failure here), and the + // breaker + /hosts telemetry now cover acquisition. An open breaker fails fast without calling the source, which + // ObserveAsync handles like any failure (reservation released). Keyed on the driver instance like a bulk Subscribe. internal void Start(IAcknowledgedAcquisitionSource source, AcquisitionSubscriptionRequest request, - Action callback) => _ = ObserveAsync(Task.Run(() => -#pragma warning disable OTOPCUA0001 - source.SubscribeAcquisitionAsync(request, callback, _stop.Token))); -#pragma warning restore OTOPCUA0001 + Action callback, IDriverCapabilityInvoker invoker, string hostKey) => _ = ObserveAsync(Task.Run(async () => + await invoker.ExecuteAsync(DriverCapability.AcquisitionSubscribe, hostKey, + async ct => await source.SubscribeAcquisitionAsync(request, callback, ct).ConfigureAwait(false), + _stop.Token).ConfigureAwait(false))); private async Task ObserveAsync(Task operation) { @@ -2418,7 +2418,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers else _sourcePublisher.TryPublish(ticket, item.Snapshot); } } - }); + }, _invoker, _driverInstanceId); started = true; var installed = await operation.Completion.WaitAsync(cts.Token); if (installed.Handle is null || installed.DesiredRevision != fence.Revision || diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsParserTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsParserTests.cs index 89a5a4d47..a77f6684d 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsParserTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsParserTests.cs @@ -371,6 +371,18 @@ public sealed class DriverResilienceOptionsParserTests diag.ShouldContain("Initialize never retries"); } + /// #1047: an AcquisitionSubscribe retryCount override is forced to 0 with a diagnostic. + [Fact] + public void AcquisitionSubscribeRetryOverride_IsForcedToZero_WithDiagnostic() + { + var options = DriverResilienceOptionsParser.ParseOrDefaults( + DriverTier.A, "{\"capabilityPolicies\":{\"AcquisitionSubscribe\":{\"retryCount\":3}}}", out var diag); + + options.Resolve(DriverCapability.AcquisitionSubscribe).RetryCount.ShouldBe(0); + diag.ShouldNotBeNull(); + diag.ShouldContain("AcquisitionSubscribe never retries"); + } + /// A Read (idempotent) retryCount override is still honored — the invariant is write-shaped only. [Fact] public void ReadRetryOverride_StillHonored() diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsTests.cs index 94403874b..67660902b 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResilienceOptionsTests.cs @@ -93,6 +93,22 @@ public sealed class DriverResilienceOptionsTests defaults[DriverCapability.Initialize].RetryCount.ShouldBe(0); } + /// + /// #1047: acknowledged acquisition never retries (a retry would orphan a handle the runtime's pending acquisition + /// owns) and its timeout outlasts the runtime's 10 s acquisition timeout, which stays the effective bound. + /// + /// The driver tier to test. + [Theory] + [InlineData(DriverTier.A)] + [InlineData(DriverTier.B)] + [InlineData(DriverTier.C)] + public void AcquisitionSubscribe_NeverRetries_AndOutlastsTheRuntimeTimeout(DriverTier tier) + { + var policy = DriverResilienceOptions.GetTierDefaults(tier)[DriverCapability.AcquisitionSubscribe]; + policy.RetryCount.ShouldBe(0); + policy.TimeoutSeconds.ShouldBeGreaterThan(10); + } + /// /// The Initialize breaker threshold must be reachable at the reconnect cadence (R2-10 T10): /// the breaker samples over 30 s and the reconnect timer fires every 10 s, so at most THREE diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionResilienceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionResilienceTests.cs new file mode 100644 index 000000000..be75bcfe6 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataAcquisitionResilienceTests.cs @@ -0,0 +1,146 @@ +using System.Collections.Concurrent; +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// lmxopcua#1047 (#1001 follow-up): acknowledged acquisition () runs through +/// the capability invoker on its own NON-retrying capability, , so +/// the breaker and the /hosts telemetry cover it. It used to call the source directly (OTOPCUA0001 suppressed): the +/// stock Subscribe pipeline retries, and a retry would orphan a physical handle the pending acquisition owns. +/// +[Trait("Feature", "GrpcData"), Trait("Category", "Unit")] +public sealed class GrpcDataAcquisitionResilienceTests : RuntimeActorTestBase +{ + [Fact] + public async Task Acquisition_routes_through_the_invoker_on_the_acquisition_capability() + { + var (hub, publisher, incarnation) = Setup(); + using (hub) + { + var invoker = new GateInvoker(failAcquisitions: 0); + var driver = new AcquisitionDriver(); + var actor = await SpawnConnectedAsync(driver, invoker, publisher, incarnation, capacity: 4); + + var ack = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken); + + ack.Succeeded.ShouldBeTrue(); + driver.Calls.ShouldBe(1, "the source ran from inside the invoker's call site"); + invoker.Calls.ShouldContain(c => c.Capability == DriverCapability.AcquisitionSubscribe && c.Host == driver.DriverInstanceId); + } + } + + /// + /// An OPEN breaker fails the acquisition fast without calling the source, and the capacity reservation is released + /// (capacity 1: the next demand, once the breaker lets it through, still gets the slot). + /// + [Fact] + public async Task A_fast_failed_acquisition_releases_its_capacity() + { + var (hub, publisher, incarnation) = Setup(); + using (hub) + { + var invoker = new GateInvoker(failAcquisitions: 1); + var driver = new AcquisitionDriver(); + var actor = await SpawnConnectedAsync(driver, invoker, publisher, incarnation, capacity: 1); + + var first = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken); + first.Succeeded.ShouldBeFalse(); + driver.Calls.ShouldBe(0, "a fast-failed call never reaches the source"); + + DriverInstanceActor.AcquisitionDemandApplied? second = null; + for (var i = 0; i < 40 && second is not { Succeeded: true }; i++) + { + second = await actor.Ask( + new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 2 + i, incarnation, true), + PresenceBudget, TestContext.Current.CancellationToken); + if (second is not { Succeeded: true }) await Task.Delay(25, TestContext.Current.CancellationToken); + } + second.ShouldNotBeNull().Succeeded.ShouldBeTrue("the failed attempt released the only capacity slot"); + driver.Calls.ShouldBe(1); + } + } + + private async Task SpawnConnectedAsync(AcquisitionDriver driver, IDriverCapabilityInvoker invoker, + SourceSamplePublisher publisher, long incarnation, int capacity) + { + var parent = CreateTestProbe(); + var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, invoker: invoker, clusterId: "cluster", + commsLossTimeout: TimeSpan.Zero, sourcePublisher: publisher, sourceIncarnation: incarnation, + acquisitionCapacity: new SubscriptionAcquisitionCapacity(capacity)), + TestContext.Current.CancellationToken); + actor.Tell(new DriverInstanceActor.InitializeRequested("{}")); + parent.ExpectMsg(m => m.Connected, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken); + await Task.CompletedTask; + return actor; + } + + private static (PartitionedSampleHub Hub, SourceSamplePublisher Publisher, long Incarnation) Setup() + { + var hub = HubTest.Create(clock: new ManualTimeProvider()); + var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1)); + var incarnation = publisher.RegisterDriverIncarnation("stub-driver-1"); + publisher.RegisterDriverShape("stub-driver-1", "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster", "stub-driver-1", "tag", incarnation).ShouldBeTrue(); + return (hub, publisher, incarnation); + } + + /// Records every routed call; the first failAcquisitions acquisition calls throw without invoking the call + /// site (an open breaker's BrokenCircuitException shape). + private sealed class GateInvoker(int failAcquisitions) : IDriverCapabilityInvoker + { + private int _acquisitionAttempts; + public ConcurrentQueue<(DriverCapability Capability, string Host)> Calls { get; } = new(); + + public ValueTask ExecuteAsync(DriverCapability capability, string hostName, + Func> callSite, CancellationToken cancellationToken) + { + Calls.Enqueue((capability, hostName)); + if (capability == DriverCapability.AcquisitionSubscribe && Interlocked.Increment(ref _acquisitionAttempts) <= failAcquisitions) + throw new InvalidOperationException("circuit open (simulated fast-fail)"); + return callSite(cancellationToken); + } + + public ValueTask ExecuteAsync(DriverCapability capability, string hostName, + Func callSite, CancellationToken cancellationToken) + { + Calls.Enqueue((capability, hostName)); + return callSite(cancellationToken); + } + + public ValueTask ExecuteWriteAsync(string hostName, bool isIdempotent, + Func> callSite, CancellationToken cancellationToken) + => callSite(cancellationToken); + } + + private sealed class AcquisitionDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource + { + private int _calls; + public int Calls => Volatile.Read(ref _calls); + public event EventHandler? OnDataChange { add { } remove { } } + public Task SubscribeAsync(IReadOnlyList refs, TimeSpan interval, CancellationToken ct) => + Task.FromResult(new Handle()); + public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask; + public Task SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request, + Action callback, CancellationToken ct) + { + Interlocked.Increment(ref _calls); + return Task.FromResult(new AcquisitionSubscriptionResult(new Handle(), request.RequestedSamplingInterval, + request.DesiredRevision, request.ProducerIncarnation)); + } + private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "acq"; } + } +}