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:
Joseph Doherty
2026-12-03 11:16:21 -05:00
28 changed files with 2034 additions and 217 deletions
+18 -1
View File
@@ -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
+1 -1
View File
@@ -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
View File
@@ -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.
+9
View File
@@ -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
+7
View File
@@ -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