From 3795cd5f216024ff5706906653a9da513345c75c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:43:35 -0500 Subject: [PATCH] fix(resilience): #999 K-6 a pipeline timeout counts toward the circuit breaker and the status tracker --- docs/DriverLifecycle.md | 10 ++- .../DriverResiliencePipelineBuilder.cs | 72 +++++++++++++++++- .../DriverResiliencePipelineBuilderTests.cs | 73 +++++++++++++++++++ 3 files changed, 151 insertions(+), 4 deletions(-) diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 4504e752a..b6e6cc3a8 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -591,8 +591,16 @@ before touching it: snapshot could never self-correct — only the discarded pipeline's `OnClosed` stamps the close — so a deploy during an outage would otherwise strand a false OPEN chip forever. This was unreachable while breakers never opened; the Initialize wrap made it reachable. -- `ConsecutiveFailures` stays 0 during a connect outage **by design** — the tracker counts retry +- `ConsecutiveFailures` stays 0 during a connect outage that FAILS fast — the tracker counts retry attempts, and Initialize has none. The breaker-OPEN chip is the operator signal. +- **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 + forever, the breaker never opened and `/hosts` read `ConsecutiveFailures = 0`. Now the breaker counts + the timed-out attempt (a cancellation the CALLER asked for still does not count — an outermost + pass-through records the caller's token so the two are told apart) and `OnTimeout` records one tracker + failure. The timeout is the call's total budget, so it is still not retried. Pinned by + `Pipeline_timeouts_open_the_breaker_and_reach_the_tracker` + `Caller_cancellation_is_not_a_failure`. --- diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs index 60b863655..d697a4430 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs @@ -17,6 +17,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Resilience; /// Per-device isolation. Composition from outside-in: /// Timeout → Retry (when capability permits) → Circuit Breaker (when tier permits). /// +/// The pipeline's own timeout is a failure (#999 / review K-6). The timeout is the call's TOTAL +/// budget, so it is not retried, but the breaker counts the cancelled attempt as a failure (unless the caller +/// cancelled — told apart by the caller token an outermost pass-through records) and OnTimeout records a +/// tracker failure. Before, both predicates excluded every : a hung +/// device burned the full timeout on every call forever with the breaker closed and no failure on /hosts. +/// /// Pipeline resolution is lock-free on the hot path: the inner /// caches a per key; /// first-call cost is one .Build. Thereafter reads are O(1). @@ -135,10 +141,29 @@ public sealed class DriverResiliencePipelineBuilder // builder invariant. Three integer ops once per pipeline build (not per call). var timeoutSeconds = Math.Clamp( policy.TimeoutSeconds, ResiliencePolicyRanges.MinTimeoutSeconds, ResiliencePolicyRanges.MaxTimeoutSeconds); - builder.AddTimeout(new TimeoutStrategyOptions + + // #999 / review K-6: outermost, BEFORE the timeout links its own token in — record the caller's token so the + // inner predicates can tell the pipeline's own timeout (a failure) from a cancellation the caller asked for. + builder.AddStrategy(static _ => CallerTokenStrategy.Instance, CallerTokenStrategyOptions.Instance); + + var timeoutOptions = new TimeoutStrategyOptions { Timeout = TimeSpan.FromSeconds(timeoutSeconds), - }); + }; + if (tracker is not null || logger is not null) + { + // The total budget ran out: a failure of the target, like a retried exception (K-6). Without this a + // hung device read ConsecutiveFailures = 0 on /hosts forever. + timeoutOptions.OnTimeout = args => + { + tracker?.RecordFailure(driverInstanceId, hostName, timeProvider.GetUtcNow().UtcDateTime); + logger?.LogWarning( + "Driver resilience timeout: instance={DriverInstanceId} host={HostName} capability={Capability} timeout={Timeout}", + driverInstanceId, hostName, capability, args.Timeout); + return default; + }; + } + builder.AddTimeout(timeoutOptions); if (policy.RetryCount > 0) { @@ -149,6 +174,8 @@ public sealed class DriverResiliencePipelineBuilder UseJitter = true, Delay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromSeconds(5), + // A pipeline timeout is NOT retried: it is the TOTAL budget (the timeout is outermost), so nothing is + // left to retry with. It is still a breaker failure (below) and a tracker failure (OnTimeout). ShouldHandle = new PredicateBuilder().Handle(ex => ex is not OperationCanceledException and not DriverOperationRefusedException), }; if (tracker is not null || logger is not null) @@ -173,7 +200,16 @@ public sealed class DriverResiliencePipelineBuilder MinimumThroughput = Math.Max(ResiliencePolicyRanges.MinEnabledBreakerFailureThreshold, policy.BreakerFailureThreshold), SamplingDuration = TimeSpan.FromSeconds(30), BreakDuration = TimeSpan.FromSeconds(15), - ShouldHandle = new PredicateBuilder().Handle(ex => ex is not OperationCanceledException and not DriverOperationRefusedException), + // #999 / review K-6: the pipeline's own timeout cancels the attempt, so the breaker sees an + // OperationCanceledException — a failure of the target unless the CALLER cancelled. Excluding every + // OCE meant a hung device never opened the breaker. A refusal stays a non-failure. + ShouldHandle = args => new ValueTask(args.Outcome.Exception switch + { + null => false, + DriverOperationRefusedException => false, + OperationCanceledException => IsPipelineTimeout(args.Context), + _ => true, + }), }; if (tracker is not null || logger is not null) { @@ -205,5 +241,35 @@ public sealed class DriverResiliencePipelineBuilder return builder.Build(); } + /// The caller's token, recorded by before the timeout links its own. + private static readonly ResiliencePropertyKey CallerTokenKey = new("otopcua.caller-token"); + + /// + /// True when an attempt's cancellation came from the pipeline's own timeout (the attempt token is cancelled but + /// the caller's is not). Unknown caller token ⇒ false, the pre-#999 behaviour. + /// + private static bool IsPipelineTimeout(ResilienceContext context) + => context.CancellationToken.IsCancellationRequested + && context.Properties.TryGetValue(CallerTokenKey, out var caller) + && !caller.IsCancellationRequested; + + /// Outermost pass-through that records the caller's cancellation token on the context (#999 / K-6). + private sealed class CallerTokenStrategy : ResilienceStrategy + { + public static readonly CallerTokenStrategy Instance = new(); + + protected override ValueTask> ExecuteCore( + Func>> callback, ResilienceContext context, TState state) + { + context.Properties.Set(CallerTokenKey, context.CancellationToken); + return callback(context, state); + } + } + + private sealed class CallerTokenStrategyOptions : ResilienceStrategyOptions + { + public static readonly CallerTokenStrategyOptions Instance = new() { Name = "CallerToken" }; + } + private readonly record struct PipelineKey(string DriverInstanceId, string HostName, DriverCapability Capability, long Generation); } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs index 246d33460..e5863b23f 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs @@ -516,6 +516,79 @@ public sealed class DriverResiliencePipelineBuilderTests attempts.ShouldBe(1, "the new generation must honor optsB (retryCount 0), not the stale optsA re-cache"); } + /// + /// #999 / review K-6: the pipeline's OWN timeout is a failure the breaker and the status tracker see. Before + /// the fix the hung attempt surfaced inside the pipeline as an , which + /// both predicates excluded: every call burned the full timeout forever, the breaker never opened and + /// /hosts showed ConsecutiveFailures = 0 for a dead device. + /// + [Fact] + public async Task Pipeline_timeouts_open_the_breaker_and_reach_the_tracker() + { + var tracker = new DriverResilienceStatusTracker(); + var builder = new DriverResiliencePipelineBuilder(statusTracker: tracker); + var options = new DriverResilienceOptions + { + Tier = DriverTier.A, + CapabilityPolicies = new Dictionary + { + [DriverCapability.Read] = new(TimeoutSeconds: 1, RetryCount: 3, BreakerFailureThreshold: 2), + }, + }; + var pipeline = builder.GetOrCreate("drv-hang", "host-h", DriverCapability.Read, options); + var attempts = 0; + async ValueTask Hang(CancellationToken t) + { + Interlocked.Increment(ref attempts); + await Task.Delay(Timeout.Infinite, t); // honours the token, like a blackholed socket read + } + + for (var i = 0; i < 2; i++) + { + await Should.ThrowAsync(async () => + await pipeline.ExecuteAsync(Hang, TestContext.Current.CancellationToken)); + tracker.TryGet("drv-hang", "host-h")!.ConsecutiveFailures.ShouldBe(i + 1, "each timeout is a failure"); + } + + await Should.ThrowAsync(async () => + await pipeline.ExecuteAsync(Hang, TestContext.Current.CancellationToken)); + attempts.ShouldBe(2, "the open breaker short-circuits the third call"); + tracker.TryGet("drv-hang", "host-h")!.IsBreakerOpen.ShouldBeTrue(); + } + + /// + /// #999 / K-6 control: a cancellation the CALLER asked for is still not a failure — it neither counts toward the + /// breaker nor reaches the tracker. Positive control: after more caller cancels than the threshold, the next call + /// still reaches the call site. + /// + [Fact] + public async Task Caller_cancellation_is_not_a_failure() + { + var tracker = new DriverResilienceStatusTracker(); + var builder = new DriverResiliencePipelineBuilder(statusTracker: tracker); + var options = new DriverResilienceOptions + { + Tier = DriverTier.A, + CapabilityPolicies = new Dictionary + { + [DriverCapability.Read] = new(TimeoutSeconds: 30, RetryCount: 3, BreakerFailureThreshold: 2), + }, + }; + var pipeline = builder.GetOrCreate("drv-cxl", "host-c", DriverCapability.Read, options); + + for (var i = 0; i < 4; i++) + { + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(20)); + await Should.ThrowAsync(async () => + await pipeline.ExecuteAsync(async t => await Task.Delay(Timeout.Infinite, t), cts.Token)); + } + + var reached = false; + await pipeline.ExecuteAsync(_ => { reached = true; return ValueTask.CompletedTask; }, TestContext.Current.CancellationToken); + reached.ShouldBeTrue("the breaker stayed closed"); + (tracker.TryGet("drv-cxl", "host-c")?.ConsecutiveFailures ?? 0).ShouldBe(0); + } + /// /// A controllable whose clock advances only on . /// Drives both wall-clock () and monotonic ()