docs(review): 2026-12-02 full code review (10 slices, ~150 findings) + remediation plan
Tracked as #971-#1002.
This commit is contained in:
@@ -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).
|
||||
@@ -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<ulong, long>(_versions)` plus a new `HashSet<ulong>`;
|
||||
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`.
|
||||
@@ -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<NodeId, List<item>>` 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<Variant>` 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<string>` 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<ProjectedMonitoredItem>()) 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<NodeId, List<ProjectedMonitoredItem>>` 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).
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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/<keyId>/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` `<option>` lists), `:222-267`
|
||||
- `AdminUI/DataConnections/DataConnectionAdminService.cs:16-21` (`LoadAsync`), `:22-45` (`LoadAppliedAsync`), `:47-71` / `:73-94` (`SaveAsync` / `DeleteAsync`)
|
||||
- `Core/Configuration/Validation/DraftSnapshotFactory.cs:56-103` (reads every config table)
|
||||
- **Description:** Three compounding costs on a page that only needs three small tables plus some picker labels:
|
||||
1. `LoadAsync` calls `DraftSnapshotFactory.FromConfigDbAsync`, which materialises **every** config table fleet-wide as full entities — all `Tags` with `TagConfig`, all `Scripts` with `SourceCode`, `NodeAcls`, and `ApiKeys` rows — inside a SNAPSHOT transaction. The page keeps that object in `_snapshot` for the life of the circuit. The page is `AuthenticatedRead`, so any signed-in user can do this per tab.
|
||||
2. `LoadAppliedAsync` loops the cluster's nodes and, for each, fetches the whole `Deployment.ArtifactBlob` (the gzip of the fleet config) and parses it. Two nodes on the same deployment fetch and inflate the same blob twice. This runs on every `Reload`, i.e. on page open and after every save/delete.
|
||||
3. `SaveAsync`/`DeleteAsync` each load the full snapshot again and run `DataConnectionValidator.Validate` over it twice (baseline + after).
|
||||
In the editors, the export-root `<select>` renders one `<option>` per raw tag in the cluster and per UNS reference/virtual tag, and the remote-root `<select>` one per tag of the target cluster; these are rebuilt from the snapshot on every render (each `@bind` change re-renders).
|
||||
- **Failure scenario:** On a fleet with 50k tags and a few hundred scripts, opening the page costs a full-fleet read (tens of MB of entities) that stays pinned per open tab; saving one connection draft costs two more full reads, two validations and N artifact downloads before the handler returns. Opening "New export" pushes ~50k `<option>` elements over the circuit (several MB in one render batch) and each subsequent checkbox click re-diffs them. A handful of users on this page noticeably loads the admin node and ConfigDb; the SNAPSHOT transactions also hold version-store rows for the duration.
|
||||
- **Suggested fix:** Give the page its own narrow read model: the three connection tables for the cluster, `ClusterNode` rows, and id/name projections for the pickers (no `TagConfig`, `SourceCode`, ACLs or API keys). Replace the tag-level `<select>` with the existing `RawTree` picker or a typed-id field with server-side validation. In `LoadAppliedAsync`, resolve distinct deployment ids first and parse each blob once (or reuse the per-deployment cache pattern from `Hosts/DeployedDriverSet.cs`). Keep the full-snapshot validation in `SaveAsync` if the rules need it, but do not hold the snapshot in the component.
|
||||
- **Test to add:** Query-count test with a logging interceptor: opening the page issues no query against `Tag.TagConfig` / `Script.SourceCode`; `LoadAppliedAsync` for two nodes on one deployment reads the blob once.
|
||||
|
||||
---
|
||||
|
||||
## A-6 — `BrowseSessionReaper` never drains open browse sessions on shutdown
|
||||
|
||||
- **Severity:** Low
|
||||
- **Category:** bug (resource cleanup)
|
||||
- **Confidence:** High
|
||||
- **Location:** `AdminUI/Browsing/BrowseSessionReaper.cs:24-37` (`ExecuteAsync`), `:60-68` (`DrainAllAsync`)
|
||||
- **Description:** The loop is `while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))`. When the host stops, `WaitForNextTickAsync` throws `OperationCanceledException` (it does not return `false`), so control leaves `ExecuteAsync` by exception and the `await DrainAllAsync()` after the loop is never reached. There is no `StopAsync` override.
|
||||
- **Failure scenario:** An admin node is stopped or restarted while authors have address pickers open. The OPC UA client sessions, MQTT connections and mxaccessgw browse sessions held in `BrowseSessionRegistry` are abandoned rather than closed: the remote OPC UA server keeps the session until its timeout, and the gateway keeps a browse session/worker until its own idle reaping.
|
||||
- **Suggested fix:** Wrap the loop in `try { … } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { }` and call `DrainAllAsync()` in a `finally`.
|
||||
- **Test to add:** Register a fake `IBrowseSession`, start the service, cancel the stopping token, await `ExecuteTask` → the session's `DisposeAsync` was called and the registry is empty.
|
||||
|
||||
---
|
||||
|
||||
## A-7 — Telemetry dial to a node with no driver snapshots is cut and re-dialled forever, with an unthrottled warning
|
||||
|
||||
- **Severity:** Low
|
||||
- **Category:** bug
|
||||
- **Confidence:** Medium (the supervisor logic is verified; that a driver-less node's hub replays nothing on subscribe is inferred from the design notes, not traced into `TelemetryLocalHub`)
|
||||
- **Location:** `AdminUI/Telemetry/TelemetryDialSupervisor.cs` — `HandleDialDeadline` (`:311-326`), `HandleTelemetryReceived` (`Connected` flips only on the first routed record), `StartDialer` (arms the deadline per dial)
|
||||
- **Description:** A dial counts as established only when the first telemetry record arrives; until then the `CallTimeoutSeconds` deadline cancels it and reconnects. The comment assumes "a live node answers a fresh subscribe at once" because the node replays its health/resilience snapshots — but a node with no driver instances (new site node before its first deployment, or a node whose drivers were all removed and evicted) has nothing to replay and may have no alarms or script logs either. The wire has no hello/heartbeat record.
|
||||
- **Failure scenario:** Such a node is healthy and its stream is open, yet every `CallTimeoutSeconds` the supervisor cancels the stream, logs "delivered nothing within Ns; cancelling it and re-dialing" at Warning (this line is not covered by the failure-streak throttle), waits the backoff and dials again — indefinitely. If every dialled node is in that state the `/alerts` and `/script-log` pill reads disconnected. Any alarm or log line published in the backoff gap is not shown.
|
||||
- **Suggested fix:** Have the node send one "subscribed" record (or an empty snapshot marker) at stream start and treat it as establishment; or mark the dialer connected when the response headers arrive rather than on the first record. Apply the streak throttle to the deadline warning.
|
||||
- **Test to add:** Supervisor test with a dial loop that connects and stays silent: after 3× the deadline the dial has not been cancelled (once a subscribed marker exists), or at minimum only one Warning was logged.
|
||||
|
||||
---
|
||||
|
||||
## A-8 — `/reservations` reads and renders the whole `ExternalIdReservations` table, released rows included, with no paging
|
||||
|
||||
- **Severity:** Low
|
||||
- **Category:** perf
|
||||
- **Confidence:** High
|
||||
- **Location:** `AdminUI/Components/Pages/Reservations.razor:61-67`
|
||||
- **Description:** `OnInitializedAsync` loads every reservation row (active and released, full entities) ordered by kind/value and the markup renders all of them. Released rows accumulate for the life of the database. Compare `ClusterAudit.razor`, which caps at `PageSize = 200`.
|
||||
- **Failure scenario:** A fleet with a few thousand equipment and some churn yields tens of thousands of rows; each page open sends them all in one render batch (and once more for the prerender), from a page any signed-in user can open.
|
||||
- **Suggested fix:** Default to active rows (`ReleasedAt == null`), project only displayed columns, and add `Take(N)` with a "show released / load more" control.
|
||||
- **Test to add:** Page test seeded with 1,000 rows renders at most the page size and shows the total.
|
||||
|
||||
---
|
||||
|
||||
## A-9 — Deleting an API key leaves the list stale and the ack secret behind when the secret clean-up fails
|
||||
|
||||
- **Severity:** Low
|
||||
- **Category:** bug
|
||||
- **Confidence:** High
|
||||
- **Location:** `AdminUI/Components/Pages/ApiKeys.razor:288-301` (`DeleteAsync`)
|
||||
- **Description:** The handler deletes the key, then clears its Galaxy ack identity, then reloads — all in one `try`. If `AckIdentities.ClearAsync` throws (Secrets store unavailable — the same condition `ReloadAsync` already tolerates for listing), `ReloadAsync` is skipped.
|
||||
- **Failure scenario:** The key is gone from the database, but the page still lists it with live Revoke / Ack identity / Delete buttons and shows only the secret-store error; the `otopcua/apikeys/<keyId>/galaxy-ack-*` secrets stay in the store with no remaining UI path to remove them (the key row that exposed the editor no longer exists after a refresh).
|
||||
- **Suggested fix:** Clear the ack identity first (it is idempotent), or reload in a `finally`; report "key deleted, ack identity clean-up failed — remove secrets X/Y manually" when the second step fails.
|
||||
- **Test to add:** Page test with an `IApiKeyGalaxyAckIdentityService` whose `ClearAsync` throws: after delete, the key is no longer listed and the error names the leftover secrets.
|
||||
|
||||
---
|
||||
|
||||
## Areas reviewed with no findings
|
||||
|
||||
- **Page hygiene:** all 32 routable pages carry a non-bare `[Authorize(Policy = …)]` (Login is `AllowAnonymous`); every interactive page wraps its body in `<PageErrorBoundary>` (Account, Home and Login are static). No `@x[..N]` slicing of DB strings in Razor; no `MarkupString`, `innerHTML` or `eval` anywhere in `.razor`/`.cs`/project JS.
|
||||
- **Mutations on read-only pages:** Alerts, Certificates, ClusterRedundancy, ClusterDataConnections, DriverStatusPanel and the address pickers re-check the policy server-side at action time (`IAuthorizationService.AuthorizeAsync`), not only at render.
|
||||
- **Endpoints:** `/api/script-analysis/*` and `/api/raw/tags.csv` require `ConfigEditor`; `/api/deployments` uses a fixed-time key compare and is disabled when unconfigured; `/auth/token` is cookie-scheme-only; `returnUrl` is restricted to well-formed relative URLs; hubs are `[Authorize]`.
|
||||
- **Security project:** JWT validation parameters pin HS256, issuer, audience and zero clock skew and are shared between mint and validate; no-role sign-ins and no-role tokens are refused; LDAP fails closed on plaintext transport and on mapper faults.
|
||||
- **Timers / subscriptions / disposal:** Hosts, Fleet, AlarmsHistorian, Alerts, ScriptLog, DriverStatusPanel, DriverTestConnectButton, `CoalescingRenderScheduler`, `LiveTailBuffer` — unsubscribe-before-drain, overlap guards and `_disposed` checks are in place. Prior L1–L5 and P4/P7 are fixed.
|
||||
- **DbContext lifetime:** every service and page uses `IDbContextFactory` with a context per operation; no circuit-scoped `DbContext`.
|
||||
- **Script editor:** `ScriptAnalysisService` derives from a shared base compilation, honours request cancellation and bounds markers; `monaco-init.js` sequences diagnostics, aborts superseded requests and syncs text only on blur/save under the hub size limit. Prior P1–P3, P9, S2–S3 are fixed; `/scripts` no longer loads `SourceCode` (P8).
|
||||
- **CSV:** equipment import now uses the shared RFC-4180 `CsvParser` (S6 fixed); raw-tag import is all-or-nothing with intra-batch duplicate detection; export streams over HTTP rather than the circuit (P6 fixed).
|
||||
- **`RawTreeService`:** sibling-name pre-checks, row-version concurrency and batched reference checks throughout.
|
||||
- **`CertificateStoreManager`:** thumbprint is validated as 40/64 hex before any path is built; store names come from a closed set.
|
||||
- **`DeploymentDriftProbe`, `DeployedDriverSet`, `DeployApiEndpoints`, gRPC services (`CentralCommandGrpcService`, `DeploymentArtifactGrpcService`):** no findings in this slice (their PSK/API-key interceptors live in the Host project and were not reviewed here).
|
||||
@@ -0,0 +1,289 @@
|
||||
# 05 — Host / ControlPlane / Cluster review
|
||||
|
||||
- **Date:** 2026-12-02
|
||||
- **Commit:** master @ `708a4889c`
|
||||
- **Scope:** `src/Server/ZB.MOM.WW.OtOpcUa.Host/`, `src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/`,
|
||||
`src/Core/ZB.MOM.WW.OtOpcUa.Cluster/`
|
||||
- **Method:** code reading with callers traced; no builds or tests were run, and nothing was reproduced on a
|
||||
live rig. Each finding says what was and was not verified.
|
||||
- **Prior review:** `docs/reviews/2026-10-21/02-runtime-cluster.md` and `03-host-controlplane-security-config.md`
|
||||
were skimmed. Their findings in this slice are remediated in the code read here, except the residue of
|
||||
03 §2.6 reported as H-2.
|
||||
- **Depth caveat:** the ControlPlane and Cluster projects and the Host lifecycle / health / mesh-gRPC files were
|
||||
read in full. `OtOpcUaServerHostedService` was read for control flow only. The data-plane auth files
|
||||
(`BoundedApiKeyStore`, `ConfigDbApiKeyStore`, `ApiKeyOpcUaUserAuthenticator`), `DataConnection*`,
|
||||
`RoslynVirtualTagEvaluator`, `LocalDbSetup` and `AlarmSfLegacyMigrator` were **not** reviewed in depth — no
|
||||
conclusion is offered on them.
|
||||
|
||||
| ID | Severity | Category | Confidence | Title |
|
||||
|---|---|---|---|---|
|
||||
| H-1 | High | bug | Medium | A node that leaves or is downed stops as a *clean* Windows service stop, so `sc.exe failure` never restarts it |
|
||||
| H-2 | Medium | bug | High | `AuditWriterActor` drops the whole buffered batch on a transient ConfigDb failure |
|
||||
| H-3 | Medium | bug | High | `RestartDriver` / `ReconnectDriver` report failure for a command that was already dispatched, and hold the AdminOps mailbox across DB I/O |
|
||||
| H-4 | Low | bug | Medium | `ConfigPublishCoordinator.HandleDispatch` supersedes a different in-flight deployment without closing it |
|
||||
| H-5 | Low | bug | High | An HTTPS URL binding disables every mesh listener with only a log line; the node still boots and reports ready |
|
||||
| H-6 | Low | perf | Medium | Synchronous EF calls on the deploy-coordinator singleton thread serialise connect timeouts during a ConfigDb outage |
|
||||
|
||||
---
|
||||
|
||||
## H-1 — A node that leaves or is downed stops as a clean Windows service stop, so `sc.exe failure` never restarts it
|
||||
|
||||
- **Severity:** High
|
||||
- **Category:** bug
|
||||
- **Confidence:** Medium — the code path is verified; the Windows SCM behaviour is from documented semantics and
|
||||
was not reproduced (this review ran on macOS). Worth a 10-minute check on a Windows box before acting.
|
||||
- **Location:**
|
||||
- `src/Server/ZB.MOM.WW.OtOpcUa.Host/ActorSystemTerminationWatchdog.cs:55-68`
|
||||
- `src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs:90` (`UseWindowsService`), `:870` (`await app.RunAsync()` returns normally)
|
||||
- `scripts/install/Install-Services.ps1:215` (`sc.exe failure OtOpcUaHost … actions= restart/…`, no `failureflag`)
|
||||
- `docs/Redundancy.md:468-476`, `ControlPlane/Redundancy/ManualFailoverService.cs:78-85` (the stated reliance)
|
||||
|
||||
**Description.** Recovery of a node whose `ActorSystem` terminates outside host shutdown is exit-and-rejoin:
|
||||
the watchdog calls `IHostApplicationLifetime.StopApplication()` and "the supervisor restarts it".
|
||||
`StopApplication()` is a graceful host stop. Under `UseWindowsService`, the host's `WindowsServiceLifetime`
|
||||
then calls `ServiceBase.Stop()`, which reports `SERVICE_STOPPED` with a Win32 exit code of 0. Windows SCM runs
|
||||
`sc failure` recovery actions only when the service process dies *without* reporting `SERVICE_STOPPED` (or,
|
||||
with `sc failureflag <svc> 1`, when it reports stopped with a non-zero exit code). Neither holds here: the stop
|
||||
is reported cleanly, and the install script never sets the failure flag. Akka.Hosting's
|
||||
`Environment.ExitCode = -1` (noted in `GracefulClusterLeaveService.cs:36-38`) changes the *process* exit code,
|
||||
which SCM does not consult once the service has reported stopped. Microsoft's Windows-service guidance says the
|
||||
same thing: a cleanly stopped host does not trigger recovery; `Environment.Exit(1)` is required.
|
||||
|
||||
Docker is unaffected (`restart: unless-stopped` restarts on any exit), which is why every live gate on the
|
||||
docker-dev rig passes.
|
||||
|
||||
**Failure scenario.** On a Windows pair:
|
||||
1. An operator presses manual failover (`ManualFailoverService.FailOverCore` → `cluster.Leave(primary)`), or
|
||||
`OpcUaEndpointStepDownActor` makes a failed Primary leave, or the peer auto-downs this node after a >25 s
|
||||
pause/partition.
|
||||
2. The node's `ActorSystem` terminates; the watchdog logs Critical and calls `StopApplication()`.
|
||||
3. The service stops cleanly and stays stopped. The pair runs on one node, with no redundancy, until someone
|
||||
notices and starts the service. The log line says the supervisor will restart it.
|
||||
|
||||
**Suggested fix.** On the watchdog's unexpected-termination path, end the process as a failure instead of a
|
||||
clean stop: flush Serilog, then `Environment.Exit(1)` (optionally after a bounded `StopApplication()` drain so
|
||||
the OPC UA endpoint closes first). Alternatively set `ServiceBase.ExitCode` non-zero *and* add
|
||||
`sc.exe failureflag OtOpcUaHost 1` to `Install-Services.ps1`; the `Environment.Exit` route is simpler and does
|
||||
not depend on installer state on already-deployed boxes.
|
||||
|
||||
**Test to add.** A Windows-only install test (alongside `Test-ScriptWorkerIsolation.Windows.ps1`): install the
|
||||
service, trigger `Cluster.Leave(self)` (or the manual-failover endpoint) on a 2-node pair, and assert the
|
||||
service returns to `Running` within the first recovery delay. A unit test can pin that the watchdog's
|
||||
unexpected-termination path invokes an injected "fail the process" delegate rather than only `StopApplication`.
|
||||
|
||||
---
|
||||
|
||||
## H-2 — `AuditWriterActor` drops the whole buffered batch on a transient ConfigDb failure
|
||||
|
||||
- **Severity:** Medium
|
||||
- **Category:** bug
|
||||
- **Confidence:** High
|
||||
- **Location:** `src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Audit/AuditWriterActor.cs:86-102` (clear-then-save),
|
||||
`:138-171` (`SaveBatch`), `:177-192` (`TrySave` filter)
|
||||
- **Relation to prior review:** 03 §2.6 (one constraint hit dropped the batch) is fixed — `SaveBatch` now
|
||||
isolates rejected rows. The transient-failure half of the same shape is **still present**.
|
||||
|
||||
**Description.** `FlushBuffer` copies the buffer, clears it, then saves. `TrySave` catches only a
|
||||
`DbUpdateException` with entries or a unique violation. Anything else — a `SqlException` from a failed
|
||||
connection open, a login timeout, the follow-up `existing` query in `SaveBatch` failing because the database is
|
||||
still down — propagates to `FlushBuffer`'s catch-all, which logs `"flush failed; {Count} events dropped"`. The
|
||||
events are already out of the buffer, so they are gone. There is no retry and no re-buffering.
|
||||
|
||||
**Failure scenario.** Central SQL Server is unreachable for 30 seconds (failover, patching, network blip). The
|
||||
5-second flush timer fires several times; every audit event raised in that window — including
|
||||
`cluster.manual-failover` (`ManualFailoverService.cs:62-76`) and whatever the secrets library and AdminUI emit
|
||||
through `ActorAuditWriter` — is discarded. An outage is exactly when operators take the actions an audit trail
|
||||
is for. The only trace is an Error log line with a count.
|
||||
|
||||
**Suggested fix.** Distinguish "the database rejected these rows" (drop the offending rows, as today) from "the
|
||||
database did not answer" (keep the batch). On a non-rejection failure, put the snapshot back into `_buffer`
|
||||
(the `Dictionary<Guid, AuditEvent>` already de-duplicates) and let the next tick retry, with a cap (for example
|
||||
10 000 events, drop-oldest with a counted Warning) so a long outage cannot grow the buffer without bound. The
|
||||
unique index on `EventId` already makes a retried batch safe.
|
||||
|
||||
**Test to add.** A factory that throws a non-`DbUpdateException` on the first `SaveChanges` and succeeds on the
|
||||
second: assert all events are persisted after the second flush and none are dropped. A second case: the cap is
|
||||
enforced and the overflow is logged with a count.
|
||||
|
||||
---
|
||||
|
||||
## H-3 — `RestartDriver` / `ReconnectDriver` report failure for a command that was already dispatched, and hold the AdminOps mailbox across DB I/O
|
||||
|
||||
- **Severity:** Medium
|
||||
- **Category:** bug
|
||||
- **Confidence:** High
|
||||
- **Location:** `src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs:107-108`
|
||||
(`ReceiveAsync` registrations), `:776-805` (`HandleRestartDriverAsync`), `:807-835` (`HandleReconnectDriverAsync`)
|
||||
|
||||
**Description.** Both handlers do three things in one `try`: (1) `Dispatch(DriverControlTopic.Name, msg)` —
|
||||
the command is on its way to every node; (2) write a `ConfigEdit` audit row; (3) reply success. If step 2
|
||||
throws, the catch replies `RestartDriverResult(false, "RestartDriver failed on the server…")`. The command was
|
||||
still delivered.
|
||||
|
||||
Separately, these are the only two `ReceiveAsync` handlers on the actor. `ReceiveAsync` suspends the mailbox
|
||||
until the task completes, so the singleton processes nothing — `StartDeployment`, alarm acknowledge/shelve,
|
||||
Test Connect — while `CreateDbContextAsync` + `SaveChangesAsync` run. The ConfigDb context is registered with
|
||||
plain `UseSqlServer(connectionString)` and no retry strategy
|
||||
(`Core/ZB.MOM.WW.OtOpcUa.Configuration/ServiceCollectionExtensions.cs:30`), so against an unreachable server
|
||||
that is one full connect timeout (15 s by default) per click. The class comment at `:101-102` states the
|
||||
intent that the mailbox is never suspended for I/O; these two handlers are the exception.
|
||||
|
||||
**Failure scenario.** SQL Server is slow or down. An operator clicks **Restart** on a driver. The driver
|
||||
restarts (the dispatch went out), the UI shows a failure after ~15 s, the operator clicks again, and the driver
|
||||
restarts a second time — a second data gap on a live device connection. Meanwhile another operator's alarm
|
||||
acknowledge sits queued behind the suspended mailbox and may exceed its Ask timeout.
|
||||
|
||||
**Suggested fix.** Make both handlers synchronous `Receive`s: dispatch, reply success immediately (the reply
|
||||
describes the dispatch, which is what happened), and write the audit row off the actor with
|
||||
`Task.Run(...).PipeTo(Self)` or, better, emit it through the existing `AuditWriterActor` pipeline so it gets
|
||||
that actor's batching. A failed audit write should log, not flip the operator-visible result.
|
||||
|
||||
**Test to add.** With a `IDbContextFactory` whose `SaveChangesAsync` throws: assert the mesh router still
|
||||
received the `MeshCommand`, and the reply is success (or a distinct "dispatched, audit not recorded" outcome).
|
||||
With a factory that blocks: assert a `StartDeployment` sent afterwards is handled before the audit write
|
||||
completes.
|
||||
|
||||
---
|
||||
|
||||
## H-4 — `ConfigPublishCoordinator.HandleDispatch` supersedes a different in-flight deployment without closing it
|
||||
|
||||
- **Severity:** Low
|
||||
- **Category:** bug
|
||||
- **Confidence:** Medium — the handler behaviour is verified; the trigger needs a narrow race and was not reproduced.
|
||||
- **Location:** `src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs:493-532`
|
||||
(guards cover only the *same* id and *terminal* rows), `:530-532` (`_current` overwritten), `:588` (deadline
|
||||
timer replaced); `AdminOperations/AdminOperationsActor.cs:316-347` (`CheckInFlightAsync`), `:353-389`
|
||||
(lost-dispatch closure covers only `Dispatching` rows with no node rows)
|
||||
|
||||
**Description.** When a `DispatchDeployment` for deployment B arrives while `_current` is a different,
|
||||
still-in-flight deployment A, the handler overwrites `_current`, clears `_acks`, and replaces the single
|
||||
deadline timer. Nothing writes a terminal status for A. A's row stays `AwaitingApplyAcks` with its
|
||||
`NodeDeploymentState` rows; its acks are discarded as stale (`HandleAck`, `:607-612`); its deadline never fires.
|
||||
|
||||
The intended interlock is `CheckInFlightAsync`, but that check runs *before* the compose transaction and its
|
||||
app lock, so it does not cover two composes overlapping across an AdminOps singleton hand-over — the case the
|
||||
compose lock comment (`AdminOperationsActor.cs:483-487`) says can happen.
|
||||
|
||||
**Failure scenario.**
|
||||
1. A deploy is composing on the old admin node when the singletons hand over (manual failover of the central
|
||||
Primary, node restart). Its task commits row A as `Dispatching`; the `DeployComposed` message goes to a
|
||||
stopped actor.
|
||||
2. The new coordinator's recovery load finds A with no node rows inside the deadline and re-dispatches it —
|
||||
A is now `AwaitingApplyAcks` with seeded rows.
|
||||
3. The operator's retry had already passed `CheckInFlightAsync` on the new AdminOps (A was not committed yet)
|
||||
and was waiting on the compose lock. It commits row B and dispatches B. The coordinator switches to B.
|
||||
4. B seals. A is still `AwaitingApplyAcks`. Every later `StartDeployment` is refused with
|
||||
`AnotherDeploymentInFlight` naming A — the lost-dispatch closure skips it because it has node rows and is not
|
||||
`Dispatching`. The wedge clears only when the coordinator restarts and recovery times A out.
|
||||
|
||||
**Suggested fix.** In `HandleDispatch`, when `_current` is set and differs from `msg.DeploymentId`, close the
|
||||
old deployment first (`TimedOut` or `PartiallyFailed`, `onlyIfInFlight: true`, with a reason such as
|
||||
"superseded by deployment B before its acks completed") before adopting the new one. Independently, re-run the
|
||||
in-flight check inside the compose transaction after the app lock is held, so the second compose is refused.
|
||||
|
||||
**Test to add.** Coordinator test: dispatch A (seeded, awaiting acks), then dispatch B; assert A's row is
|
||||
terminal with a reason and a following `StartDeployment` is not refused on A's account.
|
||||
|
||||
---
|
||||
|
||||
## H-5 — An HTTPS URL binding disables every mesh listener with only a log line; the node still boots and reports ready
|
||||
|
||||
- **Severity:** Low
|
||||
- **Category:** bug
|
||||
- **Confidence:** High (code path); no deployment is known to hit it today — the install script and the rig both use HTTP behind Traefik.
|
||||
- **Location:** `src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs:752-767`; contrast `:754-755` (the data listener
|
||||
throws in the same situation); `Configuration/MeshGrpcEndpoints.cs:74-123` (services are mapped only when the port is > 0)
|
||||
|
||||
**Description.** If any configured URL is HTTPS and a dedicated h2c port is requested, the composition root
|
||||
logs one Error and zeroes `syncListenPort`, `configServeGrpcPort` and `telemetryListenPort`. Start-up
|
||||
continues. The option validators that require these transports (`SplitTopologyTransportValidator`,
|
||||
`TelemetryOptionsValidator`) validate the *configured* values, so they pass. No health check reads the
|
||||
effective ports.
|
||||
|
||||
**Failure scenario.** A `cluster-SITE-A` driver node is given `ASPNETCORE_URLS=https://…`. It boots, joins its
|
||||
mesh, and reports ready. It has no `NodeCommandService` endpoint, so every deployment dispatch to it fails and
|
||||
every deployment times out naming it; telemetry never connects; on central the same mistake removes the
|
||||
config-serve and deploy-ack endpoint, so *no* node can fetch config or report an ack. The cause is one Error
|
||||
line emitted before the boot banner.
|
||||
|
||||
**Suggested fix.** Fail host start when a listener that the node's validated configuration *requires* is being
|
||||
disabled (Grpc mesh transport on a cluster-role node, `FetchAndCache` serve side on central). Keep the
|
||||
log-and-continue path only for the genuinely optional case (LocalDb sync on a node with replication off). At
|
||||
minimum, surface the disabled state through a Degraded readiness check.
|
||||
|
||||
**Test to add.** A composition-root test (the existing `WebApplicationFactory`-style host tests) with an HTTPS
|
||||
URL plus `Telemetry:GrpcListenPort` on a cluster-role node: assert start-up fails with a message naming both
|
||||
settings.
|
||||
|
||||
---
|
||||
|
||||
## H-6 — Synchronous EF calls on the deploy-coordinator singleton thread serialise connect timeouts during a ConfigDb outage
|
||||
|
||||
- **Severity:** Low
|
||||
- **Category:** perf
|
||||
- **Confidence:** Medium — the blocking calls are verified; the timing is estimated from the default 15 s SQL connect timeout, not measured.
|
||||
- **Location:** `src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Coordinators/ConfigPublishCoordinator.cs:754-775`
|
||||
(`PersistNodeAck`), `:512-582` (`HandleDispatch`), `:783-821`, `:823-902` (terminal writes), `:835` (deadline
|
||||
re-persists the whole backlog inline). Same shape, lower stakes: `Audit/AuditWriterActor.cs:177-192`,
|
||||
`Fleet/ClusterNodeAddressReconcilerActor.cs:109-140`.
|
||||
|
||||
**Description.** The recovery load was moved off the actor thread (#868), but every steady-state database call
|
||||
in the coordinator is still a blocking `SaveChanges`/`FirstOrDefault` inside a message handler. With no retry
|
||||
strategy on the context, a call against an unreachable server blocks for the connect timeout. Each
|
||||
`ApplyAck` attempt, each per-node retry tick and each backlog item re-tried by `HandleDeadline` pays that cost
|
||||
one after another on the one thread.
|
||||
|
||||
**Estimated cost.** Six nodes acking during an outage: 6 × 15 s = 90 s of blocked mailbox for the first
|
||||
attempts, then the same again per retry round (1 s → capped backoff per node, each tick blocking 15 s). The
|
||||
deadline tick queues behind them and then re-tries all six inline (another 90 s). Nothing is lost — acks are
|
||||
held and retried — but the coordinator's reaction to everything else (a new dispatch, the deadline decision) is
|
||||
delayed by minutes rather than seconds, and the Akka dispatcher thread is held throughout.
|
||||
|
||||
**Suggested fix.** Apply the pattern `StartRecoveryLoad` already uses: run the ack persist as an async task and
|
||||
pipe `AckPersisted` / `AckPersistFailed` back, keeping the count/seal decision on the actor thread. Coalesce
|
||||
the backlog into one context and one `SaveChanges` per retry tick instead of one connection attempt per node.
|
||||
Setting an explicit short `Connect Timeout` for the coordinator's contexts would shrink the problem without
|
||||
restructuring.
|
||||
|
||||
**Test to add.** With a factory whose `CreateDbContext` blocks for a configurable delay, send N acks and then a
|
||||
`DeadlineElapsed`; assert the deadline is handled within a bound that does not scale with N.
|
||||
|
||||
---
|
||||
|
||||
## Areas reviewed with no findings
|
||||
|
||||
- **`ConfigPublishCoordinator`** recovery and ack state machine: Loading/Ready stash, lost-dispatch re-drive
|
||||
and closure, RowVersion-conditioned `AwaitingApplyAcks` flip, poison-vs-transient ack classification,
|
||||
bounded deadline deferral, `PreRestart` re-send of unpersisted and memory-only acks, degraded seal. Only H-4
|
||||
and H-6 came out of it.
|
||||
- **`CentralCommunicationActor`**: deferred dependency resolution, per-node dial off the actor thread, one
|
||||
result channel (`CommandDispatched`) so a dial fault is never read as a contact-load failure, lifecycle token
|
||||
handling in `PostStop`, known-cluster gate publication and bootstrap retry, channel pruning via `RetainOnly`.
|
||||
- **`MeshPskProvider` / `MeshGrpcCommandDialer` / `CentralCommandAuthInterceptor`**: fail-closed on every
|
||||
unresolvable case, constant-time compare, no key material in logs or status details, bounded store reads,
|
||||
refresh keeps the previous key on a failed read and revokes on a definite not-found.
|
||||
- **`AdminOperationsActor` deploy path**: compose off the mailbox, SNAPSHOT transaction plus app lock,
|
||||
validation from the same snapshot, generic `ServerFault` text to callers. (Restart/Reconnect are H-3.)
|
||||
- **`AlarmCommandVerdictCollector` / aggregator**: window timer always answers; transport failure maps to
|
||||
outcome-unknown, never not-applied.
|
||||
- **`RedundancyStateActor` / `ManualFailoverService`**: oldest-Up-driver election matches singleton placement
|
||||
and the failover target; debounce plus 10 s heartbeat republish; revision triple; peer guard before audit.
|
||||
- **`DeploymentRetentionActor`**, **`ClusterNodeAddressReconcilerActor`**, **`TelemetryStreamClient`**: sweeps
|
||||
off the actor thread or guarded; the keep window counts sealed rows only; a clean server-side stream end is
|
||||
redialled by `TelemetryDialSupervisor` (checked in AdminUI because the client alone does not signal it).
|
||||
- **Cluster library**: `EffectiveRoles` / `RoleParser` single role authority, `AkkaClusterOptionsValidator`,
|
||||
`SplitTopologyTransportValidator`, `MeshTransportOptionsValidator`, `ConfigSourceOptionsValidator`,
|
||||
`BuildDowningHocon` / `BuildClusterOptions`, `ClusterBootstrapGuard` founder tie-break (case-insensitive on
|
||||
both sides), `ClusterBootstrapCoordinator` probe-then-single-join and its cancellation on stop,
|
||||
`ClusterRoleInfo` locking and member bookkeeping, `ServiceLevelCalculator`, `akka.conf` failure-detector and
|
||||
downing timings.
|
||||
- **Host lifecycle**: `GracefulClusterLeaveService` ordering and token bounds,
|
||||
`ShutdownStreamCancellationInterceptor`, `SecretReplicationStarter`, `DriverResilienceStatusPublisherService`,
|
||||
`AclRevalidationTimer`, the `Program.cs` start-up wrapper (Fatal + stderr + `Environment.Exit(1)`), the
|
||||
single re-bind of existing Kestrel endpoints alongside dedicated h2c ports (apart from H-5).
|
||||
- **Health checks**: `OpcUaEndpointHealthCheck` (Failed/NotStarted/Stopped all Unhealthy),
|
||||
`ConfigPublishCoordinatorHealthCheck`, `ScriptRunnerHealthCheck` (never fails ready, by design),
|
||||
`LocalDbReplicationHealthCheck`.
|
||||
- **Mesh gRPC services**: `NodeCommandGrpcService` (Unavailable while starting, bounded verdict wait),
|
||||
`TelemetryStreamGrpcService` (stream cap paired on every path, bounded lifetime), `MeshGrpcEndpoints` mapping
|
||||
gates, `CentralCommandGrpcService` (read in AdminUI as the ack path's far end).
|
||||
@@ -0,0 +1,462 @@
|
||||
# 06 — Core slice review (2026-12-02)
|
||||
|
||||
**Commit:** master @ `708a4889c`
|
||||
**Scope (src/):** `Core/…Commons`, `Core/…Core.Abstractions`, `Core/…Core`, `Core/…Core.Scripting`,
|
||||
`…Core.Scripting.Abstractions`, `…Core.Scripting.Protocol`, `…Core.Scripting.OutOfProcess`,
|
||||
`…Core.ScriptedAlarms`, `…Core.AlarmHistorian`, `…Core.VirtualTags`, `Server/…ScriptWorker` (~33k lines).
|
||||
|
||||
**Method.** Read-only. The scripting, out-of-process runner, script-worker, scripted-alarm and alarm-historian
|
||||
projects were read directly; Commons / Core.Abstractions / Core / Core.VirtualTags were read by a delegated
|
||||
reviewer and each of its findings re-checked against the code before inclusion (marked "delegated" below).
|
||||
Four findings were confirmed by running the already-built assemblies from a throwaway project outside the repo
|
||||
(K-1, K-3 timing, K-7, and the delegated probes for K-6/K-8/K-9/K-10). Nothing in the repo was edited or built.
|
||||
|
||||
**Prior review** (`docs/reviews/2026-10-21/05-core.md`): items 1, 3, 4, 7, 10, 12 are remediated. Item 2 (one
|
||||
orphaned pool thread per runaway in-process script) is still true by design and is not re-reported. Item 10
|
||||
(sandbox) was closed for `System.Threading` / `Type.GetType` / `RuntimeHelpers`, but the deny-list is still
|
||||
bypassable by other routes — see K-1.
|
||||
|
||||
| ID | Severity | Category | Title |
|
||||
|---|---|---|---|
|
||||
| K-1 | Critical | bug | Script sandbox deny-list is bypassable: arbitrary process start, file read/write, network, background work |
|
||||
| K-2 | High | bug | Alarm store-and-forward dead-letters queued events after ~6.5 min of historian outage |
|
||||
| K-3 | High | perf | Every deploy recompiles every scripted-alarm predicate serially under the engine gate |
|
||||
| K-4 | Medium | bug | A timed shelve that expires on a predicate evaluation emits no `Unshelved` event and no audit entry |
|
||||
| K-5 | Medium | bug | Frame writer can build a frame over the 4 MiB cap (log batch, coalesced evals/results) and kills the worker |
|
||||
| K-6 | Medium | bug | Resilience pipeline timeout is invisible to retry, breaker and status tracker |
|
||||
| K-7 | Low | bug | `ScriptRunGuard`: a script-thrown `TimeoutException` surfaces as `ObjectDisposedException` |
|
||||
| K-8 | Low | bug | `ResilienceConfig` with valid-JSON-but-wrong shape throws out of driver spawn |
|
||||
| K-9 | Low | bug | Wire-value decoders leak `OverflowException` / `FormatException` / `ArgumentOutOfRangeException` |
|
||||
| K-10 | Low | bug | Poll backoff cap below the subscription interval polls a failing device faster than a healthy one |
|
||||
| K-11 | Low | perf | Redundant sizing on the gRPC value-frame decode path; two allocations per out-of-process evaluation |
|
||||
|
||||
---
|
||||
|
||||
## K-1 — Script sandbox deny-list is bypassable
|
||||
|
||||
- **Severity:** Critical · **Category:** bug (sandbox escape) · **Confidence:** High (reproduced)
|
||||
- **Location:** `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs:43-152` (the three deny-lists),
|
||||
`ScriptSandbox.cs:75-109` and `:147-178` (every `System.*` TPA assembly plus `Serilog` is referenced).
|
||||
|
||||
**Description.** The sandbox references the whole BCL and relies on `ForbiddenTypeAnalyzer` as "the sole gate".
|
||||
The gate is a deny-list of namespaces, a few types and `System.Type` members. Several BCL surfaces that give
|
||||
reflection-equivalent power, or do I/O under a path/URL string, live in namespaces that are not listed.
|
||||
|
||||
Each of these compiled through `ScriptEvaluator<TContext, object?>.Compile` and ran (a `System.IO.File`
|
||||
control was correctly blocked):
|
||||
|
||||
| Script | Result |
|
||||
|---|---|
|
||||
| `Delegate.CreateDelegate(typeof(Func<string,Type>), typeof(Type), "GetType")`, then a second `CreateDelegate` on the returned `System.IO.File` type for `ReadAllText` | read `/etc/hosts` |
|
||||
| `Expression.Call(typeof(Type), "GetType", …)` compiled, then `Expression.Call(processType, "Start", null, …)` compiled and invoked | **started `/usr/bin/touch`; the file was created** |
|
||||
| `System.Xml.Linq.XDocument.Load(path-or-URL)` | read a local file (same call fetches HTTP) |
|
||||
| `new System.Xml.Linq.XElement("a","b").Save(path)` | wrote a file |
|
||||
| `System.Formats.Tar.TarFile.CreateFromDirectory(dir, file, false)` | wrote an archive of a directory |
|
||||
| `new System.Security.Cryptography.X509Certificates.X509Store().Name` | reached the certificate store API |
|
||||
| `new System.Timers.Timer(50){…}.Start()`, `BackgroundWorker.RunWorkerAsync()`, `Enumerable.Range(…).AsParallel()` | background threads that outlive the evaluation budget |
|
||||
| `Serilog.Log.Logger = Serilog.Core.Logger.None;` | replaced the process-global logger |
|
||||
|
||||
The `Type.GetType` entry in `ForbiddenMembers` is only checked for a syntactic call; binding it by name through
|
||||
`Delegate.CreateDelegate` or `System.Linq.Expressions` never names the member.
|
||||
|
||||
**Failure scenario.** Scripts are authored by the `ConfigEditor` policy (Administrator **or Designer**). In the
|
||||
default `Scripting:Runner = InProcess` a Designer's virtual-tag, Calculation or alarm script runs arbitrary
|
||||
code as the OtOpcUa service account, in the server process: start processes, read the secrets store / PKI
|
||||
private keys / `appsettings`, write files, open sockets. With `OutOfProcess` the same code runs in the
|
||||
ScriptWorker; without `Scripting:Worker:Identity` that is the same account. With the restricted identity the
|
||||
blast radius is the worker, but note `WorkerHost.cs:104-108`: the worker is handed the PE-cache HMAC key, and a
|
||||
cache hit is loaded by `FromImage` without re-running the analyzer (`WorkerHost.cs` `LoadedScript.Load`), so
|
||||
code that has escaped inside a worker can forge a signed cache entry for any other script's source and persist
|
||||
across restarts and redeploys.
|
||||
|
||||
The background-work cases matter even without malice: a script that starts a `System.Timers.Timer` leaks a
|
||||
timer and its callback per evaluation, which is exactly what the `System.Threading` ban was added to prevent.
|
||||
|
||||
**Suggested fix.** A deny-list over the full BCL cannot be closed. Options, strongest first:
|
||||
1. Invert to an allow-list: only symbols whose containing namespace/type is on an explicit list
|
||||
(`System` primitives, `Math`, `String`, `Convert`, `DateTime`/`TimeSpan`, `System.Linq.Enumerable`,
|
||||
`System.Collections.Generic`, `System.Text` (`StringBuilder`), `System.Text.RegularExpressions`,
|
||||
`System.Globalization` read-only, the OtOpcUa script types, `Serilog.ILogger` instance methods).
|
||||
2. As an immediate stopgap add to the deny-lists: `System.Delegate` / `System.MulticastDelegate` members
|
||||
`CreateDelegate`, `DynamicInvoke`, `Method`; namespaces `System.Linq.Expressions`, `System.Xml`,
|
||||
`System.Formats`, `System.Timers`, `System.ComponentModel`, `System.Security`, `System.Data`,
|
||||
`System.Resources`, `System.Runtime.Serialization`, `System.Net` (already), `System.Linq.ParallelEnumerable`
|
||||
/ `ParallelQuery`; types `Serilog.Log`, `Serilog.LoggerConfiguration`, `System.Type` members returning
|
||||
reflection objects (`Assembly`, `Module`, `TypeInitializer`, `GetInterface*`, `GetNestedType*`,
|
||||
`GetTypeFromProgID/CLSID`, `MakeGenericType`).
|
||||
3. Narrow `ScriptSandbox.EnumerateBclAssemblyPaths` to the handful of reference assemblies scripts need, so
|
||||
an unlisted type fails to bind at all. (Type forwarding makes this insufficient alone, but it removes most
|
||||
of the surface.)
|
||||
4. Treat the worker as untrusted for the PE cache: have the host sign entries (worker returns the image, host
|
||||
writes it), or keep the key out of `Hello`.
|
||||
|
||||
Document, until this is closed, that `InProcess` scripting grants Designers code execution as the service.
|
||||
|
||||
**Test to add.** A theory in `ForbiddenTypeAnalyzerTests` over the eight snippets above asserting
|
||||
`ScriptSandboxViolationException`; plus an allow-list inversion test that enumerates every public type in the
|
||||
referenced assemblies and asserts each is either allow-listed or rejected when named.
|
||||
|
||||
---
|
||||
|
||||
## K-2 — Alarm store-and-forward dead-letters events during a historian outage
|
||||
|
||||
- **Severity:** High · **Category:** bug (data loss) · **Confidence:** High
|
||||
- **Location:** `src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs:28-35` (backoff
|
||||
ladder), `:404-421` (`RetryPlease` branch: `if (liveRows[i].AttemptCount + 1 >= _maxAttempts)` → dead-letter).
|
||||
Writers: `GatewayAlarmHistorianWriter.cs:113,176,289-310`, `SqlServerAlarmHistorianWriter.cs:53,144-147`,
|
||||
`QuestDbAlarmHistorianWriter.cs:60,138-142`.
|
||||
|
||||
**Description.** All three production writers are documented "never throws" and answer a systemic outage
|
||||
(`Unavailable`, auth failure, transient SQL, bootstrap failure) with `RetryPlease` for every event in the batch.
|
||||
The sink's poison-row cap does not distinguish "this row keeps failing" from "the historian is down": every
|
||||
`RetryPlease` bumps `attempt_count`, and at `MaxAttempts` (default 10) the row is dead-lettered. Only a writer
|
||||
that *throws* takes the no-bump path, and none does.
|
||||
|
||||
With the defaults (`DrainIntervalSeconds = 5`, ladder 1/2/5/15/60 s) attempts land at roughly
|
||||
t = 0, 5, 10, 25, 85, 145, … s, so the tenth is at about 385 s.
|
||||
|
||||
**Failure scenario.** The historian (or the HistorianGateway sidecar, or its API key) is unavailable for
|
||||
longer than ~6.5 minutes. The oldest 100 queued alarm events are dead-lettered; a further 100 follow every
|
||||
10 minutes after that. An 8-hour overnight outage dead-letters about 4,800 events. Dead-lettered rows are never
|
||||
retried automatically (`RetryDeadLettered` is a manual operator action) and are purged after 30 days. The
|
||||
queue's 1,000,000-row capacity and `docs/AlarmTracking.md` ("during a historian outage, older rows are evicted"
|
||||
at capacity) both describe retention through an outage; the writers' own comments say "an auth blip never
|
||||
dead-letters". The cap defeats both.
|
||||
|
||||
**Suggested fix.** Count an attempt against a row only when the batch shows the historian is reachable — i.e.
|
||||
when at least one event in the same drain was `Ack` or `PermanentFail`. A batch that is 100 % `RetryPlease` is
|
||||
an outage: back off, bump nothing. (Alternatively add a fourth outcome, `Unavailable`, that the writers return
|
||||
for systemic faults and the sink never counts.) Consider auto-reviving rows dead-lettered with
|
||||
"max attempts exceeded" on the first successful drain after an outage.
|
||||
|
||||
**Test to add.** `LocalDbStoreAndForwardSinkTests`: a writer returning all-`RetryPlease` for `MaxAttempts + 5`
|
||||
drains leaves `DeadLetterDepth == 0` and `QueueDepth` unchanged; then one row in a mixed batch
|
||||
(`Ack` siblings, one `RetryPlease`) is still dead-lettered after `MaxAttempts`.
|
||||
|
||||
---
|
||||
|
||||
## K-3 — Every deploy recompiles every scripted-alarm predicate under the engine gate
|
||||
|
||||
- **Severity:** High · **Category:** perf · **Confidence:** High on mechanism; cost measured, scale is site-dependent
|
||||
- **Location:** `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs` `LoadAsync`
|
||||
(`_compileCache.Clear()` then the `foreach (var def in definitions)` loop calling
|
||||
`_compileCache.GetOrCompile` / `CompileToImage`, all inside `_evalGate`). Trigger:
|
||||
`src/Server/…Runtime/Drivers/DriverHostActor.cs:4235` sends `ApplyScriptedAlarms` on every apply;
|
||||
`ScriptedAlarmHostActor.OnApply` calls `_engine.LoadAsync` directly.
|
||||
|
||||
**Description.** `LoadAsync` runs on every deploy, including a surgical one that touched no alarm. It clears
|
||||
the compile cache and compiles each predicate again, one at a time, synchronously, while holding `_evalGate`.
|
||||
When the gate is uncontended, `await _evalGate.WaitAsync` completes synchronously, so the whole compile loop
|
||||
also runs on the `ScriptedAlarmHostActor`'s dispatcher thread. In `OutOfProcess` mode the host still compiles
|
||||
every predicate to a PE image for validation and discards it, and the worker then compiles again.
|
||||
|
||||
Measured on this machine against the built assemblies (warm Roslyn, trivial one-line predicates):
|
||||
100 `Compile` calls took 4.3 s (~43 ms each); 100 `CompileToImage` calls took 1.9 s (~19 ms each).
|
||||
|
||||
**Failure scenario.** A site with 1,000 scripted alarms deploys any change. For roughly 20–40 s no scripted
|
||||
alarm is evaluated (the gate is held, subscriptions are torn down first), operator acknowledge / shelve
|
||||
commands queue behind the gate, and an Akka dispatcher thread is pinned. Alarms that should have activated
|
||||
during the window activate late; this repeats on every deploy.
|
||||
|
||||
**Suggested fix.**
|
||||
- Keep evaluators whose source is unchanged: diff the new definitions against the cache by source hash, dispose
|
||||
only the entries no definition references, and compile only the new ones.
|
||||
- Compile outside `_evalGate` (and off the actor thread, e.g. `Task.Run` with bounded parallelism), then take
|
||||
the gate only for the swap.
|
||||
- In `OutOfProcess` mode skip the host-side validation compile when the PE cache already holds a verified entry
|
||||
for that source, or validate with the analyzer only (no `Emit`).
|
||||
|
||||
**Test to add.** An engine test that loads N definitions, reloads the same N, and asserts zero additional
|
||||
compiles (a counting hook on `CompiledScriptCache`), plus one asserting `AcknowledgeAsync` completes while a
|
||||
reload's compile phase is in progress.
|
||||
|
||||
---
|
||||
|
||||
## K-4 — Timed shelve expiring on a predicate evaluation is silent
|
||||
|
||||
- **Severity:** Medium · **Category:** bug (alarm state machine) · **Confidence:** High
|
||||
- **Location:** `src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs` `ApplyPredicate`
|
||||
(`var shelving = MaybeExpireShelving(current.Shelving, nowUtc);` … final
|
||||
`return new TransitionResult(stateWithShelving, EmissionKind.None);`), consumed by
|
||||
`ScriptedAlarmEngine.EvaluatePredicateToStateAsync` / `ApplyPredicateOutcome`.
|
||||
|
||||
**Description.** `ApplyPredicate` expires a timed shelve itself and, when the predicate result matches the
|
||||
current active state, returns the unshelved state with `EmissionKind.None`. The engine saves the state and
|
||||
emits nothing. The 5 s shelving timer then finds `Shelving.Kind != Timed` and does nothing either. The
|
||||
`AutoUnshelve` audit comment that `ApplyShelvingCheck` writes is never added.
|
||||
|
||||
This was recognised and fixed for the load path only (`ExpireTimedShelveAtLoad`, "#935 review N5: otherwise
|
||||
`ApplyPredicate`'s own expiry silently unshelved it (no audit entry, no event)"). The steady-state push path
|
||||
still has it.
|
||||
|
||||
**Failure scenario.** An operator timed-shelves an active alarm for 10 minutes. Its input tag updates at
|
||||
1 Hz, so after expiry the next predicate evaluation arrives before the next 5 s timer tick about four times
|
||||
out of five. The engine's state becomes Unshelved, but no `Unshelved` event is raised: the OPC UA condition
|
||||
node keeps `ShelvingState = TimedShelved` (the SDK's own timed-unshelve is deliberately a no-op, per
|
||||
`.claude/rules/alarms.md`), `/alerts` and ScadaBridge keep showing it shelved, and the audit trail has no
|
||||
auto-unshelve entry. It stays that way until the alarm's next real transition — for an alarm that remains
|
||||
active, indefinitely.
|
||||
|
||||
**Suggested fix.** Make the shelving check the only place a timed shelve expires. In
|
||||
`EvaluatePredicateToStateAsync` and the batch path, run `Part9StateMachine.ApplyShelvingCheck(seed, nowUtc)`
|
||||
first (as `ExpireTimedShelveAtLoad` does), queue its `Unshelved` emission, and pass the resulting state to
|
||||
`ApplyPredicate`; then remove `MaybeExpireShelving` from `ApplyPredicate`.
|
||||
|
||||
**Test to add.** Engine test: timed-shelve an active alarm, advance the clock past `UnshelveAtUtc`, push an
|
||||
input that leaves the predicate true, and assert exactly one `Unshelved` event and an `AutoUnshelve` comment —
|
||||
without calling the shelving check.
|
||||
|
||||
---
|
||||
|
||||
## K-5 — Frame writer can exceed the frame cap and kill the worker
|
||||
|
||||
- **Severity:** Medium · **Category:** bug (worker protocol) · **Confidence:** High on mechanism; Medium on how often the eval/result case is reached
|
||||
- **Location:** `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptWorkerFramePipe.cs` `FillPass`
|
||||
(unbounded `evals.Items.AddRange` / `results.Items.AddRange`) and `Append`
|
||||
(`if (size > MaxFrameBytes) throw new ScriptWorkerProtocolException`);
|
||||
`src/Server/…ScriptWorker/WorkerHost.cs` `ForwardingLogSink` (`Capacity` 1000 lines, `Rendered` up to 8 K
|
||||
chars, `Exception` up to 16 K chars, one `LogBatch` per 100 ms drain) and `OnWriteFault`
|
||||
(`Environment.Exit(ExitProtocolFault)`); host side `WorkerConnection.OnWriteFault` → `Kill(Crash)`.
|
||||
|
||||
**Description.** Each envelope handed to `TryWrite` may be within the 4 MiB cap, but the writer never checks
|
||||
before merging, and nothing bounds a single `LogBatch` or `EvalBatch` by bytes:
|
||||
|
||||
1. **Log batch (easy to hit).** `Drain()` puts every buffered line in one `LogBatch`. 1,000 lines × 8 K chars
|
||||
is 8 MB or more. `Append` throws, `OnWriteFault` exits the worker with code 4.
|
||||
2. **Coalesced evals / results.** While one write is in progress, queued `Eval` (host) or `Results` (worker)
|
||||
envelopes are merged into one frame. `OutOfProcessScriptRunner.RunBatch` also submits one `EvalBatch` per
|
||||
connection with no byte limit. Around 4,000 evaluations of ~1 KB of inputs each (array-valued inputs get
|
||||
there with far fewer) exceed the cap.
|
||||
|
||||
In every case the writer faults, the worker is killed or exits, and the host records a crash "with no deadline
|
||||
crossed".
|
||||
|
||||
**Failure scenario.** One script logs a large string in a loop — e.g. 600 × `ctx.Logger.Information(bigArrayText)`
|
||||
inside one 100 ms window. The worker exits; every evaluation in flight on that shard publishes
|
||||
`BadResourceUnavailable`; every in-flight key is marked Suspect and rerouted through the one-at-a-time
|
||||
isolation worker for its probation runs; the shard restarts with backoff. The offending script repeats this
|
||||
until it accumulates enough isolation-worker kill strikes to be quarantined. The design intent ("bounded log
|
||||
buffer, lines dropped and counted") is not met: lines are dropped only by count, not by bytes.
|
||||
|
||||
**Suggested fix.** In `FillPass`, track the accumulated encoded size and `Append` the current merged frame
|
||||
before it would cross `MaxFrameBytes` (start a new one). Bound `ForwardingLogSink.Drain` by bytes as well as
|
||||
lines (emit several `LogBatch` envelopes or count the remainder as dropped). Split `SubmitBatch` the same way.
|
||||
A single item that is over the cap on its own should fail that one evaluation
|
||||
(`unsupported type` / "input too large"), not the connection.
|
||||
|
||||
**Test to add.** `ScriptWorkerFrameWriter` unit test: enqueue N eval envelopes totalling 3× the cap while the
|
||||
stream write is blocked, release it, and assert several frames each ≤ cap and no fault. A `Category=ScriptWorker`
|
||||
test where a script logs 2,000 × 8 KB lines and the worker survives with `Dropped > 0`.
|
||||
|
||||
---
|
||||
|
||||
## K-6 — Resilience pipeline timeout is invisible to retry, breaker and tracker (delegated; probe-verified)
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High on mechanism, Medium on intent
|
||||
- **Location:** `src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs:138-141`
|
||||
(timeout added first, i.e. outermost), `:152` and `:176`
|
||||
(`ShouldHandle = … ex is not OperationCanceledException and not DriverOperationRefusedException`), `:158`
|
||||
(the only `RecordFailure` call, inside `OnRetry`).
|
||||
|
||||
**Description.** When the outer timeout fires, Polly cancels the inner token; the retry and breaker strategies
|
||||
see an `OperationCanceledException`, which both predicates exclude. The caller gets `TimeoutRejectedException`,
|
||||
but no retry happens, the breaker records nothing, and the status tracker is never told. No code in `src/`
|
||||
handles `TimeoutRejectedException`.
|
||||
|
||||
Probe (Timeout 1 s, Retry 3, Breaker 2, a call that hangs honouring the token): 6 calls → 6
|
||||
`TimeoutRejectedException`, 6 attempts, breaker never opened, no tracker snapshot. Control: two `IOException`s
|
||||
opened the breaker.
|
||||
|
||||
**Failure scenario.** A blackholed or wedged device whose driver call outlasts the pipeline timeout (Tier A
|
||||
Read is 2 s; S7's own default timeout is 5 s, OpcUaClient's 10 s). Every call burns the full timeout forever,
|
||||
the breaker that should stop the hammering never opens, and `/hosts` shows `ConsecutiveFailures = 0` and no
|
||||
"Breaker OPEN" for a dead device.
|
||||
|
||||
**Suggested fix.** Count the pipeline's own timeout as a handled failure: put a per-attempt timeout inside
|
||||
retry and breaker (keeping an outer total budget), or have both predicates handle an OCE when the caller's
|
||||
token is not cancelled, and call `RecordFailure` on the timeout path in `CapabilityInvoker`.
|
||||
|
||||
**Test to add.** `DriverResiliencePipelineBuilderTests` with a `FakeTimeProvider`: N hung calls with
|
||||
`BreakerFailureThreshold = 2` end in `BrokenCircuitException` and `tracker.TryGet(…).IsBreakerOpen`.
|
||||
|
||||
---
|
||||
|
||||
## K-7 — `ScriptRunGuard`: script-thrown `TimeoutException` becomes `ObjectDisposedException`
|
||||
|
||||
- **Severity:** Low · **Category:** bug · **Confidence:** High (reproduced)
|
||||
- **Location:** `src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs` `RunAsync`: the
|
||||
`runTask.ContinueWith(t => { runCts.Dispose(); … })` continuation, and
|
||||
`catch (TimeoutException) { … runCts.Cancel(); … }`. Same catch shape in `TimedScriptEvaluator.cs`.
|
||||
|
||||
**Description.** `catch (TimeoutException)` is meant for `WaitAsync`'s synthesized timeout, but it also catches
|
||||
a `TimeoutException` the script itself threw (including `RegexMatchTimeoutException`, which derives from it).
|
||||
By then `runTask` has completed, its continuation has disposed `runCts`, and `runCts.Cancel()` throws.
|
||||
|
||||
Reproduced: `throw new TimeoutException("mine");` and a `Regex.IsMatch(…, TimeSpan.FromMilliseconds(20))` that
|
||||
times out both surface from `ScriptRunGuard.RunAsync` as
|
||||
`ObjectDisposedException: The CancellationTokenSource has been disposed.` (an `InvalidOperationException`
|
||||
control propagates unchanged).
|
||||
|
||||
The same `Cancel()`-after-dispose also occurs as a narrow race when a script finishes in the instant its real
|
||||
timeout fires; the Calculation evaluator already carries a one-shot retry for that
|
||||
(`CalculationEvaluator.cs:293`).
|
||||
|
||||
**Failure scenario.** A script using a regex with a match timeout publishes Bad with
|
||||
"script threw: The CancellationTokenSource has been disposed." instead of its own exception; in the Calculation
|
||||
seam the script is run twice (the retry) each time. If the dispose ordering ever changes, the same script would
|
||||
instead be counted as a guard timeout and quarantined after three evaluations.
|
||||
|
||||
**Suggested fix.** Distinguish the two cases: `catch (TimeoutException) when (!runTask.IsCompleted)` for the
|
||||
synthesized timeout (a completed `runTask` means the exception is the script's own and should fall through to
|
||||
the generic handler), and guard `runCts.Cancel()` with `try { } catch (ObjectDisposedException) { }`.
|
||||
|
||||
**Test to add.** `ScriptRunGuardTests`: a script that throws `TimeoutException` propagates that exception,
|
||||
leaves `ConsecutiveTimeouts` at 0 and is not quarantined after N runs.
|
||||
|
||||
---
|
||||
|
||||
## K-8 — `ResilienceConfig` with a wrong-shaped but valid JSON value throws (delegated; probe-verified)
|
||||
|
||||
- **Severity:** Low · **Category:** bug · **Confidence:** High on the throw, Medium on reachability
|
||||
- **Location:** `src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs:104-114`.
|
||||
|
||||
**Description.** Only `JsonException` is caught. `Enum.TryParse<DriverCapability>` accepts numeric strings, so
|
||||
`{"capabilityPolicies":{"42":{"timeoutSeconds":3}}}` reaches `merged[capability]` and throws
|
||||
`KeyNotFoundException`; `{"capabilityPolicies":{"Read":null}}` dereferences a null `overridePolicy`
|
||||
(`NullReferenceException`). Both were reproduced.
|
||||
|
||||
**Failure scenario.** The parser is reached from `DriverCapabilityInvokerFactory.Create`, which
|
||||
`DriverHostActor.SpawnChild` does not wrap (it wraps only the driver factory). The AdminUI form writes good
|
||||
shapes, but the column constraint is only `ISJSON` and the form preserves a blob it cannot parse, so a restored
|
||||
database, a manual SQL edit or an older build can deliver one. The exception leaves the `DriverHostActor`
|
||||
handler that hosts every driver on the node, and the same artifact is re-applied afterwards. This contradicts
|
||||
the "never bricks" invariant that `ResilienceConfigBrickTests` exists for.
|
||||
|
||||
**Suggested fix.** After `TryParse` require `Enum.IsDefined` and `merged.TryGetValue`; skip a null override
|
||||
with a diagnostic; wrap `_invokerFactory.Create` in `SpawnChild` as the driver factory call is.
|
||||
|
||||
**Test to add.** `ResilienceConfigBrickTests`: both JSON strings return tier defaults plus a diagnostic.
|
||||
|
||||
---
|
||||
|
||||
## K-9 — Wire-value decoders leak unexpected exception types
|
||||
|
||||
- **Severity:** Low · **Category:** bug · **Confidence:** High
|
||||
- **Location:**
|
||||
- `src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs:139` (`ToDateTimeOffset`),
|
||||
`:201-218` (`checked(...)` narrowing), `:236` (`Guid.ParseExact`); status mapping at
|
||||
`src/Server/…Host/Grpc/DataConnectionGrpcService.cs:370-374` (delegated; probe-verified).
|
||||
- `src/Core/…Core.Scripting.Protocol/VariantCodec.cs` `Decode` (`checked(...)`, `new DateTime(ticks, Utc)`),
|
||||
caught in `OutOfProcessScriptRunner.Complete` only as `ScriptWorkerProtocolException`.
|
||||
|
||||
**Description.** Both decoders document one failure type but throw others for out-of-range input.
|
||||
|
||||
- gRPC data plane: the service maps `ArgumentException` → `InvalidArgument` and `InvalidOperationException` →
|
||||
`Unavailable`. An Int8 carrying 300 throws `OverflowException` and a bad GUID `FormatException` (neither is
|
||||
mapped; they escape the handler as an internal error), and an out-of-range timestamp throws
|
||||
`InvalidOperationException`, which tells the client to retry or fail over a request that can never succeed.
|
||||
- Script worker: a result whose variant is tagged `Byte` with value 300, or `DatetimeUtc` with out-of-range
|
||||
ticks, throws out of `AwaitSubmittedAsync`. `IScriptRunner.RunAsync` is documented "never faults"; the seam
|
||||
sees a faulted task instead of a `Failed` outcome. (Only a misbehaving or compromised worker produces this.)
|
||||
|
||||
**Suggested fix.** Normalise inside each codec: range-check before narrowing, use `Guid.TryParseExact`, check
|
||||
the tick / seconds range, and throw the codec's documented exception type.
|
||||
|
||||
**Test to add.** Theories over the malformed payloads asserting `ArgumentException` (TypedValueCodec) and
|
||||
`ScriptWorkerProtocolException` (VariantCodec); a service-level test that such a Write returns
|
||||
`StatusCode.InvalidArgument`.
|
||||
|
||||
---
|
||||
|
||||
## K-10 — Backoff cap below the interval polls a failing device faster (delegated; probe-verified)
|
||||
|
||||
- **Severity:** Low · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ConnectionBackoff.cs:53-62`
|
||||
(`if (ticks <= 0 || ticks > cap.Ticks) return cap;`), used at `PollGroupEngine.cs:307-310`.
|
||||
|
||||
**Description.** The cap is an absolute ceiling, not `max(interval, …)`. `ComputeDelay(60 s, 1, 30 s)` returns
|
||||
30 s. The engine's own remarks acknowledge the asymmetry for a cap below the *minimum* interval, but not for a
|
||||
subscription whose publishing interval is above the cap.
|
||||
|
||||
**Failure scenario.** Every poll driver passes a 30 s cap. A subscription polled every 60 s (plausible for the
|
||||
Sql poll driver) is polled every 30 s once it starts failing — the opposite of "a dead device must not be
|
||||
hammered at fixed rate".
|
||||
|
||||
**Suggested fix.** `delay = max(state.Interval, ComputeDelay(…))` in `PollLoopAsync`, or clamp the cap to at
|
||||
least the base interval inside `ComputeDelay`.
|
||||
|
||||
**Test to add.** `PollGroupEngine` test: interval 200 ms, cap 50 ms, always-throwing reader; the gap between
|
||||
attempts is ≥ 200 ms.
|
||||
|
||||
---
|
||||
|
||||
## K-11 — Hot-path redundancy (two small items)
|
||||
|
||||
- **Severity:** Low · **Category:** perf · **Confidence:** High on the redundancy; cost not measured
|
||||
- **Location:**
|
||||
- `src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs:456-475` (`DecodeCompact`),
|
||||
`:640-663` (`DecodeValues`); `TypedValueCodec.cs:101` (delegated, code reading only).
|
||||
- `src/Core/…Core.Scripting/InProcessScriptRunner.cs` `ScopedKey` (`$"{(int)kind}:{key}"`) and
|
||||
`…OutOfProcess/OutOfProcessScriptRunner.cs` `ShardIndex` (`Encoding.UTF8.GetBytes(scopedKey)`), both called
|
||||
per evaluation from `RunOwnedAsync` / `TryPrepareBatchItem`.
|
||||
|
||||
**Description.**
|
||||
- Each received gRPC value frame is sized three to four times: `Preflight` runs `CalculateSize()` and
|
||||
`DecodedBytes` over every value, the frame is sized again, a second `DecodedBytes` loop follows, and
|
||||
`TypedValueCodec.Decode` sizes each item a third time. `DecodeValues` also decodes and validates `Serving`
|
||||
twice per item.
|
||||
- Every out-of-process evaluation allocates a scoped-key string and a UTF-8 byte array just to pick a shard,
|
||||
although the key and shard are constant for a script.
|
||||
|
||||
**Suggested fix.** Return the sizes from `Preflight` and add an already-preflighted decode entry point. Cache
|
||||
the scoped key and shard index per script (e.g. on the invocation or in a per-seam dictionary keyed by
|
||||
`(kind, key)`), and hash the string's chars directly.
|
||||
|
||||
**Test to add.** An allocation-count or BenchmarkDotNet test over a 1,000-item compact frame, and one over
|
||||
10,000 `RunBatch` items asserting no per-item `byte[]` allocation.
|
||||
|
||||
---
|
||||
|
||||
## Areas reviewed with no findings
|
||||
|
||||
- **Compile / ALC lifecycle:** `ScriptEvaluator` (collectible ALC per evaluator, unload on failed load/bind,
|
||||
wrapper-injection guard), `CompiledScriptCache` (value-scoped removal, `Clear`/`Dispose` drain),
|
||||
`ScriptStackGuard` + injector, `DependencyGraph`.
|
||||
- **Run guard / timeouts:** `ScriptRunGuard` slot accounting, stuck-orphan quarantine, allocation budget,
|
||||
slot release ordering (apart from K-7); `ScriptBatchCoalescer`; `InProcessScriptRunner`;
|
||||
`ShadowScriptRunner` (off-path mirroring, key-busy drop, in-flight cap).
|
||||
- **Out-of-process runner:** `PendingEval` deadline state machine (host clock, worker soft clock, deferral /
|
||||
start re-arming, transport deadline, late soft expiry), `WorkerConnection` handshake / nonce / pid check,
|
||||
exit attribution ordering, `Finish` vs `Submit` race (the `MemoryBarrier` fence), heartbeat / write-stall /
|
||||
progress-ceiling watchdogs, `WorkerShard` start/backoff/recovery, `ResultDispatcher`, key single-flight and
|
||||
isolation-gate handling in `OutOfProcessScriptRunner`, `WorkerLaunchMarker` orphan sweep (pid + start time +
|
||||
image name), `ScriptPeCacheStore` framing and HMAC (trust placement noted under K-1).
|
||||
- **Script worker:** `WorkerHost` scheduler (`Admit` / backlog / start notices), watchdog and soft-clock
|
||||
notices, cancel off the reader thread, parent watch, frame reader buffer management, `ScriptWorkerFrameCodec`
|
||||
length checks (apart from K-5).
|
||||
- **Windows-only code** (`RestrictedWorkerLauncher`, `WindowsJobObject`, `WindowsBlockingPipeStream`,
|
||||
`WorkerPipeSecurity`): read for handle and memory cleanup on failure paths; not executable on this machine,
|
||||
so behaviour is unverified.
|
||||
- **Scripted alarms:** `ScriptedAlarmEngine` gate discipline, persist-before-update, emit-outside-gate, drain
|
||||
coalescing and hand-over, reload carry-over (#935), recovery arming, dispose drain; `Part9StateMachine`
|
||||
other transitions (apart from K-4); `MessageTemplate`.
|
||||
- **Alarm historian:** `LocalDbStoreAndForwardSink` capacity / eviction / counter resync, idempotent enqueue,
|
||||
corrupt-row handling, drain index coverage (`ix_alarm_sf_events_drain` serves the drain read and the
|
||||
dead-letter purge) — apart from K-2; `AlarmSfSchema`, `AlarmConditionStateSchema` migration.
|
||||
- **Core/Authorization** (delegated): `DataPlaneAuthority`, `PermissionTrie*`, `AclScopePathResolver`,
|
||||
`DataOperationPolicy`, `ApiKeySecret`, `ApiKeyAdminService`, `UserAuthorizationState`, `NodeScope` — no
|
||||
bypass found; evaluation fails closed on a missing generation, cluster mismatch and unknown realm.
|
||||
- **Core, other** (delegated): `CapabilityInvoker`, `AlarmSurfaceInvoker`, `DriverCapabilityInvokerFactory`,
|
||||
`DriverResilienceStatusTracker`, `WedgeDetector`, `DriverHost`, `DriverFactoryRegistry`,
|
||||
`GenericDriverNodeManager`.
|
||||
- **Core.Abstractions** (delegated): `PollGroupEngine` lifecycle and teardown (apart from K-10),
|
||||
`CredentialReferences`, `CredentialFilePaths`, `DriverCredentialPolicy`, `TagConfigJson`,
|
||||
`ImportedConditionIds`.
|
||||
- **Commons** (delegated): `DataHistoryProtoMapper`, `DataConditionProtoMapper`, `MeshTransportDtoMapper`,
|
||||
`CsvParser` / `CsvWriter`, `RawPaths`, `RawPathResolver`, `EquipmentScriptPaths`,
|
||||
`DriverDeviceConfigMerger`, `V3NodeIds`, `DeferredAddressSpaceSink`, `DiscoveryDriverBrowser`.
|
||||
|
||||
**Not reviewed in depth:** `DriverArrayWriteSupport` (not cross-checked against each driver's tag factory),
|
||||
the `DataProtoMapper.Preflight` byte budget against the sender-side check, `OtOpcUaTelemetry`, the
|
||||
`Historian/*` contract records, `DependencyExtractor`, `ScriptLogTopicSink`, and the remaining small record /
|
||||
interface files.
|
||||
@@ -0,0 +1,478 @@
|
||||
# Review 07 — Galaxy, OpcUaClient, Historian backends (Gateway / SqlServer / QuestDb / Sql.Common)
|
||||
|
||||
Date: 2026-12-02. Repo: `/Users/dohertj2/Desktop/OtOpcUa` @ `708a4889c` (master). Read-only audit of production code under
|
||||
`src/Drivers/`: `Driver.Galaxy`, `Driver.Galaxy.Browser`, `Driver.Galaxy.Contracts`, `Driver.OpcUaClient`,
|
||||
`Driver.OpcUaClient.Session`, `Driver.OpcUaClient.Browser`, `Driver.OpcUaClient.Contracts`, `Driver.Historian.Gateway`,
|
||||
`Driver.Historian.QuestDb`, `Driver.Historian.SqlServer`, `Driver.Historian.Sql.Common`.
|
||||
|
||||
Method: findings were established by reading the cited code and its callers (`DriverInstanceActor`,
|
||||
`ContinuousHistorizationRecorder`, `LocalDbStoreAndForwardSink`, `NativeAlarmProjector`, and the sibling `mxaccessgw` /
|
||||
`HistorianGateway` repos where the wire contract mattered). **Nothing was built and no test was run** — every finding is
|
||||
from code reading (G-17 additionally from `EXPLAIN` on the QuestDB fixture), and the "Test to add" entries are proposals,
|
||||
not tests that exist. Line numbers are for the commit above.
|
||||
|
||||
Prior review (`docs/reviews/2026-10-21/06-drivers-session.md`, `08-historians-clients.md`): its Galaxy lifecycle findings
|
||||
(G-1 no-op `ShutdownAsync`, G-2 leaked `DeployWatcher`, G-4 dead probe path, G-9/G-10/G-11) and OpcUaClient O-1/O-2/O-8/O-9
|
||||
were checked and are fixed. One item it listed under "no findings" is re-raised here as G-4, marked as such.
|
||||
|
||||
Severity counts: High 1 (G-16) · Medium 6 (G-1, G-7, G-8, G-10, G-11, G-19) · Low 12.
|
||||
|
||||
---
|
||||
|
||||
## Galaxy driver
|
||||
|
||||
### G-1. `GalaxyDriver` secured-write routing is dead: the security map is only filled by `DiscoverAsync`, which the runtime never calls on the live driver
|
||||
|
||||
- Severity: Medium
|
||||
- Category: bug
|
||||
- Confidence: High (dead routing); Medium (the exact MXAccess status an operator sees)
|
||||
- Location: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs:79-80` (`_securityByFullRef`), `:1827` (only writer:
|
||||
`SecurityCapturingBuilder` inside `DiscoverAsync`), `:1851-1852` (`ResolveSecurity` defaults to `FreeAccess`), `:2156-2157`
|
||||
(`WriteAsync` passes the resolver); `Runtime/GatewayGalaxyDataWriter.cs:228-232`, `:272-273` (`NeedsSecuredWrite`),
|
||||
`:365-386` (`InvokeWriteSecuredAsync`, `CurrentUserId = 0`, `VerifierUserId = 0`).
|
||||
- Description: `WriteAsync` picks `WriteSecured` vs. supervisory raw `Write` from `_securityByFullRef`. That map is populated
|
||||
only when `DiscoverAsync` runs on the same instance. In v3 the only production callers of `ITagDiscovery.DiscoverAsync` are
|
||||
`Commons/Browsing/DiscoveryDriverBrowser.cs:159/174`, which construct a throwaway `browse-{guid}` driver; the connect-time
|
||||
discovery loop was deleted and `GenericDriverNodeManager` has no remaining references. The served driver's map is therefore
|
||||
always empty, `ResolveSecurity` returns `FreeAccess` for every tag, and `NeedsSecuredWrite` is never true.
|
||||
- Failure scenario: an operator authors a raw tag on a Galaxy attribute classified SecuredWrite or VerifiedWrite and marks
|
||||
it writable. Every OPC UA write goes down the supervisory raw-`Write` path; `StatusCodeMap` maps MXAccess detail 1012/1013
|
||||
("attribute requires a secured/verified write") to `BadUserAccessDenied`, so the tag can never be written and the status
|
||||
points at permissions rather than at the routing. (It fails closed — this is not a security bypass.) Even if the routing
|
||||
were live, `InvokeWriteSecuredAsync` sends user ids 0/0, so that path has no working identity either.
|
||||
- Suggested fix: carry the classification on the authored tag (capture it at browse-commit into `TagConfig`, read it in
|
||||
`BuildRawTagTables`) instead of depending on a discovery pass; or delete the secured path and refuse such tags at the
|
||||
deploy gate with a clear message. Decide what identity a secured write should carry before reviving it.
|
||||
- Test to add: construct `GalaxyDriver` via the production path with a raw tag whose attribute is SecuredWrite, never call
|
||||
`DiscoverAsync`, write, and assert the writer received `SecurityClassification.SecuredWrite` (today it receives `FreeAccess`).
|
||||
|
||||
### G-2. `StatusCodeMap.FromQualityByte` logs a Warning for every event carrying an unlisted quality byte, on the pump's dispatch thread
|
||||
|
||||
- Severity: Low
|
||||
- Category: perf
|
||||
- Confidence: High
|
||||
- Location: `Runtime/StatusCodeMap.cs:105` (`_ => Categorize(q, logger)`), `:251-264` (`Categorize` → `Log` → `LogWarning`,
|
||||
no once-guard); called per event from `Runtime/EventPump.cs:590`. Contrast `LogCategoryLevelOnce` (`:218`), which is
|
||||
de-duplicated.
|
||||
- Description: the table lists 15 exact OPC DA quality bytes. Any other byte — notably the same qualities with limit bits
|
||||
set (0xC1–0xC3, 0x41–0x43, …) — is categorised correctly but logs one Warning per event, forever.
|
||||
- Failure scenario: a Galaxy area fed by an OPC-sourced DI object reports `Good | LowLimited` (0xC1) on a few hundred
|
||||
attributes at 1 s cadence: several hundred Warning lines per second from the single dispatch thread. Log I/O slows the
|
||||
dispatch loop, the bounded channel fills, and events start dropping (G-4).
|
||||
- Suggested fix: warn once per distinct byte (a 256-entry flag array) and count the rest on a meter; consider masking the
|
||||
two limit bits before the table lookup.
|
||||
- Test to add: feed 1,000 events with quality 0xC1 through `EventPump`; assert exactly one Warning and status Good.
|
||||
|
||||
### G-3. `DeployWatcher` re-subscribes with no delay when the gateway completes the stream cleanly
|
||||
|
||||
- Severity: Low
|
||||
- Category: bug
|
||||
- Confidence: Medium (code path is certain; how often the gateway completes the stream without an error was not observed)
|
||||
- Location: `Browse/DeployWatcher.cs:205-206` (`"stream completed; re-subscribing"` → `continue`); backoff exists only in the
|
||||
`catch (Exception)` arm, and is reset on every received event.
|
||||
- Description: a `WatchAsync` enumeration that ends without throwing loops straight back into a new RPC. There is no delay
|
||||
and no attempt counter on this arm.
|
||||
- Failure scenario: the gateway (or a proxy in front of it) ends server-streams gracefully — e.g. during a drain on
|
||||
shutdown, or an idle-stream limit. The watcher opens a new stream as fast as the RPC round-trips until the listener
|
||||
actually closes, each iteration delivering the bootstrap event (which also resets the backoff). A gateway that always
|
||||
completes after the bootstrap event would be hammered indefinitely with health unaffected.
|
||||
- Suggested fix: treat a clean completion like a fault for pacing purposes — apply the same backoff (at least
|
||||
`_initialBackoff`) before re-subscribing, resetting it only after a stream has stayed open for some minimum time.
|
||||
- Test to add: a source whose `WatchAsync` yields one event then completes; assert at most N subscribe calls in a 1 s window.
|
||||
|
||||
### G-4. A data-change event dropped by the full `EventPump` channel leaves its tag stale-Good with no resync (still present; listed under "no findings" in the 2026-10-21 review)
|
||||
|
||||
- Severity: Low
|
||||
- Category: bug (quality contract)
|
||||
- Confidence: High on the code; the trigger needs a sustained dispatch stall
|
||||
- Location: `Runtime/EventPump.cs:295-301` (newest-dropped `TryWrite`, counter only); no caller reacts to
|
||||
`galaxy.events.dropped`.
|
||||
- Description: MXAccess only sends a value when it changes. When the bounded channel (default 50,000) is full, the newest
|
||||
event is discarded and counted. Nothing marks the affected tag, forces a re-advise, or degrades health, so the node keeps
|
||||
the previous value with Good status until that attribute happens to change again. The replay-gap path shows the intended
|
||||
remedy for "we missed events" (`OnEventPumpReplayGap` re-snapshots), but a local drop does not use it.
|
||||
- Failure scenario: a slow `OnDataChange` consumer (or the log flood in G-2) stalls dispatch during a burst; a setpoint that
|
||||
changes once during the stall is dropped. Clients read the old setpoint as Good indefinitely.
|
||||
- Suggested fix: on the first drop of a burst, schedule the same coalesced re-snapshot the replay-gap path uses (once the
|
||||
channel has drained), or record dropped item handles and re-advise just those.
|
||||
- Test to add: capacity-1 pump, block the handler, push two changes for one handle, release; assert the tag ends at the
|
||||
second value (today it stays at the first).
|
||||
|
||||
### G-5. Per-event allocations in the Galaxy fan-out path
|
||||
|
||||
- Severity: Low
|
||||
- Category: perf
|
||||
- Confidence: High
|
||||
- Location: `Runtime/SubscriptionRegistry.cs:229-230` (`new List<(long,string)>()` plus `bag.Distinct()` over an
|
||||
`ImmutableHashSet<long>`, which is already distinct); `Runtime/EventPump.cs:549` (`_handleFactory(subscriptionId)` — a new
|
||||
`GalaxySubscriptionHandle` per subscriber per event), `:358` (`DataChangeEventArgs`), `GalaxyDriver.cs:3347` (`args with`
|
||||
copy when RawPath differs from the attribute ref, i.e. for every authored tag).
|
||||
- Description: every data-change event allocates a list, a LINQ `Distinct` iterator with its internal set, a boxed
|
||||
immutable-set enumerator, a handle object, and two event-args records. `ImmutableHashSet` enumeration is itself a tree walk.
|
||||
- Estimated cost: roughly 6–8 allocations (several hundred bytes) per event; at 20k events/s that is on the order of
|
||||
100k+ allocations/s of avoidable gen-0 pressure on the single dispatch thread. Not measured.
|
||||
- Suggested fix: store subscribers per item handle as a pre-built immutable array of `(handle object, fullRef, rawPath)` built
|
||||
at `Bind` time; drop `Distinct()`; cache one `GalaxySubscriptionHandle` per subscription; resolve RawPath at bind time so
|
||||
`OnPumpDataChange` does not re-map and copy.
|
||||
- Test to add: an allocation-budget benchmark/test over `EventPump.Dispatch` for one handle with one subscriber.
|
||||
|
||||
### G-6. Replay-gap re-snapshot re-advises every tag without releasing the previous handles (latent — unreachable today)
|
||||
|
||||
- Severity: Low
|
||||
- Category: bug (leak)
|
||||
- Confidence: High on the code; currently unreachable because the pump always streams with `afterWorkerSequence: 0`
|
||||
(`Runtime/GatewayGalaxySubscriber.cs`, `StreamEventsAsync`) and the gateway only emits `ReplayGap` on a resume
|
||||
- Location: `GalaxyDriver.cs:2640-2689` (`OnEventPumpReplayGap` → `ResubscribeAllAsync(SnapshotEntries())`), `:1444-1466`
|
||||
(`SubscribeBulkAsync` then `TryRebind` — the old bindings are overwritten, never unsubscribed).
|
||||
- Description: on a reconnect the old handles die with the session, so re-subscribing is correct. On a replay gap the
|
||||
session is the same: `SubscribeBulk` is `AddItem` + `Advise` per tag on the worker, so each pass adds a second advise per
|
||||
tag, and the superseded handles keep delivering events that the registry now drops as stale.
|
||||
- Failure scenario: if stream resume (`afterWorkerSequence > 0`) is ever enabled, each gap doubles the gateway-side advise
|
||||
count and the event volume for the life of the session.
|
||||
- Suggested fix: in the gap path, unsubscribe each entry's previous live handles after the rebind succeeds.
|
||||
- Test to add: fake subscriber, raise a `ReplayGap`, assert `UnsubscribeBulkAsync` was called with the pre-gap handles.
|
||||
|
||||
### G-19. A silently dead gateway connection (no FIN/RST) never faults the event stream, so Galaxy stays Healthy with stale Good values
|
||||
|
||||
- Severity: Medium
|
||||
- Category: bug (health / quality contract)
|
||||
- Confidence: Medium (from code and .NET defaults; not reproduced — needs a black-holed connection, e.g. the S7 blackhole recipe pointed at the gateway port)
|
||||
- Location: `GalaxyDriver.cs:2703-2748` and `:2542-2555` (the only two `ReportTransportFailure` call sites — both driven by
|
||||
the `EventPump` stream ending); `GalaxyDriverFactoryExtensions.cs` (`StreamTimeoutSeconds` default `0` = unlimited);
|
||||
`Contracts/GalaxyDriverOptions.cs:130-139`. The gRPC handler is built in the sibling client
|
||||
(`MxAccessGateway/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClient.cs:398-403`) with only `ConnectTimeout` — no
|
||||
`KeepAlivePingDelay` / `KeepAlivePingTimeout`, so HTTP/2 keep-alive pings are off (.NET default).
|
||||
- Description: the reconnect supervisor is triggered only when `StreamEvents` throws or completes. On a server-streaming
|
||||
call the client sends nothing after the request, so if the gateway host loses power or a firewall starts dropping the
|
||||
flow, no TCP error ever surfaces and `MoveNextAsync` waits indefinitely. Nothing else probes the session: there is no
|
||||
client keep-alive RPC, unary calls that time out (read/write/subscribe) do not report to the supervisor, and the #527
|
||||
watchdog needs a non-Healthy state, which the driver never reaches. The alarm feed's `StreamAlarms` stream has the same
|
||||
exposure.
|
||||
- Failure scenario: a read-only Galaxy deployment (static subscription set, no writes). The gateway VM is hard-powered-off
|
||||
or a network partition opens. `GetHealth()` stays Healthy, the transport host entry stays Running, no node goes
|
||||
`BadNoCommunication`, and every value is served at its last reading as Good until something happens to send bytes on that
|
||||
connection or the process restarts. A gateway process crash is not affected (the OS closes the socket).
|
||||
- Suggested fix: enable HTTP/2 keep-alive pings on the client handler (`KeepAlivePingDelay` ~15 s, `KeepAlivePingTimeout`
|
||||
~10 s, `KeepAlivePingPolicy = Always`) — a `mxaccessgw` client change, so file it cross-repo; and/or have the driver run
|
||||
a cheap periodic unary liveness call on the session channel and report a failure to the supervisor.
|
||||
- Test to add: fake `IGalaxySubscriber` whose stream never yields and never faults plus a liveness seam that fails; assert
|
||||
the supervisor leaves Healthy within the liveness budget. Live: black-hole the gateway port and watch `/hosts`.
|
||||
|
||||
---
|
||||
|
||||
## Historian — Gateway backend
|
||||
|
||||
### G-7. `FasterLogHistorizationOutbox.RemoveAsync` can truncate an entry that was enqueued but not yet indexed — a silently lost historized value
|
||||
|
||||
- Severity: Medium
|
||||
- Category: bug (data loss, race)
|
||||
- Confidence: High on the interleaving; the frequency estimate is reasoning, not measurement
|
||||
- Location: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/Recorder/FasterLogHistorizationOutbox.cs:151-155`
|
||||
(`EnqueueAsync` outside the lock, then `lock (_state)` to index), `:293-315` (`RemoveAsync`:
|
||||
`truncateTo = node.Next?.Value.Start ?? _log.TailAddress`, `_nextScanAddress = truncateTo`, `TruncateUntil`). Concurrent
|
||||
callers: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ContinuousHistorizationRecorder.cs:387/619` (append loop on its
|
||||
own `Task.Run`) and `:840/967/1027` (drain, piped off the actor).
|
||||
- Description: the append loop and the drain run concurrently. `AppendBatchAsync` advances the log tail in `EnqueueAsync`
|
||||
and only afterwards takes `_state` to add the entry to `_live`. If `RemoveAsync` for the last indexed entry runs in that
|
||||
gap, `node.Next` is null, so it truncates to `_log.TailAddress` — which already includes the new, un-indexed entry — and
|
||||
moves `_nextScanAddress` past it. The new entry is then indexed as a phantom whose address is below the scan head: it is
|
||||
never peeked, never sent, and is cleaned out of `_live` by the next prefix removal. No counter moves (`DroppedCount` is
|
||||
untouched).
|
||||
- Failure scenario: steady state — the drain keeps up, so each drained batch ends at the last indexed entry and every
|
||||
`RemoveAsync` takes the `TailAddress` branch. One value arrives while the drain's historian write is completing; its
|
||||
enqueue lands between tail advance and index. That value is never historized. The window is sub-microsecond on the
|
||||
synchronous enqueue path, so the per-drain probability is small, but it is exposed on every drain for the life of the
|
||||
process, and it is much wider whenever `EnqueueAsync` completes asynchronously (page roll / flush wait).
|
||||
- Suggested fix: make enqueue + index atomic with respect to the head computation — e.g. take `_state` around a synchronous
|
||||
`_log.Enqueue` and the `_live.AddLast`, or have the drain truncate to the `next` address the scan returned for the last
|
||||
peeked record (the pattern `PeekBatchAsync` already uses for the unreadable-head drop) instead of the live tail.
|
||||
- Test to add: a test seam between `EnqueueAsync` and the index lock; park an append there, `RemoveAsync` the current last
|
||||
entry, release; assert the parked entry is returned by the next `PeekBatchAsync` (today it is not).
|
||||
|
||||
### G-8. `GatewayAlarmHistorianWriter` classifies gRPC `Cancelled` / `Unknown` (and every non-RPC exception) as `PermanentFail`, dead-lettering alarm events on a transient gateway condition
|
||||
|
||||
- Severity: Medium
|
||||
- Category: bug
|
||||
- Confidence: Medium (the classification is certain; that the gateway returns `Cancelled` on shutdown/internal timeout is
|
||||
read from its `HistorianRpcFaults` mapping, not observed live)
|
||||
- Location: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs:286-299` (`Classify`,
|
||||
default arm `PermanentFail`), `:301-317` (`ClassifyStatus`, default arm `PermanentFail`; `Cancelled`, `Unknown`,
|
||||
`DataLoss`, `NotFound` unlisted). Consumer: `Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs:442` flips `dead_lettered`.
|
||||
- Description: the client wraps every `RpcException` as `HistorianGatewayException { InnerException: RpcException }`, so the
|
||||
outcome is decided by `ClassifyStatus`. The HistorianGateway maps a server-side `OperationCanceledException` to
|
||||
`StatusCode.Cancelled` and itself treats `Cancelled` as transient (`HistorianRpcFaults.cs:109-110`), but here it falls to
|
||||
the default arm. `Unknown` (an unmapped server exception) does the same. In `Classify`, anything that is not one of the
|
||||
named gateway exception types or an `RpcException` — `ObjectDisposedException`, `IOException`, `HttpRequestException`, a
|
||||
`HistorianGatewayException` without an inner `RpcException` — is also permanent.
|
||||
- Failure scenario: the gateway is restarted while a `SendEvents` batch is in flight and answers `Cancelled`. The batch is
|
||||
"refused", each event is re-sent singly (`SendSinglesAsync`), those also get `Cancelled`, and up to the whole drained batch
|
||||
of alarm transitions is dead-lettered instead of retried seconds later. Alarm history has a hole until an operator
|
||||
requeues the dead letters.
|
||||
- Related: G-16 — even the codes this writer does classify as `RetryPlease` are dead-lettered once the outage outlasts the
|
||||
sink's attempt cap.
|
||||
- Suggested fix: invert the default — treat unknown status codes and unknown exception types as `RetryPlease`, and list
|
||||
only the codes that prove a bad event (`InvalidArgument`, `OutOfRange`, `FailedPrecondition`, `Unimplemented`) as
|
||||
permanent. Add `Cancelled`, `Unknown`, `DataLoss` to the retry arm explicitly.
|
||||
- Test to add: client stub throwing `HistorianGatewayException(inner: RpcException(Cancelled))` from both `SendEventsAsync`
|
||||
and `SendEventAsync`; assert every outcome is `RetryPlease`.
|
||||
|
||||
### G-9. Any failed read marks the gateway connection closed in the health snapshot, including request-level refusals
|
||||
|
||||
- Severity: Low
|
||||
- Category: bug (health contract)
|
||||
- Confidence: High on the code; impact depends on what consumes `ProcessConnectionOpen`
|
||||
- Location: `GatewayHistorianDataSource.cs:1016-1020` (`RecordReadFailure`), `:1032` (`_lastObservationOpen = success`),
|
||||
reached from the catch-all arms at `:288`, `:552`, `:601`, `:663`, `:694`.
|
||||
- Description: the catch-all in each read records a failure for every exception that is not cancellation, a ceiling
|
||||
rejection or an aggregate-not-supported refusal — e.g. an `InvalidArgument` for a malformed window or tag name. That
|
||||
increments `ConsecutiveFailures` and sets `ProcessConnectionOpen`/`EventConnectionOpen` false although the gateway just
|
||||
answered. The next successful read or probe tick flips it back.
|
||||
- Failure scenario: a client polling HistoryRead with a bad argument keeps the historian showing "connection closed" with a
|
||||
growing consecutive-failure count while the gateway is healthy.
|
||||
- Suggested fix: only transport failures (`IsTransportFailure`) should clear `_lastObservationOpen`; count answered refusals
|
||||
separately (or as successes for connectivity purposes).
|
||||
- Test to add: client stub throwing `RpcException(InvalidArgument, "bad window")`; assert `ProcessConnectionOpen` stays true.
|
||||
|
||||
---
|
||||
|
||||
## OpcUaClient driver
|
||||
|
||||
### G-10. In-place recovery re-publish is O(refs × monitored items) under the delivery lock
|
||||
|
||||
- Severity: Medium
|
||||
- Category: perf
|
||||
- Confidence: High
|
||||
- Location: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs:4190-4192` (`PublishUpstreamLocked`:
|
||||
`rs.ItemHandlers.Any(p => RefOf(p.Item) == fullRef)` per subscription), called once per ref from
|
||||
`RecoverAfterOutageAsync` (`:4152-4162`) and `ReconcileAfterRecoveryAsync` (`:4233-4243`).
|
||||
- Description: each recovered ref linearly scans every monitored item of every subscription (plus a closure allocation)
|
||||
while holding `_deliveryLock`. A same-session recovery re-publishes every subscribed ref, so the total is about N²/2
|
||||
string compares.
|
||||
- Estimated cost: 50k tags on one subscription ≈ 1.25 × 10⁹ compares — estimated tens of seconds of CPU (not measured) during
|
||||
which live notifications queue on the lock and nodes stay `BadNoCommunication`. 10k tags ≈ 5 × 10⁷.
|
||||
- Suggested fix: keep a `ref → subscription handle(s)` map (or a per-`RemoteSubscription` `HashSet<string>`) built at
|
||||
subscribe time and look up in O(1).
|
||||
- Test to add: 20k refs via `AddSubscriptionForTest`, drive bad then good keep-alives on a mock session, assert the
|
||||
recovery task completes within a tight bound (or count `RefOf` calls through a seam).
|
||||
|
||||
### G-11. `UnsubscribeAsync` removes the registry entry before it holds the gate; a cancelled wait orphans a live, still-delivering subscription
|
||||
|
||||
- Severity: Medium
|
||||
- Category: bug (subscription leak / duplicate delivery)
|
||||
- Confidence: Medium
|
||||
- Location: `OpcUaClientDriver.cs:2105-2129` (`TryRemove` at `:2108`, cancellable `_subscriptionGate.WaitAsync` at `:2111`,
|
||||
detach + delete only at `:2119-2120`). Caller: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs:2512-2541`
|
||||
(5 s token, exception swallowed). `UnsubscribeAlarmsAsync` (`:2649-2675`) has the same ordering.
|
||||
- Description: if the gate wait is cancelled, the SDK subscription is never deleted and its `Notification` handlers are
|
||||
never detached, yet the driver no longer tracks it; a retried unsubscribe returns at the failed `TryRemove`.
|
||||
`PublishNotification` does not consult the registry, so the orphan keeps raising `OnDataChange` on the old handle until
|
||||
the session is released.
|
||||
- Failure scenario: the gate is held by a `ConditionRefresh` against a slow upstream (bounded by the 10 s operation timeout,
|
||||
longer than the host's 5 s unsubscribe token). A deploy's data re-subscribe arrives in that window: the unsubscribe is
|
||||
cancelled, the new set is subscribed anyway. Result: two server-side subscriptions, duplicate values, values still
|
||||
published for tags the deploy removed, and an upstream subscription slot leaked.
|
||||
- Suggested fix: acquire the gate first, then `TryRemove`; or on a cancelled wait detach the handlers synchronously and
|
||||
queue a deferred best-effort delete.
|
||||
- Test to add: hold the gate, call `UnsubscribeAsync` with a cancelled token, release, deliver a notification; assert
|
||||
nothing reaches `OnDataChange` and the delete was eventually issued.
|
||||
|
||||
### G-12. Per-item monitored-item create failures and unresolvable refs are silent on subscribe
|
||||
|
||||
- Severity: Low
|
||||
- Category: bug (quality / diagnostics)
|
||||
- Confidence: High on the code; Medium on what the host displays for such a node
|
||||
- Location: `OpcUaClientDriver.cs:2060-2087` (`continue` at `:2062` for an unresolvable ref; `item.Status.Error` /
|
||||
`item.Created` never inspected after `CreateItemsAsync` at `:2086`).
|
||||
- Description: a ref whose node id does not resolve, or whose monitored item the server rejects (`BadNodeIdUnknown`,
|
||||
`BadAttributeIdInvalid`, …), gets no Bad publish, no log and no skipped-tag entry; the subscribe succeeds and health is
|
||||
Healthy.
|
||||
- Failure scenario: an upstream is re-commissioned with renamed nodes. After the reconnect those tags never receive a value
|
||||
or status from the driver and sit at the host's last stamp (`BadNoCommunication`), pointing the operator at comms rather
|
||||
than at a bad address.
|
||||
- Suggested fix: after `CreateItemsAsync`, publish one Bad `DataChangeEventArgs` per failed item with the item's error code
|
||||
(`BadNodeIdInvalid` for unresolved refs), log one summarised warning, and add them to the skipped-tag ledger.
|
||||
- Test to add: subscribe one good and one unknown upstream node; assert the unknown ref gets exactly one Bad `OnDataChange`
|
||||
with the upstream code.
|
||||
|
||||
### G-13. A non-condition event from an authored alarm source is forwarded as `Unspecified`, which the host records as "Activated"
|
||||
|
||||
- Severity: Low
|
||||
- Category: bug
|
||||
- Confidence: Medium (depends on the upstream emitting such events)
|
||||
- Location: `OpcUaClientDriver.cs:2928-2933` (`state is null` branch), source match at `:3636-3639`; host side
|
||||
`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/NativeAlarmProjector.cs:150-153`.
|
||||
- Description: the alarm item is an unfiltered event subscription on the Server object. Any event whose `SourceNode` is an
|
||||
authored alarm tag's node and that carries no `ActiveState`/`AckedState` (audit events, system events) is emitted with
|
||||
`Kind = Unspecified`, unflagged; the projector's default arm overwrites the condition's message/severity and writes a
|
||||
history row rendered "Activated".
|
||||
- Failure scenario: an alarm tag authored on a source variable of an upstream with auditing enabled — every audited write
|
||||
to that variable adds an "Activated" `/alerts` row and replaces the condition's message with the audit text.
|
||||
- Suggested fix: drop events with no condition state / empty ConditionId when an authored index is in use, or add an
|
||||
`OfType(ConditionType)` where-clause to the event filter.
|
||||
- Test to add: `RouteAlarmEvent` with an `AuditWriteUpdateEventType` field list for an authored source; assert no
|
||||
`OnAlarmEvent`.
|
||||
|
||||
### G-14. A write that fails after dispatch is reported `BadCommunicationError` ("did not reach the server") instead of `BadTimeout` ("outcome unknown")
|
||||
|
||||
- Severity: Low
|
||||
- Category: bug (write-confirm semantics)
|
||||
- Confidence: Medium (assumes SDK 2.0.1 surfaces its operation timeout as `ServiceResultException(BadRequestTimeout)`; not
|
||||
confirmed against the SDK)
|
||||
- Location: `OpcUaClientDriver.cs:1614-1633`.
|
||||
- Description: only `OperationCanceledException` maps to `BadTimeout`. The generic catch — commented "Pre-wire transport
|
||||
failure — the write definitely did not reach the server" — also receives `BadRequestTimeout`, `BadSecureChannelClosed` and
|
||||
`BadConnectionClosed`, all of which can occur after the request was sent.
|
||||
- Failure scenario: the upstream applies a setpoint but its response is lost in a stall; the SDK timeout fires before the
|
||||
host's and the operator sees `0x80050000` for a write that took effect. Today the host treats every non-Good result as a
|
||||
failure, so the impact is the misleading code.
|
||||
- Suggested fix: map `ServiceResultException` with `BadRequestTimeout` / `BadTimeout` / `BadSecureChannelClosed` /
|
||||
`BadConnectionClosed` / `BadRequestInterrupted` to `BadTimeout`.
|
||||
- Test to add: mock session whose `WriteAsync` throws `ServiceResultException(BadRequestTimeout)`; assert `0x800A0000`.
|
||||
|
||||
### G-15. Test Connect probes' TCP preflight is IPv4-only (OpcUaClient and Galaxy)
|
||||
|
||||
- Severity: Low
|
||||
- Category: bug
|
||||
- Confidence: High on the socket family; the resulting message was inferred, not run
|
||||
- Location: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriverProbe.cs:63-64`
|
||||
(`new Socket(AddressFamily.InterNetwork, …)`).
|
||||
- Description: an IPv6 literal or AAAA-only host cannot connect on that socket, so the probe fails before the OPC UA
|
||||
handshake, while the driver itself supports IPv6 endpoints (#819).
|
||||
`GalaxyDriverProbe` has the same IPv4-only preflight (`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverProbe.cs`,
|
||||
the `new Socket(AddressFamily.InterNetwork, …)` before `TestConnectionAsync`).
|
||||
- Failure scenario: `opc.tcp://[fe80::1%eth0]:4840` shows a red Test Connect although a deploy would connect.
|
||||
- Suggested fix: `new Socket(SocketType.Stream, ProtocolType.Tcp)` (dual-mode) or `TcpClient.ConnectAsync(host, port, ct)`.
|
||||
- Test to add: probe against a listener bound to `[::1]`; assert success.
|
||||
|
||||
---
|
||||
|
||||
## Historian — alarm writers (all three backends) and SQL backends
|
||||
|
||||
### G-16. A historian outage longer than about 6.5 minutes dead-letters queued alarm events: every writer answers an outage with `RetryPlease`, and the sink counts each one against `MaxAttempts`
|
||||
|
||||
- Severity: High
|
||||
- Category: bug (data loss)
|
||||
- Confidence: High on the mechanism (read in the writers and the sink; not executed). The 6.5-minute figure is derived
|
||||
from the backoff ladder (1 + 2 + 5 + 15 + 60 s, then 60 s per attempt, 10 attempts).
|
||||
- Location: writers — `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.SqlServer/SqlServerAlarmHistorianWriter.cs:53`, `:142-147`;
|
||||
`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbAlarmHistorianWriter.cs:60`, `:136-142`;
|
||||
`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/AlarmBatchWrite.cs:64-77`;
|
||||
`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayAlarmHistorianWriter.cs:286-317` (`Unavailable`,
|
||||
`DeadlineExceeded`, auth failures → `RetryPlease`; the class never throws). Consumer (outside this slice):
|
||||
`src/Core/ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian/LocalDbStoreAndForwardSink.cs:447-462` (dead-letters when
|
||||
`AttemptCount + 1 >= MaxAttempts`, default 10), `:399-409` (the only no-bump path: the writer throwing).
|
||||
- Description: all three writers swallow outage-class failures (database or gateway unreachable, failed schema bootstrap,
|
||||
transient SQL error, caller cancellation) and return one `RetryPlease` per event. The sink cannot tell an outage from a
|
||||
poison row: it bumps `attempt_count` for every `RetryPlease` and dead-letters at the cap. `RetryDeadLettered()` has no
|
||||
production caller, so dead-lettered rows are only purged after `DeadLetterRetentionDays`.
|
||||
- Failure scenario: the SQL Server historian (or the HistorianGateway) is down for 20 minutes of patching. The head batch
|
||||
is retried at 1 → 2 → 5 → 15 → 60 s and dead-lettered on its 10th drain, about 6.5 minutes in; with the backoff pinned at
|
||||
60 s, a further batch is dead-lettered roughly every 10 minutes. When the backend returns the drain reports healthy, but
|
||||
the oldest alarm history of the outage is never written.
|
||||
- Secondary effect (SQL backends): `AlarmBatchWrite` falls back to per-event sends only on `PermanentFail`. A deterministic
|
||||
error the classifier does not recognise is `RetryPlease` for the whole chunk (150 rows SqlServer, 500 QuestDb, whose
|
||||
classifier is a five-string message match), so one unrecognised poison event takes its chunk-mates to the dead-letter
|
||||
table.
|
||||
- Suggested fix: one of — (a) in the sink, do not bump attempts on a drain in which no event was `Ack`/`PermanentFail`
|
||||
(the "did anything else succeed this pass?" discriminator #538 uses for the value outbox); or (b) have the writers throw
|
||||
on a systemic failure (bootstrap failure, or a transient failure with nothing acked) so the sink takes its no-bump path.
|
||||
Either way, split a chunk that fails with a non-transient, unclassified error.
|
||||
- Test to add: sink + writer against a backend that refuses connections for `MaxAttempts + 2` drains and then recovers —
|
||||
assert zero dead letters and every event written; control: one genuinely poison event among healthy ones still
|
||||
dead-letters alone. `AlarmBatchWrite` unit test: chunk of 3, callback throws an unclassified non-transient exception for
|
||||
one index ⇒ the other two `Ack`.
|
||||
|
||||
### G-17. QuestDB reverse / end-only event reads scan the whole window on every page
|
||||
|
||||
- Severity: Low
|
||||
- Category: perf
|
||||
- Confidence: High on the plan (four `EXPLAIN` statements run on the shared QuestDB fixture); Medium on impact (depends on
|
||||
event volume)
|
||||
- Location: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb/QuestDbHistorianDataSource.cs:465-482`
|
||||
(`ORDER BY ts DESC, event_id DESC LIMIT n`).
|
||||
- Description: the forward form plans as a partially-sorted `Encode sort light` that stops early. The reverse form plans as
|
||||
`Async Top K` (no source filter) or a plain sort (with `source = …`) over a forward scan of the entire window, with no
|
||||
early exit. Raw reverse reads are unaffected (`Index backward scan`).
|
||||
- Failure scenario: a client asks for the latest 1,000 alarms on an equipment folder (end-only, so the window is epoch to
|
||||
EndTime). Every page reads every event row for that source — the whole table with no source filter — and pays it again
|
||||
per continuation page; with no TTL the cost grows with table age. `ServerHistorian:EventReadHorizon` bounds it but is
|
||||
opt-in.
|
||||
- Suggested fix: find the boundary first (`SELECT ts … ORDER BY ts DESC LIMIT n+1`, a backward scan with early exit), then
|
||||
read `ts >= boundary` and order by `(ts DESC, event_id DESC)` so boundary ties are still chosen by `event_id`.
|
||||
- Test to add: integration test (`HISTORIAN_QUESTDB_TEST_CONNECTION`) asserting the reverse query's `EXPLAIN` contains a
|
||||
backward scan, plus a tie-at-the-cut case comparing paged reverse results with an unpaged read.
|
||||
|
||||
### G-18. `TimeWeightedAggregator` allocates two delegates and a closure per sample
|
||||
|
||||
- Severity: Low
|
||||
- Category: perf
|
||||
- Confidence: High (code read; allocation size estimated, not profiled)
|
||||
- Location: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common/TimeWeightedAggregator.cs:403-408`, `:426-432`, `:493`.
|
||||
- Description: `AddRaw` and `AddBridged` each pass a fresh capturing lambda to `Distribute` for every usable sample.
|
||||
- Estimated cost: about 160 B per sample — roughly 160 MB of gen-0 churn for one read at the default
|
||||
`MaxTimeWeightedRawRows` (1,000,000). Several such reads can be in flight, and the Gateway backend's raw-evaluated
|
||||
aggregates share the evaluator.
|
||||
- Suggested fix: give `Distribute` an enum/bool target and write into the arrays directly.
|
||||
- Test to add: allocation guard (`GC.GetAllocatedBytesForCurrentThread`) around `Evaluate` over 100k samples, asserting
|
||||
O(buckets) not O(samples).
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Areas reviewed with no findings
|
||||
|
||||
**Galaxy**
|
||||
- Lifecycle: `ShutdownAsync` / `InitializeAsync` / `DisposeAsync` now share `TeardownRuntimeAsync` under `_lifecycleGate`;
|
||||
supervisor, deploy watcher, probe watcher, pump, alarm feed, MX session and both gRPC clients are stopped and released;
|
||||
the host tears down before every retry (`DriverInstanceActor` `RetryConnect`, `teardownFirst: true`). Runtime-generation
|
||||
and session fences on subscribe / read / replay / seed.
|
||||
- `ReconnectSupervisor` state machine, backoff, fault-during-replay retry, `StopAsync`.
|
||||
- `SubscriptionRegistry` early-event parking, window-sequence trimming, session invalidation; `ReadViaSubscribeOnceAsync`
|
||||
deadline, late-subscribe cleanup and handle release.
|
||||
- Health: supervisor-overlaid `GetHealth`, stranded-subscription Degraded, throttled `LastSuccessfulRead` stamp from stream
|
||||
data only.
|
||||
- `GatewayGalaxyDataWriter` fail-closed supervisory advise, lane ordering, reply translation (`Pending`/`Warning` →
|
||||
Uncertain, empty statuses metered).
|
||||
- Alarm feed reconnect loop, snapshot/truncation handling, snapshot re-read supersede logic, told-active reconciliation;
|
||||
ack credential resolution and password scrubbing; ack confirmation tracker.
|
||||
- `PerPlatformProbeWatcher`, `HostStatusAggregator`, `MxValueDecoder` / `MxValueEncoder`, hierarchy paging (repeated-token
|
||||
guard), `GalaxyBrowseSession`.
|
||||
- Not opened: `GalaxyDriverProbe`, `GalaxyDriverFactoryExtensions`, `GalaxyDiscoverer`, `AlarmRefBuilder`, the `Traced*`
|
||||
wrappers, `Galaxy.Contracts`, `GalaxyDriverBrowser`.
|
||||
|
||||
**OpcUaClient**
|
||||
- Init / shutdown / session release generation gating, failed-init discard, cert-validation handler detach, half-built
|
||||
subscription cleanup on data and alarm paths.
|
||||
- Health contract: bad keep-alive → Degraded with the stamp frozen, sticky subscription-lost latch, `ConnectionLost` only
|
||||
on definitive losses, answered refusals not counted as comms faults.
|
||||
- Delivery ordering (replay guard, `_deliveryLock`, trailing reconcile, (value, status) comparison); the #926 refresh
|
||||
bracket / sequence-gap logic; ack target pairing.
|
||||
- Browse continuation-point follow and release in driver and `OpcUaClientBrowseSession`; discovery bounds.
|
||||
- `NamespaceMap`, `OpcUaEndpointSelection`, `OpcUaEndpointUrlRewriter`, `UpstreamValueMapping`, `SdkTelemetry`.
|
||||
- Not opened: `OpcUaUserIdentityFactory`, `OpcUaUserCertificatePaths`, `OpcUaClientTagDefinitionFactory`, `ParseOptions`.
|
||||
`LegacyRsaUserNameIdentityTokenHandler` was read but not verified against the SDK wire format.
|
||||
|
||||
**Historian — Gateway**
|
||||
- Raw read budgeting / crowded-pre-window re-reads / server cap (default 10,000 per read), ceiling learning
|
||||
(`GatewayRowCeiling`), native aggregate request planning and bucket placement, raw-evaluated aggregates
|
||||
(`RawAggregateReader`, `RawBucketAccumulator`), events drain and truncation flag, tag presence cache (bounded, TTL),
|
||||
provisioner (CreateOnly lookup, failure accounting), value writer (duplicate-timestamp first-wins, non-numeric skip),
|
||||
mappers, outbox recovery / capacity drop / unreadable-head handling.
|
||||
- `GatewayAtTimeReader` was skimmed only (read budget and entry logic), not reviewed line by line.
|
||||
|
||||
**Historian — SqlServer / QuestDb / Sql.Common** (read in full)
|
||||
- SQL injection: every value is parameterised; the only interpolated identifiers are the schema and table prefix
|
||||
(regex-validated in the connection constructors) and TVP type names.
|
||||
- UTC handling: `datetime2(7)` + `SpecifyKind(Utc)` on SQL Server; microsecond truncation on QuestDB; pre-1970 handling.
|
||||
- Raw paging and caps (`MaxRawValuesPerRead` wired through, cap+1 probe refuses rather than truncates); modified-read
|
||||
`(SourceTime, ModifiedId)` cursor in both directions on both backends.
|
||||
- Bucket math (T-SQL tick reconstruction, QuestDB `cast(ts AS LONG)*10`, reverse-anchored index) agrees with
|
||||
`BucketPlan.IndexOf`; aggregate evaluators, `AtTimeEvaluator`, `HistoryUpdatePlanner`.
|
||||
- HistoryUpdate on both backends (atomic MERGE/DELETE with `OUTPUT … INTO`, batched `DeleteRaw`; QuestDB trail-before-change,
|
||||
markers, tombstones — per-instance stripe locks remain the documented residual).
|
||||
- Retention (eligible-tag pre-filter, applock release, batch size), schema bootstrap (applock, failure cache), live value
|
||||
writers (insert-if-absent, cancellation, single WAL wait), connection lifetime (all `await using`, no sync-over-async).
|
||||
- The prior review's SQL-historian items 1.1, 3.1–3.4, 4.1, 4.3 were checked and are remediated.
|
||||
|
||||
Side effect to know about: checking G-17 created and dropped two scratch tables (`rvw1202_event`, `rvw1202_sample`) on the
|
||||
shared QuestDB fixture at `10.100.0.35`. No source file was modified.
|
||||
@@ -0,0 +1,483 @@
|
||||
# Review 08 — Drivers: MTConnect, MQTT / Sparkplug B, Heidenhain
|
||||
|
||||
Repo: `/Users/dohertj2/Desktop/OtOpcUa` @ `708a4889c` (master). Production code only, read-only audit.
|
||||
|
||||
Slice (under `src/Drivers/`): `Driver.MTConnect`, `Driver.MTConnect.Contracts`, `Driver.Mqtt`, `Driver.Mqtt.Contracts`,
|
||||
`Driver.Mqtt.Browser`, `Driver.Mqtt.Transport`, `Driver.Heidenhain`, `Driver.Heidenhain.Contracts` (~30k lines).
|
||||
|
||||
Method: the MQTT projects were read in full by the lead; MTConnect and Heidenhain were read in full by two forks, and
|
||||
every fork finding kept here was spot-checked by the lead against the cited lines. Callers in
|
||||
`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs` were read where a finding depends on host
|
||||
behaviour. No test suites were run. One finding (M-2) was confirmed with a throwaway console probe against the pinned
|
||||
MQTTnet 5.2.0.1603.
|
||||
|
||||
Prior review `docs/reviews/2026-10-21/06-drivers-session.md`: M-1…M-11 and T-1…T-8 were checked and are remediated;
|
||||
none is re-reported. M-7 below is a side effect of the old T-2 fix.
|
||||
|
||||
No Critical or High findings. Six Medium, thirteen Low.
|
||||
|
||||
| ID | Sev | Cat | Area | Title |
|
||||
|---|---|---|---|---|
|
||||
| M-1 | Medium | bug | Sparkplug | Rebirth give-up counter is reset by the NBIRTH it provokes — permanent 10 s rebirth storm |
|
||||
| M-2 | Medium | bug | MQTT plain | One malformed topic filter fails the single batched SUBSCRIBE — every tag on the driver goes dark |
|
||||
| M-3 | Medium | bug | Sparkplug | Primary-host client id is the literal `-spbhost` when `clientId` is unset — drivers sharing a broker evict each other |
|
||||
| M-4 | Medium | bug | MTConnect | A fault that raises and clears inside one `/sample` chunk latches "Fault" on the value tag |
|
||||
| M-5 | Medium | bug | MTConnect | Data subscriptions are never released on shutdown/re-init — one `SubscriptionState` leaks per reconnect |
|
||||
| M-6 | Medium | bug | Sparkplug | Primary-host claim is never re-established once its connection goes `Faulted` |
|
||||
| M-7 | Low | bug | MTConnect | `ReadAsync` restart detection advances the cursor without re-baselining the shared index |
|
||||
| M-8 | Low | bug | MTConnect | One malformed observation fails the whole document, and so the whole driver |
|
||||
| M-9 | Low | bug | MTConnect, MQTT | Subscribe's initial replay can overwrite a newer pushed value |
|
||||
| M-10 | Low | bug | MTConnect | Unsubscribing the last handle can cancel a pump a concurrent subscribe relied on (latent) |
|
||||
| M-11 | Low | perf | Sparkplug | Array metrics are boxed element by element, twice |
|
||||
| M-12 | Low | perf | MQTT | Avoidable per-message allocations on the dispatcher thread |
|
||||
| M-13 | Low | bug | MQTT | Abandoned subscription handles accumulate in `_refsByHandle` |
|
||||
| M-14 | Low | bug | MQTT browser | Browse ignores CONNACK and SUBACK verdicts — a refused subscribe is a silently empty tree |
|
||||
| M-15 | Low | bug | MQTT plain | Scalar/Raw boolean writes publish `True` / `False` |
|
||||
| M-16 | Low | bug | Heidenhain | Stopping a control loop is non-deterministic: spurious comms-loss retire, or a cache left Good |
|
||||
| M-17 | Low | bug | Heidenhain | A down control's host status flaps Stopped↔Unknown and its "since" time resets every retry |
|
||||
| M-18 | Low | perf | Heidenhain | Optional-role login is retried on every poll batch with no throttle |
|
||||
| M-19 | Low | bug | Heidenhain | Watchdog re-init resets the reconnect backoff; `MaxDelayMs` above ~90 s is unreachable |
|
||||
|
||||
---
|
||||
|
||||
## Medium
|
||||
|
||||
### M-1. Sparkplug rebirth give-up counter is reset by the NBIRTH it provokes — permanent 10 s rebirth storm
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugIngestor.cs`
|
||||
- `:1830-1848` `RequestMetadataRebirth` (cap `MaxConsecutiveMetadataRebirths = 3`, `:152`)
|
||||
- `:916` and `:957` — `_metadataRebirths.TryRemove(node, out _)` on every NBIRTH and every DBIRTH
|
||||
- `:755-774` — an oversized body is dropped before `Dispatch` (the comment at `:760-762` claims the cap stops the loop)
|
||||
- `:989-1003` (data before birth) and `:1009-1032` (unknown alias) — the two callers besides late-join
|
||||
- `:940-943` — every NBIRTH stales all devices under the node
|
||||
- `:1760-1776` — the sequence-gap path calls `RequestRebirth` directly, with no cap at all
|
||||
- `Sparkplug/AliasTable.cs:163-169` — a collided alias is removed from the table
|
||||
- **Description:** The cap exists so a node that can never supply usable metadata stops being asked. But the counter is
|
||||
cleared whenever *any* birth from the node arrives, and a rebirth request is precisely what makes an NBIRTH arrive.
|
||||
For every cause the NBIRTH does not cure, `attempts` never gets past 1, and the only limiter left is the 10 s
|
||||
debounce. Causes that a rebirth does not cure:
|
||||
- a **DBIRTH** over `maxPayloadBytes` (dropped at `:755`; the NBIRTH is small and accepted);
|
||||
- a DATA metric the birth never declared — the check at `:1012-1017` fires whether or not anyone authored that metric;
|
||||
- a birth with a duplicate alias (the driver itself drops the alias, so every DATA using it is "unknown");
|
||||
- an authored device that publishes DDATA and never DBIRTHs.
|
||||
The gap path is uncapped by design, so a node that does not maintain `seq` (always 0, or two publishers under one
|
||||
edge-node id) loops the same way.
|
||||
- **Failure scenario:** Edge node `EdgeA` has devices `Filler1`…`Filler5`; `Filler3`'s DBIRTH is 1.2 MB.
|
||||
1. `Filler3` DDATA arrives, no alias table → NCMD rebirth (attempt 1).
|
||||
2. `EdgeA` re-births. NBIRTH resets the counter and evicts all five device tables; `FanStale` publishes
|
||||
`BadCommunicationError` (value null) for every authored tag on all five devices.
|
||||
3. Four DBIRTHs restore their devices; `Filler3`'s is dropped again.
|
||||
4. Next `Filler3` DDATA, 10 s later → attempt 1 again → NCMD.
|
||||
Result: every 10 s, forever, the node re-publishes all births and every tag on the four healthy devices blips
|
||||
Bad→Good — visible to every OPC UA client, ScadaBridge and the historian. On a redundant pair both nodes send the NCMD.
|
||||
The `metadata-exhausted` warning that would tell the operator what is wrong never fires.
|
||||
- **Suggested fix:** Reset `_metadataRebirths` only on evidence the request *worked*: in `OnData` when the scope's table
|
||||
is found and every metric resolves (or per scope on its own accepted DBIRTH), not on any birth from the node. Key the
|
||||
counter by `(node, reason-scope)` so one bad device cannot be re-armed by a sibling. Give the gap path a cap or an
|
||||
escalating debounce (10 s → 5 min) as well.
|
||||
- **Test to add:** In `SparkplugIngestorTests` with a fake clock and a publish-transport spy: author two devices, feed
|
||||
NBIRTH + one DBIRTH, then loop {DDATA for the un-birthed device, advance 11 s, NBIRTH + the one DBIRTH} ten times.
|
||||
Assert at most 3 NCMDs and exactly one `metadata-exhausted` warning. Same loop with a DATA metric whose alias the
|
||||
birth does not declare.
|
||||
|
||||
### M-2. One malformed topic filter fails the single batched SUBSCRIBE — every tag on the driver goes dark
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High (client-side case verified); Medium (broker-side case)
|
||||
- **Location:**
|
||||
- `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/MqttConnection.cs:1071-1093` — one SUBSCRIBE packet carries every filter
|
||||
- `MqttSubscriptionManager.cs:751-769` — a throw degrades **every** filter in the batch
|
||||
- `MqttSubscriptionManager.cs:450-484` — `SubscribeAsync` then throws; pending topics ride along on every retry (`:451`)
|
||||
- `MqttSubscriptionManager.cs:579-612` — reconnect includes pending filters and throws on a transport failure
|
||||
- `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttTagDefinitionFactory.cs:107-108` — the only check is non-blank;
|
||||
`:396-402` — a wildcard draws a generic advisory, not a rejection
|
||||
- **Description:** A tag's `topic` is used verbatim as a subscription filter. MQTTnet validates filters client-side and
|
||||
throws for the whole call. Confirmed against 5.2.0.1603: a SUBSCRIBE carrying `good/a` and `plant/#/temp` throws
|
||||
`MqttProtocolViolationException: The character '#' is only allowed as last character` before anything is sent.
|
||||
The manager treats that as a transport failure of the batch. The bad topic stays in `_pendingTopics`, so it is
|
||||
re-added to every later subscribe and every reconnect, and fails them too.
|
||||
A filter the client lets through but the broker rejects as malformed (`plant/te+mp`) was not tested against a broker;
|
||||
Mosquitto closes the connection for it, which would turn the same tag into a reconnect loop.
|
||||
Related and unverified: there is no chunking, so a broker with a per-SUBSCRIBE filter limit (AWS IoT Core allows 8)
|
||||
fails the same way with entirely valid topics.
|
||||
- **Failure scenario:** A plain-mode driver with 2,000 tags; an operator authors one tag with topic `line1/#/temp`.
|
||||
Deploy succeeds (advisory only). The host's subscribe throws `InvalidOperationException`, all 2,000 tags read
|
||||
`BadCommunicationError`, and every health-tick retry fails identically. Connection state is `Connected`, so
|
||||
`GetHealth()` reports Healthy and the #527 watchdog never trips. Nothing recovers until the tag is fixed.
|
||||
- **Suggested fix:**
|
||||
- Validate the filter in `FromTagConfig` with MQTT's rules (`#` only as the last level, `+` and `#` occupy a whole
|
||||
level, no empty topic) and reject the tag, so it alone reads `BadNodeIdUnknown` and shows in the skipped-tag ledger.
|
||||
- In `EstablishAsync`, on a non-cancellation failure of a multi-filter batch, fall back to per-filter (or bisected)
|
||||
SUBSCRIBEs so one filter cannot take the rest down; chunk large batches.
|
||||
- **Test to add:** `MqttSubscriptionManagerTests`: transport stub that throws when any filter equals `a/#/b`; subscribe
|
||||
five tags including that one; assert the other four are established and only the bad tag is Bad. Factory test:
|
||||
`a/#/b`, `a/b+`, `a/#b` are rejected.
|
||||
|
||||
### M-3. Primary-host client id is the literal `-spbhost` when `clientId` is unset — drivers sharing a broker evict each other
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High (mechanism), Medium (how often two such drivers share a broker)
|
||||
- **Location:**
|
||||
- `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs:64` (`ClientIdSuffix = "-spbhost"`), `:415-426`
|
||||
- `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Transport/MqttClientOptionsFactory.cs:90-94`
|
||||
- `docs/drivers/Mqtt.md:152-158` — tells operators to leave `clientId` unset; the AdminUI form defaults it blank
|
||||
- **Description:** The factory builds the id as `Concat(options.ClientId ?? "", suffix)`. With the recommended blank
|
||||
`clientId` that is exactly `-spbhost`, which is non-blank and therefore sent. The ingest connection gets a
|
||||
library-generated unique id; the probe and browser append a random suffix; the host claim is the one connection with
|
||||
a fixed, fleet-wide id. A driver subscribes one Sparkplug group (`GroupFilter`), so a plant with two groups needs two
|
||||
driver instances — both claim with `-spbhost`.
|
||||
- **Failure scenario:** Two Sparkplug drivers with `actAsPrimaryHost: true` point at one broker (two groups on one
|
||||
node, or two clusters sharing a plant broker). B's CONNECT takes over A's session; the broker closes A and publishes
|
||||
A's Will (retained OFFLINE). A's supervisor reconnects after ~1 s, evicts B, re-publishes ONLINE; B's Will fires.
|
||||
Both STATE topics flap ONLINE/OFFLINE about once a second indefinitely. Edge nodes gated on the primary host stop
|
||||
and restart publishing (store-and-forward, rebirths) on every flap. Ingest connections are unaffected, so both
|
||||
drivers report Healthy. A single driver on a redundant pair is safe only because one node claims at a time.
|
||||
- **Suggested fix:** Make the claim id unique per driver instance and node, e.g.
|
||||
`{clientId or "otopcua"}-spbhost-{hostId}-{short node/driver id}`, or append a random suffix as the probe and browser
|
||||
do (the session is forced clean, so nothing depends on a stable id).
|
||||
- **Test to add:** `MqttClientOptionsFactoryTests`/`SparkplugPrimaryHostTests`: two hosts built from options with a null
|
||||
`ClientId` and different driver ids produce different client ids. Live-gate leg: two claims against the Mosquitto
|
||||
fixture stay connected for 30 s with no `already connected` broker log line.
|
||||
|
||||
### M-4. A fault that raises and clears inside one `/sample` chunk latches "Fault" on the condition's value tag
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectObservationIndex.cs:222-239` (`Apply` folds
|
||||
duplicates per document), `:433-442` (`Reconcile`); caller `MTConnectDriver.cs:2756` (every `/sample` chunk)
|
||||
- **Description:** When one `dataItemId` appears twice in a document, `Reconcile` keeps the more severe condition word.
|
||||
That is right for `/current`, where several states are active at once. A `/sample` chunk is a time-ordered delta:
|
||||
`<Fault>` at seq N then `<Normal>` at N+1 resolves to Fault, because the later, less severe challenger loses. The
|
||||
"scoped to one document" remark does not cover this, and `Reconcile` ignores `baseline`. Two more consequences:
|
||||
- Fault followed by `UNAVAILABLE` in one chunk stays Good "Fault" instead of `BadNoCommunication`.
|
||||
- It keys on the value text, not on the observation being a CONDITION, so an EVENT whose values happen to be
|
||||
`Normal`/`Warning`/`Fault` is reordered the same way.
|
||||
- **Failure scenario:** A CONDITION DataItem authored as an ordinary String tag (the default; alarm promotion is
|
||||
opt-in). A fault raises and clears within one `SampleIntervalMs` (1 s default), or during an outage the pump then
|
||||
replays as one catch-up chunk. The tag reads "Fault", Good, until that DataItem's next condition observation —
|
||||
possibly hours. The native-alarm path is unaffected (`MTConnectConditionTracker` handles ordering correctly).
|
||||
- **Suggested fix:** Apply worst-of only when `baseline` is true; use last-wins for `/sample`. Better, derive the value
|
||||
word from `MTConnectConditionTracker` (apply the tracker first), which also fixes a Warning on code B masking a
|
||||
still-active Fault on code A across chunks. Gate on `observation.Condition is not null`.
|
||||
- **Test to add:** `MTConnectObservationIndexTests`: one non-baseline document with Fault then Normal for one id reads
|
||||
"Normal"; Fault then Unavailable reads `BadNoCommunication`; the same pair with `baseline: true` still reads "Fault".
|
||||
|
||||
### M-5. MTConnect data subscriptions are never released on shutdown or re-init — one `SubscriptionState` leaks per reconnect
|
||||
|
||||
- **Severity:** Medium · **Category:** bug / perf (unbounded growth) · **Confidence:** High
|
||||
- **Location:**
|
||||
- `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect/MTConnectDriver.cs:263` (`_subscriptions`), `:1283` (only add),
|
||||
`:1324` (only remove); `ShutdownAsync` `:661-678` never clears it; `:3412` "Standing subscriptions survive a
|
||||
lifecycle restart"; fan-out `:2954-2979`, `MTConnectDriver.CommsLoss.cs:199-215`
|
||||
- Host: `DriverInstanceActor.cs:2549-2556` + `:2584-2599` — `DetachSubscription` nulls the handle without calling
|
||||
`UnsubscribeAsync` (used at `:926` ForceReconnect, `:2677` disconnect, `:3120`); `RetireAcquisitionHandle`
|
||||
(`:2558-2572`) unsubscribes only on the acknowledged-acquisition path, which only `ModbusDriver` implements;
|
||||
`:1947-1951` — the next subscribe sees a null handle and does not unsubscribe either
|
||||
- **Description:** The driver assumes its handles outlive a restart. The actor abandons its handle on every
|
||||
Connected→Reconnecting transition, Force Reconnect and respawn, then subscribes afresh after the next successful
|
||||
init. The old state — a `HashSet` of every reference — stays registered. Galaxy and Heidenhain clear their registries
|
||||
on shutdown (`HeidenhainDriver.cs:140`); MTConnect does not.
|
||||
- **Failure scenario:** Each comms-loss recovery or Force Reconnect adds one orphan. After N cycles on a 5k-tag Agent:
|
||||
- every observation costs N+1 lookups, `DataChangeEventArgs` allocations and handler calls;
|
||||
- with legacy-handle fencing off the actor forwards N+1 copies of each value, with it on they are built and dropped;
|
||||
- memory grows by one full reference set per cycle (roughly 0.5 MB);
|
||||
- `UnsubscribeAsync` never sees "last subscription gone", so the pump keeps streaming with no consumer.
|
||||
An Agent on a flaky link that trips the watchdog a few times a day degrades steadily until the process restarts.
|
||||
- **Suggested fix:** Clear `_subscriptions` (and the alarm slot) in `ShutdownAsync` and at the top of `InitializeAsync`,
|
||||
as Heidenhain does — the actor always re-subscribes. Alternatively make `SubscribeAsync` replace rather than add.
|
||||
- **Test to add:** Subscribe, `ShutdownAsync`, `InitializeAsync`, subscribe again, deliver one chunk; assert
|
||||
`OnDataChange` fires once per reference and only for the new handle. Repeat ten times; registry count stays 1.
|
||||
|
||||
### M-6. Sparkplug primary-host claim is never re-established once its connection goes `Faulted`
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** Medium (path verified; needs a broker that refuses a
|
||||
reconnect with an "unrecoverable" code while still accepting the ingest connection)
|
||||
- **Location:**
|
||||
- `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs:393-398` — `ClaimAsync` returns early
|
||||
whenever `_connection` is non-null ("the connection's own supervisor keeps it that way"); `:181` `IsClaimed`
|
||||
- `MqttConnection.cs:807-819` (`BuildRejection` → `Faulted`), `:1258-1267` (supervisor returns for good),
|
||||
`:1312-1323` (supervisor crash → `Faulted`), `:863-880` (the unrecoverable list)
|
||||
- **Description:** The reconcile loop treats "a connection object exists" as "the claim is held". `MqttConnection`'s
|
||||
supervisor stops permanently when a reconnect CONNACK carries an unrecoverable code (`NotAuthorized`,
|
||||
`BadUserNameOrPassword`, `Banned`, `ServerMoved`, …) or when it faults. Nothing in the primary host reads
|
||||
`connection.State`. For the ingest connection the same condition surfaces as `DriverState.Faulted` and the watchdog
|
||||
re-initialises the driver; the claim connection has no such observer.
|
||||
- **Failure scenario:** The broker restarts and, while its auth backend is still loading, answers one reconnect of the
|
||||
`-spbhost` client with `NotAuthorized`. The ingest connection reconnects a moment later and succeeds, so the driver
|
||||
is Healthy and is never re-initialised. The broker has already published the Will (retained OFFLINE); the host never
|
||||
publishes ONLINE again. Edge nodes gated on this host stay silent until someone restarts the driver. `IsClaimed`
|
||||
stays true and nothing is logged after the single supervisor error.
|
||||
- **Suggested fix:** In `ClaimAsync`, treat `connection.State is Faulted or Disposed` as "not held": dispose it under
|
||||
the gate, clear `_session`, and fall through to a fresh claim (the existing backoff already rate-limits retries).
|
||||
- **Test to add:** `SparkplugPrimaryHostTests`: claim, force the connection to `Faulted` (rejecting CONNACK from a fake
|
||||
broker), advance the reconcile loop; assert a second claim attempt and a fresh ONLINE publish.
|
||||
|
||||
---
|
||||
|
||||
## Low
|
||||
|
||||
### M-7. MTConnect `ReadAsync` restart detection advances the cursor without re-baselining the shared index
|
||||
|
||||
- **Severity:** Low · **Category:** bug · **Confidence:** Medium
|
||||
- **Location:** `MTConnectDriver.cs:770-779` (`PublishAgentCursor(readGeneration, current.InstanceId, current.NextSequence)`),
|
||||
`:783-784` (`current` is applied only to a throwaway snapshot), `:1292-1297` (subscribe replays from the shared index)
|
||||
- **Description:** The fix for old T-2 moves the session cursor to the new Agent instance so the next pump does not
|
||||
spend its first chunk on a clear + re-baseline. But that first chunk was what replaced pre-restart observations. With
|
||||
no pump running, the next pump opens on the new instance with a matching `instanceId` and no gap, so `_index` and the
|
||||
condition tracker keep the dead process's values for every DataItem that does not change afterwards.
|
||||
- **Failure scenario:** A driver with no active subscription (the window between unsubscribe-all and re-subscribe, or a
|
||||
latched stream-unsupported state) serves a `ReadAsync` after the Agent restarted, then a subscribe. The initial
|
||||
replay serves pre-restart values as Good; an item the new Agent reports `UNAVAILABLE` keeps its old value until it
|
||||
changes. With a pump running this cannot happen.
|
||||
- **Suggested fix:** In that branch also `Clear()` and `Apply(current, baseline: true)` on the shared index and tracker
|
||||
under the generation check, or do not advance the cursor.
|
||||
- **Test to add:** Init on instance 1 with X=5 and no subscription; switch the fake Agent to instance 2 with X
|
||||
`UNAVAILABLE`; `ReadAsync`, then `SubscribeAsync`; the initial callback for X must not be Good 5.
|
||||
|
||||
### M-8. One malformed MTConnect observation fails the whole document, and so the whole driver
|
||||
|
||||
- **Severity:** Low · **Category:** bug (robustness) · **Confidence:** Medium (needs a non-conforming Agent or adapter)
|
||||
- **Location:** `MTConnectStreamsParser.cs:417` (required `dataItemId`), `:631-643` (unparseable `timestamp` throws
|
||||
`InvalidDataException`); `MTConnectDriver.cs:2575-2588`, `:2681-2688`, `:3350`
|
||||
- **Description:** A single observation with a non-ISO timestamp, or an extension element with no `dataItemId`, throws
|
||||
out of the parse. Because `/current` repeats the same observation, every chunk and every re-baseline throws.
|
||||
- **Failure scenario:** One adapter emits `timestamp="2026-12-02 10:00"`-style garbage for one DataItem. The pump
|
||||
loops between reopen and re-baseline; after the watchdog's re-init, `InitializeAsync`'s `/current` throws and the
|
||||
driver is Faulted with every tag Bad — for one bad item.
|
||||
- **Suggested fix:** Skip the offending observation (warn once, optionally per-item `BadDecodingError`) and keep the
|
||||
header and the rest. Reserve whole-document failure for header/root problems.
|
||||
- **Test to add:** A streams document with one `timestamp="garbage"` observation among valid ones; `Parse` returns the
|
||||
others and the driver stays Healthy.
|
||||
|
||||
### M-9. Subscribe's initial replay can overwrite a newer pushed value (MTConnect and MQTT)
|
||||
|
||||
- **Severity:** Low · **Category:** bug (race) · **Confidence:** Medium
|
||||
- **Location:** `MTConnectDriver.cs:1292-1297` vs the pump's apply-and-fan-out at `:2756-2793`;
|
||||
`MqttSubscriptionManager.cs:964-972` and `SparkplugIngestor.cs:1635-1643` (`PushObservedSnapshots`) vs the dispatcher
|
||||
thread's `Values.Update` + `Raise`
|
||||
- **Description:** The subscribing thread reads the cached snapshot and raises it with no ordering against the ingest
|
||||
thread. Read V1 → ingest applies and raises V2 → subscriber raises V1. The node then holds V1.
|
||||
- **Failure scenario:** A re-subscribe on a deploy while traffic flows. For a report-by-exception Sparkplug metric or a
|
||||
slow MTConnect EVENT, the stale value stands until the item next changes; in plain MQTT the unchanged-value
|
||||
suppression (`MqttSubscriptionManager.cs:922-926`) then also swallows an identical republish. The window is
|
||||
microseconds per reference, so this is rare.
|
||||
- **Suggested fix:** After raising the replay, re-read the cache and re-raise if the snapshot reference changed; or
|
||||
serialise the replay through the ingest path.
|
||||
- **Test to add:** A blocking `OnDataChange` handler on the initial replay plus a concurrent delivery; assert the last
|
||||
snapshot delivered equals the cache.
|
||||
|
||||
### M-10. MTConnect: unsubscribing the last handle can cancel a pump a concurrent subscribe relied on (latent)
|
||||
|
||||
- **Severity:** Low · **Category:** bug (race) · **Confidence:** Medium — not reachable through today's actor for
|
||||
MTConnect, which awaits its unsubscribe before subscribing
|
||||
- **Location:** `MTConnectDriver.cs:1321-1339` (decides `stopStream` under the lock, releases it, then
|
||||
`StopSampleStreamAsync` re-takes it at `:3541-3549`); `:2107-2112` (`StartSampleStreamCore` returns early on a live
|
||||
pump); same shape in `MTConnectDriver.Alarms.cs:142-158`
|
||||
- **Description:** A `SubscribeAsync` landing between the remove and the stop sees a live pump, starts none, and the
|
||||
stop then cancels it. Health stays Healthy with `LastSuccessfulRead` frozen, so the watchdog (which needs
|
||||
non-Healthy) never recovers it. The overlap needs an off-mailbox unsubscribe, which the host only issues on the
|
||||
acknowledged-acquisition path MTConnect does not use.
|
||||
- **Suggested fix:** Detach `_pumpCts`/`_pumpTask` in the same critical section that removes the subscription and await
|
||||
the captured task outside the lock; or re-check `HasSubscribedReferencesCore()` under the lock inside the stop.
|
||||
- **Test to add:** A hook that blocks between the remove and the stop, a subscribe in the gap; assert a live pump
|
||||
exists and a later chunk is delivered.
|
||||
|
||||
### M-11. Sparkplug array metrics are boxed element by element, twice
|
||||
|
||||
- **Severity:** Low · **Category:** perf · **Confidence:** High
|
||||
- **Location:** `SparkplugIngestor.cs:1490-1499` (`Array.CreateInstance` + `GetValue` + `TryCoerce` + `SetValue`, per
|
||||
bound tag); `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/Sparkplug/SparkplugArrayCodec.cs:84-103` (delegate
|
||||
call per element)
|
||||
- **Description:** The packed body is decoded once into a typed array, then every bound tag copies it through
|
||||
`object`: one box out of `GetValue`, one out of the coercion, and an unbox in `SetValue`.
|
||||
- **Cost:** A 4,096-element `FloatArray` at 10 Hz is ~80k boxes and ~2 MB/s of gen-0 garbage per bound tag, on
|
||||
MQTTnet's dispatcher thread, when the decoded `float[]` is already the answer.
|
||||
- **Suggested fix:** When the decoded array's element type already equals `ElementClrType(target)`, publish the decoded
|
||||
array directly (it is not shared; clone only when more than one tag binds the metric). Keep the per-element path for
|
||||
genuine conversions.
|
||||
- **Test to add:** A benchmark or allocation assertion (`GC.GetAllocatedBytesForCurrentThread`) for a same-type
|
||||
`DoubleArray` delivery: allocation stays near the array size.
|
||||
|
||||
### M-12. Avoidable per-message allocations on the MQTT dispatcher thread
|
||||
|
||||
- **Severity:** Low · **Category:** perf · **Confidence:** High
|
||||
- **Location and cost:**
|
||||
- `SparkplugIngestor.cs:703` → `Contracts/Sparkplug/SparkplugTopic.cs:123` — `topic.Split('/')` plus a
|
||||
`SparkplugTopic` record for **every** message on the group-wide `#`, before the authored-node filter at `:745`.
|
||||
- `SparkplugIngestor.cs:707-711`, `:747-751`, `:821-825` — `_logger?.LogDebug(...)` with an enum and a struct argument
|
||||
allocates the `params` array and two boxes even when Debug is off. Together with the split that is ~10 allocations
|
||||
per discarded message; a group where this driver authors 2 of 200 edge nodes pays it for 99% of traffic.
|
||||
- `MqttSubscriptionManager.cs:1169`, `:1190-1196` — `TryEvaluateJsonPath` substrings each path segment for every tag
|
||||
on every message; a 50-field JSON topic at 10 Hz is 500+ short-lived strings a second.
|
||||
- `SparkplugIngestor.cs:2084-2094` — `WarnOnce` builds its interpolated key and calls `ConcurrentDictionary.Count`
|
||||
(takes every bucket lock) on each call; a persistently mismatched tag pays that per message.
|
||||
- **Suggested fix:** Guard the Debug lines with `IsEnabled(LogLevel.Debug)` (or `LoggerMessage`); parse the topic with
|
||||
span slicing and check the authored node before materialising a record; pre-compile `jsonPath` into a segment array
|
||||
on `MqttTagDefinition` at `Register`; in `WarnOnce` test `ContainsKey` first and track the count with an
|
||||
`Interlocked` counter.
|
||||
- **Test to add:** Allocation assertions for (a) an unauthored-node message with Debug disabled and (b) a JSON delivery
|
||||
to a tag with a three-segment path.
|
||||
|
||||
### M-13. Abandoned subscription handles accumulate in `_refsByHandle`
|
||||
|
||||
- **Severity:** Low · **Category:** bug (slow growth) · **Confidence:** High
|
||||
- **Location:** `MqttSubscriptionManager.cs:432`, `:360-366`; `SparkplugIngestor.cs:566`, `:464-470`
|
||||
- **Description:** Same host behaviour as M-5: the actor drops its handle without `UnsubscribeAsync` on a watchdog
|
||||
reconnect or Force Reconnect. `Register` prunes `_handleByRawPath` but never `_refsByHandle`, and both ingest objects
|
||||
survive a re-init. Unlike MTConnect nothing fans out through the orphans (`_handleByRawPath` is last-wins), so the
|
||||
cost is only one `string[]` of every reference per cycle (~40 KB at 5k tags).
|
||||
- **Suggested fix:** Clear `_refsByHandle`/`_handleByRawPath` in `AttachTo` (a new session means the actor will
|
||||
re-subscribe), or have `SubscribeAsync` retire handles whose references it takes over completely.
|
||||
- **Test to add:** Subscribe, re-attach to a new connection, subscribe again ×10; assert one entry remains.
|
||||
|
||||
### M-14. MQTT browse ignores CONNACK and SUBACK verdicts — a refused subscribe is a silently empty tree
|
||||
|
||||
- **Severity:** Low · **Category:** bug · **Confidence:** Medium (SUBACK refusal not exercised against a broker)
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser/MqttDriverBrowser.cs:102` (connect result discarded),
|
||||
`:106-111` (subscribe result discarded)
|
||||
- **Description:** `MqttConnection` documents that MQTTnet 5 returns a refused CONNECT as a result instead of throwing
|
||||
and checks it (`MqttConnection.cs:745-751`); the probe checks it too. The browser does neither. A refused CONNECT
|
||||
surfaces as a generic "client is not connected" from the following subscribe. A SUBACK refusal (broker ACL denies
|
||||
`#` or `spBv1.0/#` to this account) is dropped, and the session opens "successfully" with nothing in it.
|
||||
- **Failure scenario:** An operator opens the address picker against a broker whose ACL only allows `plant/#`. The tree
|
||||
is empty, with no error, and in Sparkplug mode only after the full birth window has elapsed.
|
||||
- **Suggested fix:** Throw on a non-success CONNACK using `MqttConnection.DescribeConnackRejection`; throw (or surface
|
||||
a warning node, as the truncation marker does) when the root filter is not granted.
|
||||
- **Test to add:** Browser test with a fake client returning `NotAuthorized` for the SUBACK; `OpenAsync` fails with a
|
||||
message naming the filter.
|
||||
|
||||
### M-15. Plain-mode Scalar/Raw boolean writes publish `True` / `False`
|
||||
|
||||
- **Severity:** Low · **Category:** bug (interop) · **Confidence:** Medium (depends on the consumer)
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttWriteEncoder.cs:189-191`
|
||||
- **Description:** `bool` is not `IFormattable`, so the fallback `value.ToString()` yields .NET's capitalised form. The
|
||||
same driver writes `true`/`false` for the Json format (`:177`) and when coercing a bool to a Sparkplug String
|
||||
(`SparkplugIngestor.cs:2282`). Most MQTT devices that take a text boolean compare case-sensitively against
|
||||
`true`/`false`, `1`/`0` or `ON`/`OFF`.
|
||||
- **Failure scenario:** A Boolean tag with `payloadFormat: Scalar` and a `writeTopic`. The write returns Good (the
|
||||
broker PUBACKed it); the device ignores `True`; nothing reports the mismatch.
|
||||
- **Suggested fix:** Special-case `bool` to `true`/`false`; document it in `docs/drivers/Mqtt.md`.
|
||||
- **Test to add:** `MqttWriteEncoderTests`: Scalar encode of `true` yields the bytes of `true`.
|
||||
|
||||
### M-16. Heidenhain: stopping a control loop is non-deterministic — a spurious comms-loss retire, or a cache left Good
|
||||
|
||||
- **Severity:** Low · **Category:** bug · **Confidence:** High (mechanism), Medium (impact)
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain/HeidenhainDeviceRuntime.cs:418-449` (`DisposeAsync`
|
||||
closes the session, then cancels, and bumps `_generation` only after the join), `:249-251` (`PollAsync` return →
|
||||
`Retire(..., "LSV2 communication lost")`); `HeidenhainSession.cs:178`, `:237`; `HeidenhainDriver.cs:135-140`, `:213`
|
||||
- **Description:** Two outcomes depending on where the loop is when it is stopped.
|
||||
- **Mid-batch:** the closed session short-circuits the rest of the batch to `BadNoCommunication` with no exception,
|
||||
`PollAsync` returns normally, and the full outage path runs: every tag invalidated, the alarm walk marked Bad, a
|
||||
Running→Stopped host event, and the Warning "LSV2 communication lost; reconnecting with backoff".
|
||||
- **Idle in `Task.Delay`:** it exits by cancellation and nothing is invalidated, despite the method's summary.
|
||||
`HeidenhainDriver._cache` keeps the last Good snapshots and `ShutdownAsync` never clears it.
|
||||
- **Failure scenario:** A deploy or Force Reconnect of a healthy control intermittently logs a false comms-loss warning
|
||||
and pushes a Bad burst (subscriptions are still registered during `StopDevicesAsync`). After `ShutdownAsync`, or a
|
||||
re-init that throws in option parsing before `_cache.Clear()`, `ReadAsync` returns the previous Good values with old
|
||||
timestamps while health is Faulted/Unknown.
|
||||
- **Suggested fix:** Set a stopping flag under `_publication` before `session.Close()` and have `Retire` skip the log,
|
||||
state change and alarm delivery when set; invalidate deterministically after the join (or clear / stale `_cache` in
|
||||
`StopDevicesAsync`).
|
||||
- **Test to add:** Fake LSV2 server holding a reply; dispose mid-exchange; assert no "communication lost" warning and
|
||||
no Backoff transition. Dispose while idle; assert `ReadAsync` after `ShutdownAsync` is not Good.
|
||||
|
||||
### M-17. Heidenhain: a down control's host status flaps Stopped↔Unknown and its "since" time resets on every retry
|
||||
|
||||
- **Severity:** Low · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `HeidenhainDriver.cs:398-403` (`ToHostState`: `Backoff` → `Stopped`, everything else including
|
||||
`Connecting` → `Unknown`), `:389-396`, `:406-407`; `HeidenhainDeviceRuntime.cs:199`, `:228`, `:400-411`
|
||||
- **Description:** Each reconnect attempt goes Backoff → Connecting → Backoff. Those map to different host states, so
|
||||
two `OnHostStatusChanged` events fire per attempt for as long as the control is down, and `_stateChangedUtc` is
|
||||
rewritten on each edge.
|
||||
- **Failure scenario:** A CNC powered off overnight (30 s max backoff, 5 s connect timeout): `/hosts` shows "Unknown"
|
||||
for ~5 s of every 35 s, the down-since time always reads "seconds ago" so the outage start is lost, and the host
|
||||
receives 3–4 status events a minute per control indefinitely.
|
||||
- **Suggested fix:** Map `Connecting` to the previous effective state (`Stopped` after a failure, `Unknown` only on
|
||||
first connect) and leave `_stateChangedUtc` alone on Backoff↔Connecting edges.
|
||||
- **Test to add:** Runtime against a refusing endpoint with a fake `TimeProvider`; after N attempts exactly one
|
||||
`OnHostStatusChanged` (→Stopped) and a stable `GetHostStatuses()[0].LastChangedUtc`.
|
||||
|
||||
### M-18. Heidenhain: optional-role login is retried on every poll batch with no throttle
|
||||
|
||||
- **Severity:** Low · **Category:** perf / behaviour · **Confidence:** High that the code does this; Medium that a real
|
||||
control returns the triggering codes for long
|
||||
- **Location:** `HeidenhainSession.cs:402-414` (`PrepareTelemetryAsync`), `:368-400` (`RequireLoginAsync`), `:487-498`
|
||||
(the wire cache is per batch only); `HeidenhainStatus.cs:77` (`IsStable`)
|
||||
- **Description:** If the DNC or DATA login is refused with a code that is not "stable" (operating mode, access
|
||||
timeout, any unmapped code), every later batch touching that feature re-sends `A_LG` with the cleartext password.
|
||||
De-duplication is within one batch only; there is no backoff or attempt cap.
|
||||
- **Cost:** At the default cadences (1 s / 2 s) about 1.5 logins a second, at the 100 ms floor more than 10 — roughly
|
||||
130k cleartext password transmissions a day per control, plus whatever the control logs per attempt.
|
||||
- **Suggested fix:** Keep a per-role next-attempt time on the session (exponential, e.g. 5 s → 5 min) and return the
|
||||
cached status until it elapses.
|
||||
- **Test to add:** Fake server refusing `A_LG DNC` with code 56; 20 Status batches inside the throttle window on a fake
|
||||
clock; at most one further DNC `A_LG` frame.
|
||||
|
||||
### M-19. Heidenhain: the watchdog's re-init resets the reconnect backoff; `Reconnect.MaxDelayMs` above ~90 s is unreachable
|
||||
|
||||
- **Severity:** Low · **Category:** bug (design interaction) · **Confidence:** Medium (may be accepted as watchdog design)
|
||||
- **Location:** `HeidenhainDeviceRuntime.cs:80`, `:195-200`, `:213-218` (`_consecutiveFailures` lives on the runtime);
|
||||
`HeidenhainDriver.cs:138`, `:211-225` (re-init disposes and rebuilds every runtime);
|
||||
`DriverInstanceActor.cs:1103-1127` (trips on non-Healthy + 90 s of silence);
|
||||
`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Contracts/HeidenhainOptionsParser.cs:118-120` (accepts up to 600 000 ms)
|
||||
- **Description:** With every control of an instance down (the normal case for a one-control driver), health is
|
||||
Degraded with `LastSuccessfulRead` frozen, so the watchdog re-initialises about every 90 s. Re-init discards the
|
||||
runtimes, so backoff restarts at `InitialDelayMs`. The runtime already reconnects on its own; the re-init adds nothing.
|
||||
- **Failure scenario:** A CNC off overnight, every ~90 s: the dial sequence restarts at 1, 2, 4, 8, 16, 30 s (an
|
||||
operator-set 5–10 min ceiling is silently ignored); every tag flips `BadNoCommunication` →
|
||||
`BadWaitingForInitialData` → `BadNoCommunication`; alarm conditions are annotated Good until the first connect
|
||||
fails, then Bad again; a watchdog warning is logged each cycle.
|
||||
- **Suggested fix:** Keep per-control failure counts on the driver keyed by `host:port` and seed new runtimes from
|
||||
them; seed the cache `BadNoCommunication` rather than `BadWaitingForInitialData` when that control was down.
|
||||
- **Test to add:** Driver against a refusing endpoint with a fake clock; two re-inits 90 s apart; the delay before the
|
||||
first dial after the second is not `InitialDelayMs`, and tag status does not regress to `BadWaitingForInitialData`.
|
||||
|
||||
---
|
||||
|
||||
## Areas reviewed with no findings
|
||||
|
||||
**MQTT / Sparkplug**
|
||||
- `MqttConnection`: lifecycle gate, connect-while-connected idempotence, CONNACK classification, dispose-during-connect
|
||||
hand-back, supervisor backoff, bounded SUBSCRIBE/PUBLISH/disconnect waits, re-subscribe-or-tear-down on reconnect,
|
||||
`ConnectionLost` raised once per outage on the Connected→Reconnecting edge. Handlers are synchronous, so QoS 1 acks
|
||||
follow processing. The wake semaphore over-counts failed attempts but only costs spurious loop iterations.
|
||||
- `MqttDriver`: lifecycle generation guard, teardown-before-rebuild, unpublished connection disposed on failure, health
|
||||
derived from live connection state, `LastSuccessfulRead` from inbound traffic and QoS ≥ 1 PUBACKs only, write batch
|
||||
ordering per topic with bounded concurrency. The host re-subscribes after every re-init, which is what re-establishes
|
||||
plain-mode SUBSCRIBEs after `AttachTo` clears `_subscribedTopics`.
|
||||
- `MqttSubscriptionManager`: exact-topic index plus wildcard trie (confirmed by MQTTnet's comparer), one JSON parse per
|
||||
message, payload cap before decode, pending-topic retry, refused-vs-failed SUBACK handling, connection-loss staling
|
||||
and the unchanged-value suppression that depends on it, retained-seed opt-out.
|
||||
- `SequenceTracker`: wrap at 255, resync on gap, bdSeq tie for NDEATH, stale-Will rejection.
|
||||
- `BirthCache` / `AliasTable`: atomic snapshot replace, name-first binding, NBIRTH invalidating device tables,
|
||||
eviction on death and on de-authoring, reset on every session change.
|
||||
- `SparkplugCodec` / `SparkplugFlattener` / `SparkplugArrayCodec`: total decode (never throws), depth and member caps,
|
||||
exact-length checks on packed arrays, signed reinterpretation.
|
||||
- `SparkplugValueCoercion` and the plain coercion matrix: exact-integral rule, non-finite handling, range overflow.
|
||||
- `MqttClientOptionsFactory`: CA pin replaces the trust anchor only, hostname errors stay fatal, unreadable pin refuses.
|
||||
- `MqttBrowseSession`: node cap, label and topic length limits, control-character scrubbing, rebirth fan-out cap.
|
||||
- `MqttDriverProbe`: bounded, checks the CONNACK, disposes its client.
|
||||
- Clean-session and client-id guidance for the ingest connection is documented (`docs/drivers/Mqtt.md:152-158`); not
|
||||
re-reported.
|
||||
|
||||
**MTConnect** (prior T-1…T-8 verified remediated)
|
||||
- `MTConnectAgentClient`: multipart framing (Content-length and boundary scan), 32 MiB cap, per-read heartbeat
|
||||
watchdog, non-2xx error-document lift, URI redaction, dispose ordering, deadline vs lifetime vs caller cancellation.
|
||||
- Pump state machine: backoff, the three-re-baseline stall hold, adaptive count, unsupported latch, superseded-pump
|
||||
registry, generation guards on every state write, bounded teardown joins, health writes.
|
||||
- Comms-loss fast path (#846/#852): definite-loss classification, confirm window, once-per-outage marking, recovery
|
||||
republish.
|
||||
- Condition path: tracker per-native-code semantics, baseline reset, `UNAVAILABLE` quality-only rule, told-record
|
||||
dedup/prune/resync.
|
||||
- Parsers: DTD prohibited, depth bound, DATA_SET/TABLE folding, `resetTriggered`. Coercion matrix. Probe loop, Test
|
||||
Connect, discovery, write batching. Contracts.
|
||||
|
||||
**Heidenhain**
|
||||
- `Lsv2Client` / `Lsv2Codec`: one deadline per transaction, partial reads handled, any malformed or oversized frame
|
||||
closes the socket so a desynchronised stream is never reused, no sync-over-async.
|
||||
- `Lsv2ReadOnlyPolicy`: applied in the only frame builder; no path sends an unchecked command.
|
||||
- `Lsv2Data` / `HeidenhainBindingCodec`: every decoder length-checks before indexing.
|
||||
- `HeidenhainSession`: single-threaded by construction; alarm-walk termination and the `MaxAlarms` bound.
|
||||
- `HeidenhainDeviceRuntime`: generation guard, loop cannot die silently, backoff resets only after a published batch,
|
||||
consistent lock order.
|
||||
- `HeidenhainDriver` health (refusals do not degrade, `LastSuccessfulRead` frozen while down) and
|
||||
`HeidenhainAlarmProjection` (told state survives re-init, a failed walk is quality-only).
|
||||
- Contracts: parsers never throw on bad input, credential scope enforced at resolve time, no secrets in messages.
|
||||
@@ -0,0 +1,334 @@
|
||||
# Review 09 — AB (AbCip / AbLegacy / Ab.Transport / LibplctagShared), TwinCAT, FOCAS drivers
|
||||
|
||||
- **Date:** 2026-12-02 · **Commit:** `master @ 708a4889c`
|
||||
- **Scope:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.{AbCip, AbCip.Contracts, AbLegacy, AbLegacy.Contracts, Ab.Transport, Ab.LibplctagShared, TwinCAT, TwinCAT.Contracts, FOCAS, FOCAS.Contracts}` (~30k lines).
|
||||
- **Method:** code reading of every file in scope plus callers, by five parallel sub-reviewers; the High findings and a sample of the Medium ones were then re-checked against the cited lines. **Nothing was built or run** — no finding is confirmed by a test or on hardware. Findings that depend on device behaviour (P-1's Beckhoff cache behaviour, P-9, P-13, P-17) say so in their Confidence line.
|
||||
- **Prior review** (`docs/reviews/2026-10-21/07-drivers-plc.md`): L4, L6, L8, P8, P9, P10, P11, H1, H10–H21, U8–U10, U12 read as remediated. Still present in part: **P7** (warm-path half → P-2), **L5** (→ P-24), **L7** (residual, bounded → noted under P-23). U6 (PLC-5 native limits) is still present by design and not re-reported.
|
||||
- **Open issues:** nothing below duplicates #755, #592, #969, #959, #932, #924, #915, #616 or #614.
|
||||
- Paths are relative to `src/Drivers/`, with the `ZB.MOM.WW.OtOpcUa.` prefix dropped. Timing figures are estimates from configured timeouts, not measurements.
|
||||
|
||||
## Summary
|
||||
|
||||
| ID | Sev | Cat | Driver | Title |
|
||||
|---|---|---|---|---|
|
||||
| P-1 | High | bug | TwinCAT | Online change / program download leaves stale symbol offsets and dead notifications |
|
||||
| P-2 | High | bug/perf | AbCip + Ab.Transport | A device dying mid-run stalls the whole multi-device read batch (warm handles bypass backoff; scheduler re-opens per queued batch) |
|
||||
| P-3 | High | bug/perf | TwinCAT | Reads are serial across devices with no per-device fail-fast; one silent PLC stalls the others |
|
||||
| P-4 | High | bug/perf | TwinCAT | Probe tick replays every native registration against an offline PLC before probing, one Warning each |
|
||||
| P-5 | High | bug | AbLegacy | One `Long` tag on a MicroLogix faults the whole driver instance at init |
|
||||
| P-6 | Medium | bug | FOCAS | Fixed-tree CNC refusals are counted as comms loss → watchdog reconnect loop |
|
||||
| P-7 | Medium | bug | FOCAS | A transient failure during fixed-tree bootstrap permanently latches capabilities "unsupported" |
|
||||
| P-8 | Medium | bug | FOCAS | `Dispose` runs an unbounded synchronous close handshake; recycle holds `ConnectGate` across it |
|
||||
| P-9 | Medium | bug | FOCAS | Axis/spindle wire slot index discarded; a blank name slot shifts every later axis |
|
||||
| P-10 | Medium | bug | FOCAS | Non-transient protocol errors leave the session open and desynchronised; replies not matched to requests |
|
||||
| P-11 | Medium | bug/perf | FOCAS | Dead CNC's probe connect holds `ConnectGate` ahead of the backoff fast-fail, delaying other devices |
|
||||
| P-12 | Medium | bug | TwinCAT | Device-layer ADS refusals default to `BadCommunicationError` (health flaps, endless retries) |
|
||||
| P-13 | Medium | bug | AbCip native | Whole BOOL-array read sends the bit count as the CIP element count (0xD3 elements are DWORDs) |
|
||||
| P-14 | Medium | bug/perf | AbLegacy | Bit arrays read 16× the needed words and fail when the file is shorter than `arrayLength` words |
|
||||
| P-15 | Medium | bug | AbLegacy | Writing a `Bit` tag authored without `/n` overwrites the whole 16-bit word |
|
||||
| P-16 | Medium | perf | AbCip | One Warning + stack trace per tag per poll for the whole outage |
|
||||
| P-17 | Medium | bug | AbCip | ALMD acknowledge writes the `Acked` output rather than `OperAck` |
|
||||
| P-18 | Medium | perf | AbLegacy | T/C/R sub-elements and I/O/S words are never coalesced |
|
||||
| P-19 | Medium | perf | TwinCAT | Per-tag health snapshot + symbol-path re-parse on every poll |
|
||||
| P-20 | Low–Med | bug | FOCAS | Truncated alarm list (≥32 active) falsely clears specific-selector conditions |
|
||||
| P-21 | Low–Med | perf | FOCAS | MACRO/PARAM tags cost one round trip each; `CoalesceRejected` latches on transient codes |
|
||||
| P-22 | Low–Med | bug | AbCip / TwinCAT | Pooled connection / ADS client keeps the probe's timeout, silently overriding the driver timeout |
|
||||
| P-23 | Low | bug | AbCip / AbLegacy | Smaller correctness items (RMW lock keying, LINT bits 32–63, interval clamps, cycle guard, browse drop, local refusals as "answered", block-read race, null writes) |
|
||||
| P-24 | Low | perf | AbCip / AbLegacy / Ab.Transport | Remaining hot-path allocations, unpacked structure reads, blocking lease release |
|
||||
| P-25 | Low | bug | TwinCAT / FOCAS | Bit-read parent check missing; cached failed sysinfo; short PARAM payload reads Good 0 |
|
||||
|
||||
---
|
||||
|
||||
## P-1. TwinCAT: an online change or program download leaves stale symbol offsets and dead notifications in place
|
||||
|
||||
- **Severity:** High · **Category:** bug · **Confidence:** Medium-High (driver code path verified; the claim that Beckhoff's `SymbolCache` is only emptied by `CleanupSymbolTable()`/dispose comes from decompiling `Beckhoff.TwinCAT.Ads` 7.0.172, and relocation on a real PLC was not exercised)
|
||||
- **Location:** `Driver.TwinCAT/AdsTwinCATClient.cs:52`, `:64-72`, `:376` (`ReadSymbolAsync`), `:239`/`:278`, `:414`, `:597`; `Driver.TwinCAT/TwinCATDriver.cs:1415-1423`, `:1987-1998`
|
||||
- **Description:**
|
||||
- Reads, sum-reads, raw writes and the bit RMW address the PLC by the IndexGroup/IndexOffset that `ReadSymbolAsync` returns from the Beckhoff client's symbol cache. The driver never clears that cache.
|
||||
- The client hooks `AdsNotificationEx` only. A grep of the project finds no subscription to the SDK's `AdsSymbolVersionChanged`; the driver's own `OnSymbolVersionChanged` fires only when an ADS call happens to return 1809 (`MapAndSignal`), which direct IG/IO access does not return.
|
||||
- When 1809 is seen, `HandleSymbolVersionChanged` re-arms only registrations already marked dead and raises the advisory `OnRediscoveryNeeded`. It does not recycle the client or re-register live handles.
|
||||
- The probe recycles the client only when `ReadState` fails (`:1415-1416`). A Stop→download→Run where port 851 keeps answering, and any online change, never trips it. `OnlineChangeCnt` is read only for diagnostics display (`:1535`).
|
||||
- **Failure scenario:**
|
||||
- Online change relocates a variable: the cached offset now points at other memory. Reads publish garbage at Good; a write lands on whatever now lives at the old offset.
|
||||
- Program download in native-notification mode: the PLC drops the notifications but each registration still reports a live handle. No reads run, so 1809 is never seen; tags stay frozen at Good until restart.
|
||||
- **Suggested fix:** Recycle the client and replay registrations on any of: the SDK `AdsSymbolVersionChanged` event, a `PlcState` transition non-Run→Run, or a change in `OnlineChangeCnt` (sampled unconditionally). At minimum call `CleanupSymbolTable()` and re-register every handle. Raise `OnRediscoveryNeeded` once per event (a sum-read with N 1809 sub-errors currently raises it N times).
|
||||
- **Test to add:** Fake client whose symbol offsets change after a simulated version event; assert the next read and write use the new offsets and every native registration is re-added. Second test: PlcState Run→Stop→Run with no probe failure triggers a replay.
|
||||
|
||||
## P-2. AbCip + Ab.Transport: a device that dies mid-run stalls the whole multi-device read batch
|
||||
|
||||
- **Severity:** High · **Category:** bug / perf · **Confidence:** High on mechanism, Medium on timing. Warm-path half of prior **P7 — still present.**
|
||||
- **Location:** `Driver.AbCip/AbCipDriver.cs:912-925` (one window, one `Task.WhenAll` across all devices), `:1069-1081` and `:1854` (cached runtime returned before any backoff check), `:1872` (backoff guards cold creates only), `:1210-1221` (a failed warm read evicts but records no backoff failure); `Driver.Ab.Transport/Cip/RequestScheduler.cs:251-279`, `:296-334` (`ExecuteAsync` fails only the current batch; `FaultAll` is reached only when the scheduler itself breaks); `Driver.Ab.Transport/Cip/CipConnection.cs:92-101`, `:118-184` (each `SendAsync` on a faulted session starts a fresh open; `MaxRequestBytes` falls to 502 once the open is gone).
|
||||
- **Description:** On the first poll after a device dies every tag still has a cached runtime, so each goes straight to `runtime.ReadAsync`. The scheduler sends one packed batch at a time; each batch against a dead peer pays its own timeout or throttled re-open, and a failed batch does not fail what is queued behind it. After the first failed open the pack budget shrinks from 4002 to 502 bytes (~20 DINT reads per batch). `ReadAsync` returns nothing until every item on every device has finished.
|
||||
- **Failure scenario:** One driver instance with device A (healthy) and device B (1000 tags), B unplugged. ~50 batches at 1–3 s each ≈ 50–150 s. For that whole time A publishes nothing, B's tags keep their last Good value, health stays `Healthy` (`ApplyBatchHealth` runs after the batch), and the probe read queues behind the same scheduler. Later polls are cheap (runtimes evicted, cold create is single-flight with backoff), so it recurs once per outage or flap. On libplctag the bound is roughly N/8 × Timeout.
|
||||
- **Suggested fix:**
|
||||
- Transport: when `_channel.SendAsync` fails with a connection-level error, fault everything queued at that moment with the same exception; or keep a negative cache of one `MinForwardOpenInterval` in `CipConnection.EnsureOpenAsync`.
|
||||
- Driver: a per-device fault latch set by the first transport failure in a batch; warm items check it after taking the window slot and fail fast, and the failure is recorded on `device.Backoff` under `ConnectGate`. Better: bucket and publish per device.
|
||||
- **Test to add:** Scheduler over a fake `ICipChannel` that throws `BadConnection` after a delay: enqueue 200 requests, assert all complete within ~2 attempt durations and the channel was called ≤ 2 times. Driver test with two devices, B with 200 warm runtimes that time out: `ReadAsync` returns within ~2×Timeout and A's snapshots are Good.
|
||||
|
||||
## P-3. TwinCAT: reads are serial across devices with no per-device fail-fast
|
||||
|
||||
- **Severity:** High · **Category:** bug / perf · **Confidence:** High on code, Medium on timing
|
||||
- **Location:** `Driver.TwinCAT/TwinCATDriver.cs:461-491` (serial loop; buckets awaited one device after another), `:500-523`, `:1714`, `:1753`/`:1786`, `:944-998` (subscribe)
|
||||
- **Description:** `AdsClient.Connect` only opens the local AMS router port, so for a target that stops answering `IsConnected` stays true and the connect backoff never opens. Every tag of that device pays the full client timeout one after another, in the same loop that serves every other device. `SubscribeAsync` has the same gap: `unreachable` is filled only on `DeviceUnavailableException`; the generic catch at `:985` does not add the device.
|
||||
- **Failure scenario:** One subscription spanning device A (200 tags, silently dead) and device B (healthy), sum-read off or refused: each poll ≈ 200 × 2 s = 400 s; B's values arrive only when the batch ends, stamped with the batch-start time. With sum-read on the cost is per chunk rather than per tag, but B still waits behind A. Native subscribe of the same set blocks for the same period before B registers.
|
||||
- **Suggested fix:** After the first comms-class result for a device within a call, short-circuit that device's remaining tags to `BadCommunicationError`; open the per-device `Backoff` on comms-class read failures; read devices concurrently (`Task.WhenAll` over per-device buckets); add the device to `unreachable` in the generic subscribe catch when the failure is comms-class.
|
||||
- **Test to add:** Two-device fake where A's reads delay then return `BadTimeout`: assert one wire attempt on A and that B's results are not delayed by N × timeout.
|
||||
|
||||
## P-4. TwinCAT: probe tick replays every native registration against an offline PLC before probing
|
||||
|
||||
- **Severity:** High · **Category:** bug / perf · **Confidence:** High on the path, Medium on per-failure latency
|
||||
- **Location:** `Driver.TwinCAT/TwinCATDriver.cs:1404-1406`, `:1765-1806`, `:1816-1879` (catch at `:1857-1872`), `:1415-1416`
|
||||
- **Description:** Because the connect is local it succeeds while the target is offline. Each probe tick therefore creates a client, "connects", runs `ReplayNativeRegistrationsAsync` for every stored intent — each `AddNotificationAsync` fails and logs `LogWarning(ex, …)` — and only then runs `ProbeAsync`, which fails and recycles the client. There is no "first comms failure means the rest are dead" short-circuit and no once-per-outage log gate.
|
||||
- **Failure scenario:** PLC off with 1000 native tags. If the router answers quickly: 1000 Warnings with stack traces every 5 s indefinitely. If each call waits out the 2 s timeout: one tick ≈ 33 minutes with `ConnectGate` held — host state stops updating and writes to that device park on the gate.
|
||||
- **Suggested fix:** In the probe path connect without replay, run `ProbeAsync`, and replay only on success. In the replay loop mark the remaining intents dead on the first comms-class failure. One Warning per device per outage.
|
||||
- **Test to add:** Fake client where connect succeeds but `ProbeAsync` and `AddNotificationAsync` fail with a comms error; over three ticks with 100 registrations assert ≤ 1 `AddNotificationAsync` attempt per tick and ≤ 1 Warning total.
|
||||
|
||||
## P-5. AbLegacy: one `Long` tag on a MicroLogix device faults the whole driver at init
|
||||
|
||||
- **Severity:** High · **Category:** bug · **Confidence:** High for the init-fatal path; Medium-High that the profile flag is wrong (MicroLogix 1100/1400 L-file support is product knowledge, not verified on hardware here)
|
||||
- **Location:** `Driver.AbLegacy/AbLegacyDriver.cs:253-265`; `Driver.AbLegacy.Contracts/AbLegacyPlcFamilyProfile.cs:53-59` (`MicroLogix … SupportsLongFile: false`)
|
||||
- **Description:** After building the tag table `InitializeAsync` throws `InvalidOperationException` for any `Long` tag on a family with `SupportsLongFile == false` (likewise `String` vs `SupportsStringFile`). That faults the whole instance, every device included, and contradicts the comment at `:226` ("a bad tag must not fail the whole init"). The flags are consulted nowhere else, so neither the tag editor nor the deploy gate warns first. The MicroLogix profile also contradicts the driver's own parser and coalescer, which handle `L` files and L-bit RMW.
|
||||
- **Failure scenario:** An operator adds `L9:0` typed `Long` to one MicroLogix 1400 in a multi-device driver. The deploy seals; the driver respawns; every init attempt throws; all devices in that driver stay dark in a reconnect loop until the tag is removed.
|
||||
- **Suggested fix:** Skip the tag via `_skippedTags.Skip` + Warning instead of throwing. Set `SupportsLongFile: true` for MicroLogix (or drop the flag and let the PLC answer STS 0x50). If the rule stays, move it into `AbLegacyTagDefinitionFactory.Inspect` so the deploy gate reports it.
|
||||
- **Test to add:** Init with two devices and one `Long` tag on the MicroLogix one: init succeeds, other tags read, the Long tag is in `GetSkippedTags()`.
|
||||
|
||||
## P-6. FOCAS: fixed-tree CNC refusals are counted as comms loss
|
||||
|
||||
- **Severity:** Medium · **Category:** bug (health contract) · **Confidence:** High
|
||||
- **Location:** `Driver.FOCAS/Wire/WireFocasClient.cs:506-509` (`ThrowIfRcNonZero` throws plain `InvalidOperationException`; callers `:145`, `:165`, `:224`, `:293`); `Driver.FOCAS/FocasAlarmProjection.cs:89` (`IsCncRefusal` matches only `FocasWireException { Rc: not null }`); `Driver.FOCAS/FocasDriver.cs:2098-2112` (`NoteFixedTreeFailed`)
|
||||
- **Description:** `NoteFixedTreeFailed` has a refusal branch that credits an answering CNC as alive. On the wire backend every fixed-tree call reports a non-OK rc as `InvalidOperationException`, so that branch is unreachable and a refusal of `cnc_rddynamic2` is treated as silence.
|
||||
- **Failure scenario:** FIXED-only driver on a control that answers `cnc_rddynamic2` with a non-zero rc (`EW_FUNC` on an older series, sustained `EW_BUSY`, or `EW_4` from P-9). After the 30 s stale budget `GetHealth()` is Degraded with `LastSuccessfulRead` frozen; at 90 s the #527 watchdog re-initialises, the bootstrap stamps again and the cycle repeats indefinitely, tearing down a two-socket session each time. With good PMC tags alongside it stays Degraded forever with a misleading "no answer since…".
|
||||
- **Suggested fix:** `ThrowIfRcNonZero` should throw `FocasWireException(message, rc)` as `ReadAlarmsAsync` already does. Consider one refused axis being a per-node Bad rather than aborting the tick.
|
||||
- **Test to add:** Fake wire returns `EW_FUNC` for `ReadDynamicAsync` on a FIXED-only driver; assert health stays Healthy with `LastSuccessfulRead` advancing past the stale budget.
|
||||
|
||||
## P-7. FOCAS: a transient failure during fixed-tree bootstrap permanently latches capabilities as unsupported
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `Driver.FOCAS/FocasDriver.cs:1465-1490` (bootstrap), `:1754-1768` (`SafeProbe`/`SafeTryProbe` swallow every exception); `Driver.FOCAS/Wire/FocasWireClient.cs:883-889` (a timeout closes the transport)
|
||||
- **Description:** The capability probes swallow all exceptions and record "unsupported". `FixedTreeCache` is built once per `DeviceState` and never re-probed. If one probe times out, the wire client closes the transport and every later probe in the same pass throws "not connected" and is swallowed too.
|
||||
- **Failure scenario:** `cnc_rdsvmeter` stalls once at startup. `ServoLoad`, `ProgramInfo`, `Timers`, `Status` and `SpindleLoad` are all recorded false; authored `FIXED:Program/*`, `Status/*`, `Timers/*`, `Spindle/*/Load` tags read `BadNodeIdUnknown` until the next respawn. The axis poll keeps health Healthy, so nothing recovers it, and browse hides those subtrees.
|
||||
- **Suggested fix:** Separate "refused with an rc" (capability false) from transport failure / timeout / not-connected; on the latter rethrow so the bootstrap retries, or re-probe on each reconnect.
|
||||
- **Test to add:** Fake client whose `GetServoLoadsAsync` throws a transient `FocasWireException` once and then reports `IsConnected=false`; assert no all-false cache is published and the bootstrap retries.
|
||||
|
||||
## P-8. FOCAS: `Dispose` runs an unbounded synchronous close handshake, and the recycle path holds `ConnectGate` across it
|
||||
|
||||
- **Severity:** Medium · **Category:** bug (lifecycle / hang) · **Confidence:** Medium (narrow window, large impact)
|
||||
- **Location:** `Driver.FOCAS/Wire/FocasWireClient.cs:156-182` (`_lifetimeGate.Wait()`, `SendPdu`, `FocasWireProtocol.ReadPdu` with no receive timeout and without `_requestGate`); callers `Driver.FOCAS/FocasDriver.cs:537`, `:2403-2407` (shutdown / re-init), `:1943-1959` (recycle, gate held); `SynchronizedFocasClient` `Dispose`/`DisposeWhenIdleAsync`
|
||||
- **Description:** With `_connected` true, dispose writes the close PDU and blocks a thread-pool thread in a synchronous read with no timeout. It also does not take `_requestGate`, so when `DisposeWhenIdleAsync` hits its deadline the close exchange interleaves with an in-flight request on the same stream.
|
||||
- **Failure scenario:** The CNC loses power, or its FOCAS task hangs while TCP still ACKs, between the last good poll and a shutdown, re-init or hourly recycle. The read blocks until TCP retransmission gives up (minutes; forever for an app-level hang). On the recycle path `ConnectGate` is held, so every poll, probe and alarm read for that device parks on the gate with no result and no health write — the driver stays Healthy with frozen data and the watchdog conjunction never trips. On shutdown `ShutdownAsync` does not return.
|
||||
- **Suggested fix:** Bound the close exchange (~1 s via socket timeouts or a linked CTS); skip the reply read or run it under the request gate; dispose outside `ConnectGate`.
|
||||
- **Test to add:** Mock server that answers data but never the close PDU; assert `Dispose()` and the recycle tick complete within the bound and a following `EnsureConnectedAsync` succeeds.
|
||||
|
||||
## P-9. FOCAS: axis and spindle slot index is discarded, so a blank name slot shifts every later axis
|
||||
|
||||
- **Severity:** Medium · **Category:** bug (wire decode / mapping) · **Confidence:** Medium (requires a control that returns a blank slot mid-list)
|
||||
- **Location:** `Driver.FOCAS/Wire/FocasWireClient.cs:1263-1273` (`ReadNameRecords` skips blanks but keeps the 1-based slot index); `Driver.FOCAS/Wire/WireFocasClient.cs:181-193` (`SplitAxis` drops `r.Index`, then `.Where(n => n.Name.Length > 0)`); `Driver.FOCAS/FocasDriver.cs:1542-1545` (`axisIndex = i + 1`); spindles `WireFocasClient.cs:330`, `FocasDriver.cs:1734`, `:1846-1860`
|
||||
- **Description:** The wire layer preserves each named axis's slot number; the adapter throws it away and the poll addresses `cnc_rddynamic2` by position in the filtered list. Spindle meters are keyed by raw wire slot but names by filtered position.
|
||||
- **Failure scenario:** A control reports names in slots 1, 2 and 4. The third named axis is polled as axis 3, so its nodes publish another axis's positions at Good, or get `EW_4` and feed P-6. Same shift for spindle `Load` / `MotorSpeedPct`.
|
||||
- **Suggested fix:** Carry the wire `Index` on `FocasAxisName` / `FocasSpindleName`; use it as the `ReadDynamicAsync` argument and the meter lookup key.
|
||||
- **Test to add:** Axis-name payload `X, Y, blank, Z`: assert Z is requested with axis 4. Spindle payload with a blank first slot: `Spindle/S2/Load` maps to wire slot 2.
|
||||
|
||||
## P-10. FOCAS: non-transient protocol errors leave the session open and desynchronised; replies are not matched to requests
|
||||
|
||||
- **Severity:** Medium · **Category:** bug (framing) · **Confidence:** Medium (needs a malformed or unexpected PDU)
|
||||
- **Location:** `Driver.FOCAS/Wire/FocasWireClient.cs:883` (`when (requestStarted && IsTransientException(ex))` excludes rc-less `FocasWireException`), `:953-959` (unexpected type), `:861-865` (`blocks[0]` returned with no `Command` check); `Driver.FOCAS/Wire/FocasWireProtocol.cs` `ReadPduAsync` (bad magic / unsupported version thrown before the body is consumed)
|
||||
- **Description:** The class remark promises the transport is torn down on any mid-request failure; that holds only for I/O errors and timeouts. Bad magic, an unsupported version (body left unread) or an unexpected PDU type propagate with `_connected` still true, and the driver keeps the same client.
|
||||
- **Failure scenario:** After an "unexpected PDU type" the real reply to request N is consumed as the reply to N+1. Matching is purely positional, so a PMC or macro tag could publish another request's payload at Good (a payload-length mismatch would usually fail first), or every read keeps failing until the 90 s watchdog.
|
||||
- **Suggested fix:** Close the transport on any exception once `requestStarted` is true, except a clean rc result. Verify response block count and command ids against the request.
|
||||
- **Test to add:** Mock server sends one stray non-data PDU then the real reply; assert the client closes and the next call reconnects rather than returning shifted data.
|
||||
|
||||
## P-11. FOCAS: one dead CNC's probe connect holds `ConnectGate` ahead of the backoff fast-fail
|
||||
|
||||
- **Severity:** Medium · **Category:** perf / bug (one dead device stalls others) · **Confidence:** High
|
||||
- **Location:** `Driver.FOCAS/FocasDriver.cs:2167` (gate wait) before `:2181` (backoff fast-fail); `:1413` (probe uses `bypassBackoff: true`); `:716` (`Task.WhenAll` over devices); `Driver.FOCAS/FocasAlarmProjection.cs:253` (serial device walk)
|
||||
- **Description:** The backoff fast-fail runs only after `ConnectGate.WaitAsync`. The probe bypasses backoff and holds the gate for the full connect timeout against a black-holed host; data-path callers for that device queue behind it, and `ReadAsync` awaits all devices before returning.
|
||||
- **Failure scenario:** Three CNCs, one powered off. Roughly 2 s in every 7 s the dead device's gate is held; any overlapping poll waits up to 2 s, delaying the healthy CNCs' publishes by the same amount. The alarm loop stalls the same way.
|
||||
- **Suggested fix:** For non-bypass callers check `Backoff.ShouldAttempt` before waiting on the gate, or use `ConnectGate.WaitAsync(0)` and throw `ConnectionThrottledException` when a connect is in flight.
|
||||
- **Test to add:** Fake factory whose `ConnectAsync` blocks for the timeout on device A while the probe holds it; a two-device `ReadAsync` returns B's values within milliseconds.
|
||||
|
||||
## P-12. TwinCAT: device-layer ADS refusals default to `BadCommunicationError`
|
||||
|
||||
- **Severity:** Medium · **Category:** bug (health contract) · **Confidence:** High for the mapper; Medium for the marshal-exception trigger
|
||||
- **Location:** `Driver.TwinCAT/TwinCATStatusMapper.cs:84` (`_ => BadCommunicationError`); `Driver.TwinCAT/AdsTwinCATClient.cs:164-167`, `:732-735`; `Driver.TwinCAT/TwinCATTypeGuard.cs:151-156`; `Driver.TwinCAT/TwinCATDriver.cs:518-522`, `:768-772`
|
||||
- **Description:** Unlisted device-layer answers in 0x700–0x73F (1800 Busy, 1803 InvalidParm, 1805 SyntaxError, 1814 NoMoreHandles, 1815 InvalidWatchSize, 1828 LicenseNotFound) map to `BadCommunicationError`; `IsCommsStatus` then calls `MarkCommsFault` and `RegistrationFailure` retries every probe tick with no refusal backoff. Separately, `ReadValueAsync` catches only `AdsErrorException`, so a Beckhoff marshal/type exception reaches `ReadOneAsync`'s generic catch and is also a comms fault; `CheckRead` lets a scalar-declared tag through against a non-array `NonScalar` symbol, the likely trigger.
|
||||
- **Failure scenario:** A tag with a malformed path (1805), or a PLC out of notification handles (1814), flips the driver Degraded on every poll/tick and the next Good read clears it — health flaps. If it is the only tag and the probe is disabled, `LastSuccessfulRead` freezes and the watchdog reconnects every 90 s. Over-limit notifications are re-attempted every 5 s forever.
|
||||
- **Suggested fix:** Default 0x700–0x73F to `BadDeviceFailure`; keep comms for router (<0x700), client (0x740+) and WSA codes. Catch non-ADS, non-connection exceptions in the client → `BadTypeMismatch`. Make `CheckRead` refuse `NonScalar` for a scalar declaration.
|
||||
- **Test to add:** Fake returning 1805 and 1814: health unchanged, refusal backoff applied. Scalar-declared tag over a struct shape returns `BadTypeMismatch` with no `MarkCommsFault`.
|
||||
|
||||
## P-13. AbCip native: a whole BOOL-array read sends the BOOL count as the CIP element count
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** Medium (wire semantics from the Logix data-access convention and this file's own comment at `:524-526`; needs an `ab_server` or hardware check)
|
||||
- **Location:** `Driver.AbCip/NativeAbCipTagRuntime.cs:98` (`_elements = ElementCount`), `:196` (read sent with that count), `:386-387`, `:688-693` (`BuildBoolArray(count)`); `Driver.AbCip/AbCipDriver.cs:1880-1882`; `Driver.AbCip/CipSymbolObjectDecoder.cs:188-204` (0xD3 unmapped → `Structure`)
|
||||
- **Description:** A tag authored `Bool`, `IsArray`, `ElementCount = 64` requests 64 elements. The comment on `TrySplitBoolArrayElement` in the same file states that a BOOL array's element segment addresses DWORDs, and the scalar-element path divides by 32 accordingly; the whole-array path does not.
|
||||
- **Failure scenario:** `BOOL[64]` is two DWORDs; the controller refuses a 64-element read (0xFF/0x2105 → `BadOutOfRange`), so the tag is permanently Bad — and kept as a refusal, so nothing escalates. Only a fake-backed test covers it. Because discovery maps 0xD3 to `Structure`, browse-commit never produces a correct Bool-array tag either.
|
||||
- **Suggested fix:** For `IsArray && AuthoredType == Bool` request `ceil(count / 32)` elements when the layout is packed (reuse the `BoolLayout` settle logic); map symbol type 0xD3 to a Bool array in `MapTypeCode` / `ArrayShape`.
|
||||
- **Test to add:** Native runtime test with a fake channel that answers 0xD3 and refuses a count above 2 for a 64-bit array: assert the request carries 2 and decodes 64 bools. Add an `ab_server`/hardware gate for a `BOOL[64]` whole read.
|
||||
|
||||
## P-14. AbLegacy: bit arrays read 16× more of the file than needed and fail when the file is shorter than `arrayLength` words
|
||||
|
||||
- **Severity:** Medium · **Category:** bug / perf · **Confidence:** High (native); Medium (libplctag — same `ElementCount`, not traced into libplctag)
|
||||
- **Location:** `Driver.AbLegacy/AbLegacyDriver.cs:1613-1614`, `:1699-1706` (`ElementCount: EffectiveArrayLength(def)`); `Driver.AbLegacy/NativeAbLegacyTagRuntime.cs:73`, `:85-86`, `:196-202` (buffer = 2 × count bytes), `:408-413` (decode uses the first count/8 bytes); `LibplctagLegacyTagRuntime.cs` `BuildTag` / `DecodeArray`
|
||||
- **Description:** For a `Bit` array `arrayLength` is a bit count but is passed as the word count of the wire read.
|
||||
- **Failure scenario:** `B3:0`, `Bit`, `arrayLength: 256` on a 16-word B3 file (exactly 256 bits). Native requests 512 bytes in three chunks; the PLC refuses anything past word 15, so a correctly authored tag is permanently Bad. When the file is long enough it works at 16× the bytes and 3× the round trips.
|
||||
- **Suggested fix:** For Bit arrays use `ElementCount = (bits + 15) / 16` (÷32 on an L file) and keep decoding `count` bits.
|
||||
- **Test to add:** Native runtime over a fake scheduler: a 32-bit `B3:0` array issues one typed read of 4 bytes and decodes the right bits.
|
||||
|
||||
## P-15. AbLegacy: writing a `Bit` tag authored without `/n` overwrites the whole 16-bit word
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `Driver.AbLegacy/AbLegacyDriver.cs:994` (RMW only when `parsed.BitIndex is int`), `:1019`; `Driver.AbLegacy/NativeAbLegacyTagRuntime.cs:425-430`; `LibplctagLegacyTagRuntime.cs` `EncodeValue` Bit arm
|
||||
- **Description:** A `Bit`-typed tag on `B3:0` or `N7:0` with no bit suffix reads as bit 0 of the word. A write falls through to `EncodeValue(Bit, null, v)`, which writes the full word as 0x0001 or 0x0000. `AbLegacyAddress.Validate` and `Inspect` accept the combination. (T/C/R status-bit writes such as `T4:0.DN` are refused by the transport and are not affected.)
|
||||
- **Failure scenario:** `B3:5` typed Bit, word currently 0x00F1. Client writes `false`; the word becomes 0x0000 and seven unrelated bits are cleared.
|
||||
- **Suggested fix:** Treat `Bit` with a null bit index on a word file as bit 0 and route through `WriteBitInWordAsync`, or refuse `BadNotSupported` and add an `Inspect` warning.
|
||||
- **Test to add:** Write `false` to `B3:0` (Bit, no suffix) with the fake word at 0xFFFF; assert 0xFFFE or a refusal.
|
||||
|
||||
## P-16. AbCip: one Warning with a stack trace per tag per poll for the whole outage
|
||||
|
||||
- **Severity:** Medium · **Category:** perf (log flood) · **Confidence:** High
|
||||
- **Location:** `Driver.AbCip/AbCipDriver.cs:1210-1221`, `:1347-1354` (generic catch logs `LogWarning(ex, …)`), `:1872-1874` (`ConnectionThrottledException` per cold tag inside the backoff window), `:1113-1116`, `:1281-1284`
|
||||
- **Description:** After eviction every tag on the dead device throws `ConnectionThrottledException` on every poll and each is logged at Warning with the exception. `ReadAsync` returns Bad snapshots rather than throwing, so the poll engine never slows down.
|
||||
- **Estimated cost:** A dead CompactLogix with 1000 tags on a 1 s poll ≈ 1000 Warning events/s with stack traces plus 1000 first-chance exceptions/s. If a sibling device is alive `LastSuccessfulRead` keeps advancing, the watchdog never re-inits, and this continues indefinitely.
|
||||
- **Suggested fix:** Return the throttled verdict without throwing; log one Warning per device per outage on the transition, with a suppressed count.
|
||||
- **Test to add:** Device in an open backoff window with 100 cold tags, 10 `ReadAsync` calls: the capturing logger holds ≤ 2 Warnings for that device.
|
||||
|
||||
## P-17. AbCip: ALMD acknowledge writes the instruction's `Acked` output, not its `OperAck` input
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** Medium (from Rockwell's `ALARM_DIGITAL` reference; not hardware-verified. The class comment at `AbCipAlarmProjection.cs:26-29` records this as a deliberate "first pass" choice, so it is a known simplification rather than an oversight)
|
||||
- **Location:** `Driver.AbCip/AbCipAlarmProjection.cs:149-158` (non-ALMA refs get `"{ref}.Acked" = true`); contrast the ALMA branch and `docs/drivers/AbCip.md:328-329`, which say "`*Acked` bits are instruction outputs and are never written"
|
||||
- **Description:** On `ALARM_DIGITAL`, `Acked` is a status output the instruction recomputes each scan; the operator-acknowledge inputs are `OperAck`/`ProgAck`. The projection applies exactly this reasoning to ALMA (`OperAckAll`) but not to ALMD.
|
||||
- **Failure scenario:** A client acknowledges an ALMD condition. The write to `Tag.Acked` returns Good and the server condition shows acknowledged, but the PLC rewrites `Acked=0` on the next scan; the alarm stays unacknowledged in the controller and on FactoryTalk with no error anywhere.
|
||||
- **Suggested fix:** Write `{ref}.OperAck` for ALMD (require or advise that member in the tag config); keep `Acked` read-only and optionally read it in the tick so device-side acks are projected, as ALMA does.
|
||||
- **Test to add:** Projection unit test asserting the ALMD ack request targets `.OperAck`; a hardware gate that acks an `AckRequired` ALMD and reads `Acked`/`InAlarmUnack` back after a scan.
|
||||
|
||||
## P-18. AbLegacy: Timer/Counter/Control sub-elements and I/O/S words are never coalesced
|
||||
|
||||
- **Severity:** Medium · **Category:** perf · **Confidence:** High
|
||||
- **Location:** `Driver.AbLegacy/AbLegacyDriver.Coalescing.cs:55-66` (`SubElement is not null || FileNumber is null` ⇒ not coalescable; only N/B/F/L qualify); serial per-device loop at `Driver.AbLegacy/AbLegacyDriver.cs:618-666`
|
||||
- **Description:** `T4:n.ACC`, `.PRE` and `.DN` are each their own PCCC exchange although one 6-byte element read returns all three and consecutive T/C/R elements are contiguous. `S:`, `I:`, `O:` words are excluded only because their file number is implicit.
|
||||
- **Estimated cost:** 50 timers × (ACC, PRE, DN) = 150 serial exchanges per poll; at an assumed 10–20 ms each that is 1.5–3 s, overrunning a 1 s poll group. Coalesced it is about two requests.
|
||||
- **Suggested fix:** Extend `PlanReadUnits` to group T/C/R by (letter, file), read whole 6-byte elements and slice words 0/1/2 and the status bits via `PcccAddress.WithSubElementName`; use `PcccFileType.ImplicitFileNumber` for S/I/O.
|
||||
- **Test to add:** Planner test: 10 timers × 3 sub-elements produce one block; decoded members equal the single-read values.
|
||||
|
||||
## P-19. TwinCAT: per-tag health snapshot and symbol-path re-parse on every poll
|
||||
|
||||
- **Severity:** Medium · **Category:** perf · **Confidence:** High (cost estimated from code, not measured)
|
||||
- **Location:** `Driver.TwinCAT/TwinCATDriver.cs:532` → `:1083-1104` (`RecordDeviceAnswered(force: true)` per Good tag: enumerates `_devices.Values` — a `ConcurrentDictionary` lock-all snapshot — and allocates a `DriverHealth`); `:477-478`, `:506-507` (`TwinCATSymbolPath.TryParse` + `ToAdsSymbolName()` per tag per read); `:603` (`GetRange` + item array per chunk)
|
||||
- **Estimated cost:** ~10–15 allocations plus one lock-all snapshot per tag per poll; at 5000 tags / 1 s roughly 60k allocations/s and 5000 lock-all operations/s.
|
||||
- **Suggested fix:** Pre-compute `AdsSymbolName` and `BitIndex` on the definition in `InitializeAsync`; call `RecordDeviceAnswered` once per device per batch.
|
||||
- **Test to add:** Counter asserting one health write per device per `ReadAsync`; a parse-count seam asserting `TryParse` is not called on the read path.
|
||||
|
||||
## P-20. FOCAS: a truncated alarm list (≥32 active) falsely clears specific-selector conditions
|
||||
|
||||
- **Severity:** Low–Medium · **Category:** bug (alarm diffing) · **Confidence:** High on code, rare in the field
|
||||
- **Location:** `Driver.FOCAS/FocasAlarmProjection.cs:322-331` (`Transition` runs unconditionally; only the `established` signal is gated on truncation); `Driver.FOCAS/FocasAlarmConditionMapper.cs:166-172`; `Driver.FOCAS/Wire/WireFocasClient.cs:499` (`MaxAlarmsPerRead = 32`)
|
||||
- **Description:** At the cap the code recognises that a condition with no match "may only be missing it" and withholds the established signal — but still feeds the inactive view into `Transition`, which emits a Clear for a condition previously told active.
|
||||
- **Failure scenario:** An alarm storm reaches 32 entries and an active `ALARM:Servo/401` falls past the cap. Its condition clears; when the list shrinks it is raised again un-acknowledged, writing a Clear and an Activated `/alerts` row.
|
||||
- **Suggested fix:** When `truncated`, the view has no match and the condition was told active, skip the transition and keep the told state. Optionally page `cnc_rdalmmsg2` or raise the cap.
|
||||
- **Test to add:** Told-active `ALARM:Servo/401`; tick with 32 alarms not containing 401 → no Clear. Then a 5-alarm tick containing 401 → no Raise/Retrigger.
|
||||
|
||||
## P-21. FOCAS: MACRO/PARAM tags cost one round trip each; `CoalesceRejected` latches on transient codes
|
||||
|
||||
- **Severity:** Low–Medium · **Category:** perf · **Confidence:** High on the serial reads and the latch; Medium that multi-block batching works for `cnc_rdmacro` (unproven on hardware)
|
||||
- **Location:** `Driver.FOCAS/FocasDriver.cs:762-847` (per-tag loop, one PDU per tag); `Driver.FOCAS/Wire/FocasWireClient.cs:607-618`; `Driver.FOCAS/FocasDriver.cs:1005-1006` (`CoalesceRejected` latch)
|
||||
- **Description:** Only PMC reads coalesce. The protocol already carries several request blocks per PDU (`ReadStatusAsync` sends 3, `ReadDynamic2Async` 9), but macro and parameter tags go one PDU per tag, serially, on the gate shared with the 250 ms fixed-tree loop and the alarm loop. Separately, any refusal other than `BadDeviceFailure` latches `CoalesceRejected` for the life of the `DeviceState`, including rc values mapped to `BadCommunicationError` (`EW_SOCKET`, `EW_UNEXP`, unknown codes).
|
||||
- **Estimated cost:** 100 macro tags on a 1 s poll = 100 round trips; at an assumed 5–15 ms each that is 0.5–1.5 s per cycle.
|
||||
- **Suggested fix:** Batch N macro/parameter blocks per PDU (chunks of ~10–20), demultiplex by block order. Latch `CoalesceRejected` only on range-shaped codes (`EW_NUMBER`, `EW_LENGTH`, `EW_DATA`, `EW_ATTRIB`).
|
||||
- **Test to add:** Mock server counts PDUs for a 50-macro batch (≤ ~5). A `ReadPmcSlotsAsync` returning the `EW_SOCKET`-mapped status once must not latch.
|
||||
|
||||
## P-22. AbCip / TwinCAT: the probe's timeout silently replaces the driver's
|
||||
|
||||
- **Severity:** Low–Medium · **Category:** bug (config trap) · **Confidence:** High
|
||||
- **Location:**
|
||||
- AbCip: `Driver.Ab.Transport/DeviceSessionPool.cs:80-97` (a later acquirer's differing options are ignored with a one-time Warning); `Driver.AbCip/NativeAbCipDevice.cs:27-33` (`Timeout` is part of `ConnectionOptions`); `Driver.AbCip/AbCipDriver.cs:724` (probe runtime uses `_options.Probe.Timeout`) vs `:1880` (data runtimes use `_options.Timeout`).
|
||||
- TwinCAT: `Driver.TwinCAT/AdsTwinCATClient.cs:77-78` (`_client.Timeout` set once by whichever caller creates the client); `Driver.TwinCAT/TwinCATDriver.cs:1404`, `:1770`.
|
||||
- **Failure scenario:** An operator raises the driver `TimeoutMs` to 8–10 s for a slow WAN/VPN link and leaves the probe at 2 s. The probe loop creates the connection first (and re-creates it after every recycle), so every data read still times out at 2 s; on AbCip each timeout faults and reopens the session.
|
||||
- **Suggested fix:** AbCip: take `Timeout` out of the pooled connection's identity and pass it per request, or resolve one effective timeout (the max) before any lease. TwinCAT: always set the client timeout from `_options.Timeout` and bound the probe's `ReadStateAsync` with a linked CTS.
|
||||
- **Test to add:** Acquire with 2 s then 8 s and assert a request through the second lease is bounded by 8 s; TwinCAT fake factory capturing the connect timeout with the probe enabled.
|
||||
|
||||
## P-23. AbCip / AbLegacy: smaller correctness items
|
||||
|
||||
All Low severity, category bug.
|
||||
|
||||
| # | Location | Problem | Fix |
|
||||
|---|---|---|---|
|
||||
| a | `Driver.AbCip/AbCipDriver.cs:2481` vs `:2478-2479` | `_rmwLocks` is case-sensitive but `ParentRuntimes` is `OrdinalIgnoreCase`: `Flags.3` and `FLAGS.4` take different RMW locks on one shared parent runtime → lost update. A whole-word write to the parent also uses a different lock. Confidence High on keying. | Key `_rmwLocks` `OrdinalIgnoreCase`; take the parent lock in whole-word writes; consider CIP 0x4E Read-Modify-Write on native. |
|
||||
| b | `Driver.AbCip/AbCipTagPath.cs:62-64` / `:89-95` vs `AbCipDriver.cs:1715-1730` | Bit selector accepted only 0–31; `MyLint.40` fails `IsValidIdent`, `TryParse` returns null and the tag is `BadConfigurationError`. The RMW's 64-bit branch is unreachable for the upper half. Confidence High. | Accept 0–63; let the width check refuse per host type. |
|
||||
| c | `Driver.AbCip/AbCipDriverFactoryExtensions.cs:61`, `:74` | `Probe.IntervalMs` / `AlarmPollIntervalMs` unclamped: 0 hot-loops against the PLC; a negative value makes `Task.Delay` throw out of the loop, which dies silently. Confidence High (AdminUI clamping not checked). | Clamp in `ParseOptions` (≥ 100 ms). |
|
||||
| d | `Driver.AbCip/AbCipDriver.cs:2095`, `:2283` | Discovery cycle guard keys on member **name**: a UDT member whose nested type has a member of the same name is skipped as "cyclic" and never appears in browse. Confidence High. | Key on `NestedTemplateId`, or rely on `MaxUdtDepth`. |
|
||||
| e | `Driver.AbCip/SymbolListingEnumerator.cs:53-63` | `catch (Exception) { continue; }` drops a whole program from browse on a timeout with no log. Confidence High. | Skip only device refusals; rethrow or log transport failures. |
|
||||
| f | `Driver.AbLegacy/AbLegacyDriver.cs:1639-1641` | `IsAnsweredRefusal` accepts any `AbTransportException` with a refusal status, including locally raised `OutOfBounds`/`TooLarge` (`PcccServices.cs:40-51`). A tag at `N7:70000` among real tags on a dead device keeps resetting the fault streak and advancing `LastSuccessfulRead`. Confidence Medium. | Require `AbDeviceReplyException`; cap the element number in `AbLegacyAddress`. |
|
||||
| g | `Driver.AbLegacy/AbLegacyDriver.Coalescing.cs:163-172` vs `:138`, `:187`/`:216` | `ReadBlockAsync` uses a runtime fetched before its gate with no re-check; a concurrent refusal evicts and disposes it, and the waiter then fails every member `BadCommunicationError` as a comms fault. The single-tag path has `CurrentRuntimeUnderLockAsync` for this. Confidence Medium. | Re-resolve under the gate; evict under the gate. |
|
||||
| h | `Driver.AbLegacy/NativeAbLegacyTagRuntime.cs:429-447`; `AbLegacyDriver.cs:1360` | A null scalar write value is encoded as 0/false/empty via `Convert.To*`; the array path already refuses null. Confidence Medium (whether the node manager can deliver null not traced). | `Value is null → BadTypeMismatch` before any runtime is created. |
|
||||
|
||||
Residual of prior **L7** (still present, bounded): `_rmwLocks`, `RefusalLogged` and `IndirectLastParent` in AbLegacy still grow per distinct resolved indirect index value.
|
||||
|
||||
- **Tests to add:** concurrent `Flags.3`/`FLAGS.4` writes both land; `TryParse("L.40")` → bit 40; `ParseOptions` with 0 / −1; nested member sharing its parent's name is emitted; listing delegate throwing `Timeout` fails or logs; dead device + `N7:70000` enters backoff; `BeforeOperationGate` eviction between fetch and lock yields no Fault verdict; null scalar write returns `BadTypeMismatch` and sends no frame.
|
||||
|
||||
## P-24. AbCip / AbLegacy / Ab.Transport: remaining hot-path cost
|
||||
|
||||
All Low severity, category perf, Confidence High. Wire latency dominates; these are GC and round-trip overhead rather than throughput limiters.
|
||||
|
||||
- **Unpacked structure reads.** `Driver.AbCip/NativeAbCipTagRuntime.cs:247-255` returns 0 for `Structure`/null authored type → `LogixTagClient.cs:122-130` `UnknownReply` → `RequestScheduler.cs:174` forces the request exclusive. Every whole-UDT read, bit-RMW parent read (`AbCipDriver.cs:1799`) and probe read is its own round trip: N UDT parents = N round trips per poll instead of ~N/20. `NativeAbCipTemplateReader.cs:88` also under-declares the `GetAttributes` reply. *Fix:* pass the known structure size (template cache or previous read length + 8).
|
||||
- **Blocking lease release.** `Driver.AbCip/NativeAbCipTagEnumerator.cs:167-174` (`release().AsTask().Wait(DisposeWait)`), called from the async iterator's `finally` (`:65`) and `NativeAbCipTemplateReader.cs:121`, `:135`: one thread-pool thread blocked up to 2 s per browse / template read. *Fix:* `ConnectionLease.ReleaseInBackground()` as the tag runtime does.
|
||||
- **Ab.Transport allocations (prior L5 — partly remediated, remainder still present).** `Logix/LogixTagClient.cs:53` rebuilds the constant read request every poll; `Cip/CipReply.cs:42` `new ushort[0]` per successful reply; `Cip/RequestScheduler.cs:193` boxed tuple per cancellable request; `:210-211`, `:262` three `List`s per pump pass plus a quadratic `BuildSize`/`ReplyEnvelopeSize` recompute under the lock.
|
||||
- **AbLegacy per-poll re-parsing.** `AbLegacyDriver.cs:526`, `:726` (`AbLegacyAddress.TryParse` twice per tag per poll), `:698` (third parse for arrays), `:517-540`; `AbLegacyDriver.Coalescing.cs:73-118` (grouping + `OrderBy` rebuilt every poll; `block.Key` string formatted ~4× per block); `NativeAbLegacyTagRuntime.cs:268`, `:253-258`. 1000 tags at 1 s ≈ 2000 parses + ~15–20k short-lived objects per second. *Fix:* cache the parsed address on the definition at init; memoise the read plan.
|
||||
- **Test to add:** ten structure reads with a known size produce one MSP; a slow release delegate does not delay `EnumerateAsync`; allocation ceilings for a 100-tag packed native poll and a 500-tag AbLegacy `ReadAsync`.
|
||||
|
||||
## P-25. TwinCAT / FOCAS: smaller correctness items
|
||||
|
||||
All Low severity, category bug.
|
||||
|
||||
- **TwinCAT bit-indexed BOOL poll read skips the parent check** (Confidence Medium — Beckhoff marshaller conversion not traced to the end). `Driver.TwinCAT/AdsTwinCATClient.cs:101-109` reads the parent as `typeof(uint)` and never calls `TwinCATBitAccess.CheckParent`, unlike the notify (`:572`) and write (`:658`) paths. `MAIN.wFlags.20` on a 16-bit WORD reads Good `false` on the poll path but `BadOutOfRange` on the other two; a float/struct parent may throw in the marshaller and then count as a comms fault via P-12. *Fix:* `DescribeSymbolAsync` → `CheckParent` → `ReadRawAsync(parent.ByteSize)` → `ReadBit`. *Test:* parity of poll / notification / write status for the same (parent shape, bit).
|
||||
- **FOCAS caches a failed `cnc_sysinfo`** (Confidence Medium). `Driver.FOCAS/Wire/FocasWireClient.cs:133`, `:230` cache the connect-time result even when its rc is non-zero; `GetSysInfoAsync` then throws from the cache for the life of the session, so the fixed-tree bootstrap can never succeed while other tags keep the session alive. *Fix:* cache only when `IsOk`.
|
||||
- **FOCAS short parameter payload reads Good 0** (Confidence Medium — `docs/drivers/FOCAS.md` notes no successful `cnc_rdparam` capture exists, so the layout itself is unvalidated). `Driver.FOCAS/Wire/FocasWireClient.cs:533-584` return `default` with `Rc == 0` when the payload is shorter than the requested width; the macro path refuses short payloads. *Fix:* return a Bad status on a short payload.
|
||||
|
||||
---
|
||||
|
||||
## Areas reviewed with no findings
|
||||
|
||||
**Ab.Transport / Ab.LibplctagShared**
|
||||
- EIP framing: `EncapsulationCodec`, `EncapsulationClient` (single-flight gate, abandoned-exchange drain, sequence wrap, reply matching, fault and dispose).
|
||||
- `CipPath` route / symbolic / element / class-instance encoding and padding.
|
||||
- Connection manager: Forward Open, Large Forward Open, Forward Close layout, large→regular fallback, reply parse, Unconnected Send padding.
|
||||
- `CipConnection`: shared open, dispose racing an open, keep-alive, retire on 0x0107/0x0203.
|
||||
- `MultipleServicePacket` build/parse offsets and bounds; `RequestScheduler` cancellation and registration handling.
|
||||
- `LogixTagClient`: fragmented read offsets, type/handle consistency, fragmented write chunk alignment.
|
||||
- `SymbolObjectServices`, `TemplateObjectServices`, `DeviceSessionPool` refcount and close chain, `ForwardOpenThrottle`.
|
||||
- PCCC: `Field` 0xFF escape, 3-address-field typed read/write, PLC-5 range read, TNS / command echo checks, STS / EXT STS parsing.
|
||||
- `AbStatusCodes`, `AbOpcUaStatusMap`, `LibplctagOrphanRelease`.
|
||||
|
||||
**AbCip**
|
||||
- Init / re-init / shutdown lifecycle: generation guard, build-and-swap tables, dispose-before-overwrite, probe join, runtime-create orphan handling.
|
||||
- Health contract: worst-wins batch health, refusal vs comms classification on read and write, `LastSuccessfulRead` semantics.
|
||||
- Probe loop classification and backoff recording under `ConnectGate`; Test Connect probe.
|
||||
- Scalar and array write width gates, `AbCipArrayCodec`, STRING encode/decode, BOOL-element layout settle logic, sign and narrowing.
|
||||
- `CipSymbolObjectDecoder` entry walk, `CipTemplateObjectDecoder`, `NativeAbCipTemplateReader` paging, `AbCipUdtMemberLayout`, UDT planner (opt-in; reachability of the grouped path not confirmed).
|
||||
- ALMA projection state machine; `LibplctagTagRuntime` decode/encode; `AbCipTagDefinitionFactory`, `AbCipRefusals`, `AbCipStatusMapper`.
|
||||
- Not reviewed in depth: `LibplctagTemplateReader`, `LibplctagTagEnumerator`, `LibplctagStatusTranslation`, `AbCipTransportResolver`, `AbCipHostAddress`, `AbCipDriverOptions`.
|
||||
|
||||
**AbLegacy**
|
||||
- Native decode/encode: ST string layout, Int/Long/Float little-endian and sign handling, chunking under 236 bytes, all-or-nothing staged reads.
|
||||
- Bit RMW width masking and per-parent gate (non-atomicity vs ladder logic is documented).
|
||||
- Address parser: octal PLC-5 I/O, indirect nesting, sub-element/bit exclusivity.
|
||||
- Coalescing arithmetic: gap ≤ 8, ≤ 200 bytes, offset slicing, refuse-twice memory, fallback ordering.
|
||||
- Lifecycle: epoch-guarded publish, release before re-init, probe loops joined on shutdown, lease release on every path.
|
||||
- Health contract: Degraded on fault, `LastSuccessfulRead` only on an answer, throttled reads keep Degraded.
|
||||
- Array write encoder, status and name translation. Nit: the Test Connect probe passes `parsed.CipPath` where the driver uses `EffectiveCipPath`.
|
||||
|
||||
**TwinCAT**
|
||||
- Sum-read planning, partitioning, per-item decode and refusal latching.
|
||||
- `TwinCATArrayCodec`, `TwinCATStringCodec`, `TwinCATTemporalCodec`, `TwinCATBitAccess.ApplyBitWrite` and the per-parent RMW gate.
|
||||
- `TwinCATTypeGuard.CheckArray` / `CheckNotification`.
|
||||
- Lifecycle: build-and-swap tables, generation guard, bounded shutdown, dispose-before-overwrite on re-init.
|
||||
- Notification handle lifetime (orphan retraction, delete on dispose, dispatch-queue purge); variable-handle release in raw read/write.
|
||||
- `TwinCATDriverProbe`, `TwinCATTagDefinitionFactory`, `TwinCATSymbolPath`, `TwinCATSymbolExpander`, `TwinCATAmsAddress`, options parsing.
|
||||
|
||||
**FOCAS**
|
||||
- PDU framing: big-endian header and block fields, body-length bounds, `ParseResponseBlocks` bounds checks, partial-read loop.
|
||||
- Timeout / cancel path (a timed-out request closes the transport).
|
||||
- `SynchronizedFocasClient` gating and pending count; recycle loop under `ConnectGate`.
|
||||
- PMC coalescer grouping, alignment, slot indexing, bit / sbyte / float mapping.
|
||||
- Macro decode, position / servo / spindle scaling, timer decode; macro/parameter numbers no longer narrowed to `short`.
|
||||
- `ParseAlarms` layout disambiguation; alarm projection told-record handling and refusal classification on the alarm path.
|
||||
- Lifecycle: generation guard, swapped tables, `_releaseTail` chaining, release-before-overwrite, bounded loop joins.
|
||||
- Value-path health; Contracts (`FocasAddress`, `FocasTagDefinitionFactory`, `FocasAlarmSelector`, options).
|
||||
@@ -0,0 +1,380 @@
|
||||
# Code review 2026-12-02 — slice 10: S7, Modbus, Sql, Calculation, driver CLIs, OPC UA clients, analyzers
|
||||
|
||||
- **Reviewed at:** `master` @ `708a4889c` (the working tree moved to `59f1eabc8` during the review; that merge does not touch this slice).
|
||||
- **Scope (under `src/`):** `Driver.S7` (+ `.Contracts`), `Driver.Modbus` (+ `.Addressing`, `.Contracts`), `Driver.Sql`
|
||||
(+ `.Dialect`, `.Contracts`, `.Browser`), `Driver.Calculation` (+ `.Contracts`), `Drivers/Cli/*`, `Client.Shared`,
|
||||
`Client.UI`, `Client.CLI`, `Tooling/ZB.MOM.WW.OtOpcUa.Analyzers`.
|
||||
- **Method:** read-only code reading of the drivers, transports, planners and client service, with callers traced into
|
||||
`Core.Abstractions/PollGroupEngine.cs`, `Runtime/Drivers/DriverInstanceActor.cs`, `Runtime/Drivers/DriverHostActor.cs`
|
||||
and `OpcUaServer/OtOpcUaNodeManager.cs` where a finding depends on host behaviour. No tests were run and nothing was
|
||||
executed against a device or database; every finding is from code. Confidence is stated per finding.
|
||||
- **Prior review:** `docs/reviews/2026-10-21/07-drivers-plc.md` and `08-historians-clients.md` were skimmed. The items I
|
||||
re-checked in this slice (Modbus L3/P3/H2/H4/H7/H9/U3/P6, S7 P1/P2/H3/H4/H5/U4, Calculation L1/L2/P4/P5/H6/H8, client
|
||||
1.4/1.5/4.5) are remediated. S-2 is a different path into the same node-stays-Bad outcome as H2, not a regression of it.
|
||||
- **Not covered in depth:** `Sql/SqlCatalogGate.cs`, `SqlCatalogLoader.cs`, `Sql.Contracts/SqlEquipmentTagParser.cs`,
|
||||
`SqlWriteSpec.cs`, the three `*DriverFactoryExtensions.cs` / `*DriverProbe.cs` files, the AbCip/AbLegacy/FOCAS/TwinCAT
|
||||
CLIs, `Client.CLI` history commands and most of `Client.UI` (views, alarms/history view-models) were skimmed or
|
||||
grepped, not read line by line. Absence of findings there is weak evidence.
|
||||
|
||||
## Summary
|
||||
|
||||
| ID | Severity | Category | Confidence | Title |
|
||||
|---|---|---|---|---|
|
||||
| S-1 | High | bug | High | Modbus RTU-over-TCP: a caller-cancelled transaction leaves the socket open with its response in flight; later requests read the previous request's answer as Good data |
|
||||
| S-2 | High | bug | Medium | Modbus deadband baseline survives a re-subscribe, so the forced initial publish is suppressed and rebuilt nodes stay `BadWaitingForInitialData` |
|
||||
| S-3 | Medium | bug | High | Client.Shared: after a failed failover the service keeps its subscription map; a manual reconnect then silently no-ops `SubscribeAsync` for those nodes |
|
||||
| S-4 | Medium | bug | High | Client.Shared: failover is a single pass over the endpoints with no retry; `Client.CLI subscribe`/`alarms` then sit silent forever |
|
||||
| S-5 | Medium | bug | High | S7: an unconvertible/out-of-range value written to a narrow scalar returns `BadCommunicationError` and degrades driver health |
|
||||
| S-6 | Medium | bug | High | Sql: key-value and query row-key attribution is an ordinal string compare, while the database matched with its own semantics — the row is returned but the tag reads `BadNoData` |
|
||||
| S-7 | Medium | bug (security) | Medium | Sql: `SqlReadOnlyStatement` can be bypassed with provider-specific quoting (MySQL backslash escape, Postgres dollar-quote), admitting `; COMMIT; <DML/DDL>` |
|
||||
| S-8 | Medium | bug | High | Modbus DL205: an invalid octal `C…` address silently falls back to the generic `C` coil mnemonic and resolves to a different coil |
|
||||
| S-9 | Medium | perf | High | Calculation: change-triggered evaluations are queued one per input update with no coalescing; the queue is unbounded and one poll cycle evaluates a tag once per changed input |
|
||||
| S-10 | Low | bug | Medium | Sql writes: the "exactly one row" commit rule counts trigger DML, so writes to a table with a row-modifying trigger always roll back |
|
||||
| S-11 | Low | bug | High | Analyzer OTOPCUA0001 does not guard `IAcknowledgedAcquisitionSource` / `IWriteOutcomeCapability`; one production call already bypasses the invoker undetected |
|
||||
| S-12 | Low | perf | High | Client.Shared: one `ApplyChanges` round trip per subscribed node |
|
||||
|
||||
---
|
||||
|
||||
## S-1 — Modbus RTU-over-TCP: a caller-cancelled transaction desynchronises the stream and later reads return another request's data at Good
|
||||
|
||||
- **Severity:** High · **Category:** bug · **Confidence:** High (code path); not reproduced against a device.
|
||||
- **Location:**
|
||||
- `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuOverTcpTransport.cs:119-143` (`SendCoreAsync` catch filters),
|
||||
`:172-197` (`SendOnceAsync` — tears down only for `ModbusTransportDesyncException` and for a per-op timeout
|
||||
`when (!ct.IsCancellationRequested)`).
|
||||
- `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusRtuFraming.cs:104-186` (response is validated for CRC and unit
|
||||
only; nothing ties it to the request).
|
||||
- Cancellation sources: `src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/PollGroupEngine.cs:250-259` (unsubscribe cancels
|
||||
the poll token mid-read), `ModbusDriver.cs:2092-2097` (probe passes a linked token cancelled at `Probe.Timeout`).
|
||||
- **Description:** RTU has no transaction id, so the only thing keeping request and response paired is "one transaction
|
||||
on the wire at a time, and the socket is discarded whenever a transaction ends without its full response". The
|
||||
transport honours that for its own per-op timeout and for writes sent through `SendWithoutRetryAsync`
|
||||
(`catch … when (!allowRetry && (ex is OperationCanceledException …))`). For the ordinary read path (`SendAsync`,
|
||||
`allowRetry: true`) a cancellation of the **caller's** token is deliberately excluded from both catch filters
|
||||
(`!ct.IsCancellationRequested`), so the exception propagates with the socket left connected and the device's reply
|
||||
still on its way. The next request on that socket reads that stale reply. `ValidateAndStrip` accepts it (valid CRC,
|
||||
same unit), and the driver only checks the byte count (`ModbusDriver.cs:1405-1414`).
|
||||
The TCP transport is not affected: the stale reply fails the TxId check, which tears the socket down and the
|
||||
`allowRetry` path reconnects and resends.
|
||||
- **Failure scenario:** A single-unit RTU-over-TCP gateway, one subscription polling a few FC03 blocks. A deploy
|
||||
re-subscribes the kept driver (the actor unsubscribes the old handle first), which cancels the poll loop while a
|
||||
request is outstanding. The reply to that request arrives after the cancel and stays in the socket buffer. From then
|
||||
on every request N receives the reply to request N−1. Requests with the same function code and quantity (the normal
|
||||
case for repeated poll blocks, and always for same-shaped tags) decode the wrong registers and publish them at
|
||||
**Good**. A mismatched byte count throws `InvalidDataException` in the driver, which is not a transport desync and
|
||||
does not tear the socket down, so the shift persists until something else closes the connection. Health shows
|
||||
Healthy/Degraded with `LastSuccessfulRead` advancing, so the watchdog never intervenes. The same shift starts
|
||||
whenever a device answers a probe later than `Probe.Timeout` (default 2 s, equal to the transport timeout, and the
|
||||
probe's clock starts before the gate wait).
|
||||
- **Suggested fix:** In `ModbusRtuOverTcpTransport`, tear the socket down on *any* exit from `SendOnceAsync` after the
|
||||
request bytes were written without a complete, validated response — including caller cancellation (drop the
|
||||
`!ct.IsCancellationRequested` exclusion for teardown; keep it only for deciding whether to retry). Add request/response
|
||||
correlation as a second line of defence: response function code must equal the request's (or request | 0x80), and for
|
||||
FC05/06/0F/10 the echoed address must match; treat a mismatch as `ModbusTransportDesyncException`.
|
||||
- **Test to add:** With a scripted stream that delays its reply: start a read, cancel the caller token after the write,
|
||||
let the reply arrive, then issue a second read for a different address with the same quantity. Assert the second
|
||||
read either reconnects or fails — never returns the first request's payload. A second case: probe token cancelled
|
||||
before a late reply.
|
||||
|
||||
## S-2 — Modbus deadband baseline survives a re-subscribe; the forced initial publish is suppressed
|
||||
|
||||
- **Severity:** High · **Category:** bug · **Confidence:** Medium — the driver behaviour is certain from code; the
|
||||
end-to-end outcome (node stuck Bad) rests on my reading of the host's rebuild + re-subscribe sequence and was not run.
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs:83` (`_lastPublishedByRef`), `:423-453`
|
||||
(`ShouldPublish`), `:193-210` (the engine's `onChange` is filtered through it), `:2019-2021` / `:2058-2066`
|
||||
(subscribe/unsubscribe never touch the cache), `:2549` (the only bulk clear, in `TeardownAsync`).
|
||||
Host side: `OtOpcUaNodeManager.cs:5716-5777` (`RebuildAddressSpace` discards every variable; values are not carried
|
||||
over), `DriverHostActor.cs:3300-3302` (re-pushes desired subscriptions "so live values flow into the just-rebuilt
|
||||
address space"), `DriverInstanceActor.cs:1947-1951` (subscribe-twice drops the prior handle, driver not shut down).
|
||||
- **Description:** `PollGroupEngine` raises every tag once on a new subscription (`forceRaise: true`,
|
||||
`PollGroupEngine.cs:279`). For a tag with `deadband`, Modbus routes that raise through `ShouldPublish`, whose baseline
|
||||
is keyed by tag reference only and is not reset when a subscription is created or removed. If the driver published
|
||||
the tag at Good earlier and the value is still inside the deadband, the forced initial publish returns `false` and
|
||||
neither `OnDataChange` nor the cycle batch carries it. The #527 fix made the baseline (value, status) aware, which
|
||||
covers a Bad that the **driver** published; it does not cover a consumer whose copy was reset by someone else.
|
||||
- **Failure scenario:** A deploy that changes UNS equipment (a full rebuild) but not this Modbus driver's config. The
|
||||
driver is kept, all nodes are recreated at `BadWaitingForInitialData`, and the host re-subscribes. Every deadbanded
|
||||
tag whose value has not moved by ≥ deadband since its last publish — which is what a deadband is for — is suppressed
|
||||
and its node stays `BadWaitingForInitialData` until the process value drifts past the deadband. Non-deadbanded tags
|
||||
recover immediately, so the symptom looks like a handful of random stuck tags after a deploy. The reconnect and
|
||||
respawn paths are safe (both go through `ShutdownAsync` → `TeardownAsync`, which clears the cache).
|
||||
- **Suggested fix:** Make the first raise of a subscription unconditional. Simplest: clear the baseline entries for a
|
||||
subscription's references in `SubscribeAsync`/`SubscribeAcquisitionAsync` (and on unsubscribe). More robust: key the
|
||||
baseline by `(ISubscriptionHandle, tagRef)` so two subscriptions never share one, and drop a handle's entries in
|
||||
`UnsubscribeCoreAsync`.
|
||||
- **Test to add:** Subscribe a deadbanded tag, observe the first Good publish, unsubscribe, subscribe again with the
|
||||
**identical** device value, and assert the second subscription's initial publish arrives on both `OnDataChange` and
|
||||
`OnDataChangeBatch`. An end-to-end variant in `Runtime.Tests`: rebuild + re-subscribe with a kept Modbus driver and
|
||||
assert no node is left at `BadWaitingForInitialData`.
|
||||
|
||||
## S-3 — Client.Shared: stale subscription map after a failed failover makes later `SubscribeAsync` calls silent no-ops
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/OpcUaClientService.cs:999-1000` (failover ends
|
||||
`Disconnected` without clearing `_activeDataSubscriptions` / `_activeAlarmSubscription`), `:150-153`
|
||||
(`DisconnectAsync` returns immediately when already `Disconnected`, skipping the clear at `:195-199`), `:107-147`
|
||||
(`ConnectAsync` does not clear), `:319-323` (`SubscribeAsync` returns early when the key is present).
|
||||
UI caller: `Client.UI/ViewModels/MainWindowViewModel.cs:190-200`, `SubscriptionsViewModel.cs:117-135`.
|
||||
- **Description:** `_activeDataSubscriptions` is the replay list for a failover and also the "already subscribed"
|
||||
guard. When every failover endpoint fails, the state goes to `Disconnected` with the map still populated and the
|
||||
session and SDK subscription gone. Nothing on the manual reconnect path empties it.
|
||||
- **Failure scenario:** In Client.UI: subscribe to `ns=2;s=Plant/Modbus/dev1/Speed`; the server restarts; the single
|
||||
failover attempt fails (S-4) and the UI clears its subscription list on `Disconnected`. The user clicks Connect and
|
||||
adds the same node again. `SubscribeAsync` finds the key, returns successfully without creating a monitored item, the
|
||||
UI adds a row, and the row never updates. The only way out is restarting the client.
|
||||
- **Suggested fix:** Clear both maps wherever the service lands in `Disconnected` without a session: at the end of
|
||||
`RunFailoverAsync` when all endpoints failed, and at the top of `ConnectAsync`. Alternatively make `DisconnectAsync`
|
||||
always run its `finally` clean-up regardless of the current state.
|
||||
- **Test to add:** With fake session/endpoint factories: subscribe, fail the keep-alive, make every failover connect
|
||||
throw, then `ConnectAsync` + `SubscribeAsync` for the same node and assert a monitored item is created on the new
|
||||
session and `DataChanged` fires.
|
||||
|
||||
## S-4 — Client.Shared: failover is one pass with no retry; CLI commands then hang silently
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `OpcUaClientService.cs:953-1000` (`for (attempt < endpoints.Length)` — each endpoint tried once,
|
||||
immediately, then `Disconnected`), `:853-866` (failover starts on the first bad keep-alive);
|
||||
`src/Client/ZB.MOM.WW.OtOpcUa.Client.CLI/Commands/SubscribeCommand.cs:164-180` and `AlarmsCommand.cs` (no
|
||||
`ConnectionStateChanged` handler; they wait on the cancellation token only).
|
||||
- **Description:** The failover loop runs the moment the first keep-alive fails and gives each URL exactly one connect
|
||||
attempt with no delay. A server that is restarting (or a redundant pair mid-switchover) is typically still down at
|
||||
that instant, so the client ends permanently `Disconnected`. `Client.CLI subscribe` and `alarms` do not observe the
|
||||
state change: they keep running, print nothing more, and at Ctrl+C the summary reports the last values seen before
|
||||
the drop as the final state ("Last status GOOD").
|
||||
- **Failure scenario:** A live gate runs `subscribe -r` across a server restart or a redundancy failover to confirm
|
||||
values resume. With a single URL, or when the partner is not yet serving, the client drops to `Disconnected` within
|
||||
one connect timeout and the run looks like "no further data changes" — indistinguishable from a server-side
|
||||
recovery defect, which is what the gate was meant to detect.
|
||||
- **Suggested fix:** Keep cycling the endpoint list with a capped backoff (e.g. 1 s doubling to 15 s) until the epoch
|
||||
changes (user disconnect/dispose), staying in `Reconnecting`. In the CLI commands, subscribe to
|
||||
`ConnectionStateChanged`, print transitions, and exit non-zero if the service reaches `Disconnected` on its own.
|
||||
- **Test to add:** Fake endpoint factory that fails the first N connects then succeeds; assert the service returns to
|
||||
`Connected` and replays subscriptions. CLI test: a service that raises `Disconnected` makes `subscribe` terminate
|
||||
with an error rather than wait.
|
||||
|
||||
## S-5 — S7: a bad value written to a narrow scalar is reported as a comms failure and degrades health
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.S7/S7Driver.cs:2325` (`BoxValueForWrite` inside `WriteOneAsync`),
|
||||
`:2447-2455` (`Convert.ToInt16/ToByte/…` throw `OverflowException` / `FormatException` / `InvalidCastException`),
|
||||
`:2185-2193` (generic catch: `StatusBadCommunicationError` + `outcome.RecordFailure(DriverState.Degraded, …)`; the
|
||||
comment lists "conversion failure" alongside socket/timeout).
|
||||
- **Description:** Buffer types and arrays convert through `S7ValueCodecs` / `EncodeArrayBlock`, which translate
|
||||
conversion problems into `S7ValueRangeException` / `S7WriteValueException` (→ `BadOutOfRange` / `BadTypeMismatch`, no
|
||||
health change). Narrow scalars (Bool, Byte, Int16/UInt16, Int32/UInt32, Float32) convert with bare `Convert.*`, and
|
||||
those exceptions fall into the last catch. `MapDataType` exposes Int16/UInt16/Byte as an OPC UA `Int32` node
|
||||
(`:2773-2780`), so the server's own type check cannot reject an out-of-range value first.
|
||||
- **Failure scenario:** A client writes `70000` to an S7 `Int16` tag (a valid Int32 for the node). The write returns
|
||||
`BadCommunicationError`, the driver goes `Degraded` with the overflow text as `LastError`, and `_writeOwnedError` is
|
||||
latched until the next successful read pass or write. For a driver with no active subscription `LastSuccessfulRead`
|
||||
is frozen, so one bad client value satisfies the #527 conjunction and the watchdog tears the connection down 90 s
|
||||
later. `.claude/rules/drivers.md` states the intended contract: an unrepresentable write is `BadOutOfRange` with no
|
||||
health impact.
|
||||
- **Suggested fix:** Wrap `BoxValueForWrite` at the call site (or inside it): `OverflowException` →
|
||||
`S7ValueRangeException`, `FormatException`/`InvalidCastException` → `S7WriteValueException`. Leave the final catch
|
||||
for transport faults only.
|
||||
- **Test to add:** `WriteAsync` of `70000` to an Int16 tag and of `"abc"` to an Int32 tag against a fake `IS7Plc`:
|
||||
assert `BadOutOfRange` / `BadTypeMismatch`, health unchanged, and that the PLC was never called.
|
||||
|
||||
## S-6 — Sql: client-side row attribution uses an ordinal string compare the database did not use
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High (code); the per-provider examples follow from
|
||||
documented provider behaviour and were not run.
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlPollReader.cs:766-797` (`IndexByKey`:
|
||||
`Convert.ToString(keyCell, InvariantCulture)` into a `StringComparer.Ordinal` dictionary), `:857-861` (lookup by the
|
||||
authored `KeyValue`), `:916-925` (`MapQueryMember` row-key match, also ordinal).
|
||||
- **Description:** The key-value plan selects rows with `WHERE key IN (@k0, …)`, where the server compares the bound
|
||||
text to the column using the column's type and collation. The rows that come back are then re-matched to tags by
|
||||
comparing the *stringified cell* to the authored text with ordinal equality. Whenever the database considers two
|
||||
things equal that are not byte-identical strings, the row is fetched and then not attributed to any tag.
|
||||
- **Failure scenario:** Each of these returns the row and publishes `BadNoData` permanently:
|
||||
- `CHAR(10)` key column: the cell is `"PUMP1 "`, the authored key is `PUMP1`.
|
||||
- Case-insensitive collation (SQL Server and MySQL defaults): row key `PUMP1`, authored `pump1`.
|
||||
- `uniqueidentifier` key: `Guid.ToString()` is lower-case; SSMS shows and users paste upper-case.
|
||||
- Integer key authored with a leading zero (`007`), decimal keys (`1.0` vs `1.00`).
|
||||
The health path counts `BadNoData` as "answered", so the driver stays Healthy and nothing points at the cause.
|
||||
- **Suggested fix:** Attribute by the value the server matched, not by re-comparing text. Options: (a) coerce the
|
||||
authored key to the cell's CLR type and compare typed values (Guid, integral, decimal), trimming trailing spaces for
|
||||
fixed-width character types; (b) fall back to a unique case-insensitive / right-trimmed match when the ordinal lookup
|
||||
misses, mirroring `SqlCatalog.TryMatch`'s exact-then-unique-insensitive rule, and report ambiguity as
|
||||
`BadConfigurationError`.
|
||||
- **Test to add:** Poll-reader tests with a fake reader returning a padded key, a differently-cased key, a `Guid` cell
|
||||
against an upper-case authored key, and an `int` cell against `"007"`; assert Good values. Add a `Category=
|
||||
LiveIntegration` case per provider fixture for the CHAR-padded key.
|
||||
|
||||
## S-7 — Sql: the read-only statement guard can be bypassed with provider-specific quoting
|
||||
|
||||
- **Severity:** Medium · **Category:** bug (security) · **Confidence:** Medium — the guard's acceptance of the strings
|
||||
below is certain from the lexer; that the providers then execute the trailing statements was not run against the
|
||||
fixtures.
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlNamedQuery.cs:138-224`
|
||||
(`SqlReadOnlyStatement.Check`), quote handling at `:165-185`; execution at
|
||||
`src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlPollReader.cs:564-595` (the always-rolled-back transaction).
|
||||
- **Description:** The guard has one lexer for five dialects. It knows `'…'`, `"…"`, `` `…` ``, `[…]`, `--` and
|
||||
`/* */`, with doubled-quote escaping only. Where a provider's lexer ends a literal *earlier* than the guard does, the
|
||||
guard treats live SQL as literal text and never inspects it:
|
||||
- **MySQL** (backslash escapes on by default): `SELECT '\'' ; COMMIT; DELETE FROM t; -- '`. The guard reads
|
||||
`'\''…-- '` as one literal (it pairs the escaped quote with the next one as a doubled quote). MySQL reads `'\''`
|
||||
as a one-character string followed by three more statements.
|
||||
- **PostgreSQL** dollar-quoting: `SELECT $$'$$; COMMIT; DROP TABLE t; --'`. The guard ignores `$$`, opens a literal
|
||||
at `'` and closes it at the final `'`. PostgreSQL reads `$$'$$` as the literal and executes the rest.
|
||||
In both cases the guard sees a single `SELECT` with no forbidden word and no `;` outside a literal. The embedded
|
||||
`COMMIT` ends the transaction the reader opened, so the statements after it are not covered by the rollback (and DDL
|
||||
in MySQL commits implicitly anyway).
|
||||
- **Failure scenario:** A user with the `ConfigEditor` role authors a named query on a driver whose `allowWrites` is
|
||||
false, on a connection whose database principal has more than read rights. The deploy accepts it and the driver
|
||||
executes the trailing DML/DDL on every poll. The documented model ("Named `Query` tags run inside an always-rolled-
|
||||
back transaction behind the `SqlReadOnlyStatement` guard") is the control that is supposed to make that impossible
|
||||
without `allowWrites`.
|
||||
- **Suggested fix:** Make the guard reject what it cannot lex identically to every provider rather than trying to
|
||||
model each: refuse any statement containing a backslash inside a quoted literal, a `$` immediately before or after a
|
||||
quote or a `$tag$` sequence, `E'`/`q'` prefixes, and MySQL `#` comments. Independently, reject `COMMIT`, `ROLLBACK`,
|
||||
`BEGIN`, `START`, `SAVEPOINT`, `SET` as bare words, and where the provider allows it disable multi-statement
|
||||
commands on poll connections. Document that the database principal must be read-only for `Query` tags regardless.
|
||||
- **Test to add:** Unit tests asserting `Check` rejects the two strings above plus `E'\''…` and a `#`-comment variant.
|
||||
A fixture test per provider (MySQL, Postgres) that runs each rejected string directly through the provider to
|
||||
record whether it would have executed, so the guard's rejection list is tied to observed provider behaviour.
|
||||
|
||||
## S-8 — Modbus DL205: an invalid octal `C…` address silently resolves to a different coil
|
||||
|
||||
- **Severity:** Medium · **Category:** bug · **Confidence:** High
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Addressing/ModbusAddressParser.cs:259-287`
|
||||
(family-native failure falls through to `TryParseMnemonicAddress`), `:395-420` (generic `C<n>` = coil, 1-based
|
||||
decimal), `:317-322` (DL205 `C` = control relay, octal); `DirectLogicAddress.cs:215-227` (throws on digits 8/9).
|
||||
- **Description:** Under `Family = DL205`, a `C` address is a control relay in octal, offset from the C-relay coil
|
||||
base. When the digits are not valid octal the family parser throws, the exception is recorded as
|
||||
`familyNativeError`, and parsing continues with the generic mnemonic table, where `C<n>` means Modbus coil `n`
|
||||
(decimal, 1-based). That succeeds, so the family error is discarded and the tag resolves — to a coil in a different
|
||||
memory area. `C` is the only prefix shared by a family grammar and the generic grammar; `V`, `X`, `Y`, `SP`, `D`,
|
||||
`M` do not collide.
|
||||
- **Failure scenario:** A DL205 driver, tag `addressString: "C18"`, writable. The author meant a control relay and
|
||||
mistyped an octal digit. The editor and deploy gate accept it; the tag reads and writes Modbus coil offset 17
|
||||
instead of being rejected. On DirectLOGIC mappings the low coil numbers are a different relay bank, so a write lands
|
||||
on an unrelated bit.
|
||||
- **Suggested fix:** When a non-Generic family recognised the prefix and its parser failed, do not try the generic
|
||||
mnemonic for that same prefix: return the family error. (Keep the Modicon 5/6-digit fallback, which cannot collide.)
|
||||
- **Test to add:** `ModbusAddressParser.TryParse("C18", ModbusFamily.DL205, …)` returns false with the non-octal-digit
|
||||
error; `"C17"` still resolves to the DL205 relay; `"C18"` under `Generic` still resolves to coil offset 17.
|
||||
|
||||
## S-9 — Calculation: no coalescing of change-triggered evaluations; unbounded queue
|
||||
|
||||
- **Severity:** Medium · **Category:** perf (with a correctness side effect) · **Confidence:** High on the behaviour;
|
||||
the load at which it matters was not measured.
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriver.cs:417-430` (one
|
||||
`PrepareEvaluation` + enqueue per dependent per input update), `:536-564` (each allocates a dependency dictionary
|
||||
snapshot), `:596-614` (latest-wins exists only for projected inputs; local work is `_pending.AddLast`), `:631-674`
|
||||
(single pump, one evaluation at a time under the driver-wide `_evalGate`, which timer ticks also take).
|
||||
- **Description:** Every dependency value that arrives enqueues a separate evaluation for each change-triggered tag
|
||||
that reads it. A calc tag with k inputs fed by one poll cycle is evaluated k times for that cycle; the first k−1 run
|
||||
on a mix of new and previous-cycle inputs and their results are published before the consistent one. The queue has
|
||||
no bound and no per-tag replacement, so if the aggregate trigger rate exceeds what the single pump can evaluate
|
||||
(most plausible with `Scripting:Runner=OutOfProcess`, where each evaluation is an IPC round trip, or with slow
|
||||
scripts), `_pending` grows without limit, each entry holding its own snapshot, and published results fall further
|
||||
and further behind their inputs.
|
||||
- **Failure scenario:** 200 calc tags, 5 inputs each, inputs polled at 1 s and all changing: 1000 evaluations/s are
|
||||
queued where 200 would do, and each tag publishes up to four intermediate values per second computed from
|
||||
inconsistent inputs (e.g. `A − B` spikes when A has updated and B has not). At 2 ms per out-of-process evaluation
|
||||
the pump clears 500/s, so the backlog grows by 500 entries/s indefinitely.
|
||||
- **Suggested fix:** Apply the projected path's latest-wins rule to local work: keep at most one pending evaluation
|
||||
per calc tag and build its dependency snapshot when the pump dequeues it rather than when the trigger fires. That
|
||||
bounds the queue at the tag count, collapses a poll cycle's k triggers into one evaluation when the pump is busy,
|
||||
and removes the per-trigger dictionary allocation. Optionally have the host deliver a poll batch's inputs before
|
||||
triggering (a batch boundary) to remove the intermediate values entirely.
|
||||
- **Test to add:** Feed 5 inputs of one tag back-to-back while the evaluator is blocked; assert one evaluation runs
|
||||
after release (not five) and it sees all five new values. A soak-style test: sustained triggers faster than a slow
|
||||
evaluator, assert the pending count stays ≤ tag count.
|
||||
|
||||
## S-10 — Sql writes: the one-row commit rule counts trigger DML
|
||||
|
||||
- **Severity:** Low · **Category:** bug · **Confidence:** Medium (SqlClient's rows-affected semantics; not run).
|
||||
- **Location:** `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriver.cs:754-770`.
|
||||
- **Description:** A table write commits only when `ExecuteNonQueryAsync` returns between 1 and `MaxRowsAffected`.
|
||||
On SQL Server that number is the sum of rows affected by every DML statement the command caused, including
|
||||
statements in triggers that do not `SET NOCOUNT ON`.
|
||||
- **Failure scenario:** An `UPDATE` tag on a table with an audit trigger that inserts one history row returns 2. The
|
||||
write is rolled back and reported `BadConfigurationError` ("a write must touch exactly one row") every time, although
|
||||
exactly one target row matched. The failure is safe (nothing is committed) but the tag is unwritable and the message
|
||||
points at the selector rather than the trigger.
|
||||
- **Suggested fix:** Count the target rows explicitly instead of trusting the aggregate: on SQL Server append
|
||||
`; SELECT @@ROWCOUNT` is not sufficient with triggers either, so use `OUTPUT` into a count, or run the statement with
|
||||
`SET NOCOUNT OFF` and read the first result's `RecordsAffected` via `ExecuteReader`. At minimum document the
|
||||
limitation in `docs/drivers/Sql.md` and name triggers in the warning.
|
||||
- **Test to add:** SQL Server fixture test: table with an `AFTER UPDATE` audit trigger; a single-row write commits and
|
||||
returns Good.
|
||||
|
||||
## S-11 — Analyzer OTOPCUA0001 does not cover the two newer capability interfaces
|
||||
|
||||
- **Severity:** Low · **Category:** bug (analyzer false negative) · **Confidence:** High
|
||||
- **Location:** `src/Tooling/ZB.MOM.WW.OtOpcUa.Analyzers/UnwrappedCapabilityCallAnalyzer.cs:70-78`
|
||||
(`GuardedInterfaceMetadataNames`). Unflagged call: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs:2249-2251`
|
||||
(`source.SubscribeAcquisitionAsync(request, callback, _stop.Token)` inside `Task.Run`, no invoker).
|
||||
- **Description:** The guarded list is `IReadable`, `IWritable`, `ITagDiscovery`, `ISubscribable`,
|
||||
`IHostConnectivityProbe`, `IAlarmSource`. `IAcknowledgedAcquisitionSource.SubscribeAcquisitionAsync` and
|
||||
`IWriteOutcomeCapability.WriteWithOutcomesAsync` (`Core.Abstractions/DataConnections/IWriteOutcomeCapability.cs`) are
|
||||
driver capability calls added since and are not listed, so a direct call to either compiles without a diagnostic.
|
||||
The outcome-write call site happens to be inside `invoker.ExecuteWriteAsync` (`DriverInstanceActor.cs:1490-1515`);
|
||||
the acquisition subscribe is not wrapped, so it runs without the invoker's timeout, breaker and telemetry.
|
||||
Separately, `IHostConnectivityProbe` has no Task-returning member, so its entry in the list guards nothing.
|
||||
- **Failure scenario:** A later driver implements `SubscribeAcquisitionAsync` with real network work (today only Modbus
|
||||
implements it, and its body is local). A hang there is bounded only by the actor's own acquisition timeout and never
|
||||
opens the breaker or shows in resilience telemetry, and no build warning says the call is unwrapped.
|
||||
- **Suggested fix:** Add both interfaces to `GuardedInterfaceMetadataNames`, then either wrap the acquisition subscribe
|
||||
in the invoker (`DriverCapability.Subscribe`) or suppress the diagnostic at that site with a justification.
|
||||
- **Test to add:** Analyzer tests: an unwrapped `WriteWithOutcomesAsync` and an unwrapped `SubscribeAcquisitionAsync`
|
||||
each produce OTOPCUA0001; the same calls inside an `ExecuteAsync`/`ExecuteWriteAsync` lambda do not.
|
||||
|
||||
## S-12 — Client.Shared: one server round trip per subscribed node
|
||||
|
||||
- **Severity:** Low · **Category:** perf · **Confidence:** High
|
||||
- **Location:** `src/Client/ZB.MOM.WW.OtOpcUa.Client.Shared/Adapters/DefaultSubscriptionAdapter.cs:106-122`
|
||||
(`AddItemAsync` calls `ApplyChangesAsync` per item); callers `Client.CLI/Commands/SubscribeCommand.cs:147-158`,
|
||||
`Client.UI/ViewModels/SubscriptionsViewModel.cs:223-248`, and the failover replay `OpcUaClientService.cs:1026-1046`.
|
||||
- **Description / cost:** Subscribing N nodes issues N sequential `CreateMonitoredItems` requests, each holding
|
||||
`_subscriptionGate`. `subscribe -r` over a 10k-variable subtree is 10k round trips (tens of seconds on a LAN, longer
|
||||
through Traefik), and a failover replays them the same way while notifications for already-replayed items are
|
||||
flowing.
|
||||
- **Suggested fix:** Add a batch method to `ISubscriptionAdapter` (add all items, one `ApplyChangesAsync`, then read
|
||||
each item's `Status.Error`) and use it from the recursive subscribe paths and from `ReplaySubscriptionsAsync`.
|
||||
- **Test to add:** Fake subscription adapter counting apply calls: subscribing 100 nodes through the batch path makes
|
||||
one apply; a per-item creation error is reported for that node only.
|
||||
|
||||
---
|
||||
|
||||
## Areas reviewed with no findings
|
||||
|
||||
- **Modbus driver (`ModbusDriver.cs`)** — read in full. Word/byte order (`NormalizeWordOrder` for 4- and 8-byte
|
||||
types, both directions), BCD16/32 encode/decode, string byte order and odd lengths, bit-in-register read and RMW
|
||||
write (per-register lock, ascending lock order for arrays), FC01/02/03/04 response length checks, chunked reads, block
|
||||
coalescing (gap/span/cap arithmetic, auto-prohibition overlap test, bisect re-probe, refused-block fallback to
|
||||
per-tag reads), FC23/FC16/FC06/FC05/FC15 selection and acknowledgement validation in `SingleSendWriteTransport`, the
|
||||
health composition (`ReportOutcome`, refusal vs comms classification, generation fencing), lifecycle gate and
|
||||
dispose-before-overwrite of the transport and probe loops.
|
||||
- **Modbus TCP transport and socket lifecycle** — TxId/length validation, per-op timeout teardown, single throttled
|
||||
reconnect-and-resend, connect backoff, idle disconnect. The stale-response case in S-1 is caught here by the TxId
|
||||
check.
|
||||
- **Modbus addressing** — Modicon 5/6-digit parsing and bounds, type/byte-order/array-count field grammar, MELSEC and
|
||||
DL205 `V`/`X`/`Y`/`SP` conversion entry points (S-8 is the one collision). `ModbusTagDefinitionFactory` /
|
||||
`ModbusTagAddressResolution`: region/type compatibility, string-length and bit-index guards.
|
||||
- **S7 driver (`S7Driver.cs`)** — read in full. Span planner (`S7ReadSpanPlanner`: gap/span arithmetic, relative
|
||||
offsets, per-area/DB grouping), multi-var batching and its fallback bookkeeping, dead-handle fast-fail within a pass,
|
||||
narrow/array/buffer decode paths and signed reinterpretation, `S7ValueCodecs` (WSTRING, DTL, DATE, TOD, TIME, S5TIME
|
||||
base/BCD), address parser bit/size rules, `S7TagShapeRules`, reconnect backoff, access-denied sticky fault and the
|
||||
write-pass health merge, generation-fenced lifecycle. Timer/counter BCD is #616 and was not re-examined.
|
||||
- **Sql driver** — group planner (key chunking against `MaxBindParameters`, row caps, wide-row selectors), write
|
||||
planner bind order for positional providers, identifier quoting in all five dialects (quote-character doubling;
|
||||
Oracle `BindByName`), poll reader concurrency (gate, ref-counted disposal, abandoned-work handling, operation
|
||||
deadline), shape caching per subscription list, NULL/coercion/timestamp mapping, health classification
|
||||
(`ObservePollOutcome`: connection-class vs query-class vs answered), write transaction commit/rollback, catalog-gate
|
||||
wiring in `InitializeAsync`. Browser and catalog loader SQL is dialect-constant with bound parameters (grep-level
|
||||
check only).
|
||||
- **Calculation driver** — hold-on-bad-input and worst-status inheritance, (value, status) dedup on success/failure/
|
||||
hold, compile-failure memoisation per source hash, compiled-script clearing on shutdown/adopt, timer scheduler
|
||||
in-flight skip, pump scheduling flag vs enqueue race, dispose ordering. Cycle and `scriptId` gates live in the deploy
|
||||
validator, outside this slice.
|
||||
- **Client.Shared** — epoch fencing of failover against user connect/disconnect/dispose, notification filtering by
|
||||
session + subscription identity, browse and history continuation-point release, subscription detach from the SDK
|
||||
session, alarm filter field ordering vs `OnAlarmEventNotification` indices.
|
||||
- **Driver CLIs** — `Cli.Common`, Modbus CLI read/write/subscribe and value parsing spot-checked; nothing found. The
|
||||
other five CLIs were not read.
|
||||
- **Analyzer** — interface-implementation matching (explicit/implicit/generic receivers) and wrapper-lambda detection
|
||||
behave as intended for the listed interfaces; the gap is the list itself (S-11).
|
||||
@@ -0,0 +1,217 @@
|
||||
# 2026-12-02 review remediation plan
|
||||
|
||||
Source: `docs/reviews/2026-12-02/` (00-SUMMARY + 10 slice reports), master @ `708a4889c`. ~150 findings: 2 Critical, 19 High,
|
||||
62 Medium, 67 Low. Finding IDs (R-, U-, C-, A-, H-, K-, G-, M-, P-, S-) refer to the slice reports, which carry the
|
||||
file:line, failure scenario, suggested fix and test for each.
|
||||
|
||||
## Ground rules
|
||||
- **Status lives in Gitea, not here.** File one issue per workstream below (labels `type:review-finding` + priority;
|
||||
`blocked`/`cross-repo` where noted) and reference `#N` from this plan. Don't tick boxes in this file.
|
||||
- **Fix the pattern, not the instance.** Each workstream names the shared seam; fix it there and then sweep the listed instances.
|
||||
- **Every fix lands with the test named in its finding.** For absence bugs (something *not* happening), the test needs a positive
|
||||
control (`project_test_absence_positive_control`).
|
||||
- **Re-verify before fixing.** Most findings come from reading the code. Start each workstream by reproducing its finding
|
||||
in a failing test; a finding that doesn't reproduce gets closed as not-a-defect, with the evidence.
|
||||
- **Live gate per wave** on docker-dev (login disabled, so drive `/run` yourself). Hardware/VM gates are listed per item.
|
||||
- Work in parallel worktrees per workstream (the #938–#968 batch pattern), with a review round per merge. Every past review
|
||||
round caught real defects that green tests missed.
|
||||
|
||||
## Issue map (Gitea, filed 2026-12-02)
|
||||
| Issue | Scope | Pri |
|
||||
|---|---|---|
|
||||
| #971 | W0.1 sandbox (K-1) | p0 |
|
||||
| #972 | W0.2 ACL revalidation regression (U-1) | p0 |
|
||||
| #973 | W0.3 fleet-diagnostics SSRF (A-1) | p1 |
|
||||
| #974 | W0.4 Sql read-only guard (S-7) | p1 |
|
||||
| #975 | W0.5 AdminUI role freshness (A-2) | p2 |
|
||||
| #976 | W1.1 alarm S&F / historian transient (G-16≡K-2, G-8, G-7) | p1 |
|
||||
| #977 | W1.3 deploy/apply bookkeeping (R-1, U-2, U-3, U-9, R-4, R-15, R-20, H-4) | p1 |
|
||||
| #978 | W1.4 name authority + script gate (C-1≡R-5, C-4, C-7, C-2) | p1 |
|
||||
| #979 | W1.5 stale/rejected Good (U-4, R-6, G-4) | p2 |
|
||||
| #980 | W1.7 host liveness (H-1, H-2, H-5) | p1 |
|
||||
| #981 | Modbus (S-1, S-2, S-8) | p1 |
|
||||
| #982 | TwinCAT (P-1, P-3, P-4, P-12, P-19, P-22, P-25) | p1 |
|
||||
| #983 | AbCip (P-2, P-13, P-16, P-17, P-22, P-23, P-24) | p1 |
|
||||
| #984 | AbLegacy (P-5, P-14, P-15, P-18, P-23) | p1 |
|
||||
| #985 | FOCAS (P-6…P-11, P-20, P-21, P-25) | p1 |
|
||||
| #986 | S7 (S-5) | p2 |
|
||||
| #987 | Sql driver (S-6, S-10) | p2 |
|
||||
| #988 | MQTT/Sparkplug (M-1, M-2, M-3, M-6, M-11…M-15) | p2 |
|
||||
| #989 | MTConnect (M-4, M-5, M-7…M-10) | p2 |
|
||||
| #990 | Heidenhain (M-16…M-19) | p3 |
|
||||
| #991 | Galaxy (G-1…G-6, G-19 — cross-repo mxaccessgw) | p2 |
|
||||
| #992 | OpcUaClient (G-10…G-15) | p2 |
|
||||
| #993 | Historian backends (G-9, G-17, G-18) | p3 |
|
||||
| #994 | W3 gRPC data / projected scaling (R-2, R-3, R-7…R-10, R-12, R-13, R-21…R-24, U-10…U-13) | p1 |
|
||||
| #995 | W4 deploy-path perf (K-3, R-11, R-14, U-5, R-17, R-19, S-9) | p2 |
|
||||
| #996 | W4 ConfigDb/page/history perf (C-6, C-11≈A-5, A-8, H-3, H-6, U-6) | p2 |
|
||||
| #997 | AdminUI correctness (A-3, A-4, A-6, A-7, A-9) | p2 |
|
||||
| #998 | Configuration gaps (C-3, C-5, C-8, C-9, C-10) | p2 |
|
||||
| #999 | Core scripting/alarms/resilience (K-4…K-11) | p2 |
|
||||
| #1000 | Client.Shared (S-3, S-4, S-12) | p3 |
|
||||
| #1001 | Analyzer OTOPCUA0001 (S-11) | p2 |
|
||||
| #1002 | Runtime/OpcUaServer residual (R-16, R-18, R-25, U-7, U-8) | p3 |
|
||||
|
||||
---
|
||||
|
||||
## Wave 0 — Security + Critical (do first, P0/P1)
|
||||
|
||||
### W0.1 Script sandbox (K-1) — P0
|
||||
- Stopgap now (option 2 in K-1): deny `Delegate.CreateDelegate`/`DynamicInvoke`/`Method`, `System.Linq.Expressions`, `System.Xml*`,
|
||||
`System.Formats`, `System.Timers`, `System.ComponentModel`, `System.Security`, `System.Data`, `System.Resources`,
|
||||
`System.Runtime.Serialization`, `ParallelEnumerable`, `Serilog.Log`/`LoggerConfiguration`, and the reflection-returning
|
||||
`System.Type` members. File: `Core.Scripting/ForbiddenTypeAnalyzer.cs:43-152`.
|
||||
- Real fix: invert to an **allow-list** (option 1) and narrow `ScriptSandbox.EnumerateBclAssemblyPaths` (option 3).
|
||||
The editor diagnostics share the same analyzer, so Monaco ⇔ publish parity is kept automatically. Re-run the analyzer
|
||||
over every stored script in the docker-dev ConfigDb so legitimate scripts aren't broken.
|
||||
- Make the host write the PE cache, not the worker (option 4).
|
||||
- Document in `docs/VirtualTags.md`/`docs/security.md` that InProcess scripting = Designer code execution as the service until the allow-list ships.
|
||||
- Test: theory over the 8 bypass snippets in `ForbiddenTypeAnalyzerTests`, plus an allow-list regression over the shipped sample scripts.
|
||||
|
||||
### W0.2 ACL revalidation regression (U-1) — P0
|
||||
- `IsSubscriptionStillPermitted` → route through `Permits(identity, CreateMonitoredItems, nodeId)` (it carries the flag-off
|
||||
bypass); null-guard `_authorizer`; fix the timer remark. Files: `OtOpcUaNodeManager.cs:848,8741,8876-8975`.
|
||||
- Revisit `SecurityFilteringActive`'s `NamespaceIndexes.Count >= 4` term (always true). Decide whether it should exist at all.
|
||||
- Test: flag-off, anonymous subscription survives N revalidation passes + a deploy (with a positive control: flag-on denies it).
|
||||
- Live gate: docker-dev, Client.CLI anonymous `subscribe` held for 3 min across a deploy.
|
||||
|
||||
### W0.3 AdminUI fleet-diagnostics SSRF (A-1) — P1
|
||||
- Resolve `?node=` / the typed box against Up driver members ∪ enabled `ClusterNode` `Host:AkkaPort`; reject otherwise.
|
||||
Add a defence-in-depth regex in `FleetDiagnosticsClient`. Consider raising the page policy to `DriverOperator`.
|
||||
- Also audit the cluster HOCON for Akka `trusted-selection-paths` / untrusted-mode (cross-slice; H slice).
|
||||
|
||||
### W0.4 SQL read-only guard (S-7) — P1
|
||||
- `SqlNamedQuery.cs:138-224`: make the guard dialect-aware (MySQL backslash escapes, Postgres `$tag$` quoting) **and**
|
||||
execute read-only statements in a read-only transaction / read-only connection where the provider supports it,
|
||||
so the guard is no longer the only line of defence.
|
||||
- Gate: run the bypass strings against the Postgres + MySQL fixtures on `10.100.0.35`.
|
||||
|
||||
### W0.5 AdminUI role freshness (A-2) — P2
|
||||
- Re-validate role claims on a timer (cookie `OnValidatePrincipal` with a short refresh window), and have open circuits
|
||||
re-check through `RevalidatingServerAuthenticationStateProvider`.
|
||||
|
||||
---
|
||||
|
||||
## Wave 1 — Data loss & silent wrong data (P1)
|
||||
|
||||
### W1.1 Transient ≠ permanent in alarm history (G-16 ≡ K-2, G-8, G-7)
|
||||
- `LocalDbStoreAndForwardSink.cs:28-35`: `RetryPlease` must not consume `MaxAttempts` — only `PermanentFail` (or a
|
||||
poison-payload classification) counts; outage retries back off capped and never dead-letter.
|
||||
- `GatewayAlarmHistorianWriter.cs:286-299`: `Cancelled`/`Unknown`/`Unavailable`/`DeadlineExceeded` and non-RPC transport
|
||||
exceptions → `RetryPlease`.
|
||||
- `FasterLogHistorizationOutbox.cs:151-155` (G-7): truncate only up to the last *indexed* address.
|
||||
- Test: a 10 min simulated outage loses 0 events; reconnect drains everything in order.
|
||||
- Gate: the historian live-gate recipe in `.claude/rules/historian.md` (SqlServer + QuestDb backends locally; the AVEVA gateway leg is user-gated).
|
||||
|
||||
### W1.2 Wire desync / stale-offset reads reported Good (S-1, P-1, P-10)
|
||||
- **S-1** Modbus RTU-over-TCP: tear the socket down on any exit from `SendOnceAsync` after the request was written
|
||||
(cancel included). Test: cancel mid-transaction, then the next read gets its own reply.
|
||||
- **P-10** FOCAS: close the session on non-transient protocol errors and match replies to requests.
|
||||
- **P-1** TwinCAT: watch the ADS symbol-version / `AdsState` change notification; on change, invalidate the symbol cache,
|
||||
re-resolve handles and re-register notifications; mark values `BadConfigurationError`/`Uncertain` until re-resolved.
|
||||
Gate: TCBSD VM (`10.100.0.128`), online change + full download. Note in the issue that the finding relies partly on decompiled Beckhoff cache behaviour.
|
||||
|
||||
### W1.3 Deploy/apply bookkeeping (R-1, U-2, U-3, U-9, R-4, R-15, R-20, H-4)
|
||||
- **R-1** `DriverHostActor.Bootstrap`: restore from the newest **Applied** artifact, not the newest row. Test + docker-dev
|
||||
gate: a failed deploy followed by a node restart serves the last good address space.
|
||||
- **U-2/U-3/U-9** planner: add scripted-alarm `Enabled`/`AlarmType`/`Severity`/`Name` and Line→Area parentage to the diff
|
||||
(Line re-parent ⇒ rebuild, or a surgical move). Remove the VirtualTag sub-folder with the variable. This is the "omitting a field
|
||||
silently reopens staleness" class: add a test that reflects over the record fields so a new field can't be skipped.
|
||||
- **R-4** keep the degraded flag until a full re-ensure succeeds; **R-15** advance the revision after the last throwing step;
|
||||
**R-20** persist/restore `_lastApplied` across `OpcUaPublishActor` restart (or force a rebuild on restart).
|
||||
- **H-4** `HandleDispatch` must close (fail/supersede) the prior in-flight deployment row.
|
||||
|
||||
### W1.4 One name authority (C-1 ≡ R-5, C-4, C-7, C-2)
|
||||
- Expose a single `V3NodeIds.ValidateSegment(string)` (the exact rule `Uns(...)` enforces) and call it from the VirtualTag
|
||||
modal, the `DisplayNameOverride` editor, CSV import **and** `DraftValidator`. Fix `UnsSegment` to use `\z` and not `$` (C-7).
|
||||
- **R-5** defensive: `VirtualTagHostActor` skips and reports an invalid tag instead of crashing on every apply.
|
||||
- **C-2** add a script-existence gate rule for VirtualTags + ScriptedAlarms, and block deleting a script that's in use
|
||||
(usage check in the service; an FK if the model allows).
|
||||
- Gate: docker-dev, an author `a/b` VirtualTag is rejected in the modal *and* by publish.
|
||||
|
||||
### W1.5 Initial/stale publish correctness (S-2, U-4, R-6, G-4)
|
||||
- **S-2** clear `_lastPublishedByRef` for refs on (re)subscribe. **U-4** revert to the last *confirmed* value, tracking per-write
|
||||
generations. **R-6** dependents of a removed input go `BadWaitingForInitialData`/`Bad`. **G-4** a dropped pump event triggers a
|
||||
re-read of that tag (or marks it Uncertain).
|
||||
|
||||
### W1.6 Driver data-shape bugs (P-5, P-13, P-14, P-15, P-9, S-8)
|
||||
- **P-5** AbLegacy: reject a `Long` on a MicroLogix per-tag (BadConfigurationError) + a deploy-gate rule, without faulting the driver.
|
||||
- **P-13** AbCip BOOL array: element count = DWORDs (gate: `ab_server`). **P-14/P-15** AbLegacy bit arrays: size in words;
|
||||
a `Bit` write without `/n` is rejected or RMWs bit 0 (decide; document).
|
||||
- **P-9** FOCAS keep the slot index. **S-8** DL205: an invalid octal is an error, not a fallback.
|
||||
|
||||
### W1.7 Host liveness (H-1, H-2, H-5)
|
||||
- **H-1** a node that is downed or leaves the cluster exits non-zero so SCM recovery fires. Gate: `windev` (not the wonder boxes).
|
||||
- **H-2** `AuditWriterActor`: clear the buffer only after save succeeds, with a bounded retry buffer. **H-5** an HTTPS binding fails validation and stops the node from booting.
|
||||
|
||||
---
|
||||
|
||||
## Wave 2 — Health contract & device isolation (P1/P2)
|
||||
|
||||
### W2.1 Refusal vs comms-fault classification
|
||||
Add the shared helper (or extend the existing status mapping) and sweep: P-6 FOCAS fixed-tree, P-12 TwinCAT
|
||||
`TwinCATStatusMapper.cs:84` default, S-5 S7 bad write values → `BadOutOfRange`/`BadTypeMismatch`, G-9 Gateway read refusals,
|
||||
G-14 OpcUaClient post-dispatch write → `BadTimeout`, R-8 projected `QueryAsync` per-call faults, R-10 publisher capacity refusal,
|
||||
P-7 FOCAS transient bootstrap latch, P-21 `CoalesceRejected` latch. Test pattern: a refusal leaves health Healthy and
|
||||
the watchdog quiet; a real outage degrades.
|
||||
|
||||
### W2.2 Outages that never degrade
|
||||
M-2 MQTT: subscribe per filter (or validate filters at authoring and at the gate) and degrade on SUBACK failure; M-14 browse honours
|
||||
CONNACK/SUBACK; G-19 mxaccessgw HTTP/2 keep-alive + stream idle timeout (**cross-repo** `mxaccessgw`); M-6 Sparkplug primary-host
|
||||
re-claim after reconnect; M-1 the rebirth give-up counter is not reset by the NBIRTH it provoked; M-3 derive a unique
|
||||
primary-host client id.
|
||||
|
||||
### W2.3 One dead device stalls the rest
|
||||
P-2 AbCip warm-handle backoff + per-device batching; P-3 TwinCAT per-device parallel reads with fail-fast; P-4 skip the registration
|
||||
replay while the device is offline; P-11/P-8 FOCAS: check backoff before the gate, bound the close handshake. Gates: TCBSD VM,
|
||||
FOCAS sim, AbCip `ab_server` (multi-device with one blackholed).
|
||||
|
||||
---
|
||||
|
||||
## Wave 3 — gRPC data / projected path scaling (P2)
|
||||
Owner seam: `Runtime/DataConnections/*` + the projected half of `OtOpcUaNodeManager`. Keep #969 in the same issue family.
|
||||
- **R-2** batch cohort opens into one stream command (or pace them under the origin's 128/s limit).
|
||||
- **R-3** scan partition changes for the session's own sources (an index per source), not the first 32 global changes.
|
||||
- **R-7** a full channel must not tear down sibling demands (backpressure instead). **R-9** invalidate per-source, and treat lock contention as not an invalidation.
|
||||
- **R-12** authorize once per frame (memoised per session epoch). **R-13** copy-on-write handle tables.
|
||||
- **U-10** index live items by node for `TryPublish`. **U-12** O(1) eviction (LRU). **U-11** tombstone the monitored node on anchor removal.
|
||||
- **R-21, R-22, R-23, U-13** small fixes in the same files.
|
||||
- Perf test: a 10k-item cohort open plus a 1k values/s publish, with before/after numbers recorded in the issue.
|
||||
|
||||
## Wave 4 — Deploy-path & page performance (P2)
|
||||
- **K-3** cache compiled predicates by source hash and compile outside the engine gate (swap under the gate). Measure before and after on a deploy with 500 alarms.
|
||||
- **R-11** re-subscribe only drivers whose desired set changed. **R-14** parse the artifact data projection once per apply, off the pinned thread.
|
||||
- **U-5** index stood-down items by node. **U-6** add a server page cap for `HistoryReadEvents` (the same pattern as the raw cap from the October review).
|
||||
- **C-6** project `Deployment` without `ArtifactBlob` in the health probe and readiness check. **C-11 ≈ A-5** add a scoped snapshot loader for the data-connections page.
|
||||
- **H-6** run EF calls off the coordinator thread (PipeTo). **H-3** run AdminOps DB I/O off the mailbox, and audit before dispatch (or make the reply idempotent).
|
||||
- **R-17, R-19, S-9** coalesce the VirtualTag/Calculation evaluation backlogs (latest-value-wins per tag), with a bounded queue.
|
||||
|
||||
## Wave 5 — Remaining Medium bugs (P2/P3)
|
||||
Lifecycle/leaks: M-5 MTConnect subscription release, A-6 reaper drain, R-16 `StopChild` comms-latch + timer, G-11 OpcUaClient
|
||||
unsubscribe ordering, M-13 MQTT handle cleanup.
|
||||
Correctness: A-3 duplicate sibling names (pre-check + `DbUpdateException` handling), A-4 Galaxy ack password blanking, C-3 ZTag/SAPID
|
||||
reservations (write `ExternalIdReservation` or remove the UI claim), C-5 historian tagname collision rule, K-4 shelve-expiry event,
|
||||
K-5 frame cap split, K-6 resilience timeout visible to breaker, S-3/S-4 Client.Shared failover retry + map reset, S-6 Sql key
|
||||
comparison by provider semantics, M-4 MTConnect intra-chunk fault, G-1 Galaxy security map filled at init, G-10 OpcUaClient recovery index,
|
||||
P-16 AbCip log throttling, P-17 ALMD `OperAck` (hardware-gated, #592), P-18/P-19 coalescing + per-poll cost, P-20 FOCAS truncation.
|
||||
|
||||
## Wave 6 — Low items
|
||||
Batch by slice: one issue per slice report covering its remaining Low findings (R-18, R-24, R-25, C-7…C-10, A-7…A-9, K-7…K-11,
|
||||
G-2, G-3, G-5, G-6, G-12, G-13, G-15, G-17, G-18, M-7…M-12, M-15…M-19, P-22…P-25, S-10…S-12). S-11 (analyzer coverage) should go
|
||||
earlier: extending OTOPCUA0001 will flag `DriverInstanceActor.cs:2251` and may surface more instances.
|
||||
|
||||
---
|
||||
|
||||
## Sequencing & parallelism
|
||||
| Order | Workstreams | Can run in parallel | Gate |
|
||||
|---|---|---|---|
|
||||
| 1 | W0.1, W0.2, W0.3, W0.4 | yes (disjoint files) | docker-dev + Sql fixtures |
|
||||
| 2 | W1.1–W1.7, W0.5 | yes; W1.3 and W1.4 both touch `DraftValidator` / the planner, so split by file or run them sequentially | docker-dev, historian, TCBSD, windev |
|
||||
| 3 | W2.1–W2.3 | per driver | fixtures + TCBSD + `ab_server` |
|
||||
| 4 | W3, W4 | W3 is one owner (shared files) | perf numbers in issue |
|
||||
| 5 | W5, W6 | per slice | unit + spot live |
|
||||
|
||||
## Blocked / external
|
||||
- G-19 needs an `mxaccessgw` client change (**cross-repo**). Update the umbrella index row only if the wire contract changes.
|
||||
- P-17 and P-13 need bench hardware or `ab_server` (#592). H-1 needs Windows (`windev` is fine; the wonder boxes are on hold, so no psbridge/winrm).
|
||||
- Deploying any of this to the wonder boxes is blocked by the 2026-09-11 hold.
|
||||
Reference in New Issue
Block a user