diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md
index 6064f68da..c0538c9a8 100644
--- a/docs/DriverLifecycle.md
+++ b/docs/DriverLifecycle.md
@@ -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
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs
index fd750c1c0..4b95ed985 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/CapabilityInvoker.cs
@@ -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);
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 d697a4430..d853155ab 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs
@@ -23,6 +23,11 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Resilience;
/// 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.
///
+/// Every failed ATTEMPT is a tracker failure (#1052). An innermost recorder counts each attempt that ends in
+/// a handled failure (not a caller cancellation, not a , not the pipeline
+/// timeout — OnTimeout counts that one). It replaced the count in OnRetry, which a no-retry capability
+/// (Write, AlarmAcknowledge, Initialize) never reaches and which skipped every retried call's last attempt.
+///
/// 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).
@@ -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.
///
+ ///
+ /// The host the pipeline's tracker telemetry is recorded under, when it differs from the cache key's
+ /// — the non-idempotent write pipeline is cached under host::non-idempotent
+ /// but its failures and breaker belong to host (#1052). Must be a function of :
+ /// it is not part of the cache key. Null = .
+ ///
/// The cached or newly built resilience pipeline for the key.
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));
}
///
@@ -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(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();
}
+ ///
+ /// 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
+ /// OnTimeout. A refusal is not a failure of the target.
+ ///
+ private sealed class AttemptFailureRecorder(
+ DriverResilienceStatusTracker tracker, string driverInstanceId, string hostName, TimeProvider timeProvider) : ResilienceStrategy
+ {
+ protected override async ValueTask> ExecuteCore(
+ Func>> 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" };
+ }
+
/// The caller's token, recorded by before the timeout links its own.
private static readonly ResiliencePropertyKey CallerTokenKey = new("otopcua.caller-token");
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 e5863b23f..d811d7b01 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
@@ -265,7 +265,7 @@ public sealed class DriverResiliencePipelineBuilderTests
attempts.ShouldBeLessThanOrEqualTo(1);
}
- /// Verifies that the tracker records failure on every retry.
+ /// Verifies that the tracker records a failure for every failed attempt.
[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);
}
/// Verifies that the tracker stamps the breaker open when it trips.
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/TerminalFailureTrackingTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/TerminalFailureTrackingTests.cs
new file mode 100644
index 000000000..104cd26ff
--- /dev/null
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/TerminalFailureTrackingTests.cs
@@ -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;
+
+///
+/// lmxopcua#1052 (#999 follow-up, decided): ConsecutiveFailures counts FAILED ATTEMPTS, every one. It used to be
+/// fed only by the retry strategy's OnRetry, 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 host::non-idempotent row.
+///
+[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(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(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(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(async () =>
+ await pipeline.ExecuteAsync(_ => throw new InvalidOperationException("down"), TestContext.Current.CancellationToken));
+ tracker.TryGet("drv", "host-1")!.ConsecutiveFailures.ShouldBe(1);
+ }
+
+ ///
+ /// A non-idempotent write runs on a pipeline cached under host::non-idempotent; its failures and its breaker
+ /// belong to the CALLER's host, where its success already resets the counter.
+ ///
+ [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(async () =>
+ await invoker.ExecuteWriteAsync("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");
+ }
+}