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
@@ -109,7 +109,7 @@ NotificationStatus status = Notify.Status(id);
- Available to instance scripts (via Script Execution Actors), alarm on-trigger scripts (via Alarm Execution Actors), and shared scripts (executing inline).
- `Notify.To("listName").Send(...)` is **asynchronous**: it generates a `NotificationId` (GUID) locally, hands the notification to the site Store-and-Forward Engine for forwarding to central, and returns the `NotificationId` to the script **immediately**. The script does not block waiting for delivery.
- The message body is **plain text** only. No HTML content.
- `Notify.Status(notificationId)` returns a small **status record** — the current status, retry count, last error, and key timestamps (enqueued, delivered). While the notification is still in the site Store-and-Forward buffer, the site answers the query **locally** with status `Forwarding`; once forwarded to central, the query round-trips to central and reads the `Notifications` table.
- `Notify.Status(notificationId)` returns a small **status record** — the current status, retry count, last error, and key timestamps (enqueued, delivered). While the notification is still in the site Store-and-Forward buffer, the site answers the query **locally** with status `Forwarding` — the buffer is checked **first**, without contacting central (2026-12-02 review SRT-8; it used to ask central first with the script's whole execution timeout, exactly when central was unreachable); once forwarded to central, the query round-trips to central and reads the `Notifications` table. That central query is bounded by 10 s (or the script's ask timeout if shorter) and by the run's deadline.
- The returned `NotificationId` is a `TrackedOperationId` — the shared Commons tracking-handle type used by all store-and-forward producers; `NotificationId` is simply the notification-domain name for it. Likewise, `Notify.Status` is a thin alias of the unified `Tracking.Status` accessor, retained for backward compatibility. This is a naming/type clarification only — notification delivery behavior is unchanged.
## Notification Delivery Behavior
+1 -1
View File
@@ -644,7 +644,7 @@ Per Akka.NET best practices, internal actor communication uses **Tell** (fire-an
**Ask** is reserved for system boundaries where a synchronous response is needed:
- **`Instance.CallScript()`**: Ask pattern from the running script (via `ScriptRuntimeContext.CallScript`) to sibling Script Actor. The caller needs the return value. Acceptable because script calls are infrequent relative to tag updates.
- **`Route.To().Call()`**: Ask from Inbound API to site Instance Actor via Communication Layer. External caller needs a response.
- **`Route.To().Call()`**: Ask from Inbound API to site Instance Actor via Communication Layer. External caller needs a response. On the site, the Deployment Manager's Ask to the Instance Actor waits as long as the **target script** may run — its resolved execution timeout (per-script override, else the site default) plus the stuck-script grace and 5 s — instead of a hard-coded 30 s (2026-12-02 review SRT-13: a 120 s handshake script used to fail its caller at 30 s while it ran on, so a retrying caller ran it twice). Script-facing Asks (`GetAttribute`, `SetAttribute`, `CallScript`) are cancelled by the run's own deadline token (SRT-9), so a run parked in one takes the timeout path at its deadline instead of sailing past it.
- **Debug view snapshot**: Ask from Communication Layer to Instance Actor for initial state.
## Concurrency & Serialization
@@ -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);
}
}
@@ -163,4 +163,38 @@ public class DeploymentManagerRouteTraceTests : TestKit, IDisposable
var read = ExpectMsg<RouteToGetAttributesResponse>(TimeSpan.FromSeconds(10));
Assert.Equal("Hand", read.Values["Mode"]?.ToString());
}
/// <summary>
/// SRT-13: a routed inbound call waits as long as the TARGET script may run — its resolved
/// timeout (per-script override, else the site default) plus the stuck-script grace and a
/// margin — instead of a hard-coded 30 s that failed a 120 s handshake script's caller while the
/// script ran on.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RoutedCallTimeout_FollowsTheTargetScriptsTimeout()
{
var options = new SiteRuntimeOptions { ScriptExecutionTimeoutSeconds = 30, StuckScriptGraceMs = 1000 };
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Handshake",
Scripts =
[
new ResolvedScript { CanonicalName = "Slow", Code = "return 1;", ExecutionTimeoutSeconds = 120 },
new ResolvedScript { CanonicalName = "Default", Code = "return 1;" },
],
};
var instance = ActorOf(Props.Create(() => new InstanceActor(
"Handshake", JsonSerializer.Serialize(config), _storage, _compilationService, _sharedScriptLibrary,
null, options, NullLogger<InstanceActor>.Instance)));
var slack = TimeSpan.FromSeconds(1) + DeploymentManagerActor.RoutedCallMargin;
Assert.Equal(TimeSpan.FromSeconds(120) + slack,
await DeploymentManagerActor.RoutedCallTimeoutAsync(instance, "Slow", options)); // pre-fix: 30 s flat
Assert.Equal(TimeSpan.FromSeconds(30) + slack,
await DeploymentManagerActor.RoutedCallTimeoutAsync(instance, "Default", options));
// Unknown script: the site default (the instance replies "not found" on the call itself).
Assert.Equal(TimeSpan.FromSeconds(30) + slack,
await DeploymentManagerActor.RoutedCallTimeoutAsync(instance, "Missing", options));
}
}
@@ -188,6 +188,32 @@ public class StuckScriptWatchdogTests : TestKit, IDisposable
Assert.Contains("upstream request was cancelled", result.ErrorMessage);
}
/// <summary>
/// SRT-9: a script parked in <c>Instance.CallScript</c> past its own deadline takes the timeout
/// path AT the deadline. Pre-fix the Ask was bounded only by the full script timeout measured
/// from the call (and ignored the deadline token), so the run sailed past its deadline and
/// then failed with an Ask timeout — or, had the callee answered, carried on and completed.
/// </summary>
[Fact]
public void ScriptParkedInCallScript_TimesOutAtItsDeadline()
{
using var scheduler = new ScriptExecutionScheduler(1);
var options = new SiteRuntimeOptions { ScriptExecutionTimeoutSeconds = 2, StuckScriptGraceMs = 200, MaxScriptCallDepth = 10 };
// The instance (a silent probe) never answers the nested call.
var actor = BuildScriptActor("Caller", CompileRaw(
"await Task.Delay(1000); await Instance.CallScript(\"Callee\"); return 1;"),
options, scheduler, null);
var caller = CreateTestProbe();
var sw = System.Diagnostics.Stopwatch.StartNew();
actor.Tell(new ScriptCallRequest("Caller", null, 0, "corr-nested"), caller.Ref);
var result = caller.ExpectMsg<ScriptCallResult>(TimeSpan.FromSeconds(10));
Assert.False(result.Success);
Assert.Contains("timed out", result.ErrorMessage); // pre-fix: "failed: ... Timeout ..." at ~3 s
Assert.True(sw.Elapsed < TimeSpan.FromMilliseconds(2900), $"timed out after {sw.Elapsed}");
}
/// <summary>Verifies that at the detach cap no further replacement is started and an error event is emitted.</summary>
[Fact]
public void AtTheDetachCap_NoFurtherReplacementIsStarted_AndAnErrorEventIsEmitted()
@@ -276,10 +276,14 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable
Assert.Null(payload!.SourceScript);
}
/// <summary>Verifies that status, when still buffered at site, reports forwarding.</summary>
/// <summary>
/// Verifies that status, when still buffered at site, reports forwarding — answered
/// site-locally WITHOUT asking central (2026-12-02 review SRT-8: it used to ask central first,
/// with the script's whole execution timeout, exactly when central is unreachable).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Status_WhenStillBufferedAtSite_ReportsForwarding()
public async Task Status_WhenStillBufferedAtSite_ReportsForwarding_WithoutAskingCentral()
{
var commProbe = CreateTestProbe();
var notify = CreateHelper(commProbe.Ref);
@@ -287,20 +291,32 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable
// Enqueue but never let it forward — the message stays buffered at the site.
var notificationId = await notify.To("Operators").Send("Pump alarm", "Pump 3 tripped");
var statusTask = notify.Status(notificationId);
// Nobody answers on the central side: the call must still return promptly.
var status = await notify.Status(notificationId).WaitAsync(TimeSpan.FromSeconds(2));
// The status query goes to central; central has no row for an un-forwarded
// notification, so it answers Found: false.
var query = await commProbe.ExpectMsgAsync<NotificationStatusQuery>();
Assert.Equal(notificationId, query.NotificationId);
commProbe.Reply(new NotificationStatusResponse(
query.CorrelationId, Found: false, Status: "Unknown",
RetryCount: 0, LastError: null, DeliveredAt: null));
var status = await statusTask;
// Found: false AND still in the site S&F buffer → the site-local Forwarding state.
Assert.Equal("Forwarding", status.Status);
commProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(200)); // pre-fix: a NotificationStatusQuery
}
/// <summary>
/// SRT-8: the central query is bounded by the run's deadline token — a run whose deadline
/// fires while central is silent takes the timeout path rather than waiting out the Ask.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Status_CentralQuery_IsCancelledByTheRunDeadline()
{
var commProbe = CreateTestProbe();
using var deadline = new CancellationTokenSource();
var notify = new ScriptRuntimeContext.NotifyHelper(
_saf, commProbe.Ref, "site-7", "Plant.Pump3", null, TimeSpan.FromSeconds(30),
NullLogger.Instance, Guid.NewGuid(), scriptTimeoutToken: deadline.Token);
var statusTask = notify.Status("not-buffered-id");
await commProbe.ExpectMsgAsync<NotificationStatusQuery>();
deadline.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => statusTask.WaitAsync(TimeSpan.FromSeconds(5)));
}
/// <summary>Verifies that status, when central reports delivered, maps the central response.</summary>