fix(site-runtime): watchdog follows the run across awaits; only the run's own deadline is a timeout (SRT-1, SRT-10, WP3 task 3.6)

This commit is contained in:
Joseph Doherty
2026-12-03 10:06:01 -05:00
parent c000ee3203
commit a730bc0558
4 changed files with 193 additions and 19 deletions
@@ -281,18 +281,16 @@ internal static class ScriptRunLauncher
var emitPerRunEvents = ScriptRunEventPolicy.ShouldEmitPerRun(effectiveOptions, instanceName, scriptName);
var runStopwatch = Stopwatch.StartNew();
// Identify the worker this body is holding, so the watchdog can detach and
// replace it if the body wedges. Read in the FIRST synchronous segment — a script
// that later hops threads on an await no longer holds this worker, and the run-stamp
// guard in TryDetachWorker will (correctly) refuse to detach it.
var workerSlot = ScriptExecutionScheduler.CurrentWorkerSlot;
var workerRunStamp = workerSlot is { } slot ? executionScheduler.CurrentRunStamp(slot) : 0L;
// Track the worker this body is holding — not just in this first segment but after
// every await (SRT-1): each continuation runs on whichever worker dequeues it, under a
// new run stamp, so the watchdog reads the LATEST (slot, stamp) when it fires.
var workerTracker = ScriptRunWorkerTracker.Begin(executionScheduler);
IDisposable? logScope = null;
var completed = 0;
ArmStuckScriptWatchdog(
cts, options, logger, siteEventLogger, executionScheduler,
workerSlot, workerRunStamp, timeout,
workerTracker, timeout,
() => Volatile.Read(ref completed) != 0,
$"Script '{scriptName}' on instance '{instanceName}'",
instanceName, $"ScriptActor:{scriptName}");
@@ -480,7 +478,11 @@ internal static class ScriptRunLauncher
// Notify the owning ScriptActor of completion (also releases its in-flight slot).
completionTarget.Tell(new ScriptActor.ScriptExecutionCompleted(scriptName, true, null));
}
catch (OperationCanceledException)
// Only the run's OWN deadline is a timeout (SRT-10). Any other cancellation — an HTTP
// client's internal timeout, a script's own CancellationTokenSource, a cancelled read —
// falls through to the general failure path below with its real exception and stack,
// instead of being reported as "timed out after N s" for a run that lasted 5 s.
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
healthCollector?.IncrementScriptError();
summaryRecorder?.RecordTimedOut(instanceName, scriptName, runStopwatch.ElapsedMilliseconds);
@@ -714,18 +716,16 @@ internal static class ScriptRunLauncher
var scriptName = $"AlarmActor:{alarmName}";
var runStopwatch = Stopwatch.StartNew();
// Identify the worker this body is holding, so the
// stuck-script watchdog can detach and replace it if the body wedges — same
// mechanism, same gauge, as the instance-script path. Read in the FIRST synchronous
// segment, before any await.
var workerSlot = ScriptExecutionScheduler.CurrentWorkerSlot;
var workerRunStamp = workerSlot is { } slot ? executionScheduler.CurrentRunStamp(slot) : 0L;
// Track the worker this body is holding, so the stuck-script watchdog can detach and
// replace it if the body wedges — same mechanism, same gauge, as the instance-script
// path, and likewise followed across awaits (SRT-1).
var workerTracker = ScriptRunWorkerTracker.Begin(executionScheduler);
IDisposable? logScope = null;
var completed = 0;
ArmStuckScriptWatchdog(
cts, options, logger, siteEventLogger, executionScheduler,
workerSlot, workerRunStamp, timeout,
workerTracker, timeout,
() => Volatile.Read(ref completed) != 0,
$"Alarm on-trigger script for '{alarmName}' on instance '{instanceName}'",
instanceName, scriptName);
@@ -802,7 +802,8 @@ internal static class ScriptRunLauncher
summaryRecorder?.RecordCompleted(instanceName, scriptName, runStopwatch.ElapsedMilliseconds);
completionTarget.Tell(new AlarmActor.AlarmExecutionCompleted(alarmName, true));
}
catch (OperationCanceledException)
// Only the run's own deadline is a timeout (SRT-10); see RunScriptAsync.
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
healthCollector?.IncrementScriptError();
summaryRecorder?.RecordTimedOut(instanceName, scriptName, runStopwatch.ElapsedMilliseconds);
@@ -854,8 +855,7 @@ internal static class ScriptRunLauncher
ILogger logger,
ISiteEventLogger? siteEventLogger,
ScriptExecutionScheduler scheduler,
int? workerSlot,
long workerRunStamp,
ScriptRunWorkerTracker workerTracker,
TimeSpan timeout,
Func<bool> isCompleted,
string subject,
@@ -871,6 +871,8 @@ internal static class ScriptRunLauncher
var stuckMsg = $"{subject} exceeded its {timeout.TotalSeconds:F0}s timeout and is STILL EXECUTING — " +
"its dedicated script-execution thread is blocked (cooperative cancellation not observed).";
// The worker the run holds NOW — after any number of awaits (SRT-1).
var (workerSlot, workerRunStamp) = workerTracker.Snapshot();
var outcome = workerSlot is { } slot
? scheduler.TryDetachWorker(slot, workerRunStamp)
: WorkerDetachOutcome.NotRunning;
@@ -0,0 +1,111 @@
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
/// <summary>
/// Tracks WHICH script-execution worker a run is holding right now, for the stuck-script
/// watchdog (2026-12-02 review SRT-1).
/// <para>
/// The launcher used to capture <c>(slot, runStamp)</c> once, in the run's first synchronous
/// segment. But a script's <c>await</c> continuation is a NEW task queued back onto the scheduler,
/// dequeued by whichever worker is free under a NEW run stamp — so once the script had awaited
/// anything (practically every script reads an attribute before doing I/O), the watchdog's
/// captured pair no longer matched, <c>TryDetachWorker</c> answered <c>NotRunning</c>, and a
/// worker wedged in blocking I/O was never detached or replaced.
/// </para>
/// <para>
/// The run's tracker flows with its <see cref="ExecutionContext"/> through an
/// <see cref="AsyncLocal{T}"/> whose change callback fires every time a piece of the run starts
/// (context restored on a thread) or stops (context reverted) executing. On start it records the
/// current thread's worker slot and that worker's current run stamp; on stop it clears them if
/// that worker was the recorded one. A run blocked inside a continuation therefore keeps the
/// latest <c>(slot, stamp)</c> of the worker it is actually blocking, while a run parked in an
/// await (holding no thread) reads as "not on a worker".
/// </para>
/// </summary>
internal sealed class ScriptRunWorkerTracker
{
private static readonly AsyncLocal<ScriptRunWorkerTracker?> Current = new(OnContextChanged);
private readonly ScriptExecutionScheduler _scheduler;
private readonly object _gate = new();
private int _slot = -1;
private long _stamp;
private ScriptRunWorkerTracker(ScriptExecutionScheduler scheduler) => _scheduler = scheduler;
/// <summary>
/// Starts tracking the calling run: records the worker the caller is on (if any) and installs
/// the tracker in the run's execution context so every later continuation updates it. Call in
/// the run's first synchronous segment.
/// </summary>
/// <param name="scheduler">The scheduler whose workers run this script.</param>
/// <returns>The run's tracker.</returns>
public static ScriptRunWorkerTracker Begin(ScriptExecutionScheduler scheduler)
{
var tracker = new ScriptRunWorkerTracker(scheduler);
tracker.OnEnter();
Current.Value = tracker;
return tracker;
}
/// <summary>
/// The worker the run is executing on right now, as <c>(slot, runStamp)</c>; a null slot when
/// the run holds no script-execution worker (parked in an await, or on another thread).
/// </summary>
/// <returns>The latest observed worker slot and its run stamp.</returns>
public (int? Slot, long RunStamp) Snapshot()
{
lock (_gate)
return _slot >= 0 ? (_slot, _stamp) : (null, 0L);
}
private static void OnContextChanged(AsyncLocalValueChangedArgs<ScriptRunWorkerTracker?> args)
{
// Only thread switches matter; the explicit set in Begin already recorded the worker.
if (!args.ThreadContextChanged)
return;
try
{
if (args.PreviousValue is { } leaving && !ReferenceEquals(leaving, args.CurrentValue))
leaving.OnLeave();
if (args.CurrentValue is { } entering && !ReferenceEquals(entering, args.PreviousValue))
entering.OnEnter();
}
catch
{
// Never let diagnostics bookkeeping fault an execution-context switch.
}
}
private void OnEnter()
{
// Only a script-execution worker is recorded. The run's execution context also flows to
// threads that hold no worker — a thread-pool continuation, or the watchdog's own
// timer callback, which captured the context when it was registered — and those must
// NOT erase the worker a still-running segment is blocking. A stale record is harmless:
// OnLeave clears it when that worker's segment ends, and TryDetachWorker re-checks the
// run stamp before detaching anything.
if (ScriptExecutionScheduler.CurrentWorkerSlot is not { } slot)
return;
var stamp = _scheduler.CurrentRunStamp(slot);
if (stamp == 0)
return;
lock (_gate)
{
_slot = slot;
_stamp = stamp;
}
}
private void OnLeave()
{
var slot = ScriptExecutionScheduler.CurrentWorkerSlot;
lock (_gate)
{
if (slot is { } s && s == _slot)
{
_slot = -1;
_stamp = 0;
}
}
}
}