fix(runtime): arm the apply-wedge watchdog after the Applying-row write; capture telemetry counter before MeterListener (Runtime.Tests master failures)

ACompletedApply_NeverReportsAWedge failed whenever it ran first in its process: the
wedge timer was armed BEFORE the synchronous UpsertNodeDeploymentState(Applying), and
the cold EF Core model build on that first write (~350 ms) outlasted the 200 ms delay,
so the tick was enqueued ahead of the fetch's pipe-back and reported an immediately
answered fetch as WEDGED. The watchdog now arms immediately before the read/fetch starts
on both begin-paths, so it times what its Warning claims. New deterministic red/green
test ASlowApplyingRowWrite_IsNotReportedAsAWedgedFetch (row writes slowed to 4x delay).

OpcUaPublishActorWarmTests cluster-mode-mismatch test compared against
OtOpcUaTelemetry.RedundancyModeMismatch inside InstrumentPublished; when the static
initializer ran under the live listener the field still read null, so the counter was
never enabled. Capture the counter into a local before creating the listener.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-28 10:37:25 -05:00
parent c8b68940a8
commit f83cb24ed0
3 changed files with 83 additions and 4 deletions
@@ -3095,7 +3095,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// <see cref="HandleArtifactForApply"/>, the continuation both modes share.
/// </summary>
/// <remarks>
/// Both begin-paths arm the <see cref="ApplyWedgeTimerKey"/> watchdog, because both leave the
/// Both begin-paths arm the <see cref="ApplyWedgeTimerKey"/> watchdog — after the synchronous
/// Applying-row write, immediately before the read/fetch starts — because both leave the
/// host alive and dequeuing while it waits for bytes it does not have yet — which is exactly
/// what makes a silent wedge possible. (Before the Direct read moved off the mailbox this was
/// the only such path: an inline read could not be "stuck in Applying" in any sense a watchdog
@@ -3105,7 +3106,6 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
{
_applyingDeploymentId = deploymentId;
Become(Applying);
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
// Persist Applying row (idempotent on PK) — same crash-boundary marker as the Direct apply.
UpsertNodeDeploymentState(deploymentId, NodeDeploymentStatus.Applying, failureReason: null);
@@ -3126,6 +3126,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_log.Debug("DriverHost {Node}: fetching artifact for {Id} (rev {Rev}) from central over gRPC",
_localNode, deploymentId, revision);
// Armed only now, AFTER the synchronous Applying-row write above and immediately before the
// read/fetch starts: the watchdog times the read/fetch (its Warning says so), and a slow row write
// armed-before enqueued the tick ahead of the fetch's pipe-back, reporting a fetch that answered at
// once as WEDGED (Runtime.Tests master failures: ACompletedApply_NeverReportsAWedge on a cold EF model).
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
// A faulted fetch task maps to null bytes — the apply-failure path, exactly like an
// all-endpoints-down fetch — so a fault can never escape as an unhandled actor message.
_artifactFetcher.FetchAsync(deploymentId.ToString(), revision.Value, CancellationToken.None)
@@ -3164,7 +3170,6 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
{
_applyingDeploymentId = deploymentId;
Become(Applying);
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
// Persist Applying row (idempotent on PK) — the crash-boundary marker, and deliberately still
// on the actor thread: one bounded row write, and the apply must be recorded as in flight
@@ -3174,6 +3179,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_log.Debug("DriverHost {Node}: reading artifact for {Id} (rev {Rev}) from the ConfigDb, off the mailbox",
_localNode, deploymentId, revision);
// Armed after the Applying-row write, immediately before the read starts — see BeginFetchAndCacheApply.
Timers.StartSingleTimer(ApplyWedgeTimerKey, new ApplyWedged(deploymentId), _applyWedgeTimeout);
Task.Run(() => LoadArtifactBlob(deploymentId))
.PipeTo(
Self,
@@ -1,12 +1,14 @@
using System.Text.Json;
using Akka.Actor;
using Akka.Event;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Fleet;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
@@ -292,6 +294,69 @@ public sealed class DriverHostActorApplyingStashTests()
logs["appears WEDGED"].ShouldBe(0);
}
/// <summary>
/// The watchdog times the artifact read/fetch, NOT the synchronous Applying-row write that
/// precedes it — a slow ConfigDb row write must not be reported as a wedged fetch.
/// </summary>
/// <remarks>
/// <para>
/// The wedge timer used to be armed BEFORE <c>UpsertNodeDeploymentState(Applying)</c>, which
/// runs synchronously on the actor thread. Any write slower than the wedge delay therefore
/// enqueued the tick before the fetch had even started, so it was dequeued ahead of the
/// fetch's pipe-back and logged "the artifact read/fetch has neither answered nor failed" for
/// a fetch that answered immediately. This is what made
/// <see cref="ACompletedApply_NeverReportsAWedge"/> fail whenever it ran first in its process:
/// the cold EF Core model build on that first row write took ~350 ms against a 200 ms delay.
/// </para>
/// <para>
/// Every row write here is slowed to 4× the delay, deterministically. Writes that land
/// AFTER the fetch's pipe-back (the final Applied row) are harmless either way: a tick
/// enqueued during them is discarded by Akka's TimerScheduler once BecomeSteady cancels the
/// key. The presence control is the Applied ack — the apply really did run through the slow
/// writes.
/// </para>
/// </remarks>
[Fact]
public void ASlowApplyingRowWrite_IsNotReportedAsAWedgedFetch()
{
var wedgeTimeout = TimeSpan.FromMilliseconds(200);
var db = new SlowDbFactory(NewInMemoryDbFactory(), wedgeTimeout * 4);
var deploymentA = DeploymentId.NewId();
var coordinator = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "driver" },
deploymentArtifactCache: new NullArtifactCache(),
fetchAndCacheMode: true,
artifactFetcher: new GatedFetcher(ArtifactBytes(), gatedCalls: 0),
applyWedgeTimeout: wedgeTimeout));
var logs = SubscribeToLogs("appears WEDGED");
actor.Tell(new DispatchDeployment(deploymentA, RevA, CorrelationId.NewId()));
coordinator.ExpectMsg<ApplyAck>(TimeSpan.FromSeconds(20), cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
db.Calls.ShouldBeGreaterThanOrEqualTo(1);
logs.Drain(SpinWindow);
logs["appears WEDGED"].ShouldBe(0);
}
/// <summary>Delays every <see cref="IDbContextFactory{TContext}.CreateDbContext"/> on the calling thread.</summary>
private sealed class SlowDbFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner, TimeSpan delay)
: IDbContextFactory<OtOpcUaConfigDbContext>
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public OtOpcUaConfigDbContext CreateDbContext()
{
Interlocked.Increment(ref _calls);
Thread.Sleep(delay);
return inner.CreateDbContext();
}
}
/// <summary>Subscribes a fresh counter to the EventStream's log events.</summary>
/// <remarks>
/// Every fragment of interest must be declared up front, because draining is destructive: a
@@ -338,11 +338,17 @@ public sealed class OpcUaPublishActorWarmTests : RuntimeActorTestBase
Encoding.UTF8.GetBytes("{\"Clusters\":[{\"ClusterId\":\"a\",\"RedundancyMode\":\"None\"},{\"ClusterId\":\"b\",\"RedundancyMode\":\"Hot\"}],"
+ "\"Nodes\":[{\"NodeId\":\"x:1\",\"ClusterId\":\"b\"}]}"), "x:1").ShouldBe("Hot");
// Read the counter BEFORE the listener exists. If OtOpcUaTelemetry's static initializer has not run
// yet (this test alone in its process), it runs at the actor's first use while the listener is live,
// Meter.CreateCounter publishes each instrument to the live listener from INSIDE that initializer, and
// the field still reads null there — the counter was never enabled and the count stayed 0
// (Runtime.Tests master failures). A captured local is assigned by the time anything is published.
var counter = ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.RedundancyModeMismatch;
using var listener = new System.Diagnostics.Metrics.MeterListener();
long mismatches = 0;
listener.InstrumentPublished = (instrument, l) =>
{
if (ReferenceEquals(instrument, ZB.MOM.WW.OtOpcUa.Commons.Observability.OtOpcUaTelemetry.RedundancyModeMismatch))
if (ReferenceEquals(instrument, counter))
l.EnableMeasurementEvents(instrument);
};
listener.SetMeasurementEventCallback<long>((_, value, _, _) => Interlocked.Add(ref mismatches, value));