Merge #1002: StopChild clears comms latch + timer, kept alarm marks replayed, recorder catch-up uncapped, HistoryRead bad interval refused, VirtualTag host re-applied after restart, EffectiveName everywhere
This commit is contained in:
@@ -565,6 +565,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
|
||||
|
||||
+4
-1
@@ -318,7 +318,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. |
|
||||
@@ -1459,6 +1459,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
|
||||
|
||||
@@ -323,6 +323,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT
|
||||
- **`{{equip}}/<Name>` 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.
|
||||
|
||||
@@ -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
|
||||
};
|
||||
}
|
||||
|
||||
@@ -16,6 +16,20 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
/// </summary>
|
||||
internal abstract record HistoryReadVariant
|
||||
{
|
||||
/// <summary>
|
||||
/// U-7: whether a client's raw <c>ProcessingInterval</c> (a <see cref="double"/> of milliseconds) converts to a
|
||||
/// <see cref="TimeSpan"/>. <c>TimeSpan.FromMilliseconds</c> 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.
|
||||
/// </summary>
|
||||
/// <param name="milliseconds">The wire value.</param>
|
||||
/// <returns>True when <see cref="From"/> / the remote mapping will not throw.</returns>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>Maps the SDK's <see cref="HistoryReadDetails"/> onto the port variant the overrides serve.</summary>
|
||||
/// <param name="details">Raw/modified, Processed or AtTime details.</param>
|
||||
/// <returns>The equivalent variant.</returns>
|
||||
|
||||
@@ -35,6 +35,15 @@ public sealed partial class OtOpcUaNodeManager
|
||||
IList<SdkHistoryReadResult> results,
|
||||
IList<ServiceResult> 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<NodeHandle>? projected = null;
|
||||
foreach (var handle in nodesToProcess)
|
||||
if (IsProjectedDescendant(handle.NodeId)) (projected ??= []).Add(handle);
|
||||
|
||||
+1
-1
@@ -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),
|
||||
|
||||
@@ -56,6 +56,9 @@ public sealed class SourceSamplePublisher
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<BackingSourceKey, SourceTicket> _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<string, Dictionary<string, BackingSourceKey>> _driverKeys = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, BackingSourceKey> _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<string, BackingSourceKey>(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); }
|
||||
}
|
||||
/// <summary>A snapshot of <paramref name="driver"/>'s bound source keys. Caller holds <c>_gate</c>.</summary>
|
||||
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;
|
||||
|
||||
@@ -26,13 +26,16 @@ public sealed record ChildHealthRecord(
|
||||
/// <remarks>
|
||||
/// Deliberately NOT a message to the host: the children already publish through this seam on every
|
||||
/// change, so a parallel <c>Tell</c> 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 <see cref="Readmit"/>.
|
||||
/// </remarks>
|
||||
public sealed class ChildHealthLedger : IDriverHealthPublisher
|
||||
{
|
||||
private readonly IDriverHealthPublisher _inner;
|
||||
private readonly ConcurrentDictionary<string, ChildHealthRecord> _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<string, byte> _held = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Wraps <paramref name="inner"/>.</summary>
|
||||
/// <param name="inner">The publisher every snapshot is forwarded to.</param>
|
||||
@@ -54,8 +57,9 @@ public sealed class ChildHealthLedger : IDriverHealthPublisher
|
||||
SkippedTagReport? skippedTags = null,
|
||||
IReadOnlyDictionary<string, string>? 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;
|
||||
|
||||
/// <summary>Forgets <paramref name="driverInstanceId"/>'s snapshot (the child was stopped).</summary>
|
||||
/// <summary>
|
||||
/// Forgets <paramref name="driverInstanceId"/>'s snapshot (the child was stopped) and HOLDS the id: a late
|
||||
/// publish from the stopping child is forwarded but no longer recorded, until <see cref="Readmit"/>.
|
||||
/// </summary>
|
||||
/// <param name="driverInstanceId">The driver instance.</param>
|
||||
public void Forget(string driverInstanceId) => _last.TryRemove(driverInstanceId, out _);
|
||||
public void Forget(string driverInstanceId)
|
||||
{
|
||||
_held[driverInstanceId] = 0;
|
||||
_last.TryRemove(driverInstanceId, out _);
|
||||
}
|
||||
|
||||
/// <summary>Lifts the hold <see cref="Forget"/> placed, because a new child of the id is being spawned.</summary>
|
||||
/// <param name="driverInstanceId">The driver instance.</param>
|
||||
public void Readmit(string driverInstanceId) => _held.TryRemove(driverInstanceId, out _);
|
||||
}
|
||||
|
||||
@@ -331,6 +331,10 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// first apply.</summary>
|
||||
private IReadOnlyList<EquipmentScriptedAlarmPlan>? _lastScriptedAlarmPlans;
|
||||
|
||||
/// <summary>The VirtualTag plans last sent to <see cref="_virtualTagHost"/>, re-sent when it reports a supervision
|
||||
/// restart (<see cref="VirtualTagHostActor.VirtualTagHostRestarted"/>). Null until the first apply.</summary>
|
||||
private IReadOnlyList<EquipmentVirtualTagPlan>? _lastVirtualTagPlans;
|
||||
|
||||
private RevisionHash? _currentRevision;
|
||||
|
||||
/// <summary>
|
||||
@@ -1841,6 +1845,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
Receive<DrainProjectedRetirements>(RetireProjected);
|
||||
Receive<Terminated>(OnRetiredChildTerminated);
|
||||
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
|
||||
Receive<VirtualTagHostActor.VirtualTagHostRestarted>(_ => HandleVirtualTagHostRestarted());
|
||||
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
|
||||
Receive<DriverInstanceActor.ConnectivityChanged>(OnDriverConnectivityChanged);
|
||||
ReceiveConditionSignals();
|
||||
@@ -1923,6 +1928,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
Receive<DrainProjectedRetirements>(RetireProjected);
|
||||
Receive<Terminated>(OnRetiredChildTerminated);
|
||||
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
|
||||
Receive<VirtualTagHostActor.VirtualTagHostRestarted>(_ => HandleVirtualTagHostRestarted());
|
||||
Receive<DriverInstanceActor.AttributeAlarmPublished>(ForwardNativeAlarm);
|
||||
Receive<DriverInstanceActor.ConnectivityChanged>(OnDriverConnectivityChanged);
|
||||
ReceiveConditionSignals();
|
||||
@@ -3057,6 +3063,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_localNode, m.Items.Count, m.DriverInstanceId));
|
||||
Receive<Terminated>(OnRetiredChildTerminated);
|
||||
Receive<ScriptedAlarmHostActor.ScriptedAlarmHostRestarted>(_ => HandleScriptedAlarmHostRestarted());
|
||||
Receive<VirtualTagHostActor.VirtualTagHostRestarted>(_ => HandleVirtualTagHostRestarted());
|
||||
Receive<DriverInstanceActor.AttributeAlarmPublished>(m =>
|
||||
_log.Debug("DriverHost {Node}: dropping a native alarm transition ({Cond}) from {Id} while Stale",
|
||||
_localNode, m.Args.ConditionId, m.DriverInstanceId));
|
||||
@@ -4324,6 +4331,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)
|
||||
{
|
||||
@@ -4698,6 +4706,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)
|
||||
@@ -4875,6 +4884,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);
|
||||
}
|
||||
@@ -4927,6 +4942,23 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_scriptedAlarmHost.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms(_lastScriptedAlarmPlans));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>A retired child has terminated; nothing more can arrive from it.</summary>
|
||||
/// <param name="msg">The termination notice.</param>
|
||||
private void OnRetiredChildTerminated(Terminated msg) => _retiredChildren.Remove(msg.ActorRef);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
/// <summary>Every condition id a composition materialises: enabled scripted alarms (Uns) and native alarms (Raw).</summary>
|
||||
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)
|
||||
|
||||
@@ -47,6 +47,21 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
/// <param name="Plans">The desired Equipment-namespace VirtualTag plans.</param>
|
||||
public sealed record ApplyVirtualTags(IReadOnlyList<EquipmentVirtualTagPlan> Plans);
|
||||
|
||||
/// <summary>
|
||||
/// Told to the parent from <see cref="PostRestart"/> (mirrors <c>ScriptedAlarmHostActor.ScriptedAlarmHostRestarted</c>).
|
||||
/// A supervision restart is otherwise invisible to the parent and the new incarnation has NO children (Akka's
|
||||
/// default <c>PreRestart</c> stops them) and no definitions, so every VirtualTag on the node would stop
|
||||
/// evaluating until the next deploy. The parent (<c>DriverHostActor</c>) answers by re-sending the last
|
||||
/// <see cref="ApplyVirtualTags"/> it sent.
|
||||
/// </summary>
|
||||
public sealed class VirtualTagHostRestarted
|
||||
{
|
||||
/// <summary>The single instance.</summary>
|
||||
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<string> _publishedVirtualIds = new(StringComparer.Ordinal);
|
||||
@@ -113,6 +128,14 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
Receive<Terminated>(OnChildTerminated);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>Tells the parent <see cref="VirtualTagHostRestarted"/> so it re-sends the last <see cref="ApplyVirtualTags"/>.</remarks>
|
||||
protected override void PostRestart(Exception reason)
|
||||
{
|
||||
base.PostRestart(reason);
|
||||
Context.Parent.Tell(VirtualTagHostRestarted.Instance);
|
||||
}
|
||||
|
||||
private void OnApply(ApplyVirtualTags msg)
|
||||
{
|
||||
Timers.Cancel("source-binding-retry");
|
||||
|
||||
+40
@@ -92,4 +92,44 @@ public sealed class GrpcDataMappingValidationTests
|
||||
errors.ShouldContain(e => e.Code == "DataMappingRootInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An EMPTY <c>DisplayNameOverride</c> counts as "no override" (the rule both compose seams apply via
|
||||
/// <c>EquipmentReferenceMap.EffectiveName</c>): the reference materialises under its tag's name, so a mapping
|
||||
/// branch of that name collides. A bare <c>??</c> kept the empty string and never saw the collision.
|
||||
/// </summary>
|
||||
[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");
|
||||
}
|
||||
}
|
||||
|
||||
+32
@@ -195,6 +195,38 @@ public sealed class ProjectedHistoryReadTests : IAsyncDisposable
|
||||
access.Calls.ShouldBe(calls);
|
||||
}
|
||||
|
||||
/// <summary>U-7: an unconvertible <c>ProcessingInterval</c> 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.</summary>
|
||||
[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()
|
||||
|
||||
@@ -253,6 +253,53 @@ public sealed class NodeManagerHistoryReadTests : IDisposable
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// U-7: a NaN / infinite / oversized <c>ProcessingInterval</c> is a per-node <c>BadInvalidArgument</c> with the
|
||||
/// backend never called — before the fix the unguarded <c>TimeSpan.FromMilliseconds</c> 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.
|
||||
/// </summary>
|
||||
[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<NodeId> { 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();
|
||||
}
|
||||
|
||||
/// <summary>Processed read with an UNKNOWN aggregate NodeId ⇒ BadAggregateNotSupported; the source
|
||||
/// is never invoked.</summary>
|
||||
[Fact]
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>R-16: a stopped child's late health publish must not resurrect its ledger entry.</summary>
|
||||
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<HostConnectivityStatus>? hostStatuses = null, SkippedTagReport? skippedTags = null,
|
||||
IReadOnlyDictionary<string, string>? 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();
|
||||
}
|
||||
}
|
||||
+67
@@ -110,6 +110,73 @@ public sealed class DriverHostActorVirtualTagTests : RuntimeActorTestBase
|
||||
.ShouldBe(new[] { ("vt-1", true), ("vt-off", false) });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A supervision restart builds a VirtualTag host with NO children and no definitions (Akka's default
|
||||
/// <c>PreRestart</c> stops them) and nothing re-sent <c>ApplyVirtualTags</c>, 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
|
||||
/// <see cref="VirtualTagHostActor.VirtualTagHostRestarted"/> from <c>PostRestart</c> and the
|
||||
/// <see cref="DriverHostActor"/> re-sends the last plans. REAL host, real crash, no manual re-apply.
|
||||
/// </summary>
|
||||
[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<string> { "driver" },
|
||||
dependencyMux: mux.Ref,
|
||||
opcUaPublishActor: publish.Ref,
|
||||
virtualTagEvaluator: NullVirtualTagEvaluator.Instance));
|
||||
V3ArtifactSeeder.Dispatch(host, coordinator, deploymentId, RevA);
|
||||
|
||||
var first = mux.FishForMessage<DependencyMuxActor.RegisterInterest>(
|
||||
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<DependencyMuxActor.UnregisterInterest>(
|
||||
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<DependencyMuxActor.RegisterInterest>(
|
||||
r => r.TagRefs.Contains("TestMachine_001.TestDouble") && !r.Subscriber.Equals(first.Subscriber),
|
||||
TimeSpan.FromSeconds(30), cancellationToken: TestContext.Current.CancellationToken);
|
||||
second.Subscriber.ShouldNotBe(first.Subscriber);
|
||||
}
|
||||
|
||||
/// <summary>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).</summary>
|
||||
[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<string> { "driver" },
|
||||
virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
|
||||
virtualTagHostOverride: vtHost.Ref));
|
||||
actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()));
|
||||
coordinator.ExpectMsg<ApplyAck>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
|
||||
vtHost.ExpectMsg<VirtualTagHostActor.ApplyVirtualTags>(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<VirtualTagHostActor.ApplyVirtualTags>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Plans.ShouldHaveSingleItem().VirtualTagId.ShouldBe("vt-1");
|
||||
}
|
||||
|
||||
private static DeploymentId SeedDeploymentWithVirtualTag(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev, bool withDisabledSibling = false)
|
||||
{
|
||||
|
||||
+43
@@ -114,6 +114,49 @@ public sealed class DriverHostCommsLossRecoveryTests : RuntimeActorTestBase
|
||||
"the child must actually have re-subscribed — otherwise this proves nothing about the push");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<OpcUaPublishActor.AttributeStatusBatchUpdate>(_ => 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();
|
||||
|
||||
@@ -219,10 +219,12 @@ public static class V3ArtifactSeeder
|
||||
TestKitBase kit, IDbContextFactory<OtOpcUaConfigDbContext> 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<OpcUaPublishActor.RebuildAddressSpace>(RuntimeActorTestBase.PresenceBudget);
|
||||
|
||||
+37
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>drainBatchSize / drainInterval</c>.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
+33
@@ -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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <c>ConditionMarksDiscarded</c> 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.)
|
||||
/// </summary>
|
||||
[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<OpcUaPublishActor.RebuildCompleted>(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<OpcUaPublishActor.RebuildCompleted>(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()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user