fix(resilience): #999 K-6 a pipeline timeout counts toward the circuit breaker and the status tracker

This commit is contained in:
Joseph Doherty
2026-12-03 10:43:35 -05:00
parent ef782c29ae
commit 3795cd5f21
3 changed files with 151 additions and 4 deletions
+9 -1
View File
@@ -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`.
---
@@ -17,6 +17,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Resilience;
/// Per-device isolation. Composition from outside-in:
/// <b>Timeout → Retry (when capability permits) → Circuit Breaker (when tier permits)</b>.
///
/// <para><b>The pipeline's own timeout is a failure (#999 / review K-6).</b> 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 <c>OnTimeout</c> records a
/// tracker failure. Before, both predicates excluded every <see cref="OperationCanceledException"/>: a hung
/// device burned the full timeout on every call forever with the breaker closed and no failure on <c>/hosts</c>.</para>
///
/// <para>Pipeline resolution is lock-free on the hot path: the inner
/// <see cref="ConcurrentDictionary{TKey,TValue}"/> caches a <see cref="ResiliencePipeline"/> per key;
/// first-call cost is one <see cref="ResiliencePipelineBuilder"/>.Build. Thereafter reads are O(1).</para>
@@ -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<Exception>(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<Exception>(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<bool>(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();
}
/// <summary>The caller's token, recorded by <see cref="CallerTokenStrategy"/> before the timeout links its own.</summary>
private static readonly ResiliencePropertyKey<CancellationToken> CallerTokenKey = new("otopcua.caller-token");
/// <summary>
/// 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.
/// </summary>
private static bool IsPipelineTimeout(ResilienceContext context)
=> context.CancellationToken.IsCancellationRequested
&& context.Properties.TryGetValue(CallerTokenKey, out var caller)
&& !caller.IsCancellationRequested;
/// <summary>Outermost pass-through that records the caller's cancellation token on the context (#999 / K-6).</summary>
private sealed class CallerTokenStrategy : ResilienceStrategy
{
public static readonly CallerTokenStrategy Instance = new();
protected override ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>(
Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> 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);
}
@@ -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");
}
/// <summary>
/// #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 <see cref="OperationCanceledException"/>, which
/// both predicates excluded: every call burned the full timeout forever, the breaker never opened and
/// <c>/hosts</c> showed <c>ConsecutiveFailures = 0</c> for a dead device.
/// </summary>
[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, CapabilityPolicy>
{
[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<TimeoutRejectedException>(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<BrokenCircuitException>(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();
}
/// <summary>
/// #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.
/// </summary>
[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, CapabilityPolicy>
{
[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<OperationCanceledException>(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);
}
/// <summary>
/// A controllable <see cref="TimeProvider"/> whose clock advances only on <see cref="Advance"/>.
/// Drives both wall-clock (<see cref="GetUtcNow"/>) and monotonic (<see cref="GetTimestamp"/>)