fix(calculation): #995 change-triggered evaluations coalesce latest-wins per calc tag, so a poll cycle evaluates once against all its new inputs and the queue is bounded by the tag count

At most one evaluation is pending per calc tag; a re-trigger only moves its
timestamp forward and the dependency snapshot is taken when the pump dequeues
it. Previously every dependency arrival enqueued a separate evaluation per
dependent with a trigger-time snapshot: k inputs of one cycle ran k times
(publishing intermediates computed from mixed old/new inputs) and the queue had
no bound when triggers outpaced the pump. The out-of-process batch pump now
dequeues every pending tag once per batch.
This commit is contained in:
Joseph Doherty
2026-12-03 11:02:08 -05:00
parent a1b8312ea4
commit 2827a4c3bf
6 changed files with 250 additions and 66 deletions
@@ -105,11 +105,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
// run to its RunTimeout, exactly as before, since the pump drops its result once _running is false).
private readonly CancellationTokenSource _evalCts = new();
// Change-triggered evaluations queued by OnDependencyValue and drained, in arrival order, by a single
// pump task. Both fields are guarded by _lock; _pumpScheduled stays true until the pump observes an
// empty queue under the lock, so an enqueue can never be lost against a pump that is exiting.
private readonly LinkedList<PendingEvaluation> _pending = new();
private readonly Dictionary<string, LinkedListNode<PendingEvaluation>> _pendingProjected = new(StringComparer.Ordinal);
// Change-triggered evaluations queued by OnDependencyValue and drained, in first-trigger order, by a single
// pump task. Latest-wins per calc tag (#995, review S-9): at most ONE entry per tag, carrying only the newest
// trigger's timestamp — the dependency snapshot is taken when the pump dequeues it — so the queue is bounded
// by the tag count. All three fields are guarded by _lock; _pumpScheduled stays true until the pump observes
// an empty queue under the lock, so an enqueue can never be lost against a pump that is exiting.
private readonly LinkedList<PendingTrigger> _pending = new();
private readonly Dictionary<string, LinkedListNode<PendingTrigger>> _pendingByTag = new(StringComparer.Ordinal);
private bool _pumpScheduled;
private long _projectedQueueVisits;
internal long ProjectedQueueVisitsForTest => Interlocked.Read(ref _projectedQueueVisits);
@@ -419,12 +421,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
// QUEUE each change-triggered dependent — never evaluate here. This
// runs on the caller's thread, which for the live path is the Akka dispatcher thread of
// Runtime's DependencyConsumerMuxAdapter, and a script run is bounded only by RunTimeout.
// Everything under this lock is dictionary work; the script runs on the pump.
// Everything under this lock is dictionary work; the script runs on the pump. A dependent that
// already has a pending evaluation only has its trigger timestamp moved forward (#995).
var queued = false;
foreach (var calcRawPath in dependents)
{
if (PrepareEvaluation(calcRawPath, timestampUtc) is not { } prepared) continue;
EnqueueEvaluation(prepared);
if (!CanEvaluate(calcRawPath)) continue;
EnqueueTrigger(calcRawPath, timestampUtc);
queued = true;
}
if (queued) SchedulePump();
@@ -487,11 +490,11 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
// ---- evaluation ----
/// <summary>One prepared evaluation: the calc tag's definition, the dependency snapshot taken when its
/// trigger fired, and that trigger's timestamp. Built under <see cref="_lock"/> by
/// <summary>One prepared evaluation: the calc tag's definition, the dependency snapshot taken when it was
/// prepared (dequeue time for change-triggered work, #995), and the newest trigger's timestamp. Built under <see cref="_lock"/> by
/// <see cref="PrepareEvaluation"/> and executed outside it, so the script itself needs no shared state.</summary>
/// <param name="Definition">The calc tag being evaluated.</param>
/// <param name="Dependencies">Its declared reads' snapshots — value, status and timestamps — as of the trigger.</param>
/// <param name="Dependencies">Its declared reads' snapshots — value, status and timestamps — as of preparation.</param>
/// <param name="TimestampUtc">The trigger's timestamp, stamped on whatever is published.</param>
/// <param name="WorstInputStatus">The worst status among <paramref name="Dependencies"/>
/// (<see cref="InputQuality.WorstOf"/>). Bad ⇒ the script is HELD and this status is published;
@@ -525,19 +528,19 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
/// Roslyn/compiled-cache invocation. Applying it here rather than on the pump is equivalent:
/// <see cref="_arrivedDeps"/> only ever grows, and the arrival that completes the set queues its own
/// evaluation.</para>
/// <para>Snapshotting the dependency values HERE — at trigger time — is what keeps the queued path
/// semantically identical to the old inline one: a burst of arrivals evaluates against the values
/// that triggered it rather than collapsing onto whatever happened to be current when the pump
/// caught up.</para>
/// <para>For change-triggered work this is called when the pump DEQUEUES the tag (#995, review S-9), so a
/// burst of arrivals that landed while the pump was busy evaluates once, against the newest value of every
/// input. It used to be called at trigger time, which made each arrival its own evaluation against a mix of
/// new and previous-cycle inputs — publishing those intermediate values — and let the queue grow without
/// bound when triggers outpaced the pump.</para>
/// </summary>
/// <param name="rawPath">The calc tag to prepare.</param>
/// <param name="timestampUtc">The trigger's timestamp.</param>
/// <returns>The prepared evaluation, or null when the tag must not evaluate.</returns>
private PendingEvaluation? PrepareEvaluation(string rawPath, DateTime timestampUtc)
{
if (!_tagsByRawPath.TryGetValue(rawPath, out var def)) return null;
if (string.IsNullOrWhiteSpace(def.ScriptSource)) return null; // unresolved script — never computes
if (!def.DependencyRefs.All(_arrivedDeps.Contains)) return null; // still warming up — do not evaluate
if (!CanEvaluate(rawPath)) return null;
var def = _tagsByRawPath[rawPath];
var deps = new Dictionary<string, DataValueSnapshot>(StringComparer.Ordinal);
foreach (var dep in def.DependencyRefs)
@@ -580,37 +583,63 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
return true;
}
/// <summary>True when <paramref name="rawPath"/> may evaluate now: a known tag with a resolved script whose every
/// declared input has arrived (the warm-up gate — see <see cref="PrepareEvaluation"/>). MUST be called under
/// <see cref="_lock"/>.</summary>
/// <param name="rawPath">The calc tag.</param>
/// <returns>True when the tag can evaluate.</returns>
private bool CanEvaluate(string rawPath) =>
_tagsByRawPath.TryGetValue(rawPath, out var def)
&& !string.IsNullOrWhiteSpace(def.ScriptSource) // unresolved script — never computes
&& def.DependencyRefs.All(_arrivedDeps.Contains); // still warming up — do not evaluate
/// <summary>One queued change-triggered evaluation (#995): the calc tag and its NEWEST trigger's timestamp. The
/// dependency snapshot is not part of it — it is taken when the pump dequeues the entry.</summary>
private sealed class PendingTrigger(string rawPath, DateTime timestampUtc)
{
public string RawPath { get; } = rawPath;
public DateTime TimestampUtc { get; set; } = timestampUtc;
}
private void ClearPending()
{
while (_pending.Count != 0) DequeuePending().Dispose();
_pending.Clear();
_pendingByTag.Clear();
}
private PendingEvaluation DequeuePending()
/// <summary>
/// Queue a change-triggered evaluation of <paramref name="rawPath"/>, latest-wins (#995, review S-9): a tag that
/// is already queued keeps its place and takes the newer trigger timestamp, so the queue never holds more than
/// one entry per calc tag. Keeping the place (rather than moving to the back) means a tag whose inputs change
/// constantly is still served in its turn. MUST be called under <see cref="_lock"/>.
/// </summary>
/// <param name="rawPath">The calc tag.</param>
/// <param name="timestampUtc">The trigger's timestamp, stamped on what the evaluation publishes.</param>
private void EnqueueTrigger(string rawPath, DateTime timestampUtc)
{
var first = _pending.First!;
_pending.RemoveFirst();
if (first.Value.Proofs.Count > 0) _pendingProjected.Remove(first.Value.Definition.RawPath);
return first.Value;
}
private void EnqueueEvaluation(PendingEvaluation pending)
{
// Projected work is latest-wins per tag. Remove its indexed node and append the
// replacement in arrival order, without traversing unrelated projected or local work.
if (pending.Proofs.Count > 0)
_projectedQueueVisits++;
if (_pendingByTag.TryGetValue(rawPath, out var queued))
{
_projectedQueueVisits++;
if (_pendingProjected.Remove(pending.Definition.RawPath, out var prior))
{
_projectedQueueVisits++;
_pending.Remove(prior);
prior.Value.Dispose();
}
var node = _pending.AddLast(pending);
_pendingProjected.Add(pending.Definition.RawPath, node);
_projectedQueueVisits++;
queued.Value.TimestampUtc = timestampUtc;
return;
}
else _pending.AddLast(pending);
_pendingByTag.Add(rawPath, _pending.AddLast(new PendingTrigger(rawPath, timestampUtc)));
}
/// <summary>Dequeue the next queued tag and prepare it against the CURRENT inputs; null when the queue holds
/// nothing that can evaluate (an entry whose tag can no longer evaluate is dropped). MUST be called under
/// <see cref="_lock"/>.</summary>
/// <returns>The prepared evaluation, or null when the queue is drained.</returns>
private PendingEvaluation? DequeuePrepared()
{
while (_pending.First is { } first)
{
_pending.RemoveFirst();
_pendingByTag.Remove(first.Value.RawPath);
if (PrepareEvaluation(first.Value.RawPath, first.Value.TimestampUtc) is { } prepared) return prepared;
}
return null;
}
/// <summary>Start the evaluation pump if it is not already running. MUST be called under
@@ -644,12 +673,12 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
lock (_lock)
{
if (!_running) ClearPending();
if (_pending.Count == 0)
if (DequeuePrepared() is not { } prepared)
{
_pumpScheduled = false;
return;
}
next = DequeuePending();
next = prepared;
}
// _evalGate (never _lock) is held across the run, so the pump and the timer ticks still
@@ -675,9 +704,9 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
/// <summary>
/// The pump on the out-of-process path (lmxopcua#780, design §4.5): dequeue everything pending — each entry's
/// dependency snapshot was captured at enqueue — submit it as ONE batch, and publish in dequeue order. A calc tag
/// queued more than once (a burst of changes) ends the batch at its second entry, so every queued evaluation still
/// runs, in order, against the snapshot that triggered it, exactly as the one-at-a-time pump would run them.
/// dependency snapshot is taken as it is dequeued — submit it as ONE batch, and publish in dequeue order. The
/// queue holds at most one entry per calc tag (#995), so a batch never names a tag twice; triggers that arrive
/// while it runs coalesce into the next one.
/// </summary>
private async Task RunEvaluationBatchPumpAsync()
{
@@ -687,14 +716,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
lock (_lock)
{
if (!_running) ClearPending();
if (_pending.Count == 0)
batch = [];
while (DequeuePrepared() is { } prepared) batch.Add(prepared);
if (batch.Count == 0)
{
_pumpScheduled = false;
return;
}
batch = [];
var inBatch = new HashSet<string>(StringComparer.Ordinal);
while (_pending.Count > 0 && inBatch.Add(_pending.First!.Value.Definition.RawPath)) batch.Add(DequeuePending());
}
if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) { foreach (var item in batch) item.Dispose(); return; } // disposed
@@ -913,8 +941,8 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjected
{
if (_stateByRawPath.TryGetValue(rawPath, out var st)) st.RecoveryArmed = false;
if (!_running || _disposed) return;
if (PrepareEvaluation(rawPath, DateTime.UtcNow) is not { } prepared) return;
EnqueueEvaluation(prepared);
if (!CanEvaluate(rawPath)) return;
EnqueueTrigger(rawPath, DateTime.UtcNow);
SchedulePump();
}
}