From 65fd71de7a9ea3a6fa73e846c265ab66a4cde087 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 2 Dec 2026 16:06:45 -0500 Subject: [PATCH] docs(review): 2026-12-02 full code review (10 slices, ~150 findings) + remediation plan Tracked as #971-#1002. --- docs/reviews/2026-12-02/00-SUMMARY.md | 106 +++ docs/reviews/2026-12-02/01-runtime.md | 645 ++++++++++++++++++ docs/reviews/2026-12-02/02-opcuaserver.md | 384 +++++++++++ docs/reviews/2026-12-02/03-configuration.md | 329 +++++++++ .../reviews/2026-12-02/04-adminui-security.md | 160 +++++ .../05-host-controlplane-cluster.md | 289 ++++++++ docs/reviews/2026-12-02/06-core.md | 462 +++++++++++++ .../07-galaxy-opcuaclient-historians.md | 478 +++++++++++++ .../08-mtconnect-mqtt-heidenhain.md | 483 +++++++++++++ .../reviews/2026-12-02/09-ab-twincat-focas.md | 334 +++++++++ .../10-s7-modbus-sql-calc-clients.md | 380 +++++++++++ .../plans/2026-12-02-review-remediation.md | 217 ++++++ 12 files changed, 4267 insertions(+) create mode 100644 docs/reviews/2026-12-02/00-SUMMARY.md create mode 100644 docs/reviews/2026-12-02/01-runtime.md create mode 100644 docs/reviews/2026-12-02/02-opcuaserver.md create mode 100644 docs/reviews/2026-12-02/03-configuration.md create mode 100644 docs/reviews/2026-12-02/04-adminui-security.md create mode 100644 docs/reviews/2026-12-02/05-host-controlplane-cluster.md create mode 100644 docs/reviews/2026-12-02/06-core.md create mode 100644 docs/reviews/2026-12-02/07-galaxy-opcuaclient-historians.md create mode 100644 docs/reviews/2026-12-02/08-mtconnect-mqtt-heidenhain.md create mode 100644 docs/reviews/2026-12-02/09-ab-twincat-focas.md create mode 100644 docs/reviews/2026-12-02/10-s7-modbus-sql-calc-clients.md create mode 100644 docs/superpowers/plans/2026-12-02-review-remediation.md diff --git a/docs/reviews/2026-12-02/00-SUMMARY.md b/docs/reviews/2026-12-02/00-SUMMARY.md new file mode 100644 index 000000000..fb782be35 --- /dev/null +++ b/docs/reviews/2026-12-02/00-SUMMARY.md @@ -0,0 +1,106 @@ +# OtOpcUa full code review (bugs + performance) — merged summary + +Master @ `708a4889c`, 2026-12-02. 10 parallel Fable reviewers, read-only, ~430k lines of `src/`. Every finding is cited to +file:line with a failure scenario, suggested fix and test in the per-slice report. Most findings are from code reading; +the ones that were reproduced or probe-verified say so in their slice report (K-1, K-3 timing, K-7, K-6/K-8/K-9/K-10, M-2, U-1). + +| # | Slice | Report | Crit | High | Med | Low | Total | +|---|---|---|---|---|---|---|---| +| 1 | Runtime | `01-runtime.md` | – | 3 | 11 | 11 | 25 | +| 2 | OpcUaServer | `02-opcuaserver.md` | 1 | 2 | 6 | 4 | 13 | +| 3 | Configuration | `03-configuration.md` | – | 2 | 3 | 6 | 11 | +| 4 | AdminUI + Security | `04-adminui-security.md` | – | 1 | 4 | 4 | 9 | +| 5 | Host / ControlPlane / Cluster | `05-host-controlplane-cluster.md` | – | 1 | 2 | 3 | 6 | +| 6 | Core libraries + scripting | `06-core.md` | 1 | 2 | 3 | 5 | 11 | +| 7 | Galaxy / OpcUaClient / historians | `07-galaxy-opcuaclient-historians.md` | – | 1 | 6 | 12 | 19 | +| 8 | MTConnect / MQTT / Heidenhain | `08-mtconnect-mqtt-heidenhain.md` | – | – | 6 | 13 | 19 | +| 9 | AB / TwinCAT / FOCAS | `09-ab-twincat-focas.md` | – | 5 | 14 | 6 | 25 | +| 10 | S7 / Modbus / Sql / Calc / clients / analyzers | `10-s7-modbus-sql-calc-clients.md` | – | 2 | 7 | 3 | 12 | +| | | | **2** | **19** | **62** | **67** | **~150** | + +Duplicates found independently (merged below): **G-16 ≡ K-2** (alarm S&F dead-letter), **C-1 ≡ R-5** (VirtualTag name +not a legal NodeId segment), **C-11 ≈ A-5** (whole-DB snapshot loader on the data-connections page). + +Not reviewed in depth (stated in the slice reports): ~20 projected-side `DataConnections` files, `Compatibility/Aggregates/*`, +`WarmStandby.cs`, the per-driver AdminUI forms/tag editors, `RawTree`/`RawBrowseModal`, the Sql catalog gate/loader, most of Client.UI. + +## Cross-cutting themes (fix the pattern, not N instances) + +1. **Security boundaries with holes.** Script sandbox deny-list bypassable via `Delegate.CreateDelegate` / + `System.Linq.Expressions` (process start + file read reproduced) (**K-1**); ACL grants enforced on subscription + revalidation with ACLs *disabled* — a regression from `8ad03e9c5` (**U-1**); `/fleet/diagnostics` lets any signed-in user + point an Akka `ActorSelection` at an arbitrary host (**A-1**); SQL read-only guard bypassable by provider quoting (**S-7**); + AdminUI roles frozen at sign-in (**A-2**). +2. **One name authority is still missing.** VirtualTag names (C-1/R-5), `DisplayNameOverride` (C-4) and `UnsSegment`'s + `$`-accepts-newline (C-7) all pass authoring + deploy gate and then throw or vanish in `V3NodeIds.Uns`. This is the + "authoring-vs-deploy-gate drift" class again: validate with the *same* function `V3NodeIds` uses, at the gate. +3. **Transient outages are being treated as permanent.** Alarm S&F counts `RetryPlease` against `MaxAttempts` → + dead-letter after ~6.5 min outage (G-16/K-2); Gateway alarm writer maps `Cancelled`/`Unknown` to `PermanentFail` (G-8); + FOCAS bootstrap latches capabilities unsupported on one transient failure (P-7); `CoalesceRejected` latches on transient codes (P-21). +4. **Health contract still wrong in both directions.** + - *Refusals counted as comms faults:* FOCAS fixed-tree refusals (P-6), TwinCAT ADS refusals default to `BadCommunicationError` (P-12), + S7 bad-value writes (S-5), Gateway read refusals (G-9), OpcUaClient post-dispatch write (G-14), projected `QueryAsync` + cancel/fault (R-8), publisher capacity refusal retires the route (R-10). + - *Outages that never degrade:* MQTT malformed filter kills the batched SUBSCRIBE with health Healthy (M-2), silently + dead mxaccessgw connection (G-19), Galaxy dropped pump events stale-Good (G-4), Sparkplug primary-host never re-claims (M-6). +5. **One dead device stalls the rest.** AbCip warm handles bypass backoff (P-2), TwinCAT serial reads (P-3) and probe replay + of every registration (P-4), FOCAS probe holds `ConnectGate` (P-11) and unbounded close handshake (P-8). +6. **Stale or foreign data reported Good.** Modbus RTU-over-TCP desync returns another request's reply (S-1), TwinCAT online + change leaves stale symbol offsets (P-1), Modbus deadband suppresses initial publish after re-subscribe (S-2), failed + overlapping writes leave the rejected value Good (U-4), dependents of a removed input keep computing (R-6). +7. **Deploy/apply bookkeeping.** Boot after a failed deploy restores nothing (R-1); planner blind to scripted-alarm + Enabled/Type/Name (U-2) and Line re-parenting (U-3); a clean surgical apply clears the degraded flag without repair (R-4); + revision advances before the last throwing step (R-15); `OpcUaPublishActor` restart resets `_lastApplied` (R-20); + `HandleDispatch` orphans an in-flight deployment (H-4). +8. **gRPC data / projected path doesn't scale.** One stream command per cohort item vs a 128 cmd/s origin limit (R-2); + 32-changes-per-tick partition scan (R-3); per-value full scan of live items under `Lock` (U-10); quadratic projected-node + eviction (U-12); auth walk 3–4× per frame (R-12); handle tables copied per frame (R-13). +9. **Hot work on the deploy path.** Every scripted-alarm predicate recompiled serially under the engine gate per deploy (K-3); + every driver re-subscribed per apply (R-11); artifact data projection parsed 3–7× (R-14); O(nodes × items) tombstone sweep (U-5). + +## Ranked top findings + +### Critical / High +| # | ID | Finding | Where | +|---|---|---|---| +| 1 | K-1 | Script sandbox bypass → arbitrary process start / file read from a script | `Core.Scripting/ForbiddenTypeAnalyzer.cs:43-152` | +| 2 | U-1 | ACL grants enforced on subscription revalidation with `Security:Acl:Enabled=false`; anon/ungranted subs stood down every 60 s + every deploy | `OpcUaServer` revalidation (regression `8ad03e9c5`) | +| 3 | A-1 | `/fleet/diagnostics` `?node=` → `ActorSelection` to arbitrary host by any signed-in user | `AdminUI` fleet diagnostics | +| 4 | G-16/K-2 | Historian outage > ~6.5 min dead-letters queued alarm events | `Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs:28-35` + 3 writers | +| 5 | S-1 | Modbus RTU-over-TCP cancelled read desyncs the socket; later reads return another request's data at Good | `Driver.Modbus` RTU-over-TCP transport | +| 6 | P-1 | TwinCAT online change/download: stale symbol offsets → garbage Good reads, misdirected writes | `AdsTwinCATClient.cs:52-72,376`; `TwinCATDriver.cs:1415,1987` | +| 7 | R-1 | Direct-mode boot with a `Failed` newest node row starts an empty node | `DriverHostActor.cs:1463-1506` | +| 8 | U-2 | Scripted-alarm Enabled/AlarmType/Name edits never diffed — enabling an alarm never materialises it | planner / `AddressSpaceApplier` | +| 9 | U-3 | Line re-parented to another Area invisible to the plan; with ACLs on everything under it is denied | planner | +| 10 | C-1/R-5 | VirtualTag name with `/` or edge whitespace passes gate, throws on every node's apply and crashes `VirtualTagHostActor` | `V3NodeIds.cs:104-119`, `VirtualTagHostActor.cs:193,294,400` | +| 11 | C-2 | In-use script deletable; gate has no script-existence rule for VirtualTags/ScriptedAlarms — alarm silently dropped on a green deploy | `DraftValidator`, script delete | +| 12 | K-3 | Every deploy recompiles every scripted-alarm predicate serially under the engine gate (20–40 ms each) | `ScriptedAlarmEngine.LoadAsync` | +| 13 | H-1 | Left/downed node exits as a clean service stop, so `sc.exe failure` never restarts it (needs Windows confirmation) | Host shutdown path | +| 14 | R-2 | Projected cohort > ~130 items can never re-open (1 cmd/item vs 128 cmd/s limit) | `ProjectedDataAccess.cs:1625-1660` | +| 15 | R-3 | Quiet stream on a busy node resets forever (32 partition changes/tick cap) | `DataSubscriptionSession.cs:863-890` | +| 16 | P-2 | AbCip: device dying mid-run stalls the whole multi-device batch | `AbCipDriver.cs:912-925,1069-1081,1854-1872` | +| 17 | P-3 | TwinCAT serial reads, no per-device fail-fast | `TwinCATDriver.cs:461-523` | +| 18 | P-4 | TwinCAT probe tick replays every native registration against an offline PLC under `ConnectGate` | `TwinCATDriver.cs:1404,1765-1879` | +| 19 | P-5 | AbLegacy: one `Long` tag on a MicroLogix faults the whole driver at init | `AbLegacyDriver.cs:253-265` | +| 20 | S-2 | Modbus deadband baseline survives re-subscribe → nodes after rebuild stuck `BadWaitingForInitialData` | `ModbusDriver.cs:83,423-453` | + +### Medium highlights +- **U-4** overlapping failed writes leave the first rejected value at Good · **U-6** `HistoryReadEvents` no page cap · **U-10/U-12** projected publish/eviction scans under `Lock` · **U-11** projected anchor removal leaves a dead monitored node. +- **R-4** clean surgical apply clears degraded flag · **R-6** removed input's dependents keep computing · **R-7** full cohort channel tears down siblings · **R-8/R-9/R-10** connection-wide reactions to per-call/per-source events · **R-11…R-14** apply-path costs. +- **C-3** ZTag/SAPID uniqueness unenforced (`ExternalIdReservation` never written) · **C-4** invalid `DisplayNameOverride` drops the UNS variable · **C-5** two historized tags → same historian tagname. +- **A-2** roles frozen at sign-in · **A-3** duplicate Area/Line/Equipment name → error boundary · **A-4** Galaxy ack identity save blanks the password · **A-5** data-connections page loads whole fleet per circuit. +- **H-2** `AuditWriterActor` drops batch on transient DB failure · **H-3** RestartDriver double-dispatch on audit failure + mailbox held across DB I/O. +- **K-4** timed shelve expiring during evaluation is silent · **K-5** frame writer exceeds the 4 MiB cap, killing the worker · **K-6** resilience timeout invisible to breaker. +- **G-1** Galaxy secured-write routing dead in v3 · **G-7** FasterLog outbox truncates an unindexed entry · **G-8** Gateway alarm writer `PermanentFail` on transient · **G-10/G-11** OpcUaClient recovery O(refs×items) and orphaned subscription · **G-19** dead gateway connection never faults. +- **M-1** Sparkplug rebirth storm · **M-2** one bad filter darkens the driver · **M-3** `-spbhost` client-id collision · **M-4** MTConnect intra-chunk fault latch · **M-5** MTConnect subscription leak per reconnect · **M-6** primary-host never re-claimed. +- **P-6…P-11** FOCAS health/session set · **P-12** TwinCAT refusal mapping · **P-13** AbCip BOOL-array count · **P-14/P-15** AbLegacy bit arrays + whole-word Bit write · **P-16/P-17** AbCip log storm, ALMD ack target · **P-18/P-19** coalescing / per-poll cost. +- **S-3/S-4** Client.Shared failover · **S-5** S7 bad-value write = comms fault · **S-6** Sql key compare · **S-7** Sql read-only guard bypass · **S-8** DL205 octal fallback · **S-9** Calculation uncoalesced unbounded queue. + +## Verification gates the fixes will need +- **Windows box** (H-1 SCM restart semantics) — `windev` is OK; the wonder boxes are on hold (no psbridge/winrm). +- **ab_server / bench hardware** (P-13 BOOL-array, P-17 ALMD ack target) — ties to #592. +- **TwinCAT TCBSD VM** (P-1 online change, P-3/P-4) — `10.100.0.128`. +- **Real provider execution** (S-7 MySQL/Postgres quoting) — docker Sql fixtures on `10.100.0.35`. +- **docker-dev** live gates for U-1, U-2, U-3, R-1, C-1, A-1. + +Fix plan: `docs/superpowers/plans/2026-12-02-review-remediation.md`. Tracked as Gitea issues #971–#1002 (issue map in the plan). diff --git a/docs/reviews/2026-12-02/01-runtime.md b/docs/reviews/2026-12-02/01-runtime.md new file mode 100644 index 000000000..4ac7a1762 --- /dev/null +++ b/docs/reviews/2026-12-02/01-runtime.md @@ -0,0 +1,645 @@ +# Review 01 — Runtime (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/`) + +- **Slice:** `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/` (~44k lines): driver host / instance actors, value fan-out, deploy apply, + OPC UA publish actor, scripted alarms host, virtual tags + dependency mux, historian recorder, redundancy, gRPC data + (`DataConnections/`), health, telemetry. +- **Commit:** `708a4889c` (master). Read-only review; no source was changed. +- **Method:** read by one reviewer plus four scoped sub-reviews; every finding from a sub-review was then re-checked against + the code by the lead reviewer unless its **Verification** line says otherwise. +- **Nothing was built or executed.** Every finding is from reading code and its callers. Cost figures are estimates derived + from the code (limits, loop bounds), not measurements. Line numbers are for `708a4889c`. +- **Prior review:** `docs/reviews/2026-10-21/02-runtime-cluster.md` items L1–L4, U1–U5, P1–P7, H1–H5 were checked where they + were encountered; L2, L3, H1, H2, H3, H5, P2 (writes), P3, P4, P7 are remediated. Only R-14 touches a prior item (P5), and + says so. Tracked issues #969, #959, #932, #924, #915, #755, #616, #614, #592 are not re-reported. + +### Coverage and its limits + +| Area | Depth | +|---|---| +| `Drivers/DriverInstanceActor.cs` | read in full | +| `Drivers/DriverHostActor.cs` (+ `.ConditionSignals`), `DeploymentArtifact*.cs`, `NativeAlarmProjector`, small `Drivers/*`, `Communication/*`, `Deployment/*` | read in full by a sub-review; findings re-verified | +| `OpcUa/OpcUaPublishActor.cs`, `ScriptedAlarms/*`, `VirtualTags/*`, `Scripting/*` | read in full by a sub-review; findings re-verified (`DependencyMuxActor` also read by the lead) | +| `Historian/*`, `Redundancy/*`, `Health/*`, `Telemetry/*` | read in full | +| `DataConnections/` serving side (session, partitions, hub, publisher, local services, write path, history sessions) | read in full by a sub-review; findings re-verified | +| `DataConnections/` projected side: `ProjectedDataAccess`, `GrpcDataConnection*`, `ActorProjectedValuePublisher`, `DataConnectionDeploymentRuntime`, `GrpcDataDriverAdapter`, `ConfiguredProjectedInterestOwner` | read in full by a sub-review; findings re-verified | +| **Not reviewed line by line:** `RemoteNamespaceResolver`, `ProjectedCatalogCache`, `ProjectedHistoryAccess`, `ProjectedConditionAccess` (+ `.Methods`; `.Runner` only skimmed), `ProjectedMappingDeploymentRuntime`, `ProjectedNamespaceApplier`, `ProjectedCoalescingMailbox`, `ProjectedAdapterRouteSource`, `DataConnectionManager`, `FederatedBrowseService`, `MetadataAuthorityLease`, `CatalogActivation`, `ConditionKeys`, `ConditionPlacements`, the two `*Diagnostics` files, `DataConnectionWarmRoleView`, `LocalDataConnection`, `ClusterEndpointSelector`, `UnknownOperationDrops`, `ServiceCollectionExtensions.cs` | "no finding" here means **not reviewed**, not clean. The first three deserve a second pass. | + +### Finding index + +| ID | Sev | Cat | Title | +|---|---|---|---| +| R-1 | High | bug | Direct-mode boot with a `Failed` newest node row starts an empty node | +| R-2 | High | bug | Projected cohort sends one command per item; origin kills the stream at 128 commands/s | +| R-3 | High | bug/perf | Subscription session scans ≤ 32 partition changes per tick; a quiet stream on a busy node resets forever | +| R-4 | Medium | bug | A clean surgical deploy after a degraded rebuild clears the degraded flag without repairing | +| R-5 | Medium | bug | One VirtualTag with an illegal name crashes `VirtualTagHostActor`; nothing re-applies | +| R-6 | Medium | bug | Dependents of a removed/renamed input keep computing from its last Good value | +| R-7 | Medium | bug | Full cohort event channel turns one item removal into teardown of every sibling demand | +| R-8 | Medium | bug | `QueryAsync` treats a per-call failure/cancel as endpoint failure → connection-wide backoff | +| R-9 | Medium | bug | One source's invalidation (incl. lock contention) resets every stream on its partition | +| R-10 | Medium | bug | Publisher capacity refusal is handled as evidence invalidation and retires the route | +| R-11 | Medium | perf | Every apply re-subscribes every kept driver's whole data set | +| R-12 | Medium | perf | Per delivered frame: full authorization walk 3–4×, with allocations, once under the session lock | +| R-13 | Medium | perf | `RemoteSubscription` copies whole handle tables per frame/ack; O(N²) on open | +| R-14 | Medium | perf | Apply-time artifact work repeated: data projection ×3–7, pinned-thread parse + hashes | +| R-15 | Low | bug | Revision advances before the last throwing steps of an apply; same-revision re-dispatch acks clean | +| R-16 | Low | bug | `StopChild` leaves comms-latch state and its audit timer; health ledger can be resurrected | +| R-17 | Low | bug/perf | VirtualTag `source-binding-retry` replays the whole apply every 250 ms | +| R-18 | Low | bug | Deferred "known" marks discarded for conditions whose live mark landed | +| R-19 | Low | perf | `VirtualTagActor` stash is uncoalesced; array results never dedup | +| R-20 | Low | bug | `OpcUaPublishActor` restart resets `_lastApplied` while the sink keeps the address space (latent) | +| R-21 | Low | perf | `WriteOperationRegistry.Prune` copies the whole table under the lock on every claim | +| R-22 | Low | bug | History remainder bytes leak when a session is cleared mid-request | +| R-23 | Low | bug | Command barrier can be armed after its only release | +| R-24 | Low | bug | Condition stream teardown can mask its real failure | +| R-25 | Low | perf | Smaller costs: publisher per-driver scans, hub fed with no subscribers, recorder drain cadence | + +--- + +## High + +### R-1 — Direct-mode boot with a `Failed` newest node row starts an empty node + +- **Severity:** High · **Category:** bug · **Confidence:** High +- **Location:** `Drivers/DriverHostActor.cs:1463-1506` (`Bootstrap`); Failed-row writers at `:3144`, `:3260`, `:3330`. +- **Verification:** re-verified by reading. +- **Description:** `Bootstrap()` reads only the newest `NodeDeploymentState` row for the node + (`OrderByDescending(s => s.StartedAtUtc)…FirstOrDefault()`) and switches on its status. `Applied` calls + `RestoreApplied`; `Applying` replays. The `Failed`/default arm is: + ```csharp + _log.Info("DriverHost {Node}: prior deployment {Id} failed; entering Steady at last known rev", …); + BecomeSteady(); + ``` + There is no "last known rev" at that point: `_currentRevision` is null, nothing is restored, and + `TryBootFromCache()` is not consulted. The same applies to an orphan `Applying` row whose deployment row is gone + (`revision is null` → `BecomeSteady()`). +- **Failure scenario:** node applies deployment A (row Applied, serving). Deployment B fails on this node — unreadable + artifact (`:3260`), an exception in the apply (`:3330`), a FetchAndCache misconfiguration (`:3144`). The log says + "Staying on revision A and continuing to serve it", which is true in memory. Nobody redeploys. The service later + restarts (patch reboot, crash). Newest row is B/Failed → Steady with zero drivers and an empty address space, logged at + Info. Nothing heals it: the coordinator re-dispatches only its own in-flight deployments. FetchAndCache nodes are + unaffected (they boot from the LocalDb pointer). +- **Suggested fix:** in the `Failed`/default arm (and the `revision is null` arm), query the newest row with + `Status == Applied` for this node, set `_currentRevision` from it and call `RestoreApplied`; if there is none, fall + back to `TryBootFromCache()`, then Steady-with-no-revision. Log at Warning. +- **Test to add:** seed A (Applied, older `StartedAtUtc`) and B (Failed, newer); start the host; assert children are + spawned from A and `RebuildAddressSpace` carries A's blob. Second case: only a Failed row + a populated cache. +- **Existing tests:** would not catch it — no Runtime test seeds a `Failed` node row. + +### R-2 — Projected cohort sends one command per item; the origin kills the stream at 128 commands/s + +- **Severity:** High · **Category:** bug · **Confidence:** High on the mechanism, Medium on the exact threshold (not run) +- **Location:** consumer `DataConnections/ProjectedDataAccess.cs:1625-1637` (initial open loop), `:1640-1660` (`AddEvent`), + renewal Remove+Add per item; origin `DataConnections/DataSubscriptionSession.cs:224` and `:235`; + `DataConnections/SubscriptionTransportCapacity.cs:59,69-88`; limits at + `Host/Configuration/DataConnectionRegistration.cs:199-201`. +- **Verification:** re-verified by reading both sides and the production limit wiring. +- **Description:** the cohort always sends exactly one item per command, back to back, never waiting for an ack: + ```csharp + foreach (var demand in initial) { … + DataSubscriptionCommand command = !opened ? new OpenSubscription(…, [Item(registration)], …) + : new AddSubscriptionItems(…, [Item(registration)]); + await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true; } + ``` + The origin admits at most `maxCommandsPerSecond = 128` commands per principal in a fixed 1 s window (the default is + not overridden in `LocalDataRuntimeComposition.cs:40`) and stops the session on the first excess: + `if (!_capacity.TryAdmitCommand(_context.PrincipalId)) { Stop(); throw … "Principal command rate exceeded." }`. + The same burst also hits `_ackByCommand.Count >= _limits.MaxCommands` (128) on the origin, and nothing reads the + cohort's `_events` during the open loop (see R-7). +- **Failure scenario:** a cohort (connection + serving + publishing interval) holds 300 projected monitored items and + its stream drops (origin restart, failover, a designed stream reset, credential rotation). The next attempt sends 300 + commands in milliseconds; the origin stops the session at command 129; the attempt ends, backs off 100 ms–5 s and + repeats identically. The cohort never re-establishes; values go stale/Bad and the retry loop keeps hammering the + origin. `MaxMonitoredItems` defaults to 10 000, so the configured ceiling is far above what the protocol use allows. + Same root, other triggers: one `CreateMonitoredItems` with > 128 projected items; synchronized lease renewals + (2 commands per item). +- **Suggested fix:** batch items per command — the protocol already takes item lists up to `MaxBatchItems` — for open, + add, remove and the renewal re-add; window outstanding commands to `min(local pending limit, origin limit)`; consume + `_events` while opening. +- **Test to add:** wire test with a real `SubscriptionTransportCapacity` (default rate) and a cohort of 300 items: + assert the stream opens and every item reaches its first value; repeat after a forced stream drop. +- **Existing tests:** would not catch it — no Runtime/wire test puts more than a handful of value items in one cohort; + the only rate test (`GrpcDataDeliveryFairnessTests`, `maxCommandsPerSecond: 2`) is origin-side. + +### R-3 — A session scans at most 32 partition changes per tick; a quiet stream on a busy node resets forever + +- **Severity:** High · **Category:** bug/perf · **Confidence:** High on the code path, Medium on field frequency (not run) +- **Location:** `DataConnections/DataSubscriptionSession.cs:863-890` (esp. `:879`), `:431-432` (100 ms tick), `:808-812`; + `DataConnections/SourceInterestLease.cs:65-84`; `DataConnections/SamplePartition.cs:447-454`, `:601-622`; + defaults `DataConnections/DataResourceBudget.cs:8,16`. +- **Verification:** re-verified by reading. +- **Description:** each tick takes at most 32 interest groups and calls `group.Lease.TryReadChanges(32, …)` once per + group. `ReadInterestChanges` counts `scanned++` for **every** change recorded in the partition, whether or not the + key is one of the lease's tickets, and the 32 is shared across all of the lease's partition cursors. A tick is queued + only by the 100 ms timer or by a dequeued delivery — there is no re-queue when the budget ran out with changes still + unread. `RecordChange` runs for every applied publish (`SamplePartition.cs:432`) and keeps only + `MaxSnapshotCatchUpItems` (default 1024) entries per partition; a cursor that falls off the end fails + `_changeIndex.TryGetValue(position + 1)` and the session is closed with `"Source change history expired."`. + With DataConnections enabled every driver value tag feeds the hub regardless of gRPC demand + (`DriverHostActor.cs:4133` registers a shape per value tag; `DriverInstanceActor.cs:2049/2068` → `PublishSource`). +- **Failure scenario:** node publishing 2 000 value changes/s (4 partitions, ~500 each). A consumer subscribes to 20 + slow-changing items. Its scan capacity is ≈ 32 × (10 timer ticks + delivered frames per second) ≈ a few hundred + changes/s against 2 000 produced. The cursors lose ground continuously, the 1024-entry history rolls off in seconds, + and the stream resets; the consumer re-opens, snapshots, and it repeats. Raising `MaxSnapshotCatchUpItems` only delays + it because the lag is unbounded. +- **Suggested fix:** drain each group until `position == watermark` under a per-tick work budget and `QueueTick()` when + work remains; or keep a per-source dirty version so a lease checks only its own tickets instead of walking the + partition-wide change list. +- **Test to add:** session with a few interests on sources A; publish ≥ 5 000 changes to unrelated sources B in the + same partitions over a few seconds on a fake clock; assert no reset and that A's later change is still delivered. +- **Existing tests:** unlikely to catch it — fixtures use tiny source counts and no off-interest traffic. + +--- + +## Medium + +### R-4 — A clean surgical deploy after a degraded rebuild clears the degraded flag without repairing anything + +- **Severity:** Medium · **Category:** bug · **Confidence:** High +- **Location:** `OpcUa/OpcUaPublishActor.cs:1554-1576` (empty-plan repair) vs `:1581-1627`. +- **Verification:** re-verified by reading. +- **Description:** `_lastAppliedDegraded` is honoured only on the empty-plan path (which re-ensures the full + composition). On a non-empty plan the code runs the delta (`MaterialiseNodes(plan, composition, fullComposition: + outcome.RebuildCalled)`) and then overwrites the flag unconditionally: + ```csharp + if (outcome.RebuildCalled || failedNodes == 0) { + _lastApplied = composition; … + _lastAppliedDegraded = outcome.RebuildFailed || failedNodes > 0; + ``` +- **Failure scenario:** deploy A triggers a rebuild and one `EnsureVariable` faults → degraded, `_lastApplied` advances + (by design), flag = true. The operator then deploys B, an unrelated one-tag add: surgical plan, clean delta → flag = + false and `RebuildCompleted(Degraded: false)` seals green. The node A failed to place is inside `_lastApplied`, never + appears in a diff again, and a re-deploy of B is an empty plan that short-circuits clean. The address space is partial + and reported clean indefinitely — the exact outcome the CLAUDE.md "degraded apply" invariant exists to prevent. +- **Suggested fix:** when `_lastAppliedDegraded` is set, run the non-rebuild apply with `fullComposition: true` and + clear the flag only when that full pass returns 0 (otherwise keep it set and report degraded). +- **Test to add:** degraded rebuild of composition A (sink throws for node X), then composition B = A + one raw tag with + a healthy sink; assert X is ensured again, or the reply stays degraded. +- **Existing tests:** would not catch it — `Redeploying_the_same_composition_after_a_degraded_REBUILD_repairs_it…` + covers the identical-composition case only. + +### R-5 — One VirtualTag with an illegal name crashes `VirtualTagHostActor` on every apply; nothing re-applies + +- **Severity:** Medium · **Category:** bug · **Confidence:** High +- **Location:** `VirtualTags/VirtualTagHostActor.cs:193-197`, `:294`, `:400-403` (`NodeIdFor` → `V3NodeIds.Uns`); + missing gate in `AdminUI/Uns/UnsTreeService.cs:1534-1552` (`CheckVirtualTagRules`) and + `Configuration/Validation/DraftValidator.cs:689-700`, `:853-861`. +- **Verification:** re-verified by reading (throw path, absence of a name rule, absence of a restart re-apply). +- **Description:** `NodeIdFor(p)` calls `V3NodeIds.Uns(p.EquipmentId, p.Name)`, which throws `ArgumentException` for a + segment containing `/` or leading/trailing whitespace. `OnApply` calls it unguarded. A VirtualTag `Name` is not + charset-checked anywhere: `CheckVirtualTagRules` checks only script and triggers; the deploy gate's + `RawNameInvalid` covers raw names and `UnsSegmentInvalid` covers Area/Line/Equipment only. The host has no + `PostRestart`, and `DriverHostActor` has a re-apply hook for the scripted-alarm host + (`HandleScriptedAlarmHostRestarted`) but none for the VirtualTag host. +- **Failure scenario:** an operator saves a VirtualTag named `"Temp "` or `"Flow/Rate"` and deploys. `OnApply` throws + at `:196`; default supervision restarts the host; `PreRestart` stops every child; the new incarnation is empty and + nothing re-sends `ApplyVirtualTags`. Every VirtualTag on the node stops evaluating. On a surgical deploy their OPC UA + nodes keep the last value at the last (Good) status. Every later deploy carrying that row repeats it. +- **Suggested fix:** (1) compute NodeIds per plan in a try/catch before any child is stopped; skip and log the bad + plan; (2) add a `VirtualTagHostRestarted` → re-apply path mirroring the scripted-alarm one; (3) add a deploy-gate and + authoring rule validating VirtualTag and ScriptedAlarm names with `RawPaths.ValidateSegment`. +- **Test to add:** apply `[good, bad("A/B")]`; assert the good child still bridges results and the host did not + restart. `DraftValidator` test for the new rule. +- **Existing tests:** would not catch it. + +### R-6 — Dependents of a removed or renamed input keep computing from its last Good value + +- **Severity:** Medium · **Category:** bug (wrong quality) · **Confidence:** High for VirtualTag→VirtualTag, Medium for raw tags +- **Location:** `VirtualTags/DependencyMuxActor.cs` `OnVirtualTagOutputsRemoved` and `OnSourceRemoved` (contrast + `OnProjectedReferenceRetired`, which does fan a Bad); `VirtualTags/VirtualTagActor.cs:135,333,358,382-403`; + `VirtualTags/VirtualTagHostActor.cs:321`; `Drivers/DriverHostActor.cs:4769`; + `ScriptedAlarms/DependencyMuxTagUpstreamSource.cs` (`RetainOnly`). +- **Verification:** re-verified by reading the mux and the actor's `_dependencies` use. +- **Description:** removal only `Forget`s the mux entry, which protects future replays. Nothing is sent to current + subscribers. A surviving `VirtualTagActor` (plan unchanged, so not respawned) keeps `_dependencies[removedKey]` and + the scripted-alarm upstream keeps its cached value while it is still referenced. +- **Failure scenario:** VirtualTag B reads `ctx.GetTag("…/A")` by absolute literal (no deploy gate rejects an + unresolved absolute literal; a raw rename only warns). The operator deletes or renames A. B keeps publishing Good, + computed from A's final value, on every timer tick or other-input change; a scripted alarm reading A is frozen on its + last input. After a process restart the same configuration behaves differently (the input never arrives, so B never + evaluates). Disabling A is handled (`BadOutOfService` is routed); removing it is not. This contradicts the R3-02 + quality contract ("a value consumer never reports a quality better than its source's"). +- **Suggested fix:** in `OnVirtualTagOutputsRemoved` and `OnSourceRemoved`, send each `entry.Subscribers` a batch + carrying null + a Bad status (`BadNodeIdUnknown` or `BadNoCommunication`) before forgetting; do the same for raw refs + dropped from the driver ref index on apply. +- **Test to add:** A→B chain; apply without A; assert B publishes Bad and the alarm upstream `ReadTag` goes Bad. Replay + the identical value afterwards to prove the (value, status) dedup does not swallow the transition. +- **Existing tests:** would not catch it — the existing removal test asserts only the key release. + +### R-7 — A full cohort event channel turns one item removal into teardown of every sibling demand + +- **Severity:** Medium · **Category:** bug · **Confidence:** Medium (needs a frame backlog) +- **Location:** `DataConnections/ProjectedDataAccess.cs:1279-1285`, `:1297-1313` (pump), `:1351-1370` (`RunAsync` + finally); single acquire site `OpcUaServer/OtOpcUaNodeManager.cs:4658`. +- **Verification:** re-verified by reading. +- **Description:** `_events` is one bounded channel (`Math.Clamp(MaxDemands * 2, 4, 128)`) shared by value frames (the + pump uses `WriteAsync`, so backpressure deliberately keeps it full under load) and by control events: + ```csharp + internal bool Add(Demand demand) => _events.Writer.TryWrite(new AddEvent(demand)); + internal void Remove(Demand demand) { if (!_events.Writer.TryWrite(new RemoveEvent(demand))) Stop(); } + ``` + `Stop()` ends `RunAsync`, whose finally disposes **every** demand the cohort owns. +- **Failure scenario:** the channel is full (burst/snapshot backlog, or the initial-open loop of a large cohort, during + which nothing reads `_events`). A client deletes one monitored item → `Demand.Dispose` → `Remove` → `TryWrite` fails + → `Stop()` → all sibling demands disposed. A projected monitored item acquires its demand once at creation and has no + re-acquire path, so the siblings are dead until the client recreates them. Related: `Add` fails the same way + (`StartSubscription` returns false) and renewal ticks are dropped on a failed `TryWrite`, so leases can lapse under + backlog. +- **Suggested fix:** give control events their own unbounded or demand-bounded channel (or a per-demand flag set the + loop scans). Never tear the cohort down on a failed Remove enqueue — the next attempt already reconciles disposed + demands via `ReleaseDemand`. +- **Test to add:** fill `_events` with frames (blocked consumer hook), dispose one demand, assert the other demands + stay live and keep delivering. +- **Existing tests:** unlikely to catch it. + +### R-8 — `QueryAsync` treats caller cancellation and per-call faults as endpoint failure → connection-wide backoff + +- **Severity:** Medium · **Category:** bug · **Confidence:** High +- **Location:** `DataConnections/GrpcDataConnection.cs:331-361`, `:158-169`; gated paths at `:469`, `:610`, + `GrpcDataConnection.History.cs:85`. +- **Verification:** re-verified by reading. +- **Description:** after a successful `SelectAsync` (which calls `ProbeSucceeded()`), a failure of the call itself is + caught by the same handler as a discovery failure: + `catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or + HttpRequestException) { failure = ex; RecordFailure(ex); }` and after the loop `ProbeFailed(); throw new + InvalidOperationException("No ready authenticated data endpoint.", failure);`. A caller cancel or deadline surfaces + as `RpcException(Cancelled/DeadlineExceeded)` and lands there. The history and condition-method paths already filter + this; the unary path (Read, GetMetadata, Browse, GetCapabilities) does not. +- **Failure scenario:** single-endpoint connection; one projected read is cancelled by its OPC UA client or times out. + `ProbeFailed()` arms `_nextProbeTimestamp` (~250 ms ±20 %). During that window every other operation on the + connection is refused unsent: subscribe throws "Data endpoint discovery is backing off" (costing the cohort an + attempt), writes are rejected before dispatch, fresh history reads return `BadNoCommunication`; diagnostics flip to + `backoff`; and the caller sees `InvalidOperationException` instead of a cancellation. Any per-request fault + (`InvalidArgument`, `ResourceExhausted`) does the same, so a client polling one bad node id degrades the whole + connection on every poll. +- **Suggested fix:** rethrow as `OperationCanceledException` when `ct.IsCancellationRequested`; call `ProbeFailed()` + only when `SelectAsync` itself failed for every endpoint, not when the post-select call failed. +- **Test to add:** cancel one unary read after selection; assert a concurrent subscribe/write on the same connection is + not refused and the caller observes `OperationCanceledException`. +- **Existing tests:** would not catch it — cancel tests exist for the history path only. + +### R-9 — Any single source's invalidation resets every stream on its partition; lock contention is a trigger + +- **Severity:** Medium · **Category:** bug (robustness) · **Confidence:** Medium (the quiet fence is deliberate; the blast + radius and trigger set may not be) +- **Location:** `DataConnections/SamplePartition.cs:137-156` (`Signal`), `:308`, `:317`, `:334`; + `DataConnections/PartitionControlSignal.cs`; `DataConnections/SourceInterestLease.cs:55-62`; + `DataConnections/SourceSamplePublisher.cs:328-334`, `:464-481`. +- **Verification:** re-verified by reading. +- **Description:** `Signal()` always runs `Control.BeginQuiet(); … Control.EndQuiet();` on the **partition-wide** + signal, bumping its generation. Every interest lease checks + `!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)` and reports reset, and the session closes with + `"Source change history expired."`. `Signal` is reached from ordinary contention: + `TryStatus`: `if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; }`; `TryPublish`: + `if (!Monitor.TryEnter(slot.Gate)) { _hub.Invalidate(ticket, "source serialization contention"); … }`; plus every + other `_hub.Invalidate` reason (ingress capacity, commit rejected, status overtook an in-flight sample). +- **Failure scenario:** a device with a few hundred tags goes offline. The driver emits a burst of Bad statuses; each + schedules the partition drain, which holds `_gate`. One `TryEnter` miss calls `Signal`. Every session with a cursor + on that partition — with 4 partitions, effectively every multi-item stream on the node, including ones not subscribed + to that driver — resets and re-snapshots. The tag whose status lost the race ends `Invalidated` rather than carrying + its Bad status. Combined with R-2 on the consumer side, a reset can become a permanent outage for a large cohort. +- **Suggested fix:** scope the quiet fence per source (compare `gate.Invalidated` / `InvalidationVersion` for the + lease's own tickets, as the read path already does) and keep the partition-wide bump for `InvalidatePartition` and + dispose only. Independently, queue a contended status instead of invalidating. +- **Test to add:** two sessions on disjoint sources in one partition; invalidate a source of the first; assert the + second is not reset. +- **Existing tests:** contention-driven cross-source resets are probably not covered. + +### R-10 — Publisher capacity refusal is handled as evidence invalidation and retires the source route + +- **Severity:** Medium · **Category:** bug (robustness) · **Confidence:** Medium (may be a deliberate fail-closed choice) +- **Location:** `DataConnections/ActorProjectedValuePublisher.cs:175-183`, `:193-252` (esp. `:214`, `:223`, `:252`); + `DataConnections/ProjectedDataAccess.cs:1990`; default `Host/Configuration/DataConnectionOptions.cs:26` + (`MaxPendingBytes` = 1 MiB). +- **Verification:** `TryPublish`/`Invalidate` re-verified by reading; the downstream effect on the source state was not + fully traced. +- **Description:** `TryPublish` refuses when `charge > _maximumBytes - _pendingBytes` and goes through the same + `Refused()` as an invalid proof: `Invalidate(captured)` → `update.SourceProof.Invalidate(); Retire(update.Route)` + (unless the evidence is droppable and the route current). The caller then runs `source.Invalidate()` when the proof + cannot be dropped. +- **Failure scenario:** the node-manager lock is held for a few hundred ms (a deploy apply, a large + `CreateMonitoredItems` — exactly when projected subscriptions start) while samples arrive at several thousand per + second. At ~800 B charged per sample the 1 MiB pending cap is ~1 300 samples. The next sample is refused for + capacity, its healthy proof is invalidated and the route retired; deltas are rejected until the next freshness + snapshot (50 ms–5 s); it repeats for each refused sample while the stall lasts. Clients see gaps caused purely by + local backpressure. +- **Suggested fix:** distinguish "no capacity" from "invalid evidence" in `TryPublish`: on capacity, coalesce to the + latest value per route (or apply backpressure to the cohort loop) without invalidating the proof or the route. +- **Test to add:** stall the sink, publish past `MaxPendingBytes`, release; assert the route was not retired and the + latest value is delivered without a re-snapshot. +- **Existing tests:** capacity refusal is probably tested as a refusal; this consequence is not. + +### R-11 — Every apply re-subscribes every kept driver's whole data set, even when its set is unchanged + +- **Severity:** Medium · **Category:** perf · **Confidence:** High on the behaviour (documented), cost not measured +- **Location:** `Drivers/DriverHostActor.cs:4202-4206` → `SendDesiredSubscriptions` (`:4262-4269`); receiver + `Drivers/DriverInstanceActor.cs:982-987`, `:1947-1951`, `:1995-2002`. +- **Verification:** re-verified by reading both ends. +- **Description:** the bulk push Tells `SetDesiredSubscriptions` to every child on every apply with no equality check. + The Connected handler unconditionally does `Self.Tell(new Subscribe(_desiredRefs, _desiredInterval))`, and + `HandleSubscribeAsync` awaits `UnsubscribeAsync()` and then a fresh `SubscribeAsync` of the full set inside a + `ReceiveAsync` (mailbox suspended for both round-trips, up to 5 s + 10 s). This is documented behaviour + (`.claude/rules/drivers.md` #662; the forced initial push is what seeds rebuilt nodes and new UNS mirrors), so it is + reported as a cost, not a defect. +- **Cost:** an ACL-only, script-only or single-reference deploy tears down and rebuilds every driver subscription on + every node: OpcUaClient monitored-item delete/create upstream, Galaxy unadvise/advise of all items through + mxaccessgw, a forced full re-read on every poll driver, plus a data gap per driver. It scales with total tag count, + not the delta, which undercuts the surgical-deploy goal on the device side. +- **Suggested fix:** skip the push for a driver when its `DesiredSubscriptionSet` is sequence-equal to the previous + one, the apply is not a rebuild, and no node was added to that driver's fan-out sets; or seed new UNS mirrors from + the raw node in the sink so the re-subscribe is no longer needed for seeding. +- **Test to add:** non-rebuild deploy that leaves driver X untouched, with a counting `ISubscribable`; assert zero + unsubscribe/subscribe calls on X and that a newly added mirror of X's tag still receives a value. +- **Existing tests:** currently assert that the re-subscribe happens. + +### R-12 — Each delivered value frame runs the full authorization walk 3–4 times, once under the session lock + +- **Severity:** Medium · **Category:** perf · **Confidence:** Medium on magnitude +- **Location:** `DataConnections/DataSubscriptionSession.cs:1083-1100`, `:1240-1246`, `:1302-1308`; + `DataConnections/LocalDataServices.cs:120-142`, `:187-192`; `DataConnections/LocalExportCatalog.cs:139-149`, + `:185-195`, `:209-219`; `DataConnections/LocalCatalogCoordinator.cs:80-110`. +- **Verification:** **not independently re-read by the lead**; reported from the sub-review's full read. +- **Description:** `Gate()` is called before `Take`, after it, and again inside `Commit()` under `lock (_gate)`; the + sink path adds one more. Each call runs `item.View.CanPublish()`: `_catalog()` → `Current` (invokes `_serving()` + twice, each allocating a `ServingIdentity`), `TryResolve` (allocates two records per call via `with`, even when + equal), `AllowsExport` → `IsAncestor` (one `TryResolve` per ancestor level per export rule), then + `_policy.AuthorizeLocal`. +- **Cost:** for a tag five levels under its export root, an estimated 60–100 allocations and several µs per delivered + sample; at 10k samples/s roughly a million allocations/s, and a longer `_gate` hold that the worker tick contends on + (which also reduces the scan capacity in R-3). +- **Suggested fix:** make `TryResolve` allocation-free; memoise the per-(principal, node, operation) export verdict in + the immutable catalog; cache the `CanPublish` verdict keyed on (catalog reference, authority/policy generation); do + the full gate once outside the lock and keep only cheap identity checks inside `Commit`. +- **Test to add:** allocation-budget test (`GC.GetAllocatedBytesForCurrentThread`) around N deliveries of one item. +- **Existing tests:** no perf harness on this path. + +### R-13 — `RemoteSubscription` copies whole handle tables per frame and per ack; O(N²) on open + +- **Severity:** Medium · **Category:** perf · **Confidence:** High for (a); Medium for (b), unmeasured +- **Location:** (a) `DataConnections/GrpcDataConnection.cs:881-884`, `:943`, `:983`; (b) + `DataConnections/ProjectedDataAccess.cs:829`, `:1816-1857`, `:1899-1937`. +- **Verification:** **not independently re-read by the lead**; reported from the sub-review's full read. +- **Description:** (a) every value frame runs `new Dictionary(_versions)` plus a new `HashSet`; + every ack copies four collections (`_handles`, `_clientHandles`, `_usedHandles`, `_versions`); each frame also calls + `wire.CalculateSize()` (a full re-walk). The copy-then-commit atomicity buys nothing, because any throw in that block + terminates the stream. (b) per sample in the cohort: `Demand.IsValid` 3–4× (each a node lookup, proof check and a + full `_policy.AuthorizeMapped`), `GetSource` under the global `_sync` shared by all cohorts with a + `ToUpperInvariant()` and a `SourceKey` record allocation, `EvidenceFor` (`Where(…).ToArray()` + closure), + `TryPublish([update])` (array + `Distinct()` + `Select`), a deep copy in `CacheLocked`; and after each item ack + `_registrations.Values.Min(…)` — O(N²) across an open. +- **Cost:** at 10k items the versions dictionary is ~280 KB (LOH) reallocated per frame, ~10×/s per stream at a + 100 ms interval. With one ack per item (R-2) an open is ~10k × 4 × ~5k entry copies ≈ 2×10⁸ — seconds of CPU and + gigabytes of garbage per reconnect. +- **Suggested fix:** mutate in place for (a). For (b) cache the `SourceState` on the `Registration` and revalidate on + events (binding swap, catalog invalidation) instead of per sample; pre-uppercase the connection id once; publish per + frame as a batch. +- **Test to add:** allocation budget per frame at N = 5 000 handles; open-time budget for N items. +- **Existing tests:** none for performance. + +### R-14 — Apply-time artifact work is repeated: data projection ×3–7, pinned-thread parse and hashes + +- **Severity:** Medium · **Category:** perf · **Confidence:** High on the repetition; cost estimated +- **Location:** `Drivers/DeploymentArtifact.cs:1019-1026`, `:273-278`, `:580`, `:833-848`; + `Drivers/DeploymentArtifact.DataConnections.cs:71-112`, `:120-206`, `:331-339`; + `Drivers/DriverHostActor.cs:3701-3741`; `OpcUa/OpcUaPublishActor.cs:853-863`, `:917`, `:1832`, `:2327-2334`. +- **Verification:** re-verified by reading (the `InjectScriptSource` per-tag parse was not re-read). +- **Description:** + 1. `ParseDataPlaneAuthority` calls `ParseDataConnections`, `ParseDataExports` and `ParseRemoteNamespaceMappings`; + each calls the un-memoised `ReadDataProjection(nodeId)`, which deserialises Clusters, Nodes, RawFolders, + DriverInstances, Devices, TagGroups, **Tags**, the UNS tables, VirtualTags, ScriptedAlarms and Scripts into + entities, then `ValidateRows` runs `DataConnectionValidator.ValidateDeployed(snapshot)`. The only early-out is + "none of the three properties exist", and `ConfigComposer.cs:99-107` always emits them — so a node with **zero** + data connections still pays three full passes per apply (off-thread in the publish actor's plan task). With + DataConnections enabled, `DriverHostActor.StageCatalog` adds up to four more on the host mailbox. + 2. `OpcUaPublishActor.HandleRebuild` runs on the pinned OPC UA thread: SHA-256 of the whole artifact when a catalog + coordinator exists, and — when `OpcUa:Redundancy:Mode` is `None`/`Warm` — `CheckRedundancyMode` → + `ReadClusterRedundancyMode`, which does `blob.ToArray()` and a full `Open` (inflate + JSON parse) just to read one + cluster field. The artifact is hashed again in `StartRebuild` and `FeedDataPlaneAuthority`. This is a partial + regression of prior item **P5** (the plan itself moved off-thread; these did not). + 3. (Sub-review, not re-read) `InjectScriptSource` runs `JsonNode.Parse(tagConfig)` for every tag whenever the + artifact has any `Scripts` row, only to look for `scriptId`. +- **Cost:** at 50k tags, an estimated 50–100 ms per projection pass → 150–700 ms of avoidable work per deploy and per + bootstrap, part of it on the two actors that carry all value fan-out and write routing; plus one extra full parse and + up to three hashes of a tens-of-MB artifact on the pinned thread per rebuild in Warm/None mode. +- **Suggested fix:** memoise `ReadDataProjection` (including its validation result) per `ParsedDeploymentArtifact` and + short-circuit to an empty projection when all three arrays are empty; do the redundancy-mode check inside the + existing plan `Task.Run` against the already-open `parsed`; hash once off-thread and carry the hex in + `PlanReady`/`PlanFailed`; pre-check `tagConfig.Contains("scriptId", Ordinal)` before parsing. +- **Test to add:** counting seam showing one projection build per `ParsedDeploymentArtifact` across + `ParseDataPlaneAuthority` + `StageCatalog`, and none for an artifact with empty data arrays; assert + `ReadClusterRedundancyMode` is not called on the actor thread. +- **Existing tests:** functional only (`GrpcDataCatalogStagingTests`, `OpcUaPublishActorOffThreadPlanTests`). + +--- + +## Low + +### R-15 — The revision advances before the last throwing steps of an apply; a same-revision re-dispatch acks clean + +- **Severity:** Low (latent) · **Category:** bug · **Confidence:** Medium (no concrete thrower found today) +- **Location:** `Drivers/DriverHostActor.cs:3272-3283`, catch `:3324-3340`, short-circuit `:3086-3099`. +- **Verification:** re-verified by reading. +- **Description:** `_currentRevision = msg.Revision;` is set before `PushDesiredSubscriptionsFromParsed`, the catalog + `Complete` and `AwaitAddressSpaceOutcomeThenAck`. The catch sends a Failed ack but neither restores the previous + revision nor sets `_currentRevisionUnconfirmed`. `ApplyDesiredSubscriptions` clears all routing maps before + repopulating, so a mid-pass throw also leaves value and write routing empty. +- **Failure scenario:** any exception after `:3272` → Failed ack. The operator re-deploys the same configuration (same + `RevisionHash`); `HandleDispatchFromSteady` takes "matches current rev; immediate ACK" and reports a clean Applied + although `RebuildAddressSpace` was never sent for that revision. Combined with R-1, a restart then boots empty. +- **Suggested fix:** capture the previous revision and restore it in the catch, or set + `_currentRevisionUnconfirmed = true` there. +- **Test to add:** make `BeforeSubscriptionApplyForTests` throw; assert a Failed ack, then that re-dispatching the same + revision re-applies instead of acking immediately. +- **Existing tests:** `DriverHostActorUnconfirmedRevisionTests` covers degraded/cache/restore paths, not this one. + +### R-16 — `StopChild` leaves comms-latch state and its audit timer; the health ledger can be resurrected + +- **Severity:** Low · **Category:** bug/leak · **Confidence:** High for the latch, Medium for the ledger +- **Location:** `Drivers/DriverHostActor.cs:4717-4749` (no `_commsLatched.Remove`, no audit-timer cancel) vs `:2143-2153`, + `:2204-2226`; `Drivers/ChildHealthLedger.cs:33-45`. +- **Verification:** latch re-verified by reading; ledger not re-read. +- **Description / scenario:** a driver removed or disabled while comms-lost keeps its full RawPath set in + `_commsLatched` forever. Removed within 30 s of a reconnect, the audit still fires: a false Warning ("N ref(s) still + BadNoCommunication") and an `otopcua.driver.comms_latched_refs` increment — the counter whose non-zero value is + documented as meaning "a driver reconnects without re-publishing". A disable → re-enable of the same id inherits the + stale latch. `ChildHealthLedger.Forget` is undone by the stopped child's late health publish (the hub and tracker are + tombstoned against exactly this; the ledger is not). +- **Suggested fix:** in `StopChild`, `_commsLatched.Remove(id)` and cancel `CommsAuditTimerKey(id)`; tombstone the + ledger like the hub. +- **Test to add:** disconnect a driver, remove it by deploy, advance past the audit delay; assert no Warning/metric + and an empty latch. +- **Existing tests:** none for the removal case. + +### R-17 — VirtualTag `source-binding-retry` replays the whole apply every 250 ms while a binding fails + +- **Severity:** Low · **Category:** bug/perf · **Confidence:** Medium +- **Location:** `VirtualTags/VirtualTagHostActor.cs:118`, `:223-227`, `:291-293`. +- **Verification:** the retry-replays-`OnApply` structure re-verified; the side effects per replay are from the + sub-review. +- **Description / scenario:** `Timers.StartSingleTimer("source-binding-retry", msg, 250ms)` re-delivers the original + `ApplyVirtualTags`. While `EnsureVirtualBinding` keeps failing (one persistent cause: the hub's `MaxTrackedSources` + cap), four times a second with no backoff or cap: quarantines are reset (a runaway script is re-run), + `ReassertValue` goes to every surviving child (N value updates and sink-lock acquisitions), every disabled tag's + `BadOutOfService` is republished, and the cycle graph is recomputed. Only when DataConnections is wired. +- **Suggested fix:** a dedicated retry message that only re-attempts binding and spawning for the still-unbound ids, + with backoff and one degraded log line. +- **Test to add:** fake publisher whose `EnsureVirtualBinding` fails for one id; assert no repeated + `ResetQuarantines`/`ReassertValue` across 1 s. +- **Existing tests:** would not catch it. + +### R-18 — Deferred "known" marks are discarded for conditions whose live mark actually landed + +- **Severity:** Low · **Category:** bug (false diagnostic) · **Confidence:** Medium +- **Location:** `OpcUa/OpcUaPublishActor.cs:812-816`, `:1171-1172`, `:1212-1219`. +- **Verification:** **not independently re-read by the lead.** +- **Description / scenario:** `HandleMarkConditionsKnown` applies the mark live and also defers it. At replay any + deferred alarm outside `scope.Conditions` — the normal state of every kept condition on a surgical or no-artifact + apply — calls `NoteAlarmLoss(source)`, the source's deferred Known marks are "discarded" and the sender gets + `ConditionMarksDiscarded`. A driver that reconnects during a plan window has its conditions put back in the F5 window + with a Warning and later a false "not signalled" diagnostic; the sink and the host tracker disagree. +- **Suggested fix:** note a loss only when the alarm's node is in scope but was dropped (overflow) or is absent from + both the previous and the applied composition. +- **Test to add:** plan in flight; send `AlarmStateUpdate` + `MarkConditionsKnown` for an existing condition; finish a + non-rebuild apply; assert no `ConditionMarksDiscarded`. + +### R-19 — `VirtualTagActor` evaluation backlog is uncoalesced, and array results never dedup + +- **Severity:** Low · **Category:** perf · **Confidence:** Medium +- **Location:** `VirtualTags/VirtualTagActor.cs:427-445` (stash/unstash), `:545` (dedup), `:447-458`. +- **Verification:** the `Equals(_lastValue, result.Value)` dedup and the `ReceiveAny(_ => Stash.Stash())` shape + re-verified; the rest from the sub-review. +- **Description / cost:** every evaluation is asynchronous; while one runs everything is stashed, and `UnstashAll` + re-queues M messages of which the first starts a new evaluation and M−1 are re-stashed — O(M²) message hops and one + script run per stashed batch, unbounded if arrivals outpace evaluation (out-of-process runner under load). Per-trigger + evaluation is deliberate per the class doc, so this is a cost note. Separately, `Equals` on arrays is reference + equality and the value is copied each time, so an array-typed VirtualTag publishes, routes to the mux (re-evaluating + dependents) and historizes on every trigger — up to 20/s on a 50 ms timer. +- **Suggested fix:** fold consecutive stashed `DependencyValueBatch`es into the dependency map and evaluate once; + structural comparison for arrays. +- **Test to add:** slow evaluator + 100 batches → evaluation count far below 100; array VirtualTag with unchanged + output → one publish. + +### R-20 — A supervision restart of `OpcUaPublishActor` resets `_lastApplied` while the sink keeps the address space + +- **Severity:** Low (latent) · **Category:** bug · **Confidence:** Medium on the consequence; no concrete trigger found +- **Location:** `OpcUa/OpcUaPublishActor.cs:313-318` and the unguarded handlers at `:593-594`, `:701-714`, `:812-816`, + `:853-863`, `:919`, `:1465-1473`, `:1484`, `:2261-2311`. +- **Verification:** **not independently re-read by the lead.** +- **Description / scenario:** if any unguarded handler ever throws, the new incarnation diffs the next deploy against + an empty composition: everything looks added, so it is a non-rebuild apply of idempotent ensures; nodes the deploy + removed are never removed, in-place attribute edits are skipped (`EnsureVariable` early-returns), and the apply + reports clean. `_warmRole` also resets to Standby without closing an open projection. +- **Suggested fix:** on restart mark the baseline unknown and force the first apply to be a full rebuild. +- **Test to add:** restart the actor after an apply; deploy a composition that removes a node; assert the node is gone. + +### R-21 — `WriteOperationRegistry.Prune()` copies and scans the whole table under the lock on every claim + +- **Severity:** Low · **Category:** perf · **Confidence:** High +- **Location:** `DataConnections/WriteOperationRegistry.cs:53-55`, `:104-112`. +- **Verification:** re-verified by reading. +- **Description / cost:** `foreach (var pair in _entries.ToArray()) { if (!pair.Value.Claim.CanRetire(now, + _retention)) continue; … }` runs inside `lock (_gate)` on every `Claim`. Entries live for the retention window after + completion, so at W writes/s the table holds ~retention × W entries: at 100 writes/s with a 30 s retention that is a + ~3 000-entry array copy and 3 000 `CanRetire` calls per write item, crossing the LOH threshold a little above that + rate. The condition-method registry uses the same class with a longer retention. +- **Suggested fix:** keep a completion-ordered queue and pop expired heads, or prune only at capacity / every N ms. +- **Test to add:** allocation budget for a claim against a table of 5 000 unexpired entries. + +### R-22 — History remainder bytes leak when a session is cleared while one of its requests is in flight + +- **Severity:** Low · **Category:** bug/leak · **Confidence:** Medium (narrow window) +- **Location:** `DataConnections/OriginHistorySessions.cs:80-95` (`SaveChunk`), `:124-131` (`Clear`); + `DataConnections/LocalDataServices.History.cs:203`, `:224-225`. +- **Verification:** `SaveChunk`/`Clear` re-verified by reading; the request-side window is from the sub-review. +- **Description / scenario:** `Clear()` (channel close, per-principal LRU eviction, capacity change) empties the session + and removes it from the owner but sets no closed flag. A request already holding the session reference then calls + `SaveChunk` → `_owner.TryReserve(Principal, bytes, …)` and stores the chunk in the orphan. Nothing sweeps the orphan, + so the bytes stay charged to the principal for the life of the process; after a few such events every chunked + history answer for that principal returns `BadTooManyOperations` until restart. +- **Suggested fix:** set a `_cleared` flag under `_gate` in `Clear()`; `SaveChunk` releases the bytes and returns null + when it is set. +- **Test to add:** hook between the last cancellation check and `SaveChunk`; clear the session there; assert the + principal's retained bytes return to zero. + +### R-23 — The command barrier can be armed after the only event that releases it + +- **Severity:** Low · **Category:** bug (race) · **Confidence:** Medium (narrow window) +- **Location:** `DataConnections/DataSubscriptionSession.cs:346-348`, `:392-407`, `:986-999`. +- **Verification:** the check-then-CAS shape and `ReleaseBarrier` re-verified by reading; the delivery-side ordering is + from the sub-review. +- **Description / scenario:** the worker evaluates `HasIncompleteSnapshot()` (under `_gate`), releases the lock, then + does `Interlocked.CompareExchange(ref _barrier, 1, 0)`. If the delivery thread commits the last `SnapshotEnd` in + between, its `ReleaseBarrier(1)` finds 0 and is a no-op; the worker then arms the barrier. Nothing releases it unless + another snapshot completes, every command defers, and the stream stops at the command's ack timeout. +- **Suggested fix:** arm first, then re-check and self-release; or do check-and-set and the release decision under the + same lock. +- **Test to add:** hook between the check and the CAS that completes the snapshot; assert the deferred Modify runs. + +### R-24 — Condition stream teardown can mask its real failure with `NotSupportedException` + +- **Severity:** Low · **Category:** bug (diagnostics) · **Confidence:** Medium +- **Location:** `DataConnections/ProjectedConditionAccess.Runner.cs`, `RunStreamAsync` + (`await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token);` with + `next ??= frames.MoveNextAsync().AsTask();` left pending across iterations). +- **Verification:** **not independently re-read by the lead.** +- **Description / scenario:** when `ApplyResolvedAsync` or `RetryDueAsync` throws while `next` is in flight, the + `await using` disposes an async iterator mid-`MoveNextAsync`, which throws `NotSupportedException`; that replaces the + original exception in the "stream ended" log and `next` later faults unobserved. The reconnect still happens. +- **Suggested fix:** cancel a per-stream token and await/observe `next` in the finally before disposing. + +### R-25 — Smaller costs worth a note + +- **Severity:** Low · **Category:** perf · **Confidence:** High on the code, impact small +- **Verification:** read by the lead. +- `DataConnections/SourceSamplePublisher.cs:220-238`: `RetireDriver` and `PublishDriverStatus` find a driver's refs + with `_drivers.Where(x => x.Key.Driver == driver)` — a scan of every bound ref of every driver, under the global + `_gate`, per connectivity edge and per child stop. A deploy that respawns D drivers over N total tags is O(D·N) under + the lock that `EnsureDriverBinding` only `TryEnter`s (so bindings silently fail and go to the 250 ms retry while it + is held). A per-driver index removes it. +- `Drivers/DriverInstanceActor.cs:2049`, `:2068`, `:2923-2945`: with DataConnections enabled, every driver data change + pays `PublishSource` on the driver's callback thread (1–2 dictionary probes, a size estimate, an ingress reservation + and a value copy) and enters the hub's change history whether or not any gRPC consumer exists. This is what makes + R-3 reachable on a node with a single small subscription; publishing only for sources with interest would remove + both the cost and the trigger. +- `Historian/ContinuousHistorizationRecorder.cs` `OnDrainResult`: a successful full batch re-arms the 2 s timer rather + than draining again immediately, so with no ingest a backlog drains at `drainBatchSize / drainInterval` (default + 512 entries/s — ~33 minutes for a 1M-entry outage backlog). Appends do trigger extra drains, so this only limits + catch-up during quiet periods. Re-tick immediately when `Acked == _drainBatchSize`. +- `DataConnections/ConfiguredProjectedInterestOwner.SweepAsync` (sub-review, not re-read): re-queues every desired + entry every second with no backoff; an unresolvable configured reference re-runs discovery each second indefinitely. + +--- + +## Areas reviewed with no findings + +- **`DriverInstanceActor`:** connect/reconnect state machine and single-flight init (H2 remediated); comms-loss watchdog + conjunction and per-connection grace; write slots, per-tag ordering, queue budget, abandon path and rich-write + settlement (#964/#967); native-alarm subscribe/reconcile/backoff and data-vs-alarm independence (#662); ack + confirmation off-mailbox (#869); `PostStop` bounded shutdown + dispose (P4/L1 remediated); handler detach on every + exit; health fingerprint dedup. +- **`DriverHostActor`:** value fan-out hot path (`ForwardBatchToMux` — struct items, one list per burst, guarded debug + log); comms-loss fans; write routing and Primary gate; Steady/Applying/Stale receive tables (H5 remediated); ack + holding and degraded/timeout paths (other than R-15); child spawn/restart/reprovision incarnation checks (L2 + remediated); `ConditionSignals`, `NativeAlarmProjector`, `DriverSpawnPlan`, `DriverWriteBounds`, + `ActorNodeWriteGateway`, `AkkaDriverHealthPublisher`, `NativeAlarmAckPreflightView`. +- **`Communication/*`, `Deployment/*`:** ack sender, artifact fetcher (bounded, validated timeout), LocalDb artifact + cache and schema. +- **`OpcUaPublishActor`:** value/status/alarm handlers, deferred writes and replay ordering, the degraded non-rebuild + no-advance rule, `RebuildCompleted` on every path, incarnation fencing, ServiceLevel/Warm ordering. +- **`ScriptedAlarmHostActor` and stores:** load-generation fencing, readiness, command dedup bounds, Sender capture + across awaits, engine ownership across restart (H1/H3 remediated), re-assert ordering, Primary gate; + `LocalDbAlarmConditionStateStore`; `DependencyMuxTagUpstreamSource` (L3 remediated). +- **`DependencyMuxActor`:** registration/detach/grace/sweep bookkeeping and the hot ingress path (lazy allocation, + indexed loop). `DependencyConsumerMuxAdapter`, `DpsScriptLogPublisher`. +- **`Historian/*`:** recorder ingest → bounded append channel → off-mailbox drain (P3/H3 remediated), partial-failure + head-of-line logic, backoff, status off-mailbox; `HistorianAdapterActor` bounded queue (H4 remediated); retention. +- **`Redundancy/*`, `Health/*`, `Telemetry/*`:** `RedundancyRoleView` verdict/generation fencing, `WarmRoleAuthority`, + `OpcUaEndpointStepDownActor`, peer probes, `DbHealthProbeActor` (P7 remediated), `TelemetryLocalHub` tombstones (L4 + remediated). +- **`DataConnections/` (serving side):** `PartitionedSampleHub`, `ConditionItemStream`, `ConditionStateHub`, + `SubscriptionTransportCapacity`, `DataWriteExecutor`, `WriteAdmissionTicket`, `LateWriteObserver`, + `DataWriteDispatchGate`, `DataWriteRuntime`, `SnapshotAdmissionScheduler`, `SnapshotLease`, `DeliveryScheduler`, + `OwnedDataSample`, `UpstreamDemandRegistry`, `SubscriptionItemHandleTable`, `BrowseContinuationRegistry`, + `ClientFilterState`, `LocalExportCatalog.Compilation`, `LocalDataServices.ConditionMethods`/`.Conditions`. +- **`DataConnections/` (projected side):** `GrpcDataConnection.History`/`.ConditionMethods`/`.Diagnostics`, + `DataConnectionDeploymentRuntime`, `GrpcDataDriverAdapter`. diff --git a/docs/reviews/2026-12-02/02-opcuaserver.md b/docs/reviews/2026-12-02/02-opcuaserver.md new file mode 100644 index 000000000..365454d21 --- /dev/null +++ b/docs/reviews/2026-12-02/02-opcuaserver.md @@ -0,0 +1,384 @@ +# Review 02 — `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer` (master @ 708a4889c) + +**Slice:** `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/` (~32k lines). +**Commit:** `708a4889c`. Read-only review; nothing was built or run. +**Callers read to confirm findings:** `Runtime/OpcUa/OpcUaPublishActor.cs` (plan → apply → materialise), +`Runtime/Drivers/DeploymentArtifact.cs` (artifact-side composition), `Core/Authorization/DataPlaneAuthority.cs` +(UNS folder-scope placement), `AdminUI/Uns/UnsTreeService.cs` + `LineModal.razor` (what an operator can author). + +**Scope read** + +| Area | Files | How | +|---|---|---| +| Plan / classify / apply | `AddressSpacePlan.cs`, `AddressSpaceChangeClassifier.cs`, `AddressSpaceApplier.cs`, `AddressSpaceComposer.cs` (records, UNS-reference + raw topology builders) | Read in full | +| Node manager core | `OtOpcUaNodeManager.cs`: publish path (`WriteValue(s)`/`WriteStatuses`), `EnsureFolder`/`EnsureVariable`/`UpdateTagAttributes`/`AddReference`, `RebuildAddressSpace`, `Remove*`, `RemoveSubtree`, monitored-item tombstoning + revalidation, alarm materialise / notifier wiring / carry-over, condition event delivery + deferral, method handlers, equipment write + revert, `ConditionRefresh`, Read/Browse gates, historian setters, `Dispose` | Read in full | +| History read/update | node-manager history arms + `History*.cs`, `Reverse*.cs`, `PeerHistoryContinuationStore.cs`, `HistoryReadPort.cs`, `OriginHistoryPort.cs`, `ProjectedHistoryRead.cs` | Delegated sub-review, findings re-verified | +| Security / host | `Security/*`, `OtOpcUaSdkServer.cs`, `OpcUaApplicationHost.cs`, `WarmStandby.cs` | Delegated sub-review, findings re-verified | +| Projected (gRPC data) surface | `Projected*.cs`, `ImportedConditionMethods.cs`, node-manager partials | Delegated sub-review, findings re-verified | +| Not reviewed | `Compatibility/Aggregates/*` (~6k lines of aggregate calculators) | Skimmed only | + +Prior review `docs/reviews/2026-10-21/01-opcuaserver.md` was checked first. L1, L2, L3, L4, H2, H5, P1, P2 and P5 +are fixed in the current code (non-creating writes, `TombstoneMonitoredNode`, observed write faults, no placeholder +variable, `IsHeldByAnotherKind`, guarded dispatch, subtree detach, child index, wiring dedupe). None is re-reported. + +--- + +## Findings + +### U-1. Subscription revalidation enforces ACL grants while `Security:Acl:Enabled=false` + +- **Severity:** Critical (default configuration; regression from `8ad03e9c5`, 2026-11-16, merged but not yet deployed) +- **Category:** bug +- **Confidence:** High (code path read end to end; the delegated reviewer also reproduced it with a throwaway reflection probe against the built test binaries) +- **Location:** + - `OtOpcUaNodeManager.cs:848` — `SecurityFilteringActive => AclEnforced || _mappedSubjectResolver is not null || NamespaceIndexes.Count >= 4` + - `OtOpcUaNodeManager.cs:8741-8744` (`RevalidateMonitoredItems` guard), `:8952-8975` (`IsSubscriptionStillPermitted`), `:8876-8912` (`RevalidateEventItems`) + - `Security/DataPlaneAuthorizer.cs:267-308` (`AuthorizeCached` / `IsAllowedCached` → `Evaluate(..., localBypass: false)`), versus `:154-156` (`AuthorizeIfRequired` → `localBypass: !Enabled`) + - `Host/OpcUa/OtOpcUaServerHostedService.cs:580-605` (timer armed unconditionally) +- **Description:** The manager always registers five namespaces (`RegisteredNamespaceUris`, `:124-125`), so + `NamespaceIndexes.Count >= 4` makes `SecurityFilteringActive` unconditionally true. `RevalidateMonitoredItems` + early-returns only on `!SecurityFilteringActive`, so it now runs with the flag off. When no mapped-subject resolver + is wired (`DataConnections:Enabled=false`, the default) `IsSubscriptionStillPermitted` calls + `_authorizer!.IsAllowedCached(...)`, which evaluates the grant trie with no `Enabled` bypass. Every other seam + (Read, Browse, CreateMonitoredItems, SubscribeToEvents) goes through `Permits` → `AuthorizeIfRequired`, which does + bypass. The pass fires on every deploy (`OnAuthorityChanged`, `:760`) and on the `AclRevalidationTimer` + (default 60 s). The timer's own remark still says the pass "early-returns unless … `Security:Acl:Enabled` is on". +- **Failure scenario:** Default config. An Anonymous session, or a key whose grants do not include Subscribe on the + node, creates data subscriptions (allowed: `.claude/rules/data-plane-auth.md` says subscribe is ungated with the flag + off). Within 60 s, or at the next deploy, each data item is queued `BadUserAccessDenied` and detached from its + fan-out, and each direct event item is silently unsubscribed. The client re-creates the items (creation still + bypasses) and they are stood down again on the next tick. On a node with no artifact yet or a blank `ClusterId` + every session is hit, because `Evaluate` denies outright. Secondary: `_authorizer!` at `:8827`, `:8965`, `:8972` + throws `NullReferenceException` if the authorizer is detached. +- **Suggested fix:** In `IsSubscriptionStillPermitted` use `Permits(identity, OpcUaOperation.CreateMonitoredItems, nodeId)` + for both branches (it already carries the flag-off bypass, the mapped veto and the imported classifier), keeping + the pass-local `verdicts` memo. Equivalently, skip the non-projected, non-imported items in + `RevalidateMonitoredItems` / `RevalidateEventItems` when `!AclEnforced`. Null-guard `_authorizer`. Fix the timer remark. +- **Existing tests:** none catch it. `NodeManagerStage6EnforcementTests` checks flag-off Read only; + `AclEventSubscriptionEnforcementTests.With_acl_enforcement_off…` never runs a revalidation pass. +- **Test to add:** `Authorizer(enabled: false)` with a principal holding no Subscribe grant; track one data item and + one event item; call `RevalidateMonitoredItems()`; assert zero `BadUserAccessDenied` and both still attached. Repeat + for Anonymous and for an empty authority. Wire-level: flag-off rig, anonymous subscription, `AclRevalidationTimer.Tick()`, + values keep flowing. + +### U-2. Scripted-alarm Enabled / AlarmType / Severity / Name edits never reach the address space + +- **Severity:** High +- **Category:** bug (planner omission; stale and missing condition nodes) +- **Confidence:** High +- **Location:** + - `AddressSpacePlan.cs:160-163` — alarms are diffed over `ScriptedAlarmPlans` only + - `AddressSpaceComposer.cs:324` — `ScriptedAlarmPlan(ScriptedAlarmId, EquipmentId, PredicateScriptId, MessageTemplate)`; built at `:612-615` and, artifact side, `Runtime/Drivers/DeploymentArtifact.cs:1887-1895`. Neither filters on `Enabled` + - `AddressSpaceApplier.cs:1149-1163` — materialisation reads `EquipmentScriptedAlarms` (`Name`, `AlarmType`, `Severity`, `Enabled`) and skips `!Enabled` + - `Runtime/OpcUa/OpcUaPublishActor.cs:1554` (empty plan returns before any materialise), `:1798-1806` (`DeltaScriptedAlarms` = `plan.AddedAlarms` only) + - `OtOpcUaNodeManager.cs:2575-2590` — the idempotent skip relies on "a genuine re-severity/type change arrives as a ChangedAlarms delta ⇒ full rebuild", which is not true +- **Description:** The four fields that decide whether and how a scripted condition node exists live only on + `EquipmentScriptedAlarmPlan`, which `AddressSpacePlanner.Compute` never diffs. A deploy that changes only those + fields produces no `AlarmDelta`. If nothing else changed the plan is empty and the publish actor returns before + touching the sink; if something else changed, a non-rebuild apply materialises only `AddedAlarms`. +- **Failure scenario:** + 1. Operator enables a previously disabled scripted alarm and deploys. The plan is empty. The condition node is + never materialised. The alarm host starts evaluating and calls `WriteAlarmCondition`, which is a Debug-logged + no-op for an unmaterialised id (`:1350-1358`). OPC UA clients never receive the alarm, with no error anywhere, + until an unrelated rebuild-class deploy or a process restart. + 2. Operator disables an alarm: the condition node stays browsable and subscribable in its last state. + 3. `AlarmType` or `Name` edit: the node keeps the old type definition and display name indefinitely. + (`Severity` self-heals on the next transition, because `ApplyConditionState` projects it.) +- **Suggested fix:** Diff `EquipmentScriptedAlarms` in the planner (it already has value equality) and treat a delta + in `Name` / `AlarmType` / `Severity` / `Enabled` as a `ChangedAlarms`-class change (rebuild), or more surgically: + `Enabled` false→true as an add, true→false as a remove (`RemoveAlarmConditionNode`), and type/name as + remove + re-materialise of that one condition. Whitelist the engine-only fields (`PredicateSource`, + `DependencyRefs`, `HistorizeToAveva`, `Retain`) with the same `with`-equality pattern the vtag path uses. +- **Existing tests:** none. No planner/classifier test varies `Enabled`, `AlarmType` or `Severity` on an existing alarm. +- **Test to add:** Planner: two compositions differing only in a scripted alarm's `Enabled` (and, separately, + `AlarmType`) must not be `IsEmpty`. Publish-actor: deploy disabled → deploy enabled, assert + `MaterialiseAlarmCondition` was called and a following `WriteAlarmCondition` fires an event. + +### U-3. A UNS Line re-parented to another Area is invisible to the plan; with ACLs on, everything under it is denied + +- **Severity:** High with `Security:Acl:Enabled=true`; Medium otherwise +- **Category:** bug (planner omission; stale topology, fail-closed outage) +- **Confidence:** High +- **Location:** + - `AddressSpacePlan.cs:206-208` — Areas/Lines are diffed for `DisplayName` only (`DiffRenames`); `UnsLineProjection.UnsAreaId` is never compared, and added/removed Areas and Lines are not in the plan at all + - `AddressSpaceApplier.cs:871-874` + `OtOpcUaNodeManager.cs:4297-4301` — `MaterialiseHierarchy` → `EnsureFolder` early-returns on an existing folder id, so the parent is never corrected + - `OtOpcUaNodeManager.cs:6277-6289` (`LiveHierarchyChain`), `Core/Authorization/DataPlaneAuthority.cs:205-229` (`TryGetUnsFolderSegments` requires the live id chain to equal the generation's), `Security/DataPlaneAuthorizer.cs:549-576` + - Authorable today: `AdminUI/Uns/UnsTreeService.cs:767` (`entity.UnsAreaId = newUnsAreaId`), parent-area select in `LineModal.razor:25-31` +- **Description:** Moving a Line to another Area changes no `EquipmentNode` (it carries `UnsLineId` only). The UNS + reference NodeIds under it change (`NewArea/Line/Equipment/Name`) and arrive as identity-changing + `UnsReferenceDelta`s, which are surgical. Nothing forces a rebuild, and the Line folder stays a child of the old + Area folder. +- **Failure scenario:** + - ACL off: clients browse `OldArea → Line → Equipment` and find variables whose NodeIds say `NewArea/...`; `NewArea` + shows no such line. Persists until a rebuild-class deploy or restart. If the line's equipment has no references + the plan is empty and nothing happens at all. + - ACL on: `FeedDataPlaneAuthority` installs the new generation (it runs ahead of the empty-plan return), whose + `UnsFolderScopes[line].IdChain` is `[NewArea, Line]`. The live chain is `[OldArea, Line]`. `TryGetUnsFolderSegments` + returns false for the Line folder, every Equipment folder under it, their virtual tags, their re-created reference + variables and their scripted conditions' commands — all answer `BadUserAccessDenied` ("moved, renamed, or not yet + rebuilt"). The revalidation pass that the authority change triggers stands down every existing subscription under + the line. No later surgical deploy repairs it. + - Same omission, lower impact: a deleted Area/Line folder stays browsable (empty) until a rebuild, and an added + Area/Line with no equipment is not materialised until some other change makes the plan non-empty. +- **Suggested fix:** Diff `UnsAreas` / `UnsLines` fully in the planner. Route a changed `UnsAreaId`, and any removed + Area/Line, to `Rebuild` in `AddressSpaceChangeClassifier` (default-closed, like `ChangedEquipment`); treat added + Areas/Lines as adds so the plan is not empty. A surgical re-parent is possible later but is not needed for correctness. +- **Existing tests:** none. `AddressSpacePlanner*Tests` / `AddressSpaceChangeClassifier*Tests` cover renames only. +- **Test to add:** Planner + classifier: same line id, different `UnsAreaId` ⇒ non-empty plan classified `Rebuild`. + Node-manager with authorizer enabled: apply composition A, re-parent the line, apply B, assert a granted principal + can still Read a reference variable under the line and that the Line folder's parent is the new Area. + +### U-4. Two overlapping failed writes leave the node on the first rejected value with Good status + +- **Severity:** Medium +- **Category:** bug (optimistic-write revert) +- **Confidence:** High on the mechanism (traced, not executed); Medium on frequency +- **Location:** `OtOpcUaNodeManager.cs:3509-3525` (prior value captured from the node's current value), + `:4002-4040` (`RevertOptimisticWriteIfNeeded`), `EquipmentVariableState.cs:17-24, 64-78` (single `_committedWriteToken`) +- **Description:** Write B's `priorValue` is whatever the node holds, which is write A's unconfirmed optimistic value + while A is still in flight. Only the latest committed token owns the node, so A's failure is ignored as superseded + and B's failure reverts to A's value with A's (Good) status. The real pre-A value P is never restored. +- **Failure scenario:** A client writes the same node twice inside one driver round-trip (two `WriteValue`s in one + request, or an HMI double-click) and the device refuses both (protected register, out of range). Both calls + returned Good. Subscribers see a Bad blip, then value A with Good status, which the device never accepted. The + poll engine publishes on change against its own last-seen value, so if the device still holds P no publish follows + and the node stays wrong until the device value next changes. The audit event's `OldValue` also reports A. +- **Suggested fix:** Keep a per-node "last confirmed" tuple (value, status, source timestamp) on + `EquipmentVariableState`, set by driver publishes and confirmed-success outcomes, and revert to that instead of + the value captured at handler entry. Alternatively chain priors: when a superseded attempt fails, hand its prior to + the owning attempt. +- **Existing tests:** none. `NodeManagerWriteRevertTests` covers single-write cases only. +- **Test to add:** Node at P; write A then B through the SDK `Write` path with a gateway whose two tasks complete as + failures, in both completion orders; assert final value P with P's status and timestamp. + +### U-5. Stood-down-item sweep makes rebuilds and removals O(nodes × live items) under `Lock` + +- **Severity:** Medium +- **Category:** perf +- **Confidence:** High +- **Location:** `OtOpcUaNodeManager.cs:6899-6925` (`TombstoneMonitoredNode`, sweep at `:6924`), `:6947-6958` + (`TombstoneAllMonitoredNodes`), `:6962-6982` (`SweepStoodDownItems`), callers `:5852-5890`, `:5994-6060`, `:6929-6945` +- **Description:** Whenever at least one monitored item is stood down (`_suppressedItems > 0` — an ACL-revoked item + the client has not deleted, a lapsed projected item, or any item hit by U-1), every `TombstoneMonitoredNode` call + ends with `SweepStoodDownItems(nodeId)`, a full enumeration of `_liveItems` and `_eventItems`. It is called once + per `MonitoredNodes` key by `TombstoneAllMonitoredNodes` (which then runs one more unfiltered sweep that would have + sufficed alone), once per removed variable/folder by `RemoveVariableNode` / `RemoveSubtree`, and once per child node + of a removed condition (~100+ children each) by `TombstoneMonitoredSubtree` — whether or not the node is monitored. +- **Cost:** Rebuild with 50k monitored nodes and 50k live items: up to 2.5 × 10⁹ dictionary-entry visits under the + manager `Lock` (tens of seconds, stalling every Read/Browse/publish). A surgical apply that removes 5k reference + variables (an Area rename): 2.5 × 10⁸. Removing 100 alarm-bearing tags: ~10⁴ node visits × live items. With U-1 + present, `_suppressedItems > 0` is the normal state in the default configuration. +- **Suggested fix:** Split `TombstoneMonitoredNode` into the per-node part and the sweep. `TombstoneAllMonitoredNodes` + should call only the per-node part, then its existing single `SweepStoodDownItems(null)`. For scoped removals, keep + a `Dictionary>` of suppressed items (populated where `Suppressed = true` is set, `:8729`, `:8818`, + and in `RevalidateEventItems`) so the per-node sweep is a lookup, or collect the removed NodeIds and sweep once per + apply. +- **Existing tests:** `GrpcDataSuppressedTombstoneWireTests` exercises correctness of the sweep, not its cost. +- **Test to add:** Counter-based (as `AllEventsMonitoringConditionVisits` does for P3): N monitored nodes, one + suppressed item, `RebuildAddressSpace()`; assert sweep visits are O(N + items), not O(N × items). + +### U-6. `HistoryReadEvents` has no server-side page cap + +- **Severity:** Medium +- **Category:** perf (memory / DoS) +- **Confidence:** High +- **Location:** `OtOpcUaNodeManager.cs:10019-10020` (`EventMaxEvents`: 0 → `int.MaxValue`), `:9439-9441` (fetch), + `:10032-10052` (`ProjectEvents`), `EventSourceFanOut.cs:119-161`; + `Driver.Historian.SqlServer/SqlServerHistorianDataSource.cs:407-409` (no `TOP` at `int.MaxValue`), + `Driver.Historian.QuestDb/QuestDbHistorianDataSource.cs:478-490` (no `LIMIT`) +- **Description:** Raw reads are paged at `ServerHistorian:MaxRawValuesPerRead` through `RawPageLimit.Plan`, + including `NumValuesPerNode = 0`. The events arm has no equivalent: `NumValuesPerNode = 0`, or any large N, is sent + to the backend unbounded, and the whole window is then materialised several times (backend list; the multi-source + merge, sort and EventId set; one `HistoryEventFieldList` + `List` per event; the encoder). The only bounds + are the 60 s deadline and the table size; `EventReadHorizon` is opt-in. +- **Failure scenario:** With ACLs off (default) any admitted session, Anonymous included, sends + `ReadEventDetails{Start=1970, End=now, NumValuesPerNode=0}` against an alarm-owning folder on a SQL Server or QuestDB + historian holding a few million events. The server buffers hundreds of MB to GB (largely LOH), then most likely + fails the response at encode time on `MaxMessageSize`. Up to 16 batches × 4 nodes are admitted concurrently. +- **Suggested fix:** `effective = min(N == 0 ? cap : N, cap)` before computing `fetch`; the existing truncated ⇒ + `(time, skip)` cursor already yields a continuation point. Add `ServerHistorian:MaxEventsPerRead` (0 = opt out) and + advertise it as `HistoryServerCapabilities/MaxReturnEventValues`. +- **Existing tests:** `NodeManagerHistoryReadEventsTests.cs:110-131` pins the current behaviour + (`LastMaxEvents.ShouldBe(int.MaxValue)`) and would change. +- **Test to add:** Fake source with cap + 5 events: `NumValuesPerNode = 0` returns exactly cap events plus a + continuation point, the backend saw `maxEvents <= cap (+skip)`, and paging yields every event once. Repeat for a + two-source folder and a reverse read. + +### U-7. NaN or oversized `ProcessingInterval` faults the whole HistoryRead request + +- **Severity:** Low +- **Category:** bug (wrong status; exception escapes per-node isolation) +- **Confidence:** High for the throw; Medium-High for the client-visible status (SDK dispatcher checked in source, not in the pinned binary) +- **Location:** `HistoryReadPort.cs:29-31` (`HistoryReadVariant.From`, called at `:365`), `ProjectedHistoryRead.cs:359-360` (`ToRemoteDetails`) +- **Description:** `TimeSpan.FromMilliseconds(processed.ProcessingInterval)` runs on the client's raw `Double` before + any per-node handling. It throws `ArgumentException` for NaN and `OverflowException` for ±Infinity or a magnitude + above ~9.2 × 10¹⁴ ms. Nothing between the override and the service catches it (`HistoryRead` at `:9208-9219` catches + only `ServiceResultException` for event details). +- **Failure scenario:** `ReadProcessedDetails{ProcessingInterval = double.NaN}` for 10 nodes. Expected ten per-node + `BadInvalidArgument`; actual a service-level fault (`BadUnexpectedError`) and an unexpected-exception log line per + request. +- **Suggested fix:** Validate once before conversion (`double.IsFinite(x) && Math.Abs(x) <= TimeSpan.MaxValue.TotalMilliseconds`); + otherwise set `BadInvalidArgument` for every handle and return, in both `ServeHistoryReadAdapter` and the projected path. +- **Existing tests:** none use a non-finite interval. +- **Test to add:** Theory over `NaN`, `±∞`, `double.MaxValue`: no throw, per-node `BadInvalidArgument`, backend never called; same for a projected node. + +### U-8. UNS-namespace ACL decisions allocate ahead of the decision cache on every call + +- **Severity:** Low +- **Category:** perf (ACL-on only) +- **Confidence:** High +- **Location:** `Security/DataPlaneAuthorizer.cs:705-731` (resolver + placement run before `Decisions.TryGet`; + `DataCallerIdentity` built before the lookup and again on a hit), `:543-617` (`TryPlaceUnsSubject`, + `ResolvedScopeCacheKey`), `OtOpcUaNodeManager.cs:6207-6289` (`ResolveUnsAclSubject`, `LiveHierarchyChain`) +- **Description:** The cache-hit comment says a hit returns "having built no scope, no closure". That holds for raw + nodes only. For every UNS node each decision allocates a `List` chain, a split of the identifier, LINQ + enumerators, and for folder-owned nodes a segment array plus a `string.Join` cache key, before the lookup. + Running the resolver per call is deliberate (it reads live topology); the allocations are not required by it. +- **Cost:** ~8–12 short-lived allocations per UNS node per decision: about 10k per 1,000-node UNS Read or per browse + of a 500-reference equipment, and the same per distinct node in each revalidation pass. +- **Suggested fix:** Cache the id chain and the precomputed cache key on the folder (invalidate on rebuild / removal); + compare identifier segments with spans; build one `DataCallerIdentity` per `Evaluate`. +- **Existing tests:** the decision-cost test in `NodeManagerStage6EnforcementTests` uses raw nodes only. +- **Test to add:** Allocation-budget test (`GC.GetAllocatedBytesForCurrentThread`) for a warm `IsAllowedCached` on a + UNS reference variable and a UNS folder. + +### U-9. A removed VirtualTag's sub-folder is left behind + +- **Severity:** Low +- **Category:** bug (stale node) +- **Confidence:** High +- **Location:** `AddressSpaceApplier.cs:354-359` (removes the variable only), `:1099-1106` (creates the + `{equipmentId}/{FolderPath}` folder); `ISurgicalAddressSpaceSink` has no folder remove +- **Description / scenario:** Removing the last VirtualTag in a `FolderPath` on a surviving equipment is a + `PureRemove`: the variable is removed in place, the now-empty sub-folder stays browsable until the next + rebuild-class deploy. Changing a VirtualTag's `FolderPath` is a rebuild, so only removals leak. +- **Suggested fix:** After the vtag removals, remove any `UnsSubFolder` id no remaining vtag of the composition + uses (the node manager's `RemoveSubtree` already handles a folder key; expose it for sub-folders), or accept and + document. +- **Test to add:** Applier test: two compositions, second drops the only vtag under `FolderPath = "calc"`; assert the + folder node is gone without `RebuildCalled`. + +### U-10. `IProjectedValueSink.TryPublish` snapshots and scans every live monitored item once per published value, under `Lock` + +- **Severity:** Medium (High at scale; only reachable with gRPC data connections enabled) +- **Category:** perf +- **Confidence:** High +- **Location:** `OtOpcUaNodeManager.cs:4757-4758`; `_liveItems` declared at `:7129`, populated for every owned namespace at `:6815` +- **Description:** Inside the per-value loop: `foreach (var item in _liveItems.Keys.OfType()) if (item.ProjectedNodeId == target.Id …)`. + `_liveItems` is a `ConcurrentDictionary` holding every data-change item on every namespace of this manager, not + just projected ones. `ConcurrentDictionary.Keys` takes all bucket locks and copies the keys into a new list on each + call. So each value in a batch pays an O(total items) copy plus an O(total items) type test, on the publish thread, + holding the manager `Lock`. +- **Cost:** 20,000 live items and a 500-value batch: 500 key snapshots of ~160 KB each (LOH, ~80 MB per batch) and + 10M type checks, with every `_liveItems` bucket lock taken 500 times (contending with item create/delete). Local + driver publishes and all SDK services queue behind `Lock` meanwhile. +- **Suggested fix:** Maintain a `Dictionary>` under `Lock` in + `TrackLiveMonitoredItem`, `OnMonitoredItemDeleted`, `TombstoneMonitoredNode` and the sweep (it must keep stood-down + items, which the current scan also reaches) and look up by `target.Id`. +- **Existing tests:** none measure it. +- **Test to add:** ~20k ordinary live items plus a few projected ones; publish a 500-value batch; assert allocated + bytes scale with the batch, not the item count. + +### U-11. Removing a projected anchor leaves its `MonitoredNode2` behind; event items on the re-created anchor bind to the dead folder + +- **Severity:** Medium +- **Category:** bug (the prior review's L2 class, missed on one path) +- **Confidence:** High on the mechanism; Medium on how often an anchor carries event items +- **Location:** `OtOpcUaNodeManager.cs:4381-4409` (`TryRemoveProjectedAnchor`); variant in the root-leaf folder→variable swap near `:4999` +- **Description:** `TryRemoveProjectedAnchor` calls `TombstoneMonitoredNode(id)` for every descendant (`:4398`) but + never for the anchor's own NodeId: the anchor is only unwired (`OnProjectedFolderRemoving`, `ProjectedConditionRegistry.cs:720-727`, + which touches no monitored-item state) and dropped from `PredefinedNodes`. The anchor is a legitimate event notifier + (`SubscribeToEvents` admits it through `ImportedNotifierAdmits`). The SDK keys `MonitoredNodes` by NodeId and reuses + an existing entry, so the entry keeps pointing at the dead `FolderState`; delivery requires + `ReferenceEquals(monitored.Node, node)` (`OwnNotifierFanOut`, `:2005`). +- **Failure scenario:** Client A holds an event item on a mapping's anchor. The mapping revision is bumped; the anchor + is removed and re-ensured under the same NodeId in the same pass. Imported conditions wire to the new folder. + Client B subscribes to events on the anchor: the SDK finds the stale entry, adds B there and returns Good. Neither A + nor B receives a condition event from that folder until every pre-existing item on that NodeId is deleted. +- **Suggested fix:** `TombstoneMonitoredNode(nodeId, UtcNow)` in `TryRemoveProjectedAnchor` before detaching the + anchor; in the root-leaf swap call `OnProjectedFolderRemoving` + `TombstoneMonitoredNode` on the anchor id first. +- **Existing tests:** none; the tests that call `TryRemoveProjectedAnchor` use no event items. +- **Test to add:** Materialise an anchor, subscribe an event item, remove + re-ensure with the same id, wire an + imported condition, subscribe a second item; assert `MonitoredNodes[anchorId].Node` is the new folder and the second + item receives the event. + +### U-12. Quadratic eviction scan in `ReserveProjectedNode` once the projected-node cap is reached + +- **Severity:** Medium +- **Category:** perf +- **Confidence:** High on complexity; Medium on how often a deployment sits at the cap with stale entries +- **Location:** `OtOpcUaNodeManager.cs:4511-4541`; the same `.Values.Any(...)` pattern in the page-sink remove near `:5030` +- **Description:** At the cap (default 4096 nodes / 16 MiB) every `TryEnsureProjectedVariable` / `TryEnsureProjectedAnchor` + copies `_projectedDefinitions.ToArray()` and, for each entry whose authority is stale, runs + `_projectedVariables.Values.Any(child => child.Parent == pair.Key)` — a full scan — before `TryRetire`. Stale but + unevictable entries (leaves pinned by a demand lease, folders with children) are rescanned on every call, and a + browse page calls this once per new node inside one `Lock` hold. +- **Cost:** Worst case 4096 × 4096 ≈ 16.7M predicate calls per reserve (tens of ms); a 1,000-node page at the cap with + a few hundred stale-pinned entries is on the order of 10⁹ operations — seconds of `Lock` time. +- **Suggested fix:** Keep a per-parent child count updated wherever `_projectedVariables` gains or loses an entry and + replace the `.Values.Any` calls with a lookup; reserve once per page with the summed charge. +- **Existing tests:** eviction is covered functionally, not for cost. +- **Test to add:** Fill to the cap with pinned, stale-authority leaves; apply a page of 256 new nodes; assert + `AuthorityIsCurrent` / child-scan evaluations stay linear. + +### U-13. Removing an imported condition scans the whole verdict cache under `Lock` + +- **Severity:** Low +- **Category:** perf +- **Confidence:** High +- **Location:** `ProjectedConditionRegistry.cs:159-167` (`Remove`), cache declared at `:142`, bounded at 65,536 (`:195`) +- **Description / cost:** Each removal runs `_verdicts.Keys.Where(k => k.Condition == id).ToList()`. Removing K + conditions costs about K × V NodeId comparisons under the manager `Lock`: a 1,000-condition mapping with 20 sessions + (V ≈ 20k) is ~10⁷ comparisons; at the 65k bound several times that per 128-item chunk. +- **Suggested fix:** Give each `ImportedCondition` its own small verdict dictionary so it dies with the instance, or + add a condition-id → keys index. +- **Test to add:** Seed 60k verdicts, remove 1,000 conditions, assert per-condition work is bounded. + +--- + +## Areas reviewed with no findings + +- **Publish path** — `WriteValue` / `WriteValues` / `WriteStatuses`: non-creating, per-item isolation, 512-item + lock chunks, key resolution outside `Lock`. No hot-path defect found. +- **Classifier and applier routing** — `AddressSpaceChangeClassifier` whitelists, the surgical raw-tag and + UNS-reference delta loops (identity-preserving in-place update versus remove + recreate, including name swaps and + id reuse across the remove and add sets), `ApplyPureRemove` ordering, the rebuild ratchet, historian provisioning + and recorder-feed hooks. The defects found are in what the *planner* never diffs (U-2, U-3), not in the routing. +- **Node add / update / remove** — `EnsureFolder`, `EnsureVariable`, `UpdateTagAttributes`, `AddReference`, + `RemoveVariableNode` (inverse `Organizes` severed), `RemoveAlarmConditionNode`, `RemoveEquipmentSubtree` / + `RemoveSubtree` (child index, notifier demotion), `RebuildAddressSpace` (subtree detach, carry-over capture). +- **Alarm conditions** — `MaterialiseAlarmCondition`, `WireAlarmNotifiers` reconcile, `ApplyConditionState` delta gate, + `ReportConditionEvent` and the deferred-delivery queue (gate versus `Lock` ordering), `WireMethodTransitionReporting`, + `HandleAlarmCommand` / `HandleNativeAlarmAck` gate ordering (authorize → standby → Primary), carry-over restore, + `ConditionRefresh` (non-cut path). +- **Monitored-item lifecycle** — create / delete / tombstone / component-cache reference balancing; revalidation lock + ordering (`QueueValue` outside `Lock`). Only the sweep cost (U-5) and the flag-off enforcement (U-1) were found. +- **Equipment write path** — gate order (authorize → standby refusal → structure check), dispatch fault handling, + token-owned revert. Only U-4 found. +- **ACL read-side gates** — `Permits`, `ResolveUnsAclSubject`, Read (every attribute gated), Browse (source check plus + per-target filtering), TranslateBrowsePath, CreateMonitoredItems, SubscribeToEvents, SetMonitoringMode; + `SessionAclDecisionCache` (generation stamping, bounds, no stale-allow path); `FailedCredentialLockout` and its + call site. +- **History** — authorization on every request including resumes; continuation-point isolation (per session, or per + principal + channel with single-use tokens and epoch/details binding); limiter and deadline plumbing (no semaphore + leak); HistoryUpdate plan-then-Primary ordering; event paging tie clusters and the multi-source merge (hand-traced, + no lost or duplicated event). +- **Projected surface** — lock-free `TryResolve` against the committed immutable map; node/byte/sample budget + accounting across rollback, renewal, removal, eviction and rebuild; lease release on every failure path traced; + `RingEventMonitoredItemQueue`; `ImportedConditionMethods`; scripted command verdict revert. + +**Read but not exhaustively proven:** `ServeRawPagedAsync` with `ReturnBounds`, `HistoryBounds`, `ReverseWalk`, +`ReverseRawReader` (no defect found, but the state space needs the paged-versus-unpaged fuzz harness, which was not run). + +**Not reviewed in full (no claim either way):** `Compatibility/Aggregates/*`, `WarmStandby.cs`, `ServerSdkTelemetry.cs`, +`SdkAddressSpaceSink.cs`, `AdvertisedAggregateFunctions.cs`, `AdvertisedHistoryCapabilities.cs`, +`OtOpcUaNodeManager.ConditionState.cs`, `OtOpcUaNodeManager.ConditionMethods.cs`, `ConditionStateRecords.cs`, +`ApplicationAlarmConditions.cs`, `OriginConditionSource.cs`, `ProjectedBrowseContinuation.cs`, the cut-path +`ConditionRefresh` variants, and the parts of `OtOpcUaSdkServer.cs` / `OpcUaApplicationHost.cs` outside the +impersonation and lockout call sites. + +**Prior-review items still present by design, not re-reported:** P3 (full all-events reconcile on (un)subscribe and +rebuild; removal is now incremental), P4 (sync-over-async history arms), P6 (hard-coded request quotas), H3 +(`ConditionRefresh` walk outside `Lock`, SDK parity), L5 (notifier folders not demoted on single-condition removal). + + diff --git a/docs/reviews/2026-12-02/03-configuration.md b/docs/reviews/2026-12-02/03-configuration.md new file mode 100644 index 000000000..2e7437a1a --- /dev/null +++ b/docs/reviews/2026-12-02/03-configuration.md @@ -0,0 +1,329 @@ +# 03 — Configuration (ConfigDb, DraftValidator, snapshot factory) + +- **Slice:** `src/Core/ZB.MOM.WW.OtOpcUa.Configuration/` +- **Commit:** master @ `708a4889c` +- **Date:** 2026-12-02 +- **Scope read in full:** `OtOpcUaConfigDbContext.cs`, `Validation/*` (DraftValidator, DraftSnapshot(+Factory), + DataConnectionValidator, DataConnectionScopeRevision, SqlTagDeployChecks, SqlCredentialGuard, + CredentialReferenceDeployChecks, HeidenhainDeployChecks, DriverInstanceIdentities, UnsSegment), `Services/*`, + `Queries/*`, `Entities/*`, DI registration. Migrations were only consulted (model snapshot) to confirm index + filters and foreign keys. +- **Scope note:** the project is ~5k hand-written lines; the other ~27k are generated migrations. The raw-tree / UNS + services, CSV import, `DeploymentArtifact` and the LocalDb cache named in the brief live in `AdminUI` / `Runtime`, + not in this project. Their code was read only where it is the caller that makes a gap in this slice reachable + (each such caller is cited). +- **Method:** static reading of the code paths and their callers. No tests were run. The prior review + (`docs/reviews/2026-10-21/03-host-controlplane-security-config.md`) was skimmed; nothing below repeats it except + C-6, which extends its finding 3.5 to call sites it did not list. + +## Summary + +| ID | Severity | Category | Confidence | Title | +|---|---|---|---|---| +| C-1 | High | bug | High | A VirtualTag name with `/` or edge whitespace passes authoring and the deploy gate, then throws in the address-space apply on every node | +| C-2 | High | bug | High | Deleting an in-use script succeeds and the deploy gate has no script-existence rule; the scripted alarm is silently dropped | +| C-3 | Medium | bug | High | ZTag / SAPID fleet-wide uniqueness is not enforced anywhere (nothing writes `ExternalIdReservation`) | +| C-4 | Medium | bug | High | `UnsTagReference.DisplayNameOverride` is never checked as a NodeId segment; an invalid one is dropped silently | +| C-5 | Medium | bug | Medium | No rule against two historized tags resolving to the same effective historian tagname | +| C-6 | Low | perf | High | Full-entity `Deployment` reads still drag `ArtifactBlob`, including the 5 s DB health probe | +| C-7 | Low | bug | High | `UnsSegment` regex uses `$`, so a name ending in a newline is accepted | +| C-8 | Low | bug | High | Two "unique" indexes are silently filtered by EF and do not cover the NULL case their comments claim | +| C-9 | Low | bug | Medium | `ClusterNode` / `ServerCluster` have no `RowVersion`; node edits are last-writer-wins on the deploy-topology flags | +| C-10 | Low | bug | High | Deploy-gate rules that can never fire, and comments that point at rules that do not exist | +| C-11 | Low | perf | Medium | `DraftSnapshotFactory` has no narrow variant; the data-connections page loads the whole ConfigDb per view and per save | + +--- + +## C-1 — VirtualTag name is never validated as a NodeId segment; an invalid one breaks the apply on every node + +- **Severity:** High +- **Category:** bug (validation gap: authoring and deploy gate both miss what the runtime rejects) +- **Confidence:** High +- **Location:** + - Gate gap: `Validation/DraftValidator.cs:689-703` (`ValidateRawNameCharset` covers RawFolder / DriverInstance / + Device / TagGroup / Tag only) and `:849-862` (`ValidateUnsSegments` covers Area / Line / Equipment only). + No rule looks at `VirtualTag.Name`. + - Authoring gap: `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsTreeService.cs:1534-1551` (`CheckVirtualTagRules` + checks script, trigger and timer only); create at `:1326-1376`, update at `:1417` (`entity.Name = input.Name`, + no trim). The modal has only `[Required]` (`Components/Shared/Uns/VirtualTagModal.razor:483`). + - Where it throws: `src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/V3NodeIds.cs:104-119` (`Uns(...)` throws + `ArgumentException` on any segment `RawPaths.ValidateSegment` rejects: empty, contains `/`, leading or trailing + whitespace), called unguarded from `AddressSpaceApplier.cs:591-594` (`UnsEquipmentVar`), used at `:1119` + (`MaterialiseEquipmentVirtualTags`) and `:356`, and from `VirtualTagHostActor.cs:400-403` (`NodeIdFor`), used at + `:196`, `:294`, `:328`. +- **Description:** the VirtualTag NodeId is `{EquipmentId}/{Name}` built through `V3NodeIds.Uns`, which validates + every segment and throws. Nothing upstream applies the same rule to `VirtualTag.Name`, so a name the identity + authority rejects is authorable and deployable. +- **Failure scenario:** a Designer names a VirtualTag `Flow/Rate`, or pastes `Speed ` with a trailing space. The + save succeeds and the deploy validates, seals and dispatches. On each node, `OpcUaPublishActor`'s materialise pass + (`OpcUaPublishActor.cs:1595`, VirtualTags are the last of the four passes) throws at + `AddressSpaceApplier.cs:1119`; the outer catch (`:1669-1673`) reports "address-space apply threw". VirtualTags + ordered after the bad one are not materialised, `_lastApplied` is not advanced, and every later deploy throws at + the same point until the tag is renamed. Separately, `VirtualTagHostActor` throws at `:196` inside its apply + handler (no try/catch around it), so VirtualTag evaluation on that node is disrupted for all equipment, not just + the one tag. One typo in one name degrades every node that receives the deploy. +- **Suggested fix:** add a `VirtualTagNameInvalid` rule to `DraftValidator` that runs + `RawPaths.ValidateSegment(v.Name)` for every VirtualTag (the same authority `V3NodeIds` uses), and call the same + check from `CheckVirtualTagRules` so the editor and the gate agree. Consider trimming on save. As defence in + depth, make `MaterialiseEquipmentVirtualTags` and `VirtualTagHostActor.NodeIdFor` skip-and-count an invalid name + rather than throw, as the reference pass already does. +- **Test to add:** `DraftValidatorTests`: a VirtualTag named `a/b`, ` a`, `a ` each yields `VirtualTagNameInvalid`. + `UnsTreeService` test: create/update with those names is refused. No existing test covers this (the validator has + no rule to test). + +## C-2 — An in-use script can be deleted, and the deploy gate does not check script existence for VirtualTags or ScriptedAlarms + +- **Severity:** High +- **Category:** bug (validation gap; silent loss of an alarm) +- **Confidence:** High +- **Location:** + - `OtOpcUaConfigDbContext.cs:728-778`: `VirtualTag.ScriptId` and `ScriptedAlarm.PredicateScriptId` are indexed + but have no `HasOne`/FK (confirmed: no `FK_VirtualTag_*` / `FK_ScriptedAlarm_*` in any migration). + - `Validation/DraftValidator.cs:497-519`: `ValidateVirtualTagTriggers` skips a missing script with the comment + "An unresolved script is reported elsewhere" (`:508`). No other rule reports it: the only script-existence + rules are `CalculationScriptMissing` / `CalculationScriptNotFound` (`:438-448`), for Calculation tags. + - `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor:225-241`: delete has no usage check; + its error text ("Likely because virtual tags or scripted alarms still reference this script") assumes a DB + constraint that does not exist. + - Consumer: `src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceComposer.cs:683-690` skips a scripted alarm + whose predicate script is missing ("the upstream draft validator is the authority that should prevent the + dangling reference"); `:648` gives a VirtualTag with a missing script an empty expression. +- **Description:** three layers each assume another one enforces the script reference. None does. +- **Failure scenario:** a Designer deletes a script from `/scripts` that is the predicate of a scripted alarm. The + delete succeeds. The next deploy passes the gate. The composer drops the alarm with a `Trace` warning, so the + condition node disappears and the alarm never fires again, with a green deploy and nothing in the AdminUI saying + so. For a VirtualTag the node deploys with an empty expression and reads Bad permanently (a timer-triggered one + also passes `VirtualTagNoEffectiveTrigger`). +- **Suggested fix:** add `VirtualTagScriptNotFound` and `ScriptedAlarmScriptNotFound` rules to `DraftValidator` + (the script-id set is already built at `:499-501`). In `ScriptEdit.DeleteAsync`, refuse when any VirtualTag, + ScriptedAlarm or Calculation tag (`TagConfig.scriptId`) names the script, and say which. Optionally add real FKs + with `Restrict` for the two typed columns. +- **Test to add:** `DraftValidatorTests`: an enabled scripted alarm and a timer-triggered VirtualTag whose script + id is absent each produce an error. AdminUI test: deleting a referenced script is refused. Current tests do not + catch this. + +## C-3 — ZTag / SAPID uniqueness is not enforced; the reservation pre-flight has no data to check + +- **Severity:** Medium +- **Category:** bug (broken invariant) +- **Confidence:** High +- **Location:** `Validation/DraftValidator.cs:905-926` (`ValidateReservationPreflight`), + `Validation/DraftSnapshotFactory.cs:101-104`, `OtOpcUaConfigDbContext.cs:455-456` (`IX_Equipment_ZTag` / + `IX_Equipment_SAPID` are non-unique), `Migrations/20260715230637_V3Initial.StoredProcedures.cs:185-194` + (`sp_PublishGeneration`, the former reservation writer, now only `RAISERROR`s). +- **Description:** the pre-flight compares each equipment's ZTag/SAPID with active `ExternalIdReservation` rows. + A repo-wide search finds no code that inserts into `ExternalIdReservations` (the only non-Configuration use is + the read-only `Reservations.razor:64`), so the table stays empty and the rule cannot fire. The rule also never + compared draft rows with each other. The equipment page still tells the user "Unique fleet-wide via + ExternalIdReservation" (`EquipmentPage.razor:120`), and `UnsTreeService` writes ZTag/SAPID with no uniqueness + check (`:845`, `:918`, `:970`). +- **Failure scenario:** two equipment rows (same or different clusters) are saved with the same ZTag, by hand or + through equipment CSV import. Both deploy. Anything downstream that resolves equipment by ZTag/SAPID gets two + matches. +- **Suggested fix:** enforce in the draft itself: a `DraftValidator` rule that groups `draft.Equipment` by ZTag and + by SAPID and reports duplicates, plus filtered unique indexes (`WHERE [ZTag] IS NOT NULL`). Then either delete + the reservation table/page/rule or restore a writer; do not leave the UI claiming an enforcement that is not there. +- **Test to add:** `DraftValidatorTests`: two equipment with equal ZTag and empty `ActiveReservations` → error. + +## C-4 — `DisplayNameOverride` is never checked as a NodeId segment; an invalid override drops the UNS variable silently + +- **Severity:** Medium +- **Category:** bug (validation gap) +- **Confidence:** High +- **Location:** `Validation/DraftValidator.cs:748-781` and `:790-845` use the override as the effective name but + never validate its characters. Authoring: `UnsTreeService.cs:283-306` (`SetReferenceOverrideAsync` trims and + checks uniqueness only). Consumer: `AddressSpaceComposer.cs:961-971` catches the `ArgumentException` from + `V3NodeIds.UnsChild` and `continue`s with the comment "dropped (deploy gate rejects invalid names)". +- **Description:** same root cause as C-1, different outcome: here the composer swallows the failure. An override + containing `/` is saved and deployed; the reference simply does not appear in the UNS namespace. +- **Failure scenario:** an operator sets the override `Temp/Inlet` on a reference. Deploy is green. The UNS node + is missing; ScadaBridge subscriptions to it return `BadNodeIdUnknown`. A `{{equip}}/Temp/Inlet` read in a script + cannot match it either. +- **Secondary inconsistency:** the validator computes the effective name with `r.DisplayNameOverride ?? tagName` + (`:765`, `:800`), while both compose seams use `string.IsNullOrEmpty(override) ? tagName : override` + (`EquipmentReferenceMap.cs:58`, `AddressSpaceComposer.cs:961`). For an empty-string override the validator + skips the row from both the uniqueness and the resolution sets while the composer materialises it under the tag + name. The UI normalises blank to null, so this needs a direct DB write or seed to reach; fix it with the rest. +- **Suggested fix:** in `ValidateUnsEffectiveLeafUniqueness`, compute the effective name with the composer's + `IsNullOrEmpty` rule and add `UnsEffectiveNameInvalid` when `RawPaths.ValidateSegment(effective)` fails; apply + the same check in `SetReferenceOverrideAsync`. +- **Test to add:** validator test with override `a/b`; validator test that an empty-string override collides with + a VirtualTag named like the backing tag. + +## C-5 — Two historized tags can resolve to the same effective historian tagname + +- **Severity:** Medium +- **Category:** bug (validation gap) +- **Confidence:** Medium (the gap in the gate is certain; the recorder's behaviour was read, not run) +- **Location:** `Validation/DraftValidator.cs:709-726` (`ValidateHistorizedTagnameLength` computes the effective + tagname per tag but only checks its length). Recorder: `Runtime/Historian/ContinuousHistorizationRecorder.cs:175-181` + keys by mux ref → set of names; nothing stops two refs carrying the same name. +- **Description:** the effective tagname is the `historianTagname` override, else the RawPath. Two owned + (non-`historianReadOnly`) tags can share one, by a copied override or an override equal to another tag's RawPath. + A search for a duplicate-tagname check in Configuration, ControlPlane and AdminUI found none. +- **Failure scenario:** a tag is duplicated in `/raw` (or CSV-imported from a template) with its + `historianTagname` override intact. Both tags are provisioned as one historian tag and both streams are recorded + into it. HistoryRead through either NodeId returns the interleaved values of two different signals. +- **Suggested fix:** in the same pass, group historized, non-read-only tags by effective tagname + (case-insensitive, since historian tagnames are) and report `HistorianTagnameDuplicate` naming the tags. Decide + explicitly whether sharing is allowed when all but one are `historianReadOnly`. +- **Test to add:** validator test: two historized tags with the same override → error; same override with + `historianReadOnly: true` on one → per the decision above. + +## C-6 — Full-entity `Deployment` reads still load `ArtifactBlob`, including the periodic health probe + +- **Severity:** Low +- **Category:** perf +- **Confidence:** High on the mechanism; the cost depends on artifact size (the blob is compressed JSON of the + whole fleet config) +- **Location:** entity `Entities/Deployment.cs:33` + `OtOpcUaConfigDbContext.cs:791` (blob is an ordinary column + on the hot row). Callers that materialise the whole entity: + - `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Health/DbHealthProbeActor.cs:99`: `db.Deployments.AsNoTracking().Take(1).ToList()` every 5 s, with a 2 s command timeout. + - `src/Server/ZB.MOM.WW.OtOpcUa.Host/Health/HealthEndpoints.cs:88`: same query on each readiness check. + - `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterOverview.razor:147`: latest deployment, full row. + - `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs:1475`: boot only; reads the row for `RevisionHash`. +- **Description:** the prior review (03 §3.5, 02 P7) projected the blob away in the coordinator and status paths; + these four remain (still present at this commit). The two probes are the ones that matter: a liveness check + transfers and allocates one whole artifact per tick. +- **Estimated cost:** one artifact (hundreds of KB to a few MB for a large fleet) read from SQL and allocated on + the LOH every 5 s per admin node, plus per readiness poll. On a slow link the 2 s timeout can turn a large blob + into a false "DB unhealthy". +- **Suggested fix:** probes: `db.Deployments.Select(d => d.DeploymentId).Take(1)` (or `Database.CanConnectAsync`). + Project in the other two. Structural fix in this slice: move `ArtifactBlob` to a table-split/owned type or a + `DeploymentArtifact` side table so a plain entity read can no longer include it. +- **Test to add:** a SQL-log assertion test that the probe query's SELECT list does not contain `ArtifactBlob`. + +## C-7 — `UnsSegment` accepts a trailing newline + +- **Severity:** Low +- **Category:** bug +- **Confidence:** High +- **Location:** `Validation/UnsSegment.cs:42` (`Pattern = "^[a-z0-9-]{1,32}$"`), `:49` (`AttributePattern`), `:56`. +- **Description:** in .NET, `$` without `RegexOptions.Multiline` also matches before a final `\n`, so `"press-1\n"` + is valid. `DataConnectionValidator.cs:95` in the same project already uses `\A…\z`. +- **Failure scenario:** an Area/Line/Equipment name with a trailing newline arrives through equipment CSV import + (a quoted RFC-4180 field) or the API. It passes authoring (`UnsTreeService.cs:899`) and + `ValidateUnsSegments`. `V3NodeIds.Uns` then rejects it (trailing whitespace) and the applier skips the equipment + folder (`AddressSpaceApplier.cs:1324`), so the equipment is missing after a green deploy. The DB also treats + `press-1` and `press-1\n` as different names. +- **Suggested fix:** `\A[a-z0-9-]{1,32}\z` in both patterns (the attribute pattern feeds + `[RegularExpression]`, which has the same `$` behaviour). +- **Test to add:** `UnsSegment.IsValid("abc\n")` is false. + +## C-8 — Two unique indexes are filtered by EF and do not cover the NULL case + +- **Severity:** Low +- **Category:** bug (schema does not enforce the stated invariant) +- **Confidence:** High (confirmed in `Migrations/OtOpcUaConfigDbContextModelSnapshot.cs:979-982` and `:1047-1050`) +- **Location:** `OtOpcUaConfigDbContext.cs:670-676` (`UX_LdapGroupRoleMapping_Group_Cluster`) and `:563-564` + (`UX_NodeAcl_PrincipalScope`). +- **Description:** the SQL Server provider adds `WHERE [col] IS NOT NULL` to a unique index over a nullable + column unless a filter is set explicitly. The generated indexes are therefore filtered on `[ClusterId] IS NOT NULL` + and `[ScopeId] IS NOT NULL`. The comment at `:670-673` says a NULL `ClusterId` is "its own bucket" and that + uniqueness is "one row per (LdapGroup, ClusterId)"; in fact system-wide rows are not constrained at all, and + neither are Cluster-kind ACL rows (the only kind with a NULL `ScopeId`). +- **Failure scenario:** `LdapGroupRoleMappingService.CreateAsync` (`Services/LdapGroupRoleMappingService.cs:53-65`) + has no duplicate check, so the same LDAP group can be given any number of system-wide rows, including with + different roles. The same principal can hold several Cluster-scope ACL rows in one cluster. Effects are + duplicate/contradictory grants in the UI and a revoke that removes one row while another still grants. +- **Suggested fix:** declare the intent explicitly: `.HasFilter(null)` on both indexes (SQL Server then allows one + NULL per leading-key combination), or add second filtered indexes for the NULL case as the RawFolder/Tag + indexes do. Needs a migration and a pre-check for existing duplicates. Fix the comment. +- **Test to add:** SQL Server schema test: inserting two system-wide mappings for one group fails; two + Cluster-scope ACLs for one principal+cluster fail. + +## C-9 — `ClusterNode` and `ServerCluster` have no concurrency token + +- **Severity:** Low +- **Category:** bug (lost update) +- **Confidence:** Medium +- **Location:** `Entities/ClusterNode.cs`, `Entities/ServerCluster.cs` (no `RowVersion`); + `OtOpcUaConfigDbContext.cs:174-231`. Every other authored entity has one. Editor: + `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/NodeEdit.razor:251-262` reloads the row and + assigns every form field. +- **Description:** `ClusterNode.Enabled` (with `MaintenanceMode`) defines the expected-ack set for a deploy + (`ConfigPublishCoordinator.cs:1062-1068`) and is checked by `ValidateClusterTopology`. With no token, a stale + form overwrites a concurrent change without warning. +- **Failure scenario:** user A opens a node's edit page. User B disables that node for maintenance. A saves an + unrelated field; the form's stale `Enabled = true` is written back. The next deploy waits on a node that is down. +- **Related:** `NodeDeploymentState.NodeId` → `ClusterNode` is `Restrict` (`:814`), so deleting a node that has + ever been deployed to fails with a raw FK error surfaced as `ex.Message` (`NodeEdit.razor:286-292`). +- **Suggested fix:** add `RowVersion` to both entities and set `OriginalValue` in the edit pages like the other + pages do. For delete, either remove the node's `NodeDeploymentState` rows in the same transaction or report the + constraint in words. +- **Test to add:** concurrency test on node edit (stale token → "another user changed…"). + +## C-10 — Dead deploy-gate rules and comments that cite rules which do not exist + +- **Severity:** Low +- **Category:** bug (maintenance hazard; this is how C-1, C-2 and C-4 went unnoticed) +- **Confidence:** High +- **Location / detail:** + - `DraftValidator.cs:890-903` `ValidateEquipmentUuidImmutability`: `PriorEquipment` is always `[]` + (`DraftSnapshotFactory.cs:100`), so the rule never fires. UUID immutability rests only on the UI not offering + the field. + - `DraftValidator.cs:865-888` `ValidatePathLength`: `Enterprise`/`Site` are always null, so the bound is + 32+32+32+32+32+4 = 164 < 200 once `UnsSegment` holds. It cannot fire on a valid draft. + - `DraftValidator.cs:454` ("broken chain — flagged by the charset rule") and `:717-718` ("a separate + rule/charset check flags that"): the charset rule checks names, not parent chains. No rule reports a Tag whose + Device, a Device whose DriverInstance, or a reference whose Tag/Equipment is missing; composers `continue` + past them (`EquipmentReferenceMap.cs:56-60`, `AddressSpaceComposer.cs:957-960`). These FKs are logical only + (`OtOpcUaConfigDbContext.cs:271-274`, `:416-417`, `:701-703`), and the service-layer "is it empty" checks are + not serialised against a concurrent add. + - `DraftValidator.cs:508`: see C-2. +- **Failure scenario (orphan case):** user A deletes an empty Device while user B adds a Tag under it. Both + commit. The tag has no RawPath, is skipped by every rule and every composer, and stays in the DB invisibly. +- **Suggested fix:** add one `DanglingReference` rule over the logical FKs (Tag→Device, Tag→TagGroup, + Device→Driver, TagGroup→Device/parent, Driver→RawFolder, Line→Area, Equipment→Line, Reference→Tag/Equipment, + VirtualTag/ScriptedAlarm→Equipment). The lookup maps already exist in `ValidateNodeAclScopes`. Delete or + repurpose the two dead rules. +- **Test to add:** one validator test per dangling link. + +## C-11 — The only snapshot loader is whole-DB; the data-connections page uses it per view and per save + +- **Severity:** Low +- **Category:** perf +- **Confidence:** Medium (cost scales with fleet size; not measured) +- **Location:** `Validation/DraftSnapshotFactory.cs:68-105` (20 sequential full-table reads, including every + `Tag.TagConfig`, every `Script.SourceCode` and all `ApiKeys`). Callers outside the deploy path: + `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataConnectionAdminService.cs:20` (page load), `:53` + (save), `:79` (delete). +- **Description:** the deploy path needs the full snapshot. `DataConnectionValidator` does not use Scripts, + PollGroups, NodeAcls, ApiKeys or reservations, and from Tags needs only id/device/group/name plus the alarm bit. + Each save also runs the validator twice (baseline and after), and its `Owner` / `LocalCollision` helpers are + linear `FirstOrDefault` scans per mapping/export (`DataConnectionValidator.cs:170-232`). +- **Estimated cost:** at 50k tags, tens of MB materialised per page view and per save inside a SNAPSHOT + transaction, to edit one row. +- **Suggested fix:** add a `FromConfigDbAsync` overload (or a `DataConnectionSnapshot`) that skips the unused + tables and projects Tags; build id→row dictionaries once inside `DataConnectionValidator.Validate`. +- **Test to add:** none needed for correctness; a query-count/SQL-log test would pin the narrower load. + +--- + +## Areas reviewed with no findings + +- **`DraftSnapshotFactory` transaction handling:** SNAPSHOT transaction owned only when none is ambient, committed + after a read-only pass, every composed table read `AsNoTracking` and ordered server-side by natural key (hash + stability). Correct as written. +- **`ValidateNodeAclScopes`:** existence, containment and cross-cluster checks; lookup maps built once; comparison + rules match the documented resolver behaviour. No gap found. +- **`ValidateCalculationTags`, `ValidateVirtualTagTriggers`, `ValidateVirtualTagDependencyCycles`:** cycle graph + construction and the calc-only de-duplication are consistent; `{{equip}}` substitution uses the shared + `EquipmentReferenceMap`. Script sources are re-scanned per tag (minor, not reported). +- **`ValidateUnsEffectiveLeafUniqueness` vs `EffectiveNameGuard`:** both ordinal, same three sources; agree apart + from the empty-override case noted in C-4. +- **`DataConnectionValidator`:** endpoint, secret-reference, consumer-scope, self-route, projection-loop and limit + rules read through; authoring vs `ValidateDeployed` tolerance is deliberate. Only the linear scans (C-11). +- **`DataConnectionScopeRevision.Advance`:** called after validation, so its unguarded `ToUpperInvariant` calls see + non-null values for enabled rows. +- **`SqlTagDeployChecks`, `SqlCredentialGuard`, `CredentialReferenceDeployChecks`, `HeidenhainDeployChecks`, + `DriverInstanceIdentities`:** JSON handling is exception-safe (`DriverDeviceConfigMerger.Merge` always yields an + object); loops are O(drivers × tags) only for the specific driver types. +- **`LdapGroupRoleMappingService`, `ClusterAuditQuery`:** context per call, `AsNoTracking`, translatable + predicates. `ClusterAuditQuery`'s `ClusterId = @c OR (ClusterId IS NULL AND NodeId IN …)` predicate may not seek + on `IX_ConfigAuditLog_Cluster_Time` once the audit table is large; the plan was not checked, so it is not + reported as a finding. +- **`ServiceCollectionExtensions`:** pooled factory plus the scoped bridge for DataProtection; no captured state. +- **Index coverage for the hot queries seen in callers** (`NodeDeploymentState` by node, `Deployment` by status / + created-at, `UnsTagReference` by equipment and tag, `Tag` by device): adequate. +- **EF translatability:** no client-evaluated or untranslatable query found in this project. diff --git a/docs/reviews/2026-12-02/04-adminui-security.md b/docs/reviews/2026-12-02/04-adminui-security.md new file mode 100644 index 000000000..b60e9730c --- /dev/null +++ b/docs/reviews/2026-12-02/04-adminui-security.md @@ -0,0 +1,160 @@ +# Code review 2026-12-02 — 04: AdminUI + Security + +- **Scope:** `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/` (C#, `.razor`, `wwwroot/js`) and `src/Server/ZB.MOM.WW.OtOpcUa.Security/`. +- **Commit:** master @ `708a4889c`. Read-only review; nothing was built or run — every finding is from reading the code and its callers. +- **Prior review:** `docs/reviews/2026-10-21/04-adminui.md` (L1–L5, S1–S7, P1–P9, H1–H3) was spot-checked and its items are remediated (see the last section). Nothing below repeats it. None of the findings overlaps the open issues #969, #959, #932, #924, #915, #755, #616, #614, #592. +- **Coverage note:** the pages, services, hubs, endpoints, JS and the whole Security project were read. The per-driver form/tag-editor components (`Components/Shared/Drivers/Forms/*`, `Uns/TagEditors/*`), `RawBrowseModal`, `RawTree`, `AclScopeService` and `CsvColumnMap` were only skimmed or grepped — treat them as not reviewed in depth. + +Severity order: A-1, A-2 (High/Medium security), A-3, A-4, A-5 (Medium), A-6 … A-9 (Low). + +--- + +## A-1 — `/fleet/diagnostics` lets any signed-in user make the admin node open an Akka remoting association to an arbitrary host + +- **Severity:** High +- **Category:** bug (security — authz / SSRF into the control plane) +- **Confidence:** High that the association is attempted with caller-chosen `host:port`; Medium on how far a hostile peer can take it (depends on network position and Akka serializer exposure, which is outside this slice). +- **Location:** + - `AdminUI/Components/Pages/FleetDiagnostics.razor:175-176` (`[SupplyParameterFromQuery(Name="node")]`), `:196-206` (`OnParametersSetAsync` → `LoadAsync`), `:47-51` (free-text "Host:port" box), `:245` (`NodeId.Parse(_selectedNode)`) + - `AdminUI/Clients/FleetDiagnosticsClient.cs:49-53` (`_system.ActorSelection($"akka.tcp://{_systemName}@{nodeId.Value}/user/driver-host")` + `Ask`) + - `Core/Commons/Types/NodeId.cs` (`Parse` only rejects blank) + - Page policy: `AdminUiPolicies.AuthenticatedRead` (any role, and any bearer token). +- **Description:** The page takes the target node from the `?node=` query string or the typed box and passes it, unvalidated, into an Akka actor path. It is never checked against the `_members` list the page itself builds, nor against `ClusterNode` rows. `Ask` on a remote `ActorSelection` makes Akka.Remote open an outbound association to whatever address is named. `WithRemoting` (`Core/Cluster/ServiceCollectionExtensions.cs:147`) configures no TLS, and no untrusted-mode / trusted-selection settings were found in the cluster HOCON, so an associated peer is treated like any other remote system. +- **Failure scenario:** A Viewer-role user (or anyone holding a `/auth/token` bearer) opens `/fleet/diagnostics?node=attacker-host:4053`. The central admin node dials `attacker-host:4053` from inside the control-plane network. Minimum impact is an internal port/host probe from the admin node (the page distinguishes "answered" from "empty snapshot" after 3 s). If the attacker runs an Akka endpoint there, they hold a live remoting association with the admin `ActorSystem` — a channel that the firewall would not have allowed inbound — over which remote messages to control-plane actors and serializer payloads can be delivered, bypassing every AdminUI role check. The value is also interpolated into the path, so `host:port/user/x` re-targets the `GetDiagnostics` message at a different actor path on a legitimate node (harmless message, but not intended). +- **Suggested fix:** Resolve the target server-side from a closed set: accept only a value equal (case-insensitive) to an Up driver member or to `Host:AkkaPort` of an enabled `ClusterNode` row; otherwise show "unknown node" and do not call the client. Remove the free-text box or apply the same check to it. Add the same guard inside `FleetDiagnosticsClient` (reject anything not matching `^[A-Za-z0-9.-]+:\d{1,5}$` as defence in depth). Consider raising the page to `DriverOperator`. +- **Test to add:** bUnit/page-model test: `?node=evil.example:4053` (not a member, not a `ClusterNode` row) → `IFleetDiagnosticsClient.GetDiagnosticsAsync` is never called. Client test: a value containing `/` or `@` is rejected before `ActorSelection`. + +--- + +## A-2 — AdminUI roles are frozen at sign-in: a sliding cookie and open Blazor circuits never re-check LDAP membership or role grants + +- **Severity:** Medium +- **Category:** bug (security — authz revocation gap) +- **Confidence:** High +- **Location:** + - `Security/Endpoints/AuthEndpoints.cs:149-163` (roles baked into the cookie claims at login) + - `Security/ServiceCollectionExtensions.cs:148-157, 162-187` (`AddCookie` with no `Events.OnValidatePrincipal`; `ZbCookieDefaults.Apply` sets `SlidingExpiration = true`, 30 min idle) + - No `RevalidatingServerAuthenticationStateProvider` (or any `AuthenticationStateProvider` override) is registered anywhere in `AdminUI` / `Security`. +- **Description:** Group→role resolution (`OtOpcUaGroupRoleMapper`: appsettings `GroupToRole` + DB `LdapGroupRoleMapping`) runs once, in `/auth/login`. The cookie then slides for as long as the browser makes a request every 30 minutes, with nothing re-validating the principal. Separately, an interactive Blazor circuit captures the `AuthenticationState` when it connects and keeps it for the life of the SignalR connection — cookie expiry does not end an open circuit. The code already recognises this risk for bearer tokens (`AuthEndpoints.cs:54-56`: a self-renewing bearer would outlive "the user's LDAP membership"), but the cookie has the same property. +- **Failure scenario:** An Administrator is removed from the LDAP admin group, or a FleetAdmin deletes their row on `/role-grants`. The user keeps a tab on `/raw` or `/admin/api-keys` open: every in-page check (`AuthorizeView`, `IAuthorizationService.AuthorizeAsync(auth.User, …)`) still sees the old claims, so they can go on editing configuration, minting API keys and starting deployments indefinitely. Even after closing the tab, any request within 30 minutes renews the cookie with the stale roles. Only an explicit logout or 30 idle minutes ends it. +- **Suggested fix:** Add `CookieAuthenticationEvents.OnValidatePrincipal` that, at most every N minutes (stamp an `iat`-style claim), re-runs the group lookup + `IGroupRoleMapper` and either replaces the principal (`ShouldRenew`) or calls `RejectPrincipal` + sign-out. Register a `RevalidatingServerAuthenticationStateProvider` with the same check so open circuits are covered. Consider an absolute session lifetime in `OtOpcUaCookieOptions`. +- **Test to add:** WebApplicationFactory test: sign in as a mapped user, delete the mapping, advance the clock past the revalidation interval → a `ConfigEditor` endpoint answers 302/401. Unit test for the revalidating provider returning `false` when the mapper yields no role. + +--- + +## A-3 — Creating or renaming an Area, Line or Equipment to a name that already exists under the same parent throws an unhandled `DbUpdateException` + +- **Severity:** Medium +- **Category:** bug +- **Confidence:** High +- **Location:** + - `AdminUI/Uns/UnsTreeService.cs:619-644` (`CreateAreaAsync`), `:647-681` (`UpdateAreaAsync`), `:717-742` / `:745-781` (line create/update), `:815-860` (`CreateEquipmentAsync`), `:941-992` (`UpdateEquipmentAsync`), `:863-938` (`ImportEquipmentAsync`) + - Unique indexes: `Configuration/OtOpcUaConfigDbContext.cs:311` (`UX_UnsArea_ClusterName`), `:330` (`UX_UnsLine_AreaName`), `:453` (`UX_Equipment_LinePath`) + - Callers with no catch: `Components/Shared/Uns/AreaModal.razor:128-135` (try/finally only), `Components/Pages/Uns/EquipmentPage.razor:846-851` (`catch when (!Current(...))` only), `Components/Shared/Uns/ImportEquipmentModal.razor:136-142` (same). +- **Description:** The service pre-checks only the logical id (`UnsAreaId`, `UnsLineId`) or `MachineCode`. It never checks `(ClusterId, Name)`, `(UnsAreaId, Name)` or `(UnsLineId, Name)`, which the database enforces with unique indexes. The create paths call `SaveChangesAsync` bare; the update paths catch only `DbUpdateConcurrencyException`, which a unique-index violation is not. Contrast `RawTreeService`, `CreateVirtualTagAsync` (`:1350`) and `CreateScriptedAlarmAsync` (`:1666`), which all pre-check sibling names. The EF InMemory provider used by the unit tests does not enforce unique indexes, which is why this is green. +- **Failure scenario:** An author adds an area named `Assembly` to a cluster that already has one (or renames a line/equipment onto a sibling's name, or moves equipment to a line that already has that name). SQL Server rejects the insert; the exception escapes the event handler and `PageErrorBoundary` replaces the whole `/uns` or equipment page with "DbUpdateException: An error occurred while saving the entity changes" — the modal and the typed values are gone and the message does not say what was wrong. For the CSV import, one duplicate `(UnsLineId, Name)` pair anywhere in the file (or against an existing row with a different MachineCode) fails the entire batch the same way, with no row named. A `Manufacturer`/`Model` cell longer than 64 characters does the same (no length validation on import). +- **Suggested fix:** Add sibling-name `AnyAsync` pre-checks (excluding self on update) to the six create/update methods and return `UnsMutationResult(false, "An area named 'X' already exists in this cluster.")`. In `ImportEquipmentAsync`, track `(UnsLineId, Name)` in a seen-set seeded from the DB and report the row as an error; validate column lengths. Wrap every `SaveChangesAsync` in these methods with `catch (DbUpdateException)` → friendly result, as `SaveCreateAsync` in `RawTreeService` does, to cover the concurrent-insert race. +- **Test to add:** SQL-Server-backed (or SQLite) tests in `AdminUI.Tests`: duplicate area name in a cluster, duplicate line name in an area, duplicate equipment name on a line (create, update, import) each return `Ok == false` with a message and do not throw. + +--- + +## A-4 — Saving a Galaxy ack identity without retyping the password silently overwrites the stored password with an empty string + +- **Severity:** Medium +- **Category:** bug +- **Confidence:** High +- **Location:** + - `AdminUI/Components/Pages/ApiKeys.razor:304-319` (`OpenAckEditor` pre-fills user/domain, sets `_ackPassword = ""`), `:329-342` (`SaveAckIdentityAsync` passes it straight through) + - `AdminUI/ApiKeyAck/ApiKeyGalaxyAckIdentityService.cs:97-116` (`SetAsync` upserts `password ?? string.Empty`, password first, no emptiness check) +- **Description:** The editor opens an existing identity with the user and domain filled in and the password blank (correctly never rendered back). Neither the page nor the service distinguishes "leave the password unchanged" from "set it to empty": Save always upserts the password secret with whatever is in the box. +- **Failure scenario:** A FleetAdmin opens "Ack identity" on a working key to correct the domain, changes only that field and clicks Save. The password secret `otopcua/apikeys//galaxy-ack-password` is replaced by an empty value. The service's own comment notes the driver "refuses a user without a password", so every native Galaxy alarm acknowledge from sessions on that key (including remote acks through a data export with `AllowGalaxyServiceAck`) now fails until someone notices and re-enters the password. The page shows success and the list still shows the identity. +- **Suggested fix:** In `SetAsync`, when `password` is null/empty and the user secret already exists, leave the password secret untouched; when no identity exists yet, reject an empty password (`ArgumentException`, which the page already surfaces in `_error`). Add a placeholder "leave blank to keep the current password" on the field. +- **Test to add:** Service test: set identity with password `p1`, call `SetAsync` with a new domain and empty password → password secret still decrypts to `p1`. Second test: first-time set with an empty password throws. + +--- + +## A-5 — The data-connections page loads and holds the entire fleet configuration per circuit, and re-reads it (plus full deployment artifacts) on every save + +- **Severity:** Medium +- **Category:** perf +- **Confidence:** High on the code path; cost figures are estimates. +- **Location:** + - `AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor:169-181` (`Reload`), `:164-168` (per-render computed properties), `:117` and `:136` (`ExportRoots` / `RemoteRoots` `