Files
ScadaBridge/docs/plans/2026-12-02-full-code-review-remediation.md
T

16 KiB

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.

Decisions (2026-12-03)

Where the plan first offered two options, the recommended one was accepted. The task rows say so, with the rejected option:

  • 2.1: fix GetListByNameAsync itself.
  • 2.8: preserve-if-null on the server.
  • 3.1: a generation-based seed drop.
  • 3.8: emit Good, used only to reset the backoff.
  • 4.9: Parked can be re-opened, end to end.
  • 6.1: the InstanceActor Task.Run/persist-tail/PipeTo pattern.
  • 6.8 (UI-13): a split deadline.

These were already single choices and are confirmed:

  • 1.5: bundle export of secrets needs Administrator.
  • 4.2: a standby site node refuses stream subscriptions; picking the start node from heartbeats was rejected.
  • 5.1: a NoTracking default on the circuit context, not a per-page Reset().

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. Decided: fix the repository method, so every caller gets the recipients; don't just switch the importer to 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. Decided: preserve-if-null on the server. The update command fields become nullable and the handler applies if (cmd.X is not null). Fetch-and-merge in the CLI was rejected: the fetch returns scrubbed secrets, so merging would write the placeholders back, and it races concurrent edits. 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. Decided: drop a seed for any tag that has already delivered a live value in the current subscribe generation. Comparing timestamps was rejected: it depends on device and server clocks, and on the configured timestamp mode (see DCL-7). 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 Decided: the DCL connection actor emits ConnectionQualityChanged(Good) when it re-enters Connected. The Instance Actor's Good branch only resets the Lever-1 subscribe backoff. It must not stamp bound attributes Good with their last-known values before the device re-reports. 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 Decided: Parked can be re-opened, end to end. The site tracking store accepts a transition out of Parked: Retry clears TerminalAtUtc, Discard writes Discarded, and both emit telemetry. The central guard accepts Parked → Attempted/Delivered/Failed/Discarded when the incoming UpdatedAtUtc is newer. A separate reconcile sweep of parked rows was rejected because it adds a second path. 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. Decided: follow the InstanceActor pattern. The storage call runs in Task.Run, flushes chain on a persist-tail task so batches stay ordered, and reads PipeTo(Self).
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. Decided (UI-13): split the deadline. The script deadline starts when the worker reports it is about to run user code, and a separate, generous ceiling covers start-up plus compile. A pre-warmed worker pool was rejected as more moving parts than the problem needs.
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.