Merge branch 'review/wp6' into review/integration

# Conflicts:
#	docs/requirements/Component-StoreAndForward.md
#	src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs
#	src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs
#	src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs
#	tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs
This commit is contained in:
Joseph Doherty
2026-12-03 11:03:44 -05:00
84 changed files with 4722 additions and 233 deletions
+14 -1
View File
@@ -270,6 +270,17 @@ know. `SourceNode` is stamped by the
writing node itself (`node-a` / `node-b`) at append time and travels with the row
through telemetry and reconciliation unchanged.
**Connections and indexes (WP6, 2026-12-03).** The writer and the read-only callers use
two *private-cache* WAL connections (AUD-2 — `Cache=Shared` made them share table-level
locks, so a long backlog scan stalled the batch writer); only the in-memory test override
keeps a shared cache. The reconciliation pull reads the owed states through the partial
index `IX_fwd_owed (OccurredAtUtc, EventId) WHERE ForwardState IN ('Pending','PushAbandoned','Rejected')`,
so each page is an ordered range read that stops at the limit (AUD-3; 1 M owed rows:
3.5 s → <1 ms per 256-row page), and the retention purge seeks `IX_fwd` on
`(ForwardState, IsCachedKind, OccurredAtUtc)` instead of walking each state's whole range
(AUD-4). The cached-telemetry drain resolves a batch's tracking snapshots with one batched
read of its distinct operation ids (AUD-7).
**Site SQLite retention rule (hard invariant):**
> A row is eligible for purge only when both `OccurredAtUtc < retention threshold` AND `ForwardState IN ('Forwarded', 'Reconciled')`. Pending rows — and the owed push-exit states `PushAbandoned` / `Rejected` — are never purged.
@@ -774,7 +785,9 @@ MS SQL for direct-write events). Unredacted secrets never persist.
aid, not a compliance record) whose value is a retention window in days that
MUST be strictly shorter than the global `RetentionDays`. After the daily
partition switch-out, the purge actor runs a bounded, batched row DELETE
(`PurgeChannelOlderThanAsync`) for each channel whose override is shorter than
(`PurgeChannelOlderThanAsync`, seeking the partition-aligned
`IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc)` with the channel bound as
`varchar(32)` — AUD-5) for each channel whose override is shorter than
the global window — expiring rows of that channel earlier than the global
partition switch would. Overrides equal to or longer than the global window are
silently skipped (the global switch already covers them). The DELETE runs under
+1 -1
View File
@@ -381,7 +381,7 @@ Long or concurrent page work also runs on its own scope, so it can neither colli
### Isolated Test Run workers
Test Run executes in a disposable `CentralUI.SandboxWorker` process. A process-wide admission gate permits at most four workers. Queueing, compilation, execution and gateway calls consume the requested deadline (1–10 seconds); cancellation kills the process tree and capacity is released only after confirmed exit. Console capture retains at most 32,000 characters with an explicit truncation marker; return JSON is limited to 32,000 bytes. Private IPC frames are limited to 1 MiB and stderr is drained without accumulation. Each worker has a 512 MiB managed-heap ceiling. The worker is a resource/lifetime boundary; the semantic script trust policy still gates compilation.
Test Run executes in a disposable `CentralUI.SandboxWorker` process. A process-wide admission gate permits at most four workers. The requested deadline (1–10 seconds) covers execution and gateway calls only: it starts when the worker reports it is about to run user code (UI-13, 2026-12-03). Queueing for an admission slot, worker start-up and compilation are bounded instead by a separate start-up ceiling (30 seconds plus the requested deadline), whose expiry is reported as its own timeout message; cancellation kills the process tree and capacity is released only after confirmed exit. Console capture retains at most 32,000 characters with an explicit truncation marker; return JSON is limited to 32,000 bytes. Private IPC frames are limited to 1 MiB and stderr is drained without accumulation. Each worker has a 512 MiB managed-heap ceiling. The worker is a resource/lifetime boundary; the semantic script trust policy still gates compilation.
External calls, shared-script lookup and bound-instance operations use a parent broker. `Notify` is simulated, not brokered: `Notify.To(list).Send` returns a fake `NotificationId`, queues and sends nothing, and writes a `[sandbox] … not delivered` line to the console pane; `Notify.Status` reports `Unknown`. A real send needs a deployed instance (Deployment → Flow Debugger) (#151). Configured SQL connections are recreated inside the worker using credentials passed only over its private pipe, preserving the existing SQL permissions and API. Termination prevents further calls and closes worker-owned sockets; it cannot undo SQL or remote work already accepted by another server. Timeout results do not retain a terminated worker's partial console buffer.
@@ -181,6 +181,14 @@ site-wide push would silently restart every piece of equipment an operator had
deliberately stopped; they are reported in the summary's `SkippedInstances` with
the reason "Disabled — bulk deploy preserves disabled state; deploy individually
to re-enable", and the single-instance deploy remains the explicit re-enable path.
The skip is re-checked once each instance's operation lock is held (DEP-6, 2026-12-03):
the candidate list is read once when the batch starts, so an instance an operator
disables while the batch is still preparing earlier instances is caught by a fresh,
untracked state read (`IDeploymentManagerRepository.GetInstanceStateAsync`) and reported
as skipped with the same reason, instead of being deployed and re-enabled. A failed
staging write detaches its pending changes so it cannot poison the staging writes of
the instances after it on the shared unit of work (DEP-5), and the supersede of a prior
`PendingDeployment` row is a set-based delete rather than tracked key stubs.
**Up-to-date instances are skipped too (unless `force`), at batch cost.** The
pre-filter reads the deployed-hash projection (`GetDeployedRevisionHashesAsync`) and
+1 -1
View File
@@ -175,7 +175,7 @@ The `sbk_<keyId>_<secret>` design already supports zero-downtime rotation — a
## Script Compilation & Hot-Reload
API method scripts are pre-compiled in the **background after startup** by `InboundMethodWarmupService` (a hosted service registered after `AkkaHostedService`, so it never delays the cluster join or `/health/*`): it waits for `ApplicationStarted`, then — only once this node is the active central node (`IActiveNodeGate`; a standby pays nothing until a failover promotes it) — loads all method definitions and compiles them into in-memory delegates. Lazy compile + the per-request revision check guarantee correctness regardless. Compiles are **single-flight per method name + script revision**: N concurrent first callers share one compile (and one non-collectible loaded assembly). `InboundScriptExecutor.CompileAndRegister(ApiMethod, out IReadOnlyList<string> errors)` compiles once and returns the diagnostics, so a save needs no separate validate pass; the management Create/Update path uses its sibling `CompileForPublish(method, out errors, out publish)`, which compiles once for the `compileWarning` and hands back a `publish` action queued as the post-commit registration — one compile (one pinned assembly) per save even inside a configuration transaction (review 2026-10-21 05/M1). `ApiMethodCache` prunes expired entries on a miss once large (scopes are exact method names — pinned by test — so growth is bounded). A Management API/UI create, update or delete drops that method's `ApiMethodCache` entry post-commit on the node that made the change; the peer central node converges within `ApiMethodCacheTtl` (default 5 s) — Gitea #85, audit `docs/plans/2026-11-09-central-cache-staleness-audit.md`.
API method scripts are pre-compiled in the **background after startup** by `InboundMethodWarmupService` (a hosted service registered after `AkkaHostedService`, so it never delays the cluster join or `/health/*`): it waits for `ApplicationStarted`, then — only once this node is the active central node (`IActiveNodeGate`; a standby pays nothing until a failover promotes it) — loads all method definitions and compiles them into in-memory delegates. Lazy compile + the per-request revision check guarantee correctness regardless. Compiles are **single-flight per method name + script revision**: N concurrent first callers share one compile (and one non-collectible loaded assembly). `InboundScriptExecutor.CompileAndRegister(ApiMethod, out IReadOnlyList<string> errors)` compiles once and returns the diagnostics, so a save needs no separate validate pass; the management Create/Update path uses its sibling `CompileForPublish(method, out errors, out publish)`, which compiles once for the `compileWarning` and hands back a `publish` action queued as the post-commit registration — one compile (one pinned assembly) per save even inside a configuration transaction (review 2026-10-21 05/M1). `ApiMethodCache` prunes expired entries on a miss once large (scopes are exact method names — pinned by test — so growth is bounded). A Management API/UI create, update or delete drops that method's `ApiMethodCache` entry post-commit on the node that made the change; the peer central node converges within `ApiMethodCacheTtl` (default 5 s) — Gitea #85, audit `docs/plans/2026-11-09-central-cache-staleness-audit.md`. Runtime `$ref` resolution reads the shared-schema library from a process-wide `SharedSchemaLibraryCache` snapshot on the same `ApiMethodCacheTtl`, so a schema-library edit reaches running methods within that bound instead of costing two full library reads per request (INB-2, 2026-12-03).
### Update Workflow
@@ -194,6 +194,13 @@ Each event entry contains:
- Time range
- Instance ID
- Severity
The event-type, severity and instance-ID equality filters are each backed by a composite
index with `timestamp` (`idx_events_type_timestamp`, `idx_events_severity_timestamp` — #123;
`idx_events_instance_timestamp` — SEL-1, 2026-12-03, replacing the single-column
`idx_events_instance`), so a filtered page is read in `(timestamp, id)` order and stops at the
page limit. `SiteEventLogSchema.Apply` drops the superseded single-column indexes in place on
first boot.
- **Keyword search**: Free-text search on message and source fields (SQLite LIKE query). Useful for finding events by script name, alarm name, or error message across all instances. The `LIKE` is a leading-wildcard full scan, so a keyword search is **bounded to a time window**: a query with no `From` (or a range wider than `ScadaBridge:SiteEventLog:KeywordSearchMaxWindow`, default 7 days) is clamped server-side to `(To ?? now) - window`, not rejected (review 2026-10-21 02/P1).
- Results are **paginated** with a configurable page size (default: 500 events). Each response includes a continuation token for fetching additional pages. This prevents broad queries from overwhelming the communication channel.
- The site processes the query locally against SQLite and returns matching results to central. The query runs off the actor thread (`Task.Run` + `PipeTo`) on its own short-lived read connection — WAL readers do not block the single writer, so a slow scan can no longer hold the logger's write lock and overflow the bounded write queue (review 2026-10-21 02/P1). The storage-cap trim tracks its row count locally (re-read from the database after the first batch and every 10th batch) and runs `PRAGMA incremental_vacuum` once per tick rather than per batch (02/P4).
+2 -2
View File
@@ -285,7 +285,7 @@ When the Instance Actor is stopped (due to disable, delete, or redeployment), Ak
- **WhileTrue**: On the `false → true` edge the script fires once, then re-fires on a periodic timer while the condition stays true; on the `true → false` edge the timer stops. The re-fire cadence is the script's **minimum time between runs**; with none configured the trigger degrades to the single edge fire and logs a warning.
- **Minimum time between runs**: If configured, the Script Actor tracks the last execution time and skips trigger invocations that fire before the minimum interval has elapsed. For a WhileTrue trigger it doubles as the re-fire cadence.
> **Per-attribute change routing (P2).** Rather than broadcasting every attribute change to all child Script/Alarm Actors, the Instance Actor routes each change only to the children that monitor that attribute (built from their trigger configs at spawn time); **Expression-trigger children, which read an attribute snapshot, receive all changes**. Each child still keeps its own trigger gate as defense-in-depth — the routing is an optimization, not the authority.
> **Per-attribute change routing (P2).** Rather than broadcasting every attribute change to all child Script/Alarm Actors, the Instance Actor routes each change only to the children that monitor that attribute (built from their trigger configs at spawn time); **Expression-trigger children are routed by the attribute keys their expression reads** (SRT-7, 2026-12-03): a compile-time syntax walk extracts the literal `Attributes["k"]` / `Children["c"].Attributes["k"]` reads, and the child hears only changes of those attributes. Any read the walk cannot pin down (a non-literal key, an alias or member access of the `Attributes`/`Children`/`Parent` globals, a parse error, or an expression that reads no attribute at all) falls back to **receiving all changes**, as before. Each child still keeps its own trigger gate as defense-in-depth — the routing is an optimization, not the authority.
### Concurrent Execution
- Each invocation launches a **new run** on the script-execution scheduler.
@@ -409,7 +409,7 @@ that owns the Instance Actor, and central reads the linkage from audit rows.
- **Snapshot / SnapshotComplete (reconnect reconciliation)**: `Snapshot` updates buffer into a staging set; `SnapshotComplete` performs an **atomic swap** of the mirrored set with the staged set. Any condition that was previously mirrored but is **not present** in the new snapshot emits a return-to-normal `AlarmStateChanged` and drops out. This is how the mirror self-corrects after an outage.
- **Live transitions** (`Raise` / `Ack` / `Clear` / `Retrigger` / `StateChange`): upsert the condition by `SourceReference`. Updates carrying a `TransitionTime` **older** than the currently held transition are ignored (out-of-order protection). Accepted transitions persist to SQLite and emit an enriched `AlarmStateChanged` upward to the Instance Actor.
- **Retention**: a mirrored condition is dropped once it is both inactive **and** acknowledged (`!Active && Acknowledged`) — the alarm has fully run its course at the source and no longer needs mirroring. The drop emits a final state change and deletes the SQLite row.
- **Per-source cap**: at most `MirroredAlarmCapPerSource` conditions are retained per source. When the cap is exceeded the **oldest** condition is dropped and the eviction is **logged** — there is no silent truncation. If the evicted condition is still **active**, a final return-to-normal `AlarmStateChanged` is emitted before it is dropped (mirroring the retention drop above), so a capped-out active condition is never left stuck-active downstream.
- **Per-source cap**: at most `MirroredAlarmCapPerSource` conditions are retained per source. When the cap is exceeded the **oldest** condition is dropped (selected with a bounded heap, not a sort of the whole mirror — SRT-14) and the eviction is **logged** — there is no silent truncation; the Warning is rate-limited to one a minute during a sustained flood and carries the number of evictions since the previous one. If the evicted condition is still **active**, a final return-to-normal `AlarmStateChanged` is emitted before it is dropped (mirroring the retention drop above), so a capped-out active condition is never left stuck-active downstream.
### Persistence
- Mirrored condition state is persisted to the site SQLite `native_alarm_state` table on every accepted transition and removed on drop-out.
@@ -129,7 +129,7 @@ The telemetry-emitting `ICachedCallLifecycleObserver` hook is dispatched through
### Retry Sweep Indexing
`GetMessagesForRetryAsync` orders candidates `ORDER BY created_at ASC` within the due `status`. The existing `idx_sf_messages_status_due (status, last_attempt_at_ms)` matches the status filter and due-time predicate but not this ordering, forcing a sort/scan on a large sweep. The sweep page is ranked **per `(category, target)` lane** (`ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at)`, ordered by lane rank then `created_at`, limited to `SweepBatchLimit`), so a dead target with hundreds of due rows contributes one row per round like every other lane instead of owning the whole page and starving healthy targets (review 2026-10-21 02/C2); per-target FIFO is preserved. **Due-ness is decided per lane, not per row (2026-12-02 review SF-1):** the window runs over every *pending* row of the lane in enqueue order (`created_at`, then `rowid` as the same-instant tie-break) and only the prefix of due rows before the first not-yet-due row is eligible, so a younger row is never delivered while an older row of the same lane is still backing off (previously the failed head's `last_attempt_at` moved forward while the rows behind it kept older stamps, and a later sweep delivered B before A). An older *parked* row does not hold a lane. A dead target is therefore probed once per head retry interval. **A storage error after the handler has answered is not a delivery failure (SF-2):** the try covers the handler only; on success the row delete is retried (3 attempts) and, if it still fails, the row stays `Pending` with `RetryCount`/`LastError` untouched (never parked), the lane stops for that sweep, and the next due sweep re-delivers it (at-least-once; downstream idempotency remains the caller's). A failed park write after a permanent failure is handled the same way. A second covering index, `idx_sf_messages_status_created (status, created_at)`, lets the sweep walk matching rows already in `created_at` order and stop at the batch limit without re-sorting or touching non-pending rows (arch-review WP1.4). Both indexes are retained — `idx_sf_messages_status_due` still backs status+due-time lookups that don't order by `created_at`.
`GetMessagesForRetryAsync` orders candidates `ORDER BY created_at ASC` within the due `status`. The existing `idx_sf_messages_status_due (status, last_attempt_at_ms)` matches the status filter and due-time predicate but not this ordering, forcing a sort/scan on a large sweep. The sweep page is ranked **per `(category, target)` lane** (`ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at)`, ordered by lane rank then `created_at`, limited to `SweepBatchLimit`), so a dead target with hundreds of due rows contributes one row per round like every other lane instead of owning the whole page and starving healthy targets (review 2026-10-21 02/C2); per-target FIFO is preserved. **Due-ness is decided per lane, not per row (2026-12-02 review SF-1):** the window runs over every *pending* row of the lane in enqueue order (`created_at`, then `rowid` as the same-instant tie-break) and only the prefix of due rows before the first not-yet-due row is eligible, so a younger row is never delivered while an older row of the same lane is still backing off (previously the failed head's `last_attempt_at` moved forward while the rows behind it kept older stamps, and a later sweep delivered B before A). An older *parked* row does not hold a lane. A dead target is therefore probed once per head retry interval. **A storage error after the handler has answered is not a delivery failure (SF-2):** the try covers the handler only; on success the row delete is retried (3 attempts) and, if it still fails, the row stays `Pending` with `RetryCount`/`LastError` untouched (never parked), the lane stops for that sweep, and the next due sweep re-delivers it (at-least-once; downstream idempotency remains the caller's). A failed park write after a permanent failure is handled the same way. A second covering index, `idx_sf_messages_status_created (status, created_at)`, lets the sweep walk matching rows already in `created_at` order and stop at the batch limit without re-sorting or touching non-pending rows (arch-review WP1.4). Both indexes are retained — `idx_sf_messages_status_due` still backs status+due-time lookups that don't order by `created_at`. **SF-3 (2026-12-03):** the lane ranking runs over a narrow projection (`id` + lane keys) backed by the covering `idx_sf_messages_lane (status, category, target, created_at, last_attempt_at_ms, retry_interval_ms, id)`, so the window needs no sort and never reads a payload; only the chosen page of ids is joined back for full rows (200 000 due 1 KB rows: 1.29 s → 0.15 s per sweep). The index is created in place by `StoreAndForwardSchema.Apply`.
## Parked Message Management