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
@@ -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));