From a0f41a30d8f5880a4f82d4bdb6f8b93ad893beb9 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:46:47 -0500 Subject: [PATCH] =?UTF-8?q?fix(deploy):=20#977=20deploy/apply=20bookkeepin?= =?UTF-8?q?g=20=E2=80=94=20planner=20sees=20every=20composition=20field,?= =?UTF-8?q?=20degraded/restarted=20applies=20repair,=20failed=20deploys=20?= =?UTF-8?q?restore=20the=20last=20applied=20revision,=20superseded=20deplo?= =?UTF-8?q?yments=20close?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - U-2: planner diffs the rich scripted-alarm plans; an Enabled flip is a surgical add/remove of the one condition, a Name/AlarmType/Severity edit on an enabled alarm rebuilds. - U-3: planner diffs UNS Areas/Lines in full; a Line moved to another Area rebuilds, added/removed Areas/Lines are surgical. - U-9: removing the last VirtualTag in a FolderPath removes the sub-folder in place. - AddressSpacePlannerFieldCoverageTests reflects over every composition list + record field. - R-4: while the last applied composition is degraded, a non-rebuild apply re-ensures the full composition. - R-20: a supervision restart of OpcUaPublishActor forces its first apply to rebuild. - R-1: Direct boot with a Failed/orphan newest row restores the newest Applied deployment, then the cache. - R-15: the revision advances after the last throwing apply step; a throw marks it unconfirmed. - H-4: ConfigPublishCoordinator closes a superseded in-flight deployment (TimedOut + reason). Co-Authored-By: Claude --- CLAUDE.md | 17 +- docs/Redundancy.md | 20 +- docs/ScriptedAlarms.md | 5 + .../Coordinators/ConfigPublishCoordinator.cs | 45 +++++ .../AddressSpaceApplier.cs | 74 ++++++- .../AddressSpaceChangeClassifier.cs | 42 +++- .../AddressSpacePlan.cs | 145 ++++++++++++- .../Drivers/DriverHostActor.cs | 80 +++++++- .../OpcUa/OpcUaPublishActor.cs | 61 +++++- .../ConfigPublishCoordinatorSupersedeTests.cs | 110 ++++++++++ .../AddressSpaceApplierTests.cs | 175 ++++++++++++++++ .../AddressSpacePlannerFieldCoverageTests.cs | 190 ++++++++++++++++++ .../DriverHostActorDeployBookkeepingTests.cs | 150 ++++++++++++++ .../OpcUaPublishActorApplyOutcomeTests.cs | 134 +++++++++++- 14 files changed, 1215 insertions(+), 33 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorSupersedeTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpacePlannerFieldCoverageTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDeployBookkeepingTests.cs diff --git a/CLAUDE.md b/CLAUDE.md index 4a1cec3bb..a3892dfa8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -183,8 +183,16 @@ is still default-closed; what changed is which deltas it whitelists. a plain **rename never pairs** and is served surgically as remove-one-node + add-one-node with any referencing UNS mirror re-pointed, live-gated 2026-08-15), a raw **container** (Folder/Driver/Device/TagGroup) rename or removal, `ChangedEquipment` / - `ChangedAlarms`, a non-surgical equipment-tag delta, and anything else the - `with`-equality whitelist does not name (including any FUTURE field). + `ChangedAlarms`, a non-surgical equipment-tag delta, a UNS **Line moved to another Area** (#977 U-3), + a **Name/AlarmType/Severity** edit on a scripted alarm enabled before and after (#977 U-2), and anything + else the `with`-equality whitelist does not name (including any FUTURE field). +- **The planner diffs every composition list and field (#977).** Scripted-alarm `Enabled`/`AlarmType`/ + `Severity`/`Name` (rich `EquipmentScriptedAlarms`) and Area/Line add/remove/parentage used to be invisible — + enabling an alarm or moving a Line produced an EMPTY plan. Now an alarm **enable/disable flip** is a surgical + add/remove of its one condition, added/removed Areas/Lines and an orphaned VirtualTag `FolderPath` + sub-folder are surgical too. `AddressSpacePlannerFieldCoverageTests` REFLECTS over every list and record + field of `AddressSpaceComposition` and fails a field the planner does not see — a new composition field must + be diffed (and classified) or listed as exempt there. - **Now surgical:** a **non-alarm** raw-tag delta over the in-place-updatable attributes (`Writable` / `IsHistorized` / `HistorianTagname` / `DataType` / `IsArray` / `ArrayLength`) and/or `ReferencingEquipmentPaths` — applied via `ISurgicalAddressSpaceSink.UpdateTagAttributes` @@ -208,7 +216,10 @@ is still default-closed; what changed is which deltas it whitelists. delta path removed that. Holding the composition back is the replacement — the next deploy re-diffs the same composition and re-ensures what failed, at the cost of re-emitting that apply's removes (a re-remove returns false and ratchets to a rebuild, which is the correct, - bounded resync). A **rebuild** still advances even with failures. + bounded resync). A **rebuild** still advances even with failures — and while that degraded flag is set, + every later non-rebuild apply re-ensures the FULL composition until one is clean (#977 R-4). A supervision + restart of `OpcUaPublishActor` forces its first apply to rebuild (#977 R-20: `_lastApplied` resets, the + node manager does not). - **…and the deploy ack now SAYS so (#601).** The Applied ack waits for `OpcUaPublishActor`'s `RebuildCompleted` (timeout = shared `DeployTimings.ApplyDeadline` − 15 s = 105 s ⇒ degraded "outcome not reported in time", never clean) and carries an additive `Degraded`/`DegradedReason` on both ack transports; central seals but records `NodeDeploymentState.FailureReason = "Applied degraded: …"` diff --git a/docs/Redundancy.md b/docs/Redundancy.md index d1bf5bc8c..3d763bfb6 100644 --- a/docs/Redundancy.md +++ b/docs/Redundancy.md @@ -823,7 +823,25 @@ deployment green fleet-wide. Now: missing nodes, and the ack reports the new outcome. A degraded **rebuild** is the other shape: it DOES advance `_lastApplied`, so the identical re-deploy diffs to an empty plan — the publish actor remembers that the last advance was degraded and, on that empty plan, re-ensures the whole composition (idempotent, - no second rebuild), reporting clean only if that pass is clean. + no second rebuild), reporting clean only if that pass is clean. **The same holds for a NON-empty plan + (#977 R-4):** while the flag is set, an unrelated surgical deploy re-ensures the whole composition rather + than only its own delta, and clears the flag only when that pass is clean — before, a one-tag add after a + degraded rebuild sealed green over the node the rebuild had failed to place. +- **A restarted publish actor rebuilds its first apply (#977 R-20).** A supervision restart resets + `_lastApplied` to empty while the node manager keeps serving; the new instance therefore forces a full + rebuild on its next apply (even of an otherwise empty plan) instead of diffing against nothing. +- **A failed apply never looks cleanly served (#977 R-15).** `DriverHostActor` advances `_currentRevision` only + after the last step that can throw, and a throw marks the current revision *unconfirmed* — a re-dispatch of + it re-applies instead of short-circuiting a clean `Applied`. +- **A restart after a FAILED deploy restores the last APPLIED one (#977 R-1).** A `Direct` node whose newest + `NodeDeploymentState` row is `Failed` (or an orphan `Applying` row whose deployment is gone) restores the + newest **Applied** deployment for the node — the revision it kept serving when the later apply failed — then + falls back to the LocalDb cache, and only then boots Steady with no revision. It used to boot straight to an + empty address space, logged at Info, with nothing to heal it. +- **A newer dispatch closes the one still in flight (#977 H-4).** If `ConfigPublishCoordinator` receives a + dispatch for deployment B while a different deployment A is still awaiting acks (two composes overlapping a + singleton hand-over), it writes A `TimedOut` with a "Superseded by deployment B" reason before adopting B. + A used to stay `AwaitingApplyAcks` forever, refusing every later deploy as `AnotherDeploymentInFlight`. - **A node with a ConfigDb also writes the reason on its own row** (`ApplyAck.DegradedReasonPrefix`), because central only records it when it *accepts* the ack — a timed-out deployment's late ack is discarded. **That row stays `Applying` until the outcome is known** (lmxopcua#868): it used to be written `Applied`/clean diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md index 531281c6a..32e04c1ac 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -175,6 +175,11 @@ after a full rebuild, carrying the unchanged `LastTransitionUtc`. Decisions: - **Identity is the alarm id.** An edited predicate, severity, message template or equipment placement on the same id is the same alarm. Its condition carries over, the new predicate decides the next transition (a predicate that is now false is a real `Cleared`), and the next projection carries the new severity and message. +- **The condition NODE follows the deploy too (#977 U-2).** Enabling a disabled alarm materialises its condition in place + (no rebuild), disabling one removes it in place (a terminal removed-state event first), and a `Name` / `AlarmType` / + `Severity` edit on an enabled alarm rebuilds the address space so the node gets its new type and name. Before #977 the + address-space planner never looked at those four fields: an enable produced an empty plan and the condition never appeared + (every engine write to it was a silent no-op), a disable left it browsable, and a type/name edit kept the old node. - **Removed and re-added in one deploy** is the same id in both generations, so it carries over. An alarm **removed or disabled** (the host does not load a disabled plan) by one deploy and re-added by a later one is absent from the previous generation, so it is seeded from the store like a restart: the engine stopped evaluating it, so it is a new occurrence. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs index b508feb84..70d2c04a3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs @@ -527,6 +527,13 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU guardRowVersion = guard?.RowVersion; } + // Gitea #977 (H-4): a DIFFERENT deployment is still in flight. Adopting the new one overwrites _current, clears + // the acks and replaces the single deadline timer — so nothing would ever write a terminal status for the old + // one: its row stayed AwaitingApplyAcks forever and AdminOps refused every later deploy as + // AnotherDeploymentInFlight. Close it first (TimedOut, only if still in flight, with a reason naming the + // successor), then adopt the new one. + if (_current is { } prior && prior != msg.DeploymentId) CloseSuperseded(prior, msg.DeploymentId); + _current = msg.DeploymentId; _acks.Clear(); _degraded.Clear(); @@ -602,6 +609,44 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU } } + /// + /// Gitea #977 (H-4): writes the terminal for the in-flight deployment + /// that is about to replace, and resets the per-deployment + /// state. Conditioned on the row still being in flight (a row something else already closed is left alone), and + /// never fatal: a failed write is logged and the new dispatch proceeds — the AdminOps lost-dispatch closure and + /// the coordinator's recovery remain the backstops for a row this could not close. + /// + private void CloseSuperseded(DeploymentId prior, DeploymentId successor) + { + var acked = _acks.Count; + var expected = _expectedAcks.Count; + try + { + using var db = _dbFactory.CreateDbContext(); + UpdateDeploymentStatus(db, prior, DeploymentStatus.TimedOut, onlyIfInFlight: true); + var entry = TrackStub(db, prior, onlyIfInFlight: true); + if (entry is not null) + { + entry.Entity.FailureReason = Truncate( + $"Superseded by deployment {successor} before its acks completed ({acked}/{expected} landed). " + + "Its nodes were dispatched the newer deployment instead; redeploy this revision if it is still wanted."); + entry.Property(x => x.FailureReason).IsModified = true; + } + db.SaveChanges(); + _log.Warning( + "Deployment {Id} was still in flight ({Acked}/{Total} acks) when deployment {Next} was dispatched — closed as TimedOut (superseded)", + prior, acked, expected, successor); + } + catch (Exception ex) + { + _log.Error(ex, + "Deployment {Id} was superseded by {Next} but could not be closed; it may stay in flight until recovery or the lost-dispatch closure ends it", + prior, successor); + } + + ResetForNext(); + } + private void HandleAck(ApplyAck msg) { if (_current is null || msg.DeploymentId != _current.Value) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs index cc87923f8..f00d75c01 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs @@ -82,11 +82,23 @@ public sealed class AddressSpaceApplier /// /// The plan to apply. /// A AddressSpaceApplyOutcome summarizing the applied changes. - public AddressSpaceApplyOutcome Apply(AddressSpacePlan plan) + public AddressSpaceApplyOutcome Apply(AddressSpacePlan plan) => Apply(plan, forceRebuild: false); + + /// + /// , optionally forcing a full rebuild whatever the plan's kind. Gitea #977 + /// (R-20): a caller whose diff BASELINE is not known to match the served address space (the publish actor after a + /// supervision restart reset its last-applied composition to empty while the node manager kept every node) cannot + /// trust a surgical apply — removed nodes would never be removed and in-place attribute edits would be skipped — so + /// it rebuilds once, even for an otherwise empty plan. + /// + /// The plan to apply. + /// Rebuild the sink's address space regardless of the plan's classification. + /// A AddressSpaceApplyOutcome summarizing the applied changes. + public AddressSpaceApplyOutcome Apply(AddressSpacePlan plan, bool forceRebuild) { ArgumentNullException.ThrowIfNull(plan); - if (plan.IsEmpty) + if (plan.IsEmpty && !forceRebuild) { _logger.LogDebug("AddressSpaceApplier: plan is empty; skipping sink writes"); return new AddressSpaceApplyOutcome(RemovedNodes: 0, AddedNodes: 0, ChangedNodes: 0, RebuildCalled: false); @@ -110,18 +122,20 @@ public sealed class AddressSpaceApplier // removed-vtag-only deploy. v3 Batch 4: removed raw containers/tags + UNS reference variables are // likewise real removals. removedCount += plan.RemovedEquipmentVirtualTags.Count + - plan.RemovedRawContainers.Count + plan.RemovedRawTags.Count + plan.RemovedUnsReferenceVariables.Count; + plan.RemovedRawContainers.Count + plan.RemovedRawTags.Count + plan.RemovedUnsReferenceVariables.Count + + plan.RemovedUnsAreas.Count + plan.RemovedUnsLines.Count + plan.RemovedVirtualTagFolders.Count; var changedCount = plan.ChangedEquipment.Count + plan.ChangedDrivers.Count + plan.ChangedAlarms.Count + plan.ChangedEquipmentVirtualTags.Count + plan.ChangedRawContainers.Count + plan.ChangedRawTags.Count + plan.ChangedUnsReferenceVariables.Count + // A UNS Area/Line rename is an in-place change to an existing folder node. - plan.RenamedFolders.Count; + plan.RenamedFolders.Count + plan.ChangedEquipmentScriptedAlarms.Count; var addedCount = plan.AddedEquipment.Count + plan.AddedDrivers.Count + plan.AddedAlarms.Count + plan.AddedEquipmentVirtualTags.Count + - plan.AddedRawContainers.Count + plan.AddedRawTags.Count + plan.AddedUnsReferenceVariables.Count; + plan.AddedRawContainers.Count + plan.AddedRawTags.Count + plan.AddedUnsReferenceVariables.Count + + plan.AddedUnsAreas.Count + plan.AddedUnsLines.Count; // Classify the plan and route each delta class to its MINIMAL mutation instead of // rebuilding the world for any topology change. AddressSpaceChangeClassifier is a pure policy over @@ -147,7 +161,7 @@ public sealed class AddressSpaceApplier // ChangedDrivers is node-inert (routes through DriverHostActor's spawn plan) — the classifier leaves // a driver-only plan AttributeOnly, so it never rebuilds here. var kind = AddressSpaceChangeClassifier.Classify(plan); - var mustRebuild = kind is AddressSpaceChangeKind.Rebuild; + var mustRebuild = forceRebuild || kind is AddressSpaceChangeKind.Rebuild; // PureRemove + AddRemoveMix both run the in-place remove pass below (AddRemoveMix's adds are handled // afterward by the publish actor's Materialise passes + announce). var hasRemovePass = kind is AddressSpaceChangeKind.PureRemove or AddressSpaceChangeKind.AddRemoveMix; @@ -358,6 +372,15 @@ public sealed class AddressSpaceApplier if (!SafeRemoveVariable(surgical, nodeId, AddressSpaceRealm.Uns)) return false; } + // #977 U-9 — a VirtualTag sub-folder no remaining VirtualTag uses goes with its last variable. The folder is a + // plain UNS folder, and RemoveEquipmentSubtree removes any indexed folder by id (the name predates this use); + // it runs after the variable removals above, so the folder is empty by then. Unknown ⇒ false ⇒ the rebuild + // ratchet, as for every other surgical remove. + foreach (var f in plan.RemovedVirtualTagFolders.Where(f => NotSubsumed(f.EquipmentId))) + { + if (!SafeRemoveEquipmentSubtree(surgical, UnsSubFolder(f.EquipmentId, f.FolderPath), AddressSpaceRealm.Uns)) return false; + } + // Removed scripted alarms for surviving equipment — the terminal RemovedConditionState was already // written by the top-of-Apply removal block; here we tear the condition node down in place. foreach (var alarm in plan.RemovedAlarms.Where(a => NotSubsumed(a.EquipmentId))) @@ -365,6 +388,14 @@ public sealed class AddressSpaceApplier if (!SafeRemoveAlarmCondition(surgical, alarm.ScriptedAlarmId, AddressSpaceRealm.Uns)) return false; } + // #977 U-2 — a scripted condition that stops existing without its thin row going: the alarm was DISABLED (or its + // predicate script vanished). Terminal removed state first, so a subscriber sees it end, then the in-place remove. + foreach (var alarm in plan.ScriptedConditionRemoves().Where(a => NotSubsumed(a.EquipmentId))) + { + if (!SafeWriteAlarmCondition(alarm.ScriptedAlarmId, RemovedConditionState, ts, AddressSpaceRealm.Uns)) failedNodes++; + if (!SafeRemoveAlarmCondition(surgical, alarm.ScriptedAlarmId, AddressSpaceRealm.Uns)) return false; + } + // v3 Batch 4 — removed UNS reference variables (Uns realm, plain value nodes): terminal Bad then // in-place remove. // @@ -399,6 +430,18 @@ public sealed class AddressSpaceApplier if (!SafeRemoveEquipmentSubtree(surgical, eq.EquipmentId, AddressSpaceRealm.Uns)) return false; } + // #977 U-3 — removed UNS Lines, then removed Areas (children before parents), AFTER their equipment above. The + // folder ids are the line/area ids MaterialiseHierarchy placed them at. A folder that still had live content + // would be taken with it, but nothing can: an equipment moved off a removed line is a ChangedEquipment (rebuild). + foreach (var line in plan.RemovedUnsLines) + { + if (!SafeRemoveEquipmentSubtree(surgical, line.UnsLineId, AddressSpaceRealm.Uns)) return false; + } + foreach (var area in plan.RemovedUnsAreas) + { + if (!SafeRemoveEquipmentSubtree(surgical, area.UnsAreaId, AddressSpaceRealm.Uns)) return false; + } + // v3 Batch 4 — removed RAW tags (Raw realm): an alarm-bearing raw tag is a condition node (terminal // RemovedConditionState + RemoveAlarmConditionNode); a plain raw value tag is a variable (terminal Bad // + RemoveVariableNode). @@ -525,8 +568,23 @@ public sealed class AddressSpaceApplier // folder is a UNS-realm node, announced in the Uns realm like every id this method returns. Added RAW // containers/tags have Raw-realm parents and are computed separately (ComputeRawAddAnnouncements). foreach (var v in plan.AddedUnsReferenceVariables) ids.Add(v.EquipmentId); - foreach (var eq in plan.AddedEquipment) - ids.Add(string.IsNullOrWhiteSpace(eq.UnsLineId) ? eq.EquipmentId : eq.UnsLineId); + // #977: a condition enabled in place hangs under its equipment folder. + foreach (var a in plan.ScriptedConditionAdds()) ids.Add(a.EquipmentId); + + // Folders: each added folder announces its parent — unless that parent is ITSELF added in this plan (its own + // announcement covers the whole new subtree, as in ComputeRawAddAnnouncements). An added Area hangs under the + // shared root, which has no announceable id, so it announces itself, as does an equipment with no line. + var addedFolders = new HashSet(StringComparer.Ordinal); + foreach (var a in plan.AddedUnsAreas) addedFolders.Add(a.UnsAreaId); + foreach (var l in plan.AddedUnsLines) addedFolders.Add(l.UnsLineId); + void AnnounceFolder(string nodeId, string? parentNodeId) + { + if (string.IsNullOrWhiteSpace(parentNodeId)) ids.Add(nodeId); + else if (!addedFolders.Contains(parentNodeId)) ids.Add(parentNodeId); + } + foreach (var eq in plan.AddedEquipment) AnnounceFolder(eq.EquipmentId, eq.UnsLineId); + foreach (var line in plan.AddedUnsLines) AnnounceFolder(line.UnsLineId, line.UnsAreaId); + foreach (var area in plan.AddedUnsAreas) AnnounceFolder(area.UnsAreaId, null); var list = ids.ToList(); list.Sort(StringComparer.Ordinal); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceChangeClassifier.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceChangeClassifier.cs index 2b9e4612c..c94227665 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceChangeClassifier.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceChangeClassifier.cs @@ -93,7 +93,15 @@ public static class AddressSpaceChangeClassifier plan.ChangedAlarms.Count > 0 || plan.ChangedRawContainers.Count > 0 || plan.ChangedRawTags.Any(d => !RawTagDeltaIsSurgicalEligible(d)) || - plan.ChangedEquipmentVirtualTags.Any(d => !VtagDeltaIsNodeIrrelevant(d))) + plan.ChangedEquipmentVirtualTags.Any(d => !VtagDeltaIsNodeIrrelevant(d)) || + // #977 U-2: a scripted alarm's node-shaping fields (Name / AlarmType / Severity, and its EquipmentId) changed + // on a condition that exists before AND after — the node keeps its old type/name/severity otherwise + // (MaterialiseAlarmCondition is idempotent on an existing id). Enabled flips are adds/removes, below. + plan.ChangedEquipmentScriptedAlarms.Any(d => !ScriptedAlarmDeltaIsSurgical(d)) || + // #977 U-3: a Line moved to another Area (or any future non-name Area/Line field). EnsureFolder early-returns + // on an existing folder, so only a rebuild re-parents it; a name-only delta is served by RenamedFolders. + plan.ChangedUnsAreas.Any(d => !(d.Previous with { DisplayName = d.Current.DisplayName }).Equals(d.Current)) || + plan.ChangedUnsLines.Any(d => !(d.Previous with { DisplayName = d.Current.DisplayName }).Equals(d.Current))) { return AddressSpaceChangeKind.Rebuild; } @@ -101,16 +109,23 @@ public static class AddressSpaceChangeClassifier // Driver deltas (Added/Removed/ChangedDrivers) are node-INERT — they never touch the address-space // topology (they route to DriverHostActor's spawn plan in Runtime), so they are excluded from the // add/remove split below and leave a driver-only plan classified AttributeOnly. + // #977: added Areas/Lines are materialised by the always-full MaterialiseHierarchy pass; a scripted alarm that + // becomes enabled (or whose rich row appears) is an add, one that becomes disabled (or loses its rich row) a remove; + // removed Areas/Lines and orphaned VirtualTag sub-folders are torn down in place by ApplyPureRemove. var hasAdds = plan.AddedEquipment.Count + plan.AddedAlarms.Count + plan.AddedEquipmentVirtualTags.Count + plan.AddedRawContainers.Count + plan.AddedRawTags.Count + - plan.AddedUnsReferenceVariables.Count > 0; + plan.AddedUnsReferenceVariables.Count + + plan.AddedUnsAreas.Count + plan.AddedUnsLines.Count + + plan.ScriptedConditionAdds().Count > 0; var hasRemoves = plan.RemovedEquipment.Count + plan.RemovedAlarms.Count + plan.RemovedEquipmentVirtualTags.Count + plan.RemovedRawContainers.Count + plan.RemovedRawTags.Count + - plan.RemovedUnsReferenceVariables.Count > 0; + plan.RemovedUnsReferenceVariables.Count + + plan.RemovedUnsAreas.Count + plan.RemovedUnsLines.Count + + plan.ScriptedConditionRemoves().Count + plan.RemovedVirtualTagFolders.Count > 0; // 3 — additions AND removals. if (hasAdds && hasRemoves) return AddressSpaceChangeKind.AddRemoveMix; @@ -142,6 +157,27 @@ public static class AddressSpaceChangeClassifier Enabled = d.Current.Enabled, }).Equals(d.Current); + // #977 U-2: a scripted alarm's condition node is derived from {ScriptedAlarmId, EquipmentId, Name, AlarmType, Severity} + // and exists only while Enabled. So a delta is node-irrelevant when the alarm is disabled on EITHER side (no node before + // ⇒ it is an add; no node after ⇒ a remove — both handled surgically via AddressSpacePlan.ScriptedConditionAdds/Removes), + // or when only the engine-side fields moved (predicate / template / dependencies / historize / retain), which + // ScriptedAlarmHostActor adopts from its own apply. Any other difference — including a FUTURE field — is + // default-closed to a rebuild via the with-equality whitelist. + /// Whether a changed rich scripted-alarm plan can be applied without a full rebuild. + /// The rich scripted-alarm delta. + /// when the node is unaffected, or the change is a pure enable/disable flip. + internal static bool ScriptedAlarmDeltaIsSurgical(AddressSpacePlan.EquipmentScriptedAlarmDelta d) => + !d.Previous.Enabled || !d.Current.Enabled || + (d.Previous with + { + MessageTemplate = d.Current.MessageTemplate, + PredicateScriptId = d.Current.PredicateScriptId, + PredicateSource = d.Current.PredicateSource, + DependencyRefs = d.Current.DependencyRefs, + HistorizeToAveva = d.Current.HistorizeToAveva, + Retain = d.Current.Retain, + }).Equals(d.Current); + // v3 surgical raw-tag eligibility: a NON-alarm raw tag whose only differences are the in-place-updatable // attributes (Writable / IsHistorized / HistorianTagname / HistorianReadOnly / DataType / IsArray / ArrayLength / ArrayWritable) // and/or its ReferencingEquipmentPaths. ArrayWritable only feeds the node's writability — the diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpacePlan.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpacePlan.cs index 466a4a374..70a452dc4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpacePlan.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpacePlan.cs @@ -96,6 +96,83 @@ public sealed record AddressSpacePlan( /// public IReadOnlyList ChangedUnsReferenceVariables { get; init; } = Array.Empty(); + /// + /// Gitea #977 (U-3) — the UNS Area / Line folders themselves, keyed by their stable ids. Before these sets the + /// planner looked at Areas and Lines only through , so an added or removed Area/Line + /// and — worse — a Line RE-PARENTED to another Area () never reached a + /// plan: the Line folder stayed under its old Area until some unrelated rebuild, and with ACLs on, every node under + /// it was denied because the live folder chain no longer matched the generation's. A changed record whose only + /// difference is the display name is still served in place through ; any other + /// difference (a re-parent) is a full rebuild (). Init-only, default empty. + /// + public IReadOnlyList AddedUnsAreas { get; init; } = Array.Empty(); + /// + public IReadOnlyList RemovedUnsAreas { get; init; } = Array.Empty(); + /// + public IReadOnlyList ChangedUnsAreas { get; init; } = Array.Empty(); + /// + public IReadOnlyList AddedUnsLines { get; init; } = Array.Empty(); + /// + public IReadOnlyList RemovedUnsLines { get; init; } = Array.Empty(); + /// + public IReadOnlyList ChangedUnsLines { get; init; } = Array.Empty(); + + /// + /// Gitea #977 (U-2) — the RICH scripted-alarm host plans (), + /// keyed by . The thin / + /// sets diff only id / equipment / predicate-script id / template, but the four fields that + /// decide whether and how a scripted condition NODE exists — Enabled, AlarmType, Severity, + /// Name — live only on the rich record. Without these sets enabling a disabled alarm produced an empty plan + /// (the condition was never materialised, every engine write a silent no-op), disabling one left the node + /// browsable, and a type/name edit kept the old node indefinitely. Init-only, default empty. + /// + public IReadOnlyList AddedEquipmentScriptedAlarms { get; init; } = Array.Empty(); + /// + public IReadOnlyList RemovedEquipmentScriptedAlarms { get; init; } = Array.Empty(); + /// + public IReadOnlyList ChangedEquipmentScriptedAlarms { get; init; } = Array.Empty(); + + /// + /// Gitea #977 (U-9) — VirtualTag FolderPath sub-folders ({EquipmentId}/{FolderPath}) the previous + /// composition used and the next one does not, on an equipment that SURVIVES (a removed equipment's subtree + /// removal takes its sub-folders with it). Without it, removing the last VirtualTag in a sub-folder removed the + /// variable in place and left the empty folder browsable until the next rebuild. Init-only, default empty. + /// + public IReadOnlyList RemovedVirtualTagFolders { get; init; } = Array.Empty(); + + /// + /// The scripted condition nodes this plan brings into existence BEYOND the thin : a rich + /// alarm row that appeared enabled (e.g. its predicate script only now arrived) and an alarm flipped from + /// disabled to enabled. Only meaningful on a non-rebuild apply (a rebuild materialises the whole composition). + /// + /// The rich alarm rows whose condition node must be materialised. + public IReadOnlyList ScriptedConditionAdds() + { + var list = new List(); + foreach (var a in AddedEquipmentScriptedAlarms) if (a.Enabled) list.Add(a); + foreach (var d in ChangedEquipmentScriptedAlarms) if (!d.Previous.Enabled && d.Current.Enabled) list.Add(d.Current); + return list; + } + + /// + /// The scripted condition nodes this plan takes away BEYOND the thin (which the applier + /// already tears down): an enabled alarm flipped to disabled, and an enabled rich row that vanished while its thin + /// row survived (its predicate script is gone). + /// + /// The previous rich alarm rows whose condition node must be removed. + public IReadOnlyList ScriptedConditionRemoves() + { + var list = new List(); + if (RemovedEquipmentScriptedAlarms.Count > 0) + { + var thinRemoved = new HashSet(RemovedAlarms.Select(a => a.ScriptedAlarmId), StringComparer.Ordinal); + foreach (var a in RemovedEquipmentScriptedAlarms) + if (a.Enabled && !thinRemoved.Contains(a.ScriptedAlarmId)) list.Add(a); + } + foreach (var d in ChangedEquipmentScriptedAlarms) if (d.Previous.Enabled && !d.Current.Enabled) list.Add(d.Previous); + return list; + } + /// Gets a value indicating whether the composition plan contains no changes. public bool IsEmpty => AddedEquipment.Count == 0 && RemovedEquipment.Count == 0 && ChangedEquipment.Count == 0 && @@ -105,12 +182,27 @@ public sealed record AddressSpacePlan( AddedRawContainers.Count == 0 && RemovedRawContainers.Count == 0 && ChangedRawContainers.Count == 0 && AddedRawTags.Count == 0 && RemovedRawTags.Count == 0 && ChangedRawTags.Count == 0 && AddedUnsReferenceVariables.Count == 0 && RemovedUnsReferenceVariables.Count == 0 && ChangedUnsReferenceVariables.Count == 0 && - RenamedFolders.Count == 0; + RenamedFolders.Count == 0 && + AddedUnsAreas.Count == 0 && RemovedUnsAreas.Count == 0 && ChangedUnsAreas.Count == 0 && + AddedUnsLines.Count == 0 && RemovedUnsLines.Count == 0 && ChangedUnsLines.Count == 0 && + AddedEquipmentScriptedAlarms.Count == 0 && RemovedEquipmentScriptedAlarms.Count == 0 && + ChangedEquipmentScriptedAlarms.Count == 0 && + RemovedVirtualTagFolders.Count == 0; public sealed record EquipmentDelta(EquipmentNode Previous, EquipmentNode Current); public sealed record DriverDelta(DriverInstancePlan Previous, DriverInstancePlan Current); public sealed record AlarmDelta(ScriptedAlarmPlan Previous, ScriptedAlarmPlan Current); public sealed record EquipmentVirtualTagDelta(EquipmentVirtualTagPlan Previous, EquipmentVirtualTagPlan Current); + /// A rich scripted-alarm plan present in both snapshots (same id) with ≥1 differing field. + public sealed record EquipmentScriptedAlarmDelta(EquipmentScriptedAlarmPlan Previous, EquipmentScriptedAlarmPlan Current); + /// A UNS Area present in both snapshots (same id) with ≥1 differing field. + public sealed record UnsAreaDelta(UnsAreaProjection Previous, UnsAreaProjection Current); + /// A UNS Line present in both snapshots (same id) with ≥1 differing field — a rename and/or a re-parent. + public sealed record UnsLineDelta(UnsLineProjection Previous, UnsLineProjection Current); + /// One VirtualTag FolderPath sub-folder of an equipment (node id {EquipmentId}/{FolderPath}). + /// The owning equipment folder id. + /// The VirtualTag FolderPath (non-empty). + public sealed record VirtualTagFolder(string EquipmentId, string FolderPath); /// A Raw container node present in both snapshots (same RawPath) with ≥1 differing field. public sealed record RawContainerDelta(RawContainerNode Previous, RawContainerNode Current); @@ -207,6 +299,25 @@ public static class AddressSpacePlanner .Concat(DiffRenames(previous.UnsLines, next.UnsLines, l => l.UnsLineId, l => l.DisplayName)) .ToList(); + // #977 U-3 — the Area/Line folders in full: added/removed folders and every field difference (a Line moved to + // another Area is a changed UnsAreaId). The classifier lets a rename-only delta through surgically (served by + // RenamedFolders above) and rebuilds on anything else. + var (addedAreas, removedAreas, changedAreas) = DiffById( + previous.UnsAreas, next.UnsAreas, a => a.UnsAreaId, + (a, b) => new AddressSpacePlan.UnsAreaDelta(a, b)); + var (addedLines, removedLines, changedLines) = DiffById( + previous.UnsLines, next.UnsLines, l => l.UnsLineId, + (a, b) => new AddressSpacePlan.UnsLineDelta(a, b)); + + // #977 U-2 — the rich scripted-alarm rows: Enabled / AlarmType / Severity / Name decide the condition node and + // live only here. EquipmentScriptedAlarmPlan already has element-wise value equality. + var (addedRichAlarms, removedRichAlarms, changedRichAlarms) = DiffById( + previous.EquipmentScriptedAlarms, next.EquipmentScriptedAlarms, a => a.ScriptedAlarmId, + (a, b) => new AddressSpacePlan.EquipmentScriptedAlarmDelta(a, b)); + + // #977 U-9 — VirtualTag sub-folders the next composition no longer uses, on equipment that survives. + var removedVtagFolders = DiffVirtualTagFolders(previous, next); + return new AddressSpacePlan( addedEq, removedEq, changedEq, addedDrv, removedDrv, changedDrv, @@ -225,9 +336,41 @@ public static class AddressSpacePlanner RemovedUnsReferenceVariables = removedUnsRefs, ChangedUnsReferenceVariables = changedUnsRefs, RenamedFolders = renamedFolders, + AddedUnsAreas = addedAreas, + RemovedUnsAreas = removedAreas, + ChangedUnsAreas = changedAreas, + AddedUnsLines = addedLines, + RemovedUnsLines = removedLines, + ChangedUnsLines = changedLines, + AddedEquipmentScriptedAlarms = addedRichAlarms, + RemovedEquipmentScriptedAlarms = removedRichAlarms, + ChangedEquipmentScriptedAlarms = changedRichAlarms, + RemovedVirtualTagFolders = removedVtagFolders, }; } + /// The (EquipmentId, FolderPath) sub-folders some previous VirtualTag used that no next VirtualTag uses, + /// restricted to equipment present in (a removed equipment's subtree removal subsumes them). + /// Ordinal-sorted for determinism. + private static List DiffVirtualTagFolders( + AddressSpaceComposition previous, AddressSpaceComposition next) + { + static HashSet Folders(AddressSpaceComposition c) => + c.EquipmentVirtualTags + .Where(v => !string.IsNullOrWhiteSpace(v.FolderPath)) + .Select(v => new AddressSpacePlan.VirtualTagFolder(v.EquipmentId, v.FolderPath)) + .ToHashSet(); + + var survivors = new HashSet(next.EquipmentNodes.Select(e => e.EquipmentId), StringComparer.Ordinal); + var removed = Folders(previous); + removed.ExceptWith(Folders(next)); + return removed + .Where(f => survivors.Contains(f.EquipmentId)) + .OrderBy(f => f.EquipmentId, StringComparer.Ordinal) + .ThenBy(f => f.FolderPath, StringComparer.Ordinal) + .ToList(); + } + /// /// Emit a for every folder present in /// BOTH snapshots (matched by stable ) whose 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 54b1f747e..5a036ccc7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -1495,13 +1495,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _log.Warning("DriverHost {Node}: found orphan Applying row for deployment {Id}; replaying", _localNode, latest.DeploymentId); if (revision is not null) BeginDirectApply(new DeploymentId(latest.DeploymentId), revision.Value, CorrelationId.NewId()); - else BecomeSteady(); + else RestoreLastApplied(db, latest.DeploymentId, "its orphan Applying row names a deployment that no longer exists"); break; case NodeDeploymentStatus.Failed: default: - _log.Info("DriverHost {Node}: prior deployment {Id} failed; entering Steady at last known rev", - _localNode, latest.DeploymentId); - BecomeSteady(); + RestoreLastApplied(db, latest.DeploymentId, $"the newest deployment on this node ended {latest.Status}"); break; } } @@ -1517,6 +1515,53 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn } } + /// + /// Gitea #977 (R-1). The newest node row is not Applied (a failed deploy, or an orphan Applying row whose deployment + /// is gone) — but a failed apply never stopped this node serving the revision BEFORE it ("Staying on revision A and + /// continuing to serve it"). Booting straight to an empty Steady here used to serve nothing after any restart that + /// followed a failed deploy, logged at Info, with nothing to heal it. Restore the newest APPLIED deployment for this + /// node instead; with none, fall back to the node-local cache, and only then to Steady with no revision. + /// + /// The open bootstrap context. + /// The newest (non-Applied) row's deployment, for the log. + /// Why the newest row cannot be restored, for the log. + private void RestoreLastApplied(OtOpcUaConfigDbContext db, Guid newestId, string why) + { + var lastApplied = db.NodeDeploymentStates + .AsNoTracking() + .Where(s => s.NodeId == _localNode.Value && s.Status == NodeDeploymentStatus.Applied) + .OrderByDescending(s => s.StartedAtUtc) + .Select(s => s.DeploymentId) + .Take(8) + .ToList() + // The newest Applied row whose deployment row (and so its revision) still exists. + .Select(id => (Id: id, Deployment: db.Deployments.AsNoTracking() + .Where(d => d.DeploymentId == id) + .Select(d => new { d.RevisionHash }) + .FirstOrDefault())) + .FirstOrDefault(x => x.Deployment is not null && !string.IsNullOrWhiteSpace(x.Deployment.RevisionHash)); + + if (lastApplied.Deployment is { } applied) + { + var revision = RevisionHash.Parse(applied.RevisionHash); + _currentRevision = revision; + _log.Warning( + "DriverHost {Node}: {Why} (deployment {Newest}); restoring the last APPLIED deployment {Id} (rev {Rev}) — the revision it was serving before", + _localNode, why, newestId, lastApplied.Id, revision); + BecomeSteady(); + RestoreApplied(new DeploymentId(lastApplied.Id), revision); + return; + } + + _log.Warning( + "DriverHost {Node}: {Why} (deployment {Newest}) and no earlier deployment was ever applied here; trying the node-local cache", + _localNode, why, newestId); + if (TryBootFromCache(configDbReachable: true)) return; + + _log.Warning("DriverHost {Node}: nothing to restore; entering Steady with no revision until the next dispatch", _localNode); + BecomeSteady(); + } + /// /// Per-cluster mesh Phase 3 boot for FetchAndCache mode. Restores served state from the /// LocalDb pointer without any central-SQL read. @@ -1617,7 +1662,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// would have been without a cache at all. /// /// - private bool TryBootFromCache() + /// True when the ConfigDb answered (Gitea #977 R-1: it simply holds no applied + /// deployment for this node) — the node is then not "running from cache" in the outage sense. + private bool TryBootFromCache(bool configDbReachable = false) { if (_deploymentArtifactCache is null) return false; @@ -1656,6 +1703,16 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _currentRevisionUnconfirmed = true; BecomeSteady(); + if (configDbReachable) + { + // #977 R-1: the ConfigDb answered but holds no Applied deployment for this node — not an outage. + _log.Warning( + "DriverHost {Node}: booted deployment {Id} (rev {Rev}) cached at {CachedAtUtc:o} from the node-local " + + "cache, because the ConfigDb records no applied deployment for this node; a re-dispatch re-applies it.", + _localNode, deploymentId, revision, cached.AppliedAtUtc); + return true; + } + _isRunningFromCache = true; _log.Warning( "DriverHost {Node}: RUNNING FROM CACHE — central ConfigDb is unreachable, so this node " + @@ -3269,7 +3326,10 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn return; } - _currentRevision = msg.Revision; + // #977 R-15: _currentRevision now advances BELOW, after the last step that can throw (subscription push, + // cache write, catalog completion). Advancing it here let a throw in those steps leave the new revision + // current with no address-space rebuild sent for it, and a re-dispatch of the same revision then short- + // circuited to a CLEAN Applied ack over an address space that never received it. // lmxopcua#868 review M1: the own row stays APPLYING (written by BeginDirectApply) until the // address-space outcome is known — AwaitAddressSpaceOutcomeThenAck / ReleasePendingAck write the // final Applied (clean, or with the degraded reason). Writing Applied/null here, up to ~105 s before @@ -3306,6 +3366,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn && _catalogCoordinator is not null && !_catalogCoordinator.Complete(_catalogAttempt, topologySucceeded: true) && _catalogAttempt.Expected; + // Advanced only now (R-15) — and before the ack hold below, whose no-publish-actor path settles this + // revision's confirmed/unconfirmed flag immediately and must find it current. + _currentRevision = msg.Revision; AwaitAddressSpaceOutcomeThenAck(msg.DeploymentId, msg.Revision, msg.Correlation, catalogFailed); _opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace( msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true, CatalogAttempt: _catalogAttempt)); @@ -3327,6 +3390,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // A throw after the Applied ack was put on hold — the Failed ack below is this apply's one // answer, so the held Applied must never follow it when the address-space outcome lands. DropPendingAck(msg.Correlation); + // #977 R-15: whatever revision is current now, a throw part-way through the apply means the drivers and the + // routing maps (ApplyDesiredSubscriptions clears them before repopulating) may already be the NEW revision's, + // partially. Nothing about the current revision is known-served any more, so a re-dispatch of EITHER revision + // must re-apply rather than short-circuit to a clean Applied ack. + _currentRevisionUnconfirmed = true; UpsertNodeDeploymentState(msg.DeploymentId, NodeDeploymentStatus.Failed, ex.Message); SendAck(msg.DeploymentId, ApplyAckOutcome.Failed, ex.Message, msg.Correlation); OtOpcUaTelemetry.DeploymentApplied.Add(1, new KeyValuePair("outcome", "reject")); 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 850d97126..6365f4a32 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -193,6 +193,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers internal Func? ParseAuthority { get; init; } } + /// Test-only (registered only when are supplied): throws from the handler so a test + /// can drive a supervision RESTART of this actor (Gitea #977 R-20). + internal sealed record CrashForTests; + /// The default bound on : distinct (realm, id) keys held while a plan is in flight. internal const int DefaultDeferredWriteCapacity = 250_000; @@ -307,6 +311,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// that pass is itself clean. /// private bool _lastAppliedDegraded; + /// + /// 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 + /// address space. Diffing against the seed would make every node look added — an idempotent no-op that never + /// removes what the deploy dropped and skips every in-place attribute edit — and report clean. While set, the + /// next apply is a forced full rebuild (even of an otherwise empty plan); cleared once a rebuild succeeds. + /// Persisting across the restart was the alternative; a rebuild needs no state to + /// survive the crash that caused it, which is why it was chosen. + /// + private bool _baselineUnknown; private DbHealthProbeActor.DbHealthStatus? _lastDbHealth; private RedundancyStateChanged? _lastSnapshot; private (bool Ok, DateTime At)? _probeAboutMe; @@ -623,6 +637,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers RecomputeServiceLevel(); }); Receive(_ => RecomputeServiceLevel()); + if (hooks is not null) + Receive(_ => throw new InvalidOperationException("simulated handler fault (test)")); } /// @@ -643,6 +659,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers base.PreRestart(reason, message); } + /// Gitea #977 (R-20): the new instance does not know what the sink serves — see . + /// + protected override void PostRestart(Exception reason) + { + _baselineUnknown = true; + base.PostRestart(reason); + } + /// protected override void PostStop() { @@ -1551,7 +1575,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers var composition = ready.Composition; var plan = ready.Plan; - if (plan.IsEmpty) + if (plan.IsEmpty && !_baselineUnknown) { if (_lastAppliedDegraded) { @@ -1580,7 +1604,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers return (false, null); } - var outcome = _applier!.Apply(plan); + // #977 R-20: after a supervision restart _lastApplied is the empty seed while the node manager still serves + // the previous incarnation's address space — a diff against it would add everything idempotently, never + // remove what this deploy dropped, and skip every in-place edit. The first apply of a restarted instance + // therefore rebuilds, whatever its plan says. + var forceRebuild = _baselineUnknown; + if (forceRebuild) + _log.Warning( + "OpcUaPublish: first apply after a restart of this actor (correlation={Correlation}) — the served address space is not known to match any composition, so it is REBUILT rather than diffed", + msg.Correlation); + var outcome = _applier!.Apply(plan, forceRebuild); rebuilt = outcome.RebuildCalled; // Sum swallowed per-node materialise failures across every pass together with Apply's own @@ -1592,7 +1625,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers // exist to bound — and every node the delta passes add needs its ancestor folders to already // exist, so narrowing it would mean re-deriving each add's ancestor closure (strictly more work). failedNodes += _applier.MaterialiseHierarchy(composition); - failedNodes += MaterialiseNodes(plan, composition, fullComposition: outcome.RebuildCalled); + // #977 R-4: while the last applied composition is known DEGRADED (a rebuild advanced it with failures), a + // non-rebuild apply re-ensures the WHOLE composition, not just this plan's delta. The node that rebuild failed + // 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; + failedNodes += MaterialiseNodes(plan, composition, fullComposition: outcome.RebuildCalled || repairingDegraded); + if (outcome.RebuildCalled) _baselineUnknown = outcome.RebuildFailed; // 2026-08-15 surgical-deploys review C1 — record the composition as applied ONLY when the apply was // clean, or when a rebuild ran. Two reasons this sits HERE (after the materialise passes) rather @@ -1703,12 +1742,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// UnsReferenceDelta by REMOVING the previous node and leaving the recreate to this pass, so /// the subset must carry the current side of every changed reference as well as the added ones /// — otherwise a re-pointed, renamed, or backing-edited UNS node is removed and never comes back. - /// Accepted narrowing. The plan diffs the THIN ScriptedAlarmPlans projection, so - /// the added-alarm subset is the rich EquipmentScriptedAlarms rows whose id the plan reports as - /// added. An alarm already present in both compositions whose predicate SCRIPT row only now arrived - /// (making it materialisable for the first time) is not in that set — but neither is it in any diff - /// set at all, so on its own it already produced an empty plan and materialised nothing. The delta - /// path extends that pre-existing blindness to the case where it rides along with another change. + /// Scripted alarms. The added-alarm subset is the rich EquipmentScriptedAlarms rows whose + /// id the thin diff reports as added, plus (Gitea #977 U-2) every condition the rich diff brings into existence: + /// an alarm enabled in place, or one whose predicate script only now arrived. Before #977 the plan diffed only + /// the thin projection, so both were invisible. /// /// The plan just applied — the source of the delta subsets. /// The full composition, always passed as the passes' lookup context. @@ -1798,10 +1835,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers private static IReadOnlyList DeltaScriptedAlarms( AddressSpacePlan plan, AddressSpaceComposition composition) { - if (plan.AddedAlarms.Count == 0 || composition.EquipmentScriptedAlarms.Count == 0) + // #977 U-2: plus the conditions the RICH diff brings into existence — an alarm enabled in place, or one whose rich + // row only now appeared (its predicate script arrived) — which the thin AddedAlarms never named. + var richAdds = plan.ScriptedConditionAdds(); + if ((plan.AddedAlarms.Count == 0 && richAdds.Count == 0) || composition.EquipmentScriptedAlarms.Count == 0) return Array.Empty(); var addedIds = new HashSet(plan.AddedAlarms.Select(a => a.ScriptedAlarmId), StringComparer.Ordinal); + addedIds.UnionWith(richAdds.Select(a => a.ScriptedAlarmId)); return composition.EquipmentScriptedAlarms.Where(a => addedIds.Contains(a.ScriptedAlarmId)).ToList(); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorSupersedeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorSupersedeTests.cs new file mode 100644 index 000000000..20d925977 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/ConfigPublishCoordinatorSupersedeTests.cs @@ -0,0 +1,110 @@ +using Akka.Actor; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; + +/// +/// Gitea #977 (H-4) — a dispatch of deployment B while a DIFFERENT deployment A is still in flight (two composes +/// overlapping across an AdminOps singleton hand-over) used to overwrite the coordinator's current deployment and +/// replace its deadline timer without ever closing A. A's row stayed AwaitingApplyAcks, its deadline never fired, +/// and every later StartDeployment was refused as AnotherDeploymentInFlight until a coordinator restart. +/// +public sealed class ConfigPublishCoordinatorSupersedeTests : ControlPlaneActorTestBase +{ + private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64)); + private static readonly RevisionHash RevB = RevisionHash.Parse(new string('b', 64)); + private const string Node = "site-a-1:4053"; + + [Fact] + public void Dispatching_a_new_deployment_closes_the_one_still_in_flight() + { + var dbFactory = NewInMemoryDbFactory(); + SeedNode(dbFactory); + var a = SeedDispatching(dbFactory, RevA); + var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(dbFactory, TimeSpan.FromMinutes(5))); + + actor.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId())); + AwaitStatus(dbFactory, a, DeploymentStatus.AwaitingApplyAcks); + // Committed only now — the overlapping second compose — so the coordinator's own recovery read never sees it. + var b = SeedDispatching(dbFactory, RevB); + + actor.Tell(new DispatchDeployment(b, RevB, CorrelationId.NewId())); + + AwaitStatus(dbFactory, a, DeploymentStatus.TimedOut); + using (var db = dbFactory.CreateDbContext()) + { + db.Deployments.Single(d => d.DeploymentId == a.Value).FailureReason!.ShouldContain("Superseded by deployment"); + db.Deployments.Single(d => d.DeploymentId == b.Value).Status.ShouldBe(DeploymentStatus.AwaitingApplyAcks); + } + + // The successor is fully tracked: its ack seals it. + actor.Tell(new ApplyAck(b, NodeId.Parse(Node), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + AwaitStatus(dbFactory, b, DeploymentStatus.Sealed); + // ...and a late ack for the superseded deployment changes nothing. + actor.Tell(new ApplyAck(a, NodeId.Parse(Node), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken); + using var after = dbFactory.CreateDbContext(); + after.Deployments.Single(d => d.DeploymentId == a.Value).Status.ShouldBe(DeploymentStatus.TimedOut); + } + + [Fact] + public void A_duplicate_dispatch_of_the_in_flight_deployment_does_not_close_it() + { + // Positive control: the same id again is the existing duplicate guard, not a supersede. + var dbFactory = NewInMemoryDbFactory(); + SeedNode(dbFactory); + var a = SeedDispatching(dbFactory, RevA); + var actor = Sys.ActorOf(ConfigPublishCoordinator.Props(dbFactory, TimeSpan.FromMinutes(5))); + + actor.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId())); + AwaitStatus(dbFactory, a, DeploymentStatus.AwaitingApplyAcks); + actor.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId())); + actor.Tell(new ApplyAck(a, NodeId.Parse(Node), ApplyAckOutcome.Applied, null, CorrelationId.NewId())); + + AwaitStatus(dbFactory, a, DeploymentStatus.Sealed); + } + + private void AwaitStatus(IDbContextFactory dbFactory, DeploymentId id, DeploymentStatus expected) => + AwaitAssert(() => + { + using var db = dbFactory.CreateDbContext(); + db.Deployments.Single(d => d.DeploymentId == id.Value).Status.ShouldBe(expected); + }, duration: TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + + private static void SeedNode(IDbContextFactory dbFactory) + { + using var db = dbFactory.CreateDbContext(); + db.ServerClusters.Add(new ServerCluster + { + ClusterId = "SITE-A", Name = "Site A", Enterprise = "zb", Site = "site-a", NodeCount = 1, + RedundancyMode = RedundancyMode.None, CreatedBy = "test", + }); + db.ClusterNodes.Add(new ClusterNode + { + NodeId = Node, ClusterId = "SITE-A", Host = "site-a-1", ApplicationUri = $"urn:OtOpcUa:{Node}", + Enabled = true, CreatedBy = "test", + }); + db.SaveChanges(); + } + + private static DeploymentId SeedDispatching(IDbContextFactory dbFactory, RevisionHash rev) + { + var id = DeploymentId.NewId(); + using var db = dbFactory.CreateDbContext(); + db.Deployments.Add(new Deployment + { + DeploymentId = id.Value, RevisionHash = rev.Value, Status = DeploymentStatus.Dispatching, CreatedBy = "test", + }); + db.SaveChanges(); + return id; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpaceApplierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpaceApplierTests.cs index 2a60cf29b..f2a662e3d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpaceApplierTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpaceApplierTests.cs @@ -8,9 +8,184 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; public sealed class AddressSpaceApplierTests { + // ----- Gitea #977 (U-2 / U-3 / U-9) ----- + private static AddressSpaceComposition Uns( + IReadOnlyList? lines = null, + IReadOnlyList? alarms = null, + IReadOnlyList? vtags = null, + IReadOnlyList? areas = null) => + new( + areas ?? new[] { new UnsAreaProjection("area-1", "Area 1"), new UnsAreaProjection("area-2", "Area 2") }, + lines ?? new[] { new UnsLineProjection("line-1", "area-1", "Line 1") }, + new[] { new EquipmentNode("eq-1", "Eq 1", "line-1") }, + Array.Empty(), + (alarms ?? Array.Empty()) + .Select(a => new ScriptedAlarmPlan(a.ScriptedAlarmId, a.EquipmentId, a.PredicateScriptId, a.MessageTemplate)) + .ToArray()) + { + EquipmentScriptedAlarms = alarms ?? Array.Empty(), + EquipmentVirtualTags = vtags ?? Array.Empty(), + }; + private static EquipmentScriptedAlarmPlan Alarm(bool enabled = true, string alarmType = "AlarmCondition", int severity = 500, + string name = "High", bool retain = true) => + new("al-1", "eq-1", name, alarmType, severity, "msg", "s-1", "return false;", Array.Empty(), + HistorizeToAveva: false, Retain: retain, Enabled: enabled); + private static EquipmentVirtualTagPlan Vtag(string id, string folderPath) => + new(id, "eq-1", folderPath, Name: id, DataType: "Double", Expression: "1", DependencyRefs: Array.Empty()); + + [Fact] + public void Enabling_a_disabled_scripted_alarm_materialises_its_condition_without_a_rebuild() + { + var plan = AddressSpacePlanner.Compute(Uns(alarms: new[] { Alarm(enabled: false) }), Uns(alarms: new[] { Alarm(enabled: true) })); + + plan.IsEmpty.ShouldBeFalse("an Enabled-only flip used to diff to an EMPTY plan — the condition never appeared"); + AddressSpaceChangeClassifier.Classify(plan).ShouldBe(AddressSpaceChangeKind.PureAdd); + plan.ScriptedConditionAdds().Single().ScriptedAlarmId.ShouldBe("al-1"); + + var sink = new RecordingSink(); + var applier = new AddressSpaceApplier(sink, NullLogger.Instance); + applier.Apply(plan).RebuildCalled.ShouldBeFalse(); + applier.ComputeAddAnnouncements(plan).ShouldContain("eq-1"); + } + + [Fact] + public void Disabling_a_scripted_alarm_removes_its_condition_in_place() + { + var plan = AddressSpacePlanner.Compute(Uns(alarms: new[] { Alarm(enabled: true) }), Uns(alarms: new[] { Alarm(enabled: false) })); + + AddressSpaceChangeClassifier.Classify(plan).ShouldBe(AddressSpaceChangeKind.PureRemove); + var sink = new RecordingSink(); + var outcome = new AddressSpaceApplier(sink, NullLogger.Instance).Apply(plan); + + outcome.RebuildCalled.ShouldBeFalse(); + sink.AlarmWrites.ShouldContain(w => w.NodeId == "al-1"); // terminal state first + sink.RemoveCalls.ShouldContain(("alarm", "al-1", AddressSpaceRealm.Uns)); + } + + [Theory] + [InlineData("type")] + [InlineData("severity")] + [InlineData("name")] + public void A_node_shaping_edit_on_an_enabled_scripted_alarm_rebuilds(string field) + { + var next = field switch + { + "type" => Alarm(alarmType: "LimitAlarm"), + "severity" => Alarm(severity: 900), + _ => Alarm(name: "Very high"), + }; + var plan = AddressSpacePlanner.Compute(Uns(alarms: new[] { Alarm() }), Uns(alarms: new[] { next })); + + AddressSpaceChangeClassifier.Classify(plan).ShouldBe(AddressSpaceChangeKind.Rebuild); + } + + [Fact] + public void An_engine_only_scripted_alarm_edit_is_node_inert() + { + // Positive control for the rebuild theory above: a Retain flip changes the record but not the node. + var plan = AddressSpacePlanner.Compute(Uns(alarms: new[] { Alarm(retain: true) }), Uns(alarms: new[] { Alarm(retain: false) })); + + plan.IsEmpty.ShouldBeFalse(); + AddressSpaceChangeClassifier.Classify(plan).ShouldBe(AddressSpaceChangeKind.AttributeOnly); + } + + [Fact] + public void A_line_moved_to_another_area_rebuilds() + { + var plan = AddressSpacePlanner.Compute( + Uns(lines: new[] { new UnsLineProjection("line-1", "area-1", "Line 1") }), + Uns(lines: new[] { new UnsLineProjection("line-1", "area-2", "Line 1") })); + + plan.IsEmpty.ShouldBeFalse("a re-parented Line used to diff to an EMPTY plan"); + plan.ChangedUnsLines.Single().Current.UnsAreaId.ShouldBe("area-2"); + AddressSpaceChangeClassifier.Classify(plan).ShouldBe(AddressSpaceChangeKind.Rebuild); + + var sink = new RecordingSink(); + new AddressSpaceApplier(sink, NullLogger.Instance).Apply(plan).RebuildCalled.ShouldBeTrue(); + } + + [Fact] + public void A_line_rename_alone_stays_surgical() + { + // Positive control: the whitelist must still let the DisplayName-only delta through in place. + var plan = AddressSpacePlanner.Compute( + Uns(lines: new[] { new UnsLineProjection("line-1", "area-1", "Line 1") }), + Uns(lines: new[] { new UnsLineProjection("line-1", "area-1", "Line One") })); + + AddressSpaceChangeClassifier.Classify(plan).ShouldBe(AddressSpaceChangeKind.AttributeOnly); + var sink = new RecordingSink(); + new AddressSpaceApplier(sink, NullLogger.Instance).Apply(plan).RebuildCalled.ShouldBeFalse(); + sink.FolderRenameCalls.ShouldContain(("line-1", "Line One")); + } + + [Fact] + public void Removed_and_added_areas_and_lines_reach_the_plan_and_removals_are_in_place() + { + var withLine2 = Uns(lines: new[] + { + new UnsLineProjection("line-1", "area-1", "Line 1"), new UnsLineProjection("line-2", "area-2", "Line 2"), + }); + var plain = Uns(); + var noArea2 = Uns(areas: new[] { new UnsAreaProjection("area-1", "Area 1") }); + + var add = AddressSpacePlanner.Compute(plain, withLine2); + AddressSpaceChangeClassifier.Classify(add).ShouldBe(AddressSpaceChangeKind.PureAdd); + new AddressSpaceApplier(new RecordingSink(), NullLogger.Instance) + .ComputeAddAnnouncements(add).ShouldContain("area-2"); + + var remove = AddressSpacePlanner.Compute(withLine2, noArea2); + AddressSpaceChangeClassifier.Classify(remove).ShouldBe(AddressSpaceChangeKind.PureRemove); + var sink = new RecordingSink(); + new AddressSpaceApplier(sink, NullLogger.Instance).Apply(remove).RebuildCalled.ShouldBeFalse(); + sink.RemoveCalls.Select(c => c.NodeId).ShouldBe(new[] { "line-2", "area-2" }); // child before parent + } + + [Fact] + public void Removing_the_last_virtual_tag_in_a_sub_folder_removes_the_folder_without_a_rebuild() + { + var plan = AddressSpacePlanner.Compute( + Uns(vtags: new[] { Vtag("vt-1", "calc"), Vtag("vt-2", "") }), + Uns(vtags: new[] { Vtag("vt-2", "") })); + + plan.RemovedVirtualTagFolders.ShouldBe(new[] { new AddressSpacePlan.VirtualTagFolder("eq-1", "calc") }); + var sink = new RecordingSink(); + var outcome = new AddressSpaceApplier(sink, NullLogger.Instance).Apply(plan); + + outcome.RebuildCalled.ShouldBeFalse(); + sink.RemoveCalls.ShouldBe(new[] + { + ("var", "eq-1/calc/vt-1", AddressSpaceRealm.Uns), + ("equipment", "eq-1/calc", AddressSpaceRealm.Uns), + }); + } + + [Fact] + public void A_sub_folder_still_used_by_another_virtual_tag_is_kept() + { + // Positive control for the folder removal above. + var plan = AddressSpacePlanner.Compute( + Uns(vtags: new[] { Vtag("vt-1", "calc"), Vtag("vt-2", "calc") }), + Uns(vtags: new[] { Vtag("vt-2", "calc") })); + + plan.RemovedVirtualTagFolders.ShouldBeEmpty(); + var sink = new RecordingSink(); + new AddressSpaceApplier(sink, NullLogger.Instance).Apply(plan); + sink.RemoveCalls.ShouldBe(new[] { ("var", "eq-1/calc/vt-1", AddressSpaceRealm.Uns) }); + } + + [Fact] + public void A_forced_rebuild_rebuilds_even_an_empty_plan() + { + var sink = new RecordingSink(); + var applier = new AddressSpaceApplier(sink, NullLogger.Instance); + + applier.Apply(EmptyPlan).RebuildCalled.ShouldBeFalse(); + applier.Apply(EmptyPlan, forceRebuild: true).RebuildCalled.ShouldBeTrue(); + sink.RebuildCalls.ShouldBe(1); + } /// R2-07 T2 — added Equipment VirtualTags in an otherwise-empty plan are a PureAdd: the applier /// SKIPS the rebuild (parity with the equipment-tag path). (Supersedes the pre-R2-07 "added vtags ⇒ diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpacePlannerFieldCoverageTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpacePlannerFieldCoverageTests.cs new file mode 100644 index 000000000..36e0b9eb2 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpacePlannerFieldCoverageTests.cs @@ -0,0 +1,190 @@ +using System.Collections; +using System.Reflection; +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; + +/// +/// Gitea #977 (U-2 / U-3 — "omitting a field silently reopens staleness"). The planner's job is to notice EVERY +/// difference between two compositions; anything it does not see produces an EMPTY plan, and an empty plan returns +/// before a single sink call. Scripted-alarm Enabled/AlarmType/Severity/Name and a UNS +/// Line's parent Area were exactly that: fields on the composition no diff ever looked at. +/// This test is the guard against the next one. It REFLECTS over every list on +/// and every property of each element record, builds two compositions +/// differing in exactly that one property (or in the presence of one element), and requires a non-empty plan. A +/// field added to a composition record — or a new list added to the composition — that the planner does not diff +/// fails here by name, instead of shipping as a deploy that changes nothing. +/// +public sealed class AddressSpacePlannerFieldCoverageTests +{ + /// Composition lists deliberately outside the diff, each with the reason. Keep this list short. + private static readonly IReadOnlyDictionary ExemptLists = new Dictionary(StringComparer.Ordinal) + { + // The retired v2 equipment-namespace tag path: structurally empty in v3 (both the composer and the artifact + // decode emit an empty array), materialised by nothing. Device values reach equipment as UnsReferenceVariables. + [nameof(AddressSpaceComposition.EquipmentTags)] = "retired v2 equipment-tag path, always empty in v3", + }; + + public static TheoryData CompositionLists() + { + var data = new TheoryData(); + foreach (var p in ListProperties()) data.Add(p.Name); + return data; + } + + public static TheoryData CompositionFields() + { + var data = new TheoryData(); + foreach (var list in ListProperties()) + { + if (ExemptLists.ContainsKey(list.Name)) continue; + foreach (var field in RecordFields(ElementType(list))) data.Add(list.Name, field.Name!); + } + return data; + } + + [Theory] + [MemberData(nameof(CompositionLists))] + public void Adding_or_removing_one_element_of_every_composition_list_is_seen_by_the_planner(string listName) + { + if (ExemptLists.ContainsKey(listName)) return; + var list = ListProperties().Single(p => p.Name == listName); + var element = Sample(ElementType(list)); + + var without = Composition(); + var with = Composition((list, element)); + + AddressSpacePlanner.Compute(without, with).IsEmpty.ShouldBeFalse($"adding one {listName} element"); + AddressSpacePlanner.Compute(with, without).IsEmpty.ShouldBeFalse($"removing one {listName} element"); + // Positive control: the SAME content twice (fresh instances) is not a change, or every check above is vacuous. + AddressSpacePlanner.Compute(with, Composition((list, Sample(ElementType(list))))).IsEmpty + .ShouldBeTrue($"an unchanged {listName} element must diff empty"); + } + + [Theory] + [MemberData(nameof(CompositionFields))] + public void Changing_any_single_field_of_any_composition_record_is_seen_by_the_planner(string listName, string fieldName) + { + var list = ListProperties().Single(p => p.Name == listName); + var type = ElementType(list); + var baseline = Sample(type); + var mutated = Mutate(baseline, fieldName); + mutated.ShouldNotBe(baseline, $"{type.Name}'s record equality ignores {fieldName} (or the test could not mutate it)"); + + var plan = AddressSpacePlanner.Compute(Composition((list, baseline)), Composition((list, mutated))); + + plan.IsEmpty.ShouldBeFalse( + $"{type.Name}.{fieldName} changed but the planner produced an EMPTY plan — the deploy would change nothing. " + + "Diff the field in AddressSpacePlanner.Compute (and decide in AddressSpaceChangeClassifier whether it is surgical)."); + } + + [Fact] + public void Every_composition_list_is_either_covered_or_explicitly_exempt() + { + // A list nobody wired into the theories would never run them. ListProperties is the same reflection both use, + // so this pins the shape: lists, of records, all reachable. + var lists = ListProperties().ToList(); + lists.Count.ShouldBeGreaterThanOrEqualTo(11); + foreach (var exempt in ExemptLists.Keys) lists.ShouldContain(p => p.Name == exempt); + } + + // ----- reflection helpers ----- + + private static IEnumerable ListProperties() => + typeof(AddressSpaceComposition) + .GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(IReadOnlyList<>)) + .OrderBy(p => p.Name, StringComparer.Ordinal); + + private static Type ElementType(PropertyInfo list) => list.PropertyType.GetGenericArguments()[0]; + + /// The positional members of a record: the parameters of its widest constructor. + private static IEnumerable RecordFields(Type t) => PrimaryCtor(t).GetParameters(); + + private static ConstructorInfo PrimaryCtor(Type t) => + t.GetConstructors(BindingFlags.Public | BindingFlags.Instance) + .Where(c => !(c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == t)) // copy ctor + .OrderByDescending(c => c.GetParameters().Length) + .First(); + + private static AddressSpaceComposition Composition(params (PropertyInfo List, object Element)[] items) + { + var c = new AddressSpaceComposition( + Array.Empty(), Array.Empty(), Array.Empty(), + Array.Empty(), Array.Empty()); + foreach (var (list, element) in items) + { + var array = Array.CreateInstance(ElementType(list), 1); + array.SetValue(element, 0); + c = With(c, list, array); + } + return c; + } + + /// Sets one list on a copy of the composition — the positional ones through the ctor, the init-only + /// ones through their setter on the record's clone. + private static AddressSpaceComposition With(AddressSpaceComposition c, PropertyInfo list, object value) + { + var clone = (AddressSpaceComposition)typeof(AddressSpaceComposition) + .GetMethod("$", BindingFlags.Public | BindingFlags.Instance)!.Invoke(c, null)!; + var backing = typeof(AddressSpaceComposition).GetField($"<{list.Name}>k__BackingField", + BindingFlags.NonPublic | BindingFlags.Instance)!; + backing.SetValue(clone, value); + return clone; + } + + private static object Sample(Type t) + { + var ctor = PrimaryCtor(t); + var args = ctor.GetParameters().Select(p => SampleValue(p.ParameterType, p.Name!)).ToArray(); + return ctor.Invoke(args); + } + + private static object Mutate(object record, string fieldName) + { + var t = record.GetType(); + var ctor = PrimaryCtor(t); + var args = ctor.GetParameters() + .Select(p => + { + var current = t.GetProperty(p.Name!)!.GetValue(record); + return p.Name == fieldName ? MutatedValue(p.ParameterType, current) : current; + }) + .ToArray(); + return ctor.Invoke(args); + } + + private static object? SampleValue(Type t, string name) + { + var underlying = Nullable.GetUnderlyingType(t); + if (t == typeof(string)) return $"{name}-v"; + if (t == typeof(bool)) return false; + if (t == typeof(int)) return 1; + if (t == typeof(uint)) return 1u; + if (underlying is not null) return null; // int?, uint?, bool? ⇒ start null + if (t.IsEnum) return Enum.GetValues(t).GetValue(0); + if (t == typeof(IReadOnlyList)) return new[] { $"{name}-a" }; + if (t.IsClass) return null; // nested records (e.g. alarm info) ⇒ start null + throw new NotSupportedException($"no sample for {t} ({name}) — extend the field-coverage test"); + } + + private static object? MutatedValue(Type t, object? current) + { + var underlying = Nullable.GetUnderlyingType(t); + if (t == typeof(string)) return (string?)current + "-x"; + if (t == typeof(bool)) return !(bool)current!; + if (t == typeof(int)) return (int)current! + 1; + if (t == typeof(uint)) return (uint)current! + 1; + if (underlying is not null) + return current is null ? Convert.ChangeType(underlying == typeof(bool) ? true : 7, underlying) : null; + if (t.IsEnum) + { + var values = Enum.GetValues(t); + return values.GetValue((Array.IndexOf(values, current) + 1) % values.Length); + } + if (t == typeof(IReadOnlyList)) return ((IEnumerable)current!).Cast().Append("extra").ToArray(); + if (t.IsClass) return current is null ? Sample(t) : null; + throw new NotSupportedException($"cannot mutate {t} — extend the field-coverage test"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDeployBookkeepingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDeployBookkeepingTests.cs new file mode 100644 index 000000000..e2cdaeef8 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorDeployBookkeepingTests.cs @@ -0,0 +1,150 @@ +using Akka.Actor; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache; +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; + +/// +/// Gitea #977 — deploy bookkeeping on the driver host: R-1 (a restart after a FAILED deploy must serve the last +/// APPLIED deployment, not boot empty) and R-15 (an apply that throws part-way must not leave its revision looking +/// cleanly served, so a re-dispatch re-applies). +/// +public sealed class DriverHostActorDeployBookkeepingTests : RuntimeActorTestBase +{ + private static readonly NodeId TestNode = NodeId.Parse("driver-test"); + private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64)); + private static readonly RevisionHash RevB = RevisionHash.Parse(new string('b', 64)); + + [Fact] + public void A_restart_after_a_failed_deploy_restores_the_last_applied_deployment() + { + var db = NewInMemoryDbFactory(); + var a = Seed(db, RevA, "speed"); + var b = Seed(db, RevB, "pressure"); + var t0 = DateTime.UtcNow.AddMinutes(-10); + AddNodeRow(db, a, NodeDeploymentStatus.Applied, t0); + AddNodeRow(db, b, NodeDeploymentStatus.Failed, t0.AddMinutes(5), "apply threw"); // NEWER, failed + + var publish = CreateTestProbe(); + var coordinator = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref)); + + // The address space is rebuilt from A's artifact — before the fix the Failed arm went straight to an empty Steady. + var rebuild = publish.FishForMessage( + m => m.DeploymentId == a, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + rebuild.Artifact.ShouldBe(ArtifactOf(db, a)); + + // And A is the CURRENT revision: a re-dispatch of A is the idempotent clean ack, not a re-apply. + host.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId())); + coordinator.FishForMessage(m => m.DeploymentId == a, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied); + } + + [Fact] + public void A_newest_applied_row_is_restored_exactly_as_before() + { + // Positive control for the selection above: the ordinary Applied-newest boot is unchanged. + var db = NewInMemoryDbFactory(); + var a = Seed(db, RevA, "speed"); + AddNodeRow(db, a, NodeDeploymentStatus.Applied, DateTime.UtcNow); + var publish = CreateTestProbe(); + Sys.ActorOf(DriverHostActor.Props( + db, TestNode, CreateTestProbe().Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref)); + + publish.FishForMessage( + m => m.DeploymentId == a, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact] + public void A_failed_only_history_falls_back_to_the_node_local_cache() + { + var db = NewInMemoryDbFactory(); + var b = Seed(db, RevB, "pressure"); + AddNodeRow(db, b, NodeDeploymentStatus.Failed, DateTime.UtcNow, "apply threw"); + var cachedBytes = ArtifactOf(db, b); + var cachedId = DeploymentId.NewId(); + var cache = new FixedCache(new CachedDeploymentArtifact( + cachedId.ToString(), RevA.Value, cachedBytes, DateTimeOffset.UtcNow)); + + var publish = CreateTestProbe(); + Sys.ActorOf(DriverHostActor.Props( + db, TestNode, CreateTestProbe().Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref, + deploymentArtifactCache: cache)); + + publish.FishForMessage( + m => m.DeploymentId == cachedId, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact] + public void An_apply_that_throws_after_reconcile_leaves_its_revision_unconfirmed_so_a_redispatch_reapplies() + { + var db = NewInMemoryDbFactory(); + var a = Seed(db, RevA, "speed"); + var throwOnce = 1; + var catalog = new LocalCatalogCoordinator(new CatalogActivation(), new DataPlaneAuthorityState(), + () => new ServingIdentity(TestNode.Value, "process-1", "Primary", 0, 0)); + catalog.BeforeSubscriptionApplyForTests = () => + { + if (Interlocked.Exchange(ref throwOnce, 0) == 1) throw new InvalidOperationException("subscription work failed"); + }; + var publish = CreateTestProbe(); + var coordinator = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref, + catalogCoordinator: catalog)); + + host.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId())); + coordinator.FishForMessage(m => m.DeploymentId == a, PresenceBudget, + cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Failed); + + // Same revision again: it was never served, so it must RE-APPLY (an outcome-reporting rebuild), not short-circuit + // to an immediate clean Applied. + host.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId())); + publish.FishForMessage( + m => m.DeploymentId == a && m.ReportOutcome, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + private static DeploymentId Seed(IDbContextFactory db, RevisionHash rev, string tag) => + V3ArtifactSeeder.SeedV3Deployment(db, rev, + rawTags: new[] { (Driver: "drv-1", DriverName: "Modbus", Device: "dev1", Tag: tag, DataType: "Double", Writable: false) }, + unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: tag, Effective: (string?)null) }); + + private static void AddNodeRow(IDbContextFactory db, DeploymentId id, NodeDeploymentStatus status, + DateTime startedAtUtc, string? reason = null) + { + using var ctx = db.CreateDbContext(); + ctx.NodeDeploymentStates.Add(new NodeDeploymentState + { + NodeId = TestNode.Value, DeploymentId = id.Value, Status = status, StartedAtUtc = startedAtUtc, + AppliedAtUtc = status == NodeDeploymentStatus.Applied ? startedAtUtc : null, FailureReason = reason, + }); + ctx.SaveChanges(); + } + + private static byte[] ArtifactOf(IDbContextFactory db, DeploymentId id) + { + using var ctx = db.CreateDbContext(); + return ctx.Deployments.Single(d => d.DeploymentId == id.Value).ArtifactBlob!; + } + + private sealed class FixedCache(CachedDeploymentArtifact artifact) : IDeploymentArtifactCache + { + public Task StoreAsync(string clusterId, string deploymentId, string revisionHash, byte[] bytes, CancellationToken ct = default) => Task.CompletedTask; + public Task GetCurrentAsync(string clusterId, CancellationToken ct = default) => Task.FromResult(artifact); + public Task GetCurrentUnkeyedAsync(CancellationToken ct = default) => Task.FromResult(artifact); + } +} 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 5a1f91e49..89f648ec8 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 @@ -152,6 +152,132 @@ public sealed class OpcUaPublishActorApplyOutcomeTests : RuntimeActorTestBase sink.EnsureFolderCount.ShouldBe(foldersAfterRepair); } + [Fact] + public void An_unrelated_surgical_deploy_after_a_degraded_REBUILD_re_ensures_what_the_rebuild_failed_to_place() + { + // Gitea #977 R-4. A degraded rebuild advances _lastApplied; the condition it failed to materialise is inside it + // and never appears in a diff again. A later, unrelated one-equipment add is a surgical PureAdd whose DELTA does + // not include that condition — it used to clear the degraded flag and seal green over the missing node. + 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.AlarmConditionCount.ShouldBe(1); + + // A changed equipment row ⇒ full rebuild; re-materialising the condition faults ⇒ degraded, but advanced. + sink.ThrowOnAlarmCondition = true; + Deploy(actor, BuildArtifact(new[] { "eq-1" }, "Second", withAlarm: true)).Degraded.ShouldBeTrue(); + sink.RebuildCount.ShouldBe(1); + + // Fault gone. An UNRELATED add (eq-2) — no rebuild — must still re-place the condition the rebuild lost. + sink.ThrowOnAlarmCondition = false; + var conditionsBefore = sink.AlarmConditionCount; + Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2" }, "Second", withAlarm: true)).Degraded.ShouldBeFalse(); + sink.RebuildCount.ShouldBe(1, "the repair must not need a rebuild"); + sink.AlarmConditionCount.ShouldBeGreaterThan(conditionsBefore, + "the degraded rebuild's missing condition was never re-ensured — the address space is partial and reported clean"); + + // Repaired for real: the identical re-deploy is the ordinary empty no-op again (no further re-materialise). + var afterRepair = sink.AlarmConditionCount; + Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2" }, "Second", withAlarm: true)).Degraded.ShouldBeFalse(); + sink.AlarmConditionCount.ShouldBe(afterRepair); + } + + [Fact] + public void A_still_failing_repair_keeps_reporting_degraded() + { + // R-4, the other half: while the re-ensure still fails, the unrelated deploy reports degraded rather than clean. + 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(); + Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2" }, "Second", withAlarm: true)).Degraded.ShouldBeTrue(); + } + + [Fact] + public void The_first_apply_after_a_supervision_restart_rebuilds_instead_of_diffing_against_an_empty_baseline() + { + // Gitea #977 R-20. The node manager outlives the actor; the restarted instance's _lastApplied is the empty seed. + var sink = new FaultingSink(throwOnEnsureFolder: false); + var applier = new AddressSpaceApplier(sink, NullLogger.Instance); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, applier, new OpcUaPublishActor.TestHooks())); + + Deploy(actor, BuildArtifact(new[] { "eq-1" }, "eq-1", withAlarm: false)).Degraded.ShouldBeFalse(); + // Positive control: on an un-restarted actor a pure add is surgical. + Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2" }, "eq-1", withAlarm: false)).Degraded.ShouldBeFalse(); + sink.RebuildCount.ShouldBe(0); + + actor.Tell(new OpcUaPublishActor.CrashForTests()); // same mailbox: processed (and restarted) before the next deploy + + // Same composition again: the new instance diffs it against EMPTY. Without the fix that is a pure add of + // everything — no rebuild — and a deploy that REMOVED a node would never remove it. + Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2" }, "eq-1", withAlarm: false)).Degraded.ShouldBeFalse(); + sink.RebuildCount.ShouldBe(1); + + // Once rebuilt, the baseline is known again: the next add is surgical. + Deploy(actor, BuildArtifact(new[] { "eq-1", "eq-2", "eq-3" }, "eq-1", withAlarm: false)).Degraded.ShouldBeFalse(); + sink.RebuildCount.ShouldBe(1); + } + + [Fact] + public void Enabling_a_disabled_scripted_alarm_materialises_its_condition() + { + // Gitea #977 U-2 end to end: an Enabled-only flip used to diff to an EMPTY plan, so the condition never appeared + // and every engine write to it was a silent no-op until an unrelated rebuild or a restart. + 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: true, alarmEnabled: false)).Degraded.ShouldBeFalse(); + sink.AlarmConditionCount.ShouldBe(0); + + Deploy(actor, BuildArtifact(new[] { "eq-1" }, "eq-1", withAlarm: true, alarmEnabled: true)).Degraded.ShouldBeFalse(); + sink.AlarmConditionCount.ShouldBe(1); + sink.RebuildCount.ShouldBe(0); + } + + private OpcUaPublishActor.RebuildCompleted Deploy(IActorRef actor, byte[] artifact) + { + actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact, ReportOutcome: true)); + return ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + private static byte[] BuildArtifact(string[] equipmentIds, string firstName, bool withAlarm, bool alarmEnabled = true) => + JsonSerializer.SerializeToUtf8Bytes(new + { + UnsAreas = new[] { new { UnsAreaId = "area-1", ClusterId = "c1", Name = "Area" } }, + UnsLines = new[] { new { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "Line" } }, + Equipment = equipmentIds.Select((id, i) => new + { + EquipmentId = id, + DriverInstanceId = (string?)null, + UnsLineId = "line-1", + Name = i == 0 ? firstName : id, + MachineCode = id.ToUpperInvariant(), + }).ToArray(), + RawFolders = Array.Empty(), + DriverInstances = Array.Empty(), + Devices = Array.Empty(), + TagGroups = Array.Empty(), + Tags = Array.Empty(), + ScriptedAlarms = withAlarm + ? new object[] + { + new + { + ScriptedAlarmId = "al-1", EquipmentId = "eq-1", Name = "High", AlarmType = "AlarmCondition", + Severity = 500, MessageTemplate = "high", PredicateScriptId = "s-1", HistorizeToAveva = false, + Retain = true, Enabled = alarmEnabled, + }, + } + : Array.Empty(), + Scripts = new[] { new { ScriptId = "s-1", SourceCode = "return false;" } }, + }); + private static byte[] BuildEquipmentArtifact(string equipmentId) => BuildEquipmentArtifact(equipmentId, equipmentId); private static byte[] BuildEquipmentArtifact(string equipmentId, string name) => @@ -182,10 +308,16 @@ public sealed class OpcUaPublishActorApplyOutcomeTests : RuntimeActorTestBase public bool ThrowOnEnsureFolder { get; set; } = throwOnEnsureFolder; public int EnsureFolderCount; public int RebuildCount; + public bool ThrowOnAlarmCondition { get; set; } + public int AlarmConditionCount; 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 MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) + { + AlarmConditionCount++; + if (ThrowOnAlarmCondition) throw new InvalidOperationException("simulated condition fault"); + } public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm = AddressSpaceRealm.Uns) { EnsureFolderCount++;