fix(virtualtags): #1061 a scheduler catch-up burst evaluates a timer tag once, not once per missed tick

Root cause of the intermittent VirtualTagActorTimerTests coalesce failure (full suite only):
Akka's HashedWheelTimer does not skip ticks it missed while its thread was stalled (GC pause,
CPU starvation) - it delivers them all in one burst when it resumes. Measured with a parked
scheduler thread: a 600 ms stall => 12 ticks within the same millisecond. Ticks that fell due
during the gated run therefore landed just after the release, each a fresh evaluation, and broke
the post-release bound. In production the same burst multiplied every timer tag's script runs by
stall/interval after any stall.

VirtualTagActor now drops a tick that lands within half an interval of the last timer
evaluation (scheduler monotonic clock); the regular cadence is unaffected. New deterministic
test parks the scheduler thread for 600 ms with the release inside the stall: failed 3/3
before the fix, passes after, with a cadence positive control. The in-flight assertion
(Calls == 1 while gated) has no such mechanism - ticks during a run are dropped - and did not
fail in 3 full-suite + 12 class-scoped trx runs under load average ~490.
This commit is contained in:
Joseph Doherty
2026-12-03 15:25:10 -05:00
parent e967042fbb
commit ca5ee2ac57
3 changed files with 59 additions and 2 deletions
+1 -1
View File
@@ -345,7 +345,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT
- Pinned by `VirtualTagToVirtualTagFlowTests` (Host.Tests: real mux + host + Roslyn evaluator; value, change and disabled-upstream propagation), `VirtualTagOutputRoutingTests` (Runtime.Tests: mux pinning/replay/release, host routing, re-assert exclusion, runtime cycle backstop) and `DraftValidatorVirtualTagCycleTests`.
- **Supervision restart re-applies.** A restart of `VirtualTagHostActor` builds a host with no children and no definitions; its `PostRestart` tells the parent `VirtualTagHostRestarted` and `DriverHostActor` re-sends the last `ApplyVirtualTags` (mirroring the scripted-alarm host's `ScriptedAlarmHostRestarted`), so VirtualTags resume without waiting for the next deploy. Pinned by `DriverHostActorVirtualTagTests.After_a_supervision_restart_the_virtual_tag_host_is_re_applied`.
- **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`; there is no FK, so a concurrent bind is caught by the gate). As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`.
- **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`.
- **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. A tick that lands within half an interval of the last timer evaluation is dropped too (#1061): Akka's scheduler delivers every tick it missed during a stall of its thread (GC pause, CPU starvation) as one burst when it resumes, which used to run the script once per missed tick. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`.
- **Calculation tags and scripted alarms still evaluate one script at a time per driver / per engine (deliberately, for now).** Neither blocks a thread — both await the run — but a slow script still delays its siblings. Running independent scripts in parallel was considered for #779 and not done, because it is not semantics-neutral: for Calculation, the single pump is what bounds a driver to one pool thread of script work (per-tag lanes would let N slow tags hold N pool threads, the pool Akka's dispatchers also run on, so it needs a bounded-parallelism knob), it would reorder publishes across tags, and the timer path would need per-tag exclusion with the pump; for scripted alarms, the engine gate is also the consistency boundary of the Part 9 state machine, persist-before-update and ack/shelve/load, a predicate's transition time is sampled just before its own run, and a store failure mid-batch today leaves later predicates un-run (in parallel they would already have run, moving their run-guard strike streaks and writing script logs for results that are then discarded). The out-of-process runner's batch-submit `IScriptRunner` (#750) is where that concurrency belongs, with the runner owning the bound.
- **`IHistoryWriter`** — the equipment-namespace path threads `Historize` end-to-end and `VirtualTagHostActor` invokes the injected writer on historized results (H5); the writer is resolved through `DriverHostActor` DI with a `NullHistoryWriter` default. No *durable* writer ships on this seam — durable continuous historization now flows through the separate `ContinuousHistorizationRecorder` → HistorianGateway `WriteLiveValues` path (see the `IHistoryWriter` section above and [Historian.md](Historian.md)).
@@ -130,6 +130,8 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
private readonly bool _changeTriggered;
private readonly int? _timerIntervalMs;
private ICancelable? _timer;
// Gitea #1061: scheduler-clock time of the last tick that evaluated (null until the first).
private TimeSpan? _lastTimerEvaluation;
// One outstanding RunnerRecovered wait at most: a burst of Unavailable results re-evaluates once (latest-wins).
private bool _recoveryArmed;
// R02:P6 — a script failing on every trigger of a 1 Hz input published one cluster-wide DPS
@@ -248,7 +250,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
Receive<DependencyMuxActor.ProjectedDependencyWake>(wake => wake.Consume(items => OnDependencyBatch(new(items))));
Receive<ReassertValue>(_ => OnReassertValue());
Receive<RetrySourceBinding>(_ => RetrySource());
Receive<TimerTick>(_ => Evaluate(DateTime.UtcNow));
Receive<TimerTick>(_ => OnTimerTick());
Receive<RunnerRecovered>(_ =>
{
_recoveryArmed = false;
@@ -294,6 +296,24 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
_mux?.Tell(new DependencyMuxActor.UnregisterInterest(Self));
}
/// <summary>
/// A timer tick (lmxopcua#783). Gitea #1061: Akka's scheduler does not skip the ticks it missed while its thread
/// was stalled (a GC pause, CPU starvation) — it delivers every one of them in a single burst when it resumes (a
/// 600 ms stall ⇒ 12 ticks inside one millisecond). Each used to be a full evaluation, so one stall multiplied
/// every timer tag's script runs by the stall length over its interval. A tick that lands within half an interval
/// of the last timer evaluation is such a catch-up duplicate and is dropped; the regular cadence (one tick per
/// interval, the wheel's jitter a fraction of the 50 ms floor) is never affected. Ticks during a run are still
/// dropped by <see cref="Evaluating"/>.
/// </summary>
private void OnTimerTick()
{
var now = Context.System.Scheduler.MonotonicClock;
if (_lastTimerEvaluation is { } last && _timerIntervalMs is { } ms && now - last < TimeSpan.FromMilliseconds(ms / 2.0))
return;
_lastTimerEvaluation = now;
Evaluate(DateTime.UtcNow);
}
private void ScheduleSourceRetry()
{
_sourceBindingRetry?.Cancel();
@@ -72,6 +72,43 @@ public sealed class VirtualTagActorTimerTests : RuntimeActorTestBase
$"coalesced: only real ticks may land after the release ({sinceRelease.ElapsedMilliseconds} ms since release)");
}
/// <summary>
/// Gitea #1061 — the real cause of the intermittent full-suite failure above. Akka's scheduler does not skip the
/// ticks it missed while its thread was stalled (a GC pause, CPU starvation under a loaded run): it delivers them
/// all in ONE burst when it resumes (measured: a 600 ms stall ⇒ 12 ticks within the same millisecond). Ticks that
/// fell due during a gated run therefore reached the actor just after the run, each one a fresh evaluation. The
/// stall is produced deterministically here by parking the scheduler's own thread, with the release inside it.
/// A catch-up burst must collapse to one evaluation; the cadence afterwards is unaffected (positive control).
/// </summary>
[Fact]
public void A_scheduler_catch_up_burst_after_a_slow_run_evaluates_once_not_once_per_missed_tick()
{
var parent = CreateTestProbe();
var evaluator = new CountingEvaluator(gateFirst: true);
parent.ChildActorOf(VirtualTagActor.Props("vt-1", "expr", evaluator: evaluator, timerIntervalMs: 50), TestContext.Current.CancellationToken);
AwaitCondition(() => evaluator.Calls == 1, PresenceBudget, TestContext.Current.CancellationToken);
// Park the scheduler's thread for 600 ms (~12 intervals) and finish the slow run inside that stall.
using var stalled = new ManualResetEventSlim();
using var resumed = new ManualResetEventSlim();
Sys.Scheduler.Advanced.ScheduleOnce(TimeSpan.Zero, () => { stalled.Set(); Thread.Sleep(600); resumed.Set(); });
stalled.Wait(TestContext.Current.CancellationToken);
evaluator.Release();
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken);
resumed.Wait(TestContext.Current.CancellationToken);
var sinceResume = System.Diagnostics.Stopwatch.StartNew();
// The burst lands now. Coalesced: one catch-up evaluation plus whatever real ticks elapsed meanwhile.
Thread.Sleep(100);
var elapsedTicks = (int)(sinceResume.ElapsedMilliseconds / 50) + 1;
evaluator.Calls.ShouldBeLessThanOrEqualTo(1 + 1 + elapsedTicks,
$"a catch-up burst ran once per missed tick ({sinceResume.ElapsedMilliseconds} ms since the scheduler resumed)");
// Positive control: the timer still evaluates on its cadence afterwards.
var before = evaluator.Calls;
AwaitCondition(() => evaluator.Calls >= before + 2, PresenceBudget, TestContext.Current.CancellationToken);
}
[Fact]
public void The_timer_stops_when_the_actor_stops()
{