fix(resilience): #1052 every failed attempt counts toward ConsecutiveFailures, no-retry capabilities included; non-idempotent write telemetry on the caller's host
Decided: an innermost recorder counts each attempt ending in a handled failure (not caller cancellation, not a refusal; the pipeline timeout stays counted once by OnTimeout). OnRetry only logs now. Write/AlarmAcknowledge/ Initialize failures used to never raise the /hosts count, and a retried call's last attempt was never counted. The ::non-idempotent write pipeline records failures + breaker under the caller's host (trackerHostName). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -627,8 +627,13 @@ 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 that FAILS fast — the tracker counts retry
|
||||
attempts, and Initialize has none. The breaker-OPEN chip is the operator signal.
|
||||
- **`ConsecutiveFailures` counts every failed attempt (#1052, decided).** It used to be fed only by the retry
|
||||
strategy's `OnRetry`, so a no-retry capability (Write, AlarmAcknowledge, Initialize) never raised it — a connect outage
|
||||
that failed fast read 0 on `/hosts` — and a retried call's LAST attempt was never counted. An innermost recorder now
|
||||
counts each attempt that ends in a handled failure (never a caller cancellation or a `DriverOperationRefusedException`;
|
||||
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.
|
||||
- **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
|
||||
|
||||
@@ -136,7 +136,9 @@ public sealed class CapabilityInvoker : IDriverCapabilityInvoker
|
||||
// safe and removes the per-write allocation the previous once-per-call snapshot incurred. The
|
||||
// null-check-assign tolerates a benign first-call race (both threads build an equivalent record).
|
||||
var noRetryOptions = _noRetryWriteOptions ??= BuildNoRetryWriteOptions();
|
||||
var pipeline = _builder.GetOrCreate(_driverInstanceId, $"{hostName}::non-idempotent", DriverCapability.Write, noRetryOptions, _optionsGeneration);
|
||||
// The pipeline is cached under "::non-idempotent", but its failures and breaker are the caller host's (#1052).
|
||||
var pipeline = _builder.GetOrCreate(_driverInstanceId, $"{hostName}::non-idempotent", DriverCapability.Write, noRetryOptions,
|
||||
_optionsGeneration, trackerHostName: hostName);
|
||||
// Record in-flight accounting on the CALLER's host (the "::non-idempotent" suffix is a
|
||||
// pipeline-cache key, not an operator-facing host) so Admin /hosts sees write depth too.
|
||||
_statusTracker?.RecordCallStart(_driverInstanceId, hostName);
|
||||
|
||||
@@ -23,6 +23,11 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Resilience;
|
||||
/// 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><b>Every failed ATTEMPT is a tracker failure (#1052).</b> An innermost recorder counts each attempt that ends in
|
||||
/// a handled failure (not a caller cancellation, not a <see cref="DriverOperationRefusedException"/>, not the pipeline
|
||||
/// timeout — <c>OnTimeout</c> counts that one). It replaced the count in <c>OnRetry</c>, which a no-retry capability
|
||||
/// (Write, AlarmAcknowledge, Initialize) never reaches and which skipped every retried call's last attempt.</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>
|
||||
@@ -83,21 +88,28 @@ public sealed class DriverResiliencePipelineBuilder
|
||||
/// its OWN (old) generation — a key the new invoker's generation never reads. Defaults to 0 so
|
||||
/// every existing caller/test compiles unchanged.
|
||||
/// </param>
|
||||
/// <param name="trackerHostName">
|
||||
/// The host the pipeline's tracker telemetry is recorded under, when it differs from the cache key's
|
||||
/// <paramref name="hostName"/> — the non-idempotent write pipeline is cached under <c>host::non-idempotent</c>
|
||||
/// but its failures and breaker belong to <c>host</c> (#1052). Must be a function of <paramref name="hostName"/>:
|
||||
/// it is not part of the cache key. Null = <paramref name="hostName"/>.
|
||||
/// </param>
|
||||
/// <returns>The cached or newly built resilience pipeline for the key.</returns>
|
||||
public ResiliencePipeline GetOrCreate(
|
||||
string driverInstanceId,
|
||||
string hostName,
|
||||
DriverCapability capability,
|
||||
DriverResilienceOptions options,
|
||||
long optionsGeneration = 0)
|
||||
long optionsGeneration = 0,
|
||||
string? trackerHostName = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(hostName);
|
||||
|
||||
var key = new PipelineKey(driverInstanceId, hostName, capability, optionsGeneration);
|
||||
return _pipelines.GetOrAdd(key, static (k, state) => Build(
|
||||
k.DriverInstanceId, k.HostName, state.capability, state.options, state.timeProvider, state.tracker, state.logger),
|
||||
(capability, options, timeProvider: _timeProvider, tracker: _statusTracker, logger: _logger));
|
||||
k.DriverInstanceId, state.trackerHost ?? k.HostName, state.capability, state.options, state.timeProvider, state.tracker, state.logger),
|
||||
(capability, options, timeProvider: _timeProvider, tracker: _statusTracker, logger: _logger, trackerHost: trackerHostName));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -178,12 +190,12 @@ public sealed class DriverResiliencePipelineBuilder
|
||||
// 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)
|
||||
if (logger is not null)
|
||||
{
|
||||
// The failed attempt itself is counted by the innermost AttemptFailureRecorder (#1052), not here.
|
||||
retryOptions.OnRetry = args =>
|
||||
{
|
||||
tracker?.RecordFailure(driverInstanceId, hostName, timeProvider.GetUtcNow().UtcDateTime);
|
||||
logger?.LogWarning(
|
||||
logger.LogWarning(
|
||||
"Driver resilience retry: instance={DriverInstanceId} host={HostName} capability={Capability} attempt={Attempt}: {Reason}",
|
||||
driverInstanceId, hostName, capability, args.AttemptNumber, args.Outcome.Exception?.Message ?? "unknown");
|
||||
return default;
|
||||
@@ -238,9 +250,40 @@ public sealed class DriverResiliencePipelineBuilder
|
||||
builder.AddCircuitBreaker(breakerOptions);
|
||||
}
|
||||
|
||||
// #1052: innermost, so it sees every attempt — the retried ones, the last one, and the only one of a no-retry
|
||||
// capability. ConsecutiveFailures is "failed attempts since the last success".
|
||||
if (tracker is not null)
|
||||
{
|
||||
var recorder = new AttemptFailureRecorder(tracker, driverInstanceId, hostName, timeProvider);
|
||||
builder.AddStrategy(_ => recorder, AttemptFailureRecorderOptions.Instance);
|
||||
}
|
||||
|
||||
return builder.Build();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Innermost pass-through that records a tracker failure for each attempt ending in a handled failure (#1052). A
|
||||
/// cancellation is never counted here: the caller's is not a failure, and the pipeline's own timeout is counted by
|
||||
/// <c>OnTimeout</c>. A refusal is not a failure of the target.
|
||||
/// </summary>
|
||||
private sealed class AttemptFailureRecorder(
|
||||
DriverResilienceStatusTracker tracker, string driverInstanceId, string hostName, TimeProvider timeProvider) : ResilienceStrategy
|
||||
{
|
||||
protected override async ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>(
|
||||
Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback, ResilienceContext context, TState state)
|
||||
{
|
||||
var outcome = await callback(context, state).ConfigureAwait(context.ContinueOnCapturedContext);
|
||||
if (outcome.Exception is not null and not OperationCanceledException and not DriverOperationRefusedException)
|
||||
tracker.RecordFailure(driverInstanceId, hostName, timeProvider.GetUtcNow().UtcDateTime);
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class AttemptFailureRecorderOptions : ResilienceStrategyOptions
|
||||
{
|
||||
public static readonly AttemptFailureRecorderOptions Instance = new() { Name = "AttemptFailureRecorder" };
|
||||
}
|
||||
|
||||
/// <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");
|
||||
|
||||
|
||||
+3
-2
@@ -265,7 +265,7 @@ public sealed class DriverResiliencePipelineBuilderTests
|
||||
attempts.ShouldBeLessThanOrEqualTo(1);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the tracker records failure on every retry.</summary>
|
||||
/// <summary>Verifies that the tracker records a failure for every failed attempt.</summary>
|
||||
[Fact]
|
||||
public async Task Tracker_RecordsFailure_OnEveryRetry()
|
||||
{
|
||||
@@ -283,7 +283,8 @@ public sealed class DriverResiliencePipelineBuilderTests
|
||||
var snap = tracker.TryGet("drv-trk", "host-x");
|
||||
snap.ShouldNotBeNull();
|
||||
var retryCount = TierAOptions.Resolve(DriverCapability.Read).RetryCount;
|
||||
snap!.ConsecutiveFailures.ShouldBe(retryCount);
|
||||
// #1052: every failed ATTEMPT counts, the final (un-retried) one included.
|
||||
snap!.ConsecutiveFailures.ShouldBe(retryCount + 1);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the tracker stamps the breaker open when it trips.</summary>
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Resilience;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Tests.Resilience;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1052 (#999 follow-up, decided): <c>ConsecutiveFailures</c> counts FAILED ATTEMPTS, every one. It used to be
|
||||
/// fed only by the retry strategy's <c>OnRetry</c>, so a capability with no retry (Write, AlarmAcknowledge, Initialize)
|
||||
/// never raised the /hosts failure count however often it failed, and a retried call's last attempt was never counted
|
||||
/// either. And a non-idempotent write's pipeline telemetry landed on a phantom <c>host::non-idempotent</c> row.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class TerminalFailureTrackingTests
|
||||
{
|
||||
private static readonly DriverResilienceOptions TierA = new() { Tier = DriverTier.A };
|
||||
|
||||
[Theory]
|
||||
[InlineData(DriverCapability.Write)]
|
||||
[InlineData(DriverCapability.AlarmAcknowledge)]
|
||||
[InlineData(DriverCapability.Initialize)]
|
||||
public async Task A_no_retry_capability_failure_is_counted(DriverCapability capability)
|
||||
{
|
||||
var tracker = new DriverResilienceStatusTracker();
|
||||
var pipeline = new DriverResiliencePipelineBuilder(statusTracker: tracker).GetOrCreate("drv", "host-1", capability, TierA);
|
||||
|
||||
for (var i = 1; i <= 2; i++)
|
||||
{
|
||||
await Should.ThrowAsync<InvalidOperationException>(async () =>
|
||||
await pipeline.ExecuteAsync(_ => throw new InvalidOperationException("device refused the socket"),
|
||||
TestContext.Current.CancellationToken));
|
||||
tracker.TryGet("drv", "host-1")!.ConsecutiveFailures.ShouldBe(i, $"failure {i} of a {capability} with no retry");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Every_failed_attempt_of_a_retried_call_is_counted_including_the_last()
|
||||
{
|
||||
var tracker = new DriverResilienceStatusTracker();
|
||||
var pipeline = new DriverResiliencePipelineBuilder(statusTracker: tracker).GetOrCreate("drv", "host-1", DriverCapability.Read, TierA);
|
||||
var attempts = 0;
|
||||
|
||||
await Should.ThrowAsync<InvalidOperationException>(async () =>
|
||||
await pipeline.ExecuteAsync(_ => { attempts++; throw new InvalidOperationException("down"); },
|
||||
TestContext.Current.CancellationToken));
|
||||
|
||||
attempts.ShouldBe(TierA.Resolve(DriverCapability.Read).RetryCount + 1);
|
||||
tracker.TryGet("drv", "host-1")!.ConsecutiveFailures.ShouldBe(attempts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_refusal_is_not_a_failure()
|
||||
{
|
||||
var tracker = new DriverResilienceStatusTracker();
|
||||
var pipeline = new DriverResiliencePipelineBuilder(statusTracker: tracker).GetOrCreate("drv", "host-1", DriverCapability.Write, TierA);
|
||||
|
||||
await Should.ThrowAsync<DriverOperationRefusedException>(async () =>
|
||||
await pipeline.ExecuteAsync(_ => throw new DriverOperationRefusedException("not writable"),
|
||||
TestContext.Current.CancellationToken));
|
||||
(tracker.TryGet("drv", "host-1")?.ConsecutiveFailures ?? 0).ShouldBe(0);
|
||||
|
||||
// Positive control: a genuine failure on the same pipeline IS counted.
|
||||
await Should.ThrowAsync<InvalidOperationException>(async () =>
|
||||
await pipeline.ExecuteAsync(_ => throw new InvalidOperationException("down"), TestContext.Current.CancellationToken));
|
||||
tracker.TryGet("drv", "host-1")!.ConsecutiveFailures.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A non-idempotent write runs on a pipeline cached under <c>host::non-idempotent</c>; its failures and its breaker
|
||||
/// belong to the CALLER's host, where its success already resets the counter.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Non_idempotent_write_failures_land_on_the_callers_host()
|
||||
{
|
||||
var tracker = new DriverResilienceStatusTracker();
|
||||
var invoker = new CapabilityInvoker(new DriverResiliencePipelineBuilder(statusTracker: tracker), "drv", () => TierA,
|
||||
statusTracker: tracker);
|
||||
var threshold = TierA.Resolve(DriverCapability.Write).BreakerFailureThreshold;
|
||||
|
||||
for (var i = 0; i < threshold; i++)
|
||||
await Should.ThrowAsync<InvalidOperationException>(async () =>
|
||||
await invoker.ExecuteWriteAsync<int>("host-1", isIdempotent: false,
|
||||
_ => throw new InvalidOperationException("down"), TestContext.Current.CancellationToken));
|
||||
|
||||
var snap = tracker.TryGet("drv", "host-1")!;
|
||||
snap.ConsecutiveFailures.ShouldBe(threshold);
|
||||
snap.IsBreakerOpen.ShouldBeTrue("the write breaker opened, and it is this host's breaker");
|
||||
tracker.TryGet("drv", "host-1::non-idempotent").ShouldBeNull("no phantom host row");
|
||||
|
||||
await invoker.ExecuteWriteAsync("host-1", isIdempotent: true, _ => ValueTask.FromResult(0), TestContext.Current.CancellationToken);
|
||||
tracker.TryGet("drv", "host-1")!.ConsecutiveFailures.ShouldBe(0, "a success on the same host resets it");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user