From 8b64d1ec9cfd24666ca965b817e394d0e0ea0841 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:41:03 -0500 Subject: [PATCH 01/12] fix(site-runtime): move synchronous SQLite work off the Akka dispatcher (SRT-5, WP6 task 6.1) Follows the InstanceActor static-override pattern: the storage call runs in Task.Run, flushes chain on a persist-tail task so batches stay ordered, and reads PipeTo(Self). - NativeAlarmActor: FlushDirtyUpserts runs ApplyNativeAlarmChangesAsync on an ordered persist tail; the PreStart rehydration read runs in Task.Run and seeds the tail, so no flush can commit before the read. - InstanceActor: the ungated PreStart override read runs in Task.Run; the List-override normalising re-persist joins the static-override persist tail (off-dispatcher and ordered behind/before batched flushes). Evidence (NativeAlarmActorTests.Flush_BlockedOnWriteLock_DoesNotBlockTheActorThread, another connection holding BEGIN IMMEDIATE for ~1.6 s, busy_timeout 5 s): before: the next transition's emit stalled until the lock was released (ExpectMsg 500 ms timed out; actor thread parked in the flush) after: next transition emitted while the flush waits; both rows commit once the lock is released. --- .../Actors/InstanceActor.cs | 22 ++++++++-- .../Actors/NativeAlarmActor.cs | 44 ++++++++++++++++--- .../Actors/NativeAlarmActorTests.cs | 44 +++++++++++++++++++ 3 files changed, 101 insertions(+), 9 deletions(-) diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs index 9b554c6e..82138943 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs @@ -484,10 +484,13 @@ public class InstanceActor : ReceiveActor var self = Self; var instanceName = _instanceUniqueName; var storage = _storage; + // SRT-5: SQLite's async APIs run synchronously (open included), so the ungated read is + // started on the thread pool rather than inline on this actor's dispatcher thread. var load = _staticStateResetGate == null - ? storage.GetStaticOverridesAsync(instanceName) + ? Task.Run(() => storage.GetStaticOverridesAsync(instanceName)) : _staticStateResetGate - .ContinueWith(_ => storage.GetStaticOverridesAsync(instanceName)) + .ContinueWith(_ => storage.GetStaticOverridesAsync(instanceName), + TaskScheduler.Default) .Unwrap(); load.ContinueWith(t => { @@ -2091,7 +2094,20 @@ public class InstanceActor : ReceiveActor var key = kvp.Key; var logger = _logger; var instanceName = _instanceUniqueName; - _storage.SetStaticOverrideAsync(instanceName, key, native!) + var storage = _storage; + var nativeValue = native!; + // SRT-5: off the dispatcher and on the ordered persist chain, so the + // normalising write can never land after (and undo) a newer flush. + var previous = _staticOverridePersistTail; + var normalize = Task.Run(async () => + { + try { await previous.ConfigureAwait(false); } + catch { /* logged by its own continuation */ } + await storage.SetStaticOverrideAsync(instanceName, key, nativeValue) + .ConfigureAwait(false); + }); + _staticOverridePersistTail = normalize; + normalize .ContinueWith(t => logger.LogWarning(t.Exception?.GetBaseException(), "Failed to normalize static override {Instance}.{Attr} to native JSON", instanceName, key), diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs index 53fbda64..26fae600 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs @@ -131,8 +131,17 @@ public class NativeAlarmActor : ReceiveActor // Rehydrate last-known state from SQLite (non-blocking), then subscribe. // A fresh source snapshot will reconcile/replace this once it arrives. - (_rehydrationRead ?? _storage.GetNativeAlarmsAsync(_instanceName, _source.CanonicalName)) - .PipeTo(Self, Self, rows => new RehydrationCompleted(rows)); + // SRT-5: Microsoft.Data.Sqlite's *Async methods run synchronously (connection open + // included), so the read is started on the thread pool — never on this actor's + // dispatcher thread — and the result is piped back. Persist flushes chain behind it + // (the tail starts as the read), so a flush can never commit before the read runs. + var storage = _storage; + var instanceName = _instanceName; + var canonicalName = _source.CanonicalName; + var read = _rehydrationRead + ?? Task.Run(() => storage.GetNativeAlarmsAsync(instanceName, canonicalName)); + _persistTail = read; + read.PipeTo(Self, Self, rows => new RehydrationCompleted(rows)); SendSubscribe(); @@ -158,6 +167,13 @@ public class NativeAlarmActor : ReceiveActor private readonly Task>? _rehydrationRead; + /// + /// SRT-5: the ordered persist chain (InstanceActor's static-override pattern). Each flush + /// runs on the thread pool after the previous one, so batches commit in order without the + /// SQLite open/transaction/commit ever running on the actor's dispatcher thread. + /// + private Task _persistTail = Task.CompletedTask; + private string? _subscribeCorrelation; private DateTimeOffset _subscribeDeadline; private int _subscribeDelayMs; @@ -641,11 +657,27 @@ public class NativeAlarmActor : ReceiveActor var deletes = _dirtyUpserts.Where(kv => kv.Value is null).Select(kv => kv.Key).ToList(); _dirtyUpserts.Clear(); - _storage.ApplyNativeAlarmChangesAsync(_instanceName, _source.CanonicalName, batch, deletes) - .ContinueWith( - task => _logger.LogWarning(task.Exception, + // SRT-5: run the batched transaction on the thread pool, chained behind the previous + // flush (and the rehydration read) so batches stay ordered. SQLite's async APIs block + // synchronously; a write waiting on the shared LocalDb write lock must not park a + // default-dispatcher thread. + var storage = _storage; + var instanceName = _instanceName; + var canonicalName = _source.CanonicalName; + var logger = _logger; + var previous = _persistTail; + var persist = Task.Run(async () => + { + try { await previous.ConfigureAwait(false); } + catch { /* The prior batch/read was logged; a transient failure must not poison future writes. */ } + await storage.ApplyNativeAlarmChangesAsync(instanceName, canonicalName, batch, deletes) + .ConfigureAwait(false); + }); + _persistTail = persist; + persist.ContinueWith( + task => logger.LogWarning(task.Exception, "Failed to persist {Count} native alarm changes on {Instance}", - batch.Count + deletes.Count, _instanceName), + batch.Count + deletes.Count, instanceName), TaskContinuationOptions.OnlyOnFaulted); } diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs index bf289006..9497354c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs @@ -265,6 +265,50 @@ public class NativeAlarmActorTests : TestKit, IDisposable Assert.Contains(rows, r => r.ConditionJson.Contains("49")); } + /// + /// SRT-5 (WP6 6.1): a persist flush that is waiting on the shared LocalDb write lock must not + /// park the actor's dispatcher thread. While another connection holds the write lock the + /// actor keeps processing transitions, and the blocked batch still commits (in order) once + /// the lock is released. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Flush_BlockedOnWriteLock_DoesNotBlockTheActorThread() + { + var instance = CreateTestProbe(); + var dcl = CreateTestProbe(); + var actor = SpawnWithFlush(instance.Ref, dcl.Ref, TimeSpan.FromMilliseconds(50)); + dcl.ExpectMsg(); + + await using var locker = _localDb.Db.CreateConnection(); + await using (var begin = locker.CreateCommand()) + { + begin.CommandText = "BEGIN IMMEDIATE;"; + await begin.ExecuteNonQueryAsync(); + } + + var t0 = DateTimeOffset.UtcNow; + DeliverLiveTransition(actor, "ref-a", severity: 800, t0); + instance.ExpectMsg(); + await Task.Delay(300); // the 50 ms flush has started and is waiting on the lock + + var sw = System.Diagnostics.Stopwatch.StartNew(); + DeliverLiveTransition(actor, "ref-b", severity: 801, t0.AddMilliseconds(1)); + instance.ExpectMsg(TimeSpan.FromMilliseconds(500)); + sw.Stop(); + + await using (var rollback = locker.CreateCommand()) + { + rollback.CommandText = "ROLLBACK;"; + await rollback.ExecuteNonQueryAsync(); + } + + Assert.True(sw.ElapsedMilliseconds < 500, $"actor stalled {sw.ElapsedMilliseconds} ms behind a blocked flush"); + await AwaitAssertAsync(async () => + Assert.Equal(2, (await _storage.GetNativeAlarmsAsync("inst", Source().CanonicalName)).Count), + TimeSpan.FromSeconds(5)); + } + /// A snapshot swap that drops several conditions deletes their rows via the batched flush, and a delete cancels a pending upsert (review 2026-10-21 01/SR-P2). /// A task that represents the asynchronous operation. [Fact] From d3c6295670e5c6460f53d67dac24bac8b090fb36 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:45:50 -0500 Subject: [PATCH 02/12] perf(site-runtime): route expression triggers by referenced keys; heap cap eviction; O(1) predictor lane (SRT-7, SRT-14, CMN-11, WP6 task 6.2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SRT-7: TriggerExpressionKeys extracts the literal Attributes["k"] / Children["c"].Attributes["k"] reads of an Expression trigger; the Instance Actor routes the child only those attributes (new MonitoredAttributes routing kind). Anything not pinnable (non-literal key, alias/member access of the globals, Parent, parse error, zero reads) falls back to all-changes. Child actors are unchanged (narrow: WP3 edits ScriptActor/AlarmActor). Evidence: instance with 250 attributes at 1 Hz and 10 expression children each reading 2 attributes — child mailbox deliveries (and per-eval snapshot copies + CTS allocations) go from 2,500/s to 20/s (routing-map test pins that a non-read attribute has no route). SRT-14: EnforceCap selects the oldest conditions with a bounded max-heap and rate-limits the eviction Warning (1/min with an eviction count). Stopwatch, n=1001 k=1 per transition at the cap: OrderBy 13.0-18.2 us -> heap 1.2 us. CMN-11: FlowShapePredictor looks up a node by the index encoded in its append-only id (O(1)) instead of a linear scan per AddNode/Annotate. Stopwatch PredictSiteScript, Release: 5,000 nodes 125.5 -> 54.9 ms, 20,000 nodes 434.2 -> 83.3 ms. --- docs/requirements/Component-SiteRuntime.md | 4 +- .../FlowShapePredictor.cs | 20 ++- .../Actors/InstanceActor.cs | 13 ++ .../Actors/NativeAlarmActor.cs | 67 ++++++++- .../Scripts/TriggerExpressionKeys.cs | 140 ++++++++++++++++++ .../Scripts/TriggerRouting.cs | 36 ++++- .../Actors/InstanceActorChildRoutingTests.cs | 45 ++++++ .../Actors/NativeAlarmActorTests.cs | 25 ++++ .../Scripts/TriggerExpressionKeysTests.cs | 56 +++++++ 9 files changed, 389 insertions(+), 17 deletions(-) create mode 100644 src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/TriggerExpressionKeysTests.cs diff --git a/docs/requirements/Component-SiteRuntime.md b/docs/requirements/Component-SiteRuntime.md index 9689308a..82986622 100644 --- a/docs/requirements/Component-SiteRuntime.md +++ b/docs/requirements/Component-SiteRuntime.md @@ -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. diff --git a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs index 8fb28308..e6f2986d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/FlowShapePredictor.cs @@ -185,7 +185,7 @@ public static class FlowShapePredictor _nodes.Add(new PredictedNode(id, kind, lane, title, inputDependent, mergedNote)); if (_previous != null) { - var fromLane = _nodes.First(n => n.Id == _previous).Lane; + var fromLane = _nodes[IndexOf(_previous)].Lane; _edges.Add(new PredictedEdge(_previous, id, (fromLane == FlowLane.Central) != (lane == FlowLane.Central), async)); } @@ -194,12 +194,28 @@ public static class FlowShapePredictor return id; } + /// + /// CMN-11: O(1) node lookup. Ids are minted append-only as "n" + (index + 1), so the + /// index is read from the id; the linear scan is only a fallback for a foreign id. + /// + /// The node id. + /// The node's index, or -1 when absent. + private int IndexOf(string id) + { + if (id.Length > 1 && id[0] == 'n' + && int.TryParse(id.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out var ordinal) + && ordinal >= 1 && ordinal <= _nodes.Count + && _nodes[ordinal - 1].Id == id) + return ordinal - 1; + return _nodes.FindIndex(n => n.Id == id); + } + /// Appends a note to an existing node. /// The id of the node to annotate. /// The note to append. internal void Annotate(string id, string note) { - var i = _nodes.FindIndex(n => n.Id == id); + var i = IndexOf(id); if (i < 0) return; var n = _nodes[i]; _nodes[i] = n with { Note = n.Note == null ? note : $"{n.Note}; {note}" }; diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs index 82138943..fae62ba4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs @@ -2180,6 +2180,19 @@ public class InstanceActor : ReceiveActor } list.Add(child); break; + case TriggerRoutingKind.MonitoredAttributes: + // SRT-7: an Expression trigger whose reads are all literal keys hears only + // changes of those attributes (its snapshot is only ever read at those keys). + foreach (var attribute in decision.MonitoredAttributeSet!) + { + if (!_childrenByMonitoredAttribute.TryGetValue(attribute, out var set)) + { + set = new List(); + _childrenByMonitoredAttribute[attribute] = set; + } + set.Add(child); + } + break; case TriggerRoutingKind.AllChanges: _allChangeChildren.Add(child); break; diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs index 26fae600..d1f97baa 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/NativeAlarmActor.cs @@ -443,10 +443,7 @@ public class NativeAlarmActor : ReceiveActor return; } - var overflow = _alarms.Values - .OrderBy(a => a.TransitionTime) - .Take(_alarms.Count - cap) - .ToList(); + var overflow = SelectOldest(_alarms.Values, _alarms.Count - cap); foreach (var evicted in overflow) { @@ -471,12 +468,68 @@ public class NativeAlarmActor : ReceiveActor // This condition is gone for good — evict the parent's // _latestAlarmEvents key so it does not retain a stale entry. NotifyParentDropped(sourceRef); - _logger.LogWarning( - "Native alarm cap {Cap} exceeded for {Source} on {Instance}; dropped oldest mirrored alarm {Ref}", - cap, _source.CanonicalName, _instanceName, sourceRef); + LogCapEviction(cap, sourceRef); } } + /// + /// SRT-14: the oldest mirrored conditions (by transition time), + /// oldest first, chosen with a bounded max-heap — O(n log k) with k almost always 1 — instead + /// of sorting the whole mirror on every transition at the cap. + /// + /// The mirrored conditions. + /// How many to select. + /// The selected conditions, oldest first. + internal static List SelectOldest( + IEnumerable alarms, int count) + { + var result = new List(Math.Max(0, count)); + if (count <= 0) return result; + + // Max-heap on transition time holding the k oldest seen so far. + var heap = new PriorityQueue( + count + 1, Comparer.Create((a, b) => b.CompareTo(a))); + foreach (var alarm in alarms) + { + if (heap.Count < count) + { + heap.Enqueue(alarm, alarm.TransitionTime); + } + else if (heap.TryPeek(out _, out var newestKept) && alarm.TransitionTime < newestKept) + { + heap.EnqueueDequeue(alarm, alarm.TransitionTime); + } + } + + while (heap.TryDequeue(out var alarm, out _)) + result.Add(alarm); + result.Reverse(); // the max-heap drains newest first + return result; + } + + private DateTimeOffset _lastCapWarningAt = DateTimeOffset.MinValue; + private int _capEvictionsSinceWarning; + + /// + /// SRT-14: the cap eviction Warning is rate-limited (once a minute, carrying the count of + /// evictions since the last one) so a sustained flood at the cap does not log a Warning per + /// transition. Evictions are never silent — the first one after a quiet minute logs at once. + /// + private void LogCapEviction(int cap, string sourceRef) + { + _capEvictionsSinceWarning++; + var now = DateTimeOffset.UtcNow; + if (now - _lastCapWarningAt < CapWarningInterval) return; + + _logger.LogWarning( + "Native alarm cap {Cap} exceeded for {Source} on {Instance}; dropped oldest mirrored alarm {Ref} ({Evicted} eviction(s) since the last warning)", + cap, _source.CanonicalName, _instanceName, sourceRef, _capEvictionsSinceWarning); + _lastCapWarningAt = now; + _capEvictionsSinceWarning = 0; + } + + private static readonly TimeSpan CapWarningInterval = TimeSpan.FromMinutes(1); + /// /// Signals the parent Instance Actor that a native condition has /// left the mirror for good so it can evict the matching _latestAlarmEvents diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs new file mode 100644 index 00000000..9056cbf4 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerExpressionKeys.cs @@ -0,0 +1,140 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts; + +/// +/// SRT-7: extracts the canonical attribute keys a trigger expression reads, so an +/// Expression-triggered script/alarm can be routed only the changes it depends on instead +/// of every attribute change on the instance. +/// +/// +/// +/// The walk is deliberately conservative. It recognises exactly the two literal read forms +/// exposes — Attributes["k"] (key k) and +/// Children["c"].Attributes["k"] (key c.k) — and gives up (returns +/// , which routes the child to every change exactly as before) on +/// anything it cannot pin down: a non-literal index, any other use of the +/// Attributes/Children/Parent globals (an alias, a member access, a +/// method-group pass), a parse error, or an expression that reads no attribute at all (it may +/// depend on something other than attribute values, e.g. the clock, and has always been +/// re-evaluated on every change). +/// +/// +/// Routing remains an optimisation: the child's own snapshot/evaluation is unchanged. A child +/// routed by keys simply stops receiving changes for attributes its expression never reads. +/// +/// +internal static class TriggerExpressionKeys +{ + private static readonly CSharpParseOptions ScriptParse = + CSharpParseOptions.Default.WithKind(SourceCodeKind.Script); + + /// + /// Tries to extract the literal attribute keys an expression reads. + /// + /// The trigger expression source. + /// The distinct canonical keys read, when the method returns . + /// when every attribute read is a recognised literal form and at least one exists. + public static bool TryExtract(string? expression, out IReadOnlyList keys) + { + keys = Array.Empty(); + if (string.IsNullOrWhiteSpace(expression)) return false; + + SyntaxTree tree; + try + { + tree = CSharpSyntaxTree.ParseText(expression, ScriptParse); + } + catch + { + return false; + } + + var root = tree.GetRoot(); + if (root.ContainsDiagnostics) return false; + + var found = new List(); + var seen = new HashSet(StringComparer.Ordinal); + + foreach (var id in root.DescendantNodes().OfType()) + { + switch (id.Identifier.ValueText) + { + case "Parent": + return false; + + case "Attributes": + { + // Children["c"].Attributes["k"]: the identifier is the Name of a member access + // whose receiver is a literal Children index. + if (id.Parent is MemberAccessExpressionSyntax member && member.Name == id) + { + if (!TryChildPrefix(member.Expression, out var childPrefix)) return false; + if (!TryLiteralIndex(member, out var key)) return false; + Add(childPrefix + "." + key); + break; + } + + // Attributes["k"] + if (!TryLiteralIndex(id, out var rootKey)) return false; + Add(rootKey); + break; + } + + case "Children": + // Valid only as the receiver of Children["c"].Attributes[...]; that whole + // form is validated from the Attributes identifier above. + if (!IsChildrenReceiver(id)) return false; + break; + } + } + + if (found.Count == 0) return false; + keys = found; + return true; + + void Add(string key) + { + if (seen.Add(key)) found.Add(key); + } + } + + /// True when is directly indexed by one string literal. + private static bool TryLiteralIndex(ExpressionSyntax node, out string key) + { + key = ""; + if (node.Parent is not ElementAccessExpressionSyntax access || access.Expression != node) + return false; + return TrySingleStringLiteral(access.ArgumentList, out key); + } + + /// Matches Children["c"] and returns c. + private static bool TryChildPrefix(ExpressionSyntax receiver, out string prefix) + { + prefix = ""; + return receiver is ElementAccessExpressionSyntax access + && access.Expression is IdentifierNameSyntax { Identifier.ValueText: "Children" } + && TrySingleStringLiteral(access.ArgumentList, out prefix); + } + + private static bool IsChildrenReceiver(IdentifierNameSyntax id) => + id.Parent is ElementAccessExpressionSyntax access + && access.Expression == id + && access.Parent is MemberAccessExpressionSyntax member + && member.Expression == access + && member.Name.Identifier.ValueText == "Attributes" + && TrySingleStringLiteral(access.ArgumentList, out _); + + private static bool TrySingleStringLiteral(BracketedArgumentListSyntax args, out string value) + { + value = ""; + if (args.Arguments.Count != 1) return false; + if (args.Arguments[0].Expression is not LiteralExpressionSyntax literal + || !literal.IsKind(SyntaxKind.StringLiteralExpression)) + return false; + value = literal.Token.ValueText; + return value.Length > 0; + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs index f9bd6044..4b47a6b7 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Scripts/TriggerRouting.cs @@ -14,13 +14,18 @@ internal enum TriggerRoutingKind AllChanges, /// Never reacts to attribute changes (interval / call-only scripts). - None + None, + + /// SRT-7: reacts to changes of any of a set of named attributes — an Expression + /// trigger whose attribute reads are all literal keys (see ). + MonitoredAttributes } /// /// Result of classifying a child's trigger for attribute-change routing. /// -internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind, string? MonitoredAttribute) +internal readonly record struct TriggerRoutingDecision( + TriggerRoutingKind Kind, string? MonitoredAttribute, IReadOnlyList? MonitoredAttributeSet = null) { public static readonly TriggerRoutingDecision AllChanges = new(TriggerRoutingKind.AllChanges, null); public static readonly TriggerRoutingDecision None = new(TriggerRoutingKind.None, null); @@ -29,6 +34,23 @@ internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind, /// The name of the attribute to monitor. /// A of kind . public static TriggerRoutingDecision Monitored(string attribute) => new(TriggerRoutingKind.MonitoredAttribute, attribute); + + /// Creates a decision routing on changes to any of several named attributes (SRT-7). + /// The attribute names to monitor. + /// A of kind . + public static TriggerRoutingDecision MonitoredSet(IReadOnlyList attributes) => + new(TriggerRoutingKind.MonitoredAttributes, null, attributes); + + /// + /// SRT-7: routes an Expression trigger by the literal attribute keys it reads, falling back + /// to all-changes whenever the keys cannot be pinned down. + /// + /// The Expression trigger config JSON. + /// The routing decision. + public static TriggerRoutingDecision ForExpression(string? triggerConfigJson) => + TriggerExpressionKeys.TryExtract(TriggerExpressionGlobals.ExtractExpression(triggerConfigJson), out var keys) + ? MonitoredSet(keys) + : AllChanges; } /// @@ -79,7 +101,8 @@ internal static class TriggerRouting /// /// Classifies a script trigger. valuechange/conditional → the named attribute (fail open to - /// all-changes if unparseable); expression → all-changes; interval/call → none; anything + /// all-changes if unparseable); expression → its literal attribute keys (SRT-7; all-changes + /// when they cannot be extracted); interval/call → none; anything /// unknown → all-changes (fail open — a misconfigured script still reacts, its own gate /// remains the correctness check). /// @@ -96,7 +119,7 @@ internal static class TriggerRouting ? TriggerRoutingDecision.Monitored(attr) : TriggerRoutingDecision.AllChanges; case "expression": - return TriggerRoutingDecision.AllChanges; + return TriggerRoutingDecision.ForExpression(triggerConfigJson); case "interval": case "call": return TriggerRoutingDecision.None; @@ -106,7 +129,8 @@ internal static class TriggerRouting } /// - /// Classifies an alarm trigger. Expression → all-changes; HiLo/ValueMatch/RangeViolation/ + /// Classifies an alarm trigger. Expression → its literal attribute keys (SRT-7; all-changes + /// when they cannot be extracted); HiLo/ValueMatch/RangeViolation/ /// RateOfChange → the named attribute (fail open to all-changes if unparseable); an /// unknown/unparseable trigger type → all-changes (fail open). /// @@ -120,7 +144,7 @@ internal static class TriggerRouting switch (tt) { case AlarmTriggerType.Expression: - return TriggerRoutingDecision.AllChanges; + return TriggerRoutingDecision.ForExpression(triggerConfigJson); case AlarmTriggerType.HiLo: case AlarmTriggerType.ValueMatch: case AlarmTriggerType.RangeViolation: diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorChildRoutingTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorChildRoutingTests.cs index ced04a78..7b4b601c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorChildRoutingTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorChildRoutingTests.cs @@ -116,6 +116,51 @@ public class InstanceActorChildRoutingTests : TestKit, IDisposable Assert.Single(actor.AllChangeChildren); } + /// + /// SRT-7 (WP6 6.2): an Expression script/alarm whose reads are literal keys is routed only to + /// those attributes, so a change to any other attribute no longer reaches it. + /// + [Fact] + public void LiteralKeyExpression_RoutesOnlyToTheAttributesItReads() + { + var config = new FlattenedConfiguration + { + InstanceUniqueName = "ExprKeyPump", + Attributes = + [ + new ResolvedAttribute { CanonicalName = "A", Value = "1", DataType = "Double" }, + new ResolvedAttribute { CanonicalName = "B", Value = "2", DataType = "Double" }, + new ResolvedAttribute { CanonicalName = "C", Value = "3", DataType = "Double" } + ], + Scripts = + [ + new ResolvedScript + { + CanonicalName = "S_expr", Code = "return 3;", + TriggerType = "Expression", + TriggerConfiguration = "{\"expression\":\"(double)Attributes[\\\"A\\\"] > (double)Attributes[\\\"B\\\"]\"}" + } + ], + Alarms = + [ + new ResolvedAlarm + { + CanonicalName = "ExprAlarm", + TriggerType = "Expression", + TriggerConfiguration = "{\"expression\":\"(double)Attributes[\\\"B\\\"] > 1\"}", + PriorityLevel = 1 + } + ] + }; + + var actor = BuildInstance(config); + + Assert.Empty(actor.AllChangeChildren); + Assert.Single(actor.ChildrenByMonitoredAttribute["A"]); // the script + Assert.Equal(2, actor.ChildrenByMonitoredAttribute["B"].Count); // script + alarm + Assert.False(actor.ChildrenByMonitoredAttribute.ContainsKey("C")); + } + /// Verifies that a monitored-attribute alarm routes only to its attribute while an expression alarm routes to all changes. [Fact] public void MonitoredAttributeAlarm_RoutesToItsAttribute_ExpressionAlarm_RoutesToAllChanges() diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs index 9497354c..4b286eb8 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/NativeAlarmActorTests.cs @@ -309,6 +309,31 @@ public class NativeAlarmActorTests : TestKit, IDisposable TimeSpan.FromSeconds(5)); } + /// + /// SRT-14 (WP6 6.2): cap eviction picks the oldest conditions with a bounded heap; the + /// selection (and its oldest-first order) matches the full sort it replaced. + /// + [Theory] + [InlineData(1)] + [InlineData(3)] + [InlineData(10)] + public void SelectOldest_MatchesAFullSort(int count) + { + var rng = new Random(42); + var t0 = DateTimeOffset.UtcNow; + var alarms = Enumerable.Range(0, 1001) + .Select(i => Transition($"ref-{i}", AlarmTransitionKind.Raise, + new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 800), + t0.AddMilliseconds(rng.Next(0, 1_000_000)))) + .ToList(); + + var expected = alarms.OrderBy(a => a.TransitionTime).Take(count).Select(a => a.TransitionTime).ToList(); + var actual = NativeAlarmActor.SelectOldest(alarms, count).Select(a => a.TransitionTime).ToList(); + + Assert.Equal(expected, actual); + Assert.Empty(NativeAlarmActor.SelectOldest(alarms, 0)); + } + /// A snapshot swap that drops several conditions deletes their rows via the batched flush, and a delete cancels a pending upsert (review 2026-10-21 01/SR-P2). /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/TriggerExpressionKeysTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/TriggerExpressionKeysTests.cs new file mode 100644 index 00000000..f4de3490 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/TriggerExpressionKeysTests.cs @@ -0,0 +1,56 @@ +using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts; + +namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts; + +/// +/// SRT-7 (WP6 6.2): an Expression trigger is routed by the literal attribute keys it reads, +/// and falls back to all-changes whenever those keys cannot be pinned down. +/// +public class TriggerExpressionKeysTests +{ + /// Literal root and child reads are extracted as canonical keys. + [Theory] + [InlineData("(double)Attributes[\"Temp\"] > 50", new[] { "Temp" })] + [InlineData("(double)Attributes[\"A\"] > (double)Attributes[\"B\"] && Attributes[\"A\"] != null", new[] { "A", "B" })] + [InlineData("(double)Children[\"Pump1\"].Attributes[\"Speed\"] > 10", new[] { "Pump1.Speed" })] + [InlineData("Attributes[\"Mode\"] as string == \"Auto\" || (bool)Children[\"V\"].Attributes[\"Open\"]", new[] { "Mode", "V.Open" })] + public void LiteralReads_AreExtracted(string expression, string[] expected) + { + Assert.True(TriggerExpressionKeys.TryExtract(expression, out var keys)); + Assert.Equal(expected, keys); + } + + /// Anything that is not a recognised literal read falls back to all-changes. + [Theory] + [InlineData("true")] // no attribute read (may depend on the clock) + [InlineData("DateTime.UtcNow.Second == 0")] + [InlineData("Attributes[\"A\" + \"B\"] != null")] // non-literal key + [InlineData("Attributes[name] != null")] + [InlineData("Parent != null")] + [InlineData("Children[\"P\"].Attributes[k] != null")] // non-literal child key + [InlineData("Children[c].Attributes[\"S\"] != null")] // non-literal child name + [InlineData("((Func)(() => Attributes))() != null")] // alias of the global + [InlineData("(double)Attributes[\"A\"] > 1 && this.Attributes[\"B\"] != null")] + [InlineData("(double)Attributes[\"A\" > 1")] // parse error + [InlineData("")] + public void UnpinnableReads_FallBack(string expression) + { + Assert.False(TriggerExpressionKeys.TryExtract(expression, out _)); + } + + /// Routing decisions for Expression scripts and alarms use the extracted keys. + [Fact] + public void ExpressionRouting_UsesKeysOrFallsBack() + { + var keyed = TriggerRouting.ForScript("Expression", "{\"expression\":\"(double)Attributes[\\\"A\\\"] > 1\"}"); + Assert.Equal(TriggerRoutingKind.MonitoredAttributes, keyed.Kind); + Assert.Equal(new[] { "A" }, keyed.MonitoredAttributeSet); + + var alarm = TriggerRouting.ForAlarm("Expression", "{\"expression\":\"Children[\\\"P\\\"].Attributes[\\\"X\\\"] != null\"}"); + Assert.Equal(TriggerRoutingKind.MonitoredAttributes, alarm.Kind); + Assert.Equal(new[] { "P.X" }, alarm.MonitoredAttributeSet); + + Assert.Equal(TriggerRoutingKind.AllChanges, TriggerRouting.ForScript("Expression", "{\"expression\":\"true\"}").Kind); + Assert.Equal(TriggerRoutingKind.AllChanges, TriggerRouting.ForAlarm("Expression", "not json").Kind); + } +} From 54416e33bfb6b101041224b1034c96bee5afd3f1 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:47:29 -0500 Subject: [PATCH 03/12] perf(store-and-forward): rank sweep lanes over a covering narrow index, join payloads for the page only (SF-3, WP6 task 6.3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fair-paging sweep computed ROW_NUMBER() over every column of every due row, so each sweep sorted the whole due backlog with payloads into temp storage. The ranking now projects only id + lane keys over the new covering idx_sf_messages_lane (status, category, target, created_at, last_attempt_at_ms, retry_interval_ms, id), takes the page of ids, and joins back by primary key. The index is created in place by StoreAndForwardSchema (idempotent, local only — not part of CDC capture). idx_sf_messages_category is kept (still used by parked-count filters). EXPLAIN QUERY PLAN + timing, sqlite3 3.54, 200,000 due rows x ~1 KB payload, 20 targets x 3 categories, LIMIT 500: before: SEARCH idx_sf_messages_status_created (status=?) + USE TEMP B-TREE FOR ORDER BY (window over full rows) + outer temp b-tree; 1.29 s after: SEARCH USING COVERING INDEX idx_sf_messages_lane (no window sort), outer temp b-tree over (id, rank, created_at) only, PK join of 500 rows; 0.15 s --- .../requirements/Component-StoreAndForward.md | 2 +- .../StoreAndForwardSchema.cs | 13 +++++++ .../StoreAndForwardStorage.cs | 37 +++++++++++++++---- .../StoreAndForwardStorageTests.cs | 25 +++++++++++++ 4 files changed, 68 insertions(+), 9 deletions(-) diff --git a/docs/requirements/Component-StoreAndForward.md b/docs/requirements/Component-StoreAndForward.md index c26d0938..b16ee540 100644 --- a/docs/requirements/Component-StoreAndForward.md +++ b/docs/requirements/Component-StoreAndForward.md @@ -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. 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. 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 diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs index 8f9ab17b..0a2b47e9 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs @@ -111,6 +111,19 @@ public static class StoreAndForwardSchema "CREATE INDEX IF NOT EXISTS idx_sf_messages_status_created ON sf_messages(status, created_at)"; orderIndex.ExecuteNonQuery(); } + + // SF-3: covering index for the sweep's fair lane ranking. Leading (status, category, + // target, created_at) matches ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY + // created_at) so the window reads rows already in lane order with no sort, and the + // trailing due-predicate columns + id make it covering, so the ranking never reads a + // payload. Applied in place on every boot (idempotent); local only — indexes are not + // part of LocalDb's CDC capture. + using (var laneIndex = connection.CreateCommand()) + { + laneIndex.CommandText = + "CREATE INDEX IF NOT EXISTS idx_sf_messages_lane ON sf_messages(status, category, target, created_at, last_attempt_at_ms, retry_interval_ms, id)"; + laneIndex.ExecuteNonQuery(); + } } /// diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs index 8b3b008f..da86490c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs @@ -211,16 +211,28 @@ public class StoreAndForwardStorage // hundreds of due rows contributes one row per "round" like every other // lane instead of owning the whole page. Within a lane rank order == created_at // order, so per-target FIFO is preserved for the service's GroupBy. + // + // SF-3: the ranking runs over a NARROW projection (id + lane keys) that + // idx_sf_messages_lane covers in (category, target, created_at) order, so the window + // needs no sort and never touches a payload; only the chosen page of ids is joined + // back for the full rows. Ranking over every column used to sort the whole due + // backlog — payloads included — on every sweep. cmd.CommandText = $@" - SELECT {cols} - FROM ( - SELECT {cols}, - ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at ASC) AS lane_rank - FROM sf_messages - WHERE {due} + WITH page AS ( + SELECT id, lane_rank, created_at + FROM ( + SELECT id, created_at, + ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at ASC) AS lane_rank + FROM sf_messages + WHERE {due} + ) + ORDER BY lane_rank ASC, created_at ASC + LIMIT @limit ) - ORDER BY lane_rank ASC, created_at ASC - LIMIT @limit"; + SELECT {SweepColumnsM} + FROM page p + JOIN sf_messages m ON m.id = p.id + ORDER BY p.lane_rank ASC, p.created_at ASC"; cmd.Parameters.AddWithValue("@limit", limit); } else @@ -238,6 +250,15 @@ public class StoreAndForwardStorage return await ReadMessagesAsync(cmd); } + /// The sweep's column list qualified with the m alias (SF-3 join-back). + private static readonly string SweepColumnsM = + string.Join(", ", new[] + { + "id", "category", "target", "payload_json", "retry_count", "max_retries", + "retry_interval_ms", "created_at", "last_attempt_at", "status", "last_error", "origin_instance", + "execution_id", "source_script", "parent_execution_id", + }.Select(c => "m." + c)); + /// /// Updates a message after a delivery attempt. /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs index d55c495e..c1d7e2c6 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs @@ -853,6 +853,31 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable Assert.Equal("a000", dead[0]); } + /// + /// SF-3 (WP6 6.3): the sweep ranks lanes over the covering lane index (no payload read, no + /// sort for the window) and joins back only the chosen page by primary key. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task GetMessagesForRetry_RanksOverTheCoveringLaneIndex() + { + await using var connection = _localDb.Db.CreateConnection(); + await using var cmd = connection.CreateCommand(); + cmd.CommandText = @"EXPLAIN QUERY PLAN + SELECT id, created_at, + ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at ASC) AS lane_rank + FROM sf_messages + WHERE status = 0 + AND (last_attempt_at_ms IS NULL OR retry_interval_ms = 0 OR (1 - last_attempt_at_ms) >= retry_interval_ms)"; + var plan = new List(); + await using (var reader = await cmd.ExecuteReaderAsync()) + while (await reader.ReadAsync()) + plan.Add(reader.GetString(3)); + + Assert.Contains(plan, p => p.Contains("COVERING INDEX idx_sf_messages_lane")); + Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE")); + } + // ReplaceAll_SwapsTheEntireBuffer_Atomically was DELETED with ReplaceAllAsync in // LocalDb Phase 2, and deliberately not replaced. It asserted a destructive // delete-all-then-insert-all, which was the standby's anti-entropy apply: a resync From 9f03726fc7613e68db7c2397951fc69aa6599ae0 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:58:29 -0500 Subject: [PATCH 04/12] perf(audit-log): private-cache connections, owed-range pull index, age-seekable purge, batched tracking reads (AUD-2, AUD-3, AUD-4, AUD-7, WP6 task 6.4) AUD-2: drop Cache=Shared from the file-backed site audit connection string (kept only by the in-memory test override). Two private WAL connections no longer share table-level locks. Test OpenReadTransaction_DoesNotStallTheWriter (deferred read txn open on a connection with the writer's connection string): with Cache=Shared the write timed out (>5 s; would retry to the 30 s command timeout and fault); without it the write completes in well under 1 s. AUD-3: new partial index IX_fwd_owed (OccurredAtUtc, EventId) WHERE ForwardState IN (owed states); ReadPendingSinceAsync names it (INDEXED BY), repeats the literal state list (bound parameters never satisfy a partial index's WHERE), and orders/keysets on fs.EventId (same value, no join for the sort). sqlite3 3.54, 1,000,000 audit rows (90% Pending), no ANALYZE stats, 256-row page: before: SEARCH fs USING INDEX IX_fwd (ForwardState=?) + TEMP B-TREE FOR ORDER BY; 2.6-3.5 s after: SEARCH fs USING INDEX IX_fwd_owed (OccurredAtUtc>?), no sort; 0.6-0.7 ms (keyset page with afterId: 3.6 s -> 0.6 ms) AUD-4: purge page adds IsCachedKind IN (0, 1) so IX_fwd seeks (state, kind, age). same DB, 100k Forwarded rows, nothing expiring (the final short page): before: SEARCH IX_fwd (ForwardState=?) 16.9 ms (linear in retained rows) after: SEARCH IX_fwd (ForwardState=? AND IsCachedKind=? AND OccurredAtUtc 1 barrier, 1 connection, 1 query (ids sharing an operation are read once). --- docs/requirements/Component-AuditLog.md | 11 ++ .../Site/SqliteAuditWriter.cs | 49 ++++++- .../Site/Telemetry/SiteAuditTelemetryActor.cs | 47 +++++- .../Services/IOperationTrackingBatchReader.cs | 28 ++++ .../Tracking/OperationTrackingStore.cs | 59 +++++++- .../Site/SqliteAuditWriterIndexingTests.cs | 138 ++++++++++++++++++ .../Telemetry/SiteAuditTelemetryActorTests.cs | 49 +++++++ .../Tracking/OperationTrackingStoreTests.cs | 27 ++++ 8 files changed, 395 insertions(+), 13 deletions(-) create mode 100644 src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/SqliteAuditWriterIndexingTests.cs diff --git a/docs/requirements/Component-AuditLog.md b/docs/requirements/Component-AuditLog.md index f0af2960..ac5eba56 100644 --- a/docs/requirements/Component-AuditLog.md +++ b/docs/requirements/Component-AuditLog.md @@ -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. diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs index b1728e1e..aaa06dc1 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs @@ -102,8 +102,18 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi _logger = logger; _nodeIdentity = nodeIdentity; + // AUD-2: a PRIVATE cache per connection. With Cache=Shared both connections shared one + // cache and its table-level locks, so WAL snapshot isolation did not apply between them — + // a long backlog scan on the read connection stalled the batch writer (in 150 ms + // SQLITE_LOCKED retry sleeps, up to the command timeout) and vice versa. Two private WAL + // connections let reads run against a snapshot while the writer commits. The busy + // timeout stays Microsoft.Data.Sqlite's default command timeout (30 s), which only a + // second writer could ever hit — there is one write connection. (The in-memory test + // override still uses Mode=Memory;Cache=Shared, which needs the shared cache to share + // one database at all.) var connectionString = connectionStringOverride - ?? $"Data Source={_options.DatabasePath};Cache=Shared"; + ?? $"Data Source={_options.DatabasePath}"; + ConnectionString = connectionString; _connection = new SqliteConnection(connectionString); _connection.Open(); @@ -227,7 +237,7 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi } using var cmd = _connection.CreateCommand(); - cmd.CommandText = """ + cmd.CommandText = $""" -- Canonical, append-only / write-once: the 10 fields of the canonical -- ZB.MOM.WW.Audit.AuditEvent stored directly (DetailsJson carries the -- ScadaBridge domain fields). No forwarding state lives here — that is @@ -268,6 +278,17 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi CREATE INDEX IF NOT EXISTS IX_fwd ON audit_forward_state (ForwardState, IsCachedKind, OccurredAtUtc); + -- AUD-3: the reconciliation pull reads the OWED states ordered by + -- (OccurredAtUtc, EventId); IX_fwd cannot serve that across an IN of three + -- states, so every page scanned + sorted the whole owed backlog. This partial + -- index is exactly the pull's range and order, so a page is an ordered range + -- read that stops at the limit. The query names it with INDEXED BY and repeats + -- the same literal state list (a partial index is only usable when the query's + -- WHERE implies the index's). Additive and idempotent. + CREATE INDEX IF NOT EXISTS IX_fwd_owed + ON audit_forward_state (OccurredAtUtc, EventId) + WHERE ForwardState IN ({OwedStatesSql}); + -- Node-local key/value state that must survive a process restart. Holds the -- reconciliation pull's served-rows high-water mark ('max_served_rowid'), so a -- restart no longer resets the bound that lets a covering cursor retire rows the @@ -866,7 +887,8 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi ? "fs.OccurredAtUtc >= $since" // Composite keyset, lexicographic on (OccurredAtUtc, EventId) — the same // ordering the query applies, so it is a strict "everything after this row". - : "(fs.OccurredAtUtc > $since OR (fs.OccurredAtUtc = $since AND ae.EventId > $afterId))"; + // The OccurredAtUtc >= $since conjunct is implied but lets the index seek. + : "fs.OccurredAtUtc >= $since AND (fs.OccurredAtUtc > $since OR (fs.OccurredAtUtc = $since AND fs.EventId > $afterId))"; // fs.rowid rides along as an 11th column purely to maintain // _maxServedRowId — the insertion-order high-water mark that bounds @@ -876,14 +898,13 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi SELECT ae.EventId, ae.OccurredAtUtc, ae.Actor, ae.Action, ae.Outcome, ae.Category, ae.Target, ae.SourceNode, ae.CorrelationId, ae.DetailsJson, fs.rowid - FROM audit_event ae - JOIN audit_forward_state fs ON fs.EventId = ae.EventId - WHERE fs.ForwardState IN ($pending, $pushAbandoned, $rejected) + FROM audit_forward_state fs INDEXED BY IX_fwd_owed + JOIN audit_event ae ON ae.EventId = fs.EventId + WHERE fs.ForwardState IN ({OwedStatesSql}) AND {cursorPredicate} - ORDER BY fs.OccurredAtUtc ASC, ae.EventId ASC + ORDER BY fs.OccurredAtUtc ASC, fs.EventId ASC LIMIT $limit; """; - AddOwedStateParameters(cmd); // Normalise to UTC ISO-8601 round-trip format to match how OccurredAtUtc // is stored on insert ("o" format) — string comparison is monotonic for // that encoding so we can index-scan against it. @@ -931,6 +952,17 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi /// Binds the three "owed to central" states — $pending, $pushAbandoned, /// $rejected — that the reconciliation pull serves and retires. /// + /// + /// AUD-3: the owed states as SQL literals, shared by the IX_fwd_owed partial-index + /// definition and the pull query that uses it — SQLite only uses a partial index when the + /// query's WHERE implies the index's, which a bound parameter never does. + /// + internal static readonly string OwedStatesSql = + $"'{AuditForwardState.Pending}', '{SiteAuditForwardStates.PushAbandoned}', '{SiteAuditForwardStates.Rejected}'"; + + /// The connection string both connections were opened with (AUD-2 regression surface). + internal string ConnectionString { get; } + private static void AddOwedStateParameters(SqliteCommand cmd) { cmd.Parameters.AddWithValue("$pending", AuditForwardState.Pending.ToString()); @@ -1535,6 +1567,7 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi CREATE TEMP TABLE purge_ids AS SELECT EventId FROM audit_forward_state WHERE ForwardState IN ($forwarded, $reconciled) + AND IsCachedKind IN (0, 1) -- AUD-4: lets IX_fwd seek (state, kind, age) instead of walking each state's whole range AND OccurredAtUtc < $cutoff LIMIT $limit; """; diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs index 4fb0253e..3790800a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs @@ -233,6 +233,44 @@ public class SiteAuditTelemetryActor : ReceiveActor } } + /// + /// AUD-7: builds the per-drain tracking lookup. With an + /// the distinct ids are read in one batched call (a fault there surfaces per row, exactly as a + /// per-id fault did, so those rows stay Pending); otherwise each distinct id is read once and + /// memoised for the drain. + /// + private async Task>> PrefetchTrackingAsync( + IReadOnlyList pending, CancellationToken ct) + { + var store = _trackingStore!; + if (store is IOperationTrackingBatchReader batchReader) + { + var ids = pending + .Where(r => r.CorrelationId is not null) + .Select(r => new TrackedOperationId(r.CorrelationId!.Value)) + .Distinct() + .ToList(); + try + { + var found = await batchReader.GetStatusManyAsync(ids, ct).ConfigureAwait(false); + return id => Task.FromResult(found.TryGetValue(id, out var s) ? s : null); + } + catch (Exception ex) + { + return _ => Task.FromException(ex); + } + } + + var memo = new Dictionary(); + return async id => + { + if (memo.TryGetValue(id, out var cached)) return cached; + var snapshot = await store.GetStatusAsync(id, ct).ConfigureAwait(false); + memo[id] = snapshot; + return snapshot; + }; + } + /// /// Combined-telemetry drain. Reads cached-lifecycle audit /// rows, joins each with the matching @@ -287,6 +325,12 @@ public class SiteAuditTelemetryActor : ReceiveActor var graceSeconds = Math.Max(0, _options.CachedTrackingGraceSeconds); var abandonBefore = DateTime.UtcNow - TimeSpan.FromSeconds(graceSeconds); + // AUD-7: the tracking store is a single-writer queue whose every read waits behind + // all queued writes. Resolve the batch's distinct operation ids ONCE — one barrier + // for the drain when the store offers a batched read, and never the same id twice + // (several lifecycle rows of one operation share it) otherwise. + var lookup = await PrefetchTrackingAsync(pending, ct).ConfigureAwait(false); + foreach (var auditRow in pending) { if (auditRow.CorrelationId is null) @@ -302,8 +346,7 @@ public class SiteAuditTelemetryActor : ReceiveActor TrackingStatusSnapshot? snapshot; try { - snapshot = await _trackingStore - .GetStatusAsync(new TrackedOperationId(auditRow.CorrelationId.Value), ct) + snapshot = await lookup(new TrackedOperationId(auditRow.CorrelationId.Value)) .ConfigureAwait(false); } catch (Exception ex) diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs new file mode 100644 index 00000000..a3efb977 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs @@ -0,0 +1,28 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Types; + +// Same namespace convention as IOperationTrackingStore (see the note there). +namespace ZB.MOM.WW.ScadaBridge.Commons.Interfaces; + +/// +/// Optional batched read surface of an (AUD-7). +/// +/// +/// Kept as a separate interface rather than a new member so +/// existing implementations and test doubles are untouched: a consumer probes for it and falls +/// back to per-id when it is absent. The +/// read has the same read-your-writes guarantee as GetStatusAsync, but pays the writer +/// queue barrier once for the whole set instead of once per id. +/// +public interface IOperationTrackingBatchReader +{ + /// + /// Returns the latest snapshot of each supplied id that has a tracking row. Ids with no row + /// (purged or never recorded) are absent from the result. + /// + /// The operation ids to read; duplicates are ignored. + /// Cancellation token. + /// The snapshots found, keyed by id. + Task> GetStatusManyAsync( + IReadOnlyCollection ids, + CancellationToken ct = default); +} diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs index ec2e37b4..179607fb 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs @@ -51,7 +51,7 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tracking; /// path. /// /// -public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, IDisposable +public class OperationTrackingStore : IOperationTrackingStore, IOperationTrackingBatchReader, IAsyncDisposable, IDisposable { /// Queue bound; past it Record*Async waits (never drops). internal const int MaxQueuedWrites = 8192; @@ -536,7 +536,61 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, return null; } - return new TrackingStatusSnapshot( + return ReadSnapshot(reader); + } + + /// Most ids bound into one IN (…) read (well under SQLite's parameter limit). + private const int MaxIdsPerStatusRead = 500; + + /// + /// + /// AUD-7: one writer-queue barrier for the whole set, then chunked IN (…) reads on one + /// connection — instead of a barrier + connection + query per id. + /// + public async Task> GetStatusManyAsync( + IReadOnlyCollection ids, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(ids); + var result = new Dictionary(); + if (ids.Count == 0) + { + return result; + } + + await WaitForQueuedWritesAsync(ct).ConfigureAwait(false); + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposeState) != 0, this); + + await using var readConnection = _localDb.CreateConnection(); + foreach (var chunk in ids.Select(i => i.ToString()).Distinct(StringComparer.Ordinal).Chunk(MaxIdsPerStatusRead)) + { + await using var cmd = readConnection.CreateCommand(); + var names = new string[chunk.Length]; + for (var i = 0; i < chunk.Length; i++) + { + names[i] = "$id" + i.ToString(CultureInfo.InvariantCulture); + cmd.Parameters.AddWithValue(names[i], chunk[i]); + } + + cmd.CommandText = + "SELECT TrackedOperationId, Kind, TargetSummary, Status, " + + "RetryCount, LastError, HttpStatus, CreatedAtUtc, UpdatedAtUtc, TerminalAtUtc, " + + "SourceInstanceId, SourceScript, SourceNode " + + "FROM OperationTracking WHERE TrackedOperationId IN (" + string.Join(", ", names) + ");"; + + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) + { + var snapshot = ReadSnapshot(reader); + result[snapshot.Id] = snapshot; + } + } + + return result; + } + + private static TrackingStatusSnapshot ReadSnapshot(SqliteDataReader reader) => + new TrackingStatusSnapshot( Id: TrackedOperationId.Parse(reader.GetString(0)), Kind: reader.GetString(1), TargetSummary: reader.IsDBNull(2) ? null : reader.GetString(2), @@ -550,7 +604,6 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, SourceInstanceId: reader.IsDBNull(10) ? null : reader.GetString(10), SourceScript: reader.IsDBNull(11) ? null : reader.GetString(11), SourceNode: reader.IsDBNull(12) ? null : reader.GetString(12)); - } /// public async Task PurgeTerminalAsync( diff --git a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/SqliteAuditWriterIndexingTests.cs b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/SqliteAuditWriterIndexingTests.cs new file mode 100644 index 00000000..ef712f01 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/SqliteAuditWriterIndexingTests.cs @@ -0,0 +1,138 @@ +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.Audit; +using ZB.MOM.WW.ScadaBridge.AuditLog.Site; +using ZB.MOM.WW.ScadaBridge.AuditLog.Tests.TestSupport; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; + +namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Site; + +/// +/// WP6 task 6.4: connection isolation (AUD-2) and the index shapes behind the reconciliation +/// pull (AUD-3) and the retention purge (AUD-4). +/// +public class SqliteAuditWriterIndexingTests : IDisposable +{ + private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"audit-idx-{Guid.NewGuid():N}.db"); + + /// Deletes the temp database files. + public void Dispose() + { + SqliteConnection.ClearAllPools(); + foreach (var suffix in new[] { "", "-wal", "-shm" }) + { + try { File.Delete(_dbPath + suffix); } catch { /* best-effort */ } + } + } + + private SqliteAuditWriter CreateWriter() => new( + Options.Create(new SqliteAuditWriterOptions { DatabasePath = _dbPath }), + NullLogger.Instance, + new FakeNodeIdentityProvider()); + + private static AuditEvent NewEvent(DateTime occurredAtUtc) => ScadaBridgeAuditEventFactory.Create( + eventId: Guid.NewGuid(), + occurredAtUtc: occurredAtUtc, + channel: AuditChannel.ApiOutbound, + kind: AuditKind.ApiCall, + status: AuditStatus.Delivered); + + /// + /// AUD-2: an open read transaction on a connection opened like the writer's read connection + /// must not stall the batch writer (it did under Cache=Shared: table-level shared-cache locks). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task OpenReadTransaction_DoesNotStallTheWriter() + { + await using var writer = CreateWriter(); + Assert.DoesNotContain("Cache=Shared", writer.ConnectionString, StringComparison.OrdinalIgnoreCase); + await writer.WriteAsync(NewEvent(DateTime.UtcNow)); + + await using var reader = new SqliteConnection(writer.ConnectionString); + await reader.OpenAsync(); + await using var tx = reader.BeginTransaction(deferred: true); + await using (var select = reader.CreateCommand()) + { + select.Transaction = tx; + select.CommandText = "SELECT COUNT(*) FROM audit_event"; + Assert.Equal(1L, (long)(await select.ExecuteScalarAsync())!); + } + + var sw = System.Diagnostics.Stopwatch.StartNew(); + await writer.WriteAsync(NewEvent(DateTime.UtcNow)).WaitAsync(TimeSpan.FromSeconds(5)); + sw.Stop(); + Assert.True(sw.ElapsedMilliseconds < 1000, $"writer stalled {sw.ElapsedMilliseconds} ms behind an open read"); + } + + /// + /// AUD-3: the pull pages the owed backlog as an ordered range of IX_fwd_owed (no temp sort), + /// and the keyset cursor still yields every owed row exactly once, in order. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReconciliationPull_IsAnOrderedRangeRead_AndPagesCorrectly() + { + await using var writer = CreateWriter(); + var t0 = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc); + var ids = new List(); + for (var i = 0; i < 25; i++) + { + // pairs share an instant so the EventId tiebreak is exercised + var e = NewEvent(t0.AddSeconds(i / 2)); + ids.Add(e.EventId); + await writer.WriteAsync(e); + } + + var served = new List(); + var since = DateTime.MinValue.ToUniversalTime(); + string? afterId = null; + while (true) + { + var page = await writer.ReadPendingSinceAsync(since, 4, afterId); + if (page.Count == 0) break; + served.AddRange(page.Select(p => p.EventId)); + since = page[^1].OccurredAtUtc.UtcDateTime; + afterId = page[^1].EventId.ToString(); + } + Assert.Equal(ids.Count, served.Count); + Assert.Equal(served.Count, served.Distinct().Count()); + + var plan = await PlanAsync($""" + SELECT fs.EventId FROM audit_forward_state fs INDEXED BY IX_fwd_owed + JOIN audit_event ae ON ae.EventId = fs.EventId + WHERE fs.ForwardState IN ({SqliteAuditWriter.OwedStatesSql}) AND fs.OccurredAtUtc >= '2026' + ORDER BY fs.OccurredAtUtc ASC, fs.EventId ASC LIMIT 256 + """); + Assert.Contains(plan, p => p.Contains("IX_fwd_owed")); + Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE")); + } + + /// AUD-4: the purge page seeks IX_fwd on (state, kind, age) rather than state alone. + /// A task that represents the asynchronous operation. + [Fact] + public async Task PurgePage_SeeksOnAge() + { + await using (CreateWriter()) { } + var plan = await PlanAsync(""" + SELECT EventId FROM audit_forward_state + WHERE ForwardState IN ('Forwarded', 'Reconciled') AND IsCachedKind IN (0, 1) + AND OccurredAtUtc < '2026' LIMIT 5000 + """); + Assert.Contains(plan, p => p.Contains("IX_fwd") && p.Contains("OccurredAtUtc> PlanAsync(string sql) + { + await using var connection = new SqliteConnection($"Data Source={_dbPath}"); + await connection.OpenAsync(); + await using var cmd = connection.CreateCommand(); + cmd.CommandText = "EXPLAIN QUERY PLAN " + sql; + var plan = new List(); + await using var r = await cmd.ExecuteReaderAsync(); + while (await r.ReadAsync()) plan.Add(r.GetString(3)); + return plan; + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/Telemetry/SiteAuditTelemetryActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/Telemetry/SiteAuditTelemetryActorTests.cs index 8d4e4c43..2f5ffd09 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/Telemetry/SiteAuditTelemetryActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/Telemetry/SiteAuditTelemetryActorTests.cs @@ -416,6 +416,55 @@ public class SiteAuditTelemetryActorTests : TestKit Assert.Equal(expectedIds, emittedEventIds); } + /// + /// AUD-7 (WP6 6.4): a drain resolves its rows' tracking snapshots with ONE batched read of + /// the distinct ids when the store offers it, instead of one writer-queue barrier per row. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task CachedDrain_ResolvesTrackingWithOneBatchedRead() + { + var store = Substitute.For(); + var op = Guid.NewGuid(); + var other = Guid.NewGuid(); + var cachedRows = new[] + { + NewCachedEvent(AuditKind.CachedSubmit, correlationId: op), + NewCachedEvent(AuditKind.ApiCallCached, correlationId: op), + NewCachedEvent(AuditKind.CachedResolve, correlationId: other), + }; + _queue.ReadPendingAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>(Array.Empty())); + _queue.ReadPendingCachedTelemetryAsync(Arg.Any(), Arg.Any()) + .Returns( + Task.FromResult>(cachedRows), + Task.FromResult>(Array.Empty())); + ((IOperationTrackingBatchReader)store) + .GetStatusManyAsync(Arg.Any>(), Arg.Any()) + .Returns(c => Task.FromResult>( + c.Arg>().ToDictionary(id => id, id => NewSnapshot(id)))); + _client.IngestCachedTelemetryAsync(Arg.Any(), Arg.Any()) + .Returns(call => + { + var ack = new IngestAck(); + foreach (var packet in call.Arg().Packets) + ack.AcceptedEventIds.Add(packet.AuditEvent.EventId); + return Task.FromResult(ack); + }); + + Sys.ActorOf(Props.Create(() => new SiteAuditTelemetryActor( + _queue, _client, Opts(), NullLogger.Instance, + (IOperationTrackingStore?)store))); + + await AwaitAssertAsync(async () => + await _queue.Received(1).MarkForwardedAsync( + Arg.Is>(g => g.Count == 3), Arg.Any()), + TimeSpan.FromSeconds(5)); + await ((IOperationTrackingBatchReader)store).Received(1).GetStatusManyAsync( + Arg.Is>(ids => ids.Count == 2), Arg.Any()); + await store.DidNotReceiveWithAnyArgs().GetStatusAsync(default, default); + } + /// /// Verifies that the tracking-row versions central ACCEPTED are recorded as central acks /// in the tracking store — and only those — so the SiteCalls reconciliation pull stops diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs index 68389a04..6fb73241 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs @@ -282,6 +282,33 @@ public class OperationTrackingStoreTests : IDisposable Assert.Equal("node-a", snapshot!.SourceNode); } + /// + /// AUD-7 (WP6 6.4): the batched read returns every recorded id (read-your-writes, across + /// more ids than one IN-chunk) and omits ids with no row. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task GetStatusManyAsync_ReturnsRecordedIds_AndOmitsMissing() + { + var (store, _) = CreateStore(nameof(GetStatusManyAsync_ReturnsRecordedIds_AndOmitsMissing)); + await using var _store = store; + + var recorded = Enumerable.Range(0, 1203).Select(_ => TrackedOperationId.New()).ToList(); + foreach (var id in recorded) + { + await store.RecordEnqueueAsync(id, kind: nameof(AuditKind.ApiCallCached), targetSummary: "ERP.GetOrder", + sourceInstanceId: null, sourceScript: null, sourceNode: "node-a"); + } + var missing = TrackedOperationId.New(); + + var found = await store.GetStatusManyAsync(recorded.Append(missing).Append(recorded[0]).ToList()); + + Assert.Equal(recorded.Count, found.Count); + Assert.All(recorded, id => Assert.Equal(id, found[id].Id)); + Assert.False(found.ContainsKey(missing)); + Assert.Empty(await store.GetStatusManyAsync(Array.Empty())); + } + /// Verifies that recording an enqueue persists a null source node. /// A task that represents the asynchronous operation. [Fact] From 04e39690719d38a34fb6339a2ca9956e1e8759a2 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:00:42 -0500 Subject: [PATCH 05/12] perf(audit-log,site-event-log): channel+age purge index with varchar binding; instance+timestamp event index (AUD-5, SEL-1, WP6 task 6.5) AUD-5: PurgeChannelOlderThanAsync binds @channel as varchar(32) and the model gains IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc). The migration + partition-aligned SQL script land in the WP's final migration commit (AuditLogChannelOccurredIndex). sqlcmd -I, SQL_Latin1_General_CP1_CI_AS, scratch DB with 1M AuditLog rows (6 channels, clustered (OccurredAtUtc, EventId), ScriptTrace override 30 d), steady-state per-channel tick (nothing left to purge): before (nvarchar, old indexes): 5,858 logical reads, 124 ms after (varchar + new index): 6 logical reads, 0 ms new index but nvarchar param: 4,747 logical reads, 114 ms (binding matters) SEL-1: site_events idx_events_instance -> idx_events_instance_timestamp (instance_id, timestamp), dropped/rebuilt in place by SiteEventLogSchema.Apply like #123; the storage-cap size model now charges 4 x timestamp per row. sqlite3, 2.7M rows / 20 instances, instance-filtered 501-row page: before: SEARCH idx_events_instance + USE TEMP B-TREE FOR ORDER BY; 396 ms after: SEARCH idx_events_instance_timestamp (temp b-tree for id tiebreak only); 0.7 ms --- docs/requirements/Component-AuditLog.md | 4 +++- .../Component-SiteEventLogging.md | 7 ++++++ .../AuditLogEntityTypeConfiguration.cs | 8 +++++++ .../Repositories/AuditLogRepository.cs | 8 +++---- .../EventLogPurgeService.cs | 9 ++++---- .../SiteEventLogSchema.cs | 8 ++++++- .../Repositories/AuditPurgeBudgetTests.cs | 23 +++++++++++++++++++ .../SchemaIndexTests.cs | 3 ++- .../SiteEventLogSchemaTests.cs | 2 +- .../SiteEventsSchemaCalibrationTests.cs | 8 +++---- 10 files changed, 64 insertions(+), 16 deletions(-) diff --git a/docs/requirements/Component-AuditLog.md b/docs/requirements/Component-AuditLog.md index ac5eba56..b81587c8 100644 --- a/docs/requirements/Component-AuditLog.md +++ b/docs/requirements/Component-AuditLog.md @@ -761,7 +761,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 diff --git a/docs/requirements/Component-SiteEventLogging.md b/docs/requirements/Component-SiteEventLogging.md index 01c592e0..edcbf412 100644 --- a/docs/requirements/Component-SiteEventLogging.md +++ b/docs/requirements/Component-SiteEventLogging.md @@ -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). diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs index 6a0fe5a3..df8cff37 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs @@ -235,6 +235,14 @@ public class AuditLogEntityTypeConfiguration : IEntityTypeConfiguration new { e.Channel, e.OccurredAtUtc }) + .HasDatabaseName("IX_AuditLog_Channel_Occurred"); + builder.HasIndex(e => new { e.Target, e.OccurredAtUtc }) .IsDescending(false, true) .HasFilter("[Target] IS NOT NULL") diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs index 1c6daddc..9580b291 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs @@ -769,10 +769,10 @@ VALUES pBatch.Value = (int)Math.Min(batchSize, maxRows - totalDeleted); cmd.Parameters.Add(pBatch); - var pChannel = cmd.CreateParameter(); - pChannel.ParameterName = "@channel"; - pChannel.Value = channel; - cmd.Parameters.Add(pChannel); + // AUD-5: bind as varchar(32) to match the Category column. An untyped string + // parameter goes out as nvarchar, which under a SQL collation converts the + // column side and rules out a seek on IX_AuditLog_Channel_Occurred. + AddParameter(cmd, "@channel", SqlDbType.VarChar, size: 32, channel); var pThreshold = cmd.CreateParameter(); pThreshold.ParameterName = "@threshold"; diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs index a9d12d7a..45cc347e 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs @@ -90,9 +90,10 @@ public class EventLogPurgeService : BackgroundService private const double TablePageFillFactor = 0.78; /// - /// Number of secondary indexes on site_events: timestamp, instance_id, + /// Number of secondary indexes on site_events: timestamp, (instance_id, timestamp), /// (event_type, timestamp) and (severity, timestamp). The sampled indexed_bytes - /// charges every covered column once per index, hence 3 * octet_length(timestamp). + /// charges every covered column once per index, hence 4 * octet_length(timestamp) + /// (SEL-1 added timestamp to the instance index). /// private const int IndexedColumnCount = 4; @@ -734,7 +735,7 @@ public class EventLogPurgeService : BackgroundService + octet_length(severity) + COALESCE(octet_length(instance_id), 0) + octet_length(source) + octet_length(message) + COALESCE(octet_length(details), 0) AS payload_bytes, - (3 * octet_length(timestamp)) + octet_length(event_type) + (4 * octet_length(timestamp)) + octet_length(event_type) + octet_length(severity) + COALESCE(octet_length(instance_id), 0) AS indexed_bytes FROM site_events LIMIT {SizeSampleRows} @@ -746,7 +747,7 @@ public class EventLogPurgeService : BackgroundService + octet_length(severity) + COALESCE(octet_length(instance_id), 0) + octet_length(source) + octet_length(message) + COALESCE(octet_length(details), 0) AS payload_bytes, - (3 * octet_length(timestamp)) + octet_length(event_type) + (4 * octet_length(timestamp)) + octet_length(event_type) + octet_length(severity) + COALESCE(octet_length(instance_id), 0) AS indexed_bytes FROM site_events ORDER BY rowid DESC LIMIT {SizeSampleRows} diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs index 04581b72..cd48a6b4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs @@ -67,7 +67,8 @@ public static class SiteEventLogSchema details TEXT ); CREATE INDEX IF NOT EXISTS idx_events_timestamp ON site_events(timestamp); - CREATE INDEX IF NOT EXISTS idx_events_instance ON site_events(instance_id); + DROP INDEX IF EXISTS idx_events_instance; + CREATE INDEX IF NOT EXISTS idx_events_instance_timestamp ON site_events(instance_id, timestamp); DROP INDEX IF EXISTS idx_events_type; DROP INDEX IF EXISTS idx_events_severity; CREATE INDEX IF NOT EXISTS idx_events_type_timestamp ON site_events(event_type, timestamp); @@ -85,6 +86,11 @@ public static class SiteEventLogSchema // part of LocalDb's replicated-table digest, so a pair may upgrade one node at a // time as far as this change is concerned. // + // SEL-1 (2026-12-03): the instance_id index got the same treatment — the Instances + // page drill-in filters by instance and orders by (timestamp, id), which the old + // single-column idx_events_instance could only answer by fetching and sorting every + // row of that instance. Dropped and rebuilt in place on first boot, like #123. + // // The query service also supports keyword search via leading-wildcard // LIKE on message/source. A leading-wildcard LIKE cannot use a B-tree // index, so that path intentionally full-scans; severity/event_type/ diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditPurgeBudgetTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditPurgeBudgetTests.cs index 3fe398fc..7b17962c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditPurgeBudgetTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditPurgeBudgetTests.cs @@ -24,10 +24,31 @@ public class AuditPurgeBudgetTests Assert.Equal(ConnectionState.Closed, connection.State); } + /// + /// AUD-5 (WP6 6.5): the channel is bound as varchar(32) to match the Category column — an + /// nvarchar parameter makes SQL Server convert the column under a SQL collation and rules + /// out a seek on IX_AuditLog_Channel_Occurred. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ChannelParameter_IsBoundAsVarchar32() + { + using var connection = new BackloggedConnection(); + await using var context = new ScadaBridgeDbContext(new DbContextOptionsBuilder() + .UseSqlServer(connection).Options); + await new AuditLogRepository(context).PurgeChannelOlderThanAsync( + "ScriptTrace", DateTime.UtcNow, batchSize: 3, maxRows: 3); + var channel = Assert.Single(connection.ChannelParameters); + Assert.Equal(SqlDbType.VarChar, channel.Type); + Assert.Equal(32, channel.Size); + } + private sealed class BackloggedConnection : DbConnection { /// Gets the batch sizes requested by the purge, in order. public List RequestedBatches { get; } = new(); + /// Gets the SQL type and size of each bound @channel parameter, in order. + public List<(SqlDbType Type, int Size)> ChannelParameters { get; } = new(); private ConnectionState _state; /// [AllowNull] public override string ConnectionString { get; set; } = "Server=localhost;Database=test"; @@ -81,6 +102,8 @@ public class AuditPurgeBudgetTests throw new InvalidOperationException("Purge did not yield despite exhausting its row budget."); var requested = (int)_parameters.Parameters["@batch"].Value; owner.RequestedBatches.Add(requested); + var channel = _parameters.Parameters["@channel"]; + owner.ChannelParameters.Add((channel.SqlDbType, channel.Size)); return requested; } /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SchemaIndexTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SchemaIndexTests.cs index 86199a25..6c7d0ec8 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SchemaIndexTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SchemaIndexTests.cs @@ -84,6 +84,7 @@ public class SchemaIndexTests : IDisposable [Theory] [InlineData("severity", "idx_events_severity_timestamp")] [InlineData("event_type", "idx_events_type_timestamp")] + [InlineData("instance_id", "idx_events_instance_timestamp")] // SEL-1 (WP6 6.5) public void EqualityFilteredPage_ReadsInTimestampOrder_WithoutSortingEveryMatch(string column, string expectedIndex) { foreach (var window in new[] { "", "AND timestamp >= '2026-01-01' " }) @@ -135,7 +136,7 @@ public class SchemaIndexTests : IDisposable while (reader.Read()) indexes.Add(reader.GetString(0)); Assert.Equal( - ["idx_events_instance", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"], + ["idx_events_instance_timestamp", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"], indexes); using var count = connection.CreateCommand(); count.CommandText = "SELECT COUNT(*) FROM site_events INDEXED BY idx_events_severity_timestamp WHERE severity = 'Info'"; diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventLogSchemaTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventLogSchemaTests.cs index 86d37bee..8a0211a5 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventLogSchemaTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventLogSchemaTests.cs @@ -121,7 +121,7 @@ public class SiteEventLogSchemaTests while (reader.Read()) indexes.Add(reader.GetString(0)); Assert.Equal( - ["idx_events_instance", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"], + ["idx_events_instance_timestamp", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"], indexes); } diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventsSchemaCalibrationTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventsSchemaCalibrationTests.cs index e11b3b45..c2e28e96 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventsSchemaCalibrationTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventsSchemaCalibrationTests.cs @@ -75,7 +75,7 @@ public class SiteEventsSchemaCalibrationTests Assert.True( indexes.SequenceEqual( [ - "idx_events_instance", + "idx_events_instance_timestamp", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp", @@ -89,14 +89,14 @@ public class SiteEventsSchemaCalibrationTests /// The columns the index is expected to cover, comma-separated, in key order. [Theory] [InlineData("idx_events_timestamp", "timestamp")] - [InlineData("idx_events_instance", "instance_id")] + [InlineData("idx_events_instance_timestamp", "instance_id,timestamp")] [InlineData("idx_events_type_timestamp", "event_type,timestamp")] [InlineData("idx_events_severity_timestamp", "severity,timestamp")] public void EachIndex_CoversExactlyTheColumnsTheSamplerSums(string indexName, string expectedColumns) { - // The sampler's indexed_bytes expression sums 3 * octet_length(timestamp) + + // The sampler's indexed_bytes expression sums 4 * octet_length(timestamp) + // octet_length(event_type) + octet_length(severity) + octet_length(instance_id): - // timestamp once for its own index and once for each of the two composites (#123). + // timestamp once for its own index and once for each of the three composites (#123, SEL-1). // Widening or re-pointing an index changes the real entry width without changing // what is sampled. using var connection = OpenWithSchema(); From 59817f5017118edec55d58d1cf048c3c0d34ef7e Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:09:41 -0500 Subject: [PATCH 06/12] perf(deployment,template-engine): batched untracked staleness loads, staging-failure detach, lock-held Disabled re-check, targeted single-entity loads (DEP-4, DEP-5, DEP-6, TPL-4, WP6 task 6.6) DEP-4: new ITemplateEngineRepository.GetInstancesByIdsUntrackedAsync (one AsNoTracking split query per 500-id chunk). GetInstanceStalenessAsync preloads each chunk into its FlattenSession; FlattenCoreAsync takes a preloaded instance (consumed once) before falling back to the tracked per-instance load. Deploy sessions never preload, so prepare keeps its tracked load. Throwaway harness, SQLite, 1,000 instances x 50 overrides: before: 5,000 reader commands, 51,000 tracked entities after: 10 reader commands, 0 tracked entities (wall time on in-process SQLite 2.7 s -> 2.3 s; the win on SQL Server is the 4,990 saved round-trips and the change tracker staying empty) DEP-5: AddPendingDeploymentAsync supersedes prior rows with a set-based delete (DeletePendingWhereAsync) instead of tracked key stubs, and a failed staging save calls DetachPendingChanges under dbGate so it cannot poison the next instance's staging save on the shared bulk context. Regression: prior row purged between supersede and save -> before: DbUpdateConcurrencyException; after: stages cleanly. DEP-6: bulk prepare (reconcileGate != null) re-reads the instance state untracked (new IDeploymentManagerRepository.GetInstanceStateAsync) once the operation lock is held; Disabled -> reported in SkippedInstances with the Disabled reason, never flattened/sent/re-enabled. Placed at the top of PrepareUnderLockAsync so it is independent of WP7's lock-ordering change. TPL-4: area delete uses the new shallow untracked GetInstancesBySiteIdShallowAsync; SetAlarmOverride and Delete{Attribute,Alarm,Script} read the analysis closure instead of the whole template table; MoveTemplate's collision check is the new TemplateNameExistsInFolderAsync (one folder's names). SiteService already used the include-free ISiteRepository read (unchanged). --- .../Component-DeploymentManager.md | 8 ++ .../IDeploymentManagerRepository.cs | 10 ++ .../Repositories/ITemplateEngineRepository.cs | 36 ++++++ .../DeploymentManagerRepository.cs | 61 ++++----- .../Repositories/TemplateEngineRepository.cs | 47 +++++++ .../DeploymentService.cs | 60 ++++++++- .../FlattenSession.cs | 23 ++++ .../FlatteningPipeline.cs | 5 +- .../Services/AreaService.cs | 3 +- .../Services/InstanceService.cs | 4 +- .../TemplateService.cs | 21 +-- .../PendingDeploymentRepositoryTests.cs | 22 ++++ .../TargetedLoadRepositoryTests.cs | 120 ++++++++++++++++++ .../DeploySiteAsyncTests.cs | 56 ++++++++ .../DeploymentServiceStalenessTests.cs | 31 ++++- .../FlattenSessionCacheTests.cs | 24 ++++ .../AnalysisClosureMock.cs | 10 ++ .../Services/AreaServiceTests.cs | 8 +- .../Services/InstanceServiceTests.cs | 1 + 19 files changed, 493 insertions(+), 57 deletions(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/TargetedLoadRepositoryTests.cs diff --git a/docs/requirements/Component-DeploymentManager.md b/docs/requirements/Component-DeploymentManager.md index 228d2068..276a9380 100644 --- a/docs/requirements/Component-DeploymentManager.md +++ b/docs/requirements/Component-DeploymentManager.md @@ -180,6 +180,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 diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs index 24ef39bc..ff2455a2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs @@ -413,6 +413,16 @@ public interface IDeploymentManagerRepository /// A cancellation token that can be used to cancel the operation. /// The instance, or null if not found. Task GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default); + + /// + /// DEP-6: reads an instance's CURRENT lifecycle state straight from the database, + /// untracked — bypassing EF identity resolution, which would otherwise answer with the + /// state of an entity this unit of work loaded earlier. + /// + /// The instance id. + /// Cancellation token. + /// The state, or when the instance does not exist. + Task GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default); /// /// Gets an instance by unique name. /// diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs index c78677e6..77e7c495 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs @@ -286,6 +286,18 @@ public interface ITemplateEngineRepository /// Cancellation token. /// A task that resolves to the matching instance, or if not found. Task GetInstanceByIdAsync(int id, CancellationToken cancellationToken = default); + + /// + /// DEP-4: loads several instances with the same child collections as + /// , untracked, in one split query per chunk of + /// ids — for read-only paths (fleet staleness) that must not fill the scoped change + /// tracker with every deployed instance's overrides and bindings. + /// + /// The instance ids; missing ids are absent from the result. + /// Cancellation token. + /// The instances found. + Task> GetInstancesByIdsUntrackedAsync( + IReadOnlyCollection ids, CancellationToken cancellationToken = default); /// Retrieves all instances. /// Cancellation token. /// A task that resolves to a read-only list of all instances. @@ -301,6 +313,30 @@ public interface ITemplateEngineRepository /// A task that resolves to a read-only list of instances for the specified site. Task> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default); + /// + /// TPL-4: a site's instances WITHOUT their child collections, untracked — for checks + /// that only need identity, name and area (area/site delete guards), which used to load + /// and track every instance's overrides and bindings. + /// + /// The site ID. + /// Cancellation token. + /// The site's instances, shallow and untracked. + Task> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default); + + /// + /// TPL-4: whether a template other than named + /// (case-insensitively) already sits in + /// ( = the root) — the folder-move collision check, which used to load + /// the whole template table. + /// + /// The destination folder, or null for the root. + /// The template name. + /// The template being moved. + /// Cancellation token. + /// when a sibling with that name exists. + Task TemplateNameExistsInFolderAsync( + int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default); + /// Reads one bounded, untracked page of topology instance rows for a site/area. /// The site ID. /// The area ID to filter by, or null for every area. diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs index 435252ec..ac05b215 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs @@ -407,21 +407,20 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository // Supersession: a newer deploy for the same instance replaces any prior pending // row. Safe because the per-instance operation lock serializes same-instance - // deploys. SaveChanges is deferred to the caller, matching the other Add methods. + // deploys. The new row's SaveChanges is deferred to the caller, matching the other + // Add methods. // - // Only the prior rows' KEYS are read: each row carries the whole flattened - // ConfigurationJson (tens of KB), and materialising it just to delete it was the - // dominant cost of the supersede. The delete itself stays a tracked Remove (not - // ExecuteDelete) so it still commits atomically with the new row in the caller's - // SaveChanges. - var priorIds = await _dbContext.Set() - .Where(p => p.InstanceId == pending.InstanceId) - .Select(p => p.Id) - .ToListAsync(cancellationToken); - foreach (var id in priorIds) - { - RemovePendingByKey(id); - } + // DEP-5: the prior rows are removed with a set-based ExecuteDelete keyed on the + // instance — never materialised (each carries the whole flattened ConfigurationJson) + // and never tracked. The old tracked key-only stubs made the caller's SaveChanges + // throw DbUpdateConcurrencyException whenever the TTL purge (or reconciliation) + // removed one of those rows first, and the failed stub then stayed tracked and + // poisoned every later staging save on the shared bulk-deploy context. The trade + // is that the supersede commits on its own, just before the insert: a failed + // insert leaves the instance with no pending row, which is what the superseded + // deploy was about to become anyway. + var instanceId = pending.InstanceId; + await DeletePendingWhereAsync(p => p.InstanceId == instanceId, cancellationToken); await _dbContext.Set().AddAsync(pending, cancellationToken); } @@ -505,29 +504,6 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository return rows.Count; } - /// - /// Marks the pending row with primary key for deletion on the next - /// SaveChanges without loading it: an already-tracked instance is removed in place, - /// otherwise a key-only stub is attached and removed (EF deletes by key). - /// - /// Primary key of the pending row. - private void RemovePendingByKey(int id) - { - var set = _dbContext.Set(); - var tracked = set.Local.FirstOrDefault(p => p.Id == id); - if (tracked != null) - { - set.Remove(tracked); - return; - } - - var stub = new PendingDeployment( - string.Empty, 0, string.Empty, string.Empty, string.Empty, - default, default) { Id = id }; - set.Attach(stub); - set.Remove(stub); - } - /// public async Task PurgeTerminalDeploymentRecordsAsync( DateTimeOffset cutoffUtc, @@ -777,6 +753,17 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository // --- Instance lookups for deployment pipeline --- + /// + public async Task GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default) + { + // A scalar projection is never tracked and never identity-resolved, so this sees a + // state committed by another request after this context loaded the instance. + return await _dbContext.Set() + .Where(i => i.Id == instanceId) + .Select(i => (InstanceState?)i.State) + .FirstOrDefaultAsync(cancellationToken); + } + /// public async Task GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default) { diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs index 5bef7c5a..8658168d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs @@ -501,6 +501,29 @@ public class TemplateEngineRepository : ITemplateEngineRepository .FirstOrDefaultAsync(i => i.Id == id, cancellationToken); } + /// + public async Task> GetInstancesByIdsUntrackedAsync( + IReadOnlyCollection ids, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(ids); + var result = new List(ids.Count); + // Chunked so the IN list stays well under SQL Server's 2,100-parameter limit. + foreach (var chunk in ids.Distinct().Chunk(500)) + { + result.AddRange(await _context.Instances + .AsNoTracking() + .Where(i => chunk.Contains(i.Id)) + .Include(i => i.AttributeOverrides) + .Include(i => i.AlarmOverrides) + .Include(i => i.ConnectionBindings) + .Include(i => i.NativeAlarmSourceOverrides) + .AsSplitQuery() + .ToListAsync(cancellationToken)); + } + + return result; + } + /// public async Task> GetAllInstancesAsync(CancellationToken cancellationToken = default) { @@ -521,6 +544,30 @@ public class TemplateEngineRepository : ITemplateEngineRepository .ToListAsync(cancellationToken); } + /// + public async Task> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default) + { + return await _context.Instances + .AsNoTracking() + .Where(i => i.SiteId == siteId) + .ToListAsync(cancellationToken); + } + + /// + public async Task TemplateNameExistsInFolderAsync( + int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(name); + // Only the destination folder's names are read (one narrow projection), then compared + // case-insensitively in memory — independent of the database collation. + var siblingNames = await _context.Templates + .AsNoTracking() + .Where(t => t.FolderId == folderId && t.Id != excludeTemplateId) + .Select(t => t.Name) + .ToListAsync(cancellationToken); + return siblingNames.Any(n => string.Equals(n, name, StringComparison.OrdinalIgnoreCase)); + } + /// public async Task> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default) { diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs index 968ac9e6..1b201f74 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs @@ -63,6 +63,9 @@ public class DeploymentService /// Reason reported on every a bulk site /// deploy produces for a instance. /// + /// DEP-4: instances bulk-loaded (untracked) per chunk by the fleet staleness read. + private const int StalenessPreloadChunk = 500; + internal const string DisabledSkipReason = "Disabled — bulk deploy preserves disabled state; deploy individually to re-enable"; @@ -320,6 +323,20 @@ public class DeploymentService { var instanceId = instance.Id; + // DEP-6: a bulk deploy loaded its candidates once, up front, and EF identity + // resolution hands Prepare that same tracked entity — so a Disable committed after + // the batch started was invisible here, and the batch would deploy (and finalise + // as enabled) an instance the operator had just stopped. Disable/enable take this + // operation lock too, so a fresh, untracked read of the state taken while holding + // it is authoritative. Single-instance deploy (no reconcileGate) keeps + // deploy-and-enable as its explicit operator action. + if (reconcileGate is not null + && await _repository.GetInstanceStateAsync(instanceId, cancellationToken) == InstanceState.Disabled) + { + lockHandle.Dispose(); + return PreparedDeployment.Skipped(DisabledSkipReason); + } + // Generate unique deployment ID var deploymentId = Guid.NewGuid().ToString("N"); @@ -493,6 +510,15 @@ public class DeploymentService { command = await StagePendingDeploymentAsync(prepared, user, cancellationToken); } + catch + { + // DEP-5: a failed staging save leaves its Added row tracked on the scoped + // context; in a bulk deploy every later instance's staging save would retry + // it and fail the same way. Drop it while still holding dbGate (the only + // repository writer in phase 2), like MarkDeploymentFailedAsync does (P7-5). + _repository.DetachPendingChanges(); + throw; + } finally { dbGate?.Release(); @@ -823,8 +849,19 @@ public class DeploymentService string ConfigJson, string SiteIdentifier, IDisposable? LockHandle, - Result? EarlyResult) + Result? EarlyResult, + string? SkipReason = null) { + /// + /// DEP-6: a bulk-deploy instance found Disabled once its operation lock was held — + /// reported as a skipped row (never sent, never re-enabled), not as a failure. + /// + /// The skip reason shown in the bulk summary. + /// A prepared deployment holding no lock, with set. + public static PreparedDeployment Skipped(string reason) => + new(null!, string.Empty, null!, string.Empty, string.Empty, string.Empty, null, + Result.Failure(reason), reason); + /// Builds a prepare-phase-resolved deployment carrying the given result and holding no lock. /// The result to hand back to the caller. /// A prepared deployment whose is set. @@ -1067,6 +1104,13 @@ public class DeploymentService continue; } + if (step.SkipReason is { } skipReason) + { + skipped.Add(new SkippedInstanceResult(instance.Id, instance.UniqueName, skipReason)); + disabledCount++; + continue; + } + if (step.EarlyResult is { } early) { results.Add(ToInstanceResult(instance.Id, instance.UniqueName, early)); @@ -2067,13 +2111,25 @@ public class DeploymentService // resolved together after the loop with ONE untracked snapshot read. var mismatched = new Dictionary(); - foreach (var instanceId in instanceIds.Distinct()) + // DEP-4: load the deployed instances in untracked chunks (one split query each) + // instead of a tracked four-Include load per instance — the evaluator's scoped + // context used to end up tracking every deployed instance, override and binding. + var toEvaluate = instanceIds.Distinct().Where(deployedHashes.ContainsKey).ToList(); + foreach (var instanceId in toEvaluate) { cancellationToken.ThrowIfCancellationRequested(); if (!deployedHashes.TryGetValue(instanceId, out var deployedHash)) continue; + if ((evaluated % StalenessPreloadChunk) == 0) + { + var chunk = toEvaluate.Skip(evaluated).Take(StalenessPreloadChunk).ToList(); + session.PreloadInstances( + await _templateRepository.GetInstancesByIdsUntrackedAsync(chunk, cancellationToken) + ?? (IReadOnlyList)Array.Empty()); + } + evaluated++; // Read-only path: hash only — no validation (its result was always discarded diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs index 3a7656ad..4fcc8096 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs @@ -1,3 +1,4 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; @@ -48,6 +49,7 @@ public sealed class FlattenSession private readonly Dictionary _chains = new(); private readonly Dictionary Compositions)> _compositions = new(); private readonly Dictionary> _dataConnections = new(); + private readonly Dictionary _preloadedInstances = new(); private IReadOnlyList? _sharedScripts; private IReadOnlyDictionary? _schemaLibrary; @@ -78,6 +80,27 @@ public sealed class FlattenSession /// Number of per-site data-connection queries that missed the memo. public int DataConnectionLoads { get; private set; } + /// + /// DEP-4: hands the session instances already loaded in bulk (untracked) so the flatten + /// does not load each one again. Only read-only callers (fleet staleness) preload; a + /// deploy's session never does, so prepare keeps its tracked load. + /// + /// The preloaded instances. + public void PreloadInstances(IEnumerable instances) + { + foreach (var instance in instances) + _preloadedInstances[instance.Id] = instance; + } + + /// + /// Takes (and forgets) a preloaded instance, so a chunked caller never holds more than + /// one chunk of the fleet in memory. + /// + /// The instance id. + /// The preloaded instance, or when none was preloaded. + public Instance? TakePreloadedInstance(int instanceId) => + _preloadedInstances.Remove(instanceId, out var instance) ? instance : null; + /// /// Every template id this session resolved — the union of all inheritance and /// composed chains it walked. The staleness fast path records the watermark diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs index c609abc9..03049e36 100644 --- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs +++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs @@ -190,8 +190,9 @@ public class FlatteningPipeline : IFlatteningPipeline private async Task DataConnections)>> FlattenCoreAsync(int instanceId, FlattenSession session, CancellationToken cancellationToken) { - // Load instance with full graph - var instance = await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken); + // Load instance with full graph (DEP-4: a read-only caller may have bulk-preloaded it) + var instance = session.TakePreloadedInstance(instanceId) + ?? await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken); if (instance == null) return Result<(FlattenedConfiguration, IReadOnlyDictionary)>.Failure( $"Instance with ID {instanceId} not found."); diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs index 4e317c95..d3d3e1b0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs @@ -188,7 +188,8 @@ public class AreaService return Result.Failure($"Area with ID {areaId} not found."); // Check for instances assigned to this area - var allInstances = await _repository.GetInstancesBySiteIdAsync(area.SiteId, cancellationToken); + // TPL-4: shallow + untracked — only AreaId/UniqueName are read. + var allInstances = await _repository.GetInstancesBySiteIdShallowAsync(area.SiteId, cancellationToken); var allAreas = await _repository.GetAreasBySiteIdAsync(area.SiteId, cancellationToken); // Collect this area and all descendant area IDs diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs index 39e5be85..43db0eb0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs @@ -247,7 +247,9 @@ public class InstanceService // rule for a composed alarm. Mirrors SetAttributeOverrideAsync. // The resolver reads member names and lock flags only, so the no-tracking, // script-body-free analysis projection suffices (review 2026-10-21 04/P6, 08/P1). - var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken); + // TPL-4: the template's analysis closure (chain + compositions) is all the resolver + // walks — not the whole template table. + var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(instance.TemplateId, cancellationToken); var resolvedAlarm = TemplateResolver .ResolveAllMembers(instance.TemplateId, allTemplates) .FirstOrDefault(m => m.MemberType == "Alarm" && m.CanonicalName == alarmCanonicalName); diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs index ac79c963..d37946fb 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs @@ -228,12 +228,9 @@ public class TemplateService // only invariant the move can break is two templates sharing a // (FolderId, Name) at the destination, which the design's // naming-collisions-are-design-time-errors rule forbids. - var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken); - var collision = allTemplates.FirstOrDefault(t => - t.Id != templateId && - t.FolderId == newFolderId && - string.Equals(t.Name, template.Name, StringComparison.OrdinalIgnoreCase)); - if (collision != null) + // TPL-4: a (FolderId, Name) existence query, not a load of every template. + if (await _repository.TemplateNameExistsInFolderAsync( + newFolderId, template.Name, templateId, cancellationToken)) { var location = newFolderId.HasValue ? "the target folder" : "the root"; return Result