From 28b6651a898bd17557544722621375b36140e01c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 2 Dec 2026 16:06:45 -0500 Subject: [PATCH] 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-full-code-review-remediation.md | 124 ++ docs/plans/2026-12-02-full-code-review.md | 1975 +++++++++++++++++ 2 files changed, 2099 insertions(+) create mode 100644 docs/plans/2026-12-02-full-code-review-remediation.md create mode 100644 docs/plans/2026-12-02-full-code-review.md diff --git a/docs/plans/2026-12-02-full-code-review-remediation.md b/docs/plans/2026-12-02-full-code-review-remediation.md new file mode 100644 index 00000000..aced9b34 --- /dev/null +++ b/docs/plans/2026-12-02-full-code-review-remediation.md @@ -0,0 +1,124 @@ +# Full code review 2026-12-02: fix plan + +**Source:** `docs/plans/2026-12-02-full-code-review.md` (112 findings: 9 High, 51 Medium, 52 Low; finding IDs below refer to it). + +**Base:** `main` @ `d4d5be3b`. + +**Process:** +- Each work package (WP) gets its own `git worktree`, made by hand. `isolation: "worktree"` agents share an index here. +- Run targeted tests per task. Build the full solution and run the full suite once at the end of each WP. +- Write the design-doc, code, test and migration changes for a WP together. +- File one Gitea issue per WP with the labels `type:review-finding` + `priority:pN`. Do not add new register rows. + +**Ordering:** WP1 and WP2 are the urgent ones: a trust-boundary hole, plus data that is being lost or corrupted today. WP3 to WP5 are correctness work that depends on runtime timing. WP6 and WP7 are perf and hygiene. Every WP except WP4 touches its own set of files, so they can run in parallel. WP4 shares `DeploymentService` with WP1 and should start after WP1 merges. + +--- + +## WP1: Trust boundary and audit durability (P0) + +| Task | Findings | Change | Verify | +|---|---|---|---| +| 1.1 | CMN-1 | Add a `VisitMemberBindingExpression` override to `HardeningWalker`. It applies the `ReflectionGatewayMembers` check to `?.`. Add `CreateDelegate` to the gateway members. | Regression tests: the `?.` form of every existing `.`-form rejection test must also be rejected. Include the probe script from the report. | +| 1.2 | CMN-2 | Deny the `System.AppDomain` assembly-loading members. | `ScriptTrustValidator` tests. | +| 1.3 | CMN-5 | Key `TrustVerdictCache` on (code, extraReferences digest, degraded flag). | Unit test. | +| 1.4 | DEP-1, MGT-1, TPL-3 | **Fix the shared root cause.** Add `IAuditService.LogAndSaveAsync`. It stays best-effort: it swallows and logs its own failure. Switch every post-save audit call site in the report to it: `DeploymentService`, `ArtifactDeploymentService`, `InstanceService`, and the `ManagementActor` API-key, shared-schema, ES-method and move-connection handlers. Then grep for any other `LogAsync` that follows a final save. | One real-context test per family asserting that the `AuditLogEntries` row exists. The current mocks only check `LogAsync` was called. Live-check on the rig: disable/enable/delete an instance and run Deploy Artifacts, and confirm the rows appear. | +| 1.5 | MGT-3, MGT-4 | Bundle export of secret-bearing config (SMTP/SMS/ES credentials) requires Administrator. Scrub the reply of `data-connection move`. | Update the authz matrix test. Unit test for the scrubbed reply. | +| 1.6 | MGT-2, UI-5 | Audit query/export/tree and the Audit Log grid scope by site **identifier**, not by the numeric id. Fix the execution-tree scope comparison. | Scoped-caller tests on both surfaces. | +| 1.7 | UI-7, UI-9, UI-10 | Push the site-scope filter (and the Secured Writes status filter) into the server query so it runs before paging. Scope the Notification KPI breakdown. | Paging tests with mixed-site data. | +| 1.8 | CDB-1 | Encrypt the data-connection protocol JSON in deployed snapshots and pending rows (Data Protection, as with other secrets). Write a one-time migration that re-protects existing rows. | Round-trip test. Check the rig DB for no plaintext after the migration. **Needs a migration and a QA/DEV deploy gate.** | + +## WP2: Config and transport data integrity (P0/P1) + +| Task | Findings | Change | Verify | +|---|---|---|---| +| 2.1 | TRN-1 | Add `.Include(Recipients)` to `GetListByNameAsync` (or use the bulk lookup). | Import Overwrite test: the target list {A,B} + bundle {A,C} must end as {A,C}, and stay that way after a re-import. | +| 2.2 | TPL-1, TPL-5 | Resolve alarm on-trigger script references per composition chain, not through the global `scriptCanonicalById`. | A two-slot test and a nested-slot override test. Their revision hashes change by design, so note that in the commit. | +| 2.3 | TPL-2 | A derived script override keeps the base alarm's on-trigger link (resolve by name). | Unit test. | +| 2.4 | TRN-2, TRN-6 | The diff compares the secret-bearing values by hash, which keeps them presence-only to the operator. The instance diff covers the bound connection and drops the never-written field. | Diff tests. | +| 2.5 | TRN-3, TRN-7, TRN-8, TRN-9 | Preview applies the name map. Site-scoped lookups are case-insensitive. Areas match by full path. Rename either works for every kind or is rejected where unsupported. | Importer tests. Re-run the reflection round-trip guard. | +| 2.6 | TRN-4, TRN-5 | Template Overwrite removes compositions that aren't in the bundle. The composition rewire also deletes the slot-owned derived templates. | Importer tests against a real context. | +| 2.7 | TRN-10 | Clamp the manifest KDF iteration count to a sane range. | Unit test. | +| 2.8 | CLI-2 | Update commands only send options that were actually passed. This needs a server-side partial-update path, or the CLI fetches the current entity and merges into it. | CLI tests per update command. | +| 2.9 | DEP-3 | Widen `PerSiteStatus` to `nvarchar(max)`. | **Migration + SQL script.** | + +## WP3: Site runtime and data path correctness (P1) + +| Task | Findings | Change | Verify | +|---|---|---|---| +| 3.1 | DCL-1 | Flag seed values on `TagValueReceived`. Drop a seed for any tag that already delivered a live value in the current subscribe generation, or whose timestamp is older than the last forwarded one. | Actor test with a seed that arrives after a live value. Live check: reconnect on the rig. | +| 3.2 | DCL-2, DCL-3, DCL-8 | Retry OPC UA alarm re-subscribe failures. Check the monitored-item create status. Put tags with connection-level failure rows into the retry set. | DCL actor tests. | +| 3.3 | DCL-4, DCL-9 | Cancel the re-subscribe loop when its session ends. Make the shared supervisory-advise task independent of the first caller's token. | Tests. | +| 3.4 | DCL-5, DCL-6, DCL-7 | Route alarm sources with a separator-aware prefix match. Browse/search reply with an error while disconnected. Reads honour the `Server` timestamp mode. | Tests. | +| 3.5 | SF-1, SF-2 | Keep per-target FIFO: the per-lane order must be by enqueue time, and a lane must not pass a still-pending older row. Classify a storage error after a successful delivery separately, so the delivery isn't repeated. | S&F tests. | +| 3.6 | SRT-1, SRT-10 | The watchdog detects a wedged run by deadline, not only by a blocked thread. Separate cancellation from timeout in the reported outcome. | Tests. | +| 3.7 | SRT-2, SRT-3, SRT-4 | A failed trigger evaluation keeps the previous state (no coercion to false) and logs a rate-limited event. RateOfChange clears when the value is flat. Start the WhileTrue timer when the condition is adopted from a seed. | Alarm/script actor tests. | +| 3.8 | SRT-6 | Emit `ConnectionQualityChanged(Good)` (or remove the dead reset and document the 45 s ceiling). | Test. | +| 3.9 | SRT-8, SRT-9, SRT-13 | Script-facing Asks use the remaining deadline. `Notify.Status` checks the site-local store first. Remove the hard-coded 30 s routed-call cap (use the configured timeout). | Tests. | +| 3.10 | SRT-11, SRT-12 | A static write refreshes the quality/timestamp. The redeploy reset gate covers the full actor start. | Tests. | +| 3.11 | CMN-3, CMN-4, CMN-10 | The codec handles non-finite numbers and round-trips DateTime as UTC ISO-8601 with sub-second precision (a compatibility read accepts the old format). JSON null converts to null. | Codec round-trip tests. Additive only, so the wire stays compatible. | + +## WP4: Cross-cluster, failover and central singletons (P1) + +| Task | Findings | Change | Verify | +|---|---|---|---| +| 4.1 | COMM-1, COMM-6 | Health sequence = `max(prev+1, nowMs)`, re-seeded on the standby→active transition. Reset interval counters on activation. The aggregator returns `Accepted=false` on a drop. | Aggregator tests. Failover drill with a deliberately skewed start. | +| 4.2 | COMM-2 | A site node refuses `SiteStreamService` subscriptions with `Unavailable` while it isn't `SelfIsOldestUp` for its site role, and ends its streams on losing the active role. | gRPC server test. Rig: restart NodeA after a failover, then check that Alarm Summary and Debug View go live on NodeB. | +| 4.3 | COMM-3, COMM-7 | Debug stream: buffer events until the snapshot is delivered, and handle the snapshot `Status.Failure`. | Bridge actor tests. | +| 4.4 | COMM-4, COMM-5 | Key liveness on central receive time. Set `SocketsHttpHandler.ConnectTimeout` on the gRPC channels and treat a connect-phase `DeadlineExceeded` as failover-worthy. | Tests. Black-hole drill (iptables drop) on the rig. | +| 4.5 | NTF-1 | Write the outbox's delivered state with a non-shutdown token. | Test with the stop token cancelled mid-delivery. | +| 4.6 | NTF-2, ESG-1 | Classify SMTP connection drops, OAuth2 token-endpoint outages, and a body-read `IOException`/`HttpRequestException` as transient. | Adapter tests. | +| 4.7 | DLM-1 | DelmiaNotifier: a connect failure (no request sent) fails over to the next URL; `OUTCOME_UNKNOWN` only after the send. | Notifier tests. | +| 4.8 | AUD-1 | Reconciliation keeps one cursor per (site, node) and pulls from both nodes. | Reconciliation tests. | +| 4.9 | SCA-1 | A central `SiteCalls` row follows the site's post-Retry/Discard status (via the telemetry upsert-on-newer, or a reconcile of parked rows). | Test. Rig: retry a parked call and watch the row clear. | +| 4.10 | KPI-1 | The backfill plans from its own persisted watermark, not from the periodic fold's. | Recorder test. | +| 4.11 | AUD-6 | The purge/archive covers rows before the first partition boundary. | SQL test against a partitioned test DB. | + +## WP5: Central UI DbContext lifetime (P1) + +| Task | Findings | Change | Verify | +|---|---|---|---| +| 5.1 | UI-1 | Register the circuit's context with `UseQueryTrackingBehavior(NoTracking)`. Services that mutate opt in with `AsTracking()`. Audit each mutating service: write paths that relied on implicit tracking must attach/update explicitly. | Full CentralUI + ConfigurationDatabase suites. Playwright: Move to Site, Topology rename refresh, template script reload after a CLI edit. | +| 5.2 | UI-2, UI-3, UI-8 | Run long or concurrent page actions in their own DI scope (as Topology's Deploy all already does), and serialize the page loads. | bUnit tests. | +| 5.3 | UI-4 | Check a disposed flag / CTS after every await before creating timers or subscriptions. | bUnit tests. | +| 5.4 | UI-11 | Retry/Discard on a row whose site was deleted: allow it for unscoped callers. | Test. | + +## WP6: Performance (P2) + +| Task | Findings | Change | +|---|---|---| +| 6.1 | SRT-5 | Move synchronous SQLite work off the Akka dispatcher (PipeTo pattern or the existing single-writer queue). | +| 6.2 | SRT-7, SRT-14, CMN-11 | Index expression triggers by referenced attribute. `EnforceCap` uses a priority structure. Look up the predictor lane in O(1). | +| 6.3 | SF-3 | The sweep selects ids/lanes without payloads, then loads the payloads of the chosen page. Back it with an index. | +| 6.4 | AUD-2, AUD-3, AUD-4, AUD-7 | Drop `Cache=Shared`. Keyset-page `ReadPendingSinceAsync` on an indexed `(ForwardState, OccurredAt, EventId)`. Add an age-seekable purge index. Batch the tracking reads in the telemetry drain. | +| 6.5 | AUD-5, SEL-1 | Add a `(Channel, OccurredAtUtc)` index and bind the channel as `varchar`. Add a site `site_events(instance_id, timestamp)` index. **Migration + SQL script; site schema applied in place.** | +| 6.6 | DEP-4, DEP-5, DEP-6, TPL-4 | Batch the fleet staleness queries with `AsNoTracking`. Detach a failed staging write (like P7-5). Re-check Disabled at Send time. Use targeted single-entity loads. | +| 6.7 | MGT-5, TRN-11 | Export and import resolve names with one bulk lookup per kind. | +| 6.8 | UI-6, UI-12, UI-13 | Save only the overrides that changed (one transaction). Cache the auth/site lookups per poll. Pre-warm a sandbox worker, or raise the first-run deadline. | +| 6.9 | INB-2, INB-3, INB-4 | Cache resolved `$ref` schemas per method revision. Size the audit buffer to Content-Length (capped). Expire the relay replay cache by time-ordered queue. | +| 6.10 | COMM-8, DCL-10 | Run the failback probes in parallel with a bound. Use a static quality map. | + +Each task needs a micro-benchmark or a query plan (`EXPLAIN QUERY PLAN`, or `sqlcmd -I` with SET STATISTICS IO) before and after. Record the numbers in the commit message. + +## WP7: CLI and remaining Lows (P2/P3) + +| Task | Findings | Change | +|---|---|---| +| 7.1 | CLI-1, CLI-5, CLI-6 | Exit 1 on `success:false`. Export writes to a temp file and renames it, exiting 1 on a size mismatch. Report a clean error message for user and bodyless errors. | +| 7.2 | CLI-3 | Parse numbers and dates with the invariant culture (custom parsers). Add a `de-DE` test. | +| 7.3 | CLI-4, CLI-7 | Streaming export has no fixed 30 s idle cap (use a configurable idle timeout). `debug stream` retries a failed re-subscribe. | +| 7.4 | DEP-2 | Take the operation lock before validating the state. | +| 7.5 | CMN-6, CMN-7, CMN-8, CMN-9, CMN-12 | The flow fold orders by lifecycle rank, then time. The schema `required` matching is case-insensitive. Unknown legacy types get a clear error. CSV tolerates trailing commas. `ParseEnum` ignores case. | +| 7.6 | INB-1, SEC-1 | Run inbound scripts so the timeout covers the synchronous prefix (`Task.Run` with deadline). Persist a refreshed role ticket on passive requests. | + +--- + +## Deploy and rollout notes + +- **Migrations:** 1.8 (re-protect snapshot JSON), 2.9 (`PerSiteStatus`) and 6.5 (audit index). Generate each with `dotnet ef migrations add` *after* a build, plus a `docs/plans/sql/*.sql` script for QA and DEV. +- **Revision-hash change:** 2.2 changes the flattened output for multi-slot compositions. Affected instances will read *Out of date* after the upgrade. That is correct, but call it out in the deployment record. +- **Wire changes:** none are required. 3.11 and 4.1 are additive or behavioural only. Upgrade central before the sites, as usual. +- **Rig gates per WP:** run `bash docker/deploy.sh`, then the relevant drill: + - WP3: reconnect plus seed. + - WP4: `DRILL_MODE=active bash docker/failover-drill.sh` plus a NodeA-restart stream check. + - WP5: Playwright. +- **QA (vq03/vq04) and DEV (vd03):** deploying there is the user's call. These fixes do not deploy them. diff --git a/docs/plans/2026-12-02-full-code-review.md b/docs/plans/2026-12-02-full-code-review.md new file mode 100644 index 00000000..f3203754 --- /dev/null +++ b/docs/plans/2026-12-02-full-code-review.md @@ -0,0 +1,1975 @@ +# 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` 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(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 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(() => 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`, 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` 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` 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] = ".