Merge #995: alarm predicates compiled once outside the gate, node-indexed stood-down items, kept drivers not re-subscribed, artifact parsed once, VirtualTag/Calculation evaluation coalesced
This commit is contained in:
@@ -276,10 +276,16 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
|
||||
FOCAS's is PAUSED, its told record kept, #647) — the device-state half of `ShutdownAsync` only; the poll engine is kept and the actor re-subscribes
|
||||
after every successful init. AbCip publishes fresh tag tables by reference swap (a second init used to throw
|
||||
"tag name collision"); S7 swaps `Plc` under `_gate`.
|
||||
- **Data and alarm subscriptions are independent in `DriverInstanceActor` (#662):** a data re-subscribe (every
|
||||
deploy's bulk push to a kept driver) detaches DATA only (`DetachDataSubscription`) — it used to unhook
|
||||
- **Data and alarm subscriptions are independent in `DriverInstanceActor` (#662):** a data re-subscribe (a
|
||||
deploy's bulk push to a kept driver — since #995 only when something it seeds changed, see below) detaches DATA only (`DetachDataSubscription`) — it used to unhook
|
||||
`OnAlarmEvent` too, silently killing the native-alarm feed until a respawn. The health-poll reconcile
|
||||
re-attaches/re-subscribes alarms as well as data, so a failed alarm subscribe is retried every tick.
|
||||
- **An untouched kept driver is not re-subscribed by a deploy (#995 R-11).** The bulk push skips a child whose
|
||||
seeding fingerprint (value refs + each ref's raw/UNS fan-out + historization + alarm refs) is unchanged and none of
|
||||
whose refs gained a mux consumer (VirtualTag / scripted alarm / `IDependencyConsumer` driver); skipped drivers are
|
||||
re-pushed after the address-space outcome if it was a rebuild (`RebuildCompleted.AddressSpaceRebuilt`), degraded,
|
||||
timed out, or the apply threw. A new mux value consumer must join `DriverHostActor.ConsumerRefs`.
|
||||
`docs/DriverLifecycle.md` §"A deploy no longer re-subscribes an untouched driver".
|
||||
- **A config change is a respawn — there is NO in-place path (#665).** The `ApplyDelta`/`ApplyResult`/`DeltaApplied`
|
||||
seam (host `ApplyChildDelta`, `DriverSpawnPlan.ToApplyDelta`, the actor's Connected reinit and mid-connect
|
||||
`AdoptConfigDuringInit`) was unreachable since #516 and is deleted; #663/#664 were latent bugs in it. `IDriver.ReinitializeAsync`
|
||||
|
||||
+18
-1
@@ -188,7 +188,7 @@ routes it to `Unsubscribe`, dropping a stale handle.)
|
||||
|
||||
| Route | Trigger | What re-provisions it |
|
||||
|---|---|---|
|
||||
| **Deploy reconcile** | `ApplyDriverSpecs` → `SpawnChild` | `SpawnChild` sends `InitializeRequested` then the desired set; the apply's bulk push then sends the (freshly rebuilt) set to every child. |
|
||||
| **Deploy reconcile** | `ApplyDriverSpecs` → `SpawnChild` | `SpawnChild` sends `InitializeRequested` then the desired set; the apply's bulk push then sends the (freshly rebuilt) set to every child **that needs it** (#995, below). |
|
||||
| **Operator Restart** | `/hosts` → Restart → `HandleRestartDriver` | Stops the child, respawns from the cached spec — and `SpawnChild` sends the desired set, because it always does. **This is the 03/S16 fix**: there is no bulk push on this path, and before it the respawned child subscribed to nothing until the next deployment. |
|
||||
| **Supervision restart** | a child throws ⇒ Akka's **default decider** ⇒ `Restart` | `DriverInstanceActor.PostRestart` Tells the host `ReprovisionRequested`; `HandleReprovisionRequested` logs a Warning naming the crash type, re-sends `InitializeRequested` (non-stub children) and the desired set. |
|
||||
| **Force Reconnect** | `/hosts` → Force Reconnect → `HandleReconnectDriver` | **Nothing — verified.** It Tells `ForceReconnect` to the *same* child actor, so the instance and its `_desiredRefs`/`_desiredAlarmRefs` survive and the reconnect's Connected entry re-applies them itself. Pinned by `Force_reconnect_keeps_the_desired_set_and_re_subscribes` so a future edit to the restart paths cannot break the one that was already correct. |
|
||||
@@ -252,6 +252,23 @@ Things to know before touching any of this:
|
||||
re-subscribing** so a filtering driver does not accumulate two overlapping ones. There is still
|
||||
deliberately no unsubscribe-on-**empty**: a removed alarm tag's condition node is torn down on the
|
||||
address-space rebuild and `ForwardNativeAlarm` drops any transition whose `ConditionId` no longer maps.
|
||||
- **A deploy no longer re-subscribes an untouched driver (#995, review 2026-12-02 R-11).** A re-subscribe tears down
|
||||
the driver's whole data subscription (OpcUaClient monitored items, Galaxy advise through mxaccessgw, a forced
|
||||
full re-read) and leaves a gap; on a kept driver whose set did not change its only job is **seeding** — the
|
||||
initial values it produces give a node or consumer that is new since the last apply its first value. So the
|
||||
deploy path (`HandleArtifactForApply` → `ApplyDesiredSubscriptions(skipUnchanged: true)`) skips a child only when
|
||||
ALL hold: it is the child that already got a plain (non-acquisition) set from this host (`_plainPushedTo` — a
|
||||
respawn is a new actor and is always pushed); its **seeding fingerprint** is unchanged (value refs, each ref's
|
||||
fan-out NodeIds — raw + every referencing UNS mirror, so an added/re-pointed mirror re-pushes — its
|
||||
historization, and the alarm refs); and none of its value refs **entered the mux-consumer set** (enabled
|
||||
VirtualTag / scripted-alarm deps + every hosted `IDependencyConsumer` driver's refs — the mux replays a retained
|
||||
value only for refs a replay-opting subscriber already named). A **full rebuild** recreates every node without a
|
||||
value, and only the publish actor knows whether the apply was one, so skipped drivers are held per correlation and
|
||||
re-pushed when `RebuildCompleted.AddressSpaceRebuilt` (additive, default `true`) or `Degraded` says so, when the
|
||||
outcome times out, or when the apply throws. Boot/restore applies still push every child. Pinned by
|
||||
`DriverHostActorUnchangedResubscribeTests` (absence + mirror / VirtualTag / rebuild / degraded positive controls).
|
||||
⚠️ A NEW kind of value consumer (something that registers driver refs with the mux and needs a first value) must
|
||||
join `ConsumerRefs`, or its first deploy leaves it waiting for the next value change.
|
||||
- ⚠️ **A data re-subscribe must not touch the alarm feed (#662).** Every deploy's bulk push re-sends
|
||||
`SetDesiredSubscriptions` to every kept driver, and `HandleSubscribeAsync` drops the prior DATA
|
||||
subscription first. That teardown used to be the full `DetachSubscription`, which also unhooked
|
||||
|
||||
@@ -587,7 +587,7 @@ In the v2 actor system, scripted-alarm engine composition is owned by the driver
|
||||
1. The host reads the generation's `ScriptedAlarm` + `Script` rows and resolves each row's `PredicateScriptId` to produce a `ScriptedAlarmDefinition` list. Unknown or disabled scripts fail fast — the DB publish guarantees referential integrity but this is a belt-and-braces check.
|
||||
2. A `ScriptedAlarmEngine` is constructed with the upstream-tag source, an `IAlarmStateStore` (production: `LocalDbAlarmConditionStateStore`), a shared `ScriptLoggerFactory` keyed to `scripts-*.log`, and the root Serilog logger.
|
||||
3. `alarmEngine.OnEvent` is wired to the historian sink. Fire-and-forget — the SQLite store-and-forward sink is already non-blocking.
|
||||
4. `LoadAsync(alarmDefs)` runs on startup and on every deploy: it compiles every predicate, subscribes to the union of predicate inputs and message-template tokens, seeds the value cache, seeds each alarm's condition (`previous ?? persisted ?? Fresh`, #935), re-derives `ActiveState` from a fresh predicate evaluation, and starts the 5s shelving timer. Compile failures are aggregated into one `InvalidOperationException` so operators see every bad predicate in one startup log line rather than one at a time.
|
||||
4. `LoadAsync(alarmDefs)` runs on startup and on every deploy: it compiles every predicate whose source it does not already hold (#995 K-3 — the compile cache is keyed by source hash and kept across deploys; a reload drops only the compiles no definition references any more, releasing their collectible ALCs; out of process the host's validation compile is remembered the same way), then subscribes to the union of predicate inputs and message-template tokens, seeds the value cache, seeds each alarm's condition (`previous ?? persisted ?? Fresh`, #935), re-derives `ActiveState` from a fresh predicate evaluation, and starts the 5s shelving timer. Compile failures are aggregated into one `InvalidOperationException` so operators see every bad predicate in one startup log line rather than one at a time. **Compiling runs before the engine gate is taken** (on the thread pool, bounded parallelism), so operator commands and re-evaluations keep running against the live generation while the new one compiles and only the swap holds the gate; a command that lands in that window is carried over by the swap like any other survivor state. Measured (500 alarms, distinct predicates, in process): a reload of unchanged definitions went from ~1.3 s under the gate to ~15 ms, and an acknowledge issued during an all-new reload waited ~1 ms instead of ~0.8 s.
|
||||
5. A `ScriptedAlarmSource` is created for the event stream. The v2 `ScriptedAlarmActor` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmActor.cs`) owns the active-state surface for OPC UA variable reads on the alarm's condition-state node — unknown alarm ids return `BadNodeIdUnknown` rather than silently reading `false`.
|
||||
|
||||
Both engine and source are disposed on server shutdown via the driver-role host teardown path.
|
||||
|
||||
+4
-3
@@ -175,8 +175,8 @@ processes:
|
||||
- **Batch submit (design §4.5).** `IScriptRunner.RunBatch` submits several evaluations at once: every item that is ready
|
||||
to run (its key loaded in a live worker, not a suspect) goes out in ONE `EvalBatch` frame per worker, and results are
|
||||
per item and streamed. The Calculation pump dequeues everything pending and submits it as one batch, publishing in
|
||||
dequeue order (a tag queued twice ends the batch, so every queued evaluation still runs against the snapshot that
|
||||
triggered it); the virtual-tag seam coalesces evaluations that become ready together (one actor per tag) into one
|
||||
dequeue order (the queue is latest-wins per calc tag since #995, so a batch never names a tag twice and each entry's
|
||||
snapshot is taken as it is dequeued); the virtual-tag seam coalesces evaluations that become ready together (one actor per tag) into one
|
||||
batch, with no timer; the scripted-alarm engine submits a pass's whole dirty set. In process the pump and the engine
|
||||
stay one-at-a-time, unchanged. **Per-item deadlines and blame stay exact:** an evaluation that arrives while every
|
||||
evaluation thread is busy is reported back as *deferred*, the host stops its clock, and restarts T and G when the worker
|
||||
@@ -313,7 +313,8 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT
|
||||
`ITagUpstreamSource` and `IHistoryWriter` are the two ports value consumers require from their host. Both live in `Core.VirtualTags`. In the v2 actor system:
|
||||
|
||||
- **Upstream-tag feed.** `DependencyMuxActor` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs`) routes the items of each `DriverInstanceActor.AttributeValueBatchPublished` — and every VirtualTag output (`VirtualTagOutput`, lmxopcua#791, see below) — to the `VirtualTagActor` instances that declared interest in those tag refs. Each `VirtualTagActor` holds the in-memory per-tag dependency map; the `IVirtualTagEvaluator` (`RoslynVirtualTagEvaluator`) receives the dependency snapshot through `EvaluateAsync`. Reads of never-pushed dependency refs return `null` values in the dependency snapshot.
|
||||
- **Evaluation is off the dispatcher thread (lmxopcua#779, #750 P0).** The actor used to call the blocking `Evaluate`, which parked an Akka dispatcher thread for the whole run — up to the 2 s budget per evaluation. It now calls `EvaluateAsync`: a passthrough, a compile failure or any synchronous evaluator completes in the same message turn as before, while a real script run (and a first-use compile, which is pushed to the pool) returns an incomplete task. Until it completes the actor **stashes** every further dependency / reassert message, then applies the result and unstashes in arrival order. So each trigger is still evaluated against the inputs as of that trigger, results are published in trigger order, and the dedup / Bad-transition state sees the same sequence — only the thread is freed. Pinned by `VirtualTagActorAsyncEvaluationTests` (a slow script on a one-thread dispatcher no longer starves a sibling actor; ordering, reassert and fault paths) and `RoslynVirtualTagEvaluatorAsyncTests`.
|
||||
- **Evaluation is off the dispatcher thread (lmxopcua#779, #750 P0).** The actor used to call the blocking `Evaluate`, which parked an Akka dispatcher thread for the whole run — up to the 2 s budget per evaluation. It now calls `EvaluateAsync`: a passthrough, a compile failure or any synchronous evaluator completes in the same message turn as before, while a real script run (and a first-use compile, which is pushed to the pool) returns an incomplete task. Until it completes, inputs that arrive are **held, newest value per input** (#995, review R-19), and every other message (reassert, runner recovery, source-binding retry) is stashed. On completion the result is applied, the held inputs are applied together and evaluated **once** (stamped with the newest arrival, the rule a batched mux burst already follows), and the stash is replayed. The backlog is therefore bounded by the tag's input count: before #995 each held trigger was replayed as its own script run against superseded inputs, so a slow script or a loaded out-of-process runner built an unbounded queue of runs with O(M²) re-stash hops and published intermediate values. The value dedup compares one-dimensional arrays element-wise (same element type), so an array tag whose output did not change is no longer republished, re-routed to dependents and historized on every evaluation. Pinned by `VirtualTagActorAsyncEvaluationTests` (a slow script on a one-thread dispatcher no longer starves a sibling actor; ordering, reassert and fault paths) and `RoslynVirtualTagEvaluatorAsyncTests`.
|
||||
- **Unbound data-plane sources retry alone (#995, review R-17).** When DataConnections is wired, `VirtualTagHostActor` spawns a tag's child only after `SourceSamplePublisher.EnsureVirtualBinding` succeeds. A failed binding is retried for **that tag only** (and, for a disabled tag, only its data-plane `BadOutOfService`), from 250 ms doubling to a 5 s cap, with one Warning per apply and one Info on recovery. The retry used to re-send the whole `ApplyVirtualTags` every 250 ms with no backoff, so a persistent cause (e.g. the hub's source cap) lifted every quarantine, re-asserted every child, republished every disabled tag and recomputed the cycle graph four times a second. A new apply cancels the retry and starts over from its own failures. Pinned by `VirtualTagHostSourceBindingRetryTests`.
|
||||
- **VirtualTag → VirtualTag dependencies (lmxopcua#791).** A VirtualTag's key is its UNS NodeId identifier, `{EquipmentId}/{Name}` (VirtualTags have no FolderPath, and no raw-subtree node), and a script reads another VirtualTag with that literal: `ctx.GetTag("EQ-0123456789ab/LineRate")`. It cannot collide with a RawPath in the mux's key space: a key is two segments, a tag's RawPath at least three (Driver/Device/Tag). Until #791 this never worked — VirtualTag outputs were published to their OPC UA node only, the mux carried driver values only, so a dependent sat at `BadWaitingForInitialData` forever (proven by `VirtualTagToVirtualTagFlowTests` failing on the pre-fix code), and the AdminUI completion offered the bare leaf `Name`, which resolved to nothing. Now:
|
||||
- **Routing.** `VirtualTagHostActor.OnResult` publishes each result to the node exactly as before (one publish path, one NodeId — VirtualTags exist only in the UNS realm, so there is no raw NodeId to keep consistent) and *additionally* sends it to the mux as `DependencyMuxActor.VirtualTagOutput` under the same string. A disabled tag's `BadOutOfService` is routed too. A re-assert is not routed (it repeats a state the mux already holds). So `ctx.GetTag(<key>)` returns the upstream's current value, status and timestamp, and the dependent inherits a Bad upstream status like any input (02/S14). Calculation tags and scripted alarms read the mux too, so they can read a VirtualTag by its key the same way.
|
||||
- **Retention.** A VirtualTag output is **pinned** in the mux: retained whether or not anyone has registered for it yet (an upstream and its dependent spawn in one apply and register asynchronously, so the upstream may evaluate first), never put into the replay grace, and immune to a driver's `SourceRemoved`. A dependent that registers later — or respawns on a plan edit — is replayed the current value at once. Memory is bounded by the deployed VirtualTag count; the host sends `VirtualTagOutputsRemoved` for keys that leave the deployed set (a removed or renamed tag), which drops them.
|
||||
|
||||
@@ -86,6 +86,15 @@ Two deploy-time gates run over the result:
|
||||
comes back after an outage usually comes back holding the reading it had before, so a value-only
|
||||
dedup would swallow the recovery and leave the node Bad forever.
|
||||
- **Timers are grouped by interval**, one timer per distinct interval, not one per tag.
|
||||
- **Change triggers are latest-wins per tag (#995, review S-9).** A dependency change queues the calc tags that read
|
||||
it, but at most **one** evaluation is ever pending per tag: a tag already queued keeps its place and only takes the
|
||||
newer trigger timestamp, and its dependency snapshot is taken when the single evaluation pump *dequeues* it. So
|
||||
the inputs of one poll cycle that arrive while the pump is busy evaluate **once**, against all the new values —
|
||||
not once per input, where the first k−1 runs mixed new and previous-cycle values and published those
|
||||
intermediates (an `A − B` spike when A had updated and B had not). The queue is bounded by the number of calc
|
||||
tags, so triggers that outpace the pump (slow scripts, an out-of-process runner under load) no longer build an
|
||||
unbounded backlog of stale evaluations. With an out-of-process runner the pump submits everything it dequeued as
|
||||
one batch, which therefore never names a tag twice. Pinned by `CalculationDriverCoalescingTests`.
|
||||
|
||||
## Input quality
|
||||
|
||||
|
||||
@@ -874,6 +874,13 @@ Behaviours worth knowing before enabling it:
|
||||
- **A client may delete a stood-down item** normally; the delete is absorbed (the item is already off
|
||||
the fan-out) and a later restoring deployment does not resurrect it.
|
||||
|
||||
A stood-down item (data or event) is on no fan-out list, so when a deploy **removes its node** the removal
|
||||
finds it through a per-node index of tracked items, tells a data item `BadNodeIdUnknown` and forgets it
|
||||
(else it would keep the dead node in the SDK's component cache). Since #995 (U-5) that lookup costs the
|
||||
removed node's own items — it used to scan every tracked item per removed node, so a rebuild or a surgical
|
||||
apply removing thousands of nodes was O(nodes × items) under the node manager `Lock` whenever any item
|
||||
was stood down. A rebuild runs one unfiltered sweep.
|
||||
|
||||
**Server-object (`i=2253`, all-events) event subscriptions are filtered per event at delivery** (Gitea
|
||||
#586). They used to be outside the ACL entirely: the SDK attached such an item to the fan-out of every
|
||||
one of our root notifiers through `SubscribeToAllEvents`, and an equipment folder with no direct
|
||||
|
||||
@@ -132,15 +132,26 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
/// <see cref="ScriptEvaluator{TContext, TResult}.Compile"/> calls through the
|
||||
/// cache so the collectible <see cref="System.Runtime.Loader.AssemblyLoadContext"/>
|
||||
/// each compile produces is actually disposed on the publish-replace path:
|
||||
/// the cache's <see cref="CompiledScriptCache{TContext, TResult}.Clear"/>
|
||||
/// disposes every materialised evaluator before dropping its dictionary entry,
|
||||
/// so a config-publish releases the prior generation's ALCs and the per-publish
|
||||
/// accretion the prior fix targeted is actually freed in production.
|
||||
/// the cache's <see cref="CompiledScriptCache{TContext, TResult}.RetainOnly"/>
|
||||
/// disposes every materialised evaluator no definition of the new generation
|
||||
/// references before dropping its dictionary entry, so a config-publish releases
|
||||
/// the retired predicates' ALCs while an unchanged predicate keeps its compile
|
||||
/// across deploys (#995 K-3 — the cache used to be cleared, so every deploy
|
||||
/// recompiled every predicate under the gate).
|
||||
/// Pre-fix the engine called <c>ScriptEvaluator.Compile</c> directly, which left
|
||||
/// the ALCs rooted until the process exited — defeating -008 on the real path.
|
||||
/// </summary>
|
||||
private readonly CompiledScriptCache<AlarmPredicateContext, bool> _compileCache = new();
|
||||
|
||||
/// <summary>
|
||||
/// #995 K-3, out of process only: predicate sources the host has already validated (compiled to a PE image and
|
||||
/// dropped), so a deploy that did not edit a predicate does not re-emit it. Pruned to the live definitions on
|
||||
/// every load.
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<string, byte> _validatedSources = new(StringComparer.Ordinal);
|
||||
|
||||
private long _hostValidationCompiles;
|
||||
|
||||
/// <summary>
|
||||
/// Test-only diagnostic: returns the per-alarm scratch read-cache dictionary
|
||||
/// if one has been allocated, else null. Used by regression tests to assert
|
||||
@@ -363,6 +374,10 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
/// compile failures into one <see cref="InvalidOperationException"/>, subscribes
|
||||
/// to upstream input tags, seeds the value cache, seeds each alarm's condition, and
|
||||
/// recomputes ActiveState from the current predicate (startup recovery).
|
||||
/// <para>#995 K-3: compiling happens first, on the thread pool and WITHOUT the engine gate; only the swap
|
||||
/// (everything below) holds it. A predicate whose source is unchanged since the last load is reused, not
|
||||
/// recompiled. While the new generation compiles, operator commands and re-evaluations run against the live
|
||||
/// generation — the swap then carries their result over like any other survivor state (#935).</para>
|
||||
/// <para>#935: the seed is <c>previous ?? persisted ?? Fresh</c>. An alarm id that was loaded in the
|
||||
/// last completed generation of THIS engine incarnation (a redeploy) keeps its in-memory condition, so a
|
||||
/// still-true predicate is a restatement (no emission, Ack/Confirm/LastTransitionUtc unchanged, and no
|
||||
@@ -379,10 +394,18 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(ScriptedAlarmEngine));
|
||||
if (definitions is null) throw new ArgumentNullException(nameof(definitions));
|
||||
|
||||
// #995 K-3: the compile phase runs OUTSIDE _evalGate and off the caller's thread (the host actor calls this
|
||||
// straight from its mailbox). Only the swap below takes the gate, so operator commands and evaluations keep
|
||||
// running against the live generation while the new one compiles, and a reload of unchanged predicates
|
||||
// compiles nothing (the cache is keyed by source hash and is no longer cleared per load).
|
||||
var prepared = await Task.Run(() => PreparePredicates(definitions, ct), ct).ConfigureAwait(false);
|
||||
|
||||
var pending = new PendingEmissions();
|
||||
await _evalGate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// A Dispose that ran while this load compiled must not be undone by the swap.
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(ScriptedAlarmEngine));
|
||||
_inputsEstablished.Clear();
|
||||
// Stop the prior shelving timer BEFORE clearing _alarms so no in-progress
|
||||
// tick can observe a half-cleared dictionary. Moving the dispose here also
|
||||
@@ -421,10 +444,6 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
// unsafe.
|
||||
_scratchByAlarmId.Clear();
|
||||
_lastQualityBucketByAlarmId.Clear();
|
||||
// Dispose every compiled-predicate ALC from the prior generation BEFORE we
|
||||
// recompile this one. Skipping this is what made the earlier fix a
|
||||
// no-op in production.
|
||||
_compileCache.Clear();
|
||||
// A (re)load is a deploy: lift every run-guard quarantine (an edited predicate already lifts
|
||||
// its own through the guard's source identity; this covers "redeployed to retry").
|
||||
_guard.ResetAll();
|
||||
@@ -433,17 +452,17 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
lock (_dirtyLock) _recoveryArmed.Clear();
|
||||
|
||||
var compileFailures = new List<string>();
|
||||
foreach (var def in definitions)
|
||||
foreach (var prep in prepared)
|
||||
{
|
||||
var def = prep.Definition;
|
||||
if (prep.Failure is not null)
|
||||
{
|
||||
compileFailures.Add(prep.Failure);
|
||||
continue;
|
||||
}
|
||||
try
|
||||
{
|
||||
var extraction = DependencyExtractor.Extract(def.PredicateScriptSource);
|
||||
if (!extraction.IsValid)
|
||||
{
|
||||
var joined = string.Join("; ", extraction.Rejections.Select(r => r.Message));
|
||||
compileFailures.Add($"{def.AlarmId}: dependency extraction rejected — {joined}");
|
||||
continue;
|
||||
}
|
||||
var extraction = prep.Extraction!;
|
||||
|
||||
// Route through CompiledScriptCache so the emitted assembly's
|
||||
// collectible ALC participates in publish-replace cleanup.
|
||||
@@ -454,9 +473,13 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
// Out of process (lmxopcua#780) the worker compiles and runs the predicate; here the source is only
|
||||
// compiled to PE bytes and dropped — same Roslyn, sandbox and diagnostics, so a broken predicate still
|
||||
// fails the load exactly as in process — and no assembly is loaded into the host.
|
||||
//
|
||||
// #995 K-3: PreparePredicates already compiled (or validated) every source outside the gate, so
|
||||
// this is a cache hit. It only compiles here when a concurrent load's swap evicted the entry in
|
||||
// between — correct, just slower for that one race.
|
||||
ScriptEvaluator<AlarmPredicateContext, bool>? evaluator = null;
|
||||
if (_runner is null) evaluator = _compileCache.GetOrCompile(def.PredicateScriptSource);
|
||||
else _ = ScriptEvaluator<AlarmPredicateContext, bool>.CompileToImage(def.PredicateScriptSource);
|
||||
else if (!_validatedSources.ContainsKey(def.PredicateScriptSource)) ValidateForWorker(def.PredicateScriptSource);
|
||||
var logger = _loggerFactory.Create(def.AlarmId);
|
||||
|
||||
var templateTokens = MessageTemplate.ExtractTokenPaths(def.MessageTemplate);
|
||||
@@ -479,6 +502,15 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
// #995 K-3: publish-replace — dispose only the prior generation's compiles that no definition of this one
|
||||
// references (their collectible ALCs unload) and keep the rest for reuse. _alarms was cleared above, so
|
||||
// nothing still holds a dropped evaluator. Before the failure throw, so a failed load releases them too.
|
||||
var liveSources = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var def in definitions) liveSources.Add(def.PredicateScriptSource);
|
||||
_compileCache.RetainOnly(liveSources);
|
||||
foreach (var source in _validatedSources.Keys)
|
||||
if (!liveSources.Contains(source)) _validatedSources.TryRemove(source, out _);
|
||||
|
||||
if (compileFailures.Count > 0)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
@@ -564,6 +596,75 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
FirePending(pending);
|
||||
}
|
||||
|
||||
/// <summary>One definition after the compile phase: its dependency extraction, or why it cannot load.</summary>
|
||||
private sealed record PreparedPredicate(
|
||||
ScriptedAlarmDefinition Definition, DependencyExtractionResult? Extraction, string? Failure);
|
||||
|
||||
/// <summary>
|
||||
/// #995 K-3: the compile phase of <see cref="LoadAsync"/>, run OUTSIDE <see cref="_evalGate"/> on the thread
|
||||
/// pool with bounded parallelism. Extracts each predicate's dependencies and compiles it into
|
||||
/// <see cref="_compileCache"/> (in process) or validates it to a PE image (out of process, remembered in
|
||||
/// <see cref="_validatedSources"/> so an unchanged predicate is not re-emitted on the next deploy). A source the
|
||||
/// cache already holds costs a hash and a lookup. Touches no generation state, so it is safe concurrently with
|
||||
/// evaluations and commands; the result is in definition order.
|
||||
/// </summary>
|
||||
private PreparedPredicate[] PreparePredicates(IReadOnlyList<ScriptedAlarmDefinition> definitions, CancellationToken ct)
|
||||
{
|
||||
CompilePhaseHookForTests?.Invoke();
|
||||
var result = new PreparedPredicate[definitions.Count];
|
||||
var options = new ParallelOptions
|
||||
{
|
||||
CancellationToken = ct,
|
||||
MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount / 2, 1, 4),
|
||||
};
|
||||
Parallel.For(0, definitions.Count, options, i =>
|
||||
{
|
||||
var def = definitions[i];
|
||||
try
|
||||
{
|
||||
var extraction = DependencyExtractor.Extract(def.PredicateScriptSource);
|
||||
if (!extraction.IsValid)
|
||||
{
|
||||
var joined = string.Join("; ", extraction.Rejections.Select(r => r.Message));
|
||||
result[i] = new(def, null, $"{def.AlarmId}: dependency extraction rejected — {joined}");
|
||||
return;
|
||||
}
|
||||
if (_runner is null) _ = _compileCache.GetOrCompile(def.PredicateScriptSource);
|
||||
else if (!_validatedSources.ContainsKey(def.PredicateScriptSource)) ValidateForWorker(def.PredicateScriptSource);
|
||||
result[i] = new(def, extraction, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result[i] = new(def, null, $"{def.AlarmId}: {ex.Message}");
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Out of process (lmxopcua#780) the worker compiles and runs the predicate; the host only compiles it to PE bytes
|
||||
/// and drops them — same Roslyn, sandbox and diagnostics, so a broken predicate still fails the load exactly as in
|
||||
/// process. A source that validated is remembered (#995 K-3) until a load no longer references it.
|
||||
/// </summary>
|
||||
private void ValidateForWorker(string source)
|
||||
{
|
||||
Interlocked.Increment(ref _hostValidationCompiles);
|
||||
_ = ScriptEvaluator<AlarmPredicateContext, bool>.CompileToImage(source);
|
||||
_validatedSources.TryAdd(source, 0);
|
||||
}
|
||||
|
||||
/// <summary>Test/diagnostic: Roslyn compiles this engine has run for predicates in process (cache misses).</summary>
|
||||
internal long PredicateCompileCount => _compileCache.CompileCount;
|
||||
|
||||
/// <summary>Test/diagnostic: out-of-process validation compiles (PE images emitted and dropped) this engine ran.</summary>
|
||||
internal long HostValidationCompileCount => Interlocked.Read(ref _hostValidationCompiles);
|
||||
|
||||
/// <summary>Test/diagnostic: compiled predicates currently cached (in process).</summary>
|
||||
internal int CachedPredicateCount => _compileCache.Count;
|
||||
|
||||
/// <summary>Test seam: runs at the start of a load's compile phase (outside the gate, on the thread pool).</summary>
|
||||
internal Action? CompilePhaseHookForTests { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// #935: the state a loaded alarm starts its first evaluation from — <c>previous ?? persisted ?? Fresh</c>.
|
||||
/// The previous generation's in-memory condition wins for a surviving alarm id: it is exactly what this node
|
||||
|
||||
@@ -44,6 +44,7 @@ public sealed class CompiledScriptCache<TContext, TResult> : IDisposable
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, Lazy<ScriptEvaluator<TContext, TResult>>> _cache = new();
|
||||
private bool _disposed;
|
||||
private long _compiles;
|
||||
|
||||
/// <summary>
|
||||
/// Return the compiled evaluator for <paramref name="scriptSource"/>, compiling
|
||||
@@ -61,7 +62,11 @@ public sealed class CompiledScriptCache<TContext, TResult> : IDisposable
|
||||
|
||||
var key = HashSource(scriptSource);
|
||||
var lazy = _cache.GetOrAdd(key, _ => new Lazy<ScriptEvaluator<TContext, TResult>>(
|
||||
() => ScriptEvaluator<TContext, TResult>.Compile(scriptSource),
|
||||
() =>
|
||||
{
|
||||
Interlocked.Increment(ref _compiles);
|
||||
return ScriptEvaluator<TContext, TResult>.Compile(scriptSource);
|
||||
},
|
||||
LazyThreadSafetyMode.ExecutionAndPublication));
|
||||
|
||||
try
|
||||
@@ -84,6 +89,41 @@ public sealed class CompiledScriptCache<TContext, TResult> : IDisposable
|
||||
/// <summary>Current entry count. Exposed for Admin UI diagnostics / tests.</summary>
|
||||
public int Count => _cache.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Number of Roslyn compiles this cache has started (cache misses, failed compiles included). Exposed for
|
||||
/// diagnostics and tests — #995 K-3 pins that a reload of unchanged sources compiles nothing.
|
||||
/// </summary>
|
||||
public long CompileCount => Interlocked.Read(ref _compiles);
|
||||
|
||||
/// <summary>
|
||||
/// #995 K-3: drop (and dispose) every cached compile whose source is NOT in <paramref name="keep"/>, leaving the
|
||||
/// kept entries — and their loaded evaluators — untouched. This is the publish-replace path for an engine that
|
||||
/// reuses unchanged scripts across deploys: <see cref="Clear"/> would throw away every compile and force the
|
||||
/// next generation to recompile sources it already had.
|
||||
/// </summary>
|
||||
/// <param name="keep">The sources the new generation references.</param>
|
||||
/// <returns>How many entries were removed.</returns>
|
||||
public int RetainOnly(IEnumerable<string> keep)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(keep);
|
||||
var keepKeys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var source in keep)
|
||||
if (source is not null) keepKeys.Add(HashSource(source));
|
||||
|
||||
var removed = 0;
|
||||
// Value-scoped removal, as in Clear: a concurrent GetOrCompile that re-added the key keeps its fresh entry.
|
||||
foreach (var entry in _cache.ToArray())
|
||||
{
|
||||
if (keepKeys.Contains(entry.Key)) continue;
|
||||
if (_cache.TryRemove(entry))
|
||||
{
|
||||
DisposeLazyIfMaterialised(entry.Value);
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drop every cached compile. Used on config generation publish + tests.
|
||||
/// Disposes each materialised evaluator before removing it so its collectible
|
||||
|
||||
@@ -105,11 +105,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
// run to its RunTimeout, exactly as before, since the pump drops its result once _running is false).
|
||||
private readonly CancellationTokenSource _evalCts = new();
|
||||
|
||||
// Change-triggered evaluations queued by OnDependencyValue and drained, in arrival order, by a single
|
||||
// pump task. Both fields are guarded by _lock; _pumpScheduled stays true until the pump observes an
|
||||
// empty queue under the lock, so an enqueue can never be lost against a pump that is exiting.
|
||||
private readonly LinkedList<PendingEvaluation> _pending = new();
|
||||
private readonly Dictionary<string, LinkedListNode<PendingEvaluation>> _pendingProjected = new(StringComparer.Ordinal);
|
||||
// Change-triggered evaluations queued by OnDependencyValue and drained, in first-trigger order, by a single
|
||||
// pump task. Latest-wins per calc tag (#995, review S-9): at most ONE entry per tag, carrying only the newest
|
||||
// trigger's timestamp — the dependency snapshot is taken when the pump dequeues it — so the queue is bounded
|
||||
// by the tag count. All three fields are guarded by _lock; _pumpScheduled stays true until the pump observes
|
||||
// an empty queue under the lock, so an enqueue can never be lost against a pump that is exiting.
|
||||
private readonly LinkedList<PendingTrigger> _pending = new();
|
||||
private readonly Dictionary<string, LinkedListNode<PendingTrigger>> _pendingByTag = new(StringComparer.Ordinal);
|
||||
private bool _pumpScheduled;
|
||||
private long _projectedQueueVisits;
|
||||
internal long ProjectedQueueVisitsForTest => Interlocked.Read(ref _projectedQueueVisits);
|
||||
@@ -419,12 +421,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
// QUEUE each change-triggered dependent — never evaluate here. This
|
||||
// runs on the caller's thread, which for the live path is the Akka dispatcher thread of
|
||||
// Runtime's DependencyConsumerMuxAdapter, and a script run is bounded only by RunTimeout.
|
||||
// Everything under this lock is dictionary work; the script runs on the pump.
|
||||
// Everything under this lock is dictionary work; the script runs on the pump. A dependent that
|
||||
// already has a pending evaluation only has its trigger timestamp moved forward (#995).
|
||||
var queued = false;
|
||||
foreach (var calcRawPath in dependents)
|
||||
{
|
||||
if (PrepareEvaluation(calcRawPath, timestampUtc) is not { } prepared) continue;
|
||||
EnqueueEvaluation(prepared);
|
||||
if (!CanEvaluate(calcRawPath)) continue;
|
||||
EnqueueTrigger(calcRawPath, timestampUtc);
|
||||
queued = true;
|
||||
}
|
||||
if (queued) SchedulePump();
|
||||
@@ -487,11 +490,11 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
|
||||
// ---- evaluation ----
|
||||
|
||||
/// <summary>One prepared evaluation: the calc tag's definition, the dependency snapshot taken when its
|
||||
/// trigger fired, and that trigger's timestamp. Built under <see cref="_lock"/> by
|
||||
/// <summary>One prepared evaluation: the calc tag's definition, the dependency snapshot taken when it was
|
||||
/// prepared (dequeue time for change-triggered work, #995), and the newest trigger's timestamp. Built under <see cref="_lock"/> by
|
||||
/// <see cref="PrepareEvaluation"/> and executed outside it, so the script itself needs no shared state.</summary>
|
||||
/// <param name="Definition">The calc tag being evaluated.</param>
|
||||
/// <param name="Dependencies">Its declared reads' snapshots — value, status and timestamps — as of the trigger.</param>
|
||||
/// <param name="Dependencies">Its declared reads' snapshots — value, status and timestamps — as of preparation.</param>
|
||||
/// <param name="TimestampUtc">The trigger's timestamp, stamped on whatever is published.</param>
|
||||
/// <param name="WorstInputStatus">The worst status among <paramref name="Dependencies"/>
|
||||
/// (<see cref="InputQuality.WorstOf"/>). Bad ⇒ the script is HELD and this status is published;
|
||||
@@ -525,19 +528,19 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
/// Roslyn/compiled-cache invocation. Applying it here rather than on the pump is equivalent:
|
||||
/// <see cref="_arrivedDeps"/> only ever grows, and the arrival that completes the set queues its own
|
||||
/// evaluation.</para>
|
||||
/// <para>Snapshotting the dependency values HERE — at trigger time — is what keeps the queued path
|
||||
/// semantically identical to the old inline one: a burst of arrivals evaluates against the values
|
||||
/// that triggered it rather than collapsing onto whatever happened to be current when the pump
|
||||
/// caught up.</para>
|
||||
/// <para>For change-triggered work this is called when the pump DEQUEUES the tag (#995, review S-9), so a
|
||||
/// burst of arrivals that landed while the pump was busy evaluates once, against the newest value of every
|
||||
/// input. It used to be called at trigger time, which made each arrival its own evaluation against a mix of
|
||||
/// new and previous-cycle inputs — publishing those intermediate values — and let the queue grow without
|
||||
/// bound when triggers outpaced the pump.</para>
|
||||
/// </summary>
|
||||
/// <param name="rawPath">The calc tag to prepare.</param>
|
||||
/// <param name="timestampUtc">The trigger's timestamp.</param>
|
||||
/// <returns>The prepared evaluation, or null when the tag must not evaluate.</returns>
|
||||
private PendingEvaluation? PrepareEvaluation(string rawPath, DateTime timestampUtc)
|
||||
{
|
||||
if (!_tagsByRawPath.TryGetValue(rawPath, out var def)) return null;
|
||||
if (string.IsNullOrWhiteSpace(def.ScriptSource)) return null; // unresolved script — never computes
|
||||
if (!def.DependencyRefs.All(_arrivedDeps.Contains)) return null; // still warming up — do not evaluate
|
||||
if (!CanEvaluate(rawPath)) return null;
|
||||
var def = _tagsByRawPath[rawPath];
|
||||
|
||||
var deps = new Dictionary<string, DataValueSnapshot>(StringComparer.Ordinal);
|
||||
foreach (var dep in def.DependencyRefs)
|
||||
@@ -580,37 +583,63 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="rawPath"/> may evaluate now: a known tag with a resolved script whose every
|
||||
/// declared input has arrived (the warm-up gate — see <see cref="PrepareEvaluation"/>). MUST be called under
|
||||
/// <see cref="_lock"/>.</summary>
|
||||
/// <param name="rawPath">The calc tag.</param>
|
||||
/// <returns>True when the tag can evaluate.</returns>
|
||||
private bool CanEvaluate(string rawPath) =>
|
||||
_tagsByRawPath.TryGetValue(rawPath, out var def)
|
||||
&& !string.IsNullOrWhiteSpace(def.ScriptSource) // unresolved script — never computes
|
||||
&& def.DependencyRefs.All(_arrivedDeps.Contains); // still warming up — do not evaluate
|
||||
|
||||
/// <summary>One queued change-triggered evaluation (#995): the calc tag and its NEWEST trigger's timestamp. The
|
||||
/// dependency snapshot is not part of it — it is taken when the pump dequeues the entry.</summary>
|
||||
private sealed class PendingTrigger(string rawPath, DateTime timestampUtc)
|
||||
{
|
||||
public string RawPath { get; } = rawPath;
|
||||
|
||||
public DateTime TimestampUtc { get; set; } = timestampUtc;
|
||||
}
|
||||
|
||||
private void ClearPending()
|
||||
{
|
||||
while (_pending.Count != 0) DequeuePending().Dispose();
|
||||
_pending.Clear();
|
||||
_pendingByTag.Clear();
|
||||
}
|
||||
|
||||
private PendingEvaluation DequeuePending()
|
||||
/// <summary>
|
||||
/// Queue a change-triggered evaluation of <paramref name="rawPath"/>, latest-wins (#995, review S-9): a tag that
|
||||
/// is already queued keeps its place and takes the newer trigger timestamp, so the queue never holds more than
|
||||
/// one entry per calc tag. Keeping the place (rather than moving to the back) means a tag whose inputs change
|
||||
/// constantly is still served in its turn. MUST be called under <see cref="_lock"/>.
|
||||
/// </summary>
|
||||
/// <param name="rawPath">The calc tag.</param>
|
||||
/// <param name="timestampUtc">The trigger's timestamp, stamped on what the evaluation publishes.</param>
|
||||
private void EnqueueTrigger(string rawPath, DateTime timestampUtc)
|
||||
{
|
||||
var first = _pending.First!;
|
||||
_pending.RemoveFirst();
|
||||
if (first.Value.Proofs.Count > 0) _pendingProjected.Remove(first.Value.Definition.RawPath);
|
||||
return first.Value;
|
||||
}
|
||||
|
||||
private void EnqueueEvaluation(PendingEvaluation pending)
|
||||
{
|
||||
// Projected work is latest-wins per tag. Remove its indexed node and append the
|
||||
// replacement in arrival order, without traversing unrelated projected or local work.
|
||||
if (pending.Proofs.Count > 0)
|
||||
_projectedQueueVisits++;
|
||||
if (_pendingByTag.TryGetValue(rawPath, out var queued))
|
||||
{
|
||||
_projectedQueueVisits++;
|
||||
if (_pendingProjected.Remove(pending.Definition.RawPath, out var prior))
|
||||
{
|
||||
_projectedQueueVisits++;
|
||||
_pending.Remove(prior);
|
||||
prior.Value.Dispose();
|
||||
}
|
||||
var node = _pending.AddLast(pending);
|
||||
_pendingProjected.Add(pending.Definition.RawPath, node);
|
||||
_projectedQueueVisits++;
|
||||
queued.Value.TimestampUtc = timestampUtc;
|
||||
return;
|
||||
}
|
||||
else _pending.AddLast(pending);
|
||||
_pendingByTag.Add(rawPath, _pending.AddLast(new PendingTrigger(rawPath, timestampUtc)));
|
||||
}
|
||||
|
||||
/// <summary>Dequeue the next queued tag and prepare it against the CURRENT inputs; null when the queue holds
|
||||
/// nothing that can evaluate (an entry whose tag can no longer evaluate is dropped). MUST be called under
|
||||
/// <see cref="_lock"/>.</summary>
|
||||
/// <returns>The prepared evaluation, or null when the queue is drained.</returns>
|
||||
private PendingEvaluation? DequeuePrepared()
|
||||
{
|
||||
while (_pending.First is { } first)
|
||||
{
|
||||
_pending.RemoveFirst();
|
||||
_pendingByTag.Remove(first.Value.RawPath);
|
||||
if (PrepareEvaluation(first.Value.RawPath, first.Value.TimestampUtc) is { } prepared) return prepared;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Start the evaluation pump if it is not already running. MUST be called under
|
||||
@@ -644,12 +673,12 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_running) ClearPending();
|
||||
if (_pending.Count == 0)
|
||||
if (DequeuePrepared() is not { } prepared)
|
||||
{
|
||||
_pumpScheduled = false;
|
||||
return;
|
||||
}
|
||||
next = DequeuePending();
|
||||
next = prepared;
|
||||
}
|
||||
|
||||
// _evalGate (never _lock) is held across the run, so the pump and the timer ticks still
|
||||
@@ -675,9 +704,9 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
|
||||
/// <summary>
|
||||
/// The pump on the out-of-process path (lmxopcua#780, design §4.5): dequeue everything pending — each entry's
|
||||
/// dependency snapshot was captured at enqueue — submit it as ONE batch, and publish in dequeue order. A calc tag
|
||||
/// queued more than once (a burst of changes) ends the batch at its second entry, so every queued evaluation still
|
||||
/// runs, in order, against the snapshot that triggered it, exactly as the one-at-a-time pump would run them.
|
||||
/// dependency snapshot is taken as it is dequeued — submit it as ONE batch, and publish in dequeue order. The
|
||||
/// queue holds at most one entry per calc tag (#995), so a batch never names a tag twice; triggers that arrive
|
||||
/// while it runs coalesce into the next one.
|
||||
/// </summary>
|
||||
private async Task RunEvaluationBatchPumpAsync()
|
||||
{
|
||||
@@ -687,14 +716,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_running) ClearPending();
|
||||
if (_pending.Count == 0)
|
||||
batch = [];
|
||||
while (DequeuePrepared() is { } prepared) batch.Add(prepared);
|
||||
if (batch.Count == 0)
|
||||
{
|
||||
_pumpScheduled = false;
|
||||
return;
|
||||
}
|
||||
batch = [];
|
||||
var inBatch = new HashSet<string>(StringComparer.Ordinal);
|
||||
while (_pending.Count > 0 && inBatch.Add(_pending.First!.Value.Definition.RawPath)) batch.Add(DequeuePending());
|
||||
}
|
||||
|
||||
if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) { foreach (var item in batch) item.Dispose(); return; } // disposed
|
||||
@@ -913,8 +941,8 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
|
||||
{
|
||||
if (_stateByRawPath.TryGetValue(rawPath, out var st)) st.RecoveryArmed = false;
|
||||
if (!_running || _disposed) return;
|
||||
if (PrepareEvaluation(rawPath, DateTime.UtcNow) is not { } prepared) return;
|
||||
EnqueueEvaluation(prepared);
|
||||
if (!CanEvaluate(rawPath)) return;
|
||||
EnqueueTrigger(rawPath, DateTime.UtcNow);
|
||||
SchedulePump();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -790,6 +790,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>()) item.Retire();
|
||||
_liveItems.Clear();
|
||||
_eventItems.Clear();
|
||||
lock (_trackedItemsByNodeLock) _trackedItemsByNode.Clear();
|
||||
_allEventsItems.Clear();
|
||||
lock (Lock) _allEventsMonitoredConditions.Clear();
|
||||
}
|
||||
@@ -6762,10 +6763,14 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// re-attaching an item the client has just deleted.
|
||||
lock (Lock)
|
||||
{
|
||||
if (_eventItems.TryRemove(monitoredItem, out var stoodDown) && stoodDown.Suppressed)
|
||||
if (_eventItems.TryRemove(monitoredItem, out var stoodDown))
|
||||
{
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
return ServiceResult.Good;
|
||||
UnindexIfUntracked(stoodDown.Handle.NodeId, monitoredItem);
|
||||
if (stoodDown.Suppressed)
|
||||
{
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
return ServiceResult.Good;
|
||||
}
|
||||
}
|
||||
|
||||
if (IsHandleInNamespace(sourceId) is { } h
|
||||
@@ -6813,6 +6818,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
&& monitored.EventMonitoredItems?.ContainsKey(monitoredItem.Id) == true)
|
||||
{
|
||||
_eventItems[monitoredItem] = new LiveEventItem(handle);
|
||||
IndexTrackedItem(handle.NodeId, monitoredItem); // after the map write — see IndexTrackedItem
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6861,7 +6867,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// </remarks>
|
||||
internal void TrackLiveMonitoredItem(NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem)
|
||||
{
|
||||
if (OwnsNamespace(handle.NodeId)) _liveItems[monitoredItem] = new LiveItem(handle);
|
||||
if (OwnsNamespace(handle.NodeId))
|
||||
{
|
||||
_liveItems[monitoredItem] = new LiveItem(handle);
|
||||
IndexTrackedItem(handle.NodeId, monitoredItem); // after the map write — see IndexTrackedItem
|
||||
}
|
||||
if (monitoredItem is ProjectedMonitoredItem projected) TrackProjectedHealth(projected);
|
||||
}
|
||||
|
||||
@@ -6871,6 +6881,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
{
|
||||
if (monitoredItem is ProjectedMonitoredItem projected) { ForgetProjectedHealth(projected); projected.Retire(); }
|
||||
if (_liveItems.TryRemove(monitoredItem, out var tracked) && tracked.Suppressed) Interlocked.Decrement(ref _suppressedItems);
|
||||
UnindexIfUntracked(handle.NodeId, monitoredItem);
|
||||
if (tracked is not null && tracked.Handle.NodeId != handle.NodeId) UnindexIfUntracked(tracked.Handle.NodeId, monitoredItem);
|
||||
base.OnMonitoredItemDeleted(context, handle, monitoredItem);
|
||||
}
|
||||
|
||||
@@ -6914,6 +6926,65 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// tombstone sweep for stood-down items — which are not on any fan-out list — run only when there are any.</summary>
|
||||
private int _suppressedItems;
|
||||
|
||||
/// <summary>Test/diagnostic (#995 U-5): tracked-item entries the stood-down sweep has visited. Mutated under
|
||||
/// <c>Lock</c> (every sweep runs under it).</summary>
|
||||
internal long StoodDownSweepVisits { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// #995 U-5: every item in <see cref="_liveItems"/> / <see cref="_eventItems"/>, indexed by the NodeId it was
|
||||
/// tracked against, so a removal's stood-down sweep (<see cref="SweepStoodDownItems"/>) looks up the removed
|
||||
/// node's items instead of scanning every tracked item — removing N stood-down nodes was O(N × items) under
|
||||
/// <c>Lock</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A SUPERSET index: an entry is added right after its map write (<see cref="TrackLiveMonitoredItem"/>,
|
||||
/// <c>TrackLiveEventItem</c>) and dropped when the client deletes the item; everything else that takes an item
|
||||
/// out of a map (the tombstone, a revalidation that finds its node replaced) leaves the entry, and the sweep
|
||||
/// re-validates each candidate against the maps and prunes the ones no longer tracked under that node. So the
|
||||
/// index never has to follow the <c>Suppressed</c> flips — it is only ever asked "which items could be on this
|
||||
/// node", and a candidate that is suppressed must be tracked, hence indexed. Its own lock (never held while
|
||||
/// taking <c>Lock</c>) because the track/delete paths are not all under <c>Lock</c>.
|
||||
/// </remarks>
|
||||
private readonly Dictionary<NodeId, HashSet<object>> _trackedItemsByNode = new();
|
||||
|
||||
private readonly object _trackedItemsByNodeLock = new();
|
||||
|
||||
/// <summary>Adds <paramref name="item"/> to <see cref="_trackedItemsByNode"/>. Call AFTER the map write: a
|
||||
/// concurrent prune that checks the map first then keeps the entry; one that ran before re-adds nothing it
|
||||
/// should not, because this add lands after it.</summary>
|
||||
private void IndexTrackedItem(NodeId nodeId, object item)
|
||||
{
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
if (!_trackedItemsByNode.TryGetValue(nodeId, out var set))
|
||||
_trackedItemsByNode[nodeId] = set = new HashSet<object>(System.Collections.Generic.ReferenceEqualityComparer.Instance);
|
||||
set.Add(item);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="item"/> is tracked in either map against <paramref name="nodeId"/>.</summary>
|
||||
private bool IsTrackedUnder(NodeId nodeId, object item) =>
|
||||
(item is ISampledDataChangeMonitoredItem data && _liveItems.TryGetValue(data, out var live) && live.Handle.NodeId == nodeId)
|
||||
|| (item is IEventMonitoredItem evt && _eventItems.TryGetValue(evt, out var ev) && ev.Handle.NodeId == nodeId);
|
||||
|
||||
/// <summary>Drops <paramref name="item"/>'s index entry under <paramref name="nodeId"/> unless a map still
|
||||
/// tracks it there (one object can be both a data and an event item).</summary>
|
||||
private void UnindexIfUntracked(NodeId nodeId, object item)
|
||||
{
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
if (!_trackedItemsByNode.TryGetValue(nodeId, out var set) || IsTrackedUnder(nodeId, item)) return;
|
||||
set.Remove(item);
|
||||
if (set.Count == 0) _trackedItemsByNode.Remove(nodeId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Test/diagnostic: NodeIds with at least one index entry.</summary>
|
||||
internal int TrackedItemIndexNodeCount
|
||||
{
|
||||
get { lock (_trackedItemsByNodeLock) return _trackedItemsByNode.Count; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Review 01 L2 — forget the <see cref="MonitoredNode2"/> of a node this manager is removing, telling
|
||||
/// every data-change item on it <c>BadNodeIdUnknown</c> first. MUST be called under <c>Lock</c>, BEFORE
|
||||
@@ -6945,7 +7016,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
/// </remarks>
|
||||
/// <param name="nodeId">The NodeId being removed.</param>
|
||||
/// <param name="now">The timestamp the terminal <c>BadNodeIdUnknown</c> carries.</param>
|
||||
private void TombstoneMonitoredNode(NodeId nodeId, DateTime now)
|
||||
/// <param name="sweepStoodDown">False only for <see cref="TombstoneAllMonitoredNodes"/>, which runs one
|
||||
/// unfiltered sweep after the loop instead of one per node (#995 U-5).</param>
|
||||
private void TombstoneMonitoredNode(NodeId nodeId, DateTime now, bool sweepStoodDown = true)
|
||||
{
|
||||
if (MonitoredNodes.TryGetValue(nodeId, out var monitored))
|
||||
{
|
||||
@@ -6970,7 +7043,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
}
|
||||
}
|
||||
|
||||
if (!sweepStoodDown) return;
|
||||
if (Volatile.Read(ref _suppressedItems) > 0) SweepStoodDownItems(nodeId, now);
|
||||
else PruneIndexFor(nodeId);
|
||||
}
|
||||
|
||||
/// <summary>Tombstones <paramref name="node"/> and every descendant (a condition's instance-scoped
|
||||
@@ -7000,32 +7075,107 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
foreach (var nodeId in MonitoredNodes.Keys.ToList())
|
||||
{
|
||||
if (rootId is not null && nodeId == rootId.Value) continue;
|
||||
TombstoneMonitoredNode(nodeId, now);
|
||||
// #995 U-5: no per-node sweep — the one unfiltered sweep below covers every node, and per node it was
|
||||
// a full scan of the tracked items each time (O(monitored nodes × items) under Lock).
|
||||
TombstoneMonitoredNode(nodeId, now, sweepStoodDown: false);
|
||||
}
|
||||
|
||||
if (Volatile.Read(ref _suppressedItems) > 0) SweepStoodDownItems(nodeId: null, now);
|
||||
if (Volatile.Read(ref _suppressedItems) > 0) SweepStoodDownItems(nodeId: null, now); // prunes the index too
|
||||
else PruneIndexAll();
|
||||
}
|
||||
|
||||
/// <summary>Drops the stood-down items of <paramref name="nodeId"/> (every stood-down item when null —
|
||||
/// the rebuild case) from the revalidation maps, telling the data items <c>BadNodeIdUnknown</c>.</summary>
|
||||
/// <remarks>#995 U-5: a per-node sweep visits only the candidates <see cref="_trackedItemsByNode"/> holds for
|
||||
/// that node (and prunes the ones no longer tracked there); only the rebuild's unfiltered sweep scans the maps.</remarks>
|
||||
private void SweepStoodDownItems(NodeId? nodeId, DateTime now)
|
||||
{
|
||||
foreach (var (item, tracked) in _liveItems)
|
||||
if (nodeId is null)
|
||||
{
|
||||
if (!tracked.Suppressed || (nodeId is not null && tracked.Handle.NodeId != nodeId.Value)) continue;
|
||||
if (!_liveItems.TryRemove(item, out _)) continue;
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
if (item is ProjectedMonitoredItem projected) projected.Retire();
|
||||
TellNodeRemoved(item, now);
|
||||
ReleaseComponentCacheReference(item);
|
||||
foreach (var (item, tracked) in _liveItems)
|
||||
{
|
||||
StoodDownSweepVisits++;
|
||||
if (tracked.Suppressed) DropStoodDownDataItem(item, now);
|
||||
}
|
||||
|
||||
foreach (var (item, tracked) in _eventItems)
|
||||
{
|
||||
StoodDownSweepVisits++;
|
||||
if (tracked.Suppressed) DropStoodDownEventItem(item);
|
||||
}
|
||||
|
||||
PruneIndexAll();
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var (item, tracked) in _eventItems)
|
||||
var node = nodeId.Value;
|
||||
object[] candidates;
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
if (!tracked.Suppressed || (nodeId is not null && tracked.Handle.NodeId != nodeId.Value)) continue;
|
||||
if (!_eventItems.TryRemove(item, out _)) continue;
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
// Event items hold no component-cache reference (see TombstoneMonitoredNode).
|
||||
if (!_trackedItemsByNode.TryGetValue(node, out var set)) return;
|
||||
candidates = [.. set];
|
||||
}
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
StoodDownSweepVisits++;
|
||||
if (candidate is ISampledDataChangeMonitoredItem data
|
||||
&& _liveItems.TryGetValue(data, out var live) && live.Suppressed && live.Handle.NodeId == node)
|
||||
{
|
||||
DropStoodDownDataItem(data, now);
|
||||
}
|
||||
|
||||
if (candidate is IEventMonitoredItem evt
|
||||
&& _eventItems.TryGetValue(evt, out var ev) && ev.Suppressed && ev.Handle.NodeId == node)
|
||||
{
|
||||
DropStoodDownEventItem(evt);
|
||||
}
|
||||
|
||||
UnindexIfUntracked(node, candidate);
|
||||
}
|
||||
}
|
||||
|
||||
private void DropStoodDownDataItem(ISampledDataChangeMonitoredItem item, DateTime now)
|
||||
{
|
||||
if (!_liveItems.TryRemove(item, out _)) return;
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
if (item is ProjectedMonitoredItem projected) projected.Retire();
|
||||
TellNodeRemoved(item, now);
|
||||
ReleaseComponentCacheReference(item);
|
||||
}
|
||||
|
||||
private void DropStoodDownEventItem(IEventMonitoredItem item)
|
||||
{
|
||||
if (!_eventItems.TryRemove(item, out _)) return;
|
||||
Interlocked.Decrement(ref _suppressedItems);
|
||||
// Event items hold no component-cache reference (see TombstoneMonitoredNode).
|
||||
}
|
||||
|
||||
/// <summary>#995 U-5: drops <paramref name="nodeId"/>'s index entries that no map tracks there any more (a
|
||||
/// removal with no stood-down items, which skips the sweep).</summary>
|
||||
private void PruneIndexFor(NodeId nodeId)
|
||||
{
|
||||
object[] candidates;
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
if (!_trackedItemsByNode.TryGetValue(nodeId, out var set)) return;
|
||||
candidates = [.. set];
|
||||
}
|
||||
foreach (var candidate in candidates) UnindexIfUntracked(nodeId, candidate);
|
||||
}
|
||||
|
||||
/// <summary>#995 U-5: the rebuild's whole-index prune — every entry no map tracks under its node any more.</summary>
|
||||
private void PruneIndexAll()
|
||||
{
|
||||
lock (_trackedItemsByNodeLock)
|
||||
{
|
||||
List<NodeId>? empty = null;
|
||||
foreach (var (nodeId, set) in _trackedItemsByNode)
|
||||
{
|
||||
set.RemoveWhere(item => !IsTrackedUnder(nodeId, item));
|
||||
if (set.Count == 0) (empty ??= []).Add(nodeId);
|
||||
}
|
||||
if (empty is not null) foreach (var nodeId in empty) _trackedItemsByNode.Remove(nodeId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Text.Json;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
@@ -88,8 +89,45 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
};
|
||||
private static readonly StringComparer DataIds = StringComparer.OrdinalIgnoreCase;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #995 (review 2026-12-02 R-14): the data projection deserialises the whole topology (every Tag, the UNS
|
||||
/// tables, VirtualTags, ScriptedAlarms, Scripts) and runs <see cref="DataConnectionValidator.ValidateDeployed"/>.
|
||||
/// <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/> alone asked for it three times and the driver
|
||||
/// host's catalog staging up to four more, per apply. It is now built (and validated) ONCE per node id per parsed
|
||||
/// artifact — a throw included, re-thrown to every caller — and the three row parsers skip it entirely when the
|
||||
/// artifact's data arrays are all empty (they could only return empty lists).
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, DataProjectionMemo> _dataProjectionByNodeId = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Diagnostics / tests (#995 R-14): how many data projections this parsed artifact actually built.</summary>
|
||||
internal int DataProjectionBuilds { get; private set; }
|
||||
|
||||
private sealed class DataProjectionMemo
|
||||
{
|
||||
public (DraftSnapshot Snapshot, string ClusterId)? Projection;
|
||||
public ExceptionDispatchInfo? Failure;
|
||||
public IReadOnlyList<ValidationError>? Errors;
|
||||
}
|
||||
|
||||
/// <summary>True when none of the three data arrays carries a row (absent, or present and empty) — no data row
|
||||
/// can then be returned, so the row parsers need no projection.</summary>
|
||||
private bool HasNoDataRows()
|
||||
{
|
||||
var root = Root;
|
||||
if (root.ValueKind != JsonValueKind.Object) return true;
|
||||
foreach (var name in DataArrayNames)
|
||||
if (root.TryGetProperty(name, out var value)
|
||||
&& (value.ValueKind != JsonValueKind.Array || value.GetArrayLength() != 0))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static readonly string[] DataArrayNames = ["DataConnections", "DataExports", "RemoteNamespaceMappings"];
|
||||
|
||||
public IReadOnlyList<DataConnection> ParseDataConnections(string nodeId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
|
||||
if (HasNoDataRows()) return [];
|
||||
var projection = ReadDataProjection(nodeId);
|
||||
if (projection is null)
|
||||
return [];
|
||||
@@ -104,6 +142,8 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
|
||||
public IReadOnlyList<DataExport> ParseDataExports(string nodeId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
|
||||
if (HasNoDataRows()) return [];
|
||||
var projection = ReadDataProjection(nodeId);
|
||||
if (projection is null)
|
||||
return [];
|
||||
@@ -116,6 +156,8 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
|
||||
public IReadOnlyList<RemoteNamespaceMapping> ParseRemoteNamespaceMappings(string nodeId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
|
||||
if (HasNoDataRows()) return [];
|
||||
var projection = ReadDataProjection(nodeId);
|
||||
if (projection is null)
|
||||
return [];
|
||||
@@ -140,6 +182,28 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
private (DraftSnapshot Snapshot, string ClusterId)? ReadDataProjection(string nodeId)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
|
||||
if (!_dataProjectionByNodeId.TryGetValue(nodeId, out var memo))
|
||||
{
|
||||
memo = new DataProjectionMemo();
|
||||
try { memo.Projection = BuildDataProjection(nodeId); }
|
||||
catch (Exception ex) { memo.Failure = ExceptionDispatchInfo.Capture(ex); }
|
||||
_dataProjectionByNodeId[nodeId] = memo;
|
||||
}
|
||||
memo.Failure?.Throw();
|
||||
return memo.Projection;
|
||||
}
|
||||
|
||||
/// <summary>The deployed-data validation of <paramref name="snapshot"/>, computed once per memoised projection.</summary>
|
||||
private IReadOnlyList<ValidationError> ValidationErrors(DraftSnapshot snapshot)
|
||||
{
|
||||
foreach (var memo in _dataProjectionByNodeId.Values)
|
||||
if (memo.Projection is { } p && ReferenceEquals(p.Snapshot, snapshot))
|
||||
return memo.Errors ??= DataConnectionValidator.ValidateDeployed(snapshot).ToArray();
|
||||
return DataConnectionValidator.ValidateDeployed(snapshot).ToArray();
|
||||
}
|
||||
|
||||
private (DraftSnapshot Snapshot, string ClusterId)? BuildDataProjection(string nodeId)
|
||||
{
|
||||
var root = Root;
|
||||
if (root.ValueKind != JsonValueKind.Object)
|
||||
return null;
|
||||
@@ -201,6 +265,7 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
foreach (var m in mappings)
|
||||
if (m.ConsumerNodeIds is null)
|
||||
throw InvalidRow(m.RemoteNamespaceMappingId);
|
||||
DataProjectionBuilds++;
|
||||
var snapshot = new DraftSnapshot
|
||||
{
|
||||
GenerationId = 0,
|
||||
@@ -348,11 +413,10 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateRows(DraftSnapshot snapshot, IEnumerable<string> ids)
|
||||
private void ValidateRows(DraftSnapshot snapshot, IEnumerable<string> ids)
|
||||
{
|
||||
var requested = ids.ToHashSet(DataIds);
|
||||
var error = DataConnectionValidator
|
||||
.ValidateDeployed(snapshot)
|
||||
var error = ValidationErrors(snapshot)
|
||||
.FirstOrDefault(x => x.Context is not null && requested.Contains(x.Context));
|
||||
if (error is not null)
|
||||
throw InvalidRow(error.Context);
|
||||
|
||||
@@ -276,9 +276,42 @@ public static partial class DeploymentArtifact
|
||||
try
|
||||
{
|
||||
using var parsed = Open(blob.ToArray());
|
||||
var root = parsed.Root;
|
||||
return parsed.ReadClusterRedundancyMode(nodeId);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gitea #995 (R-14): the <see cref="ReadClusterRedundancyMode(ReadOnlySpan{byte}, string)"/> read off an
|
||||
/// ALREADY-parsed artifact, so the publish actor's off-thread plan step answers it from its own single parse instead
|
||||
/// of a second inflate + parse on the pinned OPC UA thread.</summary>
|
||||
/// <param name="parsed">The parsed artifact.</param>
|
||||
/// <param name="nodeId">This node's <c>host:port</c> id.</param>
|
||||
/// <returns>The mode name, or null.</returns>
|
||||
internal static string? ReadClusterRedundancyMode(ParsedDeploymentArtifact parsed, string nodeId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return parsed.ReadClusterRedundancyMode(nodeId);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed partial class ParsedDeploymentArtifact
|
||||
{
|
||||
/// <summary>See <see cref="DeploymentArtifact.ReadClusterRedundancyMode(ReadOnlySpan{byte}, string)"/>.</summary>
|
||||
internal string? ReadClusterRedundancyMode(string nodeId)
|
||||
{
|
||||
{
|
||||
var root = Root;
|
||||
if (!root.TryGetProperty("Clusters", out var clusters) || clusters.ValueKind != JsonValueKind.Array) return null;
|
||||
var scope = parsed.ResolveClusterScope(nodeId);
|
||||
var scope = ResolveClusterScope(nodeId);
|
||||
JsonElement? match = null;
|
||||
foreach (var cluster in clusters.EnumerateArray())
|
||||
{
|
||||
@@ -301,11 +334,11 @@ public static partial class DeploymentArtifact
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static partial class DeploymentArtifact
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Resolve how a node should scope a deployment artifact to its own ClusterId. Single-cluster
|
||||
@@ -833,6 +866,11 @@ internal sealed partial class ParsedDeploymentArtifact : IDisposable
|
||||
private static string InjectScriptSource(string tagConfig, IReadOnlyDictionary<string, string> scriptSourceById)
|
||||
{
|
||||
if (scriptSourceById.Count == 0 || string.IsNullOrWhiteSpace(tagConfig)) return tagConfig;
|
||||
// #995 (R-14): a tag that cannot carry a scriptId is not parsed at all — once an artifact has any Scripts row this
|
||||
// ran a JsonNode.Parse per tag of every driver. The property lookup below is ordinal and case-sensitive, so a
|
||||
// config without the literal "scriptId" can never inject (only a \u-escaped property NAME would differ, which
|
||||
// no authoring path emits).
|
||||
if (!tagConfig.Contains("scriptId", StringComparison.Ordinal)) return tagConfig;
|
||||
JsonNode? node;
|
||||
try { node = JsonNode.Parse(tagConfig); }
|
||||
catch (JsonException) { return tagConfig; }
|
||||
|
||||
@@ -492,6 +492,33 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// the child the last-known-good set, not an empty one.</para></summary>
|
||||
private readonly Dictionary<string, DesiredSubscriptionSet> _desiredByDriver = new(StringComparer.Ordinal);
|
||||
|
||||
// ---- Gitea #995 (review 2026-12-02 R-11): skip the deploy re-subscribe of an untouched driver ----
|
||||
// A re-subscribe tears down and rebuilds the driver's whole data subscription (OpcUaClient monitored items, Galaxy
|
||||
// advise through mxaccessgw, a forced full re-read on every poll driver) and leaves a data gap. Its only job on a
|
||||
// KEPT driver whose desired set is unchanged is SEEDING: the initial values it produces are what give a node or a
|
||||
// consumer that is new since the last apply its first value. So the deploy path skips a driver only when nothing
|
||||
// that could need a seed changed for it (see SeedingFingerprint / ConsumerRefs), and re-pushes the skipped ones
|
||||
// after the address-space outcome if the apply turned out to be a full rebuild (or degraded / timed out).
|
||||
|
||||
/// <summary>The child actor last handed a plain (non-acquisition) desired set for each driver. A child that is not
|
||||
/// the current one (respawned) or that got an acquisition-demand set is never skipped.</summary>
|
||||
private readonly Dictionary<string, IActorRef> _plainPushedTo = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Per-driver seeding fingerprint from the last apply (see <see cref="SeedingFingerprint"/>).</summary>
|
||||
private Dictionary<string, string[]> _seedingFingerprints = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Every driver ref some mux consumer (enabled VirtualTag, enabled scripted alarm, dependency-consuming
|
||||
/// driver such as Calculation) read at the last apply. The mux replays a retained value only for refs a
|
||||
/// replay-opting subscriber already named, so a ref ENTERING this set needs its driver's initial value.</summary>
|
||||
private HashSet<string>? _consumerRefs;
|
||||
|
||||
/// <summary>The <see cref="IDependencyConsumer"/> drivers hosted here, keyed like <see cref="_depConsumerAdapters"/>.</summary>
|
||||
private readonly Dictionary<string, IDependencyConsumer> _depConsumers = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Drivers whose deploy re-subscribe was skipped, held per apply correlation until the address-space
|
||||
/// outcome says whether their nodes survived (non-rebuild, clean) or were recreated (re-push them).</summary>
|
||||
private readonly Dictionary<CorrelationId, HashSet<string>> _seedAfterAddressSpace = new();
|
||||
|
||||
/// <summary>
|
||||
/// Cached local <see cref="RedundancyRole"/> from the latest <see cref="RedundancyStateChanged"/>
|
||||
/// snapshot (null = unknown until the first snapshot arrives, or no local node match). The Primary
|
||||
@@ -3382,7 +3409,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
// resumes off the actor thread.
|
||||
// SubscribeBulk pass: hand each driver its desired tag references so live values flow into
|
||||
// the just-rebuilt address space instead of staying BadWaitingForInitialData.
|
||||
PushDesiredSubscriptionsFromParsed(msg.DeploymentId, parsed);
|
||||
// #995 R-11: a kept driver with nothing seedable changed is NOT re-subscribed; if the address-space apply
|
||||
// turns out to be a rebuild (its nodes recreated empty), HandleRebuildCompleted re-pushes it.
|
||||
var skippedResubscribes = PushDesiredSubscriptionsFromParsed(msg.DeploymentId, parsed, skipUnchanged: true);
|
||||
// Recorded at once, so a throw in the steps below still re-pushes them (the catch). No publish actor ⇒ no
|
||||
// address space whose rebuild could recreate a skipped driver's nodes.
|
||||
if (_opcUaPublishActor is not null && skippedResubscribes.Count > 0)
|
||||
_seedAfterAddressSpace[msg.Correlation] = new HashSet<string>(skippedResubscribes, StringComparer.Ordinal);
|
||||
// Cache the applied bytes as this node's last-known-good (idempotent store; skips empty).
|
||||
CacheAppliedArtifact(msg.DeploymentId, msg.Revision, appliedBlob, parsed);
|
||||
var catalogFailed = _opcUaPublishActor is null && _catalogAttempt is not null
|
||||
@@ -3413,6 +3446,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
// A throw after the Applied ack was put on hold — the Failed ack below is this apply's one
|
||||
// answer, so the held Applied must never follow it when the address-space outcome lands.
|
||||
DropPendingAck(msg.Correlation);
|
||||
// #995 R-11: the routing/desired state may be half-applied — re-push anything this apply skipped.
|
||||
SeedSkippedDrivers(msg.Correlation, reseed: true, "the apply threw");
|
||||
// #977 R-15: whatever revision is current now, a throw part-way through the apply means the drivers and the
|
||||
// routing maps (ApplyDesiredSubscriptions clears them before repopulating) may already be the NEW revision's,
|
||||
// partially. Nothing about the current revision is known-served any more, so a re-dispatch of EITHER revision
|
||||
@@ -3484,6 +3519,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// </summary>
|
||||
private void HandleRebuildCompleted(OpcUa.OpcUaPublishActor.RebuildCompleted msg)
|
||||
{
|
||||
SeedSkippedDrivers(msg.Correlation, reseed: msg.AddressSpaceRebuilt || msg.Degraded,
|
||||
msg.Degraded ? "degraded apply" : "full rebuild");
|
||||
if (!_pendingAcks.Remove(msg.Correlation, out var pending))
|
||||
{
|
||||
_log.Debug("DriverHost {Node}: address-space outcome for {Correlation} has no held ack (already timed out or superseded); dropping",
|
||||
@@ -3502,6 +3539,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// </summary>
|
||||
private void HandleApplyOutcomeTimedOut(ApplyOutcomeTimedOut msg)
|
||||
{
|
||||
SeedSkippedDrivers(msg.Correlation, reseed: true, "address-space outcome not reported in time");
|
||||
if (!_pendingAcks.Remove(msg.Correlation, out var pending)) return;
|
||||
|
||||
ReleasePendingAck(pending, degraded: true,
|
||||
@@ -4101,7 +4139,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// </remarks>
|
||||
/// <param name="deploymentId">The deployment being applied — diagnostics only.</param>
|
||||
/// <param name="parsed">The apply's parsed artifact.</param>
|
||||
private void PushDesiredSubscriptionsFromParsed(DeploymentId deploymentId, ParsedDeploymentArtifact parsed)
|
||||
/// <param name="skipUnchanged">#995 R-11: the deploy path skips the re-subscribe of a driver with nothing
|
||||
/// seedable changed (see <see cref="ApplyDesiredSubscriptions"/>).</param>
|
||||
/// <returns>The drivers whose re-subscribe was skipped (empty unless <paramref name="skipUnchanged"/>).</returns>
|
||||
private IReadOnlyCollection<string> PushDesiredSubscriptionsFromParsed(
|
||||
DeploymentId deploymentId, ParsedDeploymentArtifact parsed, bool skipUnchanged = false)
|
||||
{
|
||||
AddressSpaceComposition composition;
|
||||
try
|
||||
@@ -4111,10 +4153,10 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warning(ex, "DriverHost {Node}: failed to parse composition for SubscribeBulk ({Id})", _localNode, deploymentId);
|
||||
return;
|
||||
return Array.Empty<string>();
|
||||
}
|
||||
|
||||
ApplyDesiredSubscriptions(composition);
|
||||
return ApplyDesiredSubscriptions(composition, skipUnchanged);
|
||||
}
|
||||
|
||||
/// <summary>Gets (creating on first use) the per-driver bucket of a secondary index.</summary>
|
||||
@@ -4135,7 +4177,13 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// Equipment VirtualTag + ScriptedAlarm plans to their hosts.
|
||||
/// </summary>
|
||||
/// <param name="composition">The composition this node should serve.</param>
|
||||
private void ApplyDesiredSubscriptions(AddressSpaceComposition composition)
|
||||
/// <param name="skipUnchanged">
|
||||
/// #995 R-11 (deploy path only): do not re-push a kept driver whose seeding fingerprint is unchanged and none of
|
||||
/// whose value refs gained a mux consumer. The caller re-pushes the returned drivers if the address-space apply
|
||||
/// turns out to be a rebuild. Every other path (boot, restore) pushes every child, as before.
|
||||
/// </param>
|
||||
/// <returns>The drivers whose push was skipped.</returns>
|
||||
private IReadOnlyCollection<string> ApplyDesiredSubscriptions(AddressSpaceComposition composition, bool skipUnchanged = false)
|
||||
{
|
||||
_catalogCoordinator?.BeforeSubscriptionApplyForTests?.Invoke();
|
||||
// v3 Batch 4: the driver subscribes + publishes by RawPath (the wire-ref == RawPath == RawTagPlan.NodeId
|
||||
@@ -4310,9 +4358,29 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
alarmRefsByDriver.TryGetValue(driverId, out var ar) ? ar : Array.Empty<string>());
|
||||
}
|
||||
|
||||
// #995 R-11: what a re-subscribe would seed, per driver, and which refs gained a mux consumer since the last apply.
|
||||
var previousFingerprints = _seedingFingerprints;
|
||||
_seedingFingerprints = new Dictionary<string, string[]>(StringComparer.Ordinal);
|
||||
foreach (var driverId in _desiredByDriver.Keys)
|
||||
_seedingFingerprints[driverId] = SeedingFingerprint(driverId, composition);
|
||||
var previousConsumerRefs = _consumerRefs;
|
||||
_consumerRefs = ConsumerRefs(composition);
|
||||
HashSet<string>? newConsumerRefs = null;
|
||||
if (previousConsumerRefs is not null)
|
||||
{
|
||||
newConsumerRefs = new HashSet<string>(_consumerRefs, StringComparer.Ordinal);
|
||||
newConsumerRefs.ExceptWith(previousConsumerRefs);
|
||||
}
|
||||
|
||||
var total = 0;
|
||||
List<string>? skipped = null;
|
||||
foreach (var (driverId, entry) in _children)
|
||||
{
|
||||
if (skipUnchanged && CanSkipResubscribe(driverId, entry.Actor, previousFingerprints, newConsumerRefs))
|
||||
{
|
||||
(skipped ??= new List<string>()).Add(driverId);
|
||||
continue;
|
||||
}
|
||||
total += SendDesiredSubscriptions(entry.Actor, driverId);
|
||||
}
|
||||
|
||||
@@ -4321,6 +4389,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_log.Info("DriverHost {Node}: SubscribeBulk pushed {Refs} references across {Drivers} driver(s)",
|
||||
_localNode, total, refsByDriver.Count);
|
||||
}
|
||||
if (skipped is not null)
|
||||
{
|
||||
_log.Info("DriverHost {Node}: SubscribeBulk kept {Count} unchanged driver subscription(s) without re-subscribing ({Drivers})",
|
||||
_localNode, skipped.Count, string.Join(", ", skipped));
|
||||
}
|
||||
|
||||
// Hand the Equipment-namespace VirtualTags to the host so it spawns/reconciles a
|
||||
// VirtualTagActor per plan and streams their evaluated values back onto the just-rebuilt
|
||||
@@ -4350,6 +4423,84 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_log.Info("DriverHost {Node}: applied {Count} Equipment ScriptedAlarm(s) to the ScriptedAlarm host",
|
||||
_localNode, composition.EquipmentScriptedAlarms.Count);
|
||||
}
|
||||
|
||||
return (IReadOnlyCollection<string>?)skipped ?? Array.Empty<string>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 R-11: whether the deploy push to <paramref name="driverId"/> can be skipped. Only when the child is the
|
||||
/// one that already holds a plain (non-acquisition) set from this host, that set and everything it seeds are
|
||||
/// unchanged (<see cref="SeedingFingerprint"/>), and none of its value refs gained a mux consumer — any of those
|
||||
/// means some node or consumer may be new and needs the initial values a re-subscribe produces.
|
||||
/// </summary>
|
||||
private bool CanSkipResubscribe(string driverId, IActorRef child, Dictionary<string, string[]> previousFingerprints,
|
||||
HashSet<string>? newConsumerRefs)
|
||||
{
|
||||
if (newConsumerRefs is null) return false; // first apply of this incarnation
|
||||
if (_acquisitionDemands.ContainsKey(driverId)) return false;
|
||||
if (!_plainPushedTo.TryGetValue(driverId, out var pushed) || !pushed.Equals(child)) return false;
|
||||
if (!previousFingerprints.TryGetValue(driverId, out var before)
|
||||
|| !_seedingFingerprints.TryGetValue(driverId, out var now)
|
||||
|| !before.AsSpan().SequenceEqual(now)) return false;
|
||||
if (newConsumerRefs.Count > 0 && _desiredByDriver.TryGetValue(driverId, out var set))
|
||||
foreach (var r in set.ValueRefs)
|
||||
if (newConsumerRefs.Contains(r)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 R-11: everything a deploy re-subscribe of <paramref name="driverId"/> would (re)seed — its value refs, each
|
||||
/// with its fan-out NodeIds (raw + every referencing UNS mirror, so a new or re-pointed mirror changes it) and its
|
||||
/// historization (a ref that starts being recorded), then its alarm refs. Built after the routing maps.
|
||||
/// </summary>
|
||||
private string[] SeedingFingerprint(string driverId, AddressSpaceComposition composition)
|
||||
{
|
||||
var set = _desiredByDriver[driverId];
|
||||
var historized = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var t in composition.RawTags)
|
||||
if (string.Equals(t.DriverInstanceId, driverId, StringComparison.Ordinal))
|
||||
historized[t.NodeId] = t.IsHistorized ? "H:" + t.HistorianTagname : "-";
|
||||
var parts = new List<string>(set.ValueRefs.Count + set.AlarmRefs.Count + 1);
|
||||
foreach (var r in set.ValueRefs)
|
||||
{
|
||||
var nodes = _nodeIdByDriverRef.TryGetValue((driverId, r), out var fan)
|
||||
? string.Join("|", fan.Select(n => n.Realm + ":" + n.NodeId).Order(StringComparer.Ordinal))
|
||||
: string.Empty;
|
||||
parts.Add("v\u0001" + r + "\u0001" + historized.GetValueOrDefault(r, "-") + "\u0001" + nodes);
|
||||
}
|
||||
parts.Add("alarms");
|
||||
foreach (var r in set.AlarmRefs) parts.Add("a\u0001" + r);
|
||||
return parts.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>#995 R-11: every ref a mux consumer reads under <paramref name="composition"/> — enabled VirtualTags,
|
||||
/// enabled scripted alarms and the hosted dependency-consuming drivers (read after the apply's reconcile).</summary>
|
||||
private HashSet<string> ConsumerRefs(AddressSpaceComposition composition)
|
||||
{
|
||||
var refs = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var vt in composition.EquipmentVirtualTags)
|
||||
if (vt.Enabled) refs.UnionWith(vt.DependencyRefs);
|
||||
foreach (var a in composition.EquipmentScriptedAlarms)
|
||||
if (a.Enabled) refs.UnionWith(a.DependencyRefs);
|
||||
foreach (var consumer in _depConsumers.Values) refs.UnionWith(consumer.DependencyRefs);
|
||||
return refs;
|
||||
}
|
||||
|
||||
/// <summary>#995 R-11: re-push the drivers an apply skipped, once its address-space outcome says their nodes were
|
||||
/// recreated (a rebuild), may be partial (degraded) or is unknown (timed out). Always forgets the entry.</summary>
|
||||
private void SeedSkippedDrivers(CorrelationId correlation, bool reseed, string why)
|
||||
{
|
||||
if (!_seedAfterAddressSpace.Remove(correlation, out var skipped) || !reseed) return;
|
||||
var pushed = 0;
|
||||
foreach (var driverId in skipped)
|
||||
if (_children.TryGetValue(driverId, out var child))
|
||||
{
|
||||
SendDesiredSubscriptions(child.Actor, driverId);
|
||||
pushed++;
|
||||
}
|
||||
if (pushed > 0)
|
||||
_log.Info("DriverHost {Node}: re-subscribing {Count} kept driver(s) after the address-space apply ({Why})",
|
||||
_localNode, pushed, why);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -4374,8 +4525,17 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
{
|
||||
var demand = _acquisitionDemands.GetValueOrDefault(driverId);
|
||||
var message = BuildDesiredSubscriptions(driverId, demand);
|
||||
if (demand is null) actor.Tell(message);
|
||||
else if (!_acquisitionPending.ContainsKey(driverId)) StartAcquisitionDemand(driverId, demand, ActorRefs.Nobody);
|
||||
if (demand is null)
|
||||
{
|
||||
actor.Tell(message);
|
||||
_plainPushedTo[driverId] = actor;
|
||||
}
|
||||
else
|
||||
{
|
||||
// #995 R-11: an acquisition-demand set is not the plain set a later deploy could compare against.
|
||||
_plainPushedTo.Remove(driverId);
|
||||
if (!_acquisitionPending.ContainsKey(driverId)) StartAcquisitionDemand(driverId, demand, ActorRefs.Nobody);
|
||||
}
|
||||
return message.FullReferences.Count;
|
||||
}
|
||||
|
||||
@@ -4831,6 +4991,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyConsumerMuxAdapter.Props(consumer, _dependencyMux),
|
||||
"depmux-" + actorName);
|
||||
_depConsumerAdapters[spec.DriverInstanceId] = adapter;
|
||||
_depConsumers[spec.DriverInstanceId] = consumer;
|
||||
_log.Info("DriverHost {Node}: wired dependency-consumer mux adapter for {Id} ({Count} ref(s))",
|
||||
_localNode, spec.DriverInstanceId, consumer.DependencyRefs.Count);
|
||||
}
|
||||
@@ -4843,6 +5004,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// driver child is stopped/respawned so a stale adapter never keeps a dead driver's refs registered.</summary>
|
||||
private void StopDependencyAdapter(string driverInstanceId)
|
||||
{
|
||||
_depConsumers.Remove(driverInstanceId);
|
||||
if (_depConsumerAdapters.Remove(driverInstanceId, out var adapter))
|
||||
Context.Stop(adapter);
|
||||
}
|
||||
@@ -4864,6 +5026,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
_dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(driverInstanceId);
|
||||
Context.Stop(entry.Actor);
|
||||
_children.Remove(driverInstanceId);
|
||||
_plainPushedTo.Remove(driverInstanceId);
|
||||
// A1 review S2: the stopped incarnation can no longer vouch for its conditions (a respawn's carried-over
|
||||
// known state would otherwise stand until the new incarnation signals). No-op when the deploy removed them.
|
||||
WithdrawDriverConditionsKnown(driverInstanceId);
|
||||
|
||||
@@ -139,10 +139,15 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// ack only after that reply, so a degraded apply can no longer seal a deployment green. Off for the
|
||||
/// boot/restore paths, which re-ack nothing.
|
||||
/// </param>
|
||||
/// <param name="ArtifactRevision">
|
||||
/// Gitea #995 (R-14): SHA-256 (lower hex) of <see cref="Artifact"/>, computed ONCE by the actor when the request
|
||||
/// arrives and reused for the catalog attempt, the data-catalog generation and the data-plane authority revision
|
||||
/// — it used to be hashed up to three times on the pinned OPC UA thread. Callers leave it null.
|
||||
/// </param>
|
||||
public sealed record RebuildAddressSpace(
|
||||
CorrelationId Correlation, DeploymentId? DeploymentId = null, byte[]? Artifact = null,
|
||||
bool ReportOutcome = false, DataConnections.CatalogAttempt? CatalogAttempt = null,
|
||||
bool StageCatalog = false);
|
||||
bool StageCatalog = false, string? ArtifactRevision = null);
|
||||
|
||||
/// <summary>
|
||||
/// the reply to a <see cref="RebuildAddressSpace"/> carrying
|
||||
@@ -156,8 +161,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// stale. An empty plan (nothing changed) is clean.
|
||||
/// </param>
|
||||
/// <param name="DegradedReason">A short operator-readable reason; null when clean.</param>
|
||||
/// <param name="AddressSpaceRebuilt">
|
||||
/// Gitea #995 (R-11): <see langword="false"/> only when the apply was a clean NON-rebuild — every node that
|
||||
/// existed before it still exists with its value. <c>DriverHostActor</c> skips the re-subscribe of a driver
|
||||
/// whose desired set and fan-out are unchanged, and re-pushes those drivers when this is <see langword="true"/>
|
||||
/// (a full rebuild recreated their nodes without a value). Defaults to <see langword="true"/> — the
|
||||
/// conservative answer for any producer that does not know.
|
||||
/// </param>
|
||||
public sealed record RebuildCompleted(
|
||||
CorrelationId Correlation, DeploymentId? DeploymentId, bool Degraded, string? DegradedReason);
|
||||
CorrelationId Correlation, DeploymentId? DeploymentId, bool Degraded, string? DegradedReason,
|
||||
bool AddressSpaceRebuilt = true);
|
||||
|
||||
public sealed record ServiceLevelChanged(byte ServiceLevel);
|
||||
|
||||
@@ -175,11 +188,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
private sealed record PlanReady(
|
||||
object Incarnation, RebuildAddressSpace Request, IActorRef Requester, byte[] Artifact,
|
||||
DataPlaneAuthorityProjection? Authority, Exception? AuthorityError,
|
||||
AddressSpaceComposition Composition, AddressSpacePlan Plan, IReadOnlyList<string> Inconsistencies);
|
||||
AddressSpaceComposition Composition, AddressSpacePlan Plan, IReadOnlyList<string> Inconsistencies,
|
||||
string? ClusterRedundancyMode = null);
|
||||
|
||||
/// <summary>The off-thread parse / plan step threw (unreadable bytes, a composer fault).</summary>
|
||||
private sealed record PlanFailed(object Incarnation, RebuildAddressSpace Request, IActorRef Requester,
|
||||
Exception Error, DataPlaneAuthorityProjection? Authority = null, byte[]? Artifact = null);
|
||||
Exception Error, DataPlaneAuthorityProjection? Authority = null, byte[]? Artifact = null,
|
||||
string? ClusterRedundancyMode = null);
|
||||
|
||||
/// <summary>Test seams for the off-thread plan step. Production passes none.</summary>
|
||||
internal sealed class TestHooks
|
||||
@@ -189,6 +204,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
internal Action? BeforePlan { get; init; }
|
||||
internal Action? BeforeComposition { get; init; }
|
||||
|
||||
/// <summary>#995 R-14: observes every artifact redundancy-mode read (the reading thread's managed id), so a test can
|
||||
/// assert it ran on the plan step rather than the actor thread.</summary>
|
||||
internal Action<int>? OnRedundancyModeRead { get; init; }
|
||||
|
||||
/// <summary>Replaces <see cref="ParsedDeploymentArtifact.ParseDataPlaneAuthority"/> (a test makes it throw).</summary>
|
||||
internal Func<ParsedDeploymentArtifact, string, DataPlaneAuthorityProjection>? ParseAuthority { get; init; }
|
||||
}
|
||||
@@ -484,12 +503,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
IDataPlaneAuthoritySink? dataPlaneAuthority = null,
|
||||
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
|
||||
DataConnections.DataConnectionWarmRoleView? dataWarmRole = null,
|
||||
DataConnections.DataConnectionDeploymentRuntime? dataConnections = null) =>
|
||||
DataConnections.DataConnectionDeploymentRuntime? dataConnections = null,
|
||||
WarmRedundancySettings? redundancy = null) =>
|
||||
// CreateBy, not Create(expression): Akka's expression path activates through a PUBLIC constructor, and the
|
||||
// seam-carrying constructor is internal so the test seams stay off the public API (review M3).
|
||||
Akka.Actor.Props.CreateBy(new TestProducer(() => new OpcUaPublishActor(
|
||||
sink, NullServiceLevelPublisher.Instance, false, localNode, null, applier, null, null, null, null,
|
||||
false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null,
|
||||
false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null, redundancy: redundancy,
|
||||
catalogCoordinator: catalogCoordinator, dataWarmRole: dataWarmRole, dataConnections: dataConnections)));
|
||||
|
||||
/// <summary>Produces the actor through its internal (seam-carrying) constructor, for <see cref="PropsForTests(IOpcUaAddressSpaceSink, AddressSpaceApplier?, TestHooks?, int, NodeId?, IDataPlaneAuthoritySink?)"/>.</summary>
|
||||
@@ -877,16 +897,23 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
|
||||
private void HandleRebuild(RebuildAddressSpace msg)
|
||||
{
|
||||
// #995 R-14: hash the artifact ONCE; the catalog attempt, the data-catalog generation and the authority revision
|
||||
// all reuse it. The redundancy-mode cross-check is no longer a second full parse here: the plan step reads it
|
||||
// from its own parse, off this pinned thread (CheckRedundancyMode on PlanReady/PlanFailed).
|
||||
msg = WithArtifactRevision(msg);
|
||||
if (_catalogCoordinator is not null && msg.CatalogAttempt is null)
|
||||
{
|
||||
var revision = msg.Artifact is { Length: > 0 } bytes
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)) : "unavailable";
|
||||
msg = msg with { CatalogAttempt = _catalogCoordinator.BeginAttempt(revision), StageCatalog = true };
|
||||
}
|
||||
if (msg.Artifact is { Length: > 0 } artifact) CheckRedundancyMode(artifact);
|
||||
msg = msg with { CatalogAttempt = _catalogCoordinator.BeginAttempt(msg.ArtifactRevision!), StageCatalog = true };
|
||||
StartRebuild(msg, Sender);
|
||||
}
|
||||
|
||||
/// <summary>#995 R-14: stamp the request with its artifact's SHA-256 (or "unavailable"), unless it already carries it.</summary>
|
||||
private static RebuildAddressSpace WithArtifactRevision(RebuildAddressSpace msg) =>
|
||||
msg.ArtifactRevision is not null ? msg : msg with
|
||||
{
|
||||
ArtifactRevision = msg.Artifact is { Length: > 0 } bytes
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)) : "unavailable",
|
||||
};
|
||||
|
||||
private void StageStandaloneCatalog(RebuildAddressSpace msg, ParsedDeploymentArtifact parsed)
|
||||
{
|
||||
if (_catalogCoordinator is null || msg.CatalogAttempt is null) return;
|
||||
@@ -938,9 +965,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
|
||||
// Close the data-service generation before any fallible parse or topology work. Ordinary
|
||||
// local OPC UA availability remains independent; remote/mapped access uses this barrier.
|
||||
var desiredRevision = msg.Artifact is { Length: > 0 } desiredBytes
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(desiredBytes))
|
||||
: "unavailable";
|
||||
msg = WithArtifactRevision(msg);
|
||||
var desiredRevision = msg.ArtifactRevision!;
|
||||
if (_catalogCoordinator is null) _dataCatalogEpoch = _dataCatalog.Begin(desiredRevision);
|
||||
|
||||
// Only a node with NO applier at all (the F10b/dev seam) falls back to the raw-sink rebuild — and that
|
||||
@@ -948,6 +974,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
// real driver node that has an applier (that node diff-and-applies from its in-hand bytes below).
|
||||
if (_applier is null)
|
||||
{
|
||||
if (msg.Artifact is { Length: > 0 } modeBytes && WantsRedundancyModeCheck())
|
||||
CheckRedundancyMode(ReadRedundancyModeSafe(modeBytes, _localNode!.Value.Value, _hooks));
|
||||
if (msg.StageCatalog && msg.Artifact is { Length: > 0 } standaloneBytes)
|
||||
{
|
||||
try { using var parsed = DeploymentArtifact.Open(standaloneBytes); StageStandaloneCatalog(msg, parsed); }
|
||||
@@ -1001,6 +1029,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
var baseComposition = _lastApplied;
|
||||
var nodeId = _localNode?.Value;
|
||||
var wantAuthority = _dataPlaneAuthority is not null && _catalogCoordinator is null;
|
||||
var wantMode = WantsRedundancyModeCheck();
|
||||
var incarnation = _incarnation;
|
||||
var hooks = _hooks;
|
||||
Task.Run<object>(() =>
|
||||
@@ -1010,6 +1039,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
// result — and an empty composition is not a benign no-op here (see the no-bytes guard above). The
|
||||
// throw lands in PlanFailed: logged at Error, _lastApplied untouched, last-known-good still served.
|
||||
using var parsed = DeploymentArtifact.Open(artifact);
|
||||
// #995 R-14: the redundancy-mode cross-check reads this parse (it used to be a second full inflate +
|
||||
// parse of the artifact on the pinned actor thread). Compared and logged back on the actor thread.
|
||||
string? clusterMode = null;
|
||||
if (wantMode && nodeId is not null)
|
||||
{
|
||||
hooks?.OnRedundancyModeRead?.Invoke(Environment.CurrentManagedThreadId);
|
||||
// A diagnostic read: whatever it throws must never fail the address-space plan.
|
||||
try { clusterMode = DeploymentArtifact.ReadClusterRedundancyMode(parsed, nodeId); }
|
||||
catch (Exception) { clusterMode = null; }
|
||||
}
|
||||
if (msg.StageCatalog) StageStandaloneCatalog(msg, parsed);
|
||||
// The authority parse is isolated from the address-space plan (review fix I2): before the plan moved
|
||||
// off-thread a throw here was contained by FeedDataPlaneAuthority's own catch; it must not now
|
||||
@@ -1038,13 +1077,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
? parsed.ParseComposition(nodeId, inconsistencies.Add)
|
||||
: parsed.ParseComposition();
|
||||
var plan = AddressSpacePlanner.Compute(baseComposition, composition);
|
||||
return new PlanReady(incarnation, msg, requester, artifact, authority, authorityError, composition, plan, inconsistencies);
|
||||
return new PlanReady(incarnation, msg, requester, artifact, authority, authorityError, composition, plan, inconsistencies,
|
||||
clusterMode);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Parsed revocations remain independent of topology planning. Transfer them back
|
||||
// to the actor thread even when no address-space plan could be constructed.
|
||||
return new PlanFailed(incarnation, msg, requester, ex, authority, artifact);
|
||||
return new PlanFailed(incarnation, msg, requester, ex, authority, artifact, clusterMode);
|
||||
}
|
||||
})
|
||||
.PipeTo(Self, failure: ex => new PlanFailed(incarnation, msg, requester, ex));
|
||||
@@ -1053,6 +1093,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
private void HandlePlanReady(PlanReady ready)
|
||||
{
|
||||
if (IsFromAnotherIncarnation(ready.Incarnation, ready.Request, ready.Requester)) return;
|
||||
CheckRedundancyMode(ready.ClusterRedundancyMode);
|
||||
|
||||
if (ready.AuthorityError is { } authorityError)
|
||||
_log.Error(authorityError,
|
||||
@@ -1076,9 +1117,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
private void HandlePlanFailed(PlanFailed failed)
|
||||
{
|
||||
if (IsFromAnotherIncarnation(failed.Incarnation, failed.Request, failed.Requester)) return;
|
||||
CheckRedundancyMode(failed.ClusterRedundancyMode);
|
||||
|
||||
if (failed.Authority is not null && failed.Artifact is not null)
|
||||
FeedDataPlaneAuthority(failed.Authority, failed.Artifact);
|
||||
FeedDataPlaneAuthority(failed.Authority, failed.Artifact, failed.Request.ArtifactRevision);
|
||||
|
||||
_planInFlight = false;
|
||||
_log.Error(failed.Error, "OpcUaPublish: rebuild pipeline threw (correlation={Correlation})", failed.Request.Correlation);
|
||||
@@ -1491,6 +1533,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
outcome = (true, $"address-space completion threw: {ex.Message}");
|
||||
}
|
||||
|
||||
// #995 R-11: captured before the replay scope is reset — a rebuild (or the applier-less raw-sink rebuild) recreated
|
||||
// every node, so the driver host must re-seed values it skipped re-subscribing.
|
||||
var rebuilt = _applier is null || _replayScope.AllVariables;
|
||||
|
||||
// Land what arrived while the plan was in flight on the nodes the apply just created — before the answer,
|
||||
// so "applied" means the deferred first values are on the address space too (review fix C1).
|
||||
ReplayDeferredWrites(_replayScope);
|
||||
@@ -1504,7 +1550,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
|
||||
if (msg.ReportOutcome)
|
||||
requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason));
|
||||
requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason,
|
||||
AddressSpaceRebuilt: rebuilt));
|
||||
}
|
||||
|
||||
/// <summary>The actor-thread half of a rebuild: install the artifact's authority, apply the plan through the
|
||||
@@ -1580,7 +1627,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
// feeding this after that return would leave a revoked key authenticating until some unrelated
|
||||
// structural change happened to redeploy. Authorization and topology change on their own
|
||||
// schedules.
|
||||
if (ready.Authority is not null) FeedDataPlaneAuthority(ready.Authority, ready.Artifact);
|
||||
if (ready.Authority is not null) FeedDataPlaneAuthority(ready.Authority, ready.Artifact, ready.Request.ArtifactRevision);
|
||||
|
||||
var composition = ready.Composition;
|
||||
var plan = ready.Plan;
|
||||
@@ -1870,7 +1917,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// <param name="projection">The keys + grants decoded (off-thread) from the rebuild's single parse of the artifact.</param>
|
||||
/// <param name="artifactBytes">The RAW artifact bytes — hashed for the revision id, which must be
|
||||
/// SHA-256 of the exact blob (see below); never re-parsed here.</param>
|
||||
private void FeedDataPlaneAuthority(DataPlaneAuthorityProjection projection, byte[] artifactBytes)
|
||||
/// <param name="revision">#995 R-14: the request's already-computed SHA-256 of <paramref name="artifactBytes"/>; hashed
|
||||
/// here only when absent.</param>
|
||||
private void FeedDataPlaneAuthority(DataPlaneAuthorityProjection projection, byte[] artifactBytes, string? revision = null)
|
||||
{
|
||||
if (_dataPlaneAuthority is null) return;
|
||||
|
||||
@@ -1880,7 +1929,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
// which is what lets a node recognise a re-applied revision without the hash riding the wire.
|
||||
// Hashed off the RAW bytes for exactly that reason: a re-serialisation of the parsed document
|
||||
// would be a different byte sequence and would not match the deployment's RevisionHash.
|
||||
var revision = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(artifactBytes));
|
||||
revision ??= Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(artifactBytes));
|
||||
var snapshot = _dataPlaneAuthority.Apply(
|
||||
projection.ClusterId, revision, projection.Keys, projection.Grants, projection.ScopePaths,
|
||||
projection.EquipmentScopePaths, projection.ScriptedAlarmOwners, projection.UnsFolderScopes,
|
||||
@@ -2374,21 +2423,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// counts <c>otopcua.redundancy.mode_mismatch</c>. The node keeps its local mode — the only value available
|
||||
/// before SDK start. <c>Unset</c> has opted out and is not checked.
|
||||
/// </summary>
|
||||
/// <param name="artifact">The applied artifact bytes.</param>
|
||||
private void CheckRedundancyMode(byte[] artifact)
|
||||
/// <param name="clusterMode">The artifact's cluster mode, read off the plan step's parse (#995 R-14); null when the
|
||||
/// artifact does not say or could not be read.</param>
|
||||
private void CheckRedundancyMode(string? clusterMode)
|
||||
{
|
||||
if (_redundancy.Mode == OpcUaRedundancyMode.Unset || _localNode is null) return;
|
||||
string? clusterMode;
|
||||
try
|
||||
{
|
||||
clusterMode = DeploymentArtifact.ReadClusterRedundancyMode(artifact, _localNode.Value.Value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Debug(ex, "OpcUaPublish: could not read the artifact's cluster RedundancyMode");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!WantsRedundancyModeCheck()) return;
|
||||
if (clusterMode is null) return;
|
||||
if (string.Equals(clusterMode, _redundancy.Mode.ToString(), StringComparison.OrdinalIgnoreCase)) return;
|
||||
OtOpcUaTelemetry.RedundancyModeMismatch.Add(1,
|
||||
@@ -2399,6 +2438,17 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
clusterMode, _redundancy.Mode, _redundancy.Mode);
|
||||
}
|
||||
|
||||
/// <summary>Whether the #717 deploy-time redundancy-mode cross-check applies on this node.</summary>
|
||||
private bool WantsRedundancyModeCheck() => _redundancy.Mode != OpcUaRedundancyMode.Unset && _localNode is not null;
|
||||
|
||||
/// <summary>The applier-less (dev) path's synchronous redundancy-mode read; never throws.</summary>
|
||||
private static string? ReadRedundancyModeSafe(byte[] artifact, string nodeId, TestHooks? hooks)
|
||||
{
|
||||
hooks?.OnRedundancyModeRead?.Invoke(Environment.CurrentManagedThreadId);
|
||||
try { return DeploymentArtifact.ReadClusterRedundancyMode(artifact, nodeId); }
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
private void ScheduleWarmRetry() => Timers.StartSingleTimer("warm-retry", WarmRetry.Instance, TimeSpan.FromSeconds(1));
|
||||
|
||||
/// <summary>The legacy role-only ServiceLevel switch (primary-leader → 240, primary → 200,
|
||||
|
||||
@@ -31,14 +31,22 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
|
||||
/// <b>Evaluation never blocks the dispatcher (lmxopcua#779, #750 P0).</b> The evaluator is called through
|
||||
/// <see cref="IVirtualTagEvaluator.EvaluateAsync"/>. A synchronously completed result (passthrough, the null
|
||||
/// evaluator, test fakes) is applied inline in the same message turn, exactly as before. An incomplete one — a
|
||||
/// Roslyn script run, up to its 2 s budget — switches the actor into an <i>evaluating</i> behaviour that
|
||||
/// <b>stashes</b> every dependency / reassert message, and the result comes back as a private completion
|
||||
/// message. Applying it unstashes everything in arrival order. So each trigger is still evaluated against
|
||||
/// the dependency map as it stood at that trigger, results are applied and published in trigger order, and
|
||||
/// the dedup / Bad-transition state sees exactly the sequence it saw when the call blocked — only the
|
||||
/// dispatcher thread is no longer held while the script runs. The dependency map is not touched while a run
|
||||
/// is in flight (the messages that would touch it are stashed), which is what makes handing it to the
|
||||
/// script on another thread safe.
|
||||
/// Roslyn script run, up to its 2 s budget — switches the actor into an <i>evaluating</i> behaviour, and the
|
||||
/// result comes back as a private completion message. The dependency map is not touched while a run is in
|
||||
/// flight, which is what makes handing it to the script on another thread safe.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Inputs that arrive during a run are coalesced (#995, review R-19).</b> They are held one slot per input —
|
||||
/// the newest value wins — and when the run completes they are applied together and evaluated <b>once</b>, stamped
|
||||
/// with the newest arrival's timestamp (the rule a batched mux burst already follows). They used to be stashed one
|
||||
/// message per trigger and replayed as one script run each, so a slow script (or the out-of-process runner under
|
||||
/// load) built an unbounded backlog of evaluations against inputs that were already superseded, with O(M²)
|
||||
/// re-stash hops. The backlog is now bounded by the tag's input count. Other messages (reassert, runner recovery,
|
||||
/// source-binding retry, projected wakes) are still stashed and run after the coalesced evaluation starts.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The value dedup compares one-dimensional arrays element-wise (#995), so an array-typed tag whose output did not
|
||||
/// change is not republished, re-routed to its dependents and historized on every evaluation.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
@@ -135,6 +143,10 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
private readonly Dictionary<string, DataValueSnapshot> _dependencies = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, Core.Abstractions.DataConnections.IProjectedSamplePublicationProof> _projectedDependencyProofs = new(StringComparer.Ordinal);
|
||||
|
||||
// #995 (R-19): inputs that arrived while a run was in flight, latest per input; applied when it completes.
|
||||
private readonly Dictionary<string, DependencyValueChanged> _heldInputs = new(StringComparer.Ordinal);
|
||||
private DateTime _heldTimestampUtc;
|
||||
|
||||
private bool _hasLastValue;
|
||||
private object? _lastValue;
|
||||
|
||||
@@ -436,14 +448,75 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
if (msg.ActorIncarnation != _actorIncarnation) return;
|
||||
UnbecomeStacked();
|
||||
ApplyEvaluation(msg.Evaluation, msg.WorstInputStatus, msg.TimestampUtc);
|
||||
// #995 (R-19): every input that arrived during the run lands now, at once, and is evaluated ONCE —
|
||||
// before the stashed control messages, so a reassert queued behind the run re-emits the newest state.
|
||||
ReleaseHeldInputs();
|
||||
Stash.UnstashAll();
|
||||
});
|
||||
// A timer tick during a run is dropped, not stashed: the run in flight IS this interval's evaluation,
|
||||
// and stashing would replay a backlog of ticks (one script run each) after a slow script (#783).
|
||||
Receive<TimerTick>(_ => { });
|
||||
// #995 (R-19): inputs are folded, latest value per input wins, instead of stashed one message per trigger.
|
||||
Receive<DependencyValueChanged>(HoldInput);
|
||||
Receive<DependencyValueBatch>(msg =>
|
||||
{
|
||||
var items = msg.Items;
|
||||
for (var i = 0; i < items.Count; i++) HoldInput(items[i]);
|
||||
});
|
||||
ReceiveAny(_ => Stash.Stash());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 (R-19): an input that arrived while a run is in flight. The dependency map cannot change under the
|
||||
/// running script (it is handed to it on another thread), so the value is held here — one slot per input,
|
||||
/// the newest wins — and applied when the run completes. This bounds the backlog by the tag's input count,
|
||||
/// where stashing grew it by one message per trigger and replayed them as one script run each (O(M²)
|
||||
/// re-stash hops under a slow script).
|
||||
/// </summary>
|
||||
/// <param name="item">The arrived input.</param>
|
||||
private void HoldInput(DependencyValueChanged item)
|
||||
{
|
||||
_heldInputs[item.TagId] = item;
|
||||
_heldTimestampUtc = item.TimestampUtc;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies every held input (see <see cref="HoldInput"/>) to the dependency map and, for a change-triggered tag,
|
||||
/// evaluates once against the result — stamped with the newest arrival's timestamp, the same rule
|
||||
/// <see cref="OnDependencyBatch"/> applies to a mux burst. No-op when nothing arrived during the run.
|
||||
/// </summary>
|
||||
private void ReleaseHeldInputs()
|
||||
{
|
||||
if (_heldInputs.Count == 0) return;
|
||||
foreach (var item in _heldInputs.Values)
|
||||
{
|
||||
SetDependencyProof(item);
|
||||
_dependencies[item.TagId] = new DataValueSnapshot(item.Value, item.StatusCode, item.TimestampUtc, item.TimestampUtc);
|
||||
}
|
||||
_heldInputs.Clear();
|
||||
if (_changeTriggered) Evaluate(_heldTimestampUtc);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The value dedup's equality: <see cref="object.Equals(object?, object?)"/>, except that two one-dimensional
|
||||
/// arrays compare element by element (#995, R-19). Each evaluation result is a fresh copy, so reference equality
|
||||
/// made an array-typed tag publish — and re-trigger its dependents and historize — on every evaluation even when
|
||||
/// its output never changed. Arrays of different element types never compare equal.
|
||||
/// </summary>
|
||||
/// <param name="a">The last published value.</param>
|
||||
/// <param name="b">The new value.</param>
|
||||
/// <returns>True when the two values are the same output.</returns>
|
||||
internal static bool SameValue(object? a, object? b)
|
||||
{
|
||||
if (a is Array x && b is Array y)
|
||||
{
|
||||
if (ReferenceEquals(x, y)) return true;
|
||||
if (x.Rank != 1 || y.Rank != 1 || x.GetType() != y.GetType()) return false;
|
||||
return System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(x, y);
|
||||
}
|
||||
return Equals(a, b);
|
||||
}
|
||||
|
||||
private static Task<VirtualTagEvalResult> FreezeEvaluation(Task<VirtualTagEvalResult> task)
|
||||
{
|
||||
if (!task.IsCompletedSuccessfully || !task.Result.Success || ReferenceEquals(task.Result, VirtualTagEvalResult.NoChange))
|
||||
@@ -542,7 +615,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
// Dedup on (value, STATUS) — 02/S14 generalising 02/S13's recover-from-Bad bypass. Keying on
|
||||
// value alone swallows every recovery whose value is unchanged, which is what a device coming
|
||||
// back usually produces, and the node then stays Bad forever.
|
||||
if (_hasPublished && _lastPublishedStatus == worst && _hasLastValue && Equals(_lastValue, result.Value))
|
||||
if (_hasPublished && _lastPublishedStatus == worst && _hasLastValue && SameValue(_lastValue, result.Value))
|
||||
{
|
||||
OtOpcUaTelemetry.VirtualTagEval.Add(1, new KeyValuePair<string, object?>("outcome", "skip"));
|
||||
return;
|
||||
|
||||
@@ -61,6 +61,22 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
|
||||
private VirtualTagHostRestarted() { }
|
||||
}
|
||||
/// <summary>
|
||||
/// #995 (review R-17): re-attempt the data-plane source binding of the tags the last apply could not bind —
|
||||
/// and nothing else. The retry used to re-deliver the whole <see cref="ApplyVirtualTags"/> every 250 ms with no
|
||||
/// backoff, so every attempt lifted the run guard's quarantines (re-running a runaway script), re-asserted every
|
||||
/// surviving child, republished every disabled tag's <c>BadOutOfService</c> and recomputed the cycle graph.
|
||||
/// </summary>
|
||||
/// <param name="Attempt">Zero-based attempt number; the delay before the next attempt doubles with it.</param>
|
||||
private sealed record RetrySourceBindings(int Attempt);
|
||||
|
||||
private const string SourceBindingRetryTimerKey = "source-binding-retry";
|
||||
|
||||
/// <summary>First source-binding retry delay (#995). Doubles per failed attempt up to <see cref="SourceBindingRetryCap"/>.</summary>
|
||||
internal static readonly TimeSpan SourceBindingRetryInitial = TimeSpan.FromMilliseconds(250);
|
||||
|
||||
/// <summary>Longest source-binding retry delay (#995).</summary>
|
||||
internal static readonly TimeSpan SourceBindingRetryCap = TimeSpan.FromSeconds(5);
|
||||
|
||||
private readonly IActorRef? _publishActor;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
|
||||
@@ -86,6 +102,11 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
private readonly HashSet<string> _deployedKeys = new(StringComparer.Ordinal);
|
||||
// Keys on a VirtualTag dependency cycle (lmxopcua#791 runtime backstop): their outputs are never routed.
|
||||
private readonly HashSet<string> _unroutedKeys = new(StringComparer.Ordinal);
|
||||
// #995 (R-17): enabled tags of the current apply whose source binding failed, so no child was spawned yet.
|
||||
private readonly HashSet<string> _unboundEnabled = new(StringComparer.Ordinal);
|
||||
// #995 (R-17): disabled tags of the current apply whose source binding failed, so their BadOutOfService did not
|
||||
// reach the data plane yet (the OPC UA node and the mux already have it).
|
||||
private readonly HashSet<string> _unboundDisabled = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Factory method to create Props for a VirtualTagHostActor.</summary>
|
||||
/// <param name="publishActor">The OPC UA publish actor that consumes
|
||||
@@ -124,6 +145,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
_telemetryHub = telemetryHub;
|
||||
|
||||
Receive<ApplyVirtualTags>(OnApply);
|
||||
Receive<RetrySourceBindings>(OnRetrySourceBindings);
|
||||
Receive<VirtualTagActor.EvaluationResult>(OnResult);
|
||||
Receive<Terminated>(OnChildTerminated);
|
||||
}
|
||||
@@ -138,7 +160,9 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
|
||||
private void OnApply(ApplyVirtualTags msg)
|
||||
{
|
||||
Timers.Cancel("source-binding-retry");
|
||||
Timers.Cancel(SourceBindingRetryTimerKey);
|
||||
_unboundEnabled.Clear();
|
||||
_unboundDisabled.Clear();
|
||||
// lmxopcua#978 (review R-5): drop a plan whose NodeId cannot be built BEFORE anything is stopped or
|
||||
// spawned. Unguarded, one illegal name threw here, supervision restarted the host (stopping every
|
||||
// child), and nothing re-sent ApplyVirtualTags — every VirtualTag on the node stopped evaluating, on
|
||||
@@ -236,42 +260,8 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
foreach (var p in evaluated)
|
||||
{
|
||||
if (_children.ContainsKey(p.VirtualTagId)) continue;
|
||||
|
||||
// Auto-name the child: vtagIds can contain characters illegal in actor names, so let Akka
|
||||
// assign a safe unique name. The child self-registers with the mux in PreStart.
|
||||
long? sourceIncarnation = null;
|
||||
if (_sourcePublisher is not null)
|
||||
{
|
||||
if (!_virtualSourceIncarnations.TryGetValue(p.VirtualTagId, out var currentToken))
|
||||
currentToken = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
|
||||
sourceIncarnation = currentToken;
|
||||
}
|
||||
if (sourceIncarnation is { } token)
|
||||
{
|
||||
_virtualSourceIncarnations[p.VirtualTagId] = token;
|
||||
if (!_sourcePublisher!.EnsureVirtualBinding(p.VirtualTagId, token))
|
||||
{
|
||||
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
var child = Context.ActorOf(VirtualTagActor.Props(
|
||||
virtualTagId: p.VirtualTagId,
|
||||
expression: p.Expression,
|
||||
evaluator: _evaluator,
|
||||
scriptId: p.VirtualTagId,
|
||||
publisherFactory: null,
|
||||
dependencyRefs: p.DependencyRefs,
|
||||
mux: _mux,
|
||||
telemetryHub: _telemetryHub,
|
||||
changeTriggered: p.ChangeTriggered,
|
||||
timerIntervalMs: p.TimerIntervalMs,
|
||||
sourcePublisher: _sourcePublisher,
|
||||
sourceIncarnation: sourceIncarnation));
|
||||
Context.Watch(child);
|
||||
_children[p.VirtualTagId] = child;
|
||||
newlySpawned.Add(p.VirtualTagId);
|
||||
_log.Debug("VirtualTagHost: spawned child for vtag {VirtualTagId}", p.VirtualTagId);
|
||||
if (TrySpawnChild(p)) newlySpawned.Add(p.VirtualTagId);
|
||||
else _unboundEnabled.Add(p.VirtualTagId);
|
||||
}
|
||||
|
||||
// Refresh the plan map to exactly the desired set so the next apply can detect in-place
|
||||
@@ -319,7 +309,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
if (_sourcePublisher is not null &&
|
||||
!_sourcePublisher.EnsureVirtualBinding(p.VirtualTagId, _virtualSourceIncarnations[p.VirtualTagId]))
|
||||
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
|
||||
_unboundDisabled.Add(p.VirtualTagId);
|
||||
var nodeId = NodeIdFor(p);
|
||||
var now = DateTime.UtcNow;
|
||||
if (_sourcePublisher?.TryCaptureVirtual(p.VirtualTagId, out var ticket) == true)
|
||||
@@ -329,10 +319,102 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
_mux?.Tell(new DependencyMuxActor.VirtualTagOutput(nodeId, null, now, OpcUaStatus.BadOutOfService));
|
||||
}
|
||||
|
||||
if (_unboundEnabled.Count + _unboundDisabled.Count > 0)
|
||||
{
|
||||
// One degraded line per apply; the retries themselves log only at Debug, and once more on recovery.
|
||||
_log.Warning("VirtualTagHost: {0} VirtualTag(s) could not bind their data-plane source ({1}); " +
|
||||
"retrying only those, with backoff up to {2}",
|
||||
_unboundEnabled.Count + _unboundDisabled.Count,
|
||||
string.Join(", ", _unboundEnabled.Concat(_unboundDisabled).Take(10)), SourceBindingRetryCap);
|
||||
Timers.StartSingleTimer(SourceBindingRetryTimerKey, new RetrySourceBindings(0), SourceBindingRetryInitial);
|
||||
}
|
||||
|
||||
_log.Debug("VirtualTagHost: applied (desired={Desired}, children={Children}, disabled={Disabled})",
|
||||
desired.Count, _children.Count, plans.Count - evaluated.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spawns the child for <paramref name="p"/> once its data-plane source binding (when a source publisher is
|
||||
/// wired) is established. Returns false — and spawns nothing — when the binding failed; the caller retries.
|
||||
/// </summary>
|
||||
/// <param name="p">An enabled plan with no live child.</param>
|
||||
/// <returns>True when the child was spawned.</returns>
|
||||
private bool TrySpawnChild(EquipmentVirtualTagPlan p)
|
||||
{
|
||||
long? sourceIncarnation = null;
|
||||
if (_sourcePublisher is not null)
|
||||
{
|
||||
if (!_virtualSourceIncarnations.TryGetValue(p.VirtualTagId, out var token))
|
||||
token = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
|
||||
_virtualSourceIncarnations[p.VirtualTagId] = token;
|
||||
sourceIncarnation = token;
|
||||
if (!_sourcePublisher.EnsureVirtualBinding(p.VirtualTagId, token)) return false;
|
||||
}
|
||||
|
||||
// Auto-name the child: vtagIds can contain characters illegal in actor names, so let Akka
|
||||
// assign a safe unique name. The child self-registers with the mux in PreStart.
|
||||
var child = Context.ActorOf(VirtualTagActor.Props(
|
||||
virtualTagId: p.VirtualTagId,
|
||||
expression: p.Expression,
|
||||
evaluator: _evaluator,
|
||||
scriptId: p.VirtualTagId,
|
||||
publisherFactory: null,
|
||||
dependencyRefs: p.DependencyRefs,
|
||||
mux: _mux,
|
||||
telemetryHub: _telemetryHub,
|
||||
changeTriggered: p.ChangeTriggered,
|
||||
timerIntervalMs: p.TimerIntervalMs,
|
||||
sourcePublisher: _sourcePublisher,
|
||||
sourceIncarnation: sourceIncarnation));
|
||||
Context.Watch(child);
|
||||
_children[p.VirtualTagId] = child;
|
||||
_log.Debug("VirtualTagHost: spawned child for vtag {VirtualTagId}", p.VirtualTagId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 (R-17): re-attempts only the bindings the last apply could not make. An enabled tag that binds gets its
|
||||
/// child (fresh, so nothing to re-assert); a disabled tag that binds gets its <c>BadOutOfService</c> on the data
|
||||
/// plane. Nothing else of the apply is repeated. Still-unbound tags are retried after a doubling delay, capped at
|
||||
/// <see cref="SourceBindingRetryCap"/>; a new apply cancels the retry and starts over from its own failures.
|
||||
/// </summary>
|
||||
/// <param name="msg">The attempt.</param>
|
||||
private void OnRetrySourceBindings(RetrySourceBindings msg)
|
||||
{
|
||||
if (_sourcePublisher is null) { _unboundEnabled.Clear(); _unboundDisabled.Clear(); return; }
|
||||
|
||||
foreach (var id in _unboundEnabled.ToList())
|
||||
{
|
||||
// Gone from the plan set (a child terminated and was pruned) or already hosted: nothing left to bind.
|
||||
if (!_planByVtag.TryGetValue(id, out var plan) || _children.ContainsKey(id)) { _unboundEnabled.Remove(id); continue; }
|
||||
if (TrySpawnChild(plan)) _unboundEnabled.Remove(id);
|
||||
}
|
||||
|
||||
foreach (var id in _unboundDisabled.ToList())
|
||||
{
|
||||
if (!_virtualSourceIncarnations.TryGetValue(id, out var token)) { _unboundDisabled.Remove(id); continue; }
|
||||
if (!_sourcePublisher.EnsureVirtualBinding(id, token)) continue;
|
||||
_unboundDisabled.Remove(id);
|
||||
if (_sourcePublisher.TryCaptureVirtual(id, out var ticket))
|
||||
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(null, OpcUaStatus.BadOutOfService, null, null));
|
||||
}
|
||||
|
||||
var remaining = _unboundEnabled.Count + _unboundDisabled.Count;
|
||||
if (remaining == 0)
|
||||
{
|
||||
_log.Info("VirtualTagHost: every VirtualTag source binding is established (after {0} retry attempt(s))",
|
||||
msg.Attempt + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
var next = msg.Attempt + 1;
|
||||
var delay = TimeSpan.FromTicks(Math.Min(
|
||||
SourceBindingRetryCap.Ticks, SourceBindingRetryInitial.Ticks << Math.Min(next, 16)));
|
||||
_log.Debug("VirtualTagHost: {0} VirtualTag source binding(s) still unbound; retry {1} in {2}",
|
||||
remaining, next, delay);
|
||||
Timers.StartSingleTimer(SourceBindingRetryTimerKey, new RetrySourceBindings(next), delay);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#791 bookkeeping for the mux leg: release the keys that left the deployed set, and recompute which
|
||||
/// keys sit on a VirtualTag dependency cycle (an edge runs from a tag to every dependency that is itself a
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
using Serilog;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #995 K-3 — every deploy runs <see cref="ScriptedAlarmEngine.LoadAsync"/>. It used to clear the compile cache and
|
||||
/// recompile every predicate one at a time while holding the engine gate, so a deploy that touched no alarm stalled
|
||||
/// every evaluation and operator command for the whole compile. Now unchanged predicates are reused (keyed by source
|
||||
/// hash), new ones compile outside the gate, and only the swap holds it.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ScriptedAlarmEngineCompileReuseTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private static ScriptedAlarmDefinition Alarm(string id, int threshold) => new(
|
||||
AlarmId: id, EquipmentPath: "Plant/Line1/Reactor", AlarmName: id, Kind: AlarmKind.AlarmCondition,
|
||||
Severity: AlarmSeverity.High, MessageTemplate: "over",
|
||||
PredicateScriptSource: $"return (int)ctx.GetTag(\"Temp\").Value > {threshold};");
|
||||
|
||||
private static ScriptedAlarmDefinition[] Defs(int n) =>
|
||||
[.. Enumerable.Range(0, n).Select(i => Alarm($"a{i}", 100 + i))];
|
||||
|
||||
private static ScriptedAlarmEngine Build(FakeUpstream up, IScriptRunner? runner = null)
|
||||
{
|
||||
var logger = new LoggerConfiguration().CreateLogger();
|
||||
return new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger,
|
||||
scriptRunner: runner);
|
||||
}
|
||||
|
||||
/// <summary>A reload of the same definitions compiles nothing; positive control: the first load compiled each.</summary>
|
||||
[Fact]
|
||||
public async Task Reload_of_unchanged_definitions_compiles_nothing()
|
||||
{
|
||||
var up = new FakeUpstream();
|
||||
up.Set("Temp", 0);
|
||||
using var eng = Build(up);
|
||||
var defs = Defs(5);
|
||||
|
||||
await eng.LoadAsync(defs, Ct);
|
||||
eng.PredicateCompileCount.ShouldBe(5); // positive control: the counter does count compiles
|
||||
|
||||
await eng.LoadAsync(defs, Ct);
|
||||
await eng.LoadAsync(defs, Ct);
|
||||
eng.PredicateCompileCount.ShouldBe(5);
|
||||
eng.CachedPredicateCount.ShouldBe(5);
|
||||
eng.LoadedAlarmIds.Count.ShouldBe(5);
|
||||
}
|
||||
|
||||
/// <summary>An edited predicate compiles once; the retired source is dropped (its ALC released), the rest kept.</summary>
|
||||
[Fact]
|
||||
public async Task Edited_predicate_compiles_only_itself_and_retires_its_old_source()
|
||||
{
|
||||
var up = new FakeUpstream();
|
||||
up.Set("Temp", 150);
|
||||
using var eng = Build(up);
|
||||
var defs = Defs(5);
|
||||
await eng.LoadAsync(defs, Ct);
|
||||
|
||||
var edited = defs.ToArray();
|
||||
edited[2] = Alarm("a2", 500);
|
||||
await eng.LoadAsync(edited, Ct);
|
||||
|
||||
eng.PredicateCompileCount.ShouldBe(6);
|
||||
eng.CachedPredicateCount.ShouldBe(5);
|
||||
|
||||
// The new predicate is the one that runs: 150 > 500 is false, the others (100..104) are true.
|
||||
eng.GetState("a2")!.Active.ShouldBe(AlarmActiveState.Inactive);
|
||||
eng.GetState("a1")!.Active.ShouldBe(AlarmActiveState.Active);
|
||||
|
||||
// Removing alarms drops their compiles.
|
||||
await eng.LoadAsync(edited.Take(2).ToArray(), Ct);
|
||||
eng.CachedPredicateCount.ShouldBe(2);
|
||||
eng.PredicateCompileCount.ShouldBe(6);
|
||||
}
|
||||
|
||||
/// <summary>A compile failure still fails the load, and is retried (not remembered) on the next load.</summary>
|
||||
[Fact]
|
||||
public async Task Compile_failure_still_fails_the_load_and_is_retried()
|
||||
{
|
||||
var up = new FakeUpstream();
|
||||
using var eng = Build(up);
|
||||
var bad = new ScriptedAlarmDefinition("bad", "P", "bad", AlarmKind.AlarmCondition, AlarmSeverity.High, "m",
|
||||
"return nope;");
|
||||
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => eng.LoadAsync([Alarm("a0", 1), bad], Ct));
|
||||
var afterFirst = eng.PredicateCompileCount;
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => eng.LoadAsync([Alarm("a0", 1), bad], Ct));
|
||||
// a0 reused, the bad source tried again.
|
||||
(eng.PredicateCompileCount - afterFirst).ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An operator acknowledge issued while a reload is compiling completes without waiting for the compile, and
|
||||
/// its effect survives the swap (carried over like any other survivor state).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Acknowledge_completes_while_a_reload_is_compiling()
|
||||
{
|
||||
var up = new FakeUpstream();
|
||||
up.Set("Temp", 150);
|
||||
using var eng = Build(up);
|
||||
await eng.LoadAsync([Alarm("a0", 100)], Ct);
|
||||
eng.GetState("a0")!.Active.ShouldBe(AlarmActiveState.Active);
|
||||
eng.GetState("a0")!.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
|
||||
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
eng.CompilePhaseHookForTests = () =>
|
||||
{
|
||||
entered.Set();
|
||||
release.Wait(TimeSpan.FromSeconds(30));
|
||||
};
|
||||
|
||||
var reload = Task.Run(() => eng.LoadAsync([Alarm("a0", 100), Alarm("a1", 120)], Ct), Ct);
|
||||
entered.Wait(TimeSpan.FromSeconds(10), Ct).ShouldBeTrue();
|
||||
|
||||
var ack = eng.AcknowledgeAsync("a0", "op", null, Ct);
|
||||
var finished = await Task.WhenAny(ack, Task.Delay(TimeSpan.FromSeconds(5), Ct));
|
||||
finished.ShouldBe(ack, "the ack must not queue behind the reload's compile phase");
|
||||
await ack;
|
||||
reload.IsCompleted.ShouldBeFalse();
|
||||
|
||||
release.Set();
|
||||
await reload;
|
||||
eng.LoadedAlarmIds.ShouldContain("a1");
|
||||
eng.GetState("a0")!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
|
||||
}
|
||||
|
||||
/// <summary>Out of process the host validation compile is skipped for an unchanged predicate.</summary>
|
||||
[Fact]
|
||||
public async Task Out_of_process_validation_compile_is_not_repeated_for_unchanged_predicates()
|
||||
{
|
||||
var up = new FakeUpstream();
|
||||
up.Set("Temp", 0);
|
||||
using var eng = Build(up, new FalseRunner());
|
||||
var defs = Defs(3);
|
||||
|
||||
await eng.LoadAsync(defs, Ct);
|
||||
eng.HostValidationCompileCount.ShouldBe(3);
|
||||
await eng.LoadAsync(defs, Ct);
|
||||
eng.HostValidationCompileCount.ShouldBe(3);
|
||||
|
||||
var edited = defs.ToArray();
|
||||
edited[0] = Alarm("a0", 999);
|
||||
await eng.LoadAsync(edited, Ct);
|
||||
eng.HostValidationCompileCount.ShouldBe(4);
|
||||
eng.PredicateCompileCount.ShouldBe(0); // nothing is loaded into the host out of process
|
||||
|
||||
// A broken predicate still fails the load out of process.
|
||||
var bad = new ScriptedAlarmDefinition("bad", "P", "bad", AlarmKind.AlarmCondition, AlarmSeverity.High, "m",
|
||||
"return nope;");
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => eng.LoadAsync([.. edited, bad], Ct));
|
||||
}
|
||||
|
||||
private sealed class FalseRunner : IScriptRunner
|
||||
{
|
||||
public Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
|
||||
=> Task.FromResult(ScriptRunOutcome.Ok(false));
|
||||
|
||||
public void Reset(ScriptContextKind kind) { }
|
||||
|
||||
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => [];
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using Serilog;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #995 K-3 measurement: a deploy with <see cref="AlarmCount"/> scripted alarms. Opt-in and never part of a default
|
||||
/// run — skips unless <c>OTOPCUA_SCRIPT_PERF=1</c>. Reports the first load, a reload of the SAME definitions (what
|
||||
/// every deploy that did not touch an alarm does), a reload with one predicate edited, and how long an operator
|
||||
/// acknowledge issued just after a reload started waits for the engine gate.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Run: <c>OTOPCUA_SCRIPT_PERF=1 dotnet test tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests -c Release
|
||||
/// --filter Category=Perf --logger "console;verbosity=detailed"</c>.
|
||||
/// </remarks>
|
||||
[Trait("Category", "Perf")]
|
||||
public sealed class ScriptedAlarmEngineReloadPerfTests
|
||||
{
|
||||
private const int AlarmCount = 500;
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private static ScriptedAlarmDefinition Alarm(int i, int threshold) => new(
|
||||
AlarmId: $"A{i}",
|
||||
EquipmentPath: "Plant/Line1/Reactor",
|
||||
AlarmName: $"A{i}",
|
||||
Kind: AlarmKind.AlarmCondition,
|
||||
Severity: AlarmSeverity.High,
|
||||
MessageTemplate: "over",
|
||||
PredicateScriptSource: $"return (int)ctx.GetTag(\"T{i % 50}\").Value > {threshold};");
|
||||
|
||||
/// <summary>Measures load / reload / ack-during-reload for 500 alarms with distinct predicates.</summary>
|
||||
[Fact]
|
||||
public async Task Reload_of_500_alarms()
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable("OTOPCUA_SCRIPT_PERF") != "1")
|
||||
Assert.Skip("perf harness: set OTOPCUA_SCRIPT_PERF=1 to run");
|
||||
|
||||
var up = new FakeUpstream();
|
||||
for (var t = 0; t < 50; t++) up.Set($"T{t}", 0);
|
||||
var logger = new LoggerConfiguration().CreateLogger();
|
||||
using var eng = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger);
|
||||
|
||||
var defs = Enumerable.Range(0, AlarmCount).Select(i => Alarm(i, 1000 + i)).ToArray();
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
await eng.LoadAsync(defs, Ct);
|
||||
var first = sw.Elapsed;
|
||||
|
||||
sw.Restart();
|
||||
await eng.LoadAsync(defs, Ct);
|
||||
var same = sw.Elapsed;
|
||||
|
||||
var edited = defs.ToArray();
|
||||
edited[7] = Alarm(7, 4242);
|
||||
sw.Restart();
|
||||
await eng.LoadAsync(edited, Ct);
|
||||
var oneEdited = sw.Elapsed;
|
||||
|
||||
// Ack latency while a reload that must compile everything is in progress (a fresh set of sources).
|
||||
var fresh = Enumerable.Range(0, AlarmCount).Select(i => Alarm(i, 9000 + i)).ToArray();
|
||||
sw.Restart();
|
||||
var reload = Task.Run(() => eng.LoadAsync(fresh, Ct), Ct);
|
||||
await Task.Delay(200, Ct);
|
||||
var ackStart = sw.Elapsed;
|
||||
await eng.AcknowledgeAsync("A1", "op", null, Ct);
|
||||
var ackWait = sw.Elapsed - ackStart;
|
||||
await reload;
|
||||
var freshReload = sw.Elapsed;
|
||||
|
||||
var report = new StringBuilder()
|
||||
.AppendLine($"K-3 scripted-alarm reload, {AlarmCount} alarms (distinct predicates):")
|
||||
.AppendLine($" first load {first.TotalMilliseconds,10:F0} ms")
|
||||
.AppendLine($" reload, same defs {same.TotalMilliseconds,10:F0} ms")
|
||||
.AppendLine($" reload, one edited {oneEdited.TotalMilliseconds,10:F0} ms")
|
||||
.AppendLine($" reload, all new {freshReload.TotalMilliseconds,10:F0} ms")
|
||||
.AppendLine($" ack wait during that {ackWait.TotalMilliseconds,10:F0} ms")
|
||||
.ToString();
|
||||
TestContext.Current.TestOutputHelper?.WriteLine(report);
|
||||
if (Environment.GetEnvironmentVariable("OTOPCUA_SCRIPT_PERF_OUT") is { Length: > 0 } path)
|
||||
await File.AppendAllTextAsync(path, report, Ct);
|
||||
}
|
||||
}
|
||||
@@ -401,4 +401,26 @@ public sealed class CompiledScriptCacheTests
|
||||
cache.Dispose();
|
||||
Should.Throw<ObjectDisposedException>(() => cache.GetOrCompile("""return 2;"""));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 K-3: RetainOnly keeps (and does not recompile) the kept sources, and disposes + drops the rest.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task RetainOnly_keeps_kept_entries_and_disposes_the_rest()
|
||||
{
|
||||
var cache = new CompiledScriptCache<FakeScriptContext, int>();
|
||||
var kept = cache.GetOrCompile("""return 1;""");
|
||||
var dropped = cache.GetOrCompile("""return 2;""");
|
||||
cache.CompileCount.ShouldBe(2);
|
||||
|
||||
cache.RetainOnly(["""return 1;""", """return 3;"""]).ShouldBe(1);
|
||||
|
||||
cache.Count.ShouldBe(1);
|
||||
cache.Contains("""return 1;""").ShouldBeTrue();
|
||||
cache.GetOrCompile("""return 1;""").ShouldBeSameAs(kept);
|
||||
cache.CompileCount.ShouldBe(2);
|
||||
(await kept.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken)).ShouldBe(1);
|
||||
await Should.ThrowAsync<ObjectDisposedException>(
|
||||
() => dropped.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken));
|
||||
}
|
||||
}
|
||||
|
||||
+8
-9
@@ -9,9 +9,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#780 batch submit (design §4.5) in the Calculation pump: with an out-of-process runner the pump hands
|
||||
/// everything it dequeued to ONE <see cref="IScriptRunner.RunBatch"/> and publishes in dequeue order. A tag queued
|
||||
/// twice ends the batch, so every queued evaluation still runs, in order, against the snapshot that triggered it —
|
||||
/// the published sequence is exactly the one-at-a-time pump's.
|
||||
/// everything it dequeued to ONE <see cref="IScriptRunner.RunBatch"/> and publishes in dequeue order. The queue holds
|
||||
/// at most one entry per calc tag (#995, review S-9), so triggers that arrive while a batch runs coalesce into ONE
|
||||
/// next batch evaluated against the newest inputs.
|
||||
/// </summary>
|
||||
public sealed class CalculationDriverBatchPumpTests
|
||||
{
|
||||
@@ -89,7 +89,7 @@ public sealed class CalculationDriverBatchPumpTests
|
||||
driver.OnDependencyValue("src/a", 1.0, StatusGood, DateTime.UtcNow);
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
|
||||
while (DateTime.UtcNow < deadline && runner.Batches.IsEmpty) await Task.Delay(5, TestContext.Current.CancellationToken);
|
||||
// Two more triggers queue behind the held batch: six evaluations, each tag twice.
|
||||
// Two more triggers queue behind the held batch: they coalesce into one evaluation per tag (#995).
|
||||
driver.OnDependencyValue("src/a", 2.0, StatusGood, DateTime.UtcNow);
|
||||
driver.OnDependencyValue("src/a", 3.0, StatusGood, DateTime.UtcNow);
|
||||
runner.Release();
|
||||
@@ -97,14 +97,13 @@ public sealed class CalculationDriverBatchPumpTests
|
||||
|
||||
runner.SingleRuns.ShouldBe(0);
|
||||
runner.Batches.ToArray().ShouldBe(
|
||||
[["calc/t1", "calc/t2", "calc/t3"], ["calc/t1", "calc/t2", "calc/t3"], ["calc/t1", "calc/t2", "calc/t3"]],
|
||||
"a tag queued twice ends the batch; every queued evaluation still runs");
|
||||
sizes.ToArray().ShouldBe([3, 3, 3]);
|
||||
[["calc/t1", "calc/t2", "calc/t3"], ["calc/t1", "calc/t2", "calc/t3"]],
|
||||
"the two later triggers are one pending evaluation per tag, so one more batch");
|
||||
sizes.ToArray().ShouldBe([3, 3]);
|
||||
published.ToArray().ShouldBe(
|
||||
[
|
||||
("calc/t1", 1.0, StatusGood), ("calc/t2", 2.0, StatusGood), ("calc/t3", 3.0, StatusGood),
|
||||
("calc/t1", 2.0, StatusGood), ("calc/t2", 4.0, StatusGood), ("calc/t3", 6.0, StatusGood),
|
||||
("calc/t1", 3.0, StatusGood), ("calc/t2", 6.0, StatusGood), ("calc/t3", 9.0, StatusGood),
|
||||
], "dequeue order, each against the snapshot that triggered it");
|
||||
], "dequeue order; the coalesced batch sees the newest input, with no intermediate 2.0 cycle");
|
||||
}
|
||||
}
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Serilog;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #995 (review 2026-12-02 S-9) — change-triggered work is latest-wins per calc tag. Every dependency arrival used to
|
||||
/// enqueue a separate evaluation for each dependent, each with its own dependency snapshot taken at trigger time: a
|
||||
/// tag with k inputs fed by one poll cycle ran k times, the first k−1 against a mix of new and previous-cycle inputs
|
||||
/// (and published those intermediate values), and the queue had no bound, so a pump slower than the trigger rate
|
||||
/// fell further behind without limit. Now at most one evaluation is pending per tag and its snapshot is taken when
|
||||
/// the pump dequeues it.
|
||||
/// </summary>
|
||||
public sealed class CalculationDriverCoalescingTests
|
||||
{
|
||||
private const uint StatusGood = 0u;
|
||||
|
||||
private static RawTagEntry CalcTag(string rawPath, string source)
|
||||
{
|
||||
var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}";
|
||||
return new RawTagEntry(rawPath, json, WriteIdempotent: false);
|
||||
}
|
||||
|
||||
private static async Task Settle(CalculationDriver driver)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while (DateTime.UtcNow < deadline && !driver.IsEvaluationIdle) await Task.Delay(10);
|
||||
driver.IsEvaluationIdle.ShouldBeTrue();
|
||||
}
|
||||
|
||||
private static int PendingCount(CalculationDriver driver)
|
||||
{
|
||||
var field = typeof(CalculationDriver).GetField("_pending", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
|
||||
var pending = (System.Collections.ICollection)field!.GetValue(driver)!;
|
||||
return pending.Count;
|
||||
}
|
||||
|
||||
/// <summary>Blocks the pump inside the publish of the first Good value it sees after <see cref="Arm"/>.</summary>
|
||||
private sealed class PumpBlocker : IDisposable
|
||||
{
|
||||
private readonly ManualResetEventSlim _release = new();
|
||||
private readonly TaskCompletionSource _entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private int _armed;
|
||||
|
||||
public Task Entered => _entered.Task;
|
||||
|
||||
public void Arm() => Interlocked.Exchange(ref _armed, 1);
|
||||
|
||||
public void OnPublish()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _armed, 0) != 1) return;
|
||||
_entered.TrySetResult();
|
||||
_release.Wait(TimeSpan.FromSeconds(20));
|
||||
}
|
||||
|
||||
public void Release() => _release.Set();
|
||||
|
||||
public void Dispose() { _release.Set(); _release.Dispose(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Five_inputs_arriving_while_the_pump_is_blocked_evaluate_once_with_all_five_values()
|
||||
{
|
||||
const string source = "return (double)ctx.GetTag(\"src/a\").Value + (double)ctx.GetTag(\"src/b\").Value + " +
|
||||
"(double)ctx.GetTag(\"src/c\").Value + (double)ctx.GetTag(\"src/d\").Value + (double)ctx.GetTag(\"src/e\").Value;";
|
||||
using var driver = new CalculationDriver(
|
||||
new CalculationDriverOptions { RawTags = [CalcTag("calc/sum", source)] },
|
||||
"calc-drv", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
|
||||
using var blocker = new PumpBlocker();
|
||||
var published = new ConcurrentQueue<object?>();
|
||||
driver.OnDataChange += (_, e) =>
|
||||
{
|
||||
if (e.Snapshot.StatusCode != StatusGood || e.Snapshot.Value is null) return;
|
||||
published.Enqueue(e.Snapshot.Value);
|
||||
blocker.OnPublish();
|
||||
};
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
foreach (var dep in new[] { "src/a", "src/b", "src/c", "src/d", "src/e" })
|
||||
driver.OnDependencyValue(dep, 0.0, StatusGood, DateTime.UtcNow);
|
||||
await Settle(driver);
|
||||
published.ToArray().ShouldBe(new object?[] { 0.0 });
|
||||
|
||||
// The next evaluation's publish parks the pump; the other four inputs of the same poll cycle land behind it.
|
||||
blocker.Arm();
|
||||
driver.OnDependencyValue("src/a", 1.0, StatusGood, DateTime.UtcNow);
|
||||
await blocker.Entered.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken);
|
||||
driver.OnDependencyValue("src/b", 10.0, StatusGood, DateTime.UtcNow);
|
||||
driver.OnDependencyValue("src/c", 100.0, StatusGood, DateTime.UtcNow);
|
||||
driver.OnDependencyValue("src/d", 1000.0, StatusGood, DateTime.UtcNow);
|
||||
driver.OnDependencyValue("src/e", 10000.0, StatusGood, DateTime.UtcNow);
|
||||
PendingCount(driver).ShouldBe(1, "four triggers of one tag are one pending evaluation");
|
||||
|
||||
blocker.Release();
|
||||
await Settle(driver);
|
||||
|
||||
// One evaluation after the release, against all five new inputs — no intermediate 11 / 111 / 1111.
|
||||
published.ToArray().ShouldBe(new object?[] { 0.0, 1.0, 11111.0 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Sustained_triggers_faster_than_the_pump_keep_the_queue_bounded_by_the_tag_count()
|
||||
{
|
||||
const int tagCount = 3;
|
||||
using var driver = new CalculationDriver(
|
||||
new CalculationDriverOptions
|
||||
{
|
||||
RawTags = Enumerable.Range(0, tagCount)
|
||||
.Select(i => CalcTag($"calc/t{i}", $"return (double)ctx.GetTag(\"src/a\").Value + {i};")).ToArray(),
|
||||
},
|
||||
"calc-drv", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
|
||||
using var blocker = new PumpBlocker();
|
||||
var published = new ConcurrentQueue<(string Tag, object? Value)>();
|
||||
driver.OnDataChange += (_, e) =>
|
||||
{
|
||||
if (e.Snapshot.StatusCode != StatusGood || e.Snapshot.Value is null) return;
|
||||
published.Enqueue((e.FullReference, e.Snapshot.Value));
|
||||
blocker.OnPublish();
|
||||
};
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
blocker.Arm();
|
||||
driver.OnDependencyValue("src/a", 0.0, StatusGood, DateTime.UtcNow);
|
||||
await blocker.Entered.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken);
|
||||
|
||||
var maxPending = 0;
|
||||
for (var v = 1; v <= 1000; v++)
|
||||
{
|
||||
driver.OnDependencyValue("src/a", (double)v, StatusGood, DateTime.UtcNow);
|
||||
maxPending = Math.Max(maxPending, PendingCount(driver));
|
||||
}
|
||||
maxPending.ShouldBeLessThanOrEqualTo(tagCount, "the backlog is bounded by the number of calc tags, not the trigger count");
|
||||
|
||||
blocker.Release();
|
||||
await Settle(driver);
|
||||
|
||||
// Positive control: every tag ends on the newest input.
|
||||
for (var i = 0; i < tagCount; i++)
|
||||
published.Where(p => p.Tag == $"calc/t{i}").Last().Value.ShouldBe(1000.0 + i);
|
||||
published.Count.ShouldBeLessThanOrEqualTo(2 * tagCount, "one evaluation per tag before the block, one after it");
|
||||
}
|
||||
}
|
||||
@@ -199,10 +199,13 @@ public sealed class CalculationDriverTests
|
||||
CalcTag("calc/e/dbl", "return (double)ctx.GetTag(\"src/a\").Value * 2.0;"));
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
// Each arrival is queued with the dependency snapshot that triggered it, so the three evaluations
|
||||
// see 5 / 5 / 7 in that order however far the pump lags behind them.
|
||||
// Settled between arrivals: triggers that land while an evaluation is pending coalesce into one (#995),
|
||||
// so each arrival here must be evaluated on its own for the dedup to be exercised.
|
||||
driver.OnDependencyValue("src/a", 5.0, StatusGood, DateTime.UtcNow); // → 10 (publish)
|
||||
await Settle(driver);
|
||||
driver.OnDependencyValue("src/a", 5.0, StatusGood, DateTime.UtcNow); // → 10 (dedup, no publish)
|
||||
await Settle(driver);
|
||||
published.Count.ShouldBe(1);
|
||||
driver.OnDependencyValue("src/a", 7.0, StatusGood, DateTime.UtcNow); // → 14 (publish)
|
||||
await Settle(driver);
|
||||
|
||||
|
||||
+47
@@ -126,6 +126,53 @@ public sealed class NodeManagerStaleMonitoredNodeTests : IDisposable
|
||||
finally { await host.DisposeAsync(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 U-5: the stood-down sweep a removal runs is a lookup by node, not a scan of every tracked item. Removing
|
||||
/// N stood-down nodes one by one (a surgical apply dropping N reference variables) used to visit
|
||||
/// N + (N−1) + … ≈ N²/2 tracked items under <c>Lock</c>; it now visits each removed node's own items. The
|
||||
/// correctness of the sweep (every removed item told + forgotten, a survivor untouched) is asserted alongside.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Removing_N_stood_down_nodes_visits_O_N_items_not_O_N_squared()
|
||||
{
|
||||
const int n = 200;
|
||||
var (host, server) = await BootAsync();
|
||||
try
|
||||
{
|
||||
var nm = server.NodeManager!;
|
||||
var items = new List<StubItem>();
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var path = $"Plant/Modbus/dev1/T{i}";
|
||||
nm.EnsureVariable(path, null, path, "Float", writable: false, realm: AddressSpaceRealm.Raw);
|
||||
var handle = (NodeHandle)nm.GetManagerHandle(nm.TryGetVariable(path, AddressSpaceRealm.Raw)!.NodeId)!;
|
||||
var item = new StubItem(handle, Identity());
|
||||
nm.TrackLiveMonitoredItem(handle, item);
|
||||
items.Add(item);
|
||||
}
|
||||
// A survivor: stood down too, on a node the loop never removes.
|
||||
var (survivor, _) = await StandDownAsync(nm, "Plant/Modbus/dev1/Survivor");
|
||||
items.ShouldAllBe(it => it.Statuses.Contains(StatusCodes.BadUserAccessDenied), "non-vacuity: all stood down");
|
||||
|
||||
var before = nm.StoodDownSweepVisits;
|
||||
for (var i = 0; i < n; i++)
|
||||
nm.RemoveVariableNode($"Plant/Modbus/dev1/T{i}", AddressSpaceRealm.Raw).ShouldBeTrue();
|
||||
var visits = nm.StoodDownSweepVisits - before;
|
||||
|
||||
items.ShouldAllBe(it => it.Statuses.Contains(StatusCodes.BadNodeIdUnknown), "every removed item is told");
|
||||
nm.LiveItemCount.ShouldBe(1, "only the survivor stays tracked");
|
||||
survivor.Statuses.ShouldNotContain((StatusCode)StatusCodes.BadNodeIdUnknown);
|
||||
visits.ShouldBeLessThanOrEqualTo(4L * n, $"sweep visits must be O(N): {visits} for N={n}");
|
||||
|
||||
// Positive control: the survivor's node is still swept when it goes.
|
||||
nm.RemoveVariableNode("Plant/Modbus/dev1/Survivor", AddressSpaceRealm.Raw).ShouldBeTrue();
|
||||
survivor.Statuses.ShouldContain((StatusCode)StatusCodes.BadNodeIdUnknown);
|
||||
nm.LiveItemCount.ShouldBe(0);
|
||||
nm.TrackedItemIndexNodeCount.ShouldBe(0, "the per-node index does not outlive the removed nodes");
|
||||
}
|
||||
finally { await host.DisposeAsync(); }
|
||||
}
|
||||
|
||||
/// <summary>Registers a stub item on <paramref name="rawPath"/> and stands it down through a denying pass.</summary>
|
||||
private static async Task<(StubItem Item, NodeId NodeId)> StandDownAsync(OtOpcUaNodeManager nm, string rawPath)
|
||||
{
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Akka.Actor;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #995 (review 2026-12-02 R-14): apply-time artifact work was repeated. The data projection (a full
|
||||
/// deserialise of every topology table + <c>ValidateDeployed</c>) ran three times inside
|
||||
/// <c>ParseDataPlaneAuthority</c> alone — even for a node with ZERO data rows, because the composer always emits the
|
||||
/// three arrays — and up to four more in the driver host's catalog staging. The publish actor also re-parsed the
|
||||
/// whole artifact on its pinned thread just to read the cluster's redundancy mode, and hashed it up to three times.
|
||||
/// </summary>
|
||||
public sealed class DeploymentArtifactApplyCostTests : RuntimeActorTestBase
|
||||
{
|
||||
[Fact]
|
||||
public void One_data_projection_serves_every_consumer_of_one_parsed_artifact()
|
||||
{
|
||||
using var parsed = DeploymentArtifact.Open(GrpcDataCatalogStagingTests.Artifact());
|
||||
|
||||
// Exactly the calls one apply makes (DriverHostActor.StageCatalog): authority (3 row parses inside) + snapshot +
|
||||
// connections + mappings + connections again.
|
||||
var authority = parsed.ParseDataPlaneAuthority("node-a");
|
||||
parsed.ParseLocalCatalogSnapshot("node-a").ShouldNotBeNull();
|
||||
parsed.ParseDataConnections("node-a");
|
||||
parsed.ParseRemoteNamespaceMappings("node-a");
|
||||
parsed.ParseDataConnections("node-a");
|
||||
parsed.ParseDataExports("node-a").Count.ShouldBe(1, "the projection still answers (positive control)");
|
||||
|
||||
authority.CatalogValid.ShouldBeTrue();
|
||||
parsed.DataProjectionBuilds.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_artifact_with_empty_data_arrays_builds_no_projection_for_the_authority()
|
||||
{
|
||||
var root = JsonNode.Parse(GrpcDataCatalogStagingTests.Artifact())!.AsObject();
|
||||
root["DataExports"] = new JsonArray();
|
||||
using var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString()));
|
||||
|
||||
var authority = parsed.ParseDataPlaneAuthority("node-a");
|
||||
|
||||
authority.Keys.Count.ShouldBe(1, "keys still parse (positive control)");
|
||||
parsed.ParseDataConnections("node-a").ShouldBeEmpty();
|
||||
parsed.ParseDataExports("node-a").ShouldBeEmpty();
|
||||
parsed.ParseRemoteNamespaceMappings("node-a").ShouldBeEmpty();
|
||||
parsed.DataProjectionBuilds.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_invalid_data_row_still_fails_every_row_parser_from_the_memoised_projection()
|
||||
{
|
||||
using var parsed = DeploymentArtifact.Open(GrpcDataCatalogStagingTests.Artifact(invalidExport: true));
|
||||
|
||||
Should.Throw<InvalidDataException>(() => parsed.ParseDataExports("node-a"));
|
||||
Should.Throw<InvalidDataException>(() => parsed.ParseDataExports("node-a"));
|
||||
parsed.ParseDataPlaneAuthority("node-a").CatalogValid.ShouldBeFalse();
|
||||
parsed.DataProjectionBuilds.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_redundancy_mode_cross_check_reads_the_plan_steps_parse_not_the_actor_thread()
|
||||
{
|
||||
var planThread = 0;
|
||||
var readThreads = new List<int>();
|
||||
var hooks = new OpcUaPublishActor.TestHooks
|
||||
{
|
||||
BeforePlan = () => Volatile.Write(ref planThread, Environment.CurrentManagedThreadId),
|
||||
OnRedundancyModeRead = id => { lock (readThreads) readThreads.Add(id); },
|
||||
};
|
||||
var sink = new NullSink();
|
||||
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
|
||||
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks,
|
||||
localNode: NodeId.Parse("x:1"), redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm)));
|
||||
var artifact = Encoding.UTF8.GetBytes("{\"Clusters\":[{\"ClusterId\":\"c1\",\"RedundancyMode\":\"None\"}],\"Nodes\":[]}");
|
||||
|
||||
EventFilter.Error(contains: "RedundancyMode for this node's cluster is None").ExpectOne(() =>
|
||||
{
|
||||
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact, ReportOutcome: true));
|
||||
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
lock (readThreads) readThreads.ShouldBe([Volatile.Read(ref planThread)], "one read, on the plan step's thread");
|
||||
}
|
||||
|
||||
private sealed class NullSink : IOpcUaAddressSpaceSink
|
||||
{
|
||||
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime ts, AddressSpaceRealm realm) { }
|
||||
public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime ts, AddressSpaceRealm realm) { }
|
||||
public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime ts, AddressSpaceRealm realm) { }
|
||||
public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { }
|
||||
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { }
|
||||
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { }
|
||||
public void RebuildAddressSpace() { }
|
||||
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { }
|
||||
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
|
||||
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
using Akka.Actor;
|
||||
using Akka.TestKit;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #995 (review 2026-12-02 R-11): every deploy used to re-subscribe every kept driver's whole data set —
|
||||
/// upstream monitored-item delete/create, Galaxy unadvise/advise, a forced full re-read, a data gap — even when the
|
||||
/// deploy did not touch that driver. A kept driver whose desired set and everything it seeds are unchanged is now
|
||||
/// left alone on a NON-rebuild apply. The re-subscribe's seeding job is kept: a new UNS mirror, a new mux consumer
|
||||
/// of one of the driver's refs, or an address-space REBUILD (nodes recreated empty) still re-push it.
|
||||
/// </summary>
|
||||
public sealed class DriverHostActorUnchangedResubscribeTests : RuntimeActorTestBase
|
||||
{
|
||||
private static readonly NodeId TestNode = NodeId.Parse("node-1:4053");
|
||||
private const string SpeedPath = "Plant/Modbus/dev1/speed";
|
||||
private const string Equipment = "EQ-filling-line1-station1";
|
||||
|
||||
private static readonly (string, string, string, string, string, bool)[] OneDriver =
|
||||
[("drv-1", "Modbus", "dev1", "speed", "Float", false)];
|
||||
|
||||
private static readonly (string, string, string, string, string, bool)[] TwoDrivers =
|
||||
[("drv-1", "Modbus", "dev1", "speed", "Float", false), ("drv-2", "Modbus2", "dev2", "pressure", "Float", false)];
|
||||
|
||||
private static readonly (string, string, string, string, string?)[] NoRefs = [];
|
||||
|
||||
/// <summary>An unrelated deploy no longer re-subscribes drv-1; a deploy adding a UNS mirror of its tag does
|
||||
/// (the positive control that also orders drv-1's mailbox: had the first deploy pushed, the count would be 3).</summary>
|
||||
[Fact]
|
||||
public void A_kept_driver_is_not_resubscribed_by_an_unrelated_non_rebuild_deploy_but_is_by_a_new_mirror()
|
||||
{
|
||||
var rig = new Rig(this, NewInMemoryDbFactory());
|
||||
rig.Deploy(OneDriver, NoRefs, Rev('a'));
|
||||
var drv1 = rig.Driver("drv-1");
|
||||
AwaitAssert(() => drv1.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct);
|
||||
|
||||
// Deploy B adds an unrelated driver. Its own push (drv-2 subscribes) is the presence half.
|
||||
rig.Deploy(TwoDrivers, NoRefs, Rev('b'));
|
||||
AwaitAssert(() => rig.Driver("drv-2").SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct);
|
||||
|
||||
// Deploy C adds a UNS reference to drv-1's tag: the new mirror needs a seed, so drv-1 IS re-pushed.
|
||||
rig.Deploy(TwoDrivers, [("filling", "line1", "station1", "speed", null)], Rev('c'));
|
||||
AwaitAssert(() => drv1.SubscribeCount.ShouldBeGreaterThanOrEqualTo(2), PresenceBudget, cancellationToken: Ct);
|
||||
// Mailbox order: B's push (had it been sent) precedes C's, so exactly 2 means B was skipped.
|
||||
Thread.Sleep(300);
|
||||
drv1.SubscribeCount.ShouldBe(2, "the unrelated deploy B re-subscribed drv-1");
|
||||
rig.Driver("drv-2").SubscribeCount.ShouldBe(1, "deploy C did not touch drv-2");
|
||||
factoryCreatedOnce(rig);
|
||||
}
|
||||
|
||||
/// <summary>A full rebuild recreates every node without a value: the skipped driver is re-pushed once the
|
||||
/// address-space outcome reports the rebuild.</summary>
|
||||
[Fact]
|
||||
public void A_skipped_driver_is_re_pushed_when_the_address_space_apply_was_a_rebuild()
|
||||
{
|
||||
var rig = new Rig(this, NewInMemoryDbFactory());
|
||||
rig.Deploy(OneDriver, NoRefs, Rev('a'));
|
||||
var drv1 = rig.Driver("drv-1");
|
||||
AwaitAssert(() => drv1.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct);
|
||||
|
||||
rig.Rebuilt = true;
|
||||
rig.Deploy(TwoDrivers, NoRefs, Rev('b'));
|
||||
AwaitAssert(() => drv1.SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct);
|
||||
}
|
||||
|
||||
/// <summary>A degraded apply may have left nodes missing: re-push too.</summary>
|
||||
[Fact]
|
||||
public void A_skipped_driver_is_re_pushed_when_the_address_space_apply_was_degraded()
|
||||
{
|
||||
var rig = new Rig(this, NewInMemoryDbFactory());
|
||||
rig.Deploy(OneDriver, NoRefs, Rev('a'));
|
||||
var drv1 = rig.Driver("drv-1");
|
||||
AwaitAssert(() => drv1.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct);
|
||||
|
||||
rig.Degraded = true;
|
||||
rig.Deploy(TwoDrivers, NoRefs, Rev('b'), expectDegraded: true);
|
||||
AwaitAssert(() => drv1.SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct);
|
||||
}
|
||||
|
||||
/// <summary>A new VirtualTag reading drv-1's tag registers with the mux, which replays a retained value only for refs
|
||||
/// some replay-opting subscriber already named — so its first input has to come from a re-subscribe.</summary>
|
||||
[Fact]
|
||||
public void A_new_virtual_tag_consumer_of_a_kept_drivers_ref_re_pushes_that_driver()
|
||||
{
|
||||
var rig = new Rig(this, NewInMemoryDbFactory());
|
||||
var equip = new[] { ("filling", "line1", "station1", "speed", (string?)null) };
|
||||
rig.Deploy(OneDriver, equip, Rev('a'));
|
||||
var drv1 = rig.Driver("drv-1");
|
||||
AwaitAssert(() => drv1.SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct);
|
||||
|
||||
rig.Deploy(OneDriver, equip, Rev('b'),
|
||||
virtualTags: [("vt-1", Equipment, "Doubled", $"return (double)ctx.GetTag(\"{SpeedPath}\").Value * 2;")]);
|
||||
AwaitAssert(() => drv1.SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct);
|
||||
|
||||
// ...and a further unrelated deploy with the same VirtualTag does not (the consumer is no longer new).
|
||||
rig.Deploy(TwoDrivers, equip, Rev('c'),
|
||||
virtualTags: [("vt-1", Equipment, "Doubled", $"return (double)ctx.GetTag(\"{SpeedPath}\").Value * 2;")]);
|
||||
AwaitAssert(() => rig.Driver("drv-2").SubscribeCount.ShouldBe(1), PresenceBudget, cancellationToken: Ct);
|
||||
rig.Deploy(TwoDrivers, equip, Rev('d'), virtualTags:
|
||||
[
|
||||
("vt-1", Equipment, "Doubled", $"return (double)ctx.GetTag(\"{SpeedPath}\").Value * 2;"),
|
||||
("vt-2", Equipment, "Pressure2", "return (double)ctx.GetTag(\"Plant/Modbus2/dev2/pressure\").Value * 2;"),
|
||||
]);
|
||||
// Positive control: vt-2 is a new consumer of drv-2's ref, so drv-2 is re-pushed …
|
||||
AwaitAssert(() => rig.Driver("drv-2").SubscribeCount.ShouldBe(2), PresenceBudget, cancellationToken: Ct);
|
||||
Thread.Sleep(300);
|
||||
// … while drv-1 (c and d both skipped) stays at 2.
|
||||
drv1.SubscribeCount.ShouldBe(2, "an unchanged driver was re-subscribed by a deploy that added nothing it seeds");
|
||||
}
|
||||
|
||||
private static void factoryCreatedOnce(Rig rig) =>
|
||||
rig.Factory.Created.Count(d => d.DriverInstanceId == "drv-1").ShouldBe(1, "drv-1 must be the same kept driver throughout");
|
||||
|
||||
private static RevisionHash Rev(char c) => RevisionHash.Parse(new string(c, 64));
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
private readonly RuntimeActorTestBase _kit;
|
||||
private readonly IDbContextFactory<OtOpcUaConfigDbContext> _db;
|
||||
private readonly IActorRef _host;
|
||||
private readonly TestProbe _coordinator;
|
||||
|
||||
public RecordingSubscribableDriverFactory Factory { get; } = new("Modbus");
|
||||
public volatile bool Rebuilt;
|
||||
public volatile bool Degraded;
|
||||
|
||||
public Rig(RuntimeActorTestBase kit, IDbContextFactory<OtOpcUaConfigDbContext> db)
|
||||
{
|
||||
_kit = kit;
|
||||
_db = db;
|
||||
_coordinator = kit.CreateTestProbe();
|
||||
var publish = kit.CreateTestProbe();
|
||||
publish.SetAutoPilot(new DelegateAutoPilot((sender, message) =>
|
||||
{
|
||||
if (message is OpcUaPublishActor.RebuildAddressSpace { ReportOutcome: true } rebuild)
|
||||
sender.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId,
|
||||
Degraded: Degraded, DegradedReason: Degraded ? "test degraded" : null, AddressSpaceRebuilt: Rebuilt));
|
||||
return AutoPilot.KeepRunning;
|
||||
}));
|
||||
_host = kit.Sys.ActorOf(DriverHostActor.Props(
|
||||
_db, TestNode, _coordinator.Ref,
|
||||
driverFactory: Factory,
|
||||
localRoles: new HashSet<string> { "driver" },
|
||||
dependencyMux: kit.CreateTestProbe().Ref,
|
||||
opcUaPublishActor: publish.Ref,
|
||||
virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
|
||||
virtualTagHostOverride: kit.CreateTestProbe().Ref));
|
||||
}
|
||||
|
||||
public RecordingSubscribableDriver Driver(string id)
|
||||
{
|
||||
RecordingSubscribableDriver? found = null;
|
||||
_kit.AwaitAssert(() => (found = Factory.Created.LastOrDefault(d => d.DriverInstanceId == id)).ShouldNotBeNull(),
|
||||
PresenceBudget, cancellationToken: Ct);
|
||||
return found!;
|
||||
}
|
||||
|
||||
public void Deploy((string, string, string, string, string, bool)[] tags, (string, string, string, string, string?)[] refs,
|
||||
RevisionHash rev, (string, string, string, string)[]? virtualTags = null, bool expectDegraded = false)
|
||||
{
|
||||
var id = V3ArtifactSeeder.SeedV3Deployment(_db, rev, tags, refs, enabled: true, virtualTags: virtualTags);
|
||||
_host.Tell(new ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.DispatchDeployment(id, rev, CorrelationId.NewId()));
|
||||
var ack = _coordinator.FishForMessage<ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.ApplyAck>(
|
||||
m => m.DeploymentId == id, PresenceBudget, cancellationToken: Ct);
|
||||
ack.Outcome.ShouldBe(ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy.ApplyAckOutcome.Applied);
|
||||
ack.Degraded.ShouldBe(expectDegraded);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,8 @@ public static class V3ArtifactSeeder
|
||||
/// only way to express a driver that is a running child yet absent from both the value- and alarm-ref
|
||||
/// maps — the <c>_children.Keys</c> arm of <c>ApplyDesiredSubscriptions</c>'s union, which must still
|
||||
/// hand that child an explicit EMPTY set rather than skipping it.</param>
|
||||
/// <param name="virtualTags">Optional Equipment VirtualTags (#995): each gets its own script row with
|
||||
/// <c>Source</c> as its body; <c>EquipmentId</c> must name a seeded equipment (<c>EQ-{area}-{line}-{equip}</c>).</param>
|
||||
/// <returns>The seeded deployment's id.</returns>
|
||||
public static DeploymentId SeedV3Deployment(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev,
|
||||
@@ -61,7 +63,8 @@ public static class V3ArtifactSeeder
|
||||
bool enabled = false,
|
||||
IReadOnlyDictionary<string, string>? tagConfigByTag = null,
|
||||
string[]? taglessDrivers = null,
|
||||
IReadOnlyDictionary<string, Guid>? driverRowIds = null)
|
||||
IReadOnlyDictionary<string, Guid>? driverRowIds = null,
|
||||
(string VirtualTagId, string EquipmentId, string Name, string Source)[]? virtualTags = null)
|
||||
{
|
||||
Guid RowId(string id) => driverRowIds is not null && driverRowIds.TryGetValue(id, out var g) ? g : Guid.Empty;
|
||||
var drivers = rawTags
|
||||
@@ -113,6 +116,11 @@ public static class V3ArtifactSeeder
|
||||
UnsLines = lines,
|
||||
Equipment = equipment,
|
||||
UnsTagReferences = unsTagReferences,
|
||||
Scripts = (virtualTags ?? []).Select(v => new { ScriptId = "scr-" + v.VirtualTagId, SourceCode = v.Source }).ToArray(),
|
||||
VirtualTags = (virtualTags ?? []).Select(v => new
|
||||
{
|
||||
v.VirtualTagId, v.EquipmentId, v.Name, DataType = "Float", ScriptId = "scr-" + v.VirtualTagId, Enabled = true,
|
||||
}).ToArray(),
|
||||
});
|
||||
|
||||
var id = DeploymentId.NewId();
|
||||
|
||||
+103
-9
@@ -71,8 +71,13 @@ one-thread-dispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #995 (review R-19): triggers that arrive while a run is in flight are folded — newest value per input — and
|
||||
/// evaluated ONCE after it, against the newest inputs, stamped with the newest arrival. (They used to be replayed
|
||||
/// one run per trigger, each against the input as of its own trigger.)
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Triggers_during_a_run_are_evaluated_after_it_in_order_each_against_its_own_inputs()
|
||||
public void Triggers_during_a_run_are_coalesced_into_one_evaluation_against_the_newest_inputs()
|
||||
{
|
||||
var parent = CreateTestProbe();
|
||||
var evaluator = new ManualEvaluator();
|
||||
@@ -93,16 +98,100 @@ one-thread-dispatcher {
|
||||
evaluator.Complete(0, VirtualTagEvalResult.Ok(10));
|
||||
var r1 = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken);
|
||||
AwaitCondition(() => evaluator.Calls.Count == 2, PresenceBudget, TestContext.Current.CancellationToken);
|
||||
evaluator.Complete(1, VirtualTagEvalResult.Ok(20));
|
||||
evaluator.Complete(1, VirtualTagEvalResult.Ok(30));
|
||||
var r2 = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken);
|
||||
AwaitCondition(() => evaluator.Calls.Count == 3, PresenceBudget, TestContext.Current.CancellationToken);
|
||||
evaluator.Complete(2, VirtualTagEvalResult.Ok(30));
|
||||
var r3 = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
// Each evaluation saw the input as of ITS trigger — not the newest value — exactly as the blocking path did.
|
||||
evaluator.Calls.ShouldBe(new object?[] { 1, 2, 3 });
|
||||
new[] { r1.Value, r2.Value, r3.Value }.ShouldBe(new object?[] { 10, 20, 30 });
|
||||
new[] { r1.TimestampUtc, r2.TimestampUtc, r3.TimestampUtc }.ShouldBe(new[] { t1, t2, t3 });
|
||||
// Absence, with the positive control above (r2 arrived): no third run for the superseded trigger.
|
||||
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
evaluator.Calls.ShouldBe(new object?[] { 1, 3 }, "the held triggers ran once, against the newest input");
|
||||
new[] { r1.Value, r2.Value }.ShouldBe(new object?[] { 10, 30 });
|
||||
new[] { r1.TimestampUtc, r2.TimestampUtc }.ShouldBe(new[] { t1, t3 });
|
||||
}
|
||||
|
||||
/// <summary>#995 (R-19): a backlog of 100 batches behind a slow run costs one more evaluation, not 100.</summary>
|
||||
[Fact]
|
||||
public async Task A_backlog_of_batches_behind_a_slow_run_is_evaluated_once_with_the_latest_inputs()
|
||||
{
|
||||
var parent = CreateTestProbe();
|
||||
var evaluator = new ManualEvaluator();
|
||||
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-1", "expr", evaluator: evaluator,
|
||||
dependencyRefs: ["a", "b"]), TestContext.Current.CancellationToken);
|
||||
|
||||
var t0 = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc);
|
||||
actor.Tell(new VirtualTagActor.DependencyValueBatch(new[]
|
||||
{
|
||||
new VirtualTagActor.DependencyValueChanged("a", 0, t0), new VirtualTagActor.DependencyValueChanged("b", 0, t0),
|
||||
}));
|
||||
AwaitCondition(() => evaluator.Calls.Count == 1, PresenceBudget, TestContext.Current.CancellationToken);
|
||||
|
||||
for (var i = 1; i <= 100; i++)
|
||||
{
|
||||
var ts = t0.AddMilliseconds(i);
|
||||
actor.Tell(new VirtualTagActor.DependencyValueBatch(new[]
|
||||
{
|
||||
new VirtualTagActor.DependencyValueChanged("a", i, ts), new VirtualTagActor.DependencyValueChanged("b", i * 10, ts),
|
||||
}));
|
||||
}
|
||||
// Identify is handled in mailbox order: once it answers, all 100 batches have been received.
|
||||
await actor.Ask<ActorIdentity>(new Identify(1), PresenceBudget, TestContext.Current.CancellationToken);
|
||||
|
||||
evaluator.Complete(0, VirtualTagEvalResult.Ok(0));
|
||||
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken).Value.ShouldBe(0);
|
||||
AwaitCondition(() => evaluator.Calls.Count == 2, PresenceBudget, TestContext.Current.CancellationToken);
|
||||
evaluator.Complete(1, VirtualTagEvalResult.Ok(100));
|
||||
var last = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
evaluator.Calls.Count.ShouldBe(2, "100 batches held behind one run evaluate once, not 100 times");
|
||||
evaluator.Calls[1].ShouldBe(100, "the coalesced evaluation saw the newest value of input a");
|
||||
evaluator.InputsOfCall(1)["b"].ShouldBe(1000, "and of input b");
|
||||
last.TimestampUtc.ShouldBe(t0.AddMilliseconds(100));
|
||||
}
|
||||
|
||||
/// <summary>#995 (R-19): an array-typed result that did not change is published once; a changed one publishes.</summary>
|
||||
[Fact]
|
||||
public void An_unchanged_array_result_is_published_once_and_a_changed_one_publishes()
|
||||
{
|
||||
var parent = CreateTestProbe();
|
||||
var evaluator = new ArrayEvaluator { Next = () => new[] { 1, 2, 3 } };
|
||||
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-array", "expr", evaluator: evaluator), TestContext.Current.CancellationToken);
|
||||
|
||||
for (var i = 0; i < 5; i++) actor.Tell(new VirtualTagActor.DependencyValueChanged("a", i, DateTime.UtcNow));
|
||||
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Value.ShouldBe(new[] { 1, 2, 3 });
|
||||
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
evaluator.Calls.ShouldBe(5, "every trigger evaluated; only the publish was deduplicated");
|
||||
|
||||
// Positive control: a changed element publishes.
|
||||
evaluator.Next = () => new[] { 1, 2, 4 };
|
||||
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 9, DateTime.UtcNow));
|
||||
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Value.ShouldBe(new[] { 1, 2, 4 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SameValue_compares_one_dimensional_arrays_by_element_and_type()
|
||||
{
|
||||
VirtualTagActor.SameValue(new[] { 1, 2 }, new[] { 1, 2 }).ShouldBeTrue();
|
||||
VirtualTagActor.SameValue(new[] { 1, 2 }, new[] { 1, 3 }).ShouldBeFalse();
|
||||
VirtualTagActor.SameValue(new[] { 1, 2 }, new long[] { 1, 2 }).ShouldBeFalse();
|
||||
VirtualTagActor.SameValue(new[] { "x" }, new[] { "x" }).ShouldBeTrue();
|
||||
VirtualTagActor.SameValue(new int[0], null).ShouldBeFalse();
|
||||
VirtualTagActor.SameValue(5, 5).ShouldBeTrue();
|
||||
VirtualTagActor.SameValue(new int[1, 1], new int[1, 1]).ShouldBeFalse("multi-dimensional arrays keep reference equality");
|
||||
}
|
||||
|
||||
private sealed class ArrayEvaluator : IVirtualTagEvaluator
|
||||
{
|
||||
private int _calls;
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
public volatile Func<int[]> Next = () => [];
|
||||
|
||||
public VirtualTagEvalResult Evaluate(string virtualTagId, string expression, IReadOnlyDictionary<string, object?> dependencies)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
return VirtualTagEvalResult.Ok(Next());
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -264,9 +353,13 @@ one-thread-dispatcher {
|
||||
{
|
||||
private readonly ConcurrentDictionary<int, TaskCompletionSource<VirtualTagEvalResult>> _pending = new();
|
||||
private readonly ConcurrentQueue<object?> _calls = new();
|
||||
private readonly ConcurrentDictionary<int, IReadOnlyDictionary<string, object?>> _inputs = new();
|
||||
|
||||
public IReadOnlyList<object?> Calls => _calls.ToArray();
|
||||
|
||||
/// <summary>Every input value the given call was handed, read at the start of its run.</summary>
|
||||
public IReadOnlyDictionary<string, object?> InputsOfCall(int call) => _inputs[call];
|
||||
|
||||
public void Complete(int call, VirtualTagEvalResult result) => _pending[call].SetResult(result);
|
||||
|
||||
public void Fault(int call, Exception ex) => _pending[call].SetException(ex);
|
||||
@@ -281,6 +374,7 @@ one-thread-dispatcher {
|
||||
var a = dependencies.TryGetValue("a", out var snap) ? snap.Value : null;
|
||||
var tcs = new TaskCompletionSource<VirtualTagEvalResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_pending[_calls.Count] = tcs;
|
||||
_inputs[_calls.Count] = dependencies.ToDictionary(kv => kv.Key, kv => kv.Value.Value, StringComparer.Ordinal);
|
||||
_calls.Enqueue(a);
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Akka.Actor;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.VirtualTags;
|
||||
|
||||
/// <summary>
|
||||
/// #995 (review 2026-12-02 R-17) — a VirtualTag whose data-plane source binding cannot be established used to make
|
||||
/// the host re-deliver the WHOLE <see cref="VirtualTagHostActor.ApplyVirtualTags"/> to itself every 250 ms, with no
|
||||
/// backoff or cap: every replay lifted the run guard's quarantines (re-running a runaway script), re-asserted every
|
||||
/// surviving child, republished every disabled tag's <c>BadOutOfService</c> and recomputed the cycle graph. The retry
|
||||
/// now re-attempts only the still-unbound tags, with backoff, and leaves the rest of the apply alone.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class VirtualTagHostSourceBindingRetryTests : RuntimeActorTestBase
|
||||
{
|
||||
private static readonly ServingIdentity Serving = new("node-a", "instance-a", "Primary", 1, 1);
|
||||
|
||||
[Fact]
|
||||
public void A_failing_source_binding_retries_only_the_unbound_tag_and_does_not_replay_the_apply()
|
||||
{
|
||||
var hub = new RejectingHub { Reject = id => id == "vt-broken" };
|
||||
var publisher = new SourceSamplePublisher(hub, () => Serving, "cluster-a");
|
||||
var evaluator = new CountingEvaluator();
|
||||
var sink = CreateTestProbe();
|
||||
var host = Sys.ActorOf(VirtualTagHostActor.Props(sink.Ref, null, evaluator, sourcePublisher: publisher));
|
||||
|
||||
var healthy = new EquipmentVirtualTagPlan("vt-ok", "eq-1", "", "ok", "Double", "1", Array.Empty<string>());
|
||||
var broken = new EquipmentVirtualTagPlan("vt-broken", "eq-1", "", "broken", "Double", "2", Array.Empty<string>(),
|
||||
TimerIntervalMs: 50);
|
||||
var disabled = new EquipmentVirtualTagPlan("vt-off", "eq-1", "", "off", "Double", "3", Array.Empty<string>()) with { Enabled = false };
|
||||
host.Tell(new VirtualTagHostActor.ApplyVirtualTags(new[] { healthy, broken, disabled }));
|
||||
|
||||
// Four 250 ms periods. The old retry replayed OnApply each time: four more quarantine resets and four more
|
||||
// BadOutOfService publishes for the disabled tag.
|
||||
var disabledNode = V3NodeIds.Uns("eq-1", "off");
|
||||
var outOfServicePublishes = 0;
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromMilliseconds(1100);
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
var msg = sink.ReceiveOne(TimeSpan.FromMilliseconds(50), TestContext.Current.CancellationToken);
|
||||
if (msg is OpcUaPublishActor.AttributeValueUpdate u && u.NodeId == disabledNode) outOfServicePublishes++;
|
||||
}
|
||||
|
||||
evaluator.ResetCount.ShouldBe(1, "only the apply itself lifts the quarantines — a binding retry is not a redeploy");
|
||||
outOfServicePublishes.ShouldBe(1, "the disabled tag's BadOutOfService is published by the apply, not by every retry");
|
||||
evaluator.CallsFor("vt-broken").ShouldBe(0, "no child is spawned for a tag whose source is unbound");
|
||||
|
||||
// Positive control: once the binding can be made, the retry spawns the tag's child, which evaluates on its timer.
|
||||
hub.Reject = _ => false;
|
||||
AwaitCondition(() => evaluator.CallsFor("vt-broken") > 0, PresenceBudget, TestContext.Current.CancellationToken);
|
||||
publisher.TryCaptureVirtual("vt-broken", out _).ShouldBeTrue();
|
||||
evaluator.ResetCount.ShouldBe(1, "the successful retry did not replay the apply either");
|
||||
}
|
||||
|
||||
private sealed class CountingEvaluator : IVirtualTagEvaluator, IScriptQuarantineOwner
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, int> _calls = new(StringComparer.Ordinal);
|
||||
private int _resets;
|
||||
|
||||
public int ResetCount => Volatile.Read(ref _resets);
|
||||
|
||||
public int CallsFor(string id) => _calls.GetValueOrDefault(id);
|
||||
|
||||
public void ResetQuarantines() => Interlocked.Increment(ref _resets);
|
||||
|
||||
public IReadOnlyCollection<string> QuarantinedScripts => Array.Empty<string>();
|
||||
|
||||
public VirtualTagEvalResult Evaluate(string virtualTagId, string expression, IReadOnlyDictionary<string, object?> dependencies)
|
||||
{
|
||||
_calls.AddOrUpdate(virtualTagId, 1, (_, n) => n + 1);
|
||||
return VirtualTagEvalResult.Ok(1d);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A minimal hub that refuses to bind the virtual sources <see cref="Reject"/> names.</summary>
|
||||
private sealed class RejectingHub : ISourceSampleHub
|
||||
{
|
||||
private readonly ConcurrentDictionary<BackingSourceKey, SourceTicket> _current = new();
|
||||
public volatile Func<string, bool> Reject = _ => false;
|
||||
|
||||
public bool TryBind(SourceTicket ticket)
|
||||
{
|
||||
if (Reject(ticket.Key.StableSourceId)) return false;
|
||||
_current[ticket.Key] = ticket;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool TryBind(SourceTicket ticket, ProducerFence? fence) => TryBind(ticket);
|
||||
public bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket) => _current.TryGetValue(key, out ticket);
|
||||
public bool IsTicketCurrentNonBlocking(SourceTicket ticket) => _current.TryGetValue(ticket.Key, out var c) && c == ticket;
|
||||
public void InvalidatePartitionFor(BackingSourceKey key, string reason) { }
|
||||
|
||||
public bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation)
|
||||
{
|
||||
reservation = new Reservation();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Invalidate(SourceTicket ticket, string reason) { }
|
||||
public bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? s, DateTimeOffset? v) => true;
|
||||
public bool TryRemove(SourceTicket ticket, long sequence) => _current.TryRemove(ticket.Key, out _);
|
||||
|
||||
private sealed class Reservation : IIngressReservation
|
||||
{
|
||||
public bool TryCommit(DataSample sample, long sequence)
|
||||
{
|
||||
sample.Dispose();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user