diff --git a/docs/requirements/Component-SiteRuntime.md b/docs/requirements/Component-SiteRuntime.md index 9712c0fe..d2b12e96 100644 --- a/docs/requirements/Component-SiteRuntime.md +++ b/docs/requirements/Component-SiteRuntime.md @@ -711,5 +711,5 @@ Per Akka.NET best practices, internal actor communication uses **Tell** (fire-an - Alarm on-trigger runs resolve the same scoped integration services as ordinary scripts, including external systems, databases, notifications, operation tracking, auditing, and site/node provenance. The scope remains alive for the run and is disposed on every exit. - Native alarm subscription retries retain the current correlation ID until its response deadline, reject stale replies, and back off to a bounded interval. Rehydration cannot overwrite a condition touched by a live event, including deletion, or a completed authoritative snapshot. - Audited raw ADO connections expose no connection string and reject `ConnectionString` assignment and `ChangeDatabase`; their configured database name remains the audit target. -- Static override persistence runs in order off the actor dispatcher. Redeployment waits for both predecessor termination and successful final persistence acknowledgement before clearing old state; failed persistence fails the redeployment. At most four redeployment predecessor stops are in progress per deployment manager. Delete and disable retain the same-name stop barrier until the final flush and lifecycle persistence finish; an overlapping deploy/enable is rejected with a retryable busy diagnostic. Timer flushes keep coalescing while a previous SQLite write is pending. +- Static override persistence runs in order off the actor dispatcher. Redeployment waits for both predecessor termination and successful final persistence acknowledgement before clearing old state; failed persistence fails the redeployment. At most four redeployment predecessor stops are in progress per deployment manager. Delete and disable retain the same-name stop barrier until the final flush and lifecycle persistence finish; an overlapping deploy/enable is rejected with a retryable busy diagnostic. Timer flushes keep coalescing while a previous SQLite write is pending. The redeploy reset (clear static overrides, then clear native alarms) gates the **successor's whole start**, not only its override load (2026-12-02 review SRT-12): the native-alarm rehydration read and the first static-override flush are chained behind it as well, so the successor can neither re-emit the predecessor's native conditions nor have an early static write deleted by a clear that landed after it. A successful static write refreshes the attribute's stored quality (`Good`) and timestamp along with its value (SRT-11) — a List attribute whose default failed to decode used to stay `Bad` for the actor's lifetime after a valid write. - Synchronous operation-tracking disposal drains and joins its thread-pool writer before disposing SQLite resources, including when invoked under a synchronization context. diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs index f95fdf33..e5f6e24f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Actors/InstanceActor.cs @@ -339,6 +339,16 @@ public class InstanceActor : ReceiveActor // Defaults to 100 ms, mirroring NativeAlarmActor's persistFlushInterval (P4). _staticOverrideFlushInterval = staticOverrideFlushInterval ?? TimeSpan.FromMilliseconds(100); _staticStateResetGate = staticStateResetGate; + // SRT-12: the first static-override flush is ordered AFTER the redeploy reset. A value + // script on the new instance can write a static attribute within the first ~100 ms; its + // flush ran on its own connection with no ordering against the (slower, lock-contended) + // clear, so the clear could land afterwards and delete it — in memory but not on disk, + // silently reverted by the next restart. The reset's own fault is ignored here (the + // deploy fails on it through its persistence join). + if (staticStateResetGate != null) + _staticOverridePersistTail = staticStateResetGate.ContinueWith( + static _ => { }, CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); _configuration = configuration; @@ -780,6 +790,15 @@ public class InstanceActor : ReceiveActor if (!_overridesLoaded) _staticWritesBeforeOverrideLoad.Add(command.AttributeName); + // SRT-11: a successful write refreshes the stored quality and timestamp with the value. + // A List attribute loaded Bad (malformed default/override) used to stay Bad for the + // actor's lifetime — GetAttribute, the Debug View snapshot and a requireGoodQuality + // waiter all saw Bad while the stream said Good — and a static attribute had no stored + // timestamp at all, so every snapshot stamped it "now". + var writtenAt = DateTimeOffset.UtcNow; + _attributeQualities[command.AttributeName] = "Good"; + _attributeTimestamps[command.AttributeName] = writtenAt; + // Publish attribute change to stream and notify children var changed = new AttributeValueChanged( _instanceUniqueName, @@ -787,7 +806,7 @@ public class InstanceActor : ReceiveActor command.AttributeName, command.Value, "Good", - DateTimeOffset.UtcNow, + writtenAt, // (ParentExecutionId tag-cascade): carry the writing // execution's id onto the change so a child Alarm Actor this write // trips can chain its on-trigger script run under the writer. Null for @@ -1088,6 +1107,22 @@ public class InstanceActor : ReceiveActor /// Routes script call requests to the appropriate Script Actor. /// Uses Ask pattern. /// + /// + /// SRT-12: the native-alarm rehydration read, chained behind + /// when this start is a (re)deploy; null (the actor reads directly) on every other start. + /// + private Task>? GatedNativeAlarmRead(string sourceCanonicalName) + { + if (_staticStateResetGate == null) + return null; + var storage = _storage; + var instanceName = _instanceUniqueName; + return _staticStateResetGate + .ContinueWith(_ => storage.GetNativeAlarmsAsync(instanceName, sourceCanonicalName), + CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default) + .Unwrap(); + } + private void HandleGetScriptExecutionTimeout(GetScriptExecutionTimeout request) { var script = _configuration?.Scripts.FirstOrDefault(s => s.CanonicalName == request.ScriptName); @@ -2329,6 +2364,11 @@ public class InstanceActor : ReceiveActor } var nativeKind = ResolveNativeKind(nativeSource.ConnectionName); + // SRT-12: on a (re)deploy the native-alarm rehydration read is chained behind the + // reset gate too — not only the override load — so the successor can only observe the + // CLEARED native_alarm_state, never re-emit the predecessor's conditions (stale alarms + // from an old binding that no snapshot would ever reconcile if the source is down). + var rehydrationRead = GatedNativeAlarmRead(nativeSource.CanonicalName); var props = Props.Create(() => new NativeAlarmActor( nativeSource, _instanceUniqueName, @@ -2338,7 +2378,9 @@ public class InstanceActor : ReceiveActor _options, _logger, nativeKind, - _serviceProvider)); + _serviceProvider, + null, + rehydrationRead)); var actorRef = TryCreateChild( props, $"native-alarm-{nativeSource.CanonicalName}", "Native alarm source", nativeSource.CanonicalName); diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorRedeployGateTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorRedeployGateTests.cs new file mode 100644 index 00000000..4814b6b5 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorRedeployGateTests.cs @@ -0,0 +1,142 @@ +using System.Text.Json; +using Akka.Actor; +using Akka.TestKit.Xunit2; +using Microsoft.Extensions.Logging.Abstractions; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Instance; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening; +using ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors; +using ZB.MOM.WW.ScadaBridge.SiteRuntime.Persistence; +using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts; +using ZB.MOM.WW.ScadaBridge.TestSupport; + +namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Actors; + +/// +/// SRT-12 (2026-12-02 review, WP3 task 3.10): the redeploy reset gate (clear static overrides, +/// then clear native alarms) must cover the successor's whole start, not just its override load — +/// the native-alarm rehydration read and the first static-override flush are ordered behind it too. +/// +public class InstanceActorRedeployGateTests : TestKit, IDisposable +{ + private readonly SiteStorageService _storage; + private readonly ScriptCompilationService _compilationService; + private readonly SharedScriptLibrary _sharedScriptLibrary; + private readonly SiteRuntimeOptions _options = new(); + private readonly TestLocalDb _localDb; + + /// Creates a temporary LocalDb-backed site storage and the script services the actor needs. + public InstanceActorRedeployGateTests() + { + _localDb = TestLocalDb.CreateTemp("instance-redeploy-gate"); + _storage = new SiteStorageService(_localDb.Db, NullLogger.Instance); + _storage.InitializeAsync().GetAwaiter().GetResult(); + _compilationService = new ScriptCompilationService(NullLogger.Instance); + _sharedScriptLibrary = new SharedScriptLibrary(_compilationService, NullLogger.Instance); + } + + /// + void IDisposable.Dispose() + { + Shutdown(); + var path = _localDb.Path; + _localDb.Dispose(); + TestLocalDb.DeleteFiles(path); + } + + private IActorRef CreateGated(string name, FlattenedConfiguration config, IActorRef? dcl, Task gate) => + ActorOf(Props.Create(() => new InstanceActor( + name, JsonSerializer.Serialize(config), _storage, _compilationService, _sharedScriptLibrary, + null, _options, NullLogger.Instance, dcl, null, null, null, gate))); + + /// Holds true for the whole window (polling, not a blind sleep). + private static async Task AssertHoldsFor(Func> holds, TimeSpan window, string because) + { + var deadline = DateTime.UtcNow + window; + while (DateTime.UtcNow < deadline) + { + Assert.True(await holds(), because); + await Task.Delay(50); + } + } + + /// + /// The successor's first static-override flush lands only after the reset: a write made while + /// the (slow) clear is still pending must survive it. Pre-fix the flush committed within + /// ~100 ms, the delayed clear then deleted it, and the next restart silently reverted it. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task FirstStaticFlush_IsOrderedAfterTheResetGate() + { + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var config = new FlattenedConfiguration + { + InstanceUniqueName = "GateFlush", + Attributes = [new ResolvedAttribute { CanonicalName = "Mode", Value = "Auto", DataType = "String" }], + }; + var actor = CreateGated("GateFlush", config, null, gate.Task); + + actor.Tell(new SetStaticAttributeCommand("w1", "GateFlush", "Mode", "Manual", DateTimeOffset.UtcNow)); + Assert.True(ExpectMsg().Success); + + // While the reset is pending, nothing may reach the table (pre-fix: committed at ~100 ms). + await AssertHoldsFor( + async () => (await _storage.GetStaticOverridesAsync("GateFlush")).Count == 0, + TimeSpan.FromMilliseconds(500), "a static flush committed ahead of the redeploy reset"); + + // The reset runs, then the gate opens: the write lands after it and survives. + await _storage.ClearStaticOverridesAsync("GateFlush"); + gate.SetResult(); + await AwaitAssertAsync(async () => + { + var stored = await _storage.GetStaticOverridesAsync("GateFlush"); + Assert.Equal("Manual", stored.GetValueOrDefault("Mode")); + }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(50)); + } + + /// + /// The native-alarm rehydration read is chained behind the gate, so the successor can only see + /// the CLEARED table. Pre-fix NativeAlarmActor read native_alarm_state directly in PreStart and + /// re-emitted the predecessor's conditions (stale alarms from an old binding). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task NativeAlarmRehydration_IsOrderedAfterTheResetGate() + { + // The predecessor left an active condition behind. + await _storage.UpsertNativeAlarmAsync("GateNative", "Pressure", "T01.Hi", + JsonSerializer.Serialize(new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 800)), + DateTimeOffset.UtcNow); + + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var config = new FlattenedConfiguration + { + InstanceUniqueName = "GateNative", + NativeAlarmSources = + [ + new ResolvedNativeAlarmSource + { + CanonicalName = "Pressure", ConnectionName = "Opc", SourceReference = "ns=2;s=T01" + } + ], + }; + var dcl = CreateTestProbe(); + var actor = CreateGated("GateNative", config, dcl.Ref, gate.Task); + dcl.ExpectMsg(TimeSpan.FromSeconds(5)); + + // The reset clears the table, THEN the gate opens. + await Task.Delay(200); // give a pre-fix (ungated) PreStart read every chance to win the race + await _storage.ClearNativeAlarmsForInstanceAsync("GateNative"); + gate.SetResult(); + + await AssertHoldsFor(async () => + { + var snap = await actor.Ask(new SubscribeDebugViewRequest("GateNative", "c"), TimeSpan.FromSeconds(3)); + return !snap.AlarmStates.Any(a => a.SourceReference == "T01.Hi" && !a.IsConfiguredPlaceholder); + }, TimeSpan.FromSeconds(1), "the predecessor's native alarm was rehydrated"); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs index f656ad5e..72dd97e8 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorTests.cs @@ -233,6 +233,42 @@ public class InstanceActorTests : TestKit, IDisposable Assert.Equal("100.0", getResponse.Value?.ToString()); } + /// + /// SRT-11: a successful static write refreshes the stored quality and timestamp. A List + /// attribute whose config default fails to decode loads Bad; a later valid write used to fix + /// the value but leave GetAttribute (and the Debug View, and requireGoodQuality waiters) on Bad + /// for the actor's lifetime while the stream said Good. + /// + [Fact] + public void InstanceActor_StaticWrite_RefreshesQualityAndTimestamp() + { + var config = new FlattenedConfiguration + { + InstanceUniqueName = "PumpListFix", + Attributes = + [ + new ResolvedAttribute + { + CanonicalName = "Recipe", Value = "[not json", DataType = "List", ElementDataType = "Int32" + } + ] + }; + var actor = CreateInstanceActor("PumpListFix", config); + + actor.Tell(new GetAttributeRequest("q0", "PumpListFix", "Recipe", DateTimeOffset.UtcNow)); + Assert.Equal("Bad", ExpectMsg().Quality); // malformed default + + var before = DateTimeOffset.UtcNow; + actor.Tell(new SetStaticAttributeCommand("w1", "PumpListFix", "Recipe", "[1,2,3]", DateTimeOffset.UtcNow)); + Assert.True(ExpectMsg().Success); + + actor.Tell(new GetAttributeRequest("q1", "PumpListFix", "Recipe", DateTimeOffset.UtcNow)); + var after = ExpectMsg(); + Assert.Equal("Good", after.Quality); // pre-fix: "Bad" + Assert.Equal(new List { 1, 2, 3 }, Assert.IsType>(after.Value)); + Assert.True(after.Timestamp >= before, $"timestamp {after.Timestamp} not refreshed by the write"); + } + /// Verifies that setting a static attribute persists it to SQLite. /// A task that represents the asynchronous operation. [Fact]