From be4f4f8f942ade062c5d85b6066186accd23f707 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:46:17 -0500 Subject: [PATCH] fix(resilience): #999 K-8 a wrong-shaped ResilienceConfig falls back to tier defaults instead of throwing out of driver spawn --- .../DriverResilienceOptionsParser.cs | 13 +++++- .../Drivers/DriverHostActor.cs | 29 +++++++++++++- .../Resilience/ResilienceConfigBrickTests.cs | 29 ++++++++++++++ .../DriverHostActorUnreadableArtifactTests.cs | 40 +++++++++++++++++++ 4 files changed, 108 insertions(+), 3 deletions(-) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs index 3d58f1cb0..f1ad841e7 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs @@ -101,13 +101,22 @@ public static class DriverResilienceOptionsParser { foreach (var (capName, overridePolicy) in shape.CapabilityPolicies) { - if (!Enum.TryParse(capName, ignoreCase: true, out var capability)) + // #999 / review K-8: Enum.TryParse accepts any NUMERIC string ("42", "-1"), so a name is a capability + // only when it is also a defined member with a base policy; and valid JSON can carry a null policy. + // Both used to throw (KeyNotFound / NullReference) out of the parser and the driver spawn. + if (!Enum.TryParse(capName, ignoreCase: true, out var capability) + || !Enum.IsDefined(capability) + || !merged.TryGetValue(capability, out var basePolicy)) { AppendDiagnostic(ref parseDiagnostic, $"Unknown capability '{capName}' in ResilienceConfig; skipped."); continue; } + if (overridePolicy is null) + { + AppendDiagnostic(ref parseDiagnostic, $"Capability '{capName}' in ResilienceConfig has a null policy; skipped."); + continue; + } - var basePolicy = merged[capability]; var mergedPolicy = new CapabilityPolicy( TimeoutSeconds: overridePolicy.TimeoutSeconds ?? basePolicy.TimeoutSeconds, RetryCount: overridePolicy.RetryCount ?? basePolicy.RetryCount, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 43aa0623c..e06287e9e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -4594,6 +4594,33 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn StartAcquisitionDemand(ready.DriverInstanceId, desired, ActorRefs.Nobody); } + /// + /// #999 / review K-8: the resilience invoker for a spawn, never throwing. A factory throw (a wrong-shaped + /// ResilienceConfig from a restored database, a manual SQL edit or an older build) used to escape + /// and the handler hosting every driver on the node — and the same artifact was re-applied + /// afterwards. Like a driver-factory throw it is a CONFIG error: logged at Error, and the driver runs on its tier + /// defaults (no per-instance overrides); only if that throws too does it run with the pass-through invoker. + /// + private IDriverCapabilityInvoker CreateInvoker(DriverInstanceSpec spec) + { + try { return _invokerFactory.Create(spec.DriverInstanceId, spec.DriverType, spec.ResilienceConfig); } + catch (Exception ex) + { + _log.Error(ex, + "DriverHost {Node}: the ResilienceConfig of {Id} ({Type}) could not be applied — the driver runs on its " + + "tier-default resilience policy until the config is fixed and redeployed", + _localNode, spec.DriverInstanceId, spec.DriverType); + } + try { return _invokerFactory.Create(spec.DriverInstanceId, spec.DriverType, null); } + catch (Exception ex) + { + _log.Error(ex, + "DriverHost {Node}: no resilience invoker could be built for {Id} ({Type}) — its capability calls run " + + "WITHOUT retry/timeout/breaker", _localNode, spec.DriverInstanceId, spec.DriverType); + return NullDriverCapabilityInvoker.Instance; + } + } + private void SpawnChild(DriverInstanceSpec spec, bool deferSubscriptions = false) { // An instance id removed by an earlier deployment (StopChild ⇒ Evict, which also holds back late @@ -4663,7 +4690,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // route through the retry/breaker/telemetry pipeline. The tier defaults are layered // with the per-instance ResilienceConfig from the artifact; the pass-through factory yields a // no-op invoker on nodes without the real resilience factory bound. - var invoker = _invokerFactory.Create(spec.DriverInstanceId, spec.DriverType, spec.ResilienceConfig); + var invoker = CreateInvoker(spec); child = Context.ActorOf( _dataWriteRuntime is null ? DriverInstanceActor.Props( driver!, diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/ResilienceConfigBrickTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/ResilienceConfigBrickTests.cs index 4b1871d93..005decfda 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/ResilienceConfigBrickTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/ResilienceConfigBrickTests.cs @@ -45,4 +45,33 @@ public sealed class ResilienceConfigBrickTests var result = await pipeline.ExecuteAsync(_ => ValueTask.FromResult(42), CancellationToken.None); result.ShouldBe(42); } + + /// + /// #999 / review K-8: valid JSON of the wrong SHAPE must fall back like malformed JSON does. A numeric capability + /// name passes Enum.TryParse (→ KeyNotFoundException) and a null policy dereferenced null + /// (NullReferenceException) — both escaped ParseOrDefaults and, through the invoker factory, the + /// driver host's spawn. + /// + [Theory] + [InlineData("{\"capabilityPolicies\":{\"42\":{\"timeoutSeconds\":3}}}")] + [InlineData("{\"capabilityPolicies\":{\"-1\":{\"timeoutSeconds\":3}}}")] + [InlineData("{\"capabilityPolicies\":{\"Read\":null}}")] + public void WrongShapedConfig_FallsBackToTierDefaults_WithADiagnostic(string json) + { + var options = DriverResilienceOptionsParser.ParseOrDefaults(DriverTier.A, json, out var diagnostic); + + options.Resolve(DriverCapability.Read).ShouldBe(DriverResilienceOptions.GetTierDefaults(DriverTier.A)[DriverCapability.Read]); + diagnostic.ShouldNotBeNullOrWhiteSpace(); + } + + /// K-8 positive control: a well-formed override next to a wrong-shaped entry still applies. + [Fact] + public void WrongShapedEntry_DoesNotDiscardTheWellFormedOnes() + { + var options = DriverResilienceOptionsParser.ParseOrDefaults( + DriverTier.A, "{\"capabilityPolicies\":{\"42\":{\"timeoutSeconds\":3},\"Read\":{\"timeoutSeconds\":7}}}", out var diagnostic); + + options.Resolve(DriverCapability.Read).TimeoutSeconds.ShouldBe(7); + diagnostic!.ShouldContain("42"); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnreadableArtifactTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnreadableArtifactTests.cs index 8ab378328..f033b6573 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnreadableArtifactTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnreadableArtifactTests.cs @@ -333,6 +333,46 @@ public sealed class DriverHostActorUnreadableArtifactTests : RuntimeActorTestBas tracker.TryGet("drv-1", "dev1").ShouldNotBeNull().IsBreakerOpen.ShouldBeTrue(); } + /// + /// #999 / review K-8 — an invoker factory that throws (a wrong-shaped ResilienceConfig reached it) must + /// not escape SpawnChild: that took down the handler hosting every driver on the node, and the same + /// artifact was re-applied afterwards. The host falls back to the tier defaults and the driver still runs + /// (positive control: it subscribes to its tag), as a driver-factory throw already degrades to a stub. + /// + [Fact] + public void A_throwing_invoker_factory_falls_back_and_the_driver_still_runs() + { + var db = NewInMemoryDbFactory(); + var factory = new SubscribingDriverFactory("Modbus"); + var invokerFactory = new ThrowOnceInvokerFactory(); + var coordinator = CreateTestProbe(); + var actor = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, + driverFactory: factory, + localRoles: new HashSet { "driver" }, + invokerFactory: invokerFactory)); + + actor.Tell(new DispatchDeployment(SeedV3Deployment(db, RevA), RevA, CorrelationId.NewId())); + coordinator.ExpectMsg(Timeout, cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied); + AwaitAssert(() => factory.LastSubscribedRefs.ShouldNotBeNull()!.ShouldContain(SpeedRef), + duration: Timeout, cancellationToken: TestContext.Current.CancellationToken); + invokerFactory.Calls.ShouldBe(2, "the throw was followed by one tier-default retry"); + invokerFactory.LastConfig.ShouldBeNull("the fallback drops the per-instance ResilienceConfig"); + } + + private sealed class ThrowOnceInvokerFactory : IDriverCapabilityInvokerFactory + { + public int Calls; + public string? LastConfig = "unset"; + + public IDriverCapabilityInvoker Create(string driverInstanceId, string driverType, string? resilienceConfigJson = null) + { + LastConfig = resilienceConfigJson; + if (Interlocked.Increment(ref Calls) == 1) throw new KeyNotFoundException("The given key '42' was not present in the dictionary."); + return NullDriverCapabilityInvoker.Instance; + } + } + private static void PublisherTick( ZB.MOM.WW.OtOpcUa.Core.Resilience.DriverResilienceStatusTracker t, ZB.MOM.WW.OtOpcUa.Runtime.Telemetry.TelemetryLocalHub h)