diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index f43bfbd00..1676f81f2 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -284,7 +284,9 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa seeding fingerprint (value refs + each ref's raw/UNS fan-out + historization + alarm refs) is unchanged and none of whose refs gained a mux consumer (VirtualTag / scripted alarm / `IDependencyConsumer` driver); skipped drivers are re-pushed after the address-space outcome if it was a rebuild (`RebuildCompleted.AddressSpaceRebuilt`), degraded, - timed out, or the apply threw. A new mux value consumer must join `DriverHostActor.ConsumerRefs`. + timed out, or the apply threw. `AddressSpaceRebuilt` is also set for a repair pass and for any apply after a + degraded one — those create nodes the degraded apply missed, valueless, whose drivers the deploy skipped. + A new mux value consumer must join `DriverHostActor.ConsumerRefs`. `docs/DriverLifecycle.md` §"A deploy no longer re-subscribes an untouched driver". - **A config change is a respawn — there is NO in-place path (#665).** The `ApplyDelta`/`ApplyResult`/`DeltaApplied` seam (host `ApplyChildDelta`, `DriverSpawnPlan.ToApplyDelta`, the actor's Connected reinit and mid-connect diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 7e9e7d68b..31bc628fd 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -267,6 +267,11 @@ Things to know before touching any of this: re-pushed when `RebuildCompleted.AddressSpaceRebuilt` (additive, default `true`) or `Degraded` says so, when the outcome times out, or when the apply throws. Boot/restore applies still push every child. Pinned by `DriverHostActorUnchangedResubscribeTests` (absence + mirror / VirtualTag / rebuild / degraded positive controls). + The publish actor also reports `AddressSpaceRebuilt` for a **repair pass** (the empty-plan re-apply of a degraded + composition, or the #977 R-4 whole-composition re-ensure) and for **any apply following a degraded one**: the + degraded apply's re-push ran while the node it failed to place was missing, and the apply that finally creates it + skips its driver (fingerprint unchanged) — without the re-push the node stayed `BadWaitingForInitialData` until its + value changed, forever for a constant. Pinned against a real publish actor by `DriverHostActorDegradedRepairReseedTests`. ⚠️ A NEW kind of value consumer (something that registers driver refs with the mux and needs a first value) must join `ConsumerRefs`, or its first deploy leaves it waiting for the next value change. - ⚠️ **A data re-subscribe must not touch the alarm feed (#662).** Every deploy's bulk push re-sends 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 5a1d1a03f..f8f85c14a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -3520,7 +3520,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn private void HandleRebuildCompleted(OpcUa.OpcUaPublishActor.RebuildCompleted msg) { SeedSkippedDrivers(msg.Correlation, reseed: msg.AddressSpaceRebuilt || msg.Degraded, - msg.Degraded ? "degraded apply" : "full rebuild"); + msg.Degraded ? "degraded apply" : "full rebuild, or a repair of a previously degraded apply"); if (!_pendingAcks.Remove(msg.Correlation, out var pending)) { _log.Debug("DriverHost {Node}: address-space outcome for {Correlation} has no held ack (already timed out or superseded); dropping", diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs index b904c791c..ab889efda 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -165,8 +165,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// Gitea #995 (R-11): only when the apply was a clean NON-rebuild — every node that /// existed before it still exists with its value. DriverHostActor skips the re-subscribe of a driver /// whose desired set and fan-out are unchanged, and re-pushes those drivers when this is - /// (a full rebuild recreated their nodes without a value). Defaults to — the - /// conservative answer for any producer that does not know. + /// (a full rebuild recreated their nodes without a value). Also for a REPAIR pass (the + /// empty-plan re-apply of a degraded composition, or the #977 R-4 whole-composition re-ensure) and for any apply + /// following a degraded one: those can create nodes the degraded apply failed to place, valueless, whose drivers + /// the deploy skipped (#995 R-11 x #977 R-4 review). Defaults to — the conservative answer + /// for any producer that does not know. /// public sealed record RebuildCompleted( CorrelationId Correlation, DeploymentId? DeploymentId, bool Degraded, string? DegradedReason, @@ -331,6 +334,19 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// that pass is itself clean. /// private bool _lastAppliedDegraded; + + /// + /// #995 R-11 x #977 R-4 review: the previous apply (of ANY kind, reported or not) was degraded, so nodes it failed + /// to place may be created by the next one — after the driver host's post-degraded re-push already ran against + /// the missing node. The next apply therefore reports so the + /// drivers its deploy skipped are re-pushed; otherwise such a node stays BadWaitingForInitialData until its value + /// changes (forever for a constant). Set by . + /// + private bool _previousApplyDegraded; + + /// The apply in progress ran a REPAIR pass (re-ensured the whole composition after a degraded one): nodes + /// may have been created without a value. Set by , consumed by . + private bool _repairPassRan; /// /// Gitea #977 (R-20): this instance was created by a supervision RESTART, so is the /// empty seed while the sink (the node manager, which outlives the actor) still serves the previous instance's @@ -1534,8 +1550,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers } // #995 R-11: captured before the replay scope is reset — a rebuild (or the applier-less raw-sink rebuild) recreated - // every node, so the driver host must re-seed values it skipped re-subscribing. - var rebuilt = _applier is null || _replayScope.AllVariables; + // every node, so the driver host must re-seed values it skipped re-subscribing. So may a REPAIR pass, or any apply + // after a degraded one (#995 R-11 x #977 R-4 review): either can create a node the degraded apply failed to place, + // whose driver the deploy skipped because its fingerprint did not change — the node would never get a value. + var rebuilt = _applier is null || _replayScope.AllVariables || _repairPassRan || _previousApplyDegraded; + _repairPassRan = false; // Land what arrived while the plan was in flight on the nodes the apply just created — before the answer, // so "applied" means the deferred first values are on the address space too (review fix C1). @@ -1549,6 +1568,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers outcome = (true, "the expected local data catalog could not be activated"); } + // The FINAL outcome (completion and catalog included) decides whether the next apply must re-seed. + _previousApplyDegraded = outcome.Degraded; + if (msg.ReportOutcome) requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason, AddressSpaceRebuilt: rebuilt)); @@ -1638,7 +1660,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers { // The composition is unchanged but the last apply of it was a degraded // rebuild: re-ensure every node (each Ensure* no-ops on a node that stands) so the - // re-deploy actually repairs what that rebuild could not place. + // re-deploy actually repairs what that rebuild could not place. A node it now places has no value + // and its driver's re-subscribe was skipped (nothing it seeds changed): report it for a re-push. + _repairPassRan = true; var repairFailed = _applier!.MaterialiseHierarchy(composition) + MaterialiseNodes(plan, composition, fullComposition: true); if (repairFailed > 0) @@ -1687,6 +1711,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers // to place is inside _lastApplied and will never appear in a diff again, so a delta-only apply of an unrelated // change used to clear the degraded flag and report clean over a still-partial address space. var repairingDegraded = _lastAppliedDegraded && !outcome.RebuildCalled; + // Like the empty-plan repair: what the re-ensure places is valueless, so the skipped drivers must re-push. + if (repairingDegraded) _repairPassRan = true; failedNodes += MaterialiseNodes(plan, composition, fullComposition: outcome.RebuildCalled || repairingDegraded); if (outcome.RebuildCalled) _baselineUnknown = outcome.RebuildFailed; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDegradedRepairReseedTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDegradedRepairReseedTests.cs new file mode 100644 index 000000000..731632595 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDegradedRepairReseedTests.cs @@ -0,0 +1,210 @@ +using Akka.Actor; +using Akka.TestKit; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Engines; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// +/// #995 R-11 x #977 R-4 review, against a REAL (the R-11 tests stub it, so they +/// cannot see this). A degraded apply fails to create a node; the driver host's post-degraded re-push runs while the +/// node is still missing (writes are non-creating, so its value goes nowhere). The NEXT apply creates the node — but +/// the driver's seeding fingerprint is unchanged, so the deploy skipped it, and the publish actor reported a clean +/// non-rebuild. The node stayed BadWaitingForInitialData until the value changed (forever for a constant). +/// +[Collection("opcua-publish-meters")] +public sealed class DriverHostActorDegradedRepairReseedTests : RuntimeActorTestBase +{ + private static readonly NodeId TestNode = NodeId.Parse("node-1:4053"); + private const string PressurePath = "Plant/Modbus2/dev2/pressure"; + + private static readonly (string, string, string, string, string, bool)[] OneDriver = + [("drv-1", "Modbus", "dev1", "speed", "Float", false)]; + + private static readonly (string, string, string, string, string, bool)[] TwoDrivers = + [("drv-1", "Modbus", "dev1", "speed", "Float", false), ("drv-2", "Modbus2", "dev2", "pressure", "Float", false)]; + + // drv-1's driver folder renamed: a raw CONTAINER rename, which is a full rebuild; drv-2 is untouched by it. + private static readonly (string, string, string, string, string, bool)[] TwoDriversRenamed = + [("drv-1", "ModbusRenamed", "dev1", "speed", "Float", false), ("drv-2", "Modbus2", "dev2", "pressure", "Float", false)]; + + private static readonly (string, string, string, string, string, bool)[] ThreeDriversRenamed = + [ + ("drv-1", "ModbusRenamed", "dev1", "speed", "Float", false), ("drv-2", "Modbus2", "dev2", "pressure", "Float", false), + ("drv-3", "Modbus3", "dev3", "flow", "Float", false), + ]; + + private static readonly (string, string, string, string, string?)[] NoRefs = []; + + /// Degraded NON-rebuild (composition held back), then the re-diff creates the node: its driver is re-pushed. + [Fact] + public void A_node_a_degraded_add_failed_to_create_gets_its_driver_re_pushed_when_the_next_apply_creates_it() + { + var rig = new Rig(this, NewInMemoryDbFactory()); + rig.Deploy(OneDriver, Rev('a')); + AwaitAssert(() => rig.Driver("drv-1").SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + + // B adds drv-2; its pressure variable cannot be created ⇒ degraded, drv-2 pushed with its node missing. + rig.Sink.FailVariable = PressurePath; + rig.Deploy(TwoDrivers, Rev('b'), expectDegraded: true); + var drv2 = rig.Driver("drv-2"); + AwaitAssert(() => drv2.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + rig.Sink.CreatedVariables.ShouldNotContain(PressurePath); + + // C (same composition, fault gone) creates the node. drv-2's fingerprint is unchanged, so the deploy skips it — + // the outcome must still re-push it, or the new node never gets a value. + rig.Sink.FailVariable = null; + rig.Deploy(TwoDrivers, Rev('c')); + rig.Sink.CreatedVariables.ShouldContain(PressurePath); + AwaitAssert(() => drv2.SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct); + + // Positive control: the address space is clean again, so a further unrelated deploy skips drv-2 as before. + rig.Deploy(ThreeDriversWith(drv1Name: "Modbus"), Rev('d')); + AwaitAssert(() => rig.Driver("drv-3").SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + Thread.Sleep(300); + drv2.SubscribeCount.ShouldBe(2, "a clean non-rebuild deploy after the repair must still skip the untouched driver"); + } + + /// Degraded REBUILD (composition advanced), then the empty-plan repair of the same revision creates the node. + [Fact] + public void A_node_a_degraded_rebuild_failed_to_create_gets_its_driver_re_pushed_by_the_empty_plan_repair() + { + var rig = new Rig(this, NewInMemoryDbFactory()); + rig.Deploy(TwoDrivers, Rev('a')); + var drv2 = rig.Driver("drv-2"); + AwaitAssert(() => drv2.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + + rig.Sink.FailVariable = PressurePath; + rig.Deploy(TwoDriversRenamed, Rev('b'), expectDegraded: true); + rig.Sink.RebuildCount.ShouldBe(1); + // drv-2 was skipped, then re-pushed on the degraded outcome — while its node is missing. + AwaitAssert(() => drv2.SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct); + + rig.Sink.FailVariable = null; + var created = rig.Sink.CreatedVariables.Count(v => v == PressurePath); + rig.Deploy(TwoDriversRenamed, Rev('c')); // same composition ⇒ empty plan ⇒ the repair branch + rig.Sink.CreatedVariables.Count(v => v == PressurePath).ShouldBeGreaterThan(created); + rig.Sink.RebuildCount.ShouldBe(1, "the repair must not need a rebuild"); + AwaitAssert(() => drv2.SubscribeCount.ShouldBe(3), PresenceBudget, cancellationToken: Ct); + } + + /// Degraded REBUILD, then an UNRELATED add re-ensures the whole composition (#977 R-4) and creates the node. + [Fact] + public void A_node_a_degraded_rebuild_failed_to_create_gets_its_driver_re_pushed_by_the_R4_whole_composition_repair() + { + var rig = new Rig(this, NewInMemoryDbFactory()); + rig.Deploy(TwoDrivers, Rev('a')); + var drv2 = rig.Driver("drv-2"); + AwaitAssert(() => drv2.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct); + + rig.Sink.FailVariable = PressurePath; + rig.Deploy(TwoDriversRenamed, Rev('b'), expectDegraded: true); + AwaitAssert(() => drv2.SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct); + + rig.Sink.FailVariable = null; + var created = rig.Sink.CreatedVariables.Count(v => v == PressurePath); + rig.Deploy(ThreeDriversRenamed, Rev('c')); // adds drv-3 only: a surgical PureAdd + rig.Sink.CreatedVariables.Count(v => v == PressurePath).ShouldBeGreaterThan(created); + rig.Sink.RebuildCount.ShouldBe(1, "the repair must not need a rebuild"); + AwaitAssert(() => drv2.SubscribeCount.ShouldBe(3), PresenceBudget, cancellationToken: Ct); + } + + private static (string, string, string, string, string, bool)[] ThreeDriversWith(string drv1Name) => + [ + ("drv-1", drv1Name, "dev1", "speed", "Float", false), ("drv-2", "Modbus2", "dev2", "pressure", "Float", false), + ("drv-3", "Modbus3", "dev3", "flow", "Float", false), + ]; + + private static RevisionHash Rev(char c) => RevisionHash.Parse(new string(c, 64)); + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private sealed class Rig + { + private readonly RuntimeActorTestBase _kit; + private readonly IDbContextFactory _db; + private readonly IActorRef _host; + private readonly TestProbe _coordinator; + + public RecordingSubscribableDriverFactory Factory { get; } = new("Modbus"); + public SelectiveFaultSink Sink { get; } = new(); + + public Rig(RuntimeActorTestBase kit, IDbContextFactory db) + { + _kit = kit; + _db = db; + _coordinator = kit.CreateTestProbe(); + var publish = kit.Sys.ActorOf(OpcUaPublishActor.PropsForTests( + sink: Sink, applier: new AddressSpaceApplier(Sink, NullLogger.Instance))); + _host = kit.Sys.ActorOf(DriverHostActor.Props( + _db, TestNode, _coordinator.Ref, + driverFactory: Factory, + localRoles: new HashSet { "driver" }, + dependencyMux: kit.CreateTestProbe().Ref, + opcUaPublishActor: publish, + virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: kit.CreateTestProbe().Ref)); + } + + public RecordingSubscribableDriver Driver(string id) + { + RecordingSubscribableDriver? found = null; + _kit.AwaitAssert(() => (found = Factory.Created.LastOrDefault(d => d.DriverInstanceId == id)).ShouldNotBeNull(), + PresenceBudget, cancellationToken: Ct); + return found!; + } + + /// Dispatches and waits for the ack — which the host releases only after the address-space outcome (and + /// after any re-push that outcome triggers has been sent). + public void Deploy((string, string, string, string, string, bool)[] tags, RevisionHash rev, bool expectDegraded = false) + { + var id = V3ArtifactSeeder.SeedV3Deployment(_db, rev, tags, NoRefs, enabled: true); + _host.Tell(new DispatchDeployment(id, rev, CorrelationId.NewId())); + var ack = _coordinator.FishForMessage(m => m.DeploymentId == id, PresenceBudget, cancellationToken: Ct); + ack.Outcome.ShouldBe(ApplyAckOutcome.Applied); + ack.Degraded.ShouldBe(expectDegraded, ack.DegradedReason); + } + } + + /// A sink that refuses to create ONE variable (by NodeId) while names it. + private sealed class SelectiveFaultSink : IOpcUaAddressSpaceSink + { + private readonly object _gate = new(); + private readonly List _created = new(); + public volatile string? FailVariable; + public int RebuildCount; + + public IReadOnlyList CreatedVariables + { + get { lock (_gate) return _created.ToArray(); } + } + + public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { } + public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { } + public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime occurredUtc, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { } + public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { } + public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { } + + public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) + { + if (variableNodeId == FailVariable) throw new InvalidOperationException("simulated variable fault"); + lock (_gate) _created.Add(variableNodeId); + } + + public void RebuildAddressSpace() => Interlocked.Increment(ref RebuildCount); + public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { } + public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { } + public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorApplyOutcomeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorApplyOutcomeTests.cs index 89f648ec8..247564af4 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorApplyOutcomeTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorApplyOutcomeTests.cs @@ -198,6 +198,81 @@ public sealed class OpcUaPublishActorApplyOutcomeTests : RuntimeActorTestBase Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2" }, "Second", withAlarm: true)).Degraded.ShouldBeTrue(); } + /// + /// #995 R-11 x #977 R-4 review: the empty-plan repair of a degraded composition may CREATE nodes (valueless) whose + /// drivers the deploy skipped, so it must report AddressSpaceRebuilt (the driver host's re-push signal) — + /// and a genuinely clean no-op afterwards must not (positive control: the signal is not stuck on). + /// + [Fact] + public void The_empty_plan_repair_of_a_degraded_rebuild_asks_for_a_re_push_and_the_clean_no_op_after_it_does_not() + { + var sink = new FaultingSink(throwOnEnsureFolder: false); + var applier = new AddressSpaceApplier(sink, NullLogger.Instance); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink: sink, applier: applier)); + + var first = Deploy(actor, BuildArtifact(new[] { "eq-1" }, "First", withAlarm: true)); + first.Degraded.ShouldBeFalse(); + first.AddressSpaceRebuilt.ShouldBeFalse("control: a clean non-rebuild apply does not ask for a re-push"); + + sink.ThrowOnAlarmCondition = true; + var changed = BuildArtifact(new[] { "eq-1" }, "Second", withAlarm: true); + Deploy(actor, changed).Degraded.ShouldBeTrue(); + sink.RebuildCount.ShouldBe(1); + + sink.ThrowOnAlarmCondition = false; + var repair = Deploy(actor, changed); // same composition ⇒ empty plan ⇒ the repair branch + repair.Degraded.ShouldBeFalse(); + repair.AddressSpaceRebuilt.ShouldBeTrue("the repair created what the degraded rebuild could not place"); + sink.RebuildCount.ShouldBe(1); + + var noOp = Deploy(actor, changed); + noOp.Degraded.ShouldBeFalse(); + noOp.AddressSpaceRebuilt.ShouldBeFalse("a clean no-op after the repair created nothing"); + } + + /// The #977 R-4 whole-composition re-ensure (an unrelated surgical deploy after a degraded rebuild) likewise. + [Fact] + public void The_R4_whole_composition_repair_asks_for_a_re_push_and_a_clean_add_after_it_does_not() + { + var sink = new FaultingSink(throwOnEnsureFolder: false); + var applier = new AddressSpaceApplier(sink, NullLogger.Instance); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink: sink, applier: applier)); + + Deploy(actor, BuildArtifact(new[] { "eq-1" }, "First", withAlarm: true)).Degraded.ShouldBeFalse(); + sink.ThrowOnAlarmCondition = true; + Deploy(actor, BuildArtifact(new[] { "eq-1" }, "Second", withAlarm: true)).Degraded.ShouldBeTrue(); + + sink.ThrowOnAlarmCondition = false; + var repair = Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2" }, "Second", withAlarm: true)); + repair.Degraded.ShouldBeFalse(); + repair.AddressSpaceRebuilt.ShouldBeTrue("the R-4 re-ensure created what the degraded rebuild could not place"); + sink.RebuildCount.ShouldBe(1); + + var clean = Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2", "eq-3" }, "Second", withAlarm: true)); + clean.Degraded.ShouldBeFalse(); + clean.AddressSpaceRebuilt.ShouldBeFalse("an ordinary surgical add after the repair is not a repair"); + } + + /// A degraded NON-rebuild (composition held back) — the next apply's re-diff creates the missing node. + [Fact] + public void The_apply_after_a_degraded_non_rebuild_asks_for_a_re_push() + { + var sink = new FaultingSink(throwOnEnsureFolder: false); + var applier = new AddressSpaceApplier(sink, NullLogger.Instance); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink: sink, applier: applier)); + + Deploy(actor, BuildArtifact(new[] { "eq-1" }, "eq-1", withAlarm: false)).Degraded.ShouldBeFalse(); + sink.ThrowOnEnsureFolder = true; + Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2" }, "eq-1", withAlarm: false)).Degraded.ShouldBeTrue(); + sink.RebuildCount.ShouldBe(0); + + sink.ThrowOnEnsureFolder = false; + var next = Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2" }, "eq-1", withAlarm: false)); + next.Degraded.ShouldBeFalse(); + next.AddressSpaceRebuilt.ShouldBeTrue(); + sink.RebuildCount.ShouldBe(0); + } + [Fact] public void The_first_apply_after_a_supervision_restart_rebuilds_instead_of_diffing_against_an_empty_baseline() {