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.
This commit is contained in:
Joseph Doherty
2026-12-02 16:06:45 -05:00
parent d4d5be3b1c
commit 28b6651a89
2 changed files with 2099 additions and 0 deletions
@@ -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.
File diff suppressed because it is too large Load Diff