fix(site-runtime): script Asks honour the run deadline, Notify.Status checks the buffer first, routed calls wait for the script's own timeout (SRT-8, SRT-9, SRT-13, WP3 task 3.9)

This commit is contained in:
Joseph Doherty
2026-12-03 10:15:23 -05:00
parent bc7fae2652
commit b0c40deefb
8 changed files with 201 additions and 45 deletions
@@ -3423,7 +3423,14 @@ public class DeploymentManagerActor : ReceiveActor, IWithTimers
// Flow Debugger (design 2026-09-05 §5.2): the trace flag rides beside the parent id.
Trace: request.Trace);
var sender = Sender;
instanceActor.Ask<ScriptCallResult>(scriptCall, TimeSpan.FromSeconds(30))
// SRT-13: wait as long as the TARGET SCRIPT may run — its resolved execution timeout
// (enqueue-anchored, so the run replies by then even if it queued) plus the
// stuck-script grace and a small margin — not a hard-coded 30 s. A 120 s handshake
// script used to fail its inbound caller at 30 s while it ran on and completed its
// device writes, so a retrying caller ran the handshake twice.
RoutedCallTimeoutAsync(instanceActor, request.ScriptName)
.ContinueWith(timeout => instanceActor.Ask<ScriptCallResult>(scriptCall, timeout.Result))
.Unwrap()
.ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
@@ -3466,6 +3473,30 @@ public class DeploymentManagerActor : ReceiveActor, IWithTimers
}
}
/// <summary>Slack on top of a routed script's own timeout before the routed Ask gives up.</summary>
internal static readonly TimeSpan RoutedCallMargin = TimeSpan.FromSeconds(5);
/// <summary>
/// SRT-13: the routed-call Ask timeout for <paramref name="scriptName"/> — its resolved execution
/// timeout plus the stuck-script grace and <see cref="RoutedCallMargin"/>. Falls back to the
/// site default timeout when the instance cannot answer (never faults).
/// </summary>
private Task<TimeSpan> RoutedCallTimeoutAsync(IActorRef instanceActor, string scriptName) =>
RoutedCallTimeoutAsync(instanceActor, scriptName, _options);
/// <inheritdoc cref="RoutedCallTimeoutAsync(IActorRef, string)"/>
internal static Task<TimeSpan> RoutedCallTimeoutAsync(IActorRef instanceActor, string scriptName, SiteRuntimeOptions options)
{
var slack = TimeSpan.FromMilliseconds(Math.Max(0, options.StuckScriptGraceMs)) + RoutedCallMargin;
var fallback = TimeSpan.FromSeconds(options.ScriptExecutionTimeoutSeconds) + slack;
return instanceActor
.Ask<InstanceActor.ScriptExecutionTimeoutReply>(
new InstanceActor.GetScriptExecutionTimeout(scriptName), TimeSpan.FromSeconds(5))
.ContinueWith(t => t.IsCompletedSuccessfully && t.Result.Timeout is { } scriptTimeout
? scriptTimeout + slack
: fallback, TaskScheduler.Default);
}
/// <summary>
/// Projects a routed script's return value to a cross-process-serializable plain
/// CLR graph (<see cref="Dictionary{TKey,TValue}"/> / <see cref="List{T}"/> /
@@ -153,6 +153,16 @@ public class InstanceActor : ReceiveActor
internal sealed record StaticOverridesFlushed(IActorRef Actor, Exception? Error);
/// <summary>
/// SRT-13: asks for a script's resolved execution timeout (per-script override, else the
/// site default) so a routed inbound call waits as long as the script is allowed to run
/// instead of a hard-coded 30 s.
/// </summary>
internal sealed record GetScriptExecutionTimeout(string ScriptName);
/// <summary>Reply to <see cref="GetScriptExecutionTimeout"/>; null when the script is unknown.</summary>
internal sealed record ScriptExecutionTimeoutReply(TimeSpan? Timeout);
/// <summary>
/// Cached string forms of <see cref="QualityCode"/> — the TagValueUpdate ingest path calls this once or twice per update, so a
/// static lookup replaces repeated <see cref="Enum.ToString()"/> reflection.
@@ -391,6 +401,7 @@ public class InstanceActor : ReceiveActor
// Handle script call requests — route to appropriate Script Actor (Ask pattern)
Receive<ScriptCallRequest>(HandleScriptCallRequest);
Receive<GetScriptExecutionTimeout>(HandleGetScriptExecutionTimeout);
// Handle attribute value changes from DCL (Tell pattern)
Receive<AttributeValueChanged>(HandleAttributeValueChanged);
@@ -1077,6 +1088,16 @@ public class InstanceActor : ReceiveActor
/// Routes script call requests to the appropriate Script Actor.
/// Uses Ask pattern.
/// </summary>
private void HandleGetScriptExecutionTimeout(GetScriptExecutionTimeout request)
{
var script = _configuration?.Scripts.FirstOrDefault(s => s.CanonicalName == request.ScriptName);
Sender.Tell(new ScriptExecutionTimeoutReply(script is null
? null
: TimeSpan.FromSeconds(script.ExecutionTimeoutSeconds is { } perScript && perScript > 0
? perScript
: _options.ScriptExecutionTimeoutSeconds)));
}
private void HandleScriptCallRequest(ScriptCallRequest request)
{
if (_scriptActors.TryGetValue(request.ScriptName, out var scriptActor))
@@ -728,7 +728,10 @@ public class ScriptRuntimeContext
// ScadaBridge#56: the Instance Actor logs under this run's id while serving it.
SourceExecutionId: _executionId);
var response = await _instanceActor.Ask<GetAttributeResponse>(request, _askTimeout).ConfigureAwait(false);
// SRT-9: the run's deadline token cancels the wait, so a run parked here takes the timeout
// path at its deadline instead of sailing past it (Roslyn only observes the token between
// top-level statements).
var response = await _instanceActor.Ask<GetAttributeResponse>(request, _askTimeout, _scriptTimeoutToken).ConfigureAwait(false);
if (!response.Found)
{
@@ -940,7 +943,8 @@ public class ScriptRuntimeContext
{
// Ask — mutation serialized through the Instance Actor mailbox; the reply
// carries the device-write outcome for data-connected attributes.
response = await _instanceActor.Ask<SetStaticAttributeResponse>(command, _askTimeout).ConfigureAwait(false);
// SRT-9: bounded by the run's deadline too (a data-sourced write waits out the DCL Ask).
response = await _instanceActor.Ask<SetStaticAttributeResponse>(command, _askTimeout, _scriptTimeoutToken).ConfigureAwait(false);
}
catch (Exception ex) when (sw is not null)
{
@@ -1217,7 +1221,9 @@ public class ScriptRuntimeContext
Trace: _isTraced);
// Ask the Instance Actor, which routes to the appropriate Script Actor
var result = await _instanceActor.Ask<ScriptCallResult>(request, _askTimeout).ConfigureAwait(false);
// SRT-9: the CALLER's deadline cancels the wait — a nested script that outlives the caller's
// budget no longer lets the caller carry on past its timeout and be recorded as completed.
var result = await _instanceActor.Ask<ScriptCallResult>(request, _askTimeout, _scriptTimeoutToken).ConfigureAwait(false);
if (!result.Success)
{
@@ -1313,7 +1319,9 @@ public class ScriptRuntimeContext
// threaded so NotifyTarget.Send can stamp it onto NotificationSubmit.
_sourceNode,
// Flow Debugger: the NotifySend row rides the inline collector (null when untraced).
traceSink: _traceSink);
traceSink: _traceSink,
// SRT-8: Notify.Status's central query is bounded by the run's deadline.
scriptTimeoutToken: _scriptTimeoutToken);
/// <summary>
/// Read-only access to the instance's CURRENT alarm conditions (MES alarm-status API
@@ -2678,6 +2686,16 @@ public class ScriptRuntimeContext
private readonly TimeSpan _askTimeout;
private readonly ILogger _logger;
/// <summary>SRT-8: the run's deadline; cancels the central status query.</summary>
private readonly CancellationToken _scriptTimeoutToken;
/// <summary>
/// SRT-8: ceiling on the central round trip of <see cref="Status"/> — it is a point read,
/// and the script's whole execution budget (<c>_askTimeout</c>) is far too long to wait
/// when central is unreachable.
/// </summary>
internal static readonly TimeSpan CentralStatusQueryTimeout = TimeSpan.FromSeconds(10);
/// <summary>
/// The per-execution id for this script run, stamped
/// into <c>AuditEvent.ExecutionId</c> on the <c>NotifySend</c> row.
@@ -2730,6 +2748,7 @@ public class ScriptRuntimeContext
/// <param name="parentExecutionId">Optional identifier of the parent execution (for routed calls).</param>
/// <param name="sourceNode">Optional cluster node identifier (node-a/node-b) for audit stamping.</param>
/// <param name="traceSink">Flow Debugger inline collector — receives the same <see cref="AuditEvent"/> <c>Send</c> hands to the writer; null when untraced.</param>
/// <param name="scriptTimeoutToken">The run's deadline; cancels the central status query (SRT-8).</param>
// Parameter ordering: executionId sits immediately after the ILogger,
// consistent with the other audit-threaded ctors. parentExecutionId is
// a trailing optional param.
@@ -2745,8 +2764,10 @@ public class ScriptRuntimeContext
IAuditWriter? auditWriter = null,
Guid? parentExecutionId = null,
string? sourceNode = null,
Action<AuditEvent>? traceSink = null)
Action<AuditEvent>? traceSink = null,
CancellationToken scriptTimeoutToken = default)
{
_scriptTimeoutToken = scriptTimeoutToken;
_storeAndForward = storeAndForward;
_siteCommunicationActor = siteCommunicationActor;
_siteId = siteId;
@@ -2789,12 +2810,13 @@ public class ScriptRuntimeContext
/// <summary>
/// Queries the delivery status of a previously-sent notification.
///
/// The query is issued to central via the site communication actor. While the
/// notification is still buffered in the site Store-and-Forward Engine — central
/// has no row for it yet (<c>Found: false</c>) but the buffer still holds the id —
/// the status is reported as the site-local <c>Forwarding</c> state. If central
/// has a row, its status is mapped through verbatim. If central does not know the
/// id and it is not buffered locally, the status is <c>Unknown</c>.
/// While the notification is still buffered in the site Store-and-Forward Engine it is
/// answered site-locally as <c>Forwarding</c> — checked FIRST (2026-12-02 review SRT-8),
/// so the common "central unreachable, still buffered" case never waits on central.
/// Otherwise the query goes to central (bounded by <see cref="CentralStatusQueryTimeout"/>
/// and the run's deadline) and a central row's status is mapped through verbatim. If central
/// does not know the id (or cannot be reached) and it is not buffered, the status is
/// <c>Unknown</c>.
/// </summary>
/// <param name="notificationId">The notification identifier returned from Send.</param>
/// <returns>The delivery status of the notification.</returns>
@@ -2804,19 +2826,24 @@ public class ScriptRuntimeContext
throw new InvalidOperationException(
"Notification status query is not available — site communication actor not wired");
// Site-local first: still in the buffer ⇒ in transit, whatever central knows.
if (await TryBufferedStatusAsync(notificationId).ConfigureAwait(false) is { } forwarding)
return forwarding;
var correlationId = Guid.NewGuid().ToString();
var query = new NotificationStatusQuery(correlationId, notificationId);
var centralTimeout = _askTimeout < CentralStatusQueryTimeout ? _askTimeout : CentralStatusQueryTimeout;
NotificationStatusResponse response;
try
{
response = await _siteCommunicationActor
.Ask<NotificationStatusResponse>(query, _askTimeout).ConfigureAwait(false);
.Ask<NotificationStatusResponse>(query, centralTimeout, _scriptTimeoutToken).ConfigureAwait(false);
}
catch (Exception ex)
catch (Exception ex) when (!_scriptTimeoutToken.IsCancellationRequested)
{
// Central could not be reached. Fall through to the buffer check: if the
// notification is still in the local S&F buffer it is Forwarding.
// Central could not be reached. Re-check the buffer: the notification may have
// been enqueued by a sweep race between the local check and here.
_logger.LogWarning(ex,
"Notification status query for {NotificationId} did not reach central",
notificationId);
@@ -2831,20 +2858,21 @@ public class ScriptRuntimeContext
response.Status, response.RetryCount, response.LastError, response.DeliveredAt);
}
// Central has no row. If the notification is still buffered at the site it
// is in transit — report the site-local Forwarding state. Otherwise it is
// genuinely unknown (never sent, or already forwarded and central lost it).
if (_storeAndForward != null)
{
var buffered = await _storeAndForward.GetMessageByIdAsync(notificationId).ConfigureAwait(false);
if (buffered != null)
{
return new NotificationDeliveryStatus(
"Forwarding", buffered.RetryCount, buffered.LastError, DeliveredAt: null);
}
}
// Central has no row. Re-check the buffer (the forwarder may have re-buffered it
// meanwhile); otherwise it is genuinely unknown (never sent, or already forwarded
// and central lost it).
return await TryBufferedStatusAsync(notificationId).ConfigureAwait(false)
?? new NotificationDeliveryStatus("Unknown", 0, null, null);
}
return new NotificationDeliveryStatus("Unknown", 0, null, null);
private async Task<NotificationDeliveryStatus?> TryBufferedStatusAsync(string notificationId)
{
if (_storeAndForward == null)
return null;
var buffered = await _storeAndForward.GetMessageByIdAsync(notificationId).ConfigureAwait(false);
return buffered == null
? null
: new NotificationDeliveryStatus("Forwarding", buffered.RetryCount, buffered.LastError, DeliveredAt: null);
}
}