From 8b64d1ec9cfd24666ca965b817e394d0e0ea0841 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:41:03 -0500 Subject: [PATCH] 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]