From 070fd493f94e34dd0f5b0880a2ac4c8721180142 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 11:08:07 -0500 Subject: [PATCH] fix(runtime): #1002 StopChild drops comms latch/audit + holds health ledger; deferred known marks kept for kept conditions; backlog drain re-ticks; per-driver source index; unconvertible ProcessingInterval is BadInvalidArgument; VirtualTagHost re-applied after restart; empty DisplayNameOverride = tag name Co-Authored-By: Claude --- docs/DriverLifecycle.md | 6 ++ docs/Historian.md | 5 +- docs/VirtualTags.md | 1 + .../Validation/DataConnectionValidator.cs | 2 +- .../HistoryReadPort.cs | 14 ++++ .../ProjectedHistoryRead.cs | 9 +++ .../LocalExportCatalog.Compilation.cs | 2 +- .../DataConnections/SourceSamplePublisher.cs | 19 +++++- .../Drivers/ChildHealthLedger.cs | 27 ++++++-- .../Drivers/DriverHostActor.cs | 32 +++++++++ .../ContinuousHistorizationRecorder.cs | 4 ++ .../OpcUa/OpcUaPublishActor.cs | 40 ++++++----- .../VirtualTags/VirtualTagHostActor.cs | 23 +++++++ .../GrpcDataMappingValidationTests.cs | 40 +++++++++++ .../ProjectedHistoryReadTests.cs | 32 +++++++++ .../NodeManagerHistoryReadTests.cs | 47 +++++++++++++ .../Drivers/ChildHealthLedgerTests.cs | 44 ++++++++++++ .../Drivers/DriverHostActorVirtualTagTests.cs | 67 +++++++++++++++++++ .../DriverHostCommsLossRecoveryTests.cs | 43 ++++++++++++ .../Harness/V3ArtifactSeeder.cs | 6 +- ...sHistorizationRecorderBacklogDrainTests.cs | 37 ++++++++++ .../OpcUaPublishActorConditionKnownTests.cs | 33 +++++++++ 22 files changed, 504 insertions(+), 29 deletions(-) create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ChildHealthLedgerTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/ContinuousHistorizationRecorderBacklogDrainTests.cs diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 4504e752a..6bfabc8b2 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -560,6 +560,12 @@ latched Bad, as a Warning naming the driver plus the `otopcua.driver.comms_latch a push driver missing its initial push, or a value-only dedup swallowing an unchanged value. It is a tripwire, not a repair: nothing downstream depends on it. +The latch and its audit timer belong to one driver incarnation: `StopChild` (a deploy removal, a disable, the stop half of +a config-change respawn) drops the latch and cancels the pending audit (R-16), so a removed driver never fires a false +Warning / counter increment and a disable then re-enable of the same id never inherits a stale latch. `StopChild` also +holds the id in the `ChildHealthLedger` (`Forget` then `Readmit` on the next spawn), so the stopped child's late health +publish cannot resurrect its diagnostics entry. + ### The connect path feeds the circuit breaker (R2-10 T10 closure) `IDriver.InitializeAsync` is routed through the capability invoker as diff --git a/docs/Historian.md b/docs/Historian.md index caae26e29..003fd58fe 100644 --- a/docs/Historian.md +++ b/docs/Historian.md @@ -317,7 +317,7 @@ and is registered the same way for every backend. | `CommitMode` | string | `PerEntry` | `PerEntry` fsyncs before the append returns (no loss window; one group-commit fsync per ingest burst). `Periodic` is the opt-in throughput mode: it commits on a background timer every `CommitIntervalMs`, so a crash can lose at most the last interval of captured values in exchange for ingestion no longer being capped at `1 / fsync_latency`. Parsed case-insensitively; an unparseable value falls back to `PerEntry`. The code default, shipped `appsettings.json`, docker-dev and the fallback all agree on `PerEntry` (lmxopcua#776). | | `CommitIntervalMs` | int | `100` | Periodic-mode commit cadence (ms); must be `> 0` under `Periodic`, ignored under `PerEntry`. | | `DrainBatchSize` | int | `1024` | Outbox entries peeked + written per drain pass. **Raised from 64**: the peek is an in-memory scan of the outbox's live index (widening it costs allocation, not I/O), and a pass is now bounded-parallel over `DrainConcurrency` rather than sequential, so a wide batch no longer costs `tags × latency`. At 64 a drain drew down at most 64 entries every `DrainIntervalSeconds` — below the arrival rate of even a modest historized tag set — so any gateway hiccup left the outbox permanently behind, growing toward `Capacity` and shedding oldest samples instead of catching up. | -| `DrainIntervalSeconds` | double | `2` | Steady drain cadence (and the post-success reschedule). | +| `DrainIntervalSeconds` | double | `2` | Steady drain cadence (and the post-success reschedule). A pass that acked a FULL batch (`DrainBatchSize`) re-ticks immediately instead of waiting the interval (R-25), so an outage backlog catches up at writer speed rather than `DrainBatchSize / DrainIntervalSeconds`. | | `DrainConcurrency` | int | `8` | Historian tags a single drain pass writes **concurrently**. One peeked batch is grouped per historian tag and each group is an independent gateway round-trip, so a sequential pass cost `tags × latency`; this window makes it `⌈tags / concurrency⌉ × latency` while bounding how many round-trips can be outstanding against the gateway at once. `1` restores the fully sequential drain; a value `< 1` is clamped to 1 (with a `Validate()` warning). **The ack is unchanged** — still all-or-nothing after every group has reported, and the #538 per-tag quarantine still keys on "another group wrote this pass". | | `Capacity` | int | `500000` | Max un-acked outbox entries before the drop-oldest policy sheds the front of the queue; `0` = unbounded. Roughly 50 MB of FasterLog. The #538 **disk backstop** for the one case the per-tag quarantine deliberately cannot resolve — a historian unreachable or refusing *every* write, where nothing proves any particular tag is at fault so the recorder correctly retains. | | `MaxWriteAttempts` | int | `5` | #538 poison-tag budget: consecutive failed drain passes one historian tag may accumulate before its queued entries are abandoned and the FIFO head is allowed to advance. **Counted only across passes where *other* tags wrote successfully**, so an ordinary gateway outage never advances it. Clamped to at least 1; each abandonment logs a Warning naming the tag. | @@ -1458,6 +1458,9 @@ gateway refuses `start > end` and `interval <= 0`): - ⚠️ **Interval cap (client-visible):** forward native reads now go through `BucketPlan` too, so a window of more than 100,000 intervals (e.g. 1 s over 2 days) is refused up front with `BadHistoryOperationUnsupported`, as on the SQL backends — it used to be served up to the gateway's own `MaxAggregateIntervals` (1,000,000). Not counted as a backend failure. +- ⚠️ **Unconvertible `ProcessingInterval` (U-7, client-visible, every backend):** a NaN, infinite or beyond-`TimeSpan` (~9.2e14 ms) + `ProcessingInterval` is answered `BadInvalidArgument` per node (local and projected), the backend never called — it used to throw + out of `TimeSpan.FromMilliseconds` and fault the whole request (`BadUnexpectedError`). - ⚠️ **Whole milliseconds on the wire (#694, client-visible).** The gateway sends AVEVA the interval as `max(1, round(ms))` and AVEVA clips its last interval at the request's end (both observed live). So: (1) a grid of several intervals is one request only when the interval is a whole number of milliseconds — a fractional one (e.g. `ProcessingInterval = 1.5`) is read **one interval per diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 386cc7cd2..c0d82d61a 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -315,6 +315,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT - **`{{equip}}/` does not resolve a VirtualTag** — that token resolves `UnsTagReference` rows only. `EquipReferenceUnresolved` now says so when the name is a VirtualTag on that equipment and names the key form to use. - **AdminUI.** The script editor's completion/hover catalog (`ScriptTagCatalog`) lists each VirtualTag under its key instead of its bare leaf name. - Pinned by `VirtualTagToVirtualTagFlowTests` (Host.Tests: real mux + host + Roslyn evaluator; value, change and disabled-upstream propagation), `VirtualTagOutputRoutingTests` (Runtime.Tests: mux pinning/replay/release, host routing, re-assert exclusion, runtime cycle backstop) and `DraftValidatorVirtualTagCycleTests`. +- **Supervision restart re-applies.** A restart of `VirtualTagHostActor` builds a host with no children and no definitions; its `PostRestart` tells the parent `VirtualTagHostRestarted` and `DriverHostActor` re-sends the last `ApplyVirtualTags` (mirroring the scripted-alarm host's `ScriptedAlarmHostRestarted`), so VirtualTags resume without waiting for the next deploy. Pinned by `DriverHostActorVirtualTagTests.After_a_supervision_restart_the_virtual_tag_host_is_re_applied`. - **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`; there is no FK, so a concurrent bind is caught by the gate). As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`. - **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`. - **Calculation tags and scripted alarms still evaluate one script at a time per driver / per engine (deliberately, for now).** Neither blocks a thread — both await the run — but a slow script still delays its siblings. Running independent scripts in parallel was considered for #779 and not done, because it is not semantics-neutral: for Calculation, the single pump is what bounds a driver to one pool thread of script work (per-tag lanes would let N slow tags hold N pool threads, the pool Akka's dispatchers also run on, so it needs a bounded-parallelism knob), it would reorder publishes across tags, and the timer path would need per-tag exclusion with the pump; for scripted alarms, the engine gate is also the consistency boundary of the Part 9 state machine, persist-before-update and ack/shelve/load, a predicate's transition time is sampled just before its own run, and a store failure mid-batch today leaves later predicates un-run (in parallel they would already have run, moving their run-guard strike streaks and writing script logs for results that are then discarded). The out-of-process runner's batch-submit `IScriptRunner` (#750) is where that concurrency belongs, with the runner owning the bound. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs index a1bd0a196..662755223 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs @@ -226,7 +226,7 @@ public static class DataConnectionValidator "RawTagGroup" => draft.TagGroups.Any(x => Same(x.ParentTagGroupId, m.LocalParentId) && Name(x.Name)) || draft.Tags.Any(x => Same(x.TagGroupId, m.LocalParentId) && Name(x.Name)), "UnsArea" => draft.UnsLines.Any(x => Same(x.UnsAreaId, m.LocalParentId) && Name(x.Name)), "UnsLine" => draft.Equipment.Any(x => Same(x.UnsLineId, m.LocalParentId) && Name(x.Name)), - "Equipment" => draft.VirtualTags.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.ScriptedAlarms.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.UnsTagReferences.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.DisplayNameOverride ?? draft.Tags.FirstOrDefault(t => Same(t.TagId, x.TagId))?.Name)), + "Equipment" => draft.VirtualTags.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.ScriptedAlarms.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.UnsTagReferences.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(EquipmentReferenceMap.EffectiveName(x.DisplayNameOverride, draft.Tags.FirstOrDefault(t => Same(t.TagId, x.TagId))?.Name))), _ => false }; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs index 0d4802ee8..9e6580eff 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/HistoryReadPort.cs @@ -16,6 +16,20 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// internal abstract record HistoryReadVariant { + /// + /// U-7: whether a client's raw ProcessingInterval (a of milliseconds) converts to a + /// . TimeSpan.FromMilliseconds throws for NaN and for infinity / magnitudes past ~9.2e14 ms, + /// and nothing between the SDK dispatcher and the node manager catches it — one bad value faulted the whole request. + /// + /// The wire value. + /// True when / the remote mapping will not throw. + public static bool IsConvertibleProcessingInterval(double milliseconds) + { + if (!double.IsFinite(milliseconds)) return false; + try { _ = TimeSpan.FromMilliseconds(milliseconds); return true; } + catch (Exception ex) when (ex is OverflowException or ArgumentException) { return false; } + } + /// Maps the SDK's onto the port variant the overrides serve. /// Raw/modified, Processed or AtTime details. /// The equivalent variant. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs index 6d379355b..7f6fe8633 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedHistoryRead.cs @@ -35,6 +35,15 @@ public sealed partial class OtOpcUaNodeManager IList results, IList errors) { + // U-7: an unconvertible ProcessingInterval (NaN / infinity / beyond TimeSpan) is the client's invalid argument, + // answered per node — never an exception out of the conversion below that faults the whole request. + if (details is ReadProcessedDetails { ProcessingInterval: var interval } + && !HistoryReadVariant.IsConvertibleProcessingInterval(interval)) + { + foreach (var handle in nodesToProcess) SetProjectedStatus(handle, results, errors, StatusCodes.BadInvalidArgument); + return; + } + List? projected = null; foreach (var handle in nodesToProcess) if (IsProjectedDescendant(handle.NodeId)) (projected ??= []).Add(handle); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs index f01d7ebd9..2f92944b5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs @@ -53,7 +53,7 @@ public sealed partial class LocalExportCatalog var tagById = tags.ToDictionary(x => x.TagId, ids); var deviceById = devices.ToDictionary(x => x.DeviceId, ids); var driverById = drivers.ToDictionary(x => x.DriverInstanceId, ids); - var referenceNames = references.Select(x => (x.EquipmentId, x.TagId, EffectiveName: x.DisplayNameOverride ?? tagById[x.TagId].Name)).ToArray(); + var referenceNames = references.Select(x => (x.EquipmentId, x.TagId, EffectiveName: EquipmentReferenceMap.EffectiveName(x.DisplayNameOverride, tagById[x.TagId].Name)!)).ToArray(); var scopeResolver = new AclScopePathResolver( folders.ToDictionary(x => x.RawFolderId, x => (x.ParentRawFolderId, x.Name), ids), drivers.ToDictionary(x => x.DriverInstanceId, x => (x.RawFolderId, x.Name), ids), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs index 8fdd332fd..d029d5601 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs @@ -56,6 +56,9 @@ public sealed class SourceSamplePublisher private readonly object _gate = new(); private readonly Dictionary _tickets = new(); private readonly Dictionary<(string Driver, string Reference), BackingSourceKey> _drivers = new(); + // R-25: per-driver view of _drivers (reference -> key), so RetireDriver / PublishDriverStatus walk one driver's refs + // instead of scanning every bound ref of every driver under _gate. Always mutated beside _drivers. + private readonly Dictionary> _driverKeys = new(StringComparer.Ordinal); private readonly Dictionary _virtuals = new(StringComparer.Ordinal); internal sealed class SourceSlot { @@ -125,6 +128,9 @@ public sealed class SourceSamplePublisher if (SourceKey.TryDriver(key, out driver, out reference)) { _drivers[(driver, reference)] = key; + if (!_driverKeys.TryGetValue(driver, out var perDriver)) + _driverKeys[driver] = perDriver = new Dictionary(StringComparer.Ordinal); + perDriver[reference] = key; _driverRoutes[(driver, reference)] = binding; } else if (key.SourceKind == "virtual") @@ -217,6 +223,9 @@ public sealed class SourceSamplePublisher } finally { Monitor.Exit(_gate); } } + /// A snapshot of 's bound source keys. Caller holds _gate. + private BackingSourceKey[] DriverKeys(string driver) => + _driverKeys.TryGetValue(driver, out var perDriver) ? [.. perDriver.Values] : []; public void RetireDriver(string driver, long incarnation) { // The hub sees the same fence. Reads and snapshots are denied before the slow per-tag walk. @@ -226,14 +235,14 @@ public sealed class SourceSamplePublisher { if (!_driverIncarnations.TryGetValue(driver, out var current) || !ReferenceEquals(current, producer)) return; _driverIncarnations.TryRemove(driver, out _); - foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray()) + foreach (var key in DriverKeys(driver)) if (_tickets.TryGetValue(key, out var ticket)) TryRemove(ticket); } } public void PublishDriverStatus(string driver, uint status) { lock (_gate) - foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray()) + foreach (var key in DriverKeys(driver)) if (_tickets.TryGetValue(key, out var ticket)) TryPublishStatus(ticket, status, out _); } public bool TryCaptureVirtual(string id, out SourceTicket ticket) @@ -598,7 +607,11 @@ public sealed class SourceSamplePublisher _slots.TryRemove(ticket.Key, out _); _tickets.Remove(ticket.Key); if (SourceKey.TryDriver(ticket.Key, out var driver, out var reference)) - { _drivers.Remove((driver, reference)); _driverRoutes.TryRemove((driver, reference), out _); } + { + _drivers.Remove((driver, reference)); _driverRoutes.TryRemove((driver, reference), out _); + if (_driverKeys.TryGetValue(driver, out var perDriver) && perDriver.Remove(reference) && perDriver.Count == 0) + _driverKeys.Remove(driver); + } else if (ticket.Key.SourceKind == "virtual") { _virtuals.Remove(ticket.Key.StableSourceId); _virtualRoutes.TryRemove(ticket.Key.StableSourceId, out _); } if (_hub.TryRemove(ticket, checked(++slot.Sequence))) return true; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/ChildHealthLedger.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/ChildHealthLedger.cs index ec722a2c7..0fe2743a0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/ChildHealthLedger.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/ChildHealthLedger.cs @@ -26,13 +26,16 @@ public sealed record ChildHealthRecord( /// /// Deliberately NOT a message to the host: the children already publish through this seam on every /// change, so a parallel Tell would double every health transition's traffic for one consumer. -/// Entries are removed by the host when it stops a child; a late publish from a stopping child may re-add -/// one, which the host filters against its live child set when it answers. +/// Entries are removed by the host when it stops a child, and the id is then held (like the telemetry hub's +/// tombstone) so a late publish from the stopping child is not re-recorded; a later spawn of the same id lifts +/// the hold via . /// public sealed class ChildHealthLedger : IDriverHealthPublisher { private readonly IDriverHealthPublisher _inner; private readonly ConcurrentDictionary _last = new(StringComparer.Ordinal); + // Ids whose child was stopped: a late publish from the stopping child must not resurrect the entry (R-16). + private readonly ConcurrentDictionary _held = new(StringComparer.Ordinal); /// Wraps . /// The publisher every snapshot is forwarded to. @@ -54,8 +57,9 @@ public sealed class ChildHealthLedger : IDriverHealthPublisher SkippedTagReport? skippedTags = null, IReadOnlyDictionary? diagnostics = null) { - _last[driverInstanceId] = new ChildHealthRecord( - health.State, health.LastSuccessfulRead, health.LastError, hostStatuses, DateTime.UtcNow); + if (!_held.ContainsKey(driverInstanceId)) + _last[driverInstanceId] = new ChildHealthRecord( + health.State, health.LastSuccessfulRead, health.LastError, hostStatuses, DateTime.UtcNow); _inner.Publish( clusterId, driverInstanceId, health, errorCount5Min, rediscoveryNeededUtc, rediscoveryReason, hostStatuses, skippedTags, diagnostics); @@ -67,7 +71,18 @@ public sealed class ChildHealthLedger : IDriverHealthPublisher public ChildHealthRecord? TryGet(string driverInstanceId) => _last.TryGetValue(driverInstanceId, out var record) ? record : null; - /// Forgets 's snapshot (the child was stopped). + /// + /// Forgets 's snapshot (the child was stopped) and HOLDS the id: a late + /// publish from the stopping child is forwarded but no longer recorded, until . + /// /// The driver instance. - public void Forget(string driverInstanceId) => _last.TryRemove(driverInstanceId, out _); + public void Forget(string driverInstanceId) + { + _held[driverInstanceId] = 0; + _last.TryRemove(driverInstanceId, out _); + } + + /// Lifts the hold placed, because a new child of the id is being spawned. + /// The driver instance. + public void Readmit(string driverInstanceId) => _held.TryRemove(driverInstanceId, out _); } 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 26f8519eb..eb54b1951 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -331,6 +331,10 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// first apply. private IReadOnlyList? _lastScriptedAlarmPlans; + /// The VirtualTag plans last sent to , re-sent when it reports a supervision + /// restart (). Null until the first apply. + private IReadOnlyList? _lastVirtualTagPlans; + private RevisionHash? _currentRevision; /// @@ -1838,6 +1842,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn Receive(RetireProjected); Receive(OnRetiredChildTerminated); Receive(_ => HandleScriptedAlarmHostRestarted()); + Receive(_ => HandleVirtualTagHostRestarted()); Receive(ForwardNativeAlarm); Receive(OnDriverConnectivityChanged); ReceiveConditionSignals(); @@ -1920,6 +1925,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn Receive(RetireProjected); Receive(OnRetiredChildTerminated); Receive(_ => HandleScriptedAlarmHostRestarted()); + Receive(_ => HandleVirtualTagHostRestarted()); Receive(ForwardNativeAlarm); Receive(OnDriverConnectivityChanged); ReceiveConditionSignals(); @@ -3054,6 +3060,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _localNode, m.Items.Count, m.DriverInstanceId)); Receive(OnRetiredChildTerminated); Receive(_ => HandleScriptedAlarmHostRestarted()); + Receive(_ => HandleVirtualTagHostRestarted()); Receive(m => _log.Debug("DriverHost {Node}: dropping a native alarm transition ({Cond}) from {Id} while Stale", _localNode, m.Args.ConditionId, m.DriverInstanceId)); @@ -4321,6 +4328,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // deployment dispatch. This is intentional and consistent with driver recovery: the Stale // path only restores the revision marker + NodeDeploymentState; a subsequent dispatch // (or a redeploy from AdminUI) triggers the full apply + subscribe pass. + _lastVirtualTagPlans = composition.EquipmentVirtualTags; _virtualTagHost?.Tell(new VirtualTagHostActor.ApplyVirtualTags(composition.EquipmentVirtualTags)); if (composition.EquipmentVirtualTags.Count > 0) { @@ -4668,6 +4676,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // items) may come back; lift the hold BEFORE the child exists, since it publishes health as it starts. // The resilience tracker's equivalent is lifted by _invokerFactory.Create below. _telemetryHub?.Readmit(spec.DriverInstanceId); + _healthPublisher.Readmit(spec.DriverInstanceId); var stub = DriverInstanceActor.ShouldStub(spec.DriverType, _localRoles); IDriver? driver = null; if (!stub) @@ -4845,6 +4854,12 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // backoff it never earned (its first crash was deferred as a "crash loop"). _lastReprovisionUtc.Remove(driverInstanceId); Timers.Cancel(ReprovisionTimerKey(driverInstanceId)); + // R-16: the comms-loss latch and its recovery-audit timer belong to the incarnation that just ended. Left + // behind, a removed-while-comms-lost driver kept its whole RawPath set forever, a removal within the audit + // window still fired a false Warning + otopcua.driver.comms_latched_refs increment, and a disable -> + // re-enable of the same id inherited the stale latch. + _commsLatched.Remove(driverInstanceId); + Timers.Cancel(CommsAuditTimerKey(driverInstanceId)); _healthPublisher.Forget(driverInstanceId); _log.Info("DriverHost {Node}: stopped driver child {Id}", _localNode, driverInstanceId); } @@ -4897,6 +4912,23 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _scriptedAlarmHost.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(_lastScriptedAlarmPlans)); } + /// + /// The VirtualTag host was restarted by supervision and has no children: re-send the last plans so every + /// VirtualTag evaluates again without waiting for the next deploy. Only the CURRENT host's signal is honoured. + /// + private void HandleVirtualTagHostRestarted() + { + if (_virtualTagHost is null || !Sender.Equals(_virtualTagHost)) return; + if (_lastVirtualTagPlans is null) + { + _log.Debug("DriverHost {Node}: VirtualTag host restarted before any apply; nothing to re-send", _localNode); + return; + } + _log.Warning("DriverHost {Node}: VirtualTag host was restarted by supervision; re-applying {Count} virtual tag(s)", + _localNode, _lastVirtualTagPlans.Count); + _virtualTagHost.Tell(new VirtualTagHostActor.ApplyVirtualTags(_lastVirtualTagPlans)); + } + /// A retired child has terminated; nothing more can arrive from it. /// The termination notice. private void OnRetiredChildTerminated(Terminated msg) => _retiredChildren.Remove(msg.ActorRef); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ContinuousHistorizationRecorder.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ContinuousHistorizationRecorder.cs index 4b5632df9..7328a3fc0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ContinuousHistorizationRecorder.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ContinuousHistorizationRecorder.cs @@ -1057,6 +1057,10 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers _currentBackoff = _minBackoff; _nextAllowedDrainUtc = DateTime.MinValue; Timers.StartSingleTimer(DrainTimerKey, DrainTick.Instance, _drainInterval); + // R-25: a FULL acked batch means more is probably waiting (an outage backlog). Re-tick now rather than + // waiting out the interval, which capped catch-up at drainBatchSize / drainInterval (~512 entries/s by + // default — ~33 min for a 1M-entry backlog). A short batch (queue drained) falls back to the steady cadence. + if (!_stopping && result.Acked >= _drainBatchSize) Self.Tell(DrainTick.Instance); return; } 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 6365f4a32..47279f77d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -257,7 +257,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers bool AllVariables, IReadOnlySet<(AddressSpaceRealm, string)> Variables, IReadOnlyDictionary<(AddressSpaceRealm, string), VariableShape> Reshaped, - IReadOnlySet<(AddressSpaceRealm, string)> Conditions) + IReadOnlySet<(AddressSpaceRealm, string)> Conditions, + IReadOnlySet<(AddressSpaceRealm, string)>? ExistingConditions = null) { private static readonly IReadOnlySet<(AddressSpaceRealm, string)> None = new HashSet<(AddressSpaceRealm, string)>(); public static readonly ReplayScope Nothing = @@ -1189,11 +1190,17 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying {Count} deferred status writes threw", statuses.Count); } } - // G3 pre-pass: a deferred projection outside the applied scope is skipped — its source's KNOWN marks are discarded - // wherever they sit in the arrival order (the conservative reading of "never known over a projection that did - // not land"). + // G3 pre-pass: a deferred projection of a condition that exists in NEITHER the previous nor the applied + // composition never landed anywhere — its source's KNOWN marks are discarded wherever they sit in the arrival + // order (the conservative reading of "never known over a projection that did not land"). R-18: a projection + // outside the replay scope for a condition that DOES exist (a kept condition on a surgical / no-artifact apply, + // or a removed one) is not a loss — the live write already landed on the surviving node, or there is no node. foreach (var (alarm, _) in _deferred.Alarms) - if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) _deferred.NoteAlarmLoss(alarm.Source); + { + var key = (alarm.Realm, alarm.AlarmNodeId); + if (!scope.Conditions.Contains(key) && scope.ExistingConditions?.Contains(key) != true) + _deferred.NoteAlarmLoss(alarm.Source); + } // #926 review r2: alarm states, alarm qualities and condition-known marks replay as ONE list in ARRIVAL order. // Marks used to replay after every alarm, which was right for a "known" mark (it summarises the projections @@ -1523,7 +1530,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers if (a.Enabled) conditions.Add((AddressSpaceRealm.Uns, a.ScriptedAlarmId)); } - _replayScope = new ReplayScope(rebuilt, recording.Ensured, recording.Reshaped, conditions); + var existing = ConditionIds(previous); + existing.UnionWith(ConditionIds(ready.Composition)); + _replayScope = new ReplayScope(rebuilt, recording.Ensured, recording.Reshaped, conditions, existing); return result; } finally @@ -1540,16 +1549,17 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers var added = ConditionIds(next); added.ExceptWith(ConditionIds(previous)); return added; + } - static HashSet<(AddressSpaceRealm, string)> ConditionIds(AddressSpaceComposition c) - { - var ids = new HashSet<(AddressSpaceRealm, string)>(); - foreach (var a in c.EquipmentScriptedAlarms) - if (a.Enabled) ids.Add((AddressSpaceRealm.Uns, a.ScriptedAlarmId)); - foreach (var t in c.RawTags) - if (t.Alarm is not null) ids.Add((AddressSpaceRealm.Raw, t.NodeId)); - return ids; - } + /// Every condition id a composition materialises: enabled scripted alarms (Uns) and native alarms (Raw). + private static HashSet<(AddressSpaceRealm, string)> ConditionIds(AddressSpaceComposition c) + { + var ids = new HashSet<(AddressSpaceRealm, string)>(); + foreach (var a in c.EquipmentScriptedAlarms) + if (a.Enabled) ids.Add((AddressSpaceRealm.Uns, a.ScriptedAlarmId)); + foreach (var t in c.RawTags) + if (t.Alarm is not null) ids.Add((AddressSpaceRealm.Raw, t.NodeId)); + return ids; } private (bool Degraded, string? Reason) ApplyPlanCore(PlanReady ready, out bool rebuilt) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs index 03d889972..b6a484b9a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs @@ -47,6 +47,21 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers /// The desired Equipment-namespace VirtualTag plans. public sealed record ApplyVirtualTags(IReadOnlyList Plans); + /// + /// Told to the parent from (mirrors ScriptedAlarmHostActor.ScriptedAlarmHostRestarted). + /// A supervision restart is otherwise invisible to the parent and the new incarnation has NO children (Akka's + /// default PreRestart stops them) and no definitions, so every VirtualTag on the node would stop + /// evaluating until the next deploy. The parent (DriverHostActor) answers by re-sending the last + /// it sent. + /// + public sealed class VirtualTagHostRestarted + { + /// The single instance. + public static readonly VirtualTagHostRestarted Instance = new(); + + private VirtualTagHostRestarted() { } + } + private readonly IActorRef? _publishActor; private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher; private readonly HashSet _publishedVirtualIds = new(StringComparer.Ordinal); @@ -113,6 +128,14 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers Receive(OnChildTerminated); } + /// + /// Tells the parent so it re-sends the last . + protected override void PostRestart(Exception reason) + { + base.PostRestart(reason); + Context.Parent.Tell(VirtualTagHostRestarted.Instance); + } + private void OnApply(ApplyVirtualTags msg) { Timers.Cancel("source-binding-retry"); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataMappingValidationTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataMappingValidationTests.cs index 0d5721464..ab03a45f5 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataMappingValidationTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataMappingValidationTests.cs @@ -92,4 +92,44 @@ public sealed class GrpcDataMappingValidationTests errors.ShouldContain(e => e.Code == "DataMappingRootInvalid"); } + /// + /// An EMPTY DisplayNameOverride counts as "no override" (the rule both compose seams apply via + /// EquipmentReferenceMap.EffectiveName): the reference materialises under its tag's name, so a mapping + /// branch of that name collides. A bare ?? kept the empty string and never saw the collision. + /// + [Theory] + [InlineData("", "Speed", true)] // empty override ⇒ the reference is "Speed" ⇒ collision + [InlineData(null, "Speed", true)] + [InlineData("Other", "Speed", false)] // control: a real override moves the reference's name away + [InlineData("", "Free", false)] // control: no sibling of that name + public void Equipment_mapping_branch_collides_with_a_reference_by_its_effective_name(string? overrideName, string branch, bool collides) + { + var baseDraft = ValidDraft(); + var draft = new DraftSnapshot + { + GenerationId = 0, ClusterId = "cluster", + ClusterNodes = baseDraft.ClusterNodes, + DataConnections = baseDraft.DataConnections, + RemoteNamespaceMappings = baseDraft.RemoteNamespaceMappings, + UnsAreas = [new UnsArea { UnsAreaId = "area", ClusterId = "cluster", Name = "Area" }], + UnsLines = [new UnsLine { UnsLineId = "line", UnsAreaId = "area", Name = "Line" }], + Equipment = [new Equipment { EquipmentId = "eq", UnsLineId = "line", Name = "Eq", MachineCode = "EQ" }], + Tags = [new Tag { TagId = "tag", DeviceId = "dev", Name = "Speed", DataType = "Double", AccessLevel = TagAccessLevel.Read, TagConfig = "{}" }], + UnsTagReferences = [new UnsTagReference { UnsTagReferenceId = "ref", EquipmentId = "eq", TagId = "tag", DisplayNameOverride = overrideName }], + }; + var mapping = draft.RemoteNamespaceMappings[0]; + mapping.Realm = DataRealm.Uns; + mapping.RemoteRealm = DataRealm.Uns; + mapping.RemoteNamespaceUri = "https://zb.com/otopcua/uns"; + mapping.LocalParentKind = "Equipment"; + mapping.LocalParentId = "eq"; + mapping.BranchName = branch; + + var errors = DataConnectionValidator.Validate(draft); + + if (collides) errors.ShouldContain(e => e.Code == "DataMappingNameCollision"); + else errors.ShouldNotContain(e => e.Code == "DataMappingNameCollision"); + // Positive control that the parent resolved (the collision rule ran against a real equipment). + errors.ShouldNotContain(e => e.Code == "DataMappingParentInvalid"); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs index 52c8c20c8..b3ca6ad8a 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ProjectedHistoryReadTests.cs @@ -195,6 +195,38 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable access.Calls.ShouldBe(calls); } + /// U-7: an unconvertible ProcessingInterval on a projected node is a per-node BadInvalidArgument, never + /// sent remotely; the finite interval is the positive control that the same read is served. + [Theory] + [InlineData(60_000.0, true)] + [InlineData(double.NaN, false)] + [InlineData(double.PositiveInfinity, false)] + [InlineData(double.MaxValue, false)] + [Trait("Phase", "H3")] + public async Task A_projected_processed_read_with_an_unconvertible_interval_is_BadInvalidArgument_and_not_sent(double intervalMs, bool served) + { + var (nm, f) = await BootAsync(aclEnabled: false, NodePermissions.Browse | NodePermissions.Read | NodePermissions.HistoryRead); + var node = Project(nm, f, "Speed", historizing: true); + var access = new FakeAccess(); + nm.ProjectedHistoryAccess = access; + + var processed = new ReadProcessedDetails + { + StartTime = T0, EndTime = T0.AddHours(1), ProcessingInterval = intervalMs, + AggregateType = [ObjectIds.AggregateFunction_Average], + }; + var (_, errors) = Read(nm, f.Identity, processed, [node]); + + if (served) + { + access.Calls.ShouldBe(1); + return; + } + + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadInvalidArgument.Code); + access.Calls.ShouldBe(0); + } + [Fact] [Trait("Phase", "H3")] public async Task A_throw_while_serving_one_outcome_releases_every_later_outcomes_cursor() diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadTests.cs index b2bc11471..56a6bd806 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerHistoryReadTests.cs @@ -253,6 +253,53 @@ public sealed class NodeManagerHistoryReadTests : IDisposable await host.DisposeAsync(); } + /// + /// U-7: a NaN / infinite / oversized ProcessingInterval is a per-node BadInvalidArgument with the + /// backend never called — before the fix the unguarded TimeSpan.FromMilliseconds threw out of the + /// override and faulted the whole request. The finite interval in the first row is the positive control: the + /// same details shape dispatches normally. + /// + [Theory] + [InlineData(10_000.0, true)] + [InlineData(double.NaN, false)] + [InlineData(double.PositiveInfinity, false)] + [InlineData(double.NegativeInfinity, false)] + [InlineData(double.MaxValue, false)] + public async Task Processed_unconvertible_interval_is_BadInvalidArgument_per_node_and_never_reaches_the_backend( + double intervalMs, bool served) + { + var (host, server) = await BootAsync(); + var nm = server.NodeManager!; + var fake = new RecordingHistorianDataSource { ProcessedResult = Empty() }; + nm.HistorianDataSource = fake; + nm.EnsureVariable("eq-1/iv", parentFolderNodeId: null, displayName: "Iv", dataType: "Float", + writable: false, historianTagname: "WW.Iv", realm: AddressSpaceRealm.Uns); + var nodeId = nm.TryGetVariable("eq-1/iv")!.NodeId; + + var details = new ReadProcessedDetails + { + StartTime = DateTime.UtcNow.AddHours(-1), + EndTime = DateTime.UtcNow, + ProcessingInterval = intervalMs, + AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true }, + AggregateType = new List { ObjectIds.AggregateFunction_Average }, + }; + + var (_, errors) = InvokeHistoryRead(server, nm, details, nodeId); + + if (served) + { + fake.LastCall.ShouldBe("Processed"); + } + else + { + errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadInvalidArgument.Code); + fake.LastCall.ShouldBeNull(); + } + + await host.DisposeAsync(); + } + /// Processed read with an UNKNOWN aggregate NodeId ⇒ BadAggregateNotSupported; the source /// is never invoked. [Fact] diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ChildHealthLedgerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ChildHealthLedgerTests.cs new file mode 100644 index 000000000..98ef8012b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ChildHealthLedgerTests.cs @@ -0,0 +1,44 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; + +/// R-16: a stopped child's late health publish must not resurrect its ledger entry. +public sealed class ChildHealthLedgerTests +{ + private sealed class CountingPublisher : IDriverHealthPublisher + { + public int Count; + + public void Publish( + string clusterId, string driverInstanceId, DriverHealth health, int errorCount5Min, + DateTime? rediscoveryNeededUtc = null, string? rediscoveryReason = null, + IReadOnlyList? hostStatuses = null, SkippedTagReport? skippedTags = null, + IReadOnlyDictionary? diagnostics = null) => Count++; + } + + private static void Publish(ChildHealthLedger ledger, string id) => + ledger.Publish("c1", id, new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null), 0); + + [Fact] + public void A_late_publish_after_Forget_is_forwarded_but_not_recorded_until_Readmit() + { + var inner = new CountingPublisher(); + var ledger = new ChildHealthLedger(inner); + + Publish(ledger, "d1"); + ledger.TryGet("d1").ShouldNotBeNull(); // positive control: the ledger records when not held + + ledger.Forget("d1"); + ledger.TryGet("d1").ShouldBeNull(); + Publish(ledger, "d1"); // the stopping child's late publish + ledger.TryGet("d1").ShouldBeNull(); + inner.Count.ShouldBe(2); // still forwarded — the hub tombstones its own side + + ledger.Readmit("d1"); // a new child of the id spawns + Publish(ledger, "d1"); + ledger.TryGet("d1").ShouldNotBeNull(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorVirtualTagTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorVirtualTagTests.cs index 7b7a2a8ff..111748d3f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorVirtualTagTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorVirtualTagTests.cs @@ -110,6 +110,73 @@ public sealed class DriverHostActorVirtualTagTests : RuntimeActorTestBase .ShouldBe(new[] { ("vt-1", true), ("vt-off", false) }); } + /// + /// A supervision restart builds a VirtualTag host with NO children and no definitions (Akka's default + /// PreRestart stops them) and nothing re-sent ApplyVirtualTags, so every VirtualTag on the node + /// went dark until the next deploy. Mirrors the scripted-alarm host's restart handling: the host tells its parent + /// from PostRestart and the + /// re-sends the last plans. REAL host, real crash, no manual re-apply. + /// + [Fact] + public async Task After_a_supervision_restart_the_virtual_tag_host_is_re_applied() + { + var db = NewInMemoryDbFactory(); + var deploymentId = SeedDeploymentWithVirtualTag(db, RevA); + var publish = this.CreateCleanOutcomePublishProbe(); + var mux = CreateTestProbe(); + var coordinator = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, + localRoles: new HashSet { "driver" }, + dependencyMux: mux.Ref, + opcUaPublishActor: publish.Ref, + virtualTagEvaluator: NullVirtualTagEvaluator.Instance)); + V3ArtifactSeeder.Dispatch(host, coordinator, deploymentId, RevA); + + var first = mux.FishForMessage( + r => r.TagRefs.Contains("TestMachine_001.TestDouble"), TimeSpan.FromSeconds(30), cancellationToken: TestContext.Current.CancellationToken); + var vtHost = await Sys.ActorSelection(first.Subscriber.Path.Parent).ResolveOne(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + + // The crash: a result with a null VirtualTagId throws out of the host's dictionary lookup, so supervision + // restarts it (stopping its child). NO manual re-apply follows. + vtHost.Tell(new VirtualTagActor.EvaluationResult(null!, 1.0, DateTime.UtcNow, CorrelationId.NewId())); + mux.FishForMessage( + u => u.Subscriber.Equals(first.Subscriber), TimeSpan.FromSeconds(30), cancellationToken: TestContext.Current.CancellationToken); + + // The parent re-applies on the restart signal: a NEW child registers its interest again. + var second = mux.FishForMessage( + r => r.TagRefs.Contains("TestMachine_001.TestDouble") && !r.Subscriber.Equals(first.Subscriber), + TimeSpan.FromSeconds(30), cancellationToken: TestContext.Current.CancellationToken); + second.Subscriber.ShouldNotBe(first.Subscriber); + } + + /// The parent honours only the CURRENT host's restart signal and re-sends exactly the last applied plans + /// (an unrelated sender is ignored — positive and negative in one sequence). + [Fact] + public void A_restart_signal_re_sends_the_last_plans_but_only_from_the_current_host() + { + var db = NewInMemoryDbFactory(); + var deploymentId = SeedDeploymentWithVirtualTag(db, RevA); + var coordinator = CreateTestProbe(); + var vtHost = CreateTestProbe(); + var stranger = CreateTestProbe(); + var actor = Sys.ActorOf(DriverHostActor.Props( + db, TestNode, coordinator.Ref, + localRoles: new HashSet { "driver" }, + virtualTagEvaluator: NullVirtualTagEvaluator.Instance, + virtualTagHostOverride: vtHost.Ref)); + actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId())); + coordinator.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + vtHost.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + + actor.Tell(VirtualTagHostActor.VirtualTagHostRestarted.Instance, stranger.Ref); + vtHost.ExpectNoMsg(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken); + + actor.Tell(VirtualTagHostActor.VirtualTagHostRestarted.Instance, vtHost.Ref); + vtHost.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken) + .Plans.ShouldHaveSingleItem().VirtualTagId.ShouldBe("vt-1"); + } + private static DeploymentId SeedDeploymentWithVirtualTag( IDbContextFactory db, RevisionHash rev, bool withDisabledSibling = false) { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs index ca7eb36e4..0cc882c55 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostCommsLossRecoveryTests.cs @@ -114,6 +114,49 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase "the child must actually have re-subscribed — otherwise this proves nothing about the push"); } + /// + /// R-16: a driver REMOVED by a deploy while its comms latch is outstanding must take the latch and its + /// armed recovery-audit timer with it. Same silent-resubscribe setup as the control above (which proves + /// that, left alone, this very scenario trips the audit) — the only difference is the removal landing + /// inside the audit window. + /// + [Fact] + public void Removing_a_comms_lost_driver_cancels_its_audit_and_leaves_no_false_warning_or_metric() + { + var driver = new ScriptedSubscribeDriver { InstanceId = "drv-removed", InitialPush = null }; + var db = NewInMemoryDbFactory(); + var deploymentId = SeedV3Deployment(db, RevA, + rawTags: new[] { (Driver: "drv-removed", DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false) }, + unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null) }, + enabled: true); + var revB = RevisionHash.Parse(new string('e', 64)); + var emptyDeployment = SeedV3Deployment(db, revB, + rawTags: Array.Empty<(string, string, string, string, string, bool)>(), + unsRefs: Array.Empty<(string, string, string, string, string?)>(), + enabled: true); + + // Audit window long enough that the removal (immediately after the reconnect) is well inside it. + var audit = TimeSpan.FromSeconds(6); + var (host, publish, _, coordinator) = SpawnHostAndApplyWithCoordinator( + this, db, TestNode, deploymentId, RevA, + driverFactory: new SingleDriverFactory(driver), commsRecoveryAuditDelay: audit); + AwaitCondition(() => driver.SubscribeCount >= 1, PresenceBudget, TestContext.Current.CancellationToken); + using var meter = new MeterRecorder("otopcua.driver.comms_latched_refs"); + + host.Tell(new ReconnectDriver("c1", "drv-removed", "test-operator", Guid.NewGuid())); + publish.FishForMessage(_ => true, ReconnectBudget, cancellationToken: TestContext.Current.CancellationToken); + + // The reconnect arms the audit; remove the driver inside its window. + AwaitCondition(() => driver.SubscribeCount >= 2, ReconnectBudget, TestContext.Current.CancellationToken); + Dispatch(host, coordinator, emptyDeployment, revB); + + // Positive control: the audit window really elapses (a fake clock would not prove it) — so silence + // here is the cancelled timer, not an unfinished wait. + EventFilter.Warning(contains: "still BadNoCommunication") + .Expect(0, audit + TimeSpan.FromSeconds(3), () => { }, TestContext.Current.CancellationToken); + meter.SumWithTag("driver_instance", "drv-removed").ShouldBe(0); + } + private (IActorRef Host, Akka.TestKit.TestProbe Publish) Arrange(ScriptedSubscribeDriver driver, string driverId) { var db = NewInMemoryDbFactory(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs index d5edc255a..798968248 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Harness/V3ArtifactSeeder.cs @@ -219,10 +219,12 @@ public static class V3ArtifactSeeder TestKitBase kit, IDbContextFactory db, NodeId localNode, DeploymentId deploymentId, RevisionHash rev, IDriverFactory? driverFactory = null, - TimeSpan? reprovisionBackoff = null) + TimeSpan? reprovisionBackoff = null, + TimeSpan? commsRecoveryAuditDelay = null) { var publish = kit.CreateCleanOutcomePublishProbe(); - var (actor, mux, coordinator) = Spawn(kit, db, localNode, publish.Ref, driverFactory, reprovisionBackoff); + var (actor, mux, coordinator) = + Spawn(kit, db, localNode, publish.Ref, driverFactory, reprovisionBackoff, commsRecoveryAuditDelay); Dispatch(actor, coordinator, deploymentId, rev); publish.ExpectMsg(RuntimeActorTestBase.PresenceBudget); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/ContinuousHistorizationRecorderBacklogDrainTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/ContinuousHistorizationRecorderBacklogDrainTests.cs new file mode 100644 index 000000000..10c771324 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/ContinuousHistorizationRecorderBacklogDrainTests.cs @@ -0,0 +1,37 @@ +using Akka.TestKit.Xunit; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Runtime.Historian; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Historian; + +/// +/// R-25: a successful FULL batch re-ticks immediately instead of waiting out the drain interval, so catching up a +/// backlog is bounded by the writer, not by drainBatchSize / drainInterval. +/// +public sealed class ContinuousHistorizationRecorderBacklogDrainTests : TestKit +{ + private static readonly DateTime T0 = new(2026, 12, 3, 8, 0, 0, DateTimeKind.Utc); + + [Fact] + public void A_backlog_larger_than_one_batch_drains_without_waiting_for_the_interval() + { + var log = new EventLog(); + var outbox = new LoggingOutbox(log); + var writer = new LoggingPassWriter(log); + var tags = Enumerable.Range(0, 7).Select(i => $"T{i}").ToArray(); + + // A 30 s interval: four passes at batch size 2 can only finish inside the 10 s wait by re-ticking. + var rec = Sys.ActorOf(ContinuousHistorizationRecorder.Props( + CreateTestProbe().Ref, writer, outbox, historizedRefs: tags, drainBatchSize: 2, + drainInterval: TimeSpan.FromSeconds(30))); + rec.Tell(new VirtualTagActor.DependencyValueBatch( + tags.Select((t, i) => new VirtualTagActor.DependencyValueChanged(t, (double)i, T0.AddSeconds(i))).ToList()), TestActor); + + // Appended first: an outbox that has not been appended to yet is trivially empty. + AwaitAssert(() => outbox.Appended.Count.ShouldBe(7), TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => outbox.Entries.ShouldBeEmpty(), TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken); + log.Snapshot().Count(e => e.StartsWith("write:")).ShouldBe(7); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs index 0e35fffb5..0061a39d6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs @@ -115,6 +115,39 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase sink.Marks.ShouldBe(["drv-1"]); // the scripted source's mark was discarded; the unrelated source's applied } + /// + /// R-18: a KEPT condition (it stood before the apply and stands after it — the normal case on a surgical or + /// no-artifact apply) lands its live write directly, so its deferred alarm being outside the replay scope is NOT a + /// lost projection. Before the fix the source's deferred known mark was discarded, the host was told + /// ConditionMarksDiscarded and its conditions went back into the F5 window with a false warning. + /// (The out-of-scope control above — a condition that exists in neither composition — still discards.) + /// + [Fact] + public void A_kept_conditions_deferred_mark_is_replayed_not_discarded_on_a_non_rebuild_apply() + { + var sink = new OrderSink(); + using var gate = new ManualResetEventSlim(true); + var actor = Spawn(sink, gate); + + actor.Tell(Rebuild()); // establishes al-1 (scripted) in the composition + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + sink.ConditionExists("al-1").ShouldBeTrue(); + + gate.Reset(); + actor.Tell(Rebuild()); // identical artifact: a no-op apply, al-1 is KEPT + actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1")); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns)); + // Live-applied while the plan is held open (the node exists). + AwaitAssert(() => sink.Marks.Count.ShouldBe(1), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + gate.Set(); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + ExpectNoMsg(TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken); // no ConditionMarksDiscarded + sink.Marks.Count.ShouldBe(2, "the deferred mark replayed after the apply as well"); + sink.IsKnown("al-1").ShouldBeTrue(); + } + [Fact] public void A_withdrawal_reaches_MarkConditionsUnknown() {