Files
ScadaBridge/docs/plans/2026-12-02-full-code-review.md
T
Joseph Doherty 28b6651a89 docs(plans): full code review 2026-12-02 (112 findings) + remediation plan
Nine parallel read-only reviewers over every src/ project at d4d5be3b:
9 High, 51 Medium, 52 Low. Remediation grouped into WP1-WP7.
2026-12-02 16:06:45 -05:00

1976 lines
199 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Full code review — performance and bugs (2026-12-02)
**Scope:** every hand-written project under `src/` at `d4d5be3b`. Generated protobuf code, `bin/`, `obj/` and `Migrations/` were excluded.
**Method:** nine parallel Fable reviewers, each covering one slice, read-only. Each finding was traced through the code before it was reported. Most are static traces; a few were checked further against the rig database, by `EXPLAIN QUERY PLAN`, or by compiling a probe script. Nothing was built or run against a live cluster. Spot-checks during consolidation confirmed CMN-1 (no `?.` visitor), TRN-1 (no `Include`) and DEP-1 (audit staged after the last save).
**Fix plan:** `docs/plans/2026-12-02-full-code-review-remediation.md`.
## Totals
| Slice | High | Medium | Low | Total |
|---|---|---|---|---|
| 1 Communication / ClusterInfrastructure / HealthMonitoring | 2 | 3 | 3 | 8 |
| 2 SiteRuntime | 0 | 5 | 9 | 14 |
| 3 Commons / ScriptAnalysis | 1 | 2 | 9 | 12 |
| 4 CentralUI | 1 | 6 | 6 | 13 |
| 5 DataConnectionLayer / StoreAndForward / SiteEventLogging | 1 | 7 | 6 | 14 |
| 6 AuditLog / SiteCallAudit / KpiHistory | 0 | 5 | 4 | 9 |
| 7 ConfigurationDatabase / DeploymentManager / TemplateEngine | 2 | 8 | 2 | 12 |
| 8 Transport / ManagementService / CLI | 2 | 12 | 7 | 21 |
| 9 Host / InboundAPI / Notifications / ESG / Security / DelmiaNotifier | 0 | 3 | 6 | 9 |
| **Total** | **9** | **51** | **52** | **112** |
## High findings at a glance
| ID | Summary |
|---|---|
| CMN-1 | The script trust validator never inspects `?.` member bindings, so a site script can call reflection through them. This defeats the trust gate fleet-wide. |
| DEP-1 / MGT-1 (+ TPL-3) | Config-audit rows are staged after the last `SaveChanges` and never written. This affects Deploy, Disable, Enable, Delete, Deploy Artifacts, API keys, shared schemas, external-system methods, data-connection moves and InstanceService. The rig DB shows the gap. |
| TPL-1 | A module composed into two slots runs the last slot's alarm on-trigger script for both slots, so a script acts on the wrong equipment. |
| DCL-1 | Late seed-read values overwrite newer subscription values after a (re)subscribe, leaving a stale value with Good quality indefinitely. |
| COMM-1 | Health-report sequence seeding means that after a long-uptime failover, the new active node's reports are rejected silently as stale for days. |
| COMM-2 | A live stream opened to a standby site node succeeds but carries no events and never fails over, so the Alarm Summary and Debug View claim to be live while showing stale data. |
| UI-1 | The circuit-lifetime tracked DbContext serves stale entities after out-of-scope changes. Examples: a data-connection move doesn't show, Topology areas never update, and a later save can silently revert an imported script. |
| TRN-1 | Notification-list Overwrite on import appends recipients instead of replacing them, so recipients are duplicated or kept after removal. |
Severity is the reviewer's assessment. "Confirmed" means the code path was traced; "Plausible" means the logic is confirmed but the trigger depends on timing or environment.
---
## Slice: Review 01 — Communication / ClusterInfrastructure / HealthMonitoring
Scope: `src/ZB.MOM.WW.ScadaBridge.Communication/`, `src/ZB.MOM.WW.ScadaBridge.ClusterInfrastructure/`,
`src/ZB.MOM.WW.ScadaBridge.HealthMonitoring/` at HEAD `d4d5be3b` (hand-written code only).
Method: read-only code trace, callers included. Nothing was built or run, so "Confirmed" means
"confirmed by reading the full code path", not "reproduced".
Not read line by line: the three large DTO mappers (`SiteCommandDtoMapper.cs`, `CentralControlDtoMapper.cs`,
and the smaller audit/site-call mappers) were only spot-checked for null-unsafe timestamp conversions (none found
that a current peer can trigger). `ClusterInfrastructure` (options, validator, `ClusterBootstrapGuard`) produced no findings.
Paths below are relative to `src/`.
| ID | Severity | Category | Confidence | Title |
|----|----------|----------|------------|-------|
| COMM-1 | High | bug | Confirmed | Site health reports are rejected as stale after a failover of a pair that was started together |
| COMM-2 | High | bug | Confirmed | Live streams opened to a standby site node are idle but reported as connected/live |
| COMM-3 | Medium | bug | Confirmed | Debug stream delivers gap-window events before the initial snapshot reaches the consumer |
| COMM-4 | Medium | bug | Confirmed | Site liveness is keyed on the site's own clock, so a fast site clock delays offline detection |
| COMM-5 | Medium | bug | Plausible | No connect timeout on any gRPC channel: a black-holed node yields DeadlineExceeded, which never triggers failover |
| COMM-6 | Low | bug | Confirmed | Standby nodes accumulate per-interval error counters and report them as one interval after failover |
| COMM-7 | Low | bug | Confirmed | `DebugStreamBridgeActor` ignores the transport's fail-fast `Status.Failure` for the snapshot request |
| COMM-8 | Low | perf | Confirmed | Failback probes run serially for all sites inside the 1 s sweep loop |
---
## COMM-1 — Site health reports are rejected as stale after a failover of a pair that was started together
- **Severity:** High · **Category:** bug · **Confidence:** Confirmed
- **Where:** `ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs:63` (seed), `:86-87` (standby skips before incrementing), `:150` (increment);
`ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs:70-76` (reject `seq <= last`);
`ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs:352` (ack is always `Accepted: true`).
**What's wrong.** The sequence number is seeded with Unix-milliseconds at *process construction* and then incremented by 1 per
report (one per 30 s), and only on the active node. The comment claims this makes a freshly-active node always sort after the
prior active node. That holds only if the new active node's process started more milliseconds after the old one than the old
one has sent reports. The seed advances at 1000 units per second of start gap; the active counter advances at 1 unit per 30 s.
So for two nodes started `g` ms apart, the standby's first sequence (`T_B + 1`) is below the active's current sequence
(`T_A + n`) as soon as the active has been up longer than `g × 30 s`.
Central rejects the report silently (Debug log), and `CentralCommunicationActor` still acks `Accepted: true`, so the site logs
"Sent health report" and does not retry or restore anything.
**Failure scenario.** A site pair is stopped and started together (the documented requirement for site-pair upgrades; also
`deploy.sh` and any power event), node B's process starting 5 s after node A's. A is the older member and active. After
5000 × 30 s ≈ 42 hours of uptime, any failover to B (crash or `TriggerSiteFailover`) makes B's reports sort below A's last one.
Every report from B is dropped until B has sent roughly as many reports as A had (deficit ≈ A's active uptime ÷ 30 s, i.e. about
as long as A had been active — days or weeks). During that time the site shows Online (heartbeats still pass) with the dead
node's last metrics, flagged "metrics stale" after 2 minutes, and no connection/S&F/error data from the node that is actually
running. Only restarting both central nodes clears it. With the bootstrap guard on, the founder is chosen by address rather than
start order, so B's process can even be the earlier one, in which case rejection starts at the first failover regardless of uptime.
The rig failover drills do not show this because the pair's uptime is short and restarts are minutes apart.
**Suggested fix.** Re-seed the sequence from the current Unix-ms each time the node transitions standby → active (or simply use
`max(previous + 1, now-ms)` on every report), so a newly active node always sorts above anything sent earlier. Independently, have
the aggregator return a rejection in the ack (or accept a lower sequence when the reporting `NodeHostname` changed) so a drop is
never silent.
---
## COMM-2 — Live streams opened to a standby site node are idle but reported as connected/live
- **Severity:** High · **Category:** bug · **Confidence:** Confirmed
- **Where:** `ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs:317-323` (only ready/shutdown gates, no active-node check) and `:474-477` (headers flushed);
`ZB.MOM.WW.ScadaBridge.Communication/Actors/SiteAlarmAggregatorActor.cs:109` (`_useNodeA = true`), `:990`, `:1044-1050`;
`ZB.MOM.WW.ScadaBridge.Communication/Actors/DebugStreamBridgeActor.cs:118`, `:700`;
`ZB.MOM.WW.ScadaBridge.Communication/SiteAlarmLiveCacheService.cs:133-137`.
**What's wrong.** Both streaming consumers always start on NodeA and flip to NodeB only on a stream *error*. The site-side
`SiteStreamManager` is node-local (an in-process BroadcastHub fed by Instance Actors, which exist only on the active node), and
`SiteStreamGrpcServer` is marked ready on every site node. A subscription to a healthy standby node therefore succeeds: the relay
attaches, response headers are flushed, keepalive pings pass — and no event is ever delivered. Nothing on that path produces an
error, so the consumer never flips. The original design note (`docs/plans/grpc_streams.md`, "Stream Authority") assumed central
would pick the singleton owner's node via ClusterClient state; that selection no longer exists.
Unlike the command plane, there is no singleton proxy in the stream path to hide which node answered.
**Failure scenario.** NodeA of a site crashes, NodeB takes over, NodeA is restarted and rejoins as standby (the steady state after
any failover or NodeA restart).
- *Alarm Summary:* the aggregator connects to NodeA, gets headers, sets `_streamDown = false`, and `IsLive(siteId)` returns true.
`SharedAlarmSummaryService` then skips its poll fan-out and serves the cache, which now changes only on the 60–72 s reconcile
snapshot (up to two intervals when a tick is skipped). Operators see a page that claims to be live while alarm transitions lag by
a minute or more.
- *Debug View:* the snapshot arrives through the command plane (proxied to the active node), then the view never updates. No
error, no termination; the stability timer even resets the retry budget.
**Suggested fix.** Make the site refuse stream subscriptions on a non-active node — throw `Unavailable` from
`RunSubscriptionStreamAsync` when `ActiveNodeEvaluator.SelfIsOldestUp` is false for the site role, and cancel active streams when
the node loses the active role — so the existing error → flip logic lands on the active node. Alternatively pick the starting node
from the heartbeat `IsActive` stamp central already receives.
---
## COMM-3 — Debug stream delivers gap-window events before the initial snapshot reaches the consumer
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed (ordering traced; consumer impact confirmed for the SignalR hub, timing-dependent for the Blazor page)
- **Where:** `ZB.MOM.WW.ScadaBridge.Communication/DebugStreamService.cs:139-151` and `:187`;
`ZB.MOM.WW.ScadaBridge.Communication/Actors/DebugStreamBridgeActor.cs:289-291`.
**What's wrong.** The bridge actor is careful about order: `_onEvent(snapshot)`, then `FlushBuffer(snapshot)`, then pass-through.
But `DebugStreamService` diverts the snapshot into a `TaskCompletionSource` created with `RunContinuationsAsynchronously` and
passes every later event straight to the caller's `onEvent`. The buffered events are flushed synchronously on the actor thread in
the same message handler, so they reach the consumer before `StartStreamAsync`'s continuation has even resumed, let alone before
the caller has applied `session.InitialSnapshot`.
**Failure scenario.** An attribute changes while the snapshot is being built. The stream-first buffer captures it (that is the
buffer's purpose) and it is strictly newer than the snapshot row.
- `DebugStreamHub` sends `OnAttributeChanged` from the actor thread, and only afterwards (`DebugStreamHub.cs:227`) sends
`OnSnapshot`. A client that replaces its state on `OnSnapshot` regresses to the older value and stays wrong until that attribute
changes again. The CLI prints the change above "=== Initial Snapshot ===".
- `DebugView.razor` clears and repopulates `_attributeValues` from the snapshot after the await (`:575-582`); a coalesced flush of
the pending map that ran first is overwritten. The window is small there, but nothing closes it.
**Suggested fix.** Hold post-snapshot events inside `DebugStreamService` until `StartStreamAsync` has returned the snapshot (queue
them in the wrapper and drain after the caller is handed the session), or deliver the snapshot through `onEvent` as the first
callback and let consumers apply it there.
---
## COMM-4 — Site liveness is keyed on the site's own clock, so a fast site clock delays offline detection
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `ZB.MOM.WW.ScadaBridge.Communication/Actors/CentralCommunicationActor.cs:324` (passes `heartbeat.Timestamp`);
`ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthAggregator.cs:152-162` (stores the later of site time and stored time), `:282-283` (compares against central `now`).
**What's wrong.** `MarkHeartbeat` receives the timestamp the *site* stamped with its own `DateTimeOffset.UtcNow` and stores it as
`LastHeartbeatAt`; the offline branch explicitly prefers `receivedAt` when it is ahead of central's clock. `CheckForOfflineSites`
then computes `now - LastHeartbeatAt` with central's clock. A site whose clock runs ahead by X keeps `LastHeartbeatAt` X in the
future, so the 60 s offline timeout becomes 60 s + X.
**Failure scenario.** A site on an OT network without NTP runs 30 minutes fast. Its WAN link drops. Central keeps showing the site
Online for about 31 minutes instead of 1. (A slow site clock is mostly masked, because each accepted health report resets
`LastHeartbeatAt` to central time — but combined with COMM-1, where reports are rejected, a site more than ~55 s slow flaps
offline/online on every heartbeat.)
**Suggested fix.** Stamp heartbeats with central's receive time (`_timeProvider.GetUtcNow()`) in `MarkHeartbeatLocally`/`MarkHeartbeat`
and use the site timestamp only for display or ordering.
---
## COMM-5 — No connect timeout on any gRPC channel: a black-holed node yields DeadlineExceeded, which never triggers failover
- **Severity:** Medium · **Category:** bug · **Confidence:** Plausible (depends on network failure mode and host OS; not reproduced)
- **Where:** `ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs:585-591` and `:325` (failover only on `Unavailable`);
`ZB.MOM.WW.ScadaBridge.Communication/Grpc/CentralChannelProvider.cs:113-119`;
`ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcCentralTransport.cs:239-251`;
`ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcClient.cs:91-96`;
`ZB.MOM.WW.ScadaBridge.Communication/Actors/SiteAlarmAggregatorActor.cs:414-425`.
**What's wrong.** None of the three `SocketsHttpHandler`s sets `ConnectTimeout`. When a peer host is gone in a way that drops SYNs
(powered off behind a router, firewall drop, WAN black hole) rather than refusing them, the connect attempt blocks for the OS TCP
timeout (~21 s on Windows, ~2 min on Linux). Calls whose deadline is shorter end as `DeadlineExceeded`, and both failover paths act
only on `Unavailable` (plus a narrow `Internal` case on the site side). A dead node therefore fails calls without ever flipping the pair.
**Failure scenario.**
- *Central → site, Linux central (both docker rigs):* NodeA's host is black-holed with no established connection. Every command has
a 10–120 s deadline, all below the ~2 min connect timeout, so each returns `DeadlineExceeded` and `SitePairChannelProvider` stays
on NodeA indefinitely while NodeB is healthy. On Windows the 30 s-deadline calls do reach the 21 s socket timeout and flip, but
10 s calls (`DebugViewTimeout`) never do.
- *Site → central:* heartbeat and health report use a 10 s deadline. A quiet site with no audit/notification traffic keeps timing
out against a black-holed central-a and never moves to central-b, so it reads Offline at central.
- *Alarm stream:* the stream has no deadline; the 30 s open-attempt timer only releases `_openInFlight` and does not flip
`_useNodeA`. The next reconcile tick reopens on the same node and bumps the generation, so the eventual connect error from the
cancelled attempt is discarded as stale. On Linux the stream never reaches NodeB.
An already-established connection is covered: the HTTP/2 keepalive tears it down within ~25 s and in-flight calls fail `Unavailable`.
**Suggested fix.** Set `SocketsHttpHandler.ConnectTimeout` (about 5 s) on all three channel builders so a black-holed peer surfaces as
`Unavailable` well inside every call deadline, and treat `GrpcAlarmStreamOpenTimedOut` as a stream error (flip node, count a retry).
---
## COMM-6 — Standby nodes accumulate per-interval error counters and report them as one interval after failover
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `ZB.MOM.WW.ScadaBridge.HealthMonitoring/HealthReportSender.cs:86-87`;
`ZB.MOM.WW.ScadaBridge.HealthMonitoring/CentralHealthReportLoop.cs:100-101`;
`ZB.MOM.WW.ScadaBridge.HealthMonitoring/SiteHealthCollector.cs:283-287`, `:337`.
**What's wrong.** The interval counters (dead letters, script/alarm errors, audit write/redaction failures, shed runs) are reset only
by `CollectReport`, and both report loops `continue` before calling it while the node is standby. Increments still happen on a
standby (`DeadLetterMonitorActor` runs on every node), so they pile up for the node's whole standby life.
**Failure scenario.** A central or site node sits standby for three weeks and logs 4,000 dead letters over that time. On failover
its first report carries `DeadLetterCount = 4000` as the count for one 30 s interval; the Health dashboard and the KPI rate series
(`SiteHealthKpiSampleSource`) show a spike exactly when operators are looking at the failover.
**Suggested fix.** Drain the interval counters on standby ticks (call `CollectReport` and discard, or add a reset method), or reset
them when the node transitions to active.
---
## COMM-7 — `DebugStreamBridgeActor` ignores the transport's fail-fast `Status.Failure` for the snapshot request
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `ZB.MOM.WW.ScadaBridge.Communication/Actors/DebugStreamBridgeActor.cs:609-611` (Tell with `Self` as reply target), `:247-435` (no `Status.Failure` handler);
`ZB.MOM.WW.ScadaBridge.Communication/Grpc/GrpcSiteTransport.cs:84-107`.
**What's wrong.** `GrpcSiteTransport` deliberately completes a failed send with `Status.Failure` to the reply target so callers fail
immediately instead of burning a timeout. For the debug session's `SubscribeDebugViewRequest` the reply target is the bridge actor,
which has no handler for it; the message is unhandled and the session waits for a timeout it could have skipped.
**Failure scenario.** A user opens Debug View for a site with no configured gRPC channel, or whose command plane returns an error
within milliseconds. The page shows "connecting" for the full 30 s `StartStreamAsync` timeout and then reports a generic timeout
instead of the real cause; the actor and its site stream stay up for that whole period.
**Suggested fix.** Add `Receive<Status.Failure>` to the bridge actor that, before the snapshot is delivered, tears down and calls
`_onTerminated` (ideally passing the cause through so the caller's exception names it).
---
## COMM-8 — Failback probes run serially for all sites inside the 1 s sweep loop
- **Severity:** Low · **Category:** perf · **Confidence:** Confirmed
- **Where:** `ZB.MOM.WW.ScadaBridge.Communication/Grpc/SitePairChannelProvider.cs:427-454` (loop), `:619-628` (5 s probe deadline).
**What's wrong.** `FailbackLoopAsync` awaits `TryFailbackAsync` for each due site one after another. Each probe can take its full 5 s
deadline when NodeA is unreachable, and the loop also owns the graveyard sweep.
**Failure scenario.** A WAN event leaves 30 sites failed over to NodeB with NodeA slow or black-holed. One pass takes up to 150 s, so
a site whose NodeA recovered waits minutes rather than its 1–60 s backoff to fail back, and parked channels are not swept in the meantime.
**Suggested fix.** Start due probes concurrently (bounded, e.g. `Task.WhenAll` over a small semaphore) and keep the graveyard sweep
on its own cadence.
## Slice: Code review — `src/ZB.MOM.WW.ScadaBridge.SiteRuntime/` (HEAD d4d5be3b)
Scope read in full: `ScriptExecutionScheduler`, `TriggerEvalGate`, `ScriptRunLauncher`, `ScriptActor`, `AlarmActor`,
`InstanceActor`, `NativeAlarmActor`, `SiteStreamManager`, `SiteScriptCompileCache`, `SharedScriptLibrary`,
`OperationTrackingStore`, `ScriptFileReader`, `ScriptRunSummaryRecorder`, `TriggerExpressionGlobals`.
Read in part: `ScriptRuntimeContext` (core attribute/wait/call paths, ExternalSystem/Database/Notify helpers),
`DeploymentManagerActor` (deploy/redeploy/startup-batch/route paths), `SiteStorageService`, `ScopeAccessors`.
Not reviewed: `DeployedSecretsMirror`, `SecretMirrorStatusReporter`, `SiteReconciliationActor`, `CertStoreActor`,
`AuditingDb*`, `ScriptLogger`/`TraceCapturingLogger`, the artifact-apply and sweep halves of `DeploymentManagerActor`.
Paths below are relative to `src/ZB.MOM.WW.ScadaBridge.SiteRuntime/`.
| ID | Severity | Category | Title |
|---|---|---|---|
| SRT-1 | Medium | bug | Stuck-script watchdog cannot detach a worker once the script has awaited anything |
| SRT-2 | Medium | bug | A failed/timed-out trigger-expression evaluation is coerced to `false` — clears an active alarm and re-fires on recovery |
| SRT-3 | Medium | bug | RateOfChange alarm latches Active forever when the value stops changing |
| SRT-4 | Medium | bug | WhileTrue re-fire timer is never started when the condition is adopted from a seed |
| SRT-5 | Medium | perf | Synchronous SQLite work on Akka dispatcher threads (NativeAlarmActor flush/rehydrate, InstanceActor override load) |
| SRT-6 | Low | bug | `ConnectionQualityChanged(Good)` is never sent by the DCL — the Lever-1 backoff reset is dead code |
| SRT-7 | Low | perf | Expression-triggered children copy the whole attribute snapshot + allocate a timer CTS per evaluation, for every attribute change on the instance |
| SRT-8 | Low | bug | `Notify.Status` asks central first with the full script timeout; the site-local `Forwarding` answer is only a fallback |
| SRT-9 | Low | bug | Script-facing Asks use the full script timeout and ignore the deadline token |
| SRT-10 | Low | bug | Every `OperationCanceledException` out of a script is reported as "timed out after N s" |
| SRT-11 | Low | bug | A static attribute write never refreshes the stored quality/timestamp |
| SRT-12 | Low | bug | Redeploy reset gate covers the override *load* only — native-alarm rehydration and the first override flush still race the clear |
| SRT-13 | Low | bug | Routed script call is capped by a hard-coded 30 s Ask, independent of the script's timeout |
| SRT-14 | Low | perf | `NativeAlarmActor.EnforceCap` sorts the whole mirror on every transition once the cap is reached |
---
## SRT-1 — Stuck-script watchdog cannot detach a worker once the script has awaited anything
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `Scripts/ScriptRunLauncher.cs:288-298` (and `:721-731` for alarm scripts), `Scripts/ScriptExecutionScheduler.cs:275-307, 380-392`
**What's wrong.** The launcher captures `(workerSlot, workerRunStamp)` once, in the first synchronous segment of the
run. `WorkerLoop` assigns a fresh `RunStamp` per dequeued *task* and zeroes it when that task returns. A script's
`await` continuation is a new task queued back onto the scheduler (the script's awaits capture
`TaskScheduler.Current`), so it runs on whichever worker dequeues it, under a new stamp. When the watchdog later calls
`TryDetachWorker(slot, observedRunStamp)` the stamp no longer matches and it returns `NotRunning`.
The launcher comment says a script that hops threads "no longer holds this worker" and "no dedicated thread is lost".
That is true of the *first* worker only; the continuation is holding a different pool worker.
**Failure scenario.** A script does `var x = await Attributes.GetAsync("A");` (a real yield — the Ask reply arrives
asynchronously) and then makes a blocking ADO.NET call on `Database.Connection(...)` that hangs on a dead SQL server.
The timeout fires, the grace elapses, the watchdog logs "STILL EXECUTING — its dedicated script-execution thread is
blocked" but takes the `NotRunning` branch: no detach, no replacement, `DetachedScriptThreads` stays 0. Eight such runs
(`ScriptExecutionThreadCount` default) wedge the pool for every instance on the node. Practically every real script
awaits an attribute read before doing I/O, so detach-and-replace only works for a script that wedges before its first
yielding await.
**Suggested fix.** Track the current holder per run instead of once: have the worker loop publish
`(slot, stamp)` into an `AsyncLocal`/per-run holder each time it starts executing a task belonging to the run (e.g. a
small run-state object flowed via `AsyncLocal` that `WorkerLoop` or a custom awaiter updates), and have the watchdog
read the latest pair. Alternatively scan slots for the one whose current task belongs to the run.
---
## SRT-2 — Failed/timed-out trigger-expression evaluation is coerced to `false`
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `Actors/AlarmActor.cs:646-684, 692-707, 716-723`; `Actors/ScriptActor.cs:431-467, 476-496, 508-514`
**What's wrong.** The off-dispatcher evaluation catches every exception — including the `OperationCanceledException`
from `TriggerEvalTimeoutSeconds` (2 s, armed at enqueue, so gate wait burns it) — and returns `false`. The result is
then applied as a genuine evaluation: `AlarmActor.ApplyTriggeredState(false)` and
`ScriptActor._lastExpressionResult = false`. "Could not evaluate" and "evaluated false" are indistinguishable.
**Failure scenario (alarm).** Expression alarm `Attributes["Temp"] > 90` is Active. A burst saturates
`TriggerEvalGate` (or the thread pool is briefly starved) and one evaluation waits more than 2 s. It returns `false`
→ the alarm transitions Active → Normal, emits a "cleared" site event and an `AlarmStateChanged(Normal)` to central.
The next attribute change evaluates `true` → Normal → Active again: a second "activated" event and a second on-trigger
script run for a condition that never cleared. If no further attribute change arrives, the alarm stays wrongly Normal.
**Failure scenario (script).** Same shape: OnTrue expression script re-fires on the next successful evaluation;
a WhileTrue script has its re-fire timer cancelled and restarted, with an extra edge run.
**Suggested fix.** Return a tri-state (true / false / unknown) from the evaluation task and leave
`_currentState` / `_lastExpressionResult` untouched on unknown; keep the error log and counter. Optionally re-arm one
evaluation so a timed-out result is retried rather than waiting for the next attribute change.
---
## SRT-3 — RateOfChange alarm latches Active when the value stops changing
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `Actors/AlarmActor.cs:576-615` (no timer anywhere in the actor)
**What's wrong.** The rate window is only pruned and re-evaluated inside `EvaluateRateOfChange`, which runs only when
an `AttributeValueChanged` for the monitored attribute arrives. There is no time-based re-evaluation. Tag
subscriptions report on change, so a value that steps and then holds produces no further sample.
**Failure scenario.** `thresholdPerSecond = 10`, `windowSeconds = 1`. The tag goes 0 → 100 within one second: the
alarm raises (rate 100/s). The tag then sits at 100 for hours. No update arrives, the window is never pruned, and the
alarm stays Active indefinitely although the rate has been 0 since the step. It clears only when the value next
changes slowly enough — and that next sample is evaluated against whatever stale entry survives pruning at that time.
**Suggested fix.** When a RateOfChange alarm goes Active (or whenever the window is non-empty), schedule a single-shot
self-message at `oldest.Timestamp + WindowDuration`; on it, prune the window and re-evaluate (fewer than two samples
in the window ⇒ not triggered).
---
## SRT-4 — WhileTrue re-fire timer never started when the condition is adopted from a seed
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed (behaviour); intent arguable
- **Where:** `Actors/ScriptActor.cs:371-385` (seed), `:476-490` (seed-only expression result), `:531-542`; seeds come from `Actors/InstanceActor.cs:2119-2127`
**What's wrong.** Since review item 01/SR-U1, persisted static overrides reach children as `AttributeValueSeed`, which
"adopts the truth value and never fires". For a Conditional trigger the seed sets `_conditionState = true`; for an
Expression trigger the seed-only result sets `_lastExpressionResult = true`. Neither path calls
`StartWhileTrueTimer()`. Every later real change that still satisfies the condition goes through
`HandleWhileTrueTransition(true, wasTrue: true)`, which does nothing.
Not running the script *once* on a seed is the documented intent. Losing the periodic re-fire for the rest of the
actor's life is a side effect of how that was implemented.
**Failure scenario.** A WhileTrue script (`MinTimeBetweenRuns = 30 s`) is conditioned on static attribute
`Mode == 1`. An operator set `Mode = 1` yesterday; it is a persisted override. The site fails over (or the instance is
disabled/enabled, or the node restarts). The new ScriptActor is seeded `true` and never fires again — no edge run, no
30 s re-fire — until `Mode` goes false and back to true. Before the failover the script ran every 30 s.
**Suggested fix.** On a seed that leaves a WhileTrue trigger's state `true`, start the WhileTrue timer without the
immediate edge run (both in `HandleAttributeValueSeed` and in the `SeedOnly` branch of `HandleExpressionEvalResult`).
---
## SRT-5 — Synchronous SQLite work on Akka dispatcher threads
- **Severity:** Medium · **Category:** perf · **Confidence:** Confirmed
- **Where:** `Actors/NativeAlarmActor.cs:624-650` (`FlushDirtyUpserts`), `:134` (`PreStart` rehydration read);
`Actors/InstanceActor.cs:487-488` (override load when no reset gate), `:2094` (normalising re-persist);
storage bodies at `Persistence/SiteStorageService.cs:425-450, 666-732, 738-766`
**What's wrong.** `SiteStorageService` uses Microsoft.Data.Sqlite, whose `*Async` methods run synchronously, and opens
its connection synchronously. InstanceActor's own flush path acknowledges this ("SQLite's async APIs may block
synchronously") and wraps the write in `Task.Run` (`InstanceActor.cs:851`). The sites listed above call the storage
method directly from a `Receive` handler / `PreStart`, so the whole open + transaction + commit runs on the actor's
dispatcher thread.
The file is the consolidated LocalDb database, shared with the S&F buffer, site events, the replication applier and
CDC triggers on `native_alarm_state`. A write that has to wait for the SQLite write lock blocks a default-dispatcher
thread for up to the busy timeout.
**Failure scenario.** An alarm storm on a native source with 500 conditions: each `NativeAlarmActor` flushes a batched
transaction every 100 ms on the dispatcher. At the same moment the replication peer is applying a 2 MB delta batch
(or the daily `site_events` purge is deleting 250 k rows). Each flush blocks a dispatcher thread waiting for the write
lock; with several native-alarm actors flushing at once the shared dispatcher is starved, and the instance actors'
tag-update ingest and cluster heartbeats queue behind it. At failover start-up, each batch of 20 instance actors also
performs its override read and each native-alarm actor its rehydration read synchronously in `PreStart`.
**Suggested fix.** Mirror the InstanceActor pattern: run the storage call in `Task.Run`, chain flushes on a
persist-tail task so batches stay ordered, and `PipeTo(Self)` for the reads.
---
## SRT-6 — `ConnectionQualityChanged(Good)` is never sent; the Lever-1 backoff reset is dead code
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed (dead path); impact Plausible
- **Where:** `Actors/InstanceActor.cs:1430-1437`; sole producer `../ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Actors/DataConnectionActor.cs:2832`
**What's wrong.** `HandleConnectionQualityChanged` resets the tag-subscribe backoff and re-arms at the floor when the
quality is `Good`; the comment calls it "the Instance Actor's only restore signal" and CLAUDE.md documents the reset
"on Success or `ConnectionQualityChanged(Good)`". The only place in the solution that constructs the message is
`PushBadQualityForAllTags`, which always sends `QualityCode.Bad`. The `Good` branch can only be reached from tests.
**Failure scenario.** A gateway is down long enough for an instance's subscribe to fail repeatedly; the interval
backs off to `TagSubscribeRetryMaxIntervalMs` (60 s, ±20 %). The gateway returns. Nothing tells the Instance Actor, so
its next subscribe attempt is up to ~60–72 s away instead of ≤ 5 s, and its attributes stay Bad/Uncertain meanwhile.
**Suggested fix.** Have the DCL connection actor tell subscribers `ConnectionQualityChanged(Good)` when it re-enters
Connected, or drop the branch and the documentation claim. If Good is added, note that the same handler then stamps
every bound attribute `Good` with its last-known value before the device re-reports — restrict the Good case to the
backoff reset.
---
## SRT-7 — Expression-triggered children pay O(attributes) per evaluation for every change on the instance
- **Severity:** Low · **Category:** perf · **Confidence:** Confirmed
- **Where:** `Actors/InstanceActor.cs:1929-1932` (`_allChangeChildren` fan-out); `Actors/ScriptActor.cs:309-312, 424-431`; `Actors/AlarmActor.cs:312-319, 631-646`
**What's wrong.** Every Expression-triggered script and alarm is in the all-changes bucket, so it receives every
attribute change of the instance. Each evaluation start copies the full `_attributeSnapshot` dictionary, allocates a
`CancellationTokenSource` with a timer, and queues a `Task.Run` plus a `PipeTo`. Coalescing limits this to one
evaluation in flight, but under steady updates each child runs back-to-back evaluations, almost all triggered by
attributes the expression never reads.
**Failure scenario.** An instance with 250 data-sourced attributes updating at ~1 Hz and 10 expression alarms:
2 500 mailbox messages/s to the children and, per child, a continuous chain of 250-entry dictionary copies + timer CTS
allocations + Roslyn `RunAsync` state objects. Across a few hundred instances this is a large share of the node's
allocation rate and holds `TriggerEvalGate` permits that real edges then wait for (feeding SRT-2).
**Suggested fix.** At compile time, extract the literal attribute keys the expression indexes (a syntax walk over
`Attributes["…"]` / `Children["…"].Attributes["…"]`), route the child by those names like a monitored-attribute
trigger, and fall back to all-changes only when a key is not a literal. Reuse the snapshot when nothing the expression
reads has changed.
---
## SRT-8 — `Notify.Status` asks central first, with the full script timeout
- **Severity:** Low · **Category:** bug · **Confidence:** Plausible (depends on how fast the site-communication actor fails when central is unreachable)
- **Where:** `Scripts/ScriptRuntimeContext.cs:2801-2848`; `_askTimeout` is the script's execution timeout (`:357`, passed from `ScriptRunLauncher.cs:358`)
**What's wrong.** The documented contract is "answered site-locally as `Forwarding` while still in the site S&F
buffer, otherwise round-trips to central". The code does the reverse: it Asks central with `_askTimeout` and consults
the local buffer only after central answers not-found or the Ask throws. `_askTimeout` equals the script's whole
execution budget, and the Ask takes no cancellation token.
**Failure scenario.** Central is unreachable — exactly when a notification is still in the site buffer. A script calls
`Notify.Status(id)`. If the communication actor does not fail fast, the Ask waits the full 30 s before the local
lookup returns `Forwarding`; by then the script's own deadline (armed at enqueue, so earlier) has passed and the run is
reported as overdue by the stuck-script watchdog.
**Suggested fix.** Check `_storeAndForward.GetMessageByIdAsync` first and return `Forwarding` on a hit; only then ask
central, with a short bounded timeout and the script's deadline token.
---
## SRT-9 — Script-facing Asks use the full script timeout and ignore the deadline token
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `Scripts/ScriptRuntimeContext.cs:731` (`GetAttribute`), `:943` (`SetAttribute`), `:1220` (`CallScript`); contrast `:847-848` and `:1151-1152`, which pass `_scriptTimeoutToken`
**What's wrong.** These Asks are bounded by `_askTimeout` (= the run's full execution timeout, measured from the
call, not from enqueue) and are not linked to `_scriptTimeoutToken`. Roslyn only observes the run's token between
top-level statements, so a run parked in one of these awaits sails past its deadline.
**Failure scenario.** Script A (timeout 30 s) spends 20 s working, then `await Instance.CallScript("B")`; B takes
25 s. A's deadline passes at 30 s but A keeps waiting until 45 s, then carries on executing its remaining statements
(writes, external calls) and is recorded as **completed**. In between, the watchdog logs "exceeded its 30s timeout and
is STILL EXECUTING — its dedicated script-execution thread is blocked", which is false (no thread is held). The same
applies to a `SetAttribute` on a data-sourced tag waiting out the 30 s DCL write Ask.
**Suggested fix.** Pass `_scriptTimeoutToken` to all three Asks (as `WaitInternal` already does) so the deadline
cancels the await and the run takes the timeout path.
---
## SRT-10 — Every `OperationCanceledException` out of a script is reported as a timeout
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `Scripts/ScriptRunLauncher.cs:483-511` (instance scripts), `:805-813` (alarm scripts)
**What's wrong.** `catch (OperationCanceledException)` does not check `cts.IsCancellationRequested`. Any
cancellation that originates elsewhere — a `TaskCanceledException` from an HTTP client's own timeout, a script's own
`CancellationTokenSource`, a cancelled file read — is logged and replied as "timed out after {timeout}s", counted by
`RecordTimedOut`, and (by design D3) carries no `errorDetail`.
**Failure scenario.** A script with a 60 s timeout makes a call that cancels internally after 5 s. The Flow Debugger
node, the site event and the `ScriptCallResult` all say "timed out after 60s" for a 5-second run, with the real
exception and stack discarded. The interval summary's timed-out count is inflated.
**Suggested fix.** `catch (OperationCanceledException) when (cts.IsCancellationRequested)`; let other cancellations
fall through to the general failure path with the full exception.
---
## SRT-11 — A static attribute write never refreshes the stored quality/timestamp
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `Actors/InstanceActor.cs:725-800` (`ApplySetStaticAttributeCore`); quality set to `Bad` at `:360-362` and `:2082-2085`
**What's wrong.** The method updates `_attributes[name]` and publishes an `AttributeValueChanged` with quality
`"Good"`, but never writes `_attributeQualities[name]` or `_attributeTimestamps[name]`. A static List attribute whose
config default or persisted override failed to decode is stored with quality `Bad`; a later valid write fixes the
value but the stored quality stays `Bad` for the actor's lifetime.
**Failure scenario.** A List attribute loads a malformed override → `Bad`. A script writes a valid list. Subscribers
see `Good` on the stream, but `GetAttribute` replies `Bad`, the Debug View snapshot shows `Bad`, and
`Attributes.WaitAsync(name, target, timeout, requireGoodQuality: true)` can never fast-path match on the current value
(it only resolves if a later publish happens to carry `Good`). Separately, static attributes have no stored timestamp,
so each snapshot stamps them with "now".
**Suggested fix.** Set `_attributeQualities[name] = "Good"` and `_attributeTimestamps[name] = now` alongside the value
assignment.
---
## SRT-12 — Redeploy reset gate covers the override load only
- **Severity:** Low · **Category:** bug · **Confidence:** Plausible (timing-dependent)
- **Where:** `Actors/DeploymentManagerActor.cs:1542-1546` (gate), `Actors/InstanceActor.cs:487-491` (the only consumer),
`Actors/InstanceActor.cs:2300-2309` + `Actors/NativeAlarmActor.cs:134` (ungated rehydration),
`Actors/InstanceActor.cs:142, 850-857` (persist tail starts at `Task.CompletedTask`)
**What's wrong.** `staticStateResetGate` (clear overrides, then clear native alarms) was introduced so the successor
can only observe the cleared tables, but only `GetStaticOverridesAsync` is chained behind it. Two sibling paths have
the same race the gate's own comment describes:
1. `NativeAlarmActor` is created without a `rehydrationRead`, so its `PreStart` reads `native_alarm_state` directly.
The native-alarm clear is the *second* statement of the gate task, so the read can land first.
2. The new actor's first static-override flush is not chained behind the gate. `ClearStaticOverridesAsync` runs on its
own connection with no ordering against other writers.
**Failure scenario.** (1) Redeploy an instance whose native source binding changed: the new actor rehydrates the
predecessor's conditions and emits them to the instance/central. If the source is unreachable no snapshot arrives to
reconcile them, so stale alarms from the old binding stay displayed. (2) During a bulk deploy with several large
config writes contending for the SQLite write lock, a value-change script on the new instance writes a static
attribute within the first ~100 ms; its flush commits before the delayed clear, which then deletes it. Memory holds
the value, disk does not, and the next restart silently reverts it.
**Suggested fix.** Pass the gate-chained read into `NativeAlarmActor` via the existing `rehydrationRead` parameter,
and initialise `_staticOverridePersistTail` to the gate (ignoring its fault) so the first flush is ordered after the
clear.
---
## SRT-13 — Routed script call capped by a hard-coded 30 s Ask
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `Actors/DeploymentManagerActor.cs:3426`
**What's wrong.** `RouteInboundApiCall` Asks the instance with `TimeSpan.FromSeconds(30)` regardless of the target
script's `ExecutionTimeoutSeconds` or of central's configurable `Communication:IntegrationTimeout`. The script keeps
running after the Ask gives up.
**Failure scenario.** A handshake script has a per-script timeout of 120 s and central's `IntegrationTimeout` is
raised to match. The inbound call still fails at 30 s with an Ask-timeout message while the script runs on and
completes its device writes; the caller retries and the handshake runs twice. A Flow Debugger live run of the same
script loses its inline trace the same way.
**Suggested fix.** Derive the Ask timeout from the target script's resolved timeout (plus a margin), or carry the
caller's remaining deadline on `RouteToCallRequest`.
---
## SRT-14 — `NativeAlarmActor.EnforceCap` sorts the whole mirror per transition at the cap
- **Severity:** Low · **Category:** perf · **Confidence:** Confirmed
- **Where:** `Actors/NativeAlarmActor.cs:422-462`, called from `:378`
**What's wrong.** Once `_alarms.Count` reaches `MirroredAlarmCapPerSource` (1000), every new condition takes the count
to cap+1 and `EnforceCap` does `OrderBy(TransitionTime)` over all entries to evict one, then logs a Warning.
**Failure scenario.** A source in a sustained alarm flood past 1000 open conditions: each new condition costs an
O(n log n) sort of ~1000 records plus a Warning log line and a parent notification, on the actor thread, for the
duration of the flood.
**Suggested fix.** Evict in a batch (e.g. down to 90 % of the cap) so the sort amortises, and rate-limit the Warning.
## Slice: Review slice 03 — Commons + ScriptAnalysis (HEAD d4d5be3b)
Scope: `src/ZB.MOM.WW.ScadaBridge.Commons/`, `src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/` (hand-written code only).
12 findings: 1 High, 2 Medium, 9 Low.
Verification note: CMN-1..CMN-4 were confirmed by compiling a small probe out-of-tree against the
prebuilt DLLs in `tests/ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests/bin/Debug/net10.0` (nothing in the
repo was built or modified). Those DLLs may predate HEAD, but the HEAD source matches the observed
behaviour. Other findings are from reading the code and its callers.
---
## CMN-1 — Conditional member access (`?.`) is not inspected by the reflection-gateway walker
- **Severity:** High
- **Category:** bug (script trust-policy bypass)
- **Confidence:** Confirmed (probe returned 0 violations / 0 compile errors)
- **Where:** `ScriptAnalysis/ScriptTrustValidator.cs:382` (`HardeningWalker.VisitMemberAccessExpression`), node filter at `:157`; `ScriptAnalysis/ScriptTrustPolicy.cs:86` (`ReflectionGatewayMembers`)
**What's wrong.** Pass 2's gateway-member check (`GetType`, `GetMethod`, `Assembly`, `InvokeMember`, …) fires only inside `VisitMemberAccessExpression`. A conditional access such as `recv?.GetMethod(...)` parses as `ConditionalAccessExpressionSyntax` with a `MemberBindingExpressionSyntax` child, and there is no override for either, so the gateway name on the right of `?.` is never tested. Pass 1 (semantic) sees the member name but resolves it to `System.Type.GetMethod` / `System.Reflection.MethodInfo`; `System.Type` is not a forbidden scope, and the `MethodInfo` result can be converted to a delegate via `System.Delegate.CreateDelegate`, which is itself neither a forbidden scope nor a listed gateway member. The forbidden-API type name (e.g. a file API) only appears as a string literal, which the validator never inspects.
**Failure scenario.** A script that uses `?.`-chained reflection plus `Delegate.CreateDelegate` to obtain and invoke a method on a forbidden type passes `FindViolations` with an empty list and compiles clean (only CoreLib is needed). The byte-identical script written with `.` instead of `?.` is rejected. All four trust call sites (Template Engine deploy gate, Site Runtime, Inbound API, Central UI) delegate here, so the gate is defeated fleet-wide by one character.
**Suggested fix.** Add a `VisitMemberBindingExpression` override that applies the same `ReflectionGatewayMembers` check to its `Name`; alternatively check gateway names on every `SimpleNameSyntax` regardless of receiver form. Also treat `CreateDelegate` as a gateway member (or forbid `System.Delegate`/`System.Reflection.MethodInfo` conversions). Add regression tests covering the `?.` member-binding form.
---
## CMN-2 — `System.AppDomain` assembly-loading members are not on the deny-list
- **Severity:** Medium
- **Category:** bug (script trust-policy gap)
- **Confidence:** Confirmed that validator + compile gate pass such references (probe); runtime effect is standard documented `AppDomain` behaviour
- **Where:** `ScriptAnalysis/ScriptTrustPolicy.cs:36` (`ForbiddenScopes`), `:86` (`ReflectionGatewayMembers`)
**What's wrong.** `System.Runtime.Loader` and `System.Reflection` are forbidden, but `System.AppDomain` (in namespace `System`, CoreLib) is not, and its assembly-loading members (`ExecuteAssembly`, `ExecuteAssemblyByName`, `Load`, `CreateInstanceFrom`, `CreateInstanceFromAndUnwrap`, `CreateInstanceAndUnwrap`) are not in the exact-match gateway set — note `CreateInstance` is listed but does not cover `CreateInstanceFromAndUnwrap`. A reference to `AppDomain.CurrentDomain.ExecuteAssembly(path)` produced 0 violations and 0 compile errors in the probe.
**Failure scenario.** A script references an `AppDomain` assembly-load member with a path (a UNC path on a Windows node needs no local write) to pull in and run external code inside the host process — outside the intended trust boundary, with no validator or compile-gate objection.
**Suggested fix.** Add `System.AppDomain` to `ForbiddenScopes` (consistent with the existing whole-type bans on `System.Environment` and `System.GC`). Consider also `System.AppContext` and `System.Diagnostics.Debugger`.
---
## CMN-3 — `AttributeValueCodec.Encode` throws on non-finite floats/doubles in a List
- **Severity:** Medium
- **Category:** bug (serialization / round-trip)
- **Confidence:** Confirmed (probe: `ArgumentException` from `JsonSerializer.Serialize`)
- **Where:** `Commons/Types/AttributeValueCodec.cs:33` (the `IEnumerable` branch of `Encode`)
**What's wrong.** `Encode` serializes a list via `JsonSerializer.Serialize<object>(e, JsonOpts)` with default options, which throws `ArgumentException` for `double.NaN`, `PositiveInfinity`, `NegativeInfinity` (and the `float` equivalents). Scalars take the `IFormattable` branch at `:28`, which formats NaN/∞ to a string fine — so only List attributes are affected, and only for NaN/∞ elements. `Encode` is on hot paths that are not all guarded: `StreamRelayActor.HandleAttributeValueChanged` (`Communication/Actors/StreamRelayActor.cs:48`) encodes the value while projecting an `AttributeValueChanged` to the gRPC wire, and `InstanceActor` uses it for change detection and re-persist (`SiteRuntime/Actors/InstanceActor.cs:2088,2110`).
**Failure scenario.** A device or script produces a List<double> attribute containing NaN or Infinity (an OPC UA bad-scaled analog, a divide-by-zero in a computation). When the Instance Actor publishes that change, `StreamRelayActor` calls `Encode`, which throws; the exception propagates on the relay/actor path rather than being delivered as a value, dropping the update (and, in the InstanceActor change-detection path, potentially tripping supervision).
**Suggested fix.** Configure the shared `JsonOpts` with `NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals` (and mirror it in `Decode`'s deserialize so the round trip reads back), or coerce non-finite elements to a defined sentinel before serialization. Ensure the chosen handling round-trips through `Decode`.
---
## CMN-4 — Scalar DateTime encodes with no time zone / sub-second precision, breaking round-trip
- **Severity:** Low
- **Category:** bug (serialization / round-trip, culture/UTC)
- **Confidence:** Confirmed (probe)
- **Where:** `Commons/Types/AttributeValueCodec.cs:28` (scalar `IFormattable` branch) vs `:33` (list branch) and `:132`/`:153` (`Decode` parses with `RoundtripKind`)
**What's wrong.** A scalar `DateTime` hits the `IFormattable` branch and encodes as `f.ToString(null, InvariantCulture)` → `"06/15/2026 13:45:30"` (invariant general format: no offset, milliseconds truncated). A `DateTime` *inside a List* takes the JSON branch and encodes as ISO-8601 round-trip `"2026-06-15T13:45:30.123Z"`. So the same value has two encodings depending on cardinality, and the scalar form loses the Kind and the fractional second. `Decode` for lists parses with `DateTimeStyles.RoundtripKind`, which reads the ISO form correctly but would misread (or fail) the general form. The codec is documented as "canonical, round-trippable".
**Failure scenario.** A DateTime scalar attribute written at `13:45:30.123Z` reads back as `13:45:30` with `Kind=Unspecified`; comparisons/handshakes keyed on the encoded string (e.g. `WaitAttribute` equality via `Encode`, `ScopeAccessors`) can mismatch between the written target and the stored value for a sub-second or Kind-sensitive value.
**Suggested fix.** In `Encode`, special-case `DateTime`/`DateTimeOffset` to format with the ISO-8601 round-trip pattern (`"O"`) so scalar and list encodings agree and preserve offset + sub-second precision.
---
## CMN-5 — `TrustVerdictCache` keys on the raw code only; a call with `extraReferences` can get a wrong cached verdict, and the cache never reflects degraded mode
- **Severity:** Low
- **Category:** bug (caching)
- **Confidence:** Plausible
- **Where:** `ScriptAnalysis/TrustVerdictCache.cs:47` (key = SHA-256 of code only); `ScriptAnalysis/ScriptTrustValidator.cs:82-89` (only the no-extra-refs path is memoised)
**What's wrong.** The memoised path is correctly restricted to calls with no `extraReferences`, so the cross-contamination between extra-ref and no-extra-ref calls is avoided — good. The residual issue is narrower: the cache key is the code hash alone and the entry lives for the process lifetime, while the verdict also depends on `ScriptTrustPolicy.AnalysisReferences`, which is built once at type-init and can be in the *degraded* fallback mode (`AnalysisReferencesDegraded`, `ScriptTrustPolicy.cs:239`). That is process-static too, so it is not a correctness bug today; but any future change that lets the reference set vary (e.g. lazy TPA discovery, or a test toggling degraded mode) would be silently served stale verdicts with no key component to distinguish them.
**Suggested fix.** Fold a cheap policy/reference generation token (or an `AnalysisReferencesDegraded` flag) into the cache key, so the memo is self-invalidating if the resolution surface ever changes. Low priority while both inputs are immutable.
---
## CMN-6 — `FlowGraphBuilder.Fold` picks lifecycle terminal row by max OccurredAtUtc across mixed node clocks
- **Severity:** Low
- **Category:** bug (flow-graph builder logic)
- **Confidence:** Plausible
- **Where:** `Commons/Types/Debugging/FlowGraphBuilder.cs:449-463` (`Fold` orders lifecycle rows by `OccurredAtUtc`, takes `rows[^1]` as `latest`)
**What's wrong.** `Fold` groups outbound rows by `(kind, CorrelationId)` and orders them `OrderBy(OccurredAtUtc).ThenBy(LifecycleRank).ThenBy(EventId)`, then treats `rows[^1]` as the terminal state (Outcome/Subtitle/duration). Lifecycle rows of one cached operation can be written on different nodes (submit on the site, deliver/resolve centrally) whose clocks are documented to skew by 1–2 s (the same skew that motivated the input-index ordering elsewhere in this file, F5 at `:36`). When the clocks disagree, time ordering can place `Submitted`/`Forwarded` *after* `Delivered`, so `latest` is a non-terminal row and the folded node shows `Pending` (and a negative/zero duration) for an operation that actually completed.
**Failure scenario.** A cached call delivered centrally ~1 s before its site submit row's clock reads; the Flow Debugger node renders Pending forever (until a refresh re-reads rows that happen to sort correctly), and `terminal`/`duration` computation at `:456-463` is wrong.
**Suggested fix.** Order lifecycle rows by `LifecycleRank` first (status progression) and use time only as a tiebreaker, or compute `latest` as the row with the maximum `LifecycleRank`; clamp duration to ≥ 0 (already done) but derive it from the ranked terminal row.
---
## CMN-7 — `InboundApiSchema` legacy-array field names are case-sensitive against the required set; object `required` is `StringComparer.Ordinal`
- **Severity:** Low
- **Category:** bug (validation correctness)
- **Confidence:** Plausible
- **Where:** `Commons/Types/InboundApi/InboundApiSchema.cs:97` (`requiredSet` uses `StringComparer.Ordinal`), `:121` (`requiredSet.Contains(prop.Name)`), `:380` (`declared` uses `StringComparer.Ordinal`); validation `TryGetProperty` at `:392` is also ordinal
**What's wrong.** For object schemas, `required` membership and the undeclared-field check compare property names with `StringComparer.Ordinal`, and validation looks up supplied values with `JsonElement.TryGetProperty` (ordinal). JSON object keys are case-sensitive by spec, so this is internally consistent — but the legacy flat-array path (`ParseLegacyArray`, `:211`) deliberately reads *schema* field metadata case-insensitively (`TryGetMember`), creating an inconsistency: a legacy-authored schema tolerant of case produces fields that are then matched case-sensitively against the request body. A field declared `WorkOrders` but sent as `workorders` is reported both as "missing required field" and "not a declared field".
**Failure scenario.** A method migrated from the legacy array shape whose clients send a differently-cased key gets a confusing double error and is rejected, where the legacy engine may have accepted it.
**Suggested fix.** Decide one casing policy for request-body field matching and apply it uniformly (JSON is conventionally case-sensitive, so ordinal is defensible — then document it and drop the case-insensitive legacy schema read, or make both case-insensitive). At minimum avoid emitting both "missing required" and "undeclared" for the same case-mismatched field.
---
## CMN-8 — `ParseLegacyArray` unknown `type` strings pass through unchanged, later rejected as "unknown declared type"
- **Severity:** Low
- **Category:** bug (validation)
- **Confidence:** Plausible
- **Where:** `Commons/Types/InboundApi/InboundApiSchema.cs:281` (`NormalizeType` default arm `var other => other`), consumed at `:358` (validation default arm "unknown declared type")
**What's wrong.** `NormalizeType` passes an unrecognised type token through verbatim (`var other => other`). A schema with a typo'd type (`"strign"`) parses successfully, and the error only surfaces at validation time as "value has unknown declared type 'strign'" on every request — never at save/parse time. For nested/array element types the same applies.
**Failure scenario.** A method is saved with a mistyped parameter type; parse succeeds, deploy succeeds, and every inbound call fails at runtime with a type error rather than the author being told at edit time.
**Suggested fix.** Either validate the type token at `ParseSchema`/`ParseLegacyArray` time (reject unknown types during parse), or map unknown to `"string"` deliberately with a recorded warning. Prefer failing at authoring time.
---
## CMN-9 — `OverrideCsvParser` / `NativeAlarmSourceOverrideCsvParser` reject the trailing blank line only because it is blank; a stray trailing comma is a hard error
- **Severity:** Low
- **Category:** bug (parsing robustness)
- **Confidence:** Plausible
- **Where:** `Commons/Types/OverrideCsvParser.cs:52` (strict `fields.Count != expectedColumns`), `Commons/Types/NativeAlarmSourceOverrideCsvParser.cs:48`
**What's wrong.** Both parsers require an exact column count per row. A file exported by a spreadsheet with a trailing delimiter (or an extra empty column) on data rows yields `fields.Count = expected + 1` and the row is rejected line-by-line, even though every meaningful field is present and blank-trailing. Fully blank lines are skipped, but a line that is just `name,value,` is not blank and errors.
**Failure scenario.** An operator pastes CSV from Excel where a column was deleted leaving trailing commas; every data row errors with "expected N columns but found N+1" and the bulk override import fails wholesale.
**Suggested fix.** Trim a single trailing empty field before the count check (common CSV leniency), or accept `expected` or `expected+1` when the extra field is empty. Keep strictness for genuinely wrong counts.
---
## CMN-10 — `DynamicJsonElement.TryConvert` reports failure for a JSON-null scalar conversion, surfacing a binder error instead of null
- **Severity:** Low
- **Category:** bug (script-facing correctness)
- **Confidence:** Plausible
- **Where:** `Commons/Types/DynamicJsonElement.cs:70-84` (`TryConvert`), `:100-110` (`ConvertTo` returns null for any unhandled pair)
**What's wrong.** `TryConvert` returns `result != null` as its success flag for non-`object` targets. `ConvertTo` returns `null` both when the element is JSON null *and* when the type/element pair is unsupported — the two are indistinguishable. So `(int?)result.Response.maybeNull` or `(string)result.Response.nullField` binds to failure (a `RuntimeBinderException`) rather than yielding `null`, even though a JSON null is a legitimate value a script should be able to read as null. (The `typeof(object)` branch handles null correctly; only the typed-target path is affected.)
**Failure scenario.** A site/inbound script reads an external API response field that is JSON null and assigns it to a nullable/reference-typed local; instead of `null`, the dynamic bind throws, failing the run.
**Suggested fix.** In `TryConvert`, when `_element.ValueKind == JsonValueKind.Null`, set `result = null` and return `true` for reference/nullable targets (and return a sensible result or genuine failure for non-nullable value types).
---
## CMN-11 — `FlowShapePredictor.AddNode` does an O(n) linear scan per node to find the previous node's lane
- **Severity:** Low
- **Category:** perf
- **Confidence:** Confirmed (code reading)
- **Where:** `ScriptAnalysis/FlowShapePredictor.cs:188` (`_nodes.First(n => n.Id == _previous)`), also `Annotate` at `:108` (`FindIndex`) and `Reset` at `:117`
**What's wrong.** Every `AddNode` call linearly scans `_nodes` to look up the previous node by id to compute the cross-boundary flag. This is O(n²) in the number of predicted nodes. Node ids are `"n" + (_nodes.Count + 1)`, i.e. append-only, so the previous node is almost always `_nodes[^1]`.
**Failure scenario.** A deeply nested method/script prediction (bounded by `maxDepth`, but each level can emit many nodes) does quadratic work on the Blazor renderer thread. Not catastrophic at current depth caps, but needless.
**Suggested fix.** Track the previous node's `FlowLane` alongside `_previous` (or just read `_nodes[^1]` when `_previous` is the last-added id), eliminating the scan. `Annotate`/`Reset` similarly could use the known index.
---
## CMN-12 — `AuditRowProjection.ParseEnum` is case-sensitive while `Decompose` feeds it enum `.ToString()` values — fine today, fragile as a round-trip contract
- **Severity:** Low
- **Category:** bug (round-trip robustness)
- **Confidence:** Plausible
- **Where:** `Commons/Types/Audit/AuditRowProjection.cs:129` (`ParseEnum` with `ignoreCase: false`), used at `:38-40`; contrast `AuditQueryParamParsers.ParseEnumList` at `:16` which uses `ignoreCase: true`
**What's wrong.** `Decompose` parses `AuditDetails.Channel/Kind/Status` (persisted strings) with `Enum.TryParse(..., ignoreCase: false, ...)` and silently falls back to `ApiInbound`/`InboundRequest`/`Submitted` on any miss. The strings are written by `ToString()` so casing matches today. But a mis-cased or legacy value (manual DB edit, an older build that wrote a differently-cased token, a renamed enum member) is silently mapped to the *default* channel/kind/status rather than surfaced — a decomposed audit row can be mislabelled as an inbound request. The sibling parser in `AuditQueryParamParsers` uses `ignoreCase: true`, so the two disagree.
**Failure scenario.** A row whose stored `Channel` is `"apiinbound"` (or a value from a renamed enum) decomposes as the wrong channel with no error, corrupting an archive/reconciliation projection.
**Suggested fix.** Use `ignoreCase: true` in `ParseEnum` to match the query parser, and log/flag (rather than silently defaulting) when a stored token does not parse, so corrupt/legacy rows are visible rather than silently reclassified.
## Slice: Code review 04 — CentralUI + CentralUI.SandboxWorker
Scope: `src/ZB.MOM.WW.ScadaBridge.CentralUI/`, `src/ZB.MOM.WW.ScadaBridge.CentralUI.SandboxWorker/` at HEAD `d4d5be3b`.
Method: read-only code reading (nothing built or run). "Confirmed" means the code path was read end to end, including the repository / service it calls; it does not mean the failure was reproduced live.
Paths below are relative to `src/ZB.MOM.WW.ScadaBridge.CentralUI/` unless they start with another project name.
| ID | Severity | Category | Title |
|----|----------|----------|-------|
| UI-1 | High | bug | Circuit-lifetime DbContext serves stale tracked entities after changes made in another scope |
| UI-2 | Medium | bug | Deployments page runs overlapping queries on the one circuit-scoped DbContext |
| UI-3 | Medium | bug | Sites page runs artifact deploys on the circuit-scoped DbContext |
| UI-4 | Medium | bug | Timers / singleton subscriptions created after an `await` leak when the component is disposed mid-load |
| UI-5 | Medium | bug | Audit Log grid ignores site scope; execution-tree scope compares the wrong id space |
| UI-6 | Medium | perf | Instance "Save overrides" rewrites every override, one transaction and one audit row each |
| UI-7 | Medium | bug | Notification / Site Calls reports filter by site scope after server paging |
| UI-8 | Low | bug | Topology actions share the circuit DbContext with the live tick and with each other |
| UI-9 | Low | bug | Secured Writes history pages over all statuses, then filters client-side |
| UI-10 | Low | bug | Notification KPIs page shows every site's breakdown to a site-scoped Deployer |
| UI-11 | Low | bug | Retry/Discard refused for everyone when the row's source site no longer resolves |
| UI-12 | Low | perf | Per-row authorization re-checks and repeated site queries in polls and bulk loops |
| UI-13 | Low | perf | Every Test Run cold-starts a `dotnet` worker inside the 5 s default deadline |
---
## UI-1 — Circuit-lifetime DbContext serves stale tracked entities after changes made in another scope
- **Severity:** High — **Category:** bug — **Confidence:** Confirmed (code path; EF identity-resolution semantics)
- **Where:**
- `Components/Pages/Design/DataConnections.razor:305` (`LoadDataAsync`), `:438` (`OpenMoveDialog`); `Services/DataConnectionMoveService.cs` (Ask to `ManagementActor`, own DI scope)
- `Components/Pages/Deployment/Topology.razor` `LoadDeployedStateAsync` (sites + areas re-read every 15 s)
- `Components/Pages/Design/TemplateEdit.razor:127` (`LoadAsync`), `:1677` (`SaveScriptDraftAsync`)
- Repositories returning tracked entities: `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteRepository.cs:50,94` (`GetAllSitesAsync`, `GetAllDataConnectionsAsync`), `TemplateEngineRepository.cs:304,421,767` (`GetAttributesByTemplateIdAsync`, `GetScriptsByTemplateIdAsync`, `GetAreasBySiteIdAsync`)
**What's wrong.** `ScadaBridgeDbContext` is scoped, so in Blazor Server one instance lives for the whole circuit (hours, across page navigations). Most repository reads the pages use are tracking queries, and no `QueryTrackingBehavior.NoTracking` default is configured anywhere. When a tracking query returns a row whose key is already tracked, EF hands back the existing instance and does not overwrite its property values. So once a circuit has loaded an entity, every later "reload" returns the values from the first load unless the change was made through that same context. The only reset is `IConfigurationReadSession.Reset()` (`ChangeTracker.Clear()`), which is called solely from `ConfigurationCommandService` after that circuit's own commands. Changes made by any other scope — the `ManagementActorHolder` Ask services, another user, the CLI, a Transport import — are never seen.
**Failure scenarios.**
1. *Deterministic, single user:* on Design → Data Connections, use **Move to Site…** on a connection. `DataConnectionMoveService` moves it through `ManagementActor` (separate scope, no `Reset`). The dialog closes, the toast says "moved", `LoadDataAsync` re-queries — and the tree still shows the connection under its old site, because the tracked `DataConnection` keeps its old `SiteId`. It stays wrong for the rest of the circuit (navigating away and back does not help); a second Move offers targets computed from the stale site.
2. *Topology live updates:* user B renames or re-parents an area. User A's open Topology page refreshes every 15 s but the tracked `Area` rows keep the old `Name` / `ParentAreaId`, so the "live" tree never reflects it; the manual Refresh button has the same result. (Instances are read `AsNoTracking`, so their state does update.)
3. *Silent revert:* designer A has visited template T earlier in the session. A Transport import or the CLI then updates script S on T. A navigates back to T: `GetScriptsByTemplateIdAsync` returns the stale tracked S, the script dialog opens with the old code, A makes a small edit and saves — `TemplateService.UpdateScriptAsync` writes the old body plus A's edit, discarding the imported change with no warning. This goes beyond the documented last-write-wins: A never had a chance to see the newer version even after reloading the page.
**Suggested fix.** Make the UI read paths non-tracking: either `AsNoTracking()` on the list/read repository methods the pages use, or register the circuit's context with `UseQueryTrackingBehavior(NoTracking)` and opt in to tracking only inside the services that mutate. As a narrower stop-gap, call `IConfigurationReadSession.Reset()` at the top of each page-level `LoadAsync` / `LoadDataAsync` and after every `ManagementActorHolder`-based command.
---
## UI-2 — Deployments page runs overlapping queries on the one circuit-scoped DbContext
- **Severity:** Medium — **Category:** bug — **Confidence:** Confirmed (code path); frequency Plausible
- **Where:** `Components/Pages/Deployment/Deployments.razor` — `LoadDataAsync` (the method carrying the `_requestGeneration` guard), callers `DispatchReloadAsync`, `DispatchFilterReloadAsync`, `GoToPageAsync`, `SetStatusFilterAsync`, `SetSearchContainsAsync`, `ClearFiltersAsync`; repository `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs:122`
**What's wrong.** The page comment states that three independent initiators (push reload, search debounce, page/tile click) can each have a `LoadDataAsync` flight in the air at once, and adds a generation counter so the stale one's *results* are discarded. But every flight awaits `QueryDeploymentListPageAsync` + `GetDeploymentStatusCountsAsync` on the injected `IDeploymentManagerRepository`, which wraps the single circuit-scoped `ScadaBridgeDbContext`. EF Core does not allow a second operation on a context while one is in flight; the later entrant throws `InvalidOperationException` ("A second operation was started on this context instance…"). The later entrant is by definition the newest generation, so its `catch` sets `_errorMessage`, while the older flight's good results are thrown away by the generation check.
**Failure scenario.** A site-wide deploy is running, so status pushes trigger a reload every 500 ms. The operator clicks page 2 (or a status tile) while a push reload is mid-query. `GoToPageAsync` has already set `_currentPage = 2`; its flight throws; the page shows "Failed to load deployments: A second operation was started on this context instance…", the grid keeps page 1's rows and the pager reads page 2. The same happens if a push lands during the operator's own query.
**Suggested fix.** Read through a fresh DI scope per flight (the pattern `AuditLogQueryService` / `KpiHistoryQueryService` already use for exactly this reason), or serialize flights with a `SemaphoreSlim` and keep the generation guard for result ordering.
---
## UI-3 — Sites page runs artifact deploys on the circuit-scoped DbContext
- **Severity:** Medium — **Category:** bug — **Confidence:** Confirmed (code path); Plausible in frequency
- **Where:** `Components/Pages/Admin/Sites.razor:310` (`DeployArtifacts`), `:345` (`DeployArtifactsToAllSites`), injected `ArtifactDeploymentService`; `ZB.MOM.WW.ScadaBridge.DeploymentManager/ArtifactDeploymentService.cs:543-600, 825-845` (record save, audit rows, revision stamp all after the site fan-out)
**What's wrong.** Both deploy buttons call the circuit-scoped `ArtifactDeploymentService`, whose repositories and audit service share the circuit's DbContext. The site fan-out can take a long time (per-site timeouts when a site is unreachable), and everything that makes the deploy visible afterwards — the `SystemArtifactDeploymentRecord`, the `DeployArtifacts` / `DeploySiteSecrets` audit rows, and the `Site.ArtifactRevisionHash` stamp — is written *after* the fan-out on that same context. Topology's **Deploy all** already avoids this, with the comment "a deploy must not die with the circuit's scope"; the Sites page was not given the same treatment.
**Failure scenarios.**
1. The administrator clicks **Deploy artifacts to all sites** and closes the tab (or the connection drops and the circuit is evicted) while one site is slow. The circuit scope is disposed; when the fan-out finishes, `AddSystemArtifactDeploymentAsync` / `SaveChangesAsync` throw `ObjectDisposedException`. Sites have received the artifacts (and secrets), but there is no deployment record, no audit row, and no revision stamp — every site keeps reading "Out of date".
2. The administrator navigates to another page in the same circuit during the deploy. The new page's queries and the deploy's post-fan-out writes now share one context: either side can hit the "second operation" exception, and any `ConfigurationCommandService` call on the new page runs `ChangeTracker.Clear()`, detaching the `Site` entities the deploy is about to stamp so the stamp save silently writes nothing.
**Suggested fix.** Resolve `ArtifactDeploymentService` from a dedicated `IServiceScopeFactory` scope inside `DeployArtifacts` / `DeployArtifactsToAllSites` (as `Topology.DeployAll` does), so the deploy owns its context and outlives the page.
---
## UI-4 — Timers / singleton subscriptions created after an `await` leak when the component is disposed mid-load
- **Severity:** Medium — **Category:** bug — **Confidence:** Confirmed (code path)
- **Where:**
- `Components/Pages/Monitoring/Health.razor:770` — `_refreshTimer` created at the end of `OnInitializedAsync`, after `GetAllSitesAsync`, `RefreshAllAsync` (tiles wait up to 5 s each) and `LoadSiteHealthTrendsAsync` (five queries)
- `Components/Pages/Design/DataConnections.razor:250` — `_healthTimer` created after two awaited loads
- `Components/Pages/Deployment/Deployments.razor:346` — `DeploymentStatusNotifier.StatusChanged +=` after `await LoadDataAsync()`
- `Components/Health/PendingUpdatesHealthTiles.razor:90` — `_timer` created after `await LoadAsync()`
- `Components/Pages/Monitoring/AlarmSummary.razor:330` — `StartTimer()` after `await RefreshAsync()` in `OnSiteChangedAsync` (the cold fan-out can run for seconds against an unreachable site)
**What's wrong.** If the user navigates away while the awaited load is still running, Blazor calls `Dispose` first — it finds the timer field null (or unsubscribes a handler that was never added) — and then the continuation resumes and creates the timer / adds the handler on an already-disposed component. Nothing ever disposes it. `Topology.razor` fixed exactly this under a lock ("register row 103"), and `DebugView` / `PendingUpdatesIndicator` guard it too; these five places do not.
**Failure scenario.** An operator opens Monitoring → Health and clicks another nav item before the first load completes (easy when a KPI singleton is slow and tiles sit on their 5 s timeout). The orphan timer then fires every 10 s for the life of the process. Each tick is cheap while the circuit lives (`if (_disposed) return`), and after the circuit ends each tick throws inside `InvokeAsync` and logs a trace warning — but the timer roots the component and, through its injected services, the dead circuit's object graph, so none of it is collected. For Deployments the root is the process-singleton `IDeploymentStatusNotifier`, whose invocation list grows by one dead handler per occurrence and is walked on every deployment status write. On a long-running central node this accumulates without bound.
**Suggested fix.** After the awaits, check `_disposed` before creating the timer / subscribing, and make create-vs-dispose atomic the way `Topology.StartLiveUpdatesTimer` does; for Deployments, subscribe before the first load (the handler already no-ops safely) or re-check `_disposed` and unsubscribe immediately.
---
## UI-5 — Audit Log grid ignores site scope; execution-tree scope compares the wrong id space
- **Severity:** Medium — **Category:** bug (authorization) — **Confidence:** Confirmed (code path)
- **Where:** `Services/AuditLogQueryService.cs:102` (`QueryAsync`, no scope applied), `:181-186` (`GetExecutionTreeAsync`); compare `ZB.MOM.WW.ScadaBridge.ManagementService/AuditEndpoints.cs:598` (`ApplySiteScope`) and `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs:1001` (`ScopedAuditSource`)
**What's wrong.** Two inconsistencies on the same surface:
1. The management API's audit query and export apply `ApplySiteScope`: a caller carrying SiteId claims only sees rows for those sites. The Central UI grid goes through `AuditLogQueryService.QueryAsync`, which applies no scope at all, so the same user sees every site's rows (request/response summaries included) in the browser. The execution-tree call two methods down *does* apply scope, so the page is internally inconsistent as well.
2. `GetExecutionTreeAsync` passes the raw SiteId claim values as `permitted`. Those claims are integer `Site.Id` values (`SiteScopeService` parses them with `int.TryParse`; they come from `SiteScopeRule.SiteId`). `ScopedAuditSource` compares them to `AuditLog.SourceSiteId`, which holds the site *identifier* string (site rows are stamped from the site's configured id, e.g. `ScriptRuntimeContext.cs:2977`). `"3"` never equals `"site-a"`, so a scoped caller gets only central rows (`SourceSiteId IS NULL`) and none of their own site's. `ManagementActor`'s secured-write listing translates ids to identifiers first (`permittedIdentifiers`); this path does not.
**Failure scenario.** A user is in both a Viewer LDAP group and a site-scoped Deployer group (claims are per user, so the Viewer role inherits the SiteId claims). On Audit → Log they can browse and open every site's audit rows, which the CLI refuses them. On Audit → Execution Tree, a chain that ran on their own permitted site renders without its site-side nodes.
**Suggested fix.** Apply the same scope rule in `QueryAsync` (and the drill-in queries that reuse it), and translate `Site.Id` claims to `SiteIdentifier` values once before handing them to any audit repository method. The id-space mismatch appears to exist in `AuditEndpoints.ApplySiteScope` and `FlowDebugRunner.ReplayAsync` too (outside this slice), so a shared helper would fix all three.
---
## UI-6 — Instance "Save overrides" rewrites every override, one transaction and one audit row each
- **Severity:** Medium — **Category:** perf (with an audit-noise side effect) — **Confidence:** Confirmed (code path)
- **Where:** `Components/Pages/Deployment/InstanceConfigure.razor:1393-1445` (`SaveOverrides`), seed at `:950`; same loop in the CSV import at `:1503-1518`; `Services/ConfigurationCommandService.cs` (`ExecuteInstanceAsync`); `ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs:188-190`
**What's wrong.** `_overrideValues` is seeded with *all* existing overrides at load, and `SaveOverrides` iterates the whole dictionary, not the changed entries. Each iteration calls `ExecuteInstanceAsync`, which per call performs a forced session revalidation (`RequireRoleAsync`), opens a configuration transaction, re-fetches the instance, performs a second forced revalidation (`IsSiteAllowedAsync`), then `SetAttributeOverrideAsync` saves and writes an `UpdateOverride` config-audit row unconditionally. Before the loop, `GetCurrentUserAsync` does the role and site check once more.
**Failure scenario.** An instance has ~260 attribute overrides (the QA instances in this project are that size). The operator changes one value and clicks Save: ~260 sequential transactions and well over a thousand database round trips, with the button spinning throughout; the configuration audit log gains ~260 `UpdateOverride` entries for values that did not change, burying the one real edit. The save is also non-atomic — a failure half-way leaves a partial apply, reported only as a count.
**Suggested fix.** Diff against `_existingOverrides` and send only changed entries, ideally as one batch command in a single transaction (the native-alarm-source import on the same page already uses a set-style command). Have `SetAttributeOverrideAsync` skip the write and the audit row when the value is unchanged.
---
## UI-7 — Notification / Site Calls reports filter by site scope after server paging
- **Severity:** Medium — **Category:** bug — **Confidence:** Confirmed (code path)
- **Where:** `Components/Pages/SiteCalls/SiteCallsReport.razor.cs:297-307` (`FetchPage`), `Components/Pages/Notifications/NotificationReport.razor:573-574`
**What's wrong.** For a site-scoped user with the source-site filter left on "All", the query is sent unscoped, the server returns one page, and `FilterPermittedAsync` then removes rows from other sites client-side.
- *Site Calls:* the Next cursor is only kept when `_siteCalls.Count == PageSize`, measured **after** filtering. Any page containing at least one out-of-scope row is "short", so Next is disabled and the user cannot page further.
- *Notifications:* `_totalCount` is the server's unfiltered count, so the pager shows page counts for rows the user cannot see (leaking other sites' volumes), and pages can be partly or wholly empty.
**Failure scenario.** A Deployer scoped to site B opens Site Calls while site A is producing most of the traffic. The first 50 rows are all site A's; the grid renders empty with Next disabled, so the operator concludes there are no cached calls for their site even though there are parked ones further down. On Notifications the same operator sees "page 1 of 40" with zero rows.
**Suggested fix.** Push the permitted set into the query (send the permitted site identifiers as the source-site filter, or add a multi-site filter to the request) so paging and counts are computed over rows the user may see; keep the client-side filter only as a backstop.
---
## UI-8 — Topology actions share the circuit DbContext with the live tick and with each other
- **Severity:** Low — **Category:** bug — **Confidence:** Plausible (code path confirmed; needs a timing overlap)
- **Where:** `Components/Pages/Deployment/Topology.razor:1172` (`ShowDiff` → injected `DeploymentService.GetDeploymentComparisonAsync`), `:999` (`EnableInstance`), `DisableInstance`, `DeleteInstance`; live tick `OnLiveUpdatesTick` → `LoadDeployedStateAsync`
**What's wrong.** `_loadGate` serializes the page's own loads, and `DeployAll` / `DeployInstance` / the staleness fan-out were moved to their own DI scopes. But `ShowDiff` re-flattens an instance through the circuit-scoped `DeploymentService` without taking `_loadGate` or setting `_actionInProgress`, and Enable / Disable / Delete use the same circuit-scoped service. The 15 s tick skips only when `_actionInProgress` was already true at its start; a tick already in flight, or one that starts during a diff, overlaps on the one context.
**Failure scenario.** The operator clicks **Diff** on an instance with a large template chain (a multi-query flatten). The 15 s tick fires mid-flatten: either the diff dialog shows "Failed to load diff: A second operation was started on this context instance…", or the tree is replaced by "Failed to load topology: …" until the next tick.
**Suggested fix.** Run `ShowDiff` and the Enable / Disable / Delete calls in their own scope like `DeployInstance`, or take `_loadGate` around them.
---
## UI-9 — Secured Writes history pages over all statuses, then filters client-side
- **Severity:** Low — **Category:** bug — **Confidence:** Confirmed (code path)
- **Where:** `Components/Pages/Operations/SecuredWrites.razor:358-363` (`RefreshListsAsync`)
**What's wrong.** The History table requests `status: null` with `skip`/`take`, then drops non-terminal rows in memory. Pending rows therefore occupy slots in the page, and `_historyTotalCount` (which drives `HasNextHistoryPage`) counts them too.
**Failure scenario.** With 30 writes awaiting verification, history page 1 shows only 20 terminal rows instead of 50; with 50 or more pending it can show none while Next is enabled. The pager may also offer a final page that is empty.
**Suggested fix.** Let the list command accept a set of statuses (or a "terminal only" flag) so the filter and the count happen in SQL.
---
## UI-10 — Notification KPIs page shows every site's breakdown to a site-scoped Deployer
- **Severity:** Low — **Category:** bug (authorization / information exposure) — **Confidence:** Confirmed (code path)
- **Where:** `Components/Pages/Notifications/NotificationKpis.razor` (`OnInitializedAsync`, per-site table; no `SiteScopeService` injected)
**What's wrong.** The page is `RequireDeployment`, and `SiteScopeService`'s own contract says Deployment and Monitoring pages must filter every site list. Sibling pages (Notification Report, Site Calls, Parked Messages, Event Logs, Alarm Summary, Topology, Sites) do. This page loads all sites and renders the per-site KPI table unfiltered.
**Failure scenario.** A Deployer scoped to site B opens Notifications → KPIs and sees names, queue depths, parked and stuck counts for every other site.
**Suggested fix.** Filter the per-site rows through `SiteScopeService.Resolve` on the cascaded principal (no extra revalidation needed), as `PendingUpdatesHealthTiles` does. The global tiles and trends can stay as they are or be hidden for scoped users, depending on intent.
---
## UI-11 — Retry/Discard refused for everyone when the row's source site no longer resolves
- **Severity:** Low — **Category:** bug — **Confidence:** Confirmed (code path)
- **Where:** `Components/Pages/Notifications/NotificationReport.razor:853-857`, `Components/Pages/SiteCalls/SiteCallsReport.razor.cs` (`IsRowSiteAllowedAsync`)
**What's wrong.** `IsRowSiteAllowedAsync` returns `resolved is not null && …`. The display filter on the same pages deliberately *keeps* rows whose source site cannot be resolved ("stale row from a deleted site"), and the unused `IsRowSiteAllowedSync` documents "an unresolvable site identifier defaults to allowed". The async version that the actions actually call does the opposite, and it has no system-wide bypass.
**Failure scenario.** A site is deleted or its identifier changed while notifications from it are still parked centrally. The rows remain visible, but Retry and Discard both answer "You are not permitted to act on notifications for this site" — even for an Administrator — so the parked rows cannot be cleared from the UI.
**Suggested fix.** Short-circuit to allowed for a system-wide user before resolving the site, and decide explicitly what a scoped user may do with an unresolvable row (deny is reasonable); delete the unused sync variant.
---
## UI-12 — Per-row authorization re-checks and repeated site queries in polls and bulk loops
- **Severity:** Low — **Category:** perf — **Confidence:** Confirmed (code path)
- **Where:**
- `Components/Pages/Monitoring/ParkedMessages.razor` `BulkRetry` / `BulkDiscard` — inside the per-message loop: `RequireRoleAsync` (forced session revalidation), `SiteRepository.GetAllSitesAsync()`, `IsSiteAllowedAsync` (second forced revalidation)
- `Components/Pages/Deployment/Deployments.razor` `LoadDataAsync` — `IsSystemWideAsync` then `PermittedSiteIdsAsync`, i.e. two forced revalidations per reload, and reloads arrive every 500 ms during a bulk deploy
- `Services/ConnectionHealthQueryService.cs` — every 10 s tick of the Data Connections page re-queries all sites and all data connections although the page already holds both lists
- `Components/Pages/Operations/SecuredWrites.razor` `LoadSitesAsync` — one `GetDataConnectionsBySiteIdAsync` per site (the N+1 the Sites page removed under CentralUI-012)
**What's wrong.** `SiteScopeService` instance methods each call `GetAuthoritativeStateAsync`, which re-maps LDAP groups to roles against the database (its own doc comment says both entry points refresh). Calling it, plus a full site read, per row or twice per reload multiplies database round trips for no additional safety.
**Failure scenario.** Bulk-discarding 50 parked messages issues ~150 extra database round trips before any relay is sent. A 200-instance site deploy drives ~4 revalidations per second per open Deployments page on top of the grid queries.
**Suggested fix.** Resolve role and site scope once per user action (before the loop / once per `LoadDataAsync`, using a single resolve that returns both the system-wide flag and the id set), build the connection-health map from the page's already-loaded lists, and load connections for the Secured Writes form in one query.
---
## UI-13 — Every Test Run cold-starts a `dotnet` worker inside the 5 s default deadline
- **Severity:** Low — **Category:** perf — **Confidence:** Plausible (code path confirmed; timings not measured)
- **Where:** `ScriptAnalysis/SandboxWorkerProtocol.cs` `RunCoreAsync` (deadline armed before `Admission.WaitAsync` and `Process.Start`); `ZB.MOM.WW.ScadaBridge.CentralUI.SandboxWorker/Program.cs`
**What's wrong.** The run deadline (`TimeoutSeconds`, default 5, max 10) starts before admission, and every run launches a new `dotnet ZB.MOM.WW.ScadaBridge.CentralUI.SandboxWorker.dll` process that must start the runtime, JIT, and perform a first-ever Roslyn script compile (plus nested `CallShared` compiles) before user code executes. Nothing is reused between runs. The isolation itself is sound — the kill-on-deadline is what makes a runaway script safe — but the budget the user thinks applies to their script is largely consumed by start-up.
**Failure scenario.** On a busy central node (or while four other Test Runs hold the admission slots), a script that takes 1 s to run reports "exceeded the 5-second sandbox timeout" intermittently; re-running it succeeds.
**Suggested fix.** Start the deadline when the worker reports it is about to execute user code (keep a separate, generous ceiling for start-up + compile), or keep a small pool of pre-warmed single-use workers.
---
## Checked and found sound (not findings)
- No `.Result` / `.Wait()` / `GetAwaiter().GetResult()` on a renderer path; the two `GetResult` calls in `SandboxScriptHost` execute inside the worker process, not on a circuit.
- `PendingUpdatesIndicator`, `Topology` live timer, `DebugView` session/stream handling and `FlowDebugger` refresh loop: create/dispose races are guarded and state is marshalled with `InvokeAsync`.
- `/api/script-analysis/*` (RequireDesign + bound-run policy), `/api/centralui/audit/export` (Administrator only, so always system-wide), `/auth/*`: no authorization gap found.
- Flow Debugger Retry/Discard on Notify nodes skips the page-level site check, but Replay rows are already scope-filtered server-side, so a scoped user cannot reach another site's node.
- Transport import runs on the circuit context, but it is transactional, so a dropped circuit rolls back rather than leaving partial state (contrast UI-3).
## Slice: Review slice 05 — DataConnectionLayer, StoreAndForward, SiteEventLogging
HEAD `d4d5be3b`. Read-only review; nothing was built or run. Every finding below was traced through the code path named (callers included). "Confirmed" means the logic error is certain from the code; "Plausible" means the code path is certain but the trigger depends on timing, naming or an external library's behaviour I could not execute.
Paths are relative to `src/`. `DCL/` = `ZB.MOM.WW.ScadaBridge.DataConnectionLayer/`, `SF/` = `ZB.MOM.WW.ScadaBridge.StoreAndForward/`, `SEL/` = `ZB.MOM.WW.ScadaBridge.SiteEventLogging/`.
| ID | Severity | Category | Confidence | Title |
|----|----------|----------|------------|-------|
| DCL-1 | High | bug | Confirmed | Seed-read values are delivered late and unguarded, so they overwrite newer subscription values |
| DCL-2 | Medium | bug | Confirmed | An OPC UA alarm re-subscribe that fails after reconnect is never retried |
| DCL-3 | Medium | bug | Confirmed | OPC UA alarm subscribe reports success without checking the monitored item's create status |
| DCL-4 | Medium | bug | Plausible | The reconnect re-subscribe loop is not cancelled when its session ends, and keeps subscribing on the next session |
| SF-1 | Medium | bug | Confirmed | Per-target FIFO is broken: a younger buffered message can be delivered before an older one |
| SF-2 | Medium | bug | Confirmed | A storage error after a successful delivery is handled as a transient delivery failure |
| SF-3 | Medium | perf | Confirmed | Every sweep sorts the whole due backlog, payloads included |
| DCL-5 | Medium | bug | Plausible | Alarm routing matches sources by raw string prefix, so `Tank1` also receives `Tank10`'s alarms |
| DCL-6 | Low | bug | Confirmed | OPC UA search/browse throw synchronously inside the actor while disconnected; caller gets no reply |
| DCL-7 | Low | bug | Confirmed | OPC UA reads use `SourceTimestamp` even when the connection is configured for `Server` timestamps |
| DCL-8 | Low | bug | Plausible | Connection-level failure rows in a re-subscribe batch are only logged; the tags are left in no retry set |
| DCL-9 | Low | bug | Confirmed | Shared supervisory-advise task captures the first caller's cancellation token |
| DCL-10 | Low | perf | Confirmed | `MapQuality` allocates per MxGateway data-change event |
| SEL-1 | Low | perf | Plausible | Instance-filtered event queries have no `(instance_id, timestamp)` index |
---
## DCL-1 — Seed-read values are delivered late and unguarded, so they overwrite newer subscription values
- **Severity:** High · **Category:** bug · **Confidence:** Confirmed (logic); the window is timing-dependent
- **Where:**
- `DCL/Actors/DataConnectionActor.cs:1468-1470` (seed runs after the subscribe, inside the same background task)
- `DCL/Actors/DataConnectionActor.cs:1968-1975` (seeds re-injected as `TagValueReceived` when `SubscribeCompleted` is handled)
- `DCL/Actors/DataConnectionActor.cs:2990-2997` (reconnect re-seed: all seeds told to self only after the whole `SeedTagsAsync` returns)
- `DCL/Actors/DataConnectionActor.cs:2630-2637` (same pattern for newly resolved tags)
- `DCL/Actors/DataConnectionActor.cs:3047-3076` (`HandleTagValueReceived` forwards with no timestamp comparison)
- **What's wrong:** The subscription is live before the seed read starts. `HandleSubscribe` indexes the tags and sets `_subscribers` up front, so live notifications reach the Instance Actor during the seed phase. The seed values are held until the entire seed operation finishes, then forwarded as ordinary values. That operation covers all chunks and retry rounds and is bounded only by `SeedOverallTimeout` (120 s). Nothing compares the seed's timestamp with the value already delivered: not `HandleTagValueReceived`, and not `InstanceActor.HandleTagValueUpdate` (checked; it stores `update.Timestamp` unconditionally).
- **Failure scenario:** A site reconnects with a few thousand tags. `ReSubscribeAll` starts the subscribe loop and the re-seed in parallel. The seed chunk containing `Mixer.State` reads `Idle` at T0. At T0+1 s the device changes to `Running` and the new subscription delivers it. At T0+8 s the last seed chunk returns and the loop at 2995 tells every seed to self, including `Mixer.State = Idle`. The instance now holds `Idle` with Good quality until the tag changes again. For a tag that changed exactly once in the window (a state flag, handshake bit or setpoint) that can be indefinitely. Scripts, alarms and `WaitAsync` waiters then act on the regressed value. The same race exists on first subscribe, with a shorter window.
- **Suggested fix:** In `HandleTagValueReceived`, keep the last forwarded source timestamp per tag and drop a seed-origin value that is not newer than it. Mark seeds with a flag on `TagValueReceived` so only they are subject to the check. Alternatively, drop a seed for any tag that has already produced a live value in the current generation.
## DCL-2 — An OPC UA alarm re-subscribe that fails after reconnect is never retried
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `DCL/Actors/DataConnectionActor.cs:3542-3568` (`ReSubscribeAllAlarms`), `:3355-3364` (failure branch of `HandleAlarmSubscribeCompleted`); subscriber side `ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs:167` and `:381-394`
- **What's wrong:** After a reconnect the DCL re-issues every alarm feed itself, with `ReplyTo = null`. If `SubscribeAlarmsAsync` fails, `HandleAlarmSubscribeCompleted` removes the source from `_alarmSubscribesInFlight`, logs a warning and stops. There is no retry timer and no message to the subscribers. `NativeAlarmActor` set `_subscribeSucceeded = true` on the original subscribe, and `SendSubscribe` returns immediately when that flag is set. Its `NativeAlarmSourceUnavailable` handler deliberately does not re-subscribe. Data tags have the `_unresolvedTags` retry loop for this case; alarm sources have nothing.
- **Failure scenario:** An OPC UA server restarts. The session reconnects. `CreateAlarmSubscriptionAsync` throws for one source, for example because `OpcUaNodeReference.Resolve` cannot find an `nsu=` namespace the server has not loaded yet, or because the event subscription create times out. The DCL logs `Alarm subscribe failed for source …`. The instance keeps its pre-outage mirrored alarms as "last known" and never receives another transition or snapshot until the next reconnect or redeploy. The connection shows Connected throughout.
- **Suggested fix:** On a failed completion with `ReplyTo == null`, schedule a backed-off retry for that source while it still has subscribers (mirror `ScheduleTagResolutionRetry`). Alternatively, tell the subscribers a failure message that makes `NativeAlarmActor` clear `_subscribeSucceeded` and resume its own retry.
## DCL-3 — OPC UA alarm subscribe reports success without checking the monitored item's create status
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `DCL/Adapters/RealOpcUaClient.cs:965-974` (alarm path); compare the data path at `:709-720`
- **What's wrong:** The data path inspects `item.Status.Error` after `ApplyChangesAsync` and turns a bad per-item status into a failed outcome, because `ApplyChangesAsync` does not throw for per-item failures. The alarm path adds the event monitored item, applies, stores the handle in `_alarmItems` and returns it without looking at `item.Status`. The actor then records the feed as subscribed and answers `SubscribeAlarmsResponse(Success: true)`.
- **Failure scenario:** A native alarm source is bound to a node that does not exist on the server, or to a node that is not an event notifier. The server rejects the monitored item (`BadNodeIdUnknown`, `BadAttributeIdInvalid` or a rejected event filter). The DCL logs `Alarm feed subscribed for source …`, `NativeAlarmActor` logs "subscription established", and no alarm ever arrives. No error is surfaced and nothing retries.
- **Suggested fix:** After the apply, check `item.Status?.Error` with `ServiceResult.IsBad`. On failure remove the item from the event shard, drop the three per-handle dictionary entries created at 931-932, and throw so the actor reports the failure. Also clean those entries up when `ApplyChangesAsync` itself throws.
## DCL-4 — The reconnect re-subscribe loop is not cancelled when its session ends, and keeps subscribing on the next session
- **Severity:** Medium · **Category:** bug · **Confidence:** Plausible (code path confirmed; needs a subscribe call that hangs across a reconnect)
- **Where:**
- `DCL/Actors/DataConnectionActor.cs:2948-2971` (loop has no token and no generation check)
- `DCL/Actors/DataConnectionActor.cs:2714-2719` (stale batch results dropped without releasing handles)
- `DCL/Actors/DataConnectionActor.cs:1581-1592` (release skipped when the owner is the current adapter)
- `DCL/Adapters/OpcUaDataConnection.cs:221` and `DCL/Adapters/MxGatewayDataConnection.cs:372-387` (both dereference the current `_client` at call time)
- **What's wrong:** `ReSubscribeAll` captures the adapter object and the generation, then walks all chunks in one background task. `CancelSessionWork` only cancels the re-seed. On an ordinary reconnect the adapter object is reused and `ConnectAsync` swaps in a new inner client. A loop left over from generation N therefore issues its remaining chunks against generation N+1's client. Its results arrive tagged with generation N and `HandleBatchSubscribeCompleted` drops them without unsubscribing. The comment at 1581 assumes such handles "died with that session", which is false here: they were created on the new session.
- **Failure scenario:** A large site (many 500-tag chunks) is re-subscribing when the link wedges. Chunk k hangs inside `ApplyChangesAsync` (OPC UA) or `SubscribeBulkAsync` (MxGateway; there is no session command timeout yet). Keep-alive fails, the actor reconnects after 5 s and starts a new loop. When the old client is torn down or its operation timeout fires, the old loop's chunk k returns a failure and the loop continues with chunks k+1… on the new client.
- OPC UA: each of those tags gets a second monitored item whose callback carries the old generation. Notification traffic for them doubles, every duplicate becomes a dropped actor message, and the items are never released until the next reconnect.
- MxGateway: the same chunks are subscribed twice on the gateway, which is the subscribe-storm load the Lever 1 work set out to remove. The stale loop also writes `_tagToSub[tag]` with the old-generation callback; if it writes after the new loop for any tag, that tag's updates are all dropped as stale and the tag freezes.
- **Suggested fix:** Give the subscribe loop the session token created at 2988 (create it before starting the loop) and stop when it is cancelled. Also have each adapter capture `_client` once per call and reject a call whose client is no longer current.
## SF-1 — Per-target FIFO is broken: a younger buffered message can be delivered before an older one
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `SF/StoreAndForwardStorage.cs:202-223` (due predicate is per row), `SF/StoreAndForwardService.cs:889-921` (lane built only from due rows)
- **What's wrong:** A row is due when `now - last_attempt_at_ms >= retry_interval_ms`, evaluated per row. A lane is the set of rows that happen to be due, ordered by `created_at`. When the head of a lane fails, its `last_attempt_at` moves to now and the lane short-circuits. The rows behind it keep their older `last_attempt_at`, so on a later sweep they are due while the head is not. The code comment at 889-893 claims "within a lane delivery stays strictly sequential (per-target FIFO)", but that holds only among rows that are due in the same sweep.
- **Failure scenario:** Database connection `Mes` is down. A script issues `Database.CachedWrite` A at t=0 and B at t=1 (two updates to the same row). Both are buffered with `LastAttemptAt` equal to their enqueue time; retry interval 30 s, sweep every 10 s.
1. Sweep at t=30: only A is due. It fails; A is next due at t=60.
2. The database recovers at t=35.
3. Sweep at t=40: only B is due. B is delivered.
4. Sweep at t=60: A is delivered, overwriting B's newer value with the older one.
A side effect: with many staggered rows queued for a dead target, a different row becomes due on nearly every sweep, so the target is probed every 10 s instead of every retry interval.
- **Suggested fix:** Decide due-ness per lane from its oldest pending row. For example, exclude a row when an older pending row with the same `(category, target)` exists and is not due. Alternatively, on a transient failure stamp the same `last_attempt_at_ms` on every pending row of that lane.
## SF-2 — A storage error after a successful delivery is handled as a transient delivery failure
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed (logic); needs a SQLite error on the delete
- **Where:** `SF/StoreAndForwardService.cs:960-981` (success path inside the `try`), `:1011-1048` (catch-all)
- **What's wrong:** `handler(message)` and the bookkeeping that follows a `true` result share one `try`. If `RemoveMessageAsync` throws after the handler succeeded, the generic `catch` runs. It increments `RetryCount`, records the SQLite error as `LastError`, and either reschedules the message or parks it when `RetryCount >= MaxRetries`. The same applies to an exception from `UpdateMessageIfStatusAsync` on the permanent-failure path at 987.
- **Failure scenario:** A cached external call is delivered on its last allowed retry. The row delete hits `SQLITE_BUSY` or a disk-full error; the consolidated LocalDb file is shared with the event-log writer, the tracking store and the replication applier. The message is parked as `ParkedMaxRetries`, an audit row says delivery failed, and an operator who presses Retry sends the call a second time. Below the retry limit the row simply stays pending and is delivered again on the next due sweep, and a "Retried" site event is logged for a call that succeeded.
- **Suggested fix:** Narrow the `try` to the handler call. Handle post-delivery storage failures separately: retry the delete a few times, and if it still fails log an error and leave the retry count alone rather than counting or parking.
## SF-3 — Every sweep sorts the whole due backlog, payloads included
- **Severity:** Medium · **Category:** perf · **Confidence:** Confirmed
- **Where:** `SF/StoreAndForwardStorage.cs:214-223`; indexes at `SF/StoreAndForwardSchema.cs:47-48, 93-94, 110-111`
- **What's wrong:** The fair-paging query computes `ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at)` over every due pending row, and the inner select carries all columns including `payload_json`. No index is ordered `(status, category, target, created_at)`, so SQLite must sort the whole due set, payloads and all, before the outer `ORDER BY lane_rank … LIMIT 500` can pick 500 rows. This runs every `RetryTimerInterval` (10 s). The buffer has no maximum size by design, and notifications retry without limit.
- **Failure scenario:** Central is unreachable for a day and a site accumulates 200 000 buffered notifications of about 1 KB each. Each row becomes due again every 30 s, so nearly all of them are due on every sweep. Every 10 s the active node sorts roughly 200 MB into temp storage to deliver at most one row per lane, because the lane short-circuits on the first failure. Because `deferToSweep` enqueues call `TriggerSweep`, each `Notify.Send` can start another such sweep as soon as the previous one ends.
- **Suggested fix:** Rank on a narrow projection (`id, category, target, created_at`), take the 500 ids, then join back for the payloads. Add an index on `(status, category, target, created_at)` so the window needs no sort. `idx_sf_messages_category` could be dropped in exchange.
## DCL-5 — Alarm routing matches sources by raw string prefix, so `Tank1` also receives `Tank10`'s alarms
- **Severity:** Medium · **Category:** bug · **Confidence:** Plausible (logic confirmed; needs sibling names that share a prefix)
- **Where:** `DCL/Actors/DataConnectionActor.cs:3406-3407`; OPC UA identity at `DCL/Adapters/OpcUaAlarmMapper.cs:92-98`
- **What's wrong:** A transition is routed to source `S` when `SourceObjectReference.StartsWith(S)` or `SourceReference.StartsWith(S)`, with no segment-boundary check. The first-segment index at 3487-3506 does not help: references with no `.` all land in `_alarmSourcesWithoutSeparator`, and the OPC UA routing reference is the subscription's own node id string. `NativeAlarmActor` does no filtering of its own.
- **Failure scenario:** Two instances bind native alarm sources `ns=2;s=Tank1` and `ns=2;s=Tank10` (or MxGateway objects `Pump1` and `Pump10`) on one connection. Every transition from the `Tank10` feed has a routing reference that starts with `…Tank1`, so it is cached under and delivered to the `Tank1` subscriber as well. Instance Tank1 mirrors Tank10's alarms, including through snapshot swaps, and reports them to MES and the alarm UI as its own.
- **Suggested fix:** Require an exact match or a prefix that ends at a separator (`S` followed by `.`). If raw-prefix sources are intended for area subscriptions, make that an explicit opt-in such as a trailing `*`.
## DCL-6 — OPC UA search/browse throw synchronously inside the actor while disconnected; caller gets no reply
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `DCL/Adapters/OpcUaDataConnection.cs:455-465` (`SearchAddressSpaceAsync` is not `async` and throws directly), `:448-452` (`_client!.BrowseChildrenAsync` when `_client` is null); call sites `DCL/Actors/DataConnectionActor.cs:2352` and `:2271`
- **What's wrong:** The comments on the Connecting and Reconnecting cases say the adapter call "throws `ConnectionNotConnectedException` — mapped by `HandleSearch`". The mapping lives in a `ContinueWith`, which only sees a faulted task. `SearchAddressSpaceAsync` throws before returning a task, so the exception escapes `HandleSearch` on the actor thread. The supervisor resumes the actor, so subscription state is safe, but no `SearchAddressSpaceResult` is sent. Browse has the same hole when `_client` is still null: that is the case for a freshly swapped failover adapter until the reconnect timer fires, up to `ReconnectInterval`.
- **Failure scenario:** A designer opens the node browser and searches while the connection is reconnecting. Instead of the inline "connection not connected" banner, the dialog waits for the full Ask timeout and shows a generic timeout. The site log gets a "DataConnectionActor threw exception, resuming" warning for each attempt.
- **Suggested fix:** Make both adapter methods `async` so the exception faults the task, or wrap the two adapter calls in `HandleSearch`/`HandleBrowse` in a `try` that sends the typed failure.
## DCL-7 — OPC UA reads use `SourceTimestamp` even when the connection is configured for `Server` timestamps
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `DCL/Adapters/RealOpcUaClient.cs:1546-1558` (read with the configured mode, then `result.SourceTimestamp`), `DCL/Adapters/OpcUaDataConnection.cs:287` and `:359`
- **What's wrong:** `TimestampsToReturn` is passed to `session.ReadAsync`, but the code always takes `SourceTimestamp`. With `Server` the source timestamp is absent, `ToClrTimestamp` returns `DateTime.MinValue`, and the adapter builds `new DateTimeOffset(DateTime.MinValue, TimeSpan.Zero)`. The setting is also not applied to subscriptions at all; `RealOpcUaClient.cs:775` reads `SourceTimestamp` from notifications too, so a server that omits source timestamps produces the same result there.
- **Failure scenario:** A connection is configured with `TimestampsToReturn = Server`. Every seeded value (first subscribe and every reconnect re-seed) and every Test Bindings read reaches the instance with timestamp `0001-01-01T00:00:00Z`. That timestamp is stored as the attribute timestamp, streamed to central and shown in the Debug View until the tag next changes.
- **Suggested fix:** Fall back to `ServerTimestamp`, and then to `DateTime.UtcNow`, when the source timestamp is the minimum value. Do this in one helper used by both the read and notification paths.
## DCL-8 — Connection-level failure rows in a re-subscribe batch are only logged; the tags are left in no retry set
- **Severity:** Low · **Category:** bug · **Confidence:** Plausible
- **Where:** `DCL/Actors/DataConnectionActor.cs:2781-2787`; contrast `:565-569`
- **What's wrong:** When an interactive subscribe reports a connection-level failure, the Connected handler enters Reconnecting. When a row in a `BatchSubscribeCompleted` (reconnect re-subscribe) has `ConnectionLevelFailure`, the handler only logs, on the stated assumption that "the reconnect cycle re-issues everything". Nothing starts that cycle from here. If the adapter does not also raise `Disconnected`, the tags are in neither `_subscriptionIds` nor `_unresolvedTags`, because `ReSubscribeAll` cleared both, so nothing retries them.
- **Failure scenario:** During a re-subscribe, one chunk fails with an exception that `IsConnectionLevelFailure` classifies as connection-level (`InvalidOperationException`, `TimeoutException`, `IOException`) while the session and event stream stay healthy. Those 500 tags stay at Bad quality until some unrelated reconnect. I could not confirm which adapter exceptions meet this without a `Disconnected` following, hence Plausible.
- **Suggested fix:** Return a flag from `HandleBatchSubscribeCompleted` as `HandleSubscribeCompleted` does, and enter Reconnecting when a current-generation batch contains a connection-level row. Alternatively, put those tags into `_unresolvedTags` so the resolution timer retries them.
## DCL-9 — Shared supervisory-advise task captures the first caller's cancellation token
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `DCL/Adapters/RealMxGatewayClient.cs:641-643`
- **What's wrong:** `_supervisoryAdvised.GetOrAdd(handle, h => new Lazy<Task>(() => AdviseSupervisoryCoreAsync(h, ct)))` binds the shared task to the token of whichever caller created it. Later callers for the same handle await that task with their own token ignored.
- **Failure scenario:** A script writes to a tag (30 s `WriteTimeout` token) at the moment a subscribe for the same tag starts, and the gateway is slow. The write's token fires and cancels the shared advise. The subscribe, which had no deadline, fails with `OperationCanceledException`. That is classified as a tag-resolution failure: the tag is pushed to Bad and waits for the resolution retry (10 s, backing off to 5 min).
- **Suggested fix:** Run the shared advise with `CancellationToken.None` (or a client-lifetime token) and have each caller apply its own token with `Task.WaitAsync(ct)`.
## DCL-10 — `MapQuality` allocates per MxGateway data-change event
- **Severity:** Low · **Category:** perf · **Confidence:** Confirmed
- **Where:** `DCL/Adapters/RealMxGatewayClient.cs:682-685`, called from `:448-452`
- **What's wrong:** `statuses.Any(s => !s.IsSuccess())` goes through `IEnumerable<MxStatusProxy>`, which boxes the repeated-field enumerator on every event. This is on the per-value path, and the statuses list is normally empty or a single entry.
- **Failure scenario:** At the documented target of about 37 500 events/s per site this adds the same number of short-lived allocations per second to the event-loop thread for no functional gain.
- **Suggested fix:** Take the concrete `RepeatedField<MxStatusProxy>` and use an index loop with an early return when `Count == 0`.
## SEL-1 — Instance-filtered event queries have no `(instance_id, timestamp)` index
- **Severity:** Low · **Category:** perf · **Confidence:** Plausible (not measured)
- **Where:** `SEL/SiteEventLogSchema.cs:69-74`, `SEL/EventLogQueryService.cs:176-180` and `:205-211`
- **What's wrong:** The #123 change gave `event_type` and `severity` composite indexes with `timestamp` so a filtered page is read in order and stops at the limit. `instance_id` still has only the single-column `idx_events_instance`. A query filtered by instance and ordered by `timestamp, id` must either fetch and sort every row for that instance, or walk the timestamp index filtering row by row.
- **Failure scenario:** The Instances page drill-in asks for one instance's events on a site with a full 1 GB log (about 2.7 M rows). For a chatty instance, each page sorts all of its rows. For a quiet instance, if the planner walks the timestamp index, it scans most of the table. Either way this is the cold multi-second page that #123 removed for the other two filters.
- **Suggested fix:** Replace `idx_events_instance` with `(instance_id, timestamp)`, dropping the old index in `SiteEventLogSchema.Apply` the same way the other two were. The cost is roughly one more timestamp per row of index, as with #123.
---
## Checked and not reported
- `SiteEventLogger` write queue, batch/row-by-row fallback and dispose ordering: no defect found.
- `EventLogPurgeService` retention and cap loops, ceiling budget and catch-up scheduling: consistent with the documented design.
- `DataConnectionActor` generation guards on connect results, disconnects, values and subscribe completions; `Become` transitions; pending-subscribe queues; subscriber `Terminated` cleanup: no hole found beyond DCL-4 and DCL-8.
- ServiceLevel failover partial: no defect found.
- `NotificationForwarder` and `ParkedMessageHandlerActor`: no defect found.
## Slice: Review slice 06 — AuditLog / SiteCallAudit / KpiHistory
HEAD `d4d5be3b`. Read-only review. Paths are relative to `src/`.
Scope read in full: the site SQLite writer, telemetry actor, fallback/ring, retention service, central ingest / reconciliation / purge actors, pull clients, `SiteCallAuditActor`, `KpiHistoryRecorderActor`, plus the repository / archive / gRPC-handler code those call (`ConfigurationDatabase/Repositories/*`, `Maintenance/AuditLogPartitionArchive.cs`, `Communication/Grpc/SiteStreamGrpcServer.cs`).
Two things were checked outside the code: SQLite query plans (`EXPLAIN QUERY PLAN` against the exact schema) and shared-cache locking behaviour (a scratch two-connection test). Both are noted where used.
Not reported because it is documented as accepted: the "late-stamped row is protected for one pull cycle only" behaviour of `MarkReconciledUpToAsync` (`Component-AuditLog.md` → *The bound protects a late-stamped row for one pull cycle, not forever*). AUD-1 describes a different, undocumented hole in the same mechanism.
| ID | Severity | Category | Title |
|---|---|---|---|
| SCA-1 | Medium | bug | Central `SiteCalls` row never leaves `Parked` after an operator Retry or Discard |
| AUD-1 | Medium | bug | Reconciliation pull reads only NodeA's node-local store while NodeA answers; one cursor is shared by two unrelated stores |
| KPI-1 | Medium | bug | Rollup backfill is always skipped: the periodic fold advances the "watermark" 5 s before the backfill plans |
| AUD-2 | Medium | perf | `Cache=Shared` makes the "dedicated read connection" block the batch writer (and the reverse) |
| AUD-3 | Medium | perf | `ReadPendingSinceAsync` scans, joins and sorts the whole owed backlog for every 256-row page |
| AUD-4 | Low | perf | Site retention purge cannot seek on age; each page can scan the whole `Forwarded` index range under `_writeLock` |
| AUD-5 | Low | perf | Per-channel retention `DELETE` has no usable index and binds the channel as `nvarchar` |
| AUD-6 | Low | bug | Rows stamped before the first partition boundary are never purged or archived |
| AUD-7 | Low | perf | Cached-telemetry drain does one tracking-store read (a writer-queue barrier) per audit row |
---
## SCA-1 — Central `SiteCalls` row never leaves `Parked` after an operator Retry or Discard
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:**
- `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs:33-48` (rank table: `Parked` = 3 = terminal) and `:276-310` (`MonotonicUpdateSql`: equal terminal rank is immutable)
- `ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs` `HandleRetrySiteCall` / `HandleDiscardSiteCall` / `RelayRetryAsync` / `RelayDiscardAsync` (relay only, by design never mutates the row)
- `ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs:249,289` (`AND TerminalAtUtc IS NULL` on both attempt and terminal updates)
- `ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs:1248-1304` (`RetryParkedMessageAsync` / `DiscardParkedMessageAsync`)
- **What's wrong:** The spec (`Component-SiteCallAudit.md`) says `Parked` is non-terminal and that after a relayed Retry/Discard "the site applies the change and emits telemetry reflecting the new state; central never mutates the row directly". No such state can ever land:
1. Discard at the site deletes the S&F row and raises an activity only. Nothing in the site code emits a `Discarded` status for a cached call (the only `AuditStatus.Discarded` for this path is central's own operator-provenance row, which goes to `AuditLog`, not `SiteCalls`).
2. Retry re-queues the message. When it later delivers, the site tracking row is already terminal (`Parked` was written through `RecordTerminalAsync`), so both `RecordAttemptAsync` and `RecordTerminalAsync` are no-ops. The telemetry packet is built from that snapshot, so it still says `Parked`.
3. Even if a `Delivered`/`Discarded` packet did arrive, central's upsert rejects it: equal terminal rank never overwrites (`Delivered` cannot overwrite `Parked`; pinned by `SiteCallAuditRepositoryTests` line ~383).
- **Failure scenario:** A cached call parks. An operator clicks Retry on the Site Calls page; the site acks `Applied`, the call is delivered. The central row stays `Parked` until the 365-day purge. The Parked KPI tile and the `parked` trend count it forever, the page keeps offering Retry/Discard on it (each further click returns `NotParked`), and `Tracking.Status(id)` at the site also still reports `Parked`. Same outcome for Discard.
- **Suggested fix:** Decide that `Parked` is re-openable and implement it end to end: let the site tracking store accept a transition out of `Parked` (clear `TerminalAtUtc` on retry, write `Discarded` on discard, and emit telemetry for both), and let the central guard accept `Parked → Delivered/Failed/Discarded/Attempted` when the incoming `UpdatedAtUtc` is newer. Add a test for Retry-then-Delivered and Discard on the mirror.
---
## AUD-1 — Reconciliation pull reads only NodeA's node-local store while NodeA answers; one cursor is shared by two unrelated stores
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed (code path); impact depends on which node is active
- **Where:**
- `ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullAuditEventsClient.cs:103-121` (NodeB is dialled only on a *transport fault* against NodeA); same shape in `GrpcPullSiteCallsClient.cs:110`
- `ZB.MOM.WW.ScadaBridge.AuditLog/Central/SiteAuditReconciliationActor.cs:408-416,598-601` (one in-memory cursor per **site**)
- `ZB.MOM.WW.ScadaBridge.Communication/Grpc/SiteStreamGrpcServer.cs:622-700` (`PullAuditEvents` serves the local node's `ISiteAuditQueue` directly; no hop to the active node)
- **What's wrong:** The site audit store is a per-node, unreplicated SQLite file, and each node runs its own `SiteAuditTelemetryActor`. The pull is the only path for `PushAbandoned` / `Rejected` rows and the fallback when the push is failing. But the pull goes to NodeA whenever NodeA answers, regardless of which node is active. When NodeB is the active node and NodeA is a healthy standby (the normal state after any NodeA restart), every pull returns NodeA's empty store and reports "drained".
A second problem follows from the single per-site cursor. If NodeA later becomes unreachable, NodeB is pulled with the cursor NodeA's rows produced: `ReadPendingSinceAsync` skips every owed NodeB row stamped before it, and `MarkReconciledUpToAsync` runs on NodeB with a cursor that proves receipt of NodeA's rows, not NodeB's. Any NodeB row that was served earlier but not ingested (cursor held back, or the response was lost) and sits below that cursor is flipped to `Reconciled` and later purged.
- **Failure scenario:** site-b is unreplicated; NodeA restarts, NodeB becomes active and stays active. A cached call's tracking snapshot is missing past the grace window, so NodeB marks the audit row `PushAbandoned` ("the audit half still reaches central via the reconciliation pull"). Central pulls NodeA every 5 minutes, gets nothing, and never dials NodeB. The row never reaches central, is never purged at the site, and sits in NodeB's backlog count indefinitely. The same holds for `Rejected` rows and for the whole backlog during a push-only outage. For `PullSiteCalls` the same applies on site pairs that do not run LocalDb replication.
- **Suggested fix:** Pull both nodes each tick and keep the cursor per `(siteId, endpoint)` (the channel cache is already keyed that way). Alternatively route the pull to the active node, but per-node cursors are still needed because the stores are node-local.
---
## KPI-1 — Rollup backfill is always skipped: the periodic fold advances the "watermark" 5 s before the backfill plans
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed (logic and timer ordering)
- **Where:**
- `ZB.MOM.WW.ScadaBridge.KpiHistory/KpiHistoryRecorderActor.cs` `PreStart` (rollup timer initial delay 10 s, line ~242; backfill single timer 15 s, line ~251), `HandleBackfillPlan` (line ~645-653)
- `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/KpiHistoryRepository.cs:288` (`GetLatestRollupHourAsync` = `MAX(HourStartUtc)`)
- **What's wrong:** The backfill plan treats `MAX(HourStartUtc)` as "rollups are complete through here". The periodic fold writes the trailing `RollupLookbackHours` (3) hours 5 seconds before the plan is read, and if that fold is still running the backfill tick defers until it finishes. So whenever samples exist in the last 3 hours, the watermark is the previous hour, `floor >= toHour - lookback` is true, and the backfill is latched done without folding anything. `MAX` says nothing about gaps below it.
The backfill can only run when the first periodic fold writes no rows (for example a restart after more than 3 hours with no samples).
- **Failure scenario:**
1. An environment is upgraded to the rollup-enabled build with 90 days of raw `KpiSample` rows and an empty `KpiRollupHourly`. At +10 s the periodic fold writes the last 3 hours; at +15 s the plan logs "backfill skipped — rollups current". The 30 d / 90 d trend charts (routed to rollups beyond 168 h) show only data from the upgrade onward, and the raw rows age out after 90 days without ever being folded.
2. A real backfill (after a long outage) is interrupted by a failover or a failed slice. The next singleton sees a current watermark from the periodic folds and never resumes the missing slices.
- **Suggested fix:** Do not derive the plan from `MAX`. Either track backfill progress explicitly (a persisted "backfilled through" marker, or the oldest raw hour that has no rollup row), or plan the backfill before the first periodic fold and compare `MIN(raw hour)` against `MIN(rollup hour)` so a gap below the newest rollup is detected.
---
## AUD-2 — `Cache=Shared` makes the "dedicated read connection" block the batch writer (and the reverse)
- **Severity:** Medium · **Category:** perf · **Confidence:** Confirmed (connection string in code; locking behaviour reproduced in a scratch test)
- **Where:** `ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs:105-122` (`$"Data Source={path};Cache=Shared"` used for both `_connection` and `_readConnection`)
- **What's wrong:** The class comments say the second connection plus WAL lets backlog scans run "concurrently with the writer" so a slow read "never parks the hot-path writer". With `Cache=Shared`, both connections in the process share one cache and use shared-cache table-level locks, so WAL snapshot isolation does not apply between them. A scratch test with the same setup (WAL, two shared-cache connections) gives `database table is locked` for a write during an open read and for a read during an open write transaction; without `cache=shared` both succeed.
Microsoft.Data.Sqlite retries `SQLITE_LOCKED` in 150 ms sleeps up to `CommandTimeout` (30 s by default), so the effect is a stall, not an immediate error.
- **Failure scenario:** During a central outage the site holds several hundred thousand owed rows. The 30 s backlog probe (`GetBacklogStatsAsync`) or a reconciliation page (AUD-3) runs for seconds on the read connection. `FlushBatch` hits the table lock on its first INSERT and sleeps in 150 ms steps while holding `_writeLock`, so mark-forwarded flips and the purge queue behind it too. If a read exceeds 30 s the batch faults and its events go to the 1 024-slot drop-oldest ring. Every overlap, even a short one, costs the writer at least 150 ms.
- **Suggested fix:** Drop `Cache=Shared` from the file-backed connection string (keep it only for the in-memory test override) and set a `busy_timeout`/`Default Timeout` appropriate for two private WAL connections.
---
## AUD-3 — `ReadPendingSinceAsync` scans, joins and sorts the whole owed backlog for every 256-row page
- **Severity:** Medium · **Category:** perf · **Confidence:** Confirmed (`EXPLAIN QUERY PLAN` on the exact schema: `SEARCH fs USING INDEX IX_fwd (ForwardState=?)` → `SEARCH ae … (EventId=?)` → `USE TEMP B-TREE FOR ORDER BY`)
- **Where:** `ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs:860-900`; index definition `:268-269`
- **What's wrong:** `IX_fwd` is `(ForwardState, IsCachedKind, OccurredAtUtc)`. The pull query filters `ForwardState IN (3 states)` with no `IsCachedKind` equality, and orders by `fs.OccurredAtUtc, ae.EventId`. SQLite therefore cannot use the index for the range or the order: it visits every owed row, does a primary-key lookup into `audit_event` for each (the sort key includes `ae.EventId`), and keeps the top 256.
- **Failure scenario:** After a central outage a site has 1 M `Pending` rows. Recovery pulls up to `MaxPagesPerTick` (50) pages per tick, each one a 1 M-row scan plus 1 M text-key lookups, all under `_readLock` (which also serialises the push drain's reads and the backlog probe) and, per AUD-2, contending with the writer. The pull that is meant to clear the backlog gets slower the larger the backlog is.
- **Suggested fix:** Order by `fs.EventId` (same value, no join needed for the sort) and add an index that matches the query, for example a partial index `(OccurredAtUtc, EventId) WHERE ForwardState IN ('Pending','PushAbandoned','Rejected')`, so each page is an ordered range read that stops at the limit.
---
## AUD-4 — Site retention purge cannot seek on age; each page can scan the whole `Forwarded` index range under `_writeLock`
- **Severity:** Low · **Category:** perf · **Confidence:** Confirmed (plan: `SEARCH audit_forward_state USING INDEX IX_fwd (ForwardState=?)`, age is a residual filter)
- **Where:** `ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs:1533-1540` (`PurgePage`)
- **What's wrong:** Same index mismatch as AUD-3. Within one `ForwardState` the entries are ordered by `IsCachedKind` then time, so the first pages are cheap (old non-cached rows sit at the front). Once those are gone, every further page, including the final short page of every purge run, walks the entire `Forwarded`/`IsCachedKind=0` range (the bulk of 7 days of rows) before reaching the cached-kind and `Reconciled` rows. This runs on the write connection inside `_writeLock`.
- **Failure scenario:** A site with tens of millions of retained rows: each purge run ends with at least one full index-range scan (more if cached-kind rows are expiring), during which the batch writer and all forward-state flips are blocked.
- **Suggested fix:** Add `AND IsCachedKind IN (0,1)` so SQLite can seek `(state, kind, time)` for each combination, or add a dedicated `(ForwardState, OccurredAtUtc)` index.
---
## AUD-5 — Per-channel retention `DELETE` has no usable index and binds the channel as `nvarchar`
- **Severity:** Low · **Category:** perf · **Confidence:** Plausible (index list and parameter typing confirmed; the actual plan depends on the database collation and was not captured)
- **Where:** `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs:741-742` and the untyped `@channel` parameter below it; caller `ZB.MOM.WW.ScadaBridge.AuditLog/Central/AuditLogPurgeActor.cs` `RunPerChannelOverridesAsync`
- **What's wrong:** `DELETE TOP (@batch) … WHERE Category = @channel AND OccurredAtUtc < @threshold`. The only index leading on the channel is `IX_AuditLog_Channel_Status_Occurred (Channel, Status, OccurredAtUtc)`, where `Status` sits between the two predicates, and the clustered key leads on `OccurredAtUtc` (so a clustered plan reads every other channel's rows older than the threshold, i.e. most of the table when the override is 30 days against a 365-day global window). `@channel` is created with `CreateParameter()` and a string value, so it is sent as `nvarchar` against a `varchar(32)` column; under a SQL-collation database that converts the column and rules out a seek altogether. Other statements in this repository type their parameters explicitly for this reason.
- **Failure scenario:** `AuditLog:PerChannelRetentionDays:ScriptTrace=30` (set on the rig). Each purge tick runs up to 10 batches plus a final empty one, each scanning a large part of the table or index to find 5 000 rows.
- **Suggested fix:** Bind `@channel` as `SqlDbType.VarChar` and add an index on `(Category, OccurredAtUtc)` (aligned to the partition scheme), or drive the delete from a keyset on that index.
---
## AUD-6 — Rows stamped before the first partition boundary are never purged or archived
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed (SQL); how often such rows occur is not measured
- **Where:** `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs:803-830` (`GetPartitionBoundariesOlderThanAsync`, `… = b.BoundaryId + 1`)
- **What's wrong:** The enumeration only considers the partition to the right of each boundary. Partition 1 (everything earlier than the first boundary) is never a candidate, so it is never switched out and never archived.
- **Failure scenario:** `OccurredAtUtc` is stamped by the originating node. A site node with a reset clock, or a back-dated test row, produces rows that land in partition 1. They stay in `AuditLog` past the 365-day retention indefinitely and are excluded from the cold archive.
- **Suggested fix:** Include partition 1 in the enumeration (it needs a row DELETE or a split, since it has no lower boundary to key the switch on), or clamp/reject implausibly old `OccurredAtUtc` at ingest.
---
## AUD-7 — Cached-telemetry drain does one tracking-store read (a writer-queue barrier) per audit row
- **Severity:** Low · **Category:** perf · **Confidence:** Confirmed
- **Where:** `ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs:~295-340` (`GetStatusAsync` inside the `foreach` over `pending`)
- **What's wrong:** Each pending cached row triggers its own `IOperationTrackingStore.GetStatusAsync`. That store is a single-writer queue in which every read waits for all writes queued ahead of it, so a drain of `BatchSize` rows is `BatchSize` sequential barriers through the tracking writer. Several lifecycle rows of the same operation (`Submitted`, `Attempted`, `Delivered`) each look up the same id again.
- **Failure scenario:** A backlog of cached-call rows after an outage: every 5 s drain issues hundreds of sequential tracking reads that interleave with the script-path tracking writes on the same queue.
- **Suggested fix:** Look up the distinct `CorrelationId`s of the batch once (a batched `GetStatusManyAsync`, or at least a per-drain dictionary).
## Slice: Review slice 07 — ConfigurationDatabase / DeploymentManager / TemplateEngine
HEAD `d4d5be3b`. Read-only review. Paths are relative to `src/`. Abbreviations:
`CDB` = `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase`, `DEP` = `ZB.MOM.WW.ScadaBridge.DeploymentManager`,
`TPL` = `ZB.MOM.WW.ScadaBridge.TemplateEngine`.
"Confirmed" means the code path was read end to end (callers included). Three findings (DEP-1, TPL-3, CDB-1) were
additionally checked with read-only queries against the local rig database (`ScadaBridgeConfig`). Nothing was built or run.
| ID | Severity | Category | Title |
|----|----------|----------|-------|
| TPL-1 | High | bug | A module composed into two slots runs the wrong slot's alarm on-trigger script |
| DEP-1 | High | bug | Deploy / Disable / Enable / Delete / Deploy Artifacts audit rows are staged after the last save and never written |
| TPL-2 | Medium | bug | Overriding a script in a derived template silently unhooks the base alarm that triggers it |
| TPL-3 | Medium | bug | `InstanceService` stages every audit row after its save (same root cause as DEP-1) |
| DEP-2 | Medium | bug | Lifecycle commands validate state before taking the operation lock; a Delete queued behind a first deploy orphans the instance at the site |
| DEP-3 | Medium | bug | `PerSiteStatus` is `nvarchar(4000)`; a Deploy Artifacts run over ~25 sites (or a few long errors) fails after the sites applied |
| CDB-1 | Medium | bug | Deployed snapshots and pending rows store data-connection protocol JSON in plaintext, bypassing the column encryption |
| DEP-4 | Medium | perf | Fleet staleness does 5 tracked queries per instance, and every deployment completion forces it again |
| DEP-5 | Medium | bug | One failed staging write in a bulk deploy poisons every later staging write in the batch |
| TPL-4 | Medium | perf | Single-entity operations load a whole site's instance graph or the whole template table |
| DEP-6 | Low | bug | Bulk deploy re-enables an instance disabled after the batch started |
| TPL-5 | Low | bug | Nested composition: the base pass overwrites a slot-level alarm on-trigger override |
---
## TPL-1 — A module composed into two slots runs the wrong slot's alarm on-trigger script
- **Severity:** High — **Category:** bug — **Confidence:** Confirmed (static; no existing test covers two slots)
- **Where:** `TPL/Flattening/FlatteningService.cs:888-897` (`ResolveInheritedScripts`), `:474`, `:1040-1056` (`ResolveAlarmScriptReferences`)
**What's wrong.** Alarm → script links are resolved through `scriptCanonicalById`, a `Dictionary<int, string>` keyed by
`TemplateScript.Id` and shared by the whole flatten. Composing a template creates a slot-owned derived template whose member
rows are `IsInherited` placeholders (`TemplateService.BuildDerivedTemplate`). The flattener skips placeholders when the base
has the row, so the winning script row for every slot is the **base** row, with the same Id. Each slot then writes
`scriptCanonicalById[baseScriptId] = "<slot>.<script>"`, and the last slot processed wins. `alarmScriptIds` is keyed by the
alarm's canonical name, so both slots' alarms look up the same script Id and get the same (last) canonical name.
**Failure scenario.** Template `Pump` has script `OnHigh` (Id 10) and alarm `HighTemp` with `OnTriggerScriptId = 10`.
Template `Skid` composes `Pump` as `Pump1` and `Pump2`. Flattening an instance of `Skid`:
`scriptCanonicalById[10]` is set to `Pump1.OnHigh`, then overwritten with `Pump2.OnHigh`. Both `Pump1.HighTemp` and
`Pump2.HighTemp` get `OnTriggerScriptCanonicalName = "Pump2.OnHigh"`. When pump 1 alarms, the site runs pump 2's script in
pump 2's scope (`ScriptScope.SelfPath = "Pump2"`), so it reads and writes pump 2's attributes. The name resolves to a real
script, so validation passes and the wrong value is baked into the revision hash.
**Fix.** Resolve the reference per chain instead of through a global Id map: have `ResolveInheritedAlarms` return the
on-trigger script *name* (look the Id up among the script rows of that same chain, any row with that Id or name), and set
`OnTriggerScriptCanonicalName = prefix + "." + name` at the point the composed alarm is added. Add a two-slot test.
---
## DEP-1 — Deploy / Disable / Enable / Delete / Deploy Artifacts audit rows are staged after the last save and never written
- **Severity:** High — **Category:** bug — **Confidence:** Confirmed (code + rig database)
- **Where:** `DEP/DeploymentService.cs:664` (Deploy), `:773` (DeployFailed), `:1674` (Disable), `:1738` (Enable),
`:1798`/`:1866` (Delete), `:1856` (DeleteOrphaned), `:2537`/`:2559` (lifecycle timeouts);
`DEP/ArtifactDeploymentService.cs:615` (DeployArtifacts), `:652`/`:667` (secrets audit on a refused retry), `:685` (failed retry);
root cause `CDB/Services/AuditService.cs` (`LogAsync` only adds to the change tracker)
**What's wrong.** `AuditService.LogAsync` stages the row and leaves the save to the caller. In every site listed above the
audit call comes *after* the method's final `SaveChangesAsync`, and nothing saves afterwards. These commands are not
"configuration commands", so `ManagementActor.ProcessCommand` runs them through `DispatchCommand` without the trailing
flush that `ConfigurationCommandTransaction` provides. The staged row is discarded when the DI scope is disposed.
`TemplateFolderService.cs:58-62` carries a comment describing exactly this hazard and adds the second save; these services
do not. In a bulk deploy the next instance's save happens to flush the previous instance's row, so only the last one is lost.
**Evidence on the rig DB.** 62 `DeploymentRecords` (61 Success, 1 Failed) against 16 `Deploy` audit rows and zero
`DeployFailed`; 71 `SystemArtifactDeploymentRecords` against zero `DeployArtifacts` rows; zero `Disable`, `Enable` or
`Delete` rows for `Instance` since 2026-07-20, although instance Ids run to 3876 with 14 remaining.
**Failure scenario.** An operator disables, deletes, or single-deploys an instance, or runs Deploy Artifacts. The action
succeeds and the config audit log has no record of who did it. A refused artifact retry (missing secret) writes no
`DeploySiteSecrets` row either, contrary to the documented "one row per site deploy" contract.
**Fix.** Make the audit write durable where it is issued: in `TryLogAuditAsync` (and the artifact paths) call
`SaveChangesAsync` after `LogAsync`, inside the existing try/catch so it stays best-effort. Longer term, give
`IAuditService` a "log and save" method so the ordering cannot be got wrong.
---
## TPL-2 — Overriding a script in a derived template silently unhooks the base alarm that triggers it
- **Severity:** Medium — **Category:** bug — **Confidence:** Confirmed (static)
- **Where:** `TPL/Flattening/FlatteningService.cs:861-897`, `:1040-1056`; override path `TPL/TemplateService.cs:758-840`
**What's wrong.** `TemplateAlarm.OnTriggerScriptId` on the base alarm, and on the derived placeholder copied from it
(`TemplateService.cs:1143`, `:1431`), points at the **base** script row. When a derived template overrides that script,
`UpdateScriptAsync` flips `IsInherited = false` on the derived row, which has a different Id. `ResolveInheritedScripts`
then records only the winning (derived) row's Id in `scriptCanonicalById`. The alarm still carries the base Id, the lookup
misses, and `ResolveAlarmScriptReferences` sets `OnTriggerScriptCanonicalName = null`.
**Failure scenario.** Base `Tank` has alarm `HighLevel` → script `OnHighLevel`. Derived `TankWithHeater` edits
`OnHighLevel`'s code. Every instance of `TankWithHeater` now deploys `HighLevel` with no on-trigger script. A null
on-trigger script is legal, so validation raises nothing; the alarm fires and the response script never runs.
**Fix.** In `ResolveInheritedScripts`, map the Id of *every* row with that name in the chain (base and derived) to the
canonical name, not just the winner's. The name-based resolution proposed for TPL-1 fixes this as well.
---
## TPL-3 — `InstanceService` stages every audit row after its save
- **Severity:** Medium — **Category:** bug — **Confidence:** Confirmed (code + rig database)
- **Where:** `TPL/Services/InstanceService.cs:99-102`, `:137-139`, `:188-190`, `:205-207`, `:273-275`, `:291-293`,
`:321-323`, `:374-376`, `:397-399`, `:420-422`, `:442-444`
**What's wrong.** Same root cause as DEP-1: each method calls `SaveChangesAsync` and then `LogAsync`, with no second save.
The row survives only when the caller happens to flush later: a configuration command (the transaction wrapper saves), or
a Blazor circuit whose long-lived `DbContext` saves something else afterwards. The management/CLI path for
`CreateInstance`, `SetConnectionBindings` and the single-override commands does not.
**Evidence.** The rig DB holds one `Create`/`Instance` audit row for instance Ids up to 3876, and 6
`SetConnectionBindings` rows.
**Failure scenario.** `scadabridge instance create …` followed by `instance set-bindings …` from the CLI: both succeed,
neither is audited.
**Fix.** Add the second `SaveChangesAsync` after each `LogAsync` (as `TemplateService` and `TemplateFolderService` do), or
stage the audit row before the single save where the entity Id is already known.
---
## DEP-2 — Lifecycle commands validate state before taking the operation lock
- **Severity:** Medium — **Category:** bug — **Confidence:** Confirmed code path; trigger needs two overlapping commands
- **Where:** `DEP/DeploymentService.cs:1763-1783` (Delete), same shape at `:1624-1633` (Disable), `:1694-1703` (Enable), `:280-290` (Deploy)
**What's wrong.** Each command loads the instance, runs `StateTransitionValidator`, and only then waits (up to
`OperationLockTimeout`, 5 s) for the per-instance lock. After acquiring it, the code keeps using the entity it loaded
before the wait. `DeleteInstanceAsync` branches on that stale `instance.State`.
**Failure scenario.** Instance X is `NotDeployed`. A deploy of X is in flight and holds the lock. A Delete arrives (second
operator, a second tab, or a teardown script), loads X as `NotDeployed`, and waits. The deploy completes: the site is
running X and central marks it `Enabled`. The Delete gets the lock, sees the stale `NotDeployed`, skips the site
round-trip (`:1783`), and removes the central record and its deployment rows. X keeps running at the site with no central
record.
**Fix.** Re-read the instance (state at minimum, with `AsNoTracking` or a reload) after the lock is acquired and run the
transition check on that copy.
---
## DEP-3 — `PerSiteStatus` is `nvarchar(4000)`
- **Severity:** Medium — **Category:** bug — **Confidence:** Confirmed (static; size measured on the rig)
- **Where:** `CDB/Configurations/DeploymentConfiguration.cs:116-117`; written at `DEP/ArtifactDeploymentService.cs:572-582`
**What's wrong.** `DeployCoreAsync` serializes every site's `SiteArtifactResult` (identifier, name, error message, removed
secret names) into `SystemArtifactDeploymentRecord.PerSiteStatus`, which is capped at 4000 characters. On the rig, three
all-success sites serialize to 466 characters (~155 per site). The save is not guarded, and it runs *after* every site has
applied the artifacts and *before* `StampArtifactRevisionAsync`.
**Failure scenario.** A fleet of about 25 sites, or fewer with long error text (the missing-secret message lists every
referencing connection; exception messages are stored verbatim). All sites apply. `SaveChangesAsync` throws "String or
binary data would be truncated". The command returns an internal error, no site is stamped (all read *Out of date*), the
staged `DeploySiteSecrets` audit rows in the same save are lost, and every later run fails the same way.
**Fix.** Make the column `nvarchar(max)` (migration), and wrap the record save so a failure there cannot skip the stamping.
---
## CDB-1 — Deployed snapshots and pending rows store data-connection protocol JSON in plaintext
- **Severity:** Medium — **Category:** bug (data protection) — **Confidence:** Confirmed (code + rig database); design intent not documented
- **Where:** `TPL/Flattening/FlatteningService.cs:115-123`; persisted by `DEP/DeploymentService.cs` `StagePendingDeploymentAsync` (`:529`) and `StoreDeployedSnapshotAsync`; encryption defined in `CDB/DataConnectionSecretConverter.cs`
**What's wrong.** `DataConnection.PrimaryConfiguration` / `BackupConfiguration` are encrypted at rest
(`dp:protocol:v1:` — "complete protocol JSON, including nested credentials"). The flattener copies the decrypted JSON into
`FlattenedConfiguration.Connections`, and that object is serialized as-is into `PendingDeployments.ConfigurationJson` and
`DeployedConfigSnapshots.ConfigurationJson`, both plain `nvarchar(max)`. It is also returned in the deployment comparison diff.
**Evidence.** On the rig, `DataConnections.PrimaryConfiguration` starts with `dp:protocol:v1:`, while 3 of 10
`DeployedConfigSnapshots` contain a `Connections` object whose `ConfigurationJson` has the full key set, including
`userIdentity`.
**Failure scenario.** A connection configured with an inline username/password (not a `secret:` reference). After the
first deploy of any instance bound to it, the credentials sit in plaintext in two tables, readable by anyone with database
read access or a backup, which is what the column encryption was added to prevent.
**Fix.** Run the same protector over the `ConfigurationJson` columns of both tables (value converter), or strip
`Connections` from the persisted snapshot and keep only a digest for hashing and diffing.
---
## DEP-4 — Fleet staleness does 5 tracked queries per instance
- **Severity:** Medium — **Category:** perf — **Confidence:** Confirmed (static)
- **Where:** `DEP/FlatteningPipeline.cs:194` → `CDB/Repositories/TemplateEngineRepository.cs:493-502`; loop at
`DEP/DeploymentService.cs:2071-2110`; forced re-evaluation in `DEP/PendingUpdates/PendingUpdatesCache.cs` (`OnDeploymentStatusChanged`)
**What's wrong.** `GetInstanceStalenessAsync` calls `ComputeRevisionHashAsync` per instance, and each call loads the
instance with four `Include`s under `AsSplitQuery`: five round-trips, tracked, serially. The flatten session memoises
templates but not instances. Nothing is detached, so the evaluator's context ends up tracking every deployed instance and
every override and binding row in the fleet. The bulk-deploy pre-filter (`:1352`) does the same per instance and
`PrepareDeploymentAsync` then loads each deployable instance again.
The short-circuit token avoids this when nothing changed, but every terminal deployment status invalidates the memo and
forces a full evaluation, so the cost is paid repeatedly during and after bulk deploys.
**Failure scenario.** 1,000 deployed instances with a few hundred bindings each: about 5,000 round-trips and several
hundred thousand tracked entities per full evaluation, re-run on the next poll after each deployment completes.
**Fix.** Add a batched, `AsNoTracking` instance loader (one split query per chunk of ids) and feed the pipeline from it for
the read-only hash path; let the session hold the loaded instances so the pre-filter and prepare share one load.
---
## DEP-5 — One failed staging write in a bulk deploy poisons every later staging write
- **Severity:** Medium — **Category:** bug — **Confidence:** Plausible (cascade confirmed by reading; the trigger is a race or DB fault)
- **Where:** `DEP/DeploymentService.cs:493-545` (`StageAndSendDeploymentAsync` / `StagePendingDeploymentAsync`), `:1468-1520` (`SendPreparedAsync`);
`CDB/Repositories/DeploymentManagerRepository.cs:404-427`, `:514` (`RemovePendingByKey`)
**What's wrong.** Two things combine.
1. `AddPendingDeploymentAsync` reads the prior pending row Ids for the instance, then attaches a key-only stub per Id and
marks it Deleted. If `PendingDeploymentPurgeActor` (an `ExecuteDelete` of expired rows) or `ReconcileService` removes
one of those rows before the save, the save throws `DbUpdateConcurrencyException`.
2. In phase 2 all instances stage through the one scoped `DbContext` (serialised by `dbGate`). When a staging save
throws, the exception is turned into that instance's outcome but the failed Added row and Deleted stub stay tracked.
Every later instance's staging save re-attempts them and fails the same way. The P7-5 detach
(`MarkDeploymentFailedAsync`) only runs in phase 3, after all staging is over.
**Failure scenario.** A 200-instance site deploy. Instance 12's staging save loses the race with the purge tick. Instances
13–200 all fail staging with the same concurrency error and are reported failed, although nothing was wrong with them.
The single-instance path fails just that one deploy with a confusing "expected to affect 1 row" message.
**Fix.** Delete prior rows with `ExecuteDeleteAsync` (`WHERE InstanceId = @id`) instead of tracked stubs, and in
`StageAndSendDeploymentAsync` call `DetachPendingChanges()` (under `dbGate`) when the staging save throws.
---
## TPL-4 — Single-entity operations load a whole site's instance graph or the whole template table
- **Severity:** Medium — **Category:** perf — **Confidence:** Confirmed (static)
- **Where:**
- `TPL/Services/AreaService.cs:191` and `TPL/Services/SiteService.cs:96` → `CDB/Repositories/TemplateEngineRepository.cs` `GetInstancesBySiteIdAsync` (tracked, 4 `Include`s)
- `TPL/Services/InstanceService.cs:250` (`SetAlarmOverrideAsync`), `TPL/TemplateService.cs:231` (`MoveTemplateAsync`), `:452` / `:679` / `:856` (`DeleteAttribute` / `DeleteAlarm` / `DeleteScript`) → `GetAllTemplatesForAnalysisAsync`
**What's wrong.** Deleting an area or a site loads every instance of the site with all attribute overrides, alarm
overrides, connection bindings and native-alarm overrides, tracked, only to test `AreaId` membership or `Count > 0`.
Setting one alarm override, moving one template between folders, or deleting one member loads every template in the system
with all attributes, alarms, compositions and native sources. The neighbouring methods (`UpdateAttributeAsync`,
`AddAttributeAsync`) already use the bounded `GetTemplateAnalysisClosureAsync`.
**Failure scenario.** Deleting an empty area on a site with 1,000 instances materialises and tracks the whole site's
override and binding rows. A bulk CLI run that sets alarm overrides on N instances reloads the full template table N times.
**Fix.** Use `ISiteRepository.GetInstancesBySiteIdAsync` (no includes) or an `AnyAsync`/projection for the area and site
checks; switch the template call sites to `GetTemplateAnalysisClosureAsync`, and make the folder-move collision check a
`(FolderId, Name)` existence query.
---
## DEP-6 — Bulk deploy re-enables an instance disabled after the batch started
- **Severity:** Low — **Category:** bug — **Confidence:** Plausible
- **Where:** `DEP/DeploymentService.cs:982` (tracked site load), `:1018-1034` (Disabled filter), `:280-285` (`PrepareDeploymentAsync`), `:657` (`forceEnabledState: true`)
**What's wrong.** The batch loads the site's instances tracked, once. `PrepareDeploymentAsync` later re-queries each
instance through the same `DbContext`; EF identity resolution returns the already-tracked entity with its old `State`.
A Disable committed by another request after the initial load is therefore invisible to both the Disabled filter and the
transition check.
**Failure scenario.** A forced (or out-of-date) site deploy of several hundred instances is in its serial prepare phase.
An operator disables instance X, which the batch has not reached yet. The batch reaches X, sees `Enabled`, deploys it and
finalises with `forceEnabledState: true`. X is running again, which is the outcome the P7-2 "bulk deploy never re-enables"
rule exists to prevent.
**Fix.** Load the candidate list with `AsNoTracking`, and re-check the state from a fresh read inside
`PrepareUnderLockAsync` (the same reload DEP-2 needs).
---
## TPL-5 — Nested composition: the base pass overwrites a slot-level alarm on-trigger override
- **Severity:** Low — **Category:** bug — **Confidence:** Plausible (static)
- **Where:** `TPL/Flattening/FlatteningService.cs:470-475` (unconditional write to `alarmScriptIds`), `:571-592` (descent into every template of the composed chain)
**What's wrong.** `ResolveComposedAlarmsRecursive` descends into the nested compositions of *every* template in the
composed chain, so a nested slot is visited twice under the same prefix: once through the slot-derived template and once
through its base. The `alarms` dictionary is protected by "first wins", but `ResolveInheritedAlarms` writes
`alarmScriptIds[canonical]` unconditionally on both passes, so the base pass's value replaces (or re-adds) what the derived
pass decided.
**Failure scenario.** `Skid` composes `Pump` as `Pump1`; `Pump` composes `Motor` as `Motor`. On the slot-derived
`Pump1.Motor` template the alarm `Overload` is overridden to clear its on-trigger script (or point at another one). The
derived pass records no script; the base pass then sets `alarmScriptIds["Pump1.Motor.Overload"]` to the base script. The
deployed alarm keeps the overridden trigger settings but runs the base's script.
**Fix.** Only record the script Id when the alarm row from that pass is the one actually added to `alarms` (move the
`alarmScriptIds` write next to the `ContainsKey` check), which the per-chain resolution proposed in TPL-1 does naturally.
## Slice: Review 08 — Transport / ManagementService / CLI
Scope: `src/ZB.MOM.WW.ScadaBridge.Transport/`, `src/ZB.MOM.WW.ScadaBridge.ManagementService/`, `src/ZB.MOM.WW.ScadaBridge.CLI/` at HEAD d4d5be3b. Read-only review; nothing was built or run, so every finding is from reading the code path (callers and the repository methods they depend on included). Paths are relative to `src/`. Short names: `MA` = `ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs`, `BI` = `ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs`, `AD` = `ZB.MOM.WW.ScadaBridge.Transport/Import/ArtifactDiff.cs`, `CLI/` = `ZB.MOM.WW.ScadaBridge.CLI/`.
Counts: 2 High, 12 Medium, 7 Low (21 total; 19 bug, 2 perf).
Checked and found sound (not findings): actor `Sender` is captured before `PipeTo` (`MA:130-152`); the deployment-config token compare is constant-time and unknown/expired rows 404; site scope is enforced on every instance/area/site-relayed handler I traced, including fleet-wide artifact deploy and the unfiltered list paths; the import transaction sits inside the EF execution strategy with post-commit actions after commit; CLI token handling (in-memory only, keyed on URL + user + password hash, no cross-server reuse) and its exit codes for deploy/approve/verify.
---
## High
### MGT-1 — Audit rows for API-key, shared-schema, external-system-method and move-data-connection commands are never saved
- **Severity:** High · **Category:** bug · **Confidence:** Confirmed
- **Where:** `MA:160-167` (dispatch), `MA:212-226` (`IsConfigurationCommand`), `MA:3034`, `3051`, `4103`, `4119` (API keys), `MA:2523`, `2540`, `2550` (external-system methods), `MA:3753`, `3778`, `3790` (shared schemas), `MA:2381` (move data connection); `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Services/AuditService.cs:50-52`; `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Services/ConfigurationCommandTransaction.cs:22`.
- **What's wrong:** `AuditService.LogAsync` only adds the row to the change tracker ("caller is responsible for calling SaveChangesAsync"). For commands in `IsConfigurationCommand`, `ConfigurationCommandTransaction` does a final `db.SaveChangesAsync()` that flushes it. The commands listed above are not in that list, so `ProcessCommand` runs them through plain `DispatchCommand`, and each handler calls `AuditAsync` after its last `SaveChangesAsync` (or after a repository/key-store call that saves internally). The scope is then disposed with the audit row still unsaved.
- **Failure scenario:** an Administrator runs `security api-key create`, `delete`, `update` or `set-methods`. The key changes, the CLI reports success, and no `AuditLogEntries` row exists for it. The same happens for shared-schema create/update/delete, external-system method create/update/delete and `data-connection move`. The unit tests mock `IAuditService` and only assert `LogAsync` was called, so they pass.
- **Fix:** add these commands to `IsConfigurationCommand` (so the transaction wrapper flushes the audit row), or have `AuditAsync` save when no configuration transaction is active. Add one test per family against a real context asserting the row exists.
### TRN-1 — Notification-list Overwrite appends recipients instead of replacing them
- **Severity:** High · **Category:** bug · **Confidence:** Confirmed
- **Where:** `BI:4205`, `BI:4222-4231`, `BI:1665`; `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationRepository.cs:32-33`.
- **What's wrong:** `GetListByNameAsync` is `FirstOrDefaultAsync(l => l.Name == name)` with no `.Include(n => n.Recipients)` (the get-all and by-id siblings include it). Apply clears the change tracker at the start of each attempt, and there is no lazy loading, so `existing.Recipients.Clear()` runs on an empty, unloaded collection and deletes nothing. The bundle's recipients are then added on top.
- **Failure scenario:** target list has recipients A and B; the bundle's list has A and C. After Overwrite the list holds A, B, A, C. B keeps receiving notifications, A gets each one twice, and every re-import adds another copy.
- **Fix:** load the list with its recipients before the clear (add the Include to `GetListByNameAsync`, or use the bulk `GetAllNotificationListsAsync` lookup that preview already uses).
---
## Medium
### TRN-2 — A changed secret-bearing value reads Identical and is force-skipped; an unrelated Overwrite replaces it unseen
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `AD:240-247` (external-system `AuthConfiguration`), `AD:279-286` (DB `ConnectionString`), `AD:348-354` (SMTP), `AD:382-388` (SMS), `AD:483-490` (data-connection primary/backup configuration); skip mapping at `MA:4661` and `ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor:459-463`.
- **What's wrong:** presence-only diffing of secrets is documented, but its consequence is not handled. For a data connection the "secret" is the whole protocol configuration, and for a DB connection the whole connection string. If only that value changed, the row classifies as Identical, and both the CLI and the UI resolve Identical to Skip.
- **Failure scenario A:** the source environment changes an OPC UA endpoint URL. Preview says Identical, the import skips it, and the change can never be promoted through a bundle.
- **Failure scenario B:** only `FailoverRetryCount` differs. The row shows as Modified with that one field; the operator picks Overwrite, and the target's protocol configuration is replaced by the source environment's with no diff row showing it.
- **Fix:** compare the values at preview (the decrypted DTO is available in the session) and emit a value-free "changed" marker so the row classifies as Modified.
### TRN-3 — Preview ignores the site/connection name map
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `BI:631-648`, `684-690`, `840-845`, `948-964` (all resolve against the source site identifier); `BI:4762-4777`; `MA:4630-4645`, `MA:4746-4755`.
- **What's wrong:** `PreviewAsync` takes no `BundleNameMap`, so connection diffs, `AutoMatchTargetName` and the "connection unresolved" blocker are computed against the identity-matched site, never the mapped one. `HandleImportBundle` aborts on any blocker before it builds the name map. Separately, apply creates a connection when `action == CreateNew || existing is null` without checking whether a same-name row already exists on the target site.
- **Failure scenario A:** an instance-only bundle for `site-a` is imported with `--map-site site-a=site-x`, where `site-x` already has the bound connection `OPC1`. Preview emits a blocker for the unresolved connection and the import is refused; no mapping can clear it.
- **Failure scenario B:** the bundle carries `site-a/OPC1`, the site is mapped to `site-x` (which has `OPC1`), and `--create-missing-connections` is passed. Auto-match is null, the mapping becomes CreateNew, apply inserts a second `OPC1` under `site-x`, the unique `(SiteId, Name)` index rejects it, and the whole import rolls back with an internal error.
- **Fix:** let preview and the required-mapping computation take the site map (or re-run them after mapping), and treat CreateNew against an existing same-name connection as map-to-existing or a clear validation error.
### TRN-4 — Template Overwrite leaves compositions in place when the bundle template has none
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `BI:3349` (`if (dto.Compositions.Count == 0) continue;`), ahead of the clear at `BI:3376-3393`; diff side `AD:174-181`.
- **What's wrong:** the early exit runs before the code that removes existing composition rows, so a bundle template with zero compositions never clears the target's. The diff does report the removals.
- **Failure scenario:** target `Pump` composes `Motor`; the source removed all compositions. Preview shows the composition being removed, the operator overwrites, and the slot is still there. The row stays Modified on every later import.
- **Fix:** skip only when the template is not an Overwrite of an existing row; otherwise fall through to the clear with an empty add set.
### TRN-5 — Composition rewire deletes slot rows without their derived templates
- **Severity:** Medium · **Category:** bug · **Confidence:** Plausible (code path confirmed; downstream impact not exercised)
- **Where:** `BI:3378-3392` (`DeleteTemplateCompositionAsync(existing.Id)`); compare `ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs:1076-1082`, which also deletes the slot-owned derived template.
- **What's wrong:** there is no database relationship on `OwnerCompositionId`, so nothing cascades or rejects the delete.
- **Failure scenario:** the target owner has slot `S1` with a derived template; the bundle owner has only `S2`. Overwrite deletes the `S1` composition row and leaves its derived template behind with a dangling `OwnerCompositionId` and a live `ParentTemplateId`, which then blocks deleting the base template.
- **Fix:** route these deletes through `TemplateService.DeleteCompositionAsync` or replicate its derived-template cascade.
### TRN-6 — Instance diff ignores the bound connection and compares a field apply never writes
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `AD:571-581` (binding equality is `DataSourceReferenceOverride` only), `AD:537` (`State`); apply at `BI:5050`, `BI:5129`.
- **Failure scenario A:** the source rebinds an instance's attributes from `OPC1` to `OPC2`, both present on the target. The instance reads Identical, is skipped, and the rebind never lands.
- **Failure scenario B:** the source instance is Disabled and the target is Enabled with identical configuration. Only `State` differs, so an Overwrite policy replaces the children and forces the live instance to NotDeployed for no configuration change.
- **Fix:** resolve the existing `DataConnectionId` to a name at preview and compare it; drop `State` from the diff.
### TRN-7 — Site-scoped import lookups are ordinal while the database is case-insensitive
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** connections `BI:687`, `4759-4760`, `4839-4840`, `5383`; instances `BI:706`, `4972`; areas `BI:5095`; template references `BI:3424-3431`, `3517-3523`, `4991`, `2211`.
- **What's wrong:** templates, folders and members were moved to the case-insensitive `ToNameLookup`; these lookups were not.
- **Failure scenario A:** the target has connection `OPC1` (or instance `pump1`) and the bundle has `Opc1` (or `Pump1`). Preview says New, apply inserts, the unique index rejects it, and the import rolls back with a raw SQL error.
- **Failure scenario B:** bundle base `PumpBase` overwrites target `pumpbase`. The child's base-template name misses both lookups and `ParentTemplateId` is set to null (`BI:3529`) with only an audit row.
- **Fix:** use `OrdinalIgnoreCase` (via `ToNameLookup`) for these, preferring an exact match where two candidates exist.
### MGT-2 — `/api/audit/query`, `/export` and `/tree` scope by numeric site id against a column that holds the site identifier
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `ZB.MOM.WW.ScadaBridge.ManagementService/AuditEndpoints.cs:598-621` (`ApplySiteScope`), `:305-307` (`HandleTree`); compare `ZB.MOM.WW.ScadaBridge.ManagementService/FlowDebug/FlowDebugRunner.cs:782-797`, which translates the ids first.
- **What's wrong:** `AuthenticatedUser.PermittedSiteIds` are numeric site ids as strings (the same values `MA` compares to `site.Id.ToString()`). `AuditLog.SourceSiteId` holds the site identifier (for example `site-a`). `ApplySiteScope` puts the numeric ids straight into `SourceSiteIds`, and `HandleTree` passes them to `GetExecutionTreeAsync`. `ApplySiteScope` also has no Administrator exemption, unlike every other scope check.
- **Failure scenario:** a user who is Viewer (or Administrator) and also in a site-scoped Deployer group runs `audit query`. The filter becomes `SourceSiteId IN ('3')` and returns nothing, always. `audit tree` for the same Viewer returns only central rows and drops every site row. An explicit `--site site-a` filter intersects to empty and returns 403. It fails closed, unless a site's identifier happens to equal another site's numeric id.
- **Fix:** resolve the permitted ids to site identifiers before filtering (reuse the `FlowDebugRunner` helper) and exempt Administrator as the other paths do.
### MGT-3 — A Designer can read SMTP, SMS and other stored secrets through bundle export
- **Severity:** Medium · **Category:** bug (authorization) · **Confidence:** Confirmed
- **Where:** `MA:346` (`ExportBundleCommand => DesignerOnly`), `MA:295-301` (SMTP/SMS updates Admin-only "otherwise a Designer … could still rotate a production credential"), `MA:4443-4465`; `ZB.MOM.WW.ScadaBridge.Transport/Export/BundleExporter.cs:153-165`.
- **What's wrong:** export is documented as a Design-role operation "because it only reads", and unencrypted export is documented too. But the read includes the SMTP credentials and the Twilio auth token, which the management API otherwise never returns to anyone (`SmtpConfigPublicShape` / `SmsConfigPublicShape`) and only lets an Administrator write. The passphrase is chosen by the exporter, or omitted.
- **Failure scenario:** a Designer runs `bundle export --all` with no passphrase (or their own) and reads the SMTP password, Twilio token, external-system auth configuration and database connection strings from `content.json`. The only trace is an `UnencryptedBundleExport` / `BundleExported` audit row.
- **Fix:** require Administrator when the selection includes SMTP or SMS configurations (or any secret block), or strip secret blocks from non-Administrator exports. This contradicts a documented role assignment, so it needs an owner decision.
### MGT-4 — `data-connection move` returns the unscrubbed connection
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `MA:2381-2382` (`AuditAsync(..., conn); return conn;`); every sibling handler uses `DataConnectionPublicShape` (`MA:2146-2161`).
- **What's wrong:** the handler returns the raw `DataConnection` entity, so `PrimaryConfiguration` and `BackupConfiguration` reach the caller with passwords and tokens intact. The same raw entity is passed as the audit after-state (currently unsaved because of MGT-1; fixing MGT-1 alone would start writing those secrets to the audit table).
- **Failure scenario:** `data-connection move --id 7 --target-site 2` prints the connection's stored credentials to the terminal and any CI log, where `data-connection get` prints the redaction sentinel.
- **Fix:** return and audit `DataConnectionPublicShape(conn)`.
### CLI-1 — Site-relayed commands exit 0 when the reply says `success: false`
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed
- **Where:** `CLI/Commands/CachedCallCommands.cs:48-53`, `62-67`; `CLI/Commands/ConnectionBrowseCommands.cs:68-69` (used by `certs trust` and `certs remove`); server `MA:1456-1472`, `MA:4271-4287`.
- **What's wrong:** these use the default `ExecuteCommandAsync` path, which returns 0 for any 2xx body. The server returns the site's `ParkedMessageRetryResponse` / `CertTrustResult` unchanged as a 200, with failure carried in `Success`.
- **Failure scenario:** `cached-call retry` for an id that is not parked, or `certs trust` that lands on only one of the two site nodes, prints `"success": false` and exits 0. A script treats it as done and the two nodes' trust stores stay inconsistent.
- **Fix:** add a success handler (as `deploy site` and `secured-write approve` have) that reads `success` and returns 1 with the error text.
### CLI-2 — Update commands silently null or default every option that was not passed
- **Severity:** Medium · **Category:** bug (data loss) · **Confidence:** Confirmed
- **Where:** `CLI/Commands/SiteCommands.cs:91-123` → `MA:2069-2074`; `CLI/Commands/DataConnectionCommands.cs:61-93` → `MA:2242-2244`; `CLI/Commands/ApiMethodCommands.cs:126-158` → `MA:3978-3981`.
- **What's wrong:** the options are optional and the server assigns every field unconditionally. `MergeSentinels(null, stored)` returns null, `--failover-retry-count` defaults to 3 and `--timeout` to 30. The README describes these as whole-entity replace, but `--help` does not, nothing warns, and sibling updates (`template`, `external-system`, `db-connection`, `notification smtp`) preserve omitted fields.
- **Failure scenario:** `site update --id 3 --name "Plant 3"` nulls both gRPC addresses and central can no longer dial the site. `data-connection update --id 7 --name X --protocol OpcUa` wipes the primary and backup configuration including credentials. `api-method update --id 5 --script …` resets a 120 s timeout to 30 and drops the parameter and return definitions.
- **Fix:** make the replaced options required, or switch to preserve-if-null (nullable command fields and `if (cmd.X is not null)` on the server).
### CLI-3 — Number and date options parse with the machine's culture
- **Severity:** Medium · **Category:** bug · **Confidence:** Confirmed (the sub-review probed System.CommandLine 2.0.5 under `de-DE`)
- **Where:** `CLI/Commands/TemplateCommands.cs:696-704` (`--min`, `--max`, `--lolo`, `--lo`, `--hi`, `--hihi`, `--threshold-per-second`, `--window-seconds`); `CLI/Commands/AuditLogCommands.cs:72-73`; `CLI/Commands/HealthCommands.cs:75-76`.
- **Failure scenario:** on a comma-decimal workstation, `template alarm add --trigger-type HiLo --hi 80.5` parses without error as 805 and stores that setpoint. `audit-config query --from 2026-11-01T00:00:00` is read as local time, while `audit query --since` assumes UTC.
- **Fix:** set the invariant culture at the top of `Program.cs`, or give these options invariant custom parsers with `AssumeUniversal`.
### CLI-4 — `audit export` aborts after 30 s without a first byte or between flushes
- **Severity:** Medium · **Category:** bug · **Confidence:** Plausible (depends on data volume)
- **Where:** `CLI/Commands/AuditExportHelpers.cs:120`, `131`, `164-165`, `271`; server flush points `ZB.MOM.WW.ScadaBridge.ManagementService/AuditEndpoints.cs:440-493` and `AuditExportParquet.cs:83-100`.
- **What's wrong:** the headers and inactivity deadlines are both fixed at the 30 s connect timeout with no flag or environment override. The server sends nothing until the first 1,000-row page is read (CSV/JSONL) or a full 10,000-row row group is built (Parquet).
- **Failure scenario:** a selective filter (`--actor`, `--target`) over a long window, or a Parquet export of large inbound rows, takes over 30 s to produce the first page. The CLI prints `TIMEOUT`, and a retry fails the same way.
- **Fix:** add `--timeout-seconds` with a default in minutes for both phases; optionally flush response headers before the first query.
### MGT-5 — Bundle export loads every template and every instance to resolve names, then loads each selected item again one by one
- **Severity:** Medium · **Category:** perf · **Confidence:** Confirmed
- **Where:** `MA:4383-4396`; `ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs:90-93`, `505-514`; `ZB.MOM.WW.ScadaBridge.Transport/Export/DependencyResolver.cs:39-93`.
- **What's wrong:** `HandleExportBundle` calls `GetAllTemplatesAsync()` (the full tracked template graph with all child collections and script bodies) and `GetAllInstancesAsync()` (every instance with four child collections) on every export, only to map names to ids. `DependencyResolver` then issues one `Get…ByIdAsync` per selected template, shared script, external system, database connection, notification list and API method.
- **Failure scenario:** `bundle export --templates PumpBase` on a system with thousands of instances materialises the whole instance table and template library as tracked entities while holding the single-flight transport gate. `--all` adds a per-item query for each template on top.
- **Fix:** resolve names with id/name projections (`GetTemplateStubsAsync` already exists) and batch-load the selected rows with `Contains`.
---
## Low
### TRN-8 — Imported areas are matched by leaf name across the whole site and created at the root
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `BI:5094-5108`.
- **What's wrong:** the bundle carries only `AreaName`; apply takes the first area in the site with that name and creates misses with no parent. The same leaf name under two parents is legal.
- **Failure scenario:** `Line1/Cell` and `Line2/Cell` both exist; an instance exported from `Line2/Cell` lands in whichever `Cell` comes back first. A missing nested area is recreated at the site root.
- **Fix:** carry and resolve an area path; until then treat an ambiguous leaf name as a warning or blocker.
### TRN-9 — Rename resolutions do nothing useful for sites, data connections, SMTP and SMS configurations
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `BI:4596-4609`, `BI:4784-4798` (Rename treated as Skip); `BI:4298-4307`, `BI:4384-4393` (Rename mangles the key); `MA:4665-4667`; `ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs:92-95`.
- **Failure scenario:** `bundle import --conflict-policy rename` with a modified SMTP configuration inserts a second row whose host is `smtp.example.com-imported-20261202-101500` (for SMS, a mangled `AccountSid`). Delivery always uses the lowest-id row, so the import reports "Renamed: 1" while the imported settings are never used and a junk row remains. For a modified site or data connection, Rename is counted as Skipped and nothing is written.
- **Fix:** reject Rename for these entity types in validation (and hide it in the UI), mapping the CLI policy to Skip with a warning.
### TRN-10 — Import derives the bundle key with an unbounded iteration count taken from the manifest
- **Severity:** Low · **Category:** bug (denial of service, Administrator-only) · **Confidence:** Confirmed
- **Where:** `ZB.MOM.WW.ScadaBridge.Transport/Encryption/BundleSecretEncryptor.cs:88`, `105-108`; `BI:258-262`; `ZB.MOM.WW.ScadaBridge.Transport/TransportOptionsValidator.cs:60` (floor on export only).
- **What's wrong:** `Decrypt` passes `metadata.Iterations` from the uploaded manifest straight to PBKDF2 with no upper bound.
- **Failure scenario:** a bundle whose manifest says `iterations: 2147483647` pins a thread for tens of minutes on preview or import. The HTTP call times out at 5 minutes, but the handler keeps the transport gate, so every other export, preview and import on that node queues behind it.
- **Fix:** reject manifests whose iteration count is outside a sane range (for example 100,000 to 10,000,000) before deriving the key.
### TRN-11 — Per-item queries in the import apply and validation loops
- **Severity:** Low · **Category:** perf · **Confidence:** Confirmed
- **Where:** `BI:3789`, `3848`, `4144`, `4205`, `4449` (one by-name query per bundled row, Skip included); `BI:4097-4100`; `BI:5382` (site connections re-read per reference); `ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.Derived.cs:210-221`, `235-264` (`t.Name.ToLower() == lower`, twice per derived template); `BI:2229-2232`; `BI:5094`.
- **Failure scenario:** a full-environment bundle with a few hundred derived templates and a few thousand instances issues thousands of round trips inside one transaction; the `ToLower()` comparison cannot use the name index.
- **Fix:** bulk-load each library once per apply as preview does, memoise connections and areas per site, and drop `ToLower()` in favour of plain equality under the case-insensitive collation.
### CLI-5 — `bundle export` overwrites the destination first and exits 0 on a size mismatch
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `CLI/Commands/BundleCommands.cs:168-181`, `448-469`.
- **What's wrong:** the output is opened with `FileMode.Create` before the first chunk is decoded, a decode failure leaves the partial file, and the written byte count is printed beside the server's count but never compared. The output path is also only opened after the multi-minute server export, so a bad path throws an unhandled exception at the end.
- **Failure scenario:** re-exporting over last week's good bundle with a truncated response destroys the good file and can still exit 0.
- **Fix:** check the path up front, write to a temporary file, compare the counts, then move it into place; delete the temporary file and return 1 on any failure.
### CLI-6 — User errors and bodyless HTTP errors surface as stack traces or an empty message
- **Severity:** Low · **Category:** bug · **Confidence:** Confirmed
- **Where:** `CLI/ManagementHttpClient.cs:452-473` (and the three copies at `:397`, `:506`, `:563`); `CLI/Commands/NotificationCommands.cs:358-363`; `CLI/TriggerConfigJson.cs:40`, `47`; `CLI/Commands/BundleCommands.cs:219`, `376`; `CLI/Commands/AuditQueryHelpers.cs:73`.
- **Failure scenario:** a 307 from an http→https redirect or a bodyless 502 prints `{"error": "", "code": "ERROR"}` with no status. Malformed `--trigger-config` JSON, `notification sms update` with neither sender option, an unreadable bundle file, or `--since 99999999999d` each throw an unhandled exception instead of the JSON error envelope (exit code is still 1).
- **Fix:** synthesise `HTTP {status} {reason}` when the error text is empty, and wrap these input paths in the existing `OutputFormatter.WriteError` pattern.
### CLI-7 — `debug stream` goes silent if the re-subscribe after a reconnect fails
- **Severity:** Low · **Category:** bug · **Confidence:** Plausible (not exercised live)
- **Where:** `CLI/Commands/DebugCommands.cs:225-229`.
- **What's wrong:** the `Reconnected` handler returns the `SubscribeInstance` invocation without catching its failure, and that failure never reaches the exit signal.
- **Failure scenario:** after a central failover the reconnect lands on a node that rejects the subscribe. The CLI prints "Reconnected. Re-subscribing..." and then nothing, with no non-zero exit for a supervising script.
- **Fix:** catch the failure, write a `SUBSCRIBE_FAILED` error and complete the exit signal with 1.
---
## Noted but not counted
- **Deploy commands have no client deadline** (`CLI/Commands/CommandHelpers.cs:95-98`): `Timeout.InfiniteTimeSpan` for the four deploy commands. The code comment says this is deliberate ("the server bounds the operation"), so it is not listed as a finding; the cost is that a half-open connection hangs a CI job indefinitely.
- **`DebugStreamHub` role check is case-sensitive** (`ZB.MOM.WW.ScadaBridge.ManagementService/DebugStreamHub.cs`, `user.Roles.Contains(Roles.Deployer)`), where every other gate uses `OrdinalIgnoreCase`. It only matters if a role-mapping row stores a non-canonical casing.
- **`HandleCreateInstance` calls `AuditAsync` after `InstanceService` already audited** (`MA:1030`). It is currently harmless only because of MGT-1 (the second row is never saved); fixing MGT-1 globally would turn it into a duplicate audit row, so remove the call.
- **`BuildNameMap` throws on duplicate `--map-site` / `--map-connection` entries** (`MA:4703-4708`): `ToDictionary` raises `ArgumentException`, which surfaces as an opaque internal error rather than a validation message.
## Slice: Review slice 09 — Host / InboundAPI / NotificationOutbox / NotificationService / ExternalSystemGateway / Security / DelmiaNotifier
HEAD `d4d5be3b`. Read-only review. Paths are relative to `src/`.
**Coverage.** Read in full: the InboundAPI endpoint, filter, standby forwarder, relay provenance, script executor, audit middleware, DB helper and route helper; the outbox actor and both delivery adapters (plus the outbox repository's `GetDueAsync`/`UpdateAsync` as callers); all of NotificationService; all of ExternalSystemGateway; the three gRPC auth interceptors, `SitePskProvider`, `LeaderAutoDowningProvider`, `ShutOutRestart`, `ClusterBootstrapCoordinator`, listener isolation and cache-invalidation plumbing in Host; the Security session, JWT, throttle and role-mapping classes; all of DelmiaNotifier.
Only skimmed or grepped: `AkkaHostedService.cs`, `Program.cs`, `StartupValidator.cs`, `SiteLocalDbSetup.cs`, `SiteLocalDbLegacyMigrator.cs`, `SecretsRegistration.cs`, `InboundScriptLogger.cs`, the KPI sample source.
**Checked and found sound (no finding).** The PSK comparisons in all three interceptors are constant-time and fail closed. Every `CentralControlService` RPC is unary, so the per-request site-ownership check covers all of them. `LeaderAutoDownBase` matches the Akka `AutoDown` logic it ports. The relay proof is MAC-verified before the body is read and is single-use. The gRPC, health and metrics listeners are isolated by port. No sync-over-async or `new HttpClient` per call in the server projects.
| ID | Severity | Category | Title |
|----|----------|----------|-------|
| NTF-1 | Medium | bug | A delivered notification is re-sent after failover because its state write is cancelled by the shutdown token |
| NTF-2 | Medium | bug | SMTP connection drops and OAuth2 token-endpoint outages are parked as permanent |
| DLM-1 | Medium | bug | A powered-off central node yields `OUTCOME_UNKNOWN` instead of failing over to the next URL |
| ESG-1 | Low | bug | A connection lost while reading the response body escapes transient/permanent classification |
| INB-1 | Low | bug | The method timeout is not enforced on the synchronous prefix of an inbound script |
| INB-2 | Low | perf | Methods using `$ref` schemas load the whole shared-schema library from the DB twice per request |
| INB-3 | Low | perf | The audit middleware rents a 2 MiB buffer for every inbound request with a body |
| INB-4 | Low | perf | The relay replay cache is scanned in full on every relayed request once it passes 4,096 entries |
| SEC-1 | Low | perf | A role refresh done on a passive request is never saved, so it repeats on every later passive request |
---
## NTF-1 — A delivered notification is re-sent after failover because its state write is cancelled by the shutdown token
- **Severity:** Medium
- **Category:** bug (double delivery)
- **Confidence:** Confirmed
- **Location:** `ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs:701`, `:744`, `:789`, `:419-423`
**What's wrong.** `DeliverOneAsync` passes the actor's shutdown token to `adapter.DeliverAsync` (intended, so an in-flight send is cut short). It then passes the same token to `WarnIfVanishedAsync` → `repository.UpdateAsync(notification, cancellationToken)`, the write that records `Delivered`. `UpdateAsync` is an `ExecuteUpdateAsync(..., cancellationToken)`, so a token cancelled in `PostStop` makes it throw `OperationCanceledException`. `DeliverGatedAsync` swallows that silently (`catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)`). The row stays `Pending`/`Retrying` with no record of the send.
**Failure scenario.** The singleton is handed over (CoordinatedShutdown on a deploy, manual failover, shut-out restart) while a sweep has up to `ResolvedMaxParallelDeliveries` sends in flight. Any delivery whose SMTP/EWS/Twilio call has already been accepted, but whose `UpdateAsync` has not yet run or is in flight, is cancelled. The new active node's first sweep claims the same row and sends the email or SMS again. For SMS, every recipient already texted is texted again. No log line or audit row marks the first send.
**Suggested fix.** Once the adapter has returned an outcome, persist it with `CancellationToken.None` (bounded by a short timeout of its own), and emit the audit rows the same way. Keep the shutdown token only for the adapter call and the gate waits.
---
## NTF-2 — SMTP connection drops and OAuth2 token-endpoint outages are parked as permanent
- **Severity:** Medium
- **Category:** bug (transient/permanent classification)
- **Confidence:** Confirmed for the code path; the exception types are MailKit's documented ones, not reproduced live
- **Location:** `ZB.MOM.WW.ScadaBridge.NotificationService/SmtpErrorClassifier.cs:77-85`; `ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/EmailNotificationDeliveryAdapter.cs:191-210`, `:352-357`; `ZB.MOM.WW.ScadaBridge.NotificationService/OAuth2TokenService.cs:134-135`
**What's wrong.** The classifier returns `Transient` only for `SmtpCommandException` 4xx, `SmtpProtocolException`, `ServiceNotConnectedException`, `SocketException` and `TimeoutException`. Everything else is `Unknown`, and the adapter's final `catch (Exception)` turns `Unknown` into `DeliveryOutcome.Permanent`, which parks the row at once with no retry. Three network-level failures land there:
- `System.IO.IOException`, which MailKit documents for `ConnectAsync`/`AuthenticateAsync`/`SendAsync` when the connection drops. It usually wraps a `SocketException`, but the classifier does not look at inner exceptions.
- `MailKit.Security.SslHandshakeException`, e.g. a relay restarting mid-handshake.
- `HttpRequestException` or a timeout `TaskCanceledException` from `OAuth2TokenService.GetTokenAsync` (`EnsureSuccessStatusCode` on a 5xx/429 from the token endpoint, a DNS or connect failure, or the client's 100 s timeout).
The catch block's comment justifies permanent for "a broken credential". That reasoning holds for a 400/401 from the token endpoint, not for a 503 or a network failure.
**Failure scenario.** The mail relay resets the TCP connection during `DATA`, or `login.microsoftonline.com` returns 503 for a minute. Every notification attempted in that window, alarm emails included, goes straight to `Parked` with `RetryCount` 0. It stays there until an operator notices and clicks Retry, although the configured `MaxRetries` × `RetryDelay` policy would have delivered it.
**Suggested fix.** In `SmtpErrorClassifier`, treat `IOException` and `SslHandshakeException` as transient and unwrap `InnerException` for `SocketException`/`TimeoutException`. In the token path, classify `HttpRequestException` by status (5xx/408/429 or no status = transient; other 4xx = permanent) and a non-caller `OperationCanceledException` as transient.
---
## DLM-1 — A powered-off central node yields `OUTCOME_UNKNOWN` instead of failing over to the next URL
- **Severity:** Medium
- **Category:** bug (failover / transient classification)
- **Confidence:** Confirmed by code reading; not reproduced against a dead host
- **Location:** `ZB.MOM.WW.ScadaBridge.DelmiaNotifier/HttpRecipeSender.cs:42-52`, `Program.cs:54`; same predicate in `ZB.MOM.WW.ScadaBridge.InboundAPI/HttpStandbyRequestForwarder.cs:149-162`, `:202-204`
**What's wrong.** Both clients advance to the next endpoint only when the failure is DNS resolution or `SocketError.ConnectionRefused`. Refusal needs a live host with a closed port. A host that is powered off, isolated or black-holed never answers the SYN, so the attempt ends in one of two ways:
- a `SocketException` with `TimedOut`, `HostUnreachable` or `NetworkUnreachable` (Windows gives up the connect after about 21 s), or
- the overall timeout firing first (`HttpClient.Timeout` of 30 s in the notifier; the 60 s `StandbyForwardTimeout` CTS in the forwarder).
Both are classified `OutcomeUnknown`, and the loop returns without trying the next URL. Neither client sets `SocketsHttpHandler.ConnectTimeout`, so a connect-phase hang cannot be told apart from a lost response. Nothing was sent in either case, so retrying would be safe.
The README's delivery semantics deliberately limit replay to "proven" non-execution. This case is provably non-executed too, but the code cannot see that. The documented drill (`docker kill`, published ports) only exercises the refused path.
**Failure scenario.** `BaseUrls = http://vq03:…,http://vq04:…` and the VQ03 VM is powered off or loses its network. Every `DelmiaNotifier` run waits 21–30 s on VQ03 and prints `NO` + `OUTCOME_UNKNOWN: the request may have been applied; verify before retrying`. The healthy active node on VQ04 is never tried. Recipe downloads fail for the whole outage, with a message telling operators to check for a write that never happened. On the server side, a standby whose peer host has just died answers 502 `OUTCOME_UNKNOWN` after 60 s instead of 503 `ACTIVE_NODE_UNREACHABLE`.
**Suggested fix.** Give both clients a `SocketsHttpHandler` with a short `ConnectTimeout` (about 5 s). Treat connect-phase failures as not dispatched: `HttpRequestError.ConnectionError`, or an inner `SocketException` of `TimedOut`/`HostUnreachable`/`NetworkUnreachable`/`HostDown`. Keep `OUTCOME_UNKNOWN` for failures after the request was written.
---
## ESG-1 — A connection lost while reading the response body escapes transient/permanent classification
- **Severity:** Low
- **Category:** bug (error classification)
- **Confidence:** Confirmed by code reading
- **Location:** `ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs:361-398`, `:502-518`; callers `:78-90`, `:111-175`
**What's wrong.** `SendAsync` uses `HttpCompletionOption.ResponseHeadersRead`, so the body is read afterwards in `ReadBodyBoundedAsync`. The `try` around that read catches only `OperationCanceledException`. A reset or truncated response surfaces from `stream.ReadAsync` as `IOException`/`HttpIOException`, which is not an `HttpRequestException`. It is never wrapped as `TransientExternalSystemException`, and `CallAsync`/`CachedCallAsync` catch only the two gateway exception types.
**Failure scenario.** An external system returns `200` headers and then drops the connection mid-body.
- `ExternalSystem.Call` throws a raw `IOException` into the script instead of returning `ExternalCallResult(false, "Transient error: …")`.
- `ExternalSystem.CachedCall` throws too. Nothing is buffered to store-and-forward and no tracked operation is created, although a timeout at the same point (line 394) is treated as transient and buffered.
**Suggested fix.** Add `catch (Exception ex) when (ex is IOException or HttpRequestException)` around the body read and rethrow via `ErrorClassifier.AsTransient(...)`, matching the timeout branch beside it.
---
## INB-1 — The method timeout is not enforced on the synchronous prefix of an inbound script
- **Severity:** Low
- **Category:** bug (timeout not honored)
- **Confidence:** Confirmed by code reading
- **Location:** `ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs:628-629` (and the compile at `:613`)
**What's wrong.** `handlerTask = cached.Handler(context);` invokes the compiled script inline on the request thread. `Script.RunAsync` runs synchronously up to the script's first incomplete `await`. The deadline is applied only on the next line, `handlerTask.WaitAsync(cts.Token)`, which is not reached until that synchronous part returns. The existing "abandoned execution" handling therefore never engages for a script that blocks before its first await. The lazy Roslyn compile at line 613 runs inside the same window and also eats the method's budget.
**Failure scenario.** A method script does CPU work or a blocking call before any await (a large loop over `Parameters`, a `.Result` on a helper). The request holds a thread-pool thread with no deadline. `TimeoutSeconds` and client disconnect are both ignored, no `TIMEOUT` is returned, and the abandoned-execution gauge stays at zero. Enough concurrent calls starve the pool that also serves the Central UI and the gRPC control plane.
**Suggested fix.** Start the handler off the request thread (`handlerTask = Task.Run(() => cached.Handler(context))`) so `WaitAsync` bounds the whole run. Do the lazy compile before creating `timeoutCts`, or exclude it from the budget.
---
## INB-2 — Methods using `$ref` schemas load the whole shared-schema library from the DB twice per request
- **Severity:** Low
- **Category:** perf
- **Confidence:** Confirmed by code reading
- **Location:** `ZB.MOM.WW.ScadaBridge.InboundAPI/EndpointExtensions.cs:260-265`; `InboundScriptExecutor.cs:643-652`; `SchemaRefResolver.cs:53-60`; `ParameterValidator.cs:50`; `ReturnValueValidator.cs:68`
**What's wrong.** For a method whose `ParameterDefinitions` or `ReturnDefinition` contains a `$ref`, `SchemaRefResolver.BuildAsync` calls `repository.ListAsync` and builds a dictionary of every shared schema. It does this once before parameter validation and again, on a different scope and DbContext, before return validation. Each definition is then re-parsed from JSON with `InboundApiSchema.ParseWithRefs` on every call. The `ApiMethod` row is cached for 5 s, but the parsed schema and the library are not cached at all.
**Failure scenario.** An MES integration calls a `$ref`-using method at 50 req/s. That costs 100 full-table reads of the shared-schema library per second plus 100 schema parses, for data that changes only on a designer edit.
**Suggested fix.** Cache the parsed parameter and return schemas next to the compiled handler or the `ApiMethodCache` entry, keyed on the definition text plus a shared-schema revision. Invalidate through the existing `ScriptArtifactsChanged` / central cache-invalidation path.
---
## INB-3 — The audit middleware rents a 2 MiB buffer for every inbound request with a body
- **Severity:** Low
- **Category:** perf
- **Confidence:** Confirmed by code reading
- **Location:** `ZB.MOM.WW.ScadaBridge.InboundAPI/Middleware/AuditWriteMiddleware.cs:546-547`
**What's wrong.** `ReadBufferedRequestBodyAsync` rents `ArrayPool<byte>.Shared.Rent(capBytes + 1)`, where `capBytes` is `AuditLog:InboundMaxBytes` (1 MiB by default). 1,048,577 bytes rounds up to the 2 MiB pool bucket. The rent is the same size for a 200-byte JSON body, because `Content-Length` is not consulted.
**Failure scenario.** A burst of N concurrent small inbound calls holds N × 2 MiB of large-object-heap arrays. The shared pool keeps only a few arrays per bucket per core, so a burst beyond that allocates fresh 2 MiB LOH arrays and drops them, driving Gen2 collections on the node that also hosts Blazor circuits.
**Suggested fix.** Size the rent as `min(capBytes, ContentLength ?? capBytes) + 1`, or read through a small pooled chunk into a `MemoryStream` that grows only to what was actually received.
---
## INB-4 — The relay replay cache is scanned in full on every relayed request once it passes 4,096 entries
- **Severity:** Low
- **Category:** perf
- **Confidence:** Confirmed by code reading
- **Location:** `ZB.MOM.WW.ScadaBridge.InboundAPI/RelayProvenance.cs:86-101`
**What's wrong.** `TryRecordProof` enumerates the whole `SeenProofs` dictionary whenever `Count >= 4096`. Each entry lives about 301 s past its proof time, so any sustained relayed rate above roughly 14 req/s keeps the count over the threshold with nothing expired. Every relayed request then pays a full scan of a dictionary that can grow to the 100,000 hard cap. At the cap the method returns `false`, so later proofs are treated as unverified. The request still runs, but its audit row loses the caller's IP and execution id, and the standby-side suppression flag no longer applies.
**Failure scenario.** Clients are pinned to the standby (a stale DNS entry, or a client that lists the standby first) and send 50 req/s. The active node scans about 15,000 entries per request. At around 330 req/s the cap is reached and relayed calls are audited with the standby's address as `remoteIp`.
**Suggested fix.** Prune on a time basis (at most once every few seconds) instead of on every call over the threshold, or keep expiries in a queue ordered by expiry so pruning is amortised O(1).
---
## SEC-1 — A role refresh done on a passive request is never saved, so it repeats on every later passive request
- **Severity:** Low
- **Category:** perf
- **Confidence:** Plausible (logic confirmed by reading; frequency depends on how often `/auth/ping` is polled)
- **Location:** `ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs:266-275`, `:303-308`; `CookieSessionValidator.cs:198-289`
**What's wrong.** `OnValidatePrincipalAsync` runs the full `TryRefreshAsync` (role re-map, plus an LDAP group re-query when due) on passive requests (`/auth/ping`, `/auth/activity`, `/_blazor`). `ApplyValidationResultAsync` then sets `context.ShouldRenew = false` for those same requests. The replaced principal, carrying the new `zb:lastrolerefresh` / `zb:lastgrouprefresh` stamps, is never written back to the cookie. The next passive request arrives with the old stamps, finds the refresh still due, and repeats it.
**Failure scenario.** A user leaves a Blazor page open past `RoleRefreshThresholdMinutes`. From then until their next real navigation, every keep-alive ping rebuilds the principal and calls `IGroupRoleMapper.MapAsync`. When the group interval has also lapsed, it calls `DirectoryGroupRefresher.RefreshAsync` as well. `RoleMappingCache` (30 s) and the directory cache (`CacheSeconds`) dampen this, but with either cache disabled it becomes one DB query set or one LDAP search per ping per idle session.
**Suggested fix.** Keep a short-lived per-session record of the last refresh, keyed on the session id as `SessionActivityTracker` already does, and consult it in `IsRoleRefreshDue`/`IsGroupRefreshDue`. Alternatively, renew the cookie on a passive request when a refresh actually happened, while keeping the old `LastActivity` value (which `recordActivity: false` already preserves).