diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 814056d9b..76857ae92 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -215,8 +215,16 @@ 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` 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. +- **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`. +- **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()` 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. + - **Cycles are a blocking deploy error** — `VirtualTagDependencyCycle` (`DraftValidator`): A→B→A, a self-read, longer loops, and loops through a Calculation tag (whose output reaches the mux as a driver value), with `{{equip}}/` reads resolved through the same reference map the compose seams use. Only enabled VirtualTags are graph nodes: a disabled one publishes one static `BadOutOfService` and cannot carry a loop. A cycle of Calculation tags alone stays `CalculationDependencyCycle`. **Runtime backstop:** `VirtualTagHostActor` re-detects VirtualTag-only cycles on every apply (Tarjan, `DependencyGraph`) and does not route the outputs of tags on one (logged as an error), so an artifact that bypassed the gate still cannot become a feedback storm — those tags evaluate and publish, they just do not feed the loop. (A loop through a Calculation tag is caught by the deploy gate only.) `ScriptStackGuard` (#779) is unrelated — it bounds recursion inside one evaluation. + - **Trigger gate.** `VirtualTagNoEffectiveTrigger` counts literal `ctx.GetTag` reads, so a change-triggered tag whose only dependency is another VirtualTag passes — correctly, now that the upstream's output actually arrives. + - **`{{equip}}/` does not resolve a VirtualTag** — that token resolves `UnsTagReference` rows only. `EquipReferenceUnresolved` now says so when the name is a VirtualTag on that equipment and names the key form to use. + - **AdminUI.** The script editor's completion/hover catalog (`ScriptTagCatalog`) lists each VirtualTag under its key instead of its bare leaf name. + - Pinned by `VirtualTagToVirtualTagFlowTests` (Host.Tests: real mux + host + Roslyn evaluator; value, change and disabled-upstream propagation), `VirtualTagOutputRoutingTests` (Runtime.Tests: mux pinning/replay/release, host routing, re-assert exclusion, runtime cycle backstop) and `DraftValidatorVirtualTagCycleTests`. - **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`. - **Calculation tags and scripted alarms still evaluate one script at a time per driver / per engine (deliberately, for now).** Neither blocks a thread — both await the run — but a slow script still delays its siblings. Running independent scripts in parallel was considered for #779 and not done, because it is not semantics-neutral: for Calculation, the single pump is what bounds a driver to one pool thread of script work (per-tag lanes would let N slow tags hold N pool threads, the pool Akka's dispatchers also run on, so it needs a bounded-parallelism knob), it would reorder publishes across tags, and the timer path would need per-tag exclusion with the pump; for scripted alarms, the engine gate is also the consistency boundary of the Part 9 state machine, persist-before-update and ack/shelve/load, a predicate's transition time is sampled just before its own run, and a store failure mid-batch today leaves later predicates un-run (in parallel they would already have run, moving their run-guard strike streaks and writing script logs for results that are then discarded). The out-of-process runner's batch-submit `IScriptRunner` (#750) is where that concurrency belongs, with the runner owning the bound. - **`IHistoryWriter`** — the equipment-namespace path threads `Historize` end-to-end and `VirtualTagHostActor` invokes the injected writer on historized results (H5); the writer is resolved through `DriverHostActor` DI with a `NullHistoryWriter` default. No *durable* writer ships on this seam — durable continuous historization now flows through the separate `ContinuousHistorizationRecorder` → HistorianGateway `WriteLiveValues` path (see the `IHistoryWriter` section above and [Historian.md](Historian.md)). @@ -229,8 +237,8 @@ In the v2 actor system, virtual-tag engine composition is owned by the driver-ro - `AddressSpaceComposer.Compose` emits `DriverInstancePlan` / `ScriptedAlarmPlan` records; the driver-role `DriverHostActor` spawns one `VirtualTagActor` per virtual-tag expression and one `ScriptedAlarmActor` per scripted alarm. - `RoslynVirtualTagEvaluator` (`src/Server/ZB.MOM.WW.OtOpcUa.Host/Engines/RoslynVirtualTagEvaluator.cs`) is injected into each `VirtualTagActor` as its `IVirtualTagEvaluator`. It holds a per-source `CompiledScriptCache` keyed by script source and compiles on first use. -- **Disabled virtual tags (`VirtualTag.Enabled = false`, lmxopcua#787, owner decision).** A disabled tag **keeps its node** but is **never evaluated**. Both seams (`AddressSpaceComposer.Compose` and the artifact decode `DeploymentArtifact.BuildEquipmentVirtualTagPlans`, byte-parity) keep the row in `EquipmentVirtualTags` with `EquipmentVirtualTagPlan.Enabled = false` (part of the plan's value equality), so the node is materialised exactly as for an enabled tag (same NodeId, read-only). `VirtualTagHostActor` spawns **no** `VirtualTagActor` for it (no mux registration, no timer, no historization) and instead publishes **`BadOutOfService` (0x808D0000) with a null value**, stamped `DateTime.UtcNow` at deploy, on every apply (a rebuild resets the node to `BadWaitingForInitialData`; the publish lands after it in the publish actor's mailbox). A client bound to the node (e.g. ScadaBridge) therefore reads a Bad quality, not `BadNodeIdUnknown`, and can tell "deliberately out of service" from "script failed" (`BadInternalError`). Writes are refused like any VirtualTag (the node is read-only). Flipping `Enabled` is node-irrelevant to `AddressSpaceChangeClassifier` (no address-space rebuild): enabled -> disabled stops the live child and publishes `BadOutOfService`; disabled -> enabled (redeploy) spawns the child and evaluation resumes on the next trigger. A script that reads a disabled VT via `ctx.GetTag` gets no pushed value for it (VirtualTag outputs are not fed through `DependencyMuxActor`, which carries driver publishes only), i.e. the same never-pushed/null upstream it would see for an enabled VT, so a dependent never sees a stale Good. `DraftValidator` exempts a disabled VT from `VirtualTagNoEffectiveTrigger` (it never evaluates, so it must not block a deploy); its name still counts toward the equipment name-uniqueness check. **Scripted alarms are unchanged:** a disabled one is still not materialised (`MaterialiseScriptedAlarms` skips it) and exposes no node; only VirtualTags keep a node. Calculation tags have no `Enabled` flag, so there is no equivalent gap. Pinned by `VirtualTagHostActorTests`, `DeploymentArtifactVirtualTagHistorizeParityTests`, `DriverHostActorVirtualTagTests`, `DraftValidatorVirtualTagTriggerTests` and, on the wire, `DisabledVirtualTagWireTests`. -- `DependencyMuxActor` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs`) receives every `DriverInstanceActor.AttributeValueBatchPublished` and routes each item to the `VirtualTagActor` instances that registered interest in that tag ref. +- **Disabled virtual tags (`VirtualTag.Enabled = false`, lmxopcua#787, owner decision).** A disabled tag **keeps its node** but is **never evaluated**. Both seams (`AddressSpaceComposer.Compose` and the artifact decode `DeploymentArtifact.BuildEquipmentVirtualTagPlans`, byte-parity) keep the row in `EquipmentVirtualTags` with `EquipmentVirtualTagPlan.Enabled = false` (part of the plan's value equality), so the node is materialised exactly as for an enabled tag (same NodeId, read-only). `VirtualTagHostActor` spawns **no** `VirtualTagActor` for it (no mux registration, no timer, no historization) and instead publishes **`BadOutOfService` (0x808D0000) with a null value**, stamped `DateTime.UtcNow` at deploy, on every apply (a rebuild resets the node to `BadWaitingForInitialData`; the publish lands after it in the publish actor's mailbox). A client bound to the node (e.g. ScadaBridge) therefore reads a Bad quality, not `BadNodeIdUnknown`, and can tell "deliberately out of service" from "script failed" (`BadInternalError`). Writes are refused like any VirtualTag (the node is read-only). Flipping `Enabled` is node-irrelevant to `AddressSpaceChangeClassifier` (no address-space rebuild): enabled -> disabled stops the live child and publishes `BadOutOfService`; disabled -> enabled (redeploy) spawns the child and evaluation resumes on the next trigger. The same `BadOutOfService` is routed through `DependencyMuxActor` (lmxopcua#791, below), so a VirtualTag that reads a disabled one by its key holds evaluation and reports `BadOutOfService` itself — it never serves a value computed from a stale input. `DraftValidator` exempts a disabled VT from `VirtualTagNoEffectiveTrigger` (it never evaluates, so it must not block a deploy); its name still counts toward the equipment name-uniqueness check. **Scripted alarms are unchanged:** a disabled one is still not materialised (`MaterialiseScriptedAlarms` skips it) and exposes no node; only VirtualTags keep a node. Calculation tags have no `Enabled` flag, so there is no equivalent gap. Pinned by `VirtualTagHostActorTests`, `DeploymentArtifactVirtualTagHistorizeParityTests`, `DriverHostActorVirtualTagTests`, `DraftValidatorVirtualTagTriggerTests` and, on the wire, `DisabledVirtualTagWireTests`. +- `DependencyMuxActor` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs`) receives every `DriverInstanceActor.AttributeValueBatchPublished` and every `VirtualTagOutput` from the VirtualTag host (lmxopcua#791), and routes each item to the `VirtualTagActor` instances that registered interest in that tag ref. `ITagUpstreamSource` and `IHistoryWriter` remain available as `Core.VirtualTags` ports. @@ -251,7 +259,7 @@ In the v2 actor system, virtual-tag engine composition is owned by the driver-ro - `src/Core/ZB.MOM.WW.OtOpcUa.Core.VirtualTags/ITagUpstreamSource.cs` — driver-tag read + subscribe port - `src/Core/ZB.MOM.WW.OtOpcUa.Core.VirtualTags/IHistoryWriter.cs` — historize sink port + `NullHistoryWriter` - `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagActor.cs` — actor that receives `DependencyValueChanged` from the mux and invokes `IVirtualTagEvaluator` per expression -- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs` — routes `DriverInstanceActor.AttributeValueBatchPublished` items to interested `VirtualTagActor` subscribers +- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs` — routes `DriverInstanceActor.AttributeValueBatchPublished` items and VirtualTag outputs (`VirtualTagOutput`, #791) to interested `VirtualTagActor` subscribers - `src/Server/ZB.MOM.WW.OtOpcUa.Host/Engines/RoslynVirtualTagEvaluator.cs` — production `IVirtualTagEvaluator` binding; holds a per-source `CompiledScriptCache` - `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceComposer.cs` — pure data composer: config-DB entities → `AddressSpaceComposition` (UNS topology + raw subtree + driver/alarm plans) - `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs` — applies the composed plan into the SDK node manager diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs index 7a94dc25c..88714a5fd 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs @@ -41,6 +41,7 @@ public static class DraftValidator ValidateEquipReferenceResolution(draft, errors); ValidateCalculationTags(draft, errors); ValidateVirtualTagTriggers(draft, errors); + ValidateVirtualTagDependencyCycles(draft, errors); ValidateSqlConnectionStringNotPersisted(draft, errors); errors.AddRange(SqlTagDeployChecks.UndeclaredQueryErrors(draft)); errors.AddRange(SqlTagDeployChecks.WriteBlockErrors(draft)); @@ -510,6 +511,104 @@ public static class DraftValidator } } + /// The VirtualTagDependencyCycle error code (lmxopcua#791). + public const string VirtualTagDependencyCycleCode = "VirtualTagDependencyCycle"; + + /// + /// lmxopcua#791 — VirtualTag outputs feed the dependency mux, so a VirtualTag reading another VirtualTag (by + /// its key, the UNS NodeId identifier {EquipmentId}/{Name}) re-evaluates on it. A cycle through + /// VirtualTags — A→B→A, a self-read, or a loop through a Calculation tag (whose output reaches the mux as a + /// driver value) — is therefore a live feedback loop, and is a blocking deploy error naming its members. + /// Graph: nodes are the enabled VirtualTags' keys (a disabled tag never evaluates, so it + /// publishes one static BadOutOfService and cannot carry a loop) plus every Calculation tag's RawPath; + /// an edge runs from a node to each of its literal ctx.GetTag reads that is itself a node. VirtualTag + /// reads are taken after {{equip}}/<RefName> substitution, through the same reference map the + /// compose seams use, so a reference backed by a Calculation tag is an edge too. A cycle made only of + /// Calculation tags is left to CalculationDependencyCycle (one error per cycle). + /// + private static void ValidateVirtualTagDependencyCycles(DraftSnapshot draft, List errors) + { + var enabled = draft.VirtualTags.Where(v => v.Enabled).ToList(); + if (enabled.Count == 0) return; + + var scriptSourceById = draft.Scripts + .GroupBy(s => s.ScriptId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.First().SourceCode, StringComparer.Ordinal); + var resolver = BuildRawPathResolver(draft); + + // VirtualTag key → VirtualTagId (for the error context). VirtualTag has no FolderPath, so the key is the + // two-segment UNS NodeId VirtualTagHostActor publishes to and routes under. + var vtIdByKey = new Dictionary(StringComparer.Ordinal); + foreach (var v in enabled) vtIdByKey.TryAdd(VirtualTagKey(v), v.VirtualTagId); + + // Calculation tags: RawPath → literal reads. + var driverTypeByInstance = draft.DriverInstances + .GroupBy(d => d.DriverInstanceId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.First().DriverType, StringComparer.Ordinal); + var calcDeps = new Dictionary>(StringComparer.Ordinal); + var deviceIsCalc = draft.Devices + .GroupBy(d => d.DeviceId, StringComparer.Ordinal) + .ToDictionary( + g => g.Key, + g => driverTypeByInstance.TryGetValue(g.First().DriverInstanceId, out var dt) + && string.Equals(dt, Core.Abstractions.DriverTypeNames.Calculation, StringComparison.Ordinal), + StringComparer.Ordinal); + foreach (var t in draft.Tags) + { + if (!deviceIsCalc.GetValueOrDefault(t.DeviceId)) continue; + var rawPath = resolver.TryBuildTagPath(t.DeviceId, t.TagGroupId, t.Name); + if (rawPath is null) continue; + var scriptId = ParseScriptId(t.TagConfig); + var source = scriptId is not null && scriptSourceById.TryGetValue(scriptId, out var src) ? src : null; + calcDeps.TryAdd(rawPath, EquipmentScriptPaths.ExtractDependencyRefs(source)); + } + + bool IsNode(string r) => vtIdByKey.ContainsKey(r) || calcDeps.ContainsKey(r); + + // {{equip}}/ → RawPath, identical to AddressSpaceComposer / DeploymentArtifact. + var tagsById = draft.Tags + .GroupBy(t => t.TagId, StringComparer.Ordinal) + .ToDictionary( + g => g.Key, + g => new EquipmentReferenceMap.TagRow(g.First().Name, g.First().DeviceId, g.First().TagGroupId), + StringComparer.Ordinal); + var referenceMapByEquip = EquipmentReferenceMap.Build( + draft.UnsTagReferences.Select(r => new EquipmentReferenceMap.ReferenceRow( + r.UnsTagReferenceId, r.EquipmentId, r.TagId, r.DisplayNameOverride)), + tagsById, resolver); + var noRefs = (IReadOnlyDictionary)new Dictionary(StringComparer.Ordinal); + + var graph = new DependencyGraph(); + foreach (var v in enabled) + { + var src = scriptSourceById.TryGetValue(v.ScriptId, out var s) ? s : null; + if (src is null) continue; + var expanded = EquipmentScriptPaths.SubstituteEquipmentToken( + src, referenceMapByEquip.GetValueOrDefault(v.EquipmentId, noRefs)); + graph.Add(VirtualTagKey(v), EquipmentScriptPaths.ExtractDependencyRefs(expanded) + .Where(IsNode).ToHashSet(StringComparer.Ordinal)); + } + foreach (var (rawPath, deps) in calcDeps) + graph.Add(rawPath, deps.Where(IsNode).ToHashSet(StringComparer.Ordinal)); + + foreach (var cycle in graph.DetectCycles()) + { + var firstVt = cycle.FirstOrDefault(vtIdByKey.ContainsKey); + if (firstVt is null) continue; // calc-only: CalculationDependencyCycle reports it + errors.Add(new(VirtualTagDependencyCycleCode, + "VirtualTags form a dependency cycle (members: " + string.Join(", ", cycle) + + "); a VirtualTag output feeds the tags that read it, so a cycle is a live feedback loop and must be " + + "broken before deploy", + vtIdByKey[firstVt])); + } + } + + /// A VirtualTag's key in scripts and in the dependency mux — its UNS NodeId identifier + /// {EquipmentId}/{Name} (VirtualTag has no FolderPath), as published by VirtualTagHostActor. + /// The VirtualTag. + /// The key. + private static string VirtualTagKey(VirtualTag v) => v.EquipmentId + RawPaths.Separator + v.Name; + /// Read the trigger fields from a calc tag's TagConfig: changeTriggered /// (default true, the driver's own default) and timerIntervalMs (null when absent or not a /// number). Never throws — malformed JSON yields the defaults. @@ -685,6 +784,7 @@ public static class DraftValidator var scriptSourceById = draft.Scripts.GroupBy(s => s.ScriptId, StringComparer.Ordinal) .ToDictionary(g => g.Key, g => g.First().SourceCode, StringComparer.Ordinal); + var vtNames = draft.VirtualTags.Select(v => (v.EquipmentId, v.Name)).ToHashSet(); void CheckRefs(string equipmentId, IEnumerable refNames, string source) { @@ -692,9 +792,14 @@ public static class DraftValidator foreach (var name in refNames) { if (have is not null && have.Contains(name)) continue; + // lmxopcua#791: {{equip}}/ resolves references only. Name the form that does read a VirtualTag. + var hint = vtNames.Contains((equipmentId, name)) + ? $" '{name}' is a VirtualTag on this equipment: read it by its key, " + + $"ctx.GetTag(\"{equipmentId}{RawPaths.Separator}{name}\")." + : string.Empty; errors.Add(new("EquipReferenceUnresolved", $"{source} uses '{EquipmentScriptPaths.EquipTokenPrefix}{name}' but equipment '{equipmentId}' has " + - $"no reference named '{name}'; add a reference with that effective name or correct the script.", + $"no reference named '{name}'; add a reference with that effective name or correct the script." + hint, equipmentId)); } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/IScriptTagCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/IScriptTagCatalog.cs index 18370bc32..19fae3e1e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/IScriptTagCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/IScriptTagCatalog.cs @@ -41,8 +41,9 @@ public sealed record ScriptTagInfo(string Path, string Kind, string DataType, st /// /// Default . Returns ONLY the resolvable keys a script may pass to -/// ctx.GetTag / ctx.SetVirtualTag — in v3 that is a raw tag's RawPath, plus the -/// leaf Name (best-effort) for virtual tags. +/// ctx.GetTag / ctx.SetVirtualTag — in v3 that is a raw tag's RawPath, plus each virtual +/// tag's key {EquipmentId}/{Name} (its UNS NodeId identifier, which the dependency mux routes its output +/// under — lmxopcua#791). /// /// /// @@ -195,7 +196,7 @@ public sealed class ScriptTagCatalog( var vtagRows = await db.VirtualTags .AsNoTracking() - .Select(v => new { v.Name, v.DataType }) + .Select(v => new { v.EquipmentId, v.Name, v.DataType }) .ToListAsync(ct); var entries = new List(tagRows.Count + vtagRows.Count); @@ -213,9 +214,10 @@ public sealed class ScriptTagCatalog( foreach (var v in vtagRows) { - // Virtual tag — best-effort: the live resolution of virtual-tag cascade/write targets is - // unconfirmed, so emit the leaf Name only. - entries.Add(new ScriptTagInfo(v.Name, "Virtual tag", v.DataType, null)); + // Virtual tag — its key is the UNS NodeId identifier VirtualTagHostActor publishes to AND routes its + // output under in the dependency mux (lmxopcua#791), so ctx.GetTag("{EquipmentId}/{Name}") reads it. + // (The leaf Name this used to emit never resolved: nothing was published under it.) + entries.Add(new ScriptTagInfo(v.EquipmentId + RawPaths.Separator + v.Name, "Virtual tag", v.DataType, null)); } return entries; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs index 51174b9e1..9a6956eef 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs @@ -54,6 +54,17 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; /// ends (a deploy removal, the stop half of a config-change respawn, an operator Restart), and never /// on a supervision restart, which re-uses the same driver. /// +/// +/// VirtualTag outputs (lmxopcua#791). A VirtualTag's own result is a second ingress: +/// sends one per real evaluation (and the +/// BadOutOfService it publishes for a disabled tag), keyed by the VirtualTag's UNS NodeId identifier +/// ({EquipmentId}/{Name}) — the same string it is published to. So a VirtualTag, a Calculation tag +/// or a scripted alarm whose ctx.GetTag literal names that key receives it exactly like a driver +/// value. A VirtualTag output is always retained (pinned), whether or not anyone has registered for +/// it yet: dependents spawn in the same apply as their upstream and register asynchronously, and the +/// upstream may evaluate first. Memory is bounded by the number of deployed VirtualTags; +/// unpins a removed (or renamed) tag's key. +/// /// public sealed class DependencyMuxActor : ReceiveActor, IWithTimers { @@ -81,6 +92,23 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers /// The removed driver instance. public sealed record SourceRemoved(string DriverInstanceId); + /// One VirtualTag result, routed to the tags that read it (lmxopcua#791). Always retained (see the + /// type remarks), so a dependent registering later is replayed the current value. + /// The VirtualTag's key — its UNS NodeId identifier, {EquipmentId}/{Name}. + /// The published value (null for an inputs-Bad / disabled result with no value). + /// The result's timestamp. + /// The published OPC UA status code. + public sealed record VirtualTagOutput(string TagRef, object? Value, DateTime TimestampUtc, uint StatusCode); + + /// These VirtualTag keys are no longer deployed (removed, or renamed away): unpin and drop their + /// retained output so it is never replayed. Subscriptions are untouched. + /// The keys to release. + public sealed record VirtualTagOutputsRemoved(IReadOnlyCollection TagRefs); + + /// The LastSource recorded for a VirtualTag output. Not a legal driver instance id (it starts + /// with a NUL), so can never evict a VirtualTag's value. + internal const string VirtualTagSource = "\0virtual-tag"; + private sealed class SweepReleased { public static readonly SweepReleased Instance = new(); @@ -102,7 +130,11 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers public VirtualTagActor.DependencyValueChanged? Last; public string? LastSource; - public bool Retains => Replayers > 0 || ReleasedAtUtc is not null; + /// A VirtualTag output (lmxopcua#791): retained unconditionally until + /// , never put into grace. + public bool Pinned; + + public bool Retains => Pinned || Replayers > 0 || ReleasedAtUtc is not null; public bool IsDead => Subscribers.Count == 0 && Replayers == 0 && Last is null; public void Forget() @@ -151,6 +183,8 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers Receive(OnSourceRemoved); Receive(_ => OnSweep()); Receive(OnAttributeValueBatchPublished); + Receive(OnVirtualTagOutput); + Receive(OnVirtualTagOutputsRemoved); Receive(msg => RemoveSubscriber(msg.ActorRef)); } @@ -208,7 +242,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers { if (!_byRef.TryGetValue(r, out var entry)) continue; entry.Subscribers.Remove(subscriber); - if (registration.Replay && --entry.Replayers == 0 && entry.Last is not null) + if (registration.Replay && --entry.Replayers == 0 && entry.Last is not null && !entry.Pinned) { entry.ReleasedAtUtc = now; released = true; @@ -260,6 +294,33 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers _log.Debug("DependencyMux: source {Driver} removed — evicted {Count} retained value(s)", msg.DriverInstanceId, evicted); } + private void OnVirtualTagOutput(VirtualTagOutput msg) + { + if (!_byRef.TryGetValue(msg.TagRef, out var entry)) + { + entry = new RefEntry(); + _byRef[msg.TagRef] = entry; + } + var dep = new VirtualTagActor.DependencyValueChanged(msg.TagRef, msg.Value, msg.TimestampUtc, msg.StatusCode); + entry.Pinned = true; + entry.ReleasedAtUtc = null; + entry.Last = dep; + entry.LastSource = VirtualTagSource; + foreach (var sub in entry.Subscribers) + sub.Tell(new VirtualTagActor.DependencyValueBatch(new[] { dep })); + } + + private void OnVirtualTagOutputsRemoved(VirtualTagOutputsRemoved msg) + { + foreach (var r in msg.TagRefs) + { + if (!_byRef.TryGetValue(r, out var entry) || !entry.Pinned) continue; + entry.Pinned = false; + entry.Forget(); + if (entry.IsDead) _byRef.Remove(r); + } + } + private void OnAttributeValueBatchPublished(DriverInstanceActor.AttributeValueBatchPublished msg) { // Nothing registered and nothing retained — skip the whole burst rather than probing an empty map per item. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs index 172b37980..cd8729422 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs @@ -26,6 +26,17 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; /// AddressSpaceApplier.MaterialiseEquipmentVirtualTags materialises against — so the value /// always lands on a NodeId that exists. /// +/// +/// VirtualTag → VirtualTag (lmxopcua#791). Every real result (not a re-assert) is also sent to the +/// dependency mux as a keyed by that same NodeId +/// identifier, as is the BadOutOfService of a disabled tag — so a tag whose ctx.GetTag +/// literal is {EquipmentId}/{Name} re-evaluates on it like on a driver value. The OPC UA publish +/// stays single-source (this host, one NodeId); the mux leg only feeds dependents. Keys that leave the +/// deployed set are released with . Cycles are a +/// blocking deploy error (VirtualTagDependencyCycle); as a runtime backstop the host detects them +/// again on every apply and does not route the outputs of a tag on a cycle, so a cycle can never become a +/// feedback storm. +/// /// public sealed class VirtualTagHostActor : ReceiveActor { @@ -52,6 +63,10 @@ public sealed class VirtualTagHostActor : ReceiveActor // Expression/DependencyRefs) and stop+respawn the child to adopt it. Kept in lock-step with // _children: rebuilt to the desired set at the end of every apply, and pruned in OnChildTerminated. private readonly Dictionary _planByVtag = new(StringComparer.Ordinal); + // Every key (NodeId) of the last applied plan set, enabled and disabled — what the mux holds pinned outputs for. + private readonly HashSet _deployedKeys = new(StringComparer.Ordinal); + // Keys on a VirtualTag dependency cycle (lmxopcua#791 runtime backstop): their outputs are never routed. + private readonly HashSet _unroutedKeys = new(StringComparer.Ordinal); /// Factory method to create Props for a VirtualTagHostActor. /// The OPC UA publish actor that consumes @@ -219,22 +234,61 @@ public sealed class VirtualTagHostActor : ReceiveActor child.Tell(VirtualTagActor.ReassertValue.Instance); } + RouteToDependents(msg.Plans); + // Disabled plans: never evaluated; publish BadOutOfService + null value on the (still present) UNS // node, stamped at deploy time. Re-published on EVERY apply on purpose: a deploy that rebuilds the // address space resets every VirtualTag node to BadWaitingForInitialData, and this Tell lands in the // publish actor's FIFO mailbox after that RebuildAddressSpace (same ordering argument as the // re-assert above). Never historized (no real evaluation happened) and not in _nodeIdByVtag: no child // exists to send a result for them. + // The same status is routed to the tag's dependents (lmxopcua#791), so a tag reading a disabled tag + // reports BadOutOfService instead of serving a value computed from a stale input. foreach (var p in msg.Plans.Where(p => !p.Enabled)) { + var nodeId = NodeIdFor(p); + var now = DateTime.UtcNow; _publishActor.Tell(new OpcUaPublishActor.AttributeValueUpdate( - NodeIdFor(p), null, OpcUaStatus.BadOutOfService, DateTime.UtcNow, AddressSpaceRealm.Uns)); + nodeId, null, OpcUaStatus.BadOutOfService, now, AddressSpaceRealm.Uns)); + _mux?.Tell(new DependencyMuxActor.VirtualTagOutput(nodeId, null, now, OpcUaStatus.BadOutOfService)); } _log.Debug("VirtualTagHost: applied (desired={Desired}, children={Children}, disabled={Disabled})", desired.Count, _children.Count, msg.Plans.Count - evaluated.Count); } + /// + /// 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 + /// deployed, enabled VirtualTag's key). The deploy gate rejects such a cycle; this is the backstop for an + /// artifact that bypassed it — a tag on a cycle still evaluates and publishes, but its output is not fed + /// back into the cycle. + /// + /// The full desired plan set, enabled and disabled. + private void RouteToDependents(IReadOnlyList plans) + { + if (_mux is null) return; + + var keys = plans.Select(NodeIdFor).ToHashSet(StringComparer.Ordinal); + var removed = _deployedKeys.Where(k => !keys.Contains(k)).ToList(); + if (removed.Count > 0) _mux.Tell(new DependencyMuxActor.VirtualTagOutputsRemoved(removed)); + _deployedKeys.Clear(); + _deployedKeys.UnionWith(keys); + + var enabledKeys = plans.Where(p => p.Enabled).Select(NodeIdFor).ToHashSet(StringComparer.Ordinal); + var graph = new DependencyGraph(); + foreach (var p in plans.Where(p => p.Enabled)) + graph.Add(NodeIdFor(p), p.DependencyRefs.Where(enabledKeys.Contains).ToHashSet(StringComparer.Ordinal)); + _unroutedKeys.Clear(); + foreach (var cycle in graph.DetectCycles()) + { + _unroutedKeys.UnionWith(cycle); + _log.Error("VirtualTagHost: VirtualTags form a dependency cycle ({Members}); their outputs are not routed to " + + "each other. The deploy gate (VirtualTagDependencyCycle) should have rejected this.", + string.Join(", ", cycle)); + } + } + private void OnResult(VirtualTagActor.EvaluationResult result) { // A result may arrive for a vtag that was just removed from the desired set (the child's @@ -251,6 +305,12 @@ public sealed class VirtualTagHostActor : ReceiveActor _publishActor.Tell(new OpcUaPublishActor.AttributeValueUpdate( nodeId, result.Value, result.StatusCode, result.TimestampUtc, AddressSpaceRealm.Uns)); + // lmxopcua#791: feed the VirtualTags (and Calculation tags / scripted alarms) that read this one. A + // re-assert is not routed — it repeats a state the mux already holds pinned, and would only re-run every + // dependent's script on each deploy. + if (!result.IsReassert && !_unroutedKeys.Contains(nodeId)) + _mux?.Tell(new DependencyMuxActor.VirtualTagOutput(nodeId, result.Value, result.TimestampUtc, result.StatusCode)); + // Historize iff the plan opted in — but NEVER for a re-assert. A re-assert re-publishes a // stale last value stamped with a fresh deploy-time timestamp purely to repair the reset OPC UA // node; recording it would append an artificial historian sample that never corresponded to a real diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorVirtualTagCycleTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorVirtualTagCycleTests.cs new file mode 100644 index 000000000..a8187bb42 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorVirtualTagCycleTests.cs @@ -0,0 +1,123 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests; + +/// lmxopcua#791 — VirtualTag outputs feed the dependency mux, so a VirtualTag can read another one by its +/// key ({EquipmentId}/{Name}); a cycle through VirtualTags is a blocking VirtualTagDependencyCycle. +[Trait("Category", "Unit")] +public sealed class DraftValidatorVirtualTagCycleTests +{ + private const string Eq = "eq-1"; + + private static Script ScriptRow(string id, string source) => new() + { + ScriptId = id, Name = id, SourceCode = source, SourceHash = "h-" + id, + }; + + private static VirtualTag Vt(string name, string scriptId, bool enabled = true) => new() + { + VirtualTagId = "vt-" + name, EquipmentId = Eq, Name = name, DataType = "Double", ScriptId = scriptId, + Enabled = enabled, + }; + + private static string Read(string path) => $"return (double)ctx.GetTag(\"{path}\").Value + 1;"; + + private static List Cycles(DraftSnapshot draft) => + DraftValidator.Validate(draft).Where(e => e.Code == DraftValidator.VirtualTagDependencyCycleCode).ToList(); + + private static DraftSnapshot Draft(IEnumerable vts, IEnumerable