Merge #999: shelve expiry emits Unshelved first, script-owned timeouts surface as themselves, pipeline timeout visible to breaker, resilience config fallback, backoff floor, codec exceptions, worker frame cap split

This commit is contained in:
Joseph Doherty
2026-12-03 11:07:19 -05:00
31 changed files with 1024 additions and 94 deletions
+9 -1
View File
@@ -596,8 +596,16 @@ before touching it:
snapshot could never self-correct — only the discarded pipeline's `OnClosed` stamps the close —
so a deploy during an outage would otherwise strand a false OPEN chip forever. This was
unreachable while breakers never opened; the Initialize wrap made it reachable.
- `ConsecutiveFailures` stays 0 during a connect outage **by design** — the tracker counts retry
- `ConsecutiveFailures` stays 0 during a connect outage that FAILS fast — the tracker counts retry
attempts, and Initialize has none. The breaker-OPEN chip is the operator signal.
- **The pipeline's own timeout is a failure (#999 / review K-6).** A call that outlasts its capability
timeout (a blackholed device that never answers) used to reach the breaker as an
`OperationCanceledException`, which both predicates excluded — every call burned the full timeout
forever, the breaker never opened and `/hosts` read `ConsecutiveFailures = 0`. Now the breaker counts
the timed-out attempt (a cancellation the CALLER asked for still does not count — an outermost
pass-through records the caller's token so the two are told apart) and `OnTimeout` records one tracker
failure. The timeout is the call's total budget, so it is still not retried. Pinned by
`Pipeline_timeouts_open_the_breaker_and_reach_the_tracker` + `Caller_cancellation_is_not_a_failure`.
---
+1 -1
View File
@@ -122,7 +122,7 @@ rationale is recorded in the engine's class doc so it is not re-proposed:
- `ApplyOneShotShelve` / `ApplyTimedShelve(unshelveAtUtc)` / `ApplyUnshelve` — shelving transitions. `Timed` requires `unshelveAtUtc > nowUtc`.
- `ApplyEnable` / `ApplyDisable` — operator enable/disable. Disabled alarms ignore predicate results until re-enabled; on enable, `ActiveState` is re-derived from the next evaluation.
- `ApplyAddComment(text)` — append-only audit entry, no state change.
- `ApplyShelvingCheck(nowUtc)` — called by the 5s timer; promotes expired `Timed` shelving to `Unshelved` with a `system / AutoUnshelve` audit entry. The sole owner of timed-shelve expiry — the OPC UA node's own SDK timer does nothing.
- `ApplyShelvingCheck(nowUtc)` — called by the 5s timer **and by the engine before every completed predicate evaluation** (serial and out-of-process batch paths, and at load); promotes expired `Timed` shelving to `Unshelved` with a `system / AutoUnshelve` audit entry and an `Unshelved` emission queued ahead of the predicate's own transition. The sole owner of timed-shelve expiry — the OPC UA node's own SDK timer does nothing, and `ApplyPredicate` no longer expires a timed shelve itself (#999 / review K-4: an input push that crossed the deadline before the timer used to unshelve the alarm silently — no event, no audit, the node stuck at TimedShelved).
- `ApplyAcknowledge` on an already-acknowledged alarm is a no-op **unless it carries a comment**, which is recorded as an `AddComment` (emission `CommentAdded`; `LastAck*` untouched) — the OPC UA node reports a commented re-ack, so the system of record must hold the comment too.
Two invariants the machine enforces:
+8
View File
@@ -182,6 +182,14 @@ processes:
evaluation thread is busy is reported back as *deferred*, the host stops its clock, and restarts T and G when the worker
reports it *started* — so an item queued behind a runaway sibling is neither timed out nor struck, and at the kill it
is a victim (`script worker restarted`), not the culprit.
- **Frames never exceed the cap (#999 / review K-5).** The combining pipe writer merges consecutive evaluations /
results only up to the frame cap (4 MiB) and cuts a larger batch — merged or a single `EvalBatch` — into several frames,
in order; the worker's `ctx.Logger` drain is cut by bytes as well as lines (`LogBatch` per ≤ cap; a line too large for
any batch counts as dropped). One item too large for any frame fails **that evaluation alone** as `unsupported type: …
frame cap` — an oversized input set is refused before it is written (`ScriptWorkerFrameWriter.FitsOneFrame`), an
oversized result is replaced by that error in the worker. Before, any of these faulted the writer: the worker exited
(host side: was killed as a crash), every evaluation in flight on the shard published `BadResourceUnavailable`, and a
script logging megabytes in one 100 ms window repeated that until it was quarantined.
- **Scripted alarms** (only when `Scripting:Runner:Seams` lists `ScriptedAlarm`). The engine compiles each predicate at
load only to validate it (same Roslyn, sandbox and diagnostics, so a broken predicate still fails the load; no
assembly is loaded into the host), the worker compiles and runs it, and each re-evaluation pass submits its dirty set
@@ -153,6 +153,17 @@ public static class DataProtoMapper
{
ArgumentNullException.ThrowIfNull(x);
var serving = DecodeServing(x.Serving);
serving.Validate(requireEpochs: true);
return DecodeSampleCore(x, serving, maxElements, maxBytes, preflighted: false);
}
/// <summary>
/// A sample whose <paramref name="serving"/> identity is already decoded and validated; with
/// <paramref name="preflighted"/> its value's size was already bounded by the frame preflight (K-11).
/// </summary>
private static DataSample DecodeSampleCore(
W.Sample x, ServingIdentity serving, int maxElements, int maxBytes, bool preflighted)
{
var source = x.SourceTimestamp is null
? (DateTimeOffset?)null
: TypedValueCodec.DecodeTimestamp(x.SourceTimestamp);
@@ -161,9 +172,10 @@ public static class DataProtoMapper
: TypedValueCodec.DecodeTimestamp(x.ServerTimestamp);
if (x.Version <= 0)
throw new ArgumentException("Invalid sample version.");
serving.Validate(requireEpochs: true);
return new(
TypedValueCodec.Decode(x.Value, maxElements, maxBytes),
preflighted
? TypedValueCodec.DecodePreflighted(x.Value, maxElements, maxBytes)
: TypedValueCodec.Decode(x.Value, maxElements, maxBytes),
x.StatusCode,
source,
server,
@@ -459,20 +471,9 @@ public static class DataProtoMapper
new DataDecodeLimits(maxItems, maxBytes, maxElements),
batch.Items.Select(i => i.Value)
);
if (
maxItems <= 0
|| maxBytes <= 0
|| batch.Items.Count > maxItems
|| frame.CalculateSize() > maxBytes
)
throw new ArgumentException("Frame exceeds budget.");
long decodedBytes = 0;
foreach (var update in batch.Items)
{
decodedBytes += TypedValueCodec.DecodedBytes(update.Value, maxBytes - decodedBytes);
if (decodedBytes > maxBytes)
throw new ArgumentException("Decoded frame exceeds budget.");
}
// #999 / review K-11: no second sizing pass. Preflight already refused a non-positive limit, more than maxItems
// items, an encoded frame over maxBytes, and a decoded total over maxBytes (from a HIGHER starting estimate than a
// plain per-value sum) — re-sizing the frame and every value here could never reject anything it accepted.
var serving = DecodeServing(batch.Serving);
serving.Validate(requireEpochs: true);
if (serving != expectedServing)
@@ -507,7 +508,7 @@ public static class DataProtoMapper
var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness,
update.HasOriginAgeTicks, update.OriginAgeTicks, update.HasReadiness, update.Readiness);
var sample = new DataSample(
TypedValueCodec.Decode(update.Value, maxElements, maxBytes),
TypedValueCodec.DecodePreflighted(update.Value, maxElements, maxBytes),
update.HasStatusCode ? update.StatusCode : batch.DefaultStatusCode,
sourceTime,
serverTime,
@@ -642,25 +643,16 @@ public static class DataProtoMapper
|| maxItems <= 0
|| maxBytes <= 0
|| frame.Values.Items.Count > maxItems
|| frame.CalculateSize() > maxBytes
)
throw new ArgumentException("Invalid or oversized values frame.");
// #999 / review K-11: Preflight is the one sizing pass (encoded frame + every value's decoded size, against the
// same limits); the frame and each value used to be sized again here and once more per value inside Decode.
Preflight(
frame,
frame.Values.Items.Count,
new DataDecodeLimits(maxItems, maxBytes, maxElements),
frame.Values.Items.Select(i => i.Sample.Value)
);
long decodedBytes = 0;
foreach (var update in frame.Values.Items)
{
decodedBytes += TypedValueCodec.DecodedBytes(
update.Sample.Value,
maxBytes - decodedBytes
);
if (decodedBytes > maxBytes)
throw new ArgumentException("Decoded frame exceeds budget.");
}
var items = new List<DataSubscriptionValue>(frame.Values.Items.Count);
try
{
@@ -674,11 +666,14 @@ public static class DataProtoMapper
|| expected != handle
)
throw new ArgumentException("Unknown or stale handle.");
if (DecodeServing(item.Sample.Serving) != expectedServing)
// K-11: Serving is decoded once per item (it was decoded here and again inside DecodeSample); equal to
// the already-validated expected identity, it needs no second validation either.
var serving = DecodeServing(item.Sample.Serving);
if (serving != expectedServing)
throw new ArgumentException("Unexpected serving identity.");
var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness,
item.HasOriginAgeTicks, item.OriginAgeTicks, item.HasReadiness, item.Readiness);
items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes), ageBounds, readiness,
items.Add(new(handle, DecodeSampleCore(item.Sample, expectedServing, maxElements, maxBytes, preflighted: true), ageBounds, readiness,
subscriptionAgeReadiness && item.HasFreshnessChallengeId && item.FreshnessChallengeId.Length <= 32 ? item.FreshnessChallengeId : null));
}
return new(
@@ -100,7 +100,30 @@ public static class TypedValueCodec
throw new ArgumentOutOfRangeException(nameof(maxElements));
if (value.CalculateSize() > maxBytes || DecodedBytes(value, maxBytes) > maxBytes)
throw new ArgumentException("Decoded value exceeds budget.");
return DecodeCore(value, maxElements, maxBytes);
return DecodePreflighted(value, maxElements, maxBytes);
}
/// <summary>
/// <see cref="Decode"/> without re-sizing the value (#999 / review K-11): for a caller whose frame preflight has
/// already bounded every value's encoded and decoded size against the same <paramref name="maxBytes"/> — sizing
/// each value a third time per received frame was pure overhead on the gRPC hot path. Shape/element limits and
/// every validation still apply.
/// </summary>
internal static DataValue DecodePreflighted(Wire.TypedValue value, int maxElements, int maxBytes)
{
ArgumentNullException.ThrowIfNull(value);
if (maxElements <= 0 || maxBytes <= 0)
throw new ArgumentOutOfRangeException(nameof(maxElements));
try
{
return DecodeCore(value, maxElements, maxBytes);
}
catch (Exception ex) when (ex is OverflowException or FormatException)
{
// #999 / review K-9: an out-of-range narrowing (an Int8 carrying 300) or a malformed GUID is a bad REQUEST,
// so it fails as the documented ArgumentException (→ gRPC InvalidArgument), not an unmapped internal error.
throw new ArgumentException($"Invalid typed value: {ex.Message}", ex);
}
}
internal static long DecodedBytes(Wire.TypedValue value, long limit)
@@ -132,10 +155,22 @@ public static class TypedValueCodec
return size;
}
/// <summary>0001-01-01T00:00:00Z as Unix seconds — the protobuf Timestamp / DateTimeOffset lower bound.</summary>
private const long MinTimestampSeconds = -62_135_596_800L;
/// <summary>9999-12-31T23:59:59Z as Unix seconds — the protobuf Timestamp / DateTimeOffset upper bound.</summary>
private const long MaxTimestampSeconds = 253_402_300_799L;
internal static DateTimeOffset DecodeTimestamp(Timestamp value)
{
if (value.Nanos % 100 != 0)
throw new ArgumentException("Timestamp is finer than domain tick precision.");
// #999 / review K-9: Timestamp.ToDateTimeOffset throws InvalidOperationException for seconds/nanos outside the
// representable range — which the gRPC service maps to Unavailable, telling the client to retry or fail over a
// request that can never succeed. Range-check first so it is the documented ArgumentException.
if (value.Seconds < MinTimestampSeconds || value.Seconds > MaxTimestampSeconds
|| value.Nanos < 0 || value.Nanos > 999_999_999)
throw new ArgumentException("Timestamp is outside the representable range.");
return value.ToDateTimeOffset();
}
@@ -42,7 +42,8 @@ public sealed class ConnectionBackoff
/// <summary>
/// Capped exponential backoff schedule. <paramref name="consecutiveFailures"/> ≤ 0 returns
/// <paramref name="baseInterval"/>; each subsequent failure doubles the wait up to
/// <paramref name="cap"/>. Computed in ticks with an overflow guard so a large failure
/// <paramref name="cap"/> — or up to <paramref name="baseInterval"/> when the cap is smaller (a failure never
/// shortens the wait, #999 / K-10). Computed in ticks with an overflow guard so a large failure
/// count saturates at the cap rather than wrapping negative. Ported verbatim from the S7
/// poll fork's <c>ComputeBackoffDelay</c>.
/// </summary>
@@ -53,6 +54,10 @@ public sealed class ConnectionBackoff
public static TimeSpan ComputeDelay(TimeSpan baseInterval, int consecutiveFailures, TimeSpan cap)
{
if (consecutiveFailures <= 0) return baseInterval;
// #999 / review K-10: the cap bounds the GROWTH, it never undercuts the base. As an absolute ceiling a cap below
// the base (every poll driver passes 30 s; a Sql subscription may poll every 60 s) retried a FAILING device
// faster than a healthy one — the opposite of backoff.
if (cap < baseInterval) cap = baseInterval;
// Cap the shift to avoid overflow — at 30 the result already saturates the cap for any
// reasonable base interval.
var shift = Math.Min(consecutiveFailures - 1, 30);
@@ -107,11 +107,11 @@ public sealed class PollGroupEngine : IAsyncDisposable
/// <para>The <c>interval</c> feeding that schedule is the per-subscription interval
/// <i>already clamped</i> to <paramref name="minInterval"/> in <see cref="Subscribe(IReadOnlyList{string}, TimeSpan)"/>, so
/// the first failure's wait equals the clamped interval (shift 0 → 1×) and the floor is
/// honoured for free. One asymmetry worth knowing: <c>ComputeDelay</c> saturates at the cap
/// unconditionally, so a <paramref name="backoffCap"/> set SMALLER than the clamped
/// interval makes failures retry FASTER than the interval floor — the cap outranks
/// <paramref name="minInterval"/> on the failure branch. Configure it above the floor
/// (every driver here uses 30 s against a 100 ms floor).</para></param>
/// honoured for free. A <paramref name="backoffCap"/> SMALLER than a subscription's clamped
/// interval never shortens it (#999 / review K-10): <c>ComputeDelay</c> raises the cap to the
/// base, so that subscription's failure branch waits exactly its interval — a failing device is
/// never polled faster than a healthy one. (Every driver here uses 30 s, so a 60 s Sql
/// subscription used to retry every 30 s once it failed.)</para></param>
/// <param name="onBatch">Optional per-cycle batch callback — invoked once per poll cycle that
/// produced at least one change, carrying exactly that cycle's changed items in reader
/// order, after all of the cycle's per-tag <paramref name="onChange"/> callbacks. The
@@ -22,7 +22,8 @@ namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
/// (2) Shelved alarms (OneShot / Timed) don't fire active transitions to
/// subscribers, but the state record still advances so that when shelving
/// expires the ActiveState reflects current reality. OneShot expires on the
/// next clear; Timed expires at <see cref="ShelvingState.UnshelveAtUtc"/>.
/// next clear; Timed expires at <see cref="ShelvingState.UnshelveAtUtc"/>, and only through
/// <see cref="ApplyShelvingCheck"/> (#999 / K-4) — never inside <see cref="ApplyPredicate"/>.
/// </para>
/// </remarks>
public static class Part9StateMachine
@@ -44,8 +45,10 @@ public static class Part9StateMachine
if (current.Enabled == AlarmEnabledState.Disabled)
return TransitionResult.NoOp(current, "disabled — predicate result ignored");
// Expire timed shelving if the configured clock has passed.
var shelving = MaybeExpireShelving(current.Shelving, nowUtc);
// #999 / review K-4: a timed shelve is NOT expired here. Expiry belongs to ApplyShelvingCheck alone (it carries
// the AutoUnshelve audit comment and the Unshelved emission); the engine runs it before this call. Expiring it
// here returned EmissionKind.None — the alarm unshelved with no event and no audit.
var shelving = current.Shelving;
var stateWithShelving = current with { Shelving = shelving };
// Shelved alarms still update state but skip event emission.
@@ -84,8 +87,7 @@ public static class Part9StateMachine
return new TransitionResult(next, shelved ? EmissionKind.Suppressed : EmissionKind.Cleared);
}
// Predicate matches current Active — no state change beyond possible shelving
// expiry.
// Predicate matches current Active — no state change.
return new TransitionResult(stateWithShelving, EmissionKind.None);
}
@@ -325,12 +327,6 @@ public static class Part9StateMachine
return TransitionResult.None(current);
}
private static ShelvingState MaybeExpireShelving(ShelvingState s, DateTime nowUtc)
{
if (s.Kind != ShelvingKind.Timed) return s;
return s.UnshelveAtUtc is DateTime t && nowUtc >= t ? ShelvingState.Unshelved : s;
}
private static ImmutableList<AlarmComment> AppendComment(
ImmutableList<AlarmComment> existing, DateTime ts, string user, string kind, string? text)
=> existing.Add(new AlarmComment(ts, user, kind, text ?? string.Empty));
@@ -508,7 +508,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
foreach (var (alarmId, state) in _alarms)
{
var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false);
var evalSeed = ExpireTimedShelveAtLoad(state, seed.State, pending);
var evalSeed = ExpireTimedShelve(state, seed.State, _clock(), pending);
var afterPredicate = await EvaluatePredicateToStateAsync(state, evalSeed, nowUtc: _clock(), ct, pending)
.ConfigureAwait(false);
await SaveLoadedAsync(seed, afterPredicate, ct).ConfigureAwait(false);
@@ -525,7 +525,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
{
var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false);
sources.Add(seed);
seeds.Add((state, ExpireTimedShelveAtLoad(state, seed.State, pending)));
seeds.Add((state, ExpireTimedShelve(state, seed.State, _clock(), pending)));
}
var after = await EvaluatePredicateBatchToStatesAsync(seeds, _clock(), ct, pending).ConfigureAwait(false);
for (var i = 0; i < seeds.Count; i++)
@@ -605,10 +605,16 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// predicate runs. Otherwise <see cref="Part9StateMachine.ApplyPredicate"/>'s own expiry silently unshelved it
/// (no audit entry, no event) and the shelving timer found nothing left to expire.
/// </summary>
private AlarmConditionState ExpireTimedShelveAtLoad(
AlarmState state, AlarmConditionState seed, List<ScriptedAlarmEvent> pendingEmissions)
/// <remarks>
/// #999 / review K-4: the same expiry runs before every completed predicate evaluation (serial and batch paths),
/// not only at load — a push that crossed the deadline before the 5 s shelving timer otherwise unshelved the alarm
/// silently and the OPC UA node stayed TimedShelved. <see cref="Part9StateMachine.ApplyPredicate"/> no longer
/// expires a timed shelve itself, so the shelving check is the only place one expires.
/// </remarks>
private AlarmConditionState ExpireTimedShelve(
AlarmState state, AlarmConditionState seed, DateTime nowUtc, List<ScriptedAlarmEvent> pendingEmissions)
{
var check = Part9StateMachine.ApplyShelvingCheck(seed, _clock());
var check = Part9StateMachine.ApplyShelvingCheck(seed, nowUtc);
if (check.Emission == EmissionKind.None) return seed;
var evt = BuildEmission(state, check.State, check.Emission, LastWorstStatus(state.Definition.AlarmId));
if (evt is not null) pendingEmissions.Add(evt);
@@ -1109,7 +1115,10 @@ public sealed class ScriptedAlarmEngine : IDisposable
// QualityChanged on every push instead of once per real bucket change.
var qualityBucketChanged = TrackQualityBucket(state.Definition.AlarmId, worstStatus);
var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc);
// #999 / K-4: an expired timed shelve is unshelved by the shelving check (Unshelved event + AutoUnshelve audit),
// queued BEFORE the predicate's own transition, never silently inside ApplyPredicate.
var result = Part9StateMachine.ApplyPredicate(
ExpireTimedShelve(state, seed, nowUtc, pendingEmissions), predicateTrue, nowUtc);
var transition = result.Emission != EmissionKind.None
? BuildEmission(state, result.State, result.Emission, worstStatus, captured)
: null;
@@ -1285,7 +1294,10 @@ public sealed class ScriptedAlarmEngine : IDisposable
// From here on, identical to the serial path: the bucket is tracked only once the predicate completed (I3).
var qualityBucketChanged = TrackQualityBucket(state.Definition.AlarmId, worstStatus);
var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc);
// #999 / K-4: an expired timed shelve is unshelved by the shelving check (Unshelved event + AutoUnshelve audit),
// queued BEFORE the predicate's own transition, never silently inside ApplyPredicate.
var result = Part9StateMachine.ApplyPredicate(
ExpireTimedShelve(state, seed, nowUtc, pendingEmissions), predicateTrue, nowUtc);
var transition = result.Emission != EmissionKind.None
? BuildEmission(state, result.State, result.Emission, worstStatus, captured)
: null;
@@ -278,11 +278,18 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
/// <returns>The shard index.</returns>
internal static int ShardIndex(string scopedKey, int shardCount)
{
// FNV-1a over the key's UTF-8 bytes — encoded rune by rune into a stack buffer (#999 / review K-11): the same
// bytes, so the same placement as before, without a byte[] per evaluation.
var hash = 2166136261u;
foreach (var b in Encoding.UTF8.GetBytes(scopedKey))
Span<byte> utf8 = stackalloc byte[4];
foreach (var rune in scopedKey.EnumerateRunes())
{
hash ^= b;
hash *= 16777619u;
var n = rune.EncodeToUtf8(utf8);
for (var i = 0; i < n; i++)
{
hash ^= utf8[i];
hash *= 16777619u;
}
}
return (int)(hash % (uint)shardCount);
}
@@ -391,7 +398,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
var handedOff = false;
SemaphoreSlim? gate = null;
var shard = state.Suspect ? _isolation : _shards[ShardIndex(key, _shards.Length)];
var shard = state.Suspect ? _isolation : _shards[state.ShardIndexFor(key, _shards.Length)];
WorkerConnection? connection = null;
try
{
@@ -540,7 +547,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
var state = Admit(key, invocation.Kind, invocation.Source);
if (state.QuarantineReason is not null || _compileFailures.ContainsKey(state.FailureKey)) return BatchPreparation.Full;
var shard = state.Suspect ? _isolation : _shards[ShardIndex(key, _shards.Length)];
var shard = state.Suspect ? _isolation : _shards[state.ShardIndexFor(key, _shards.Length)];
if (shard.IsolationGate is not null || shard.Current is not { } connection) return BatchPreparation.Full;
if (connection.TryGetLoaded(key, state.ShaHex, SlotOrder(state, invocation.Inputs)) is not { } entry) return BatchPreparation.Full;
@@ -757,7 +764,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
/// <summary>The shard a key's NEXT evaluation goes to (attribution may just have made it a suspect).</summary>
private WorkerShard RouteFor(string key, KeyState state)
=> state.Suspect ? _isolation : _shards[ShardIndex(key, _shards.Length)];
=> state.Suspect ? _isolation : _shards[state.ShardIndexFor(key, _shards.Length)];
private static ScriptRunOutcome Unavailable(string reason, WorkerShard shard, WorkerConnection? failed)
=> ScriptRunOutcome.Unavailable(reason) with { Recovery = shard.WhenRecoveredAsync(failed) };
@@ -1044,6 +1051,20 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
/// <summary>The negative compile cache's key for this source (kind-scoped).</summary>
public string FailureKey => _failureKey ??= InProcessScriptRunner.ScopedKey(Kind, ShaHex);
private int _shardIndex = -1;
/// <summary>
/// The key's (non-suspect) shard, hashed once per key state instead of per evaluation (#999 / review K-11). The
/// state is per scoped key and the shard count is fixed for the runner's life, so it never changes; a benign
/// race hashes the same value twice.
/// </summary>
public int ShardIndexFor(string scopedKey, int shardCount)
{
var index = Volatile.Read(ref _shardIndex);
if (index < 0) Volatile.Write(ref _shardIndex, index = ShardIndex(scopedKey, shardCount));
return index;
}
/// <summary>The slot order last used for this key (see <see cref="SlotOrder"/>).</summary>
public string[]? Paths;
public readonly List<DateTime> KillStrikes = [];
@@ -659,6 +659,7 @@ internal sealed class WorkerConnection : IAsyncDisposable
var pending = new PendingEval(key, request.EvalId, onFinished, _dispatcher);
if (softTimeout is { } soft) pending.Arm(soft, hardGrace, OnHardDeadline, WorkerSoftClock);
_pending[request.EvalId] = pending;
if (RefuseOversized(request, pending)) return pending;
var batch = new EvalBatch();
batch.Items.Add(request);
if (!Send(new Envelope { Eval = batch }) || _exited.Task.IsCompleted)
@@ -689,10 +690,12 @@ internal sealed class WorkerConnection : IAsyncDisposable
var pending = new PendingEval(item.Key, item.Request.EvalId, item.OnFinished, _dispatcher);
pending.Arm(item.SoftTimeout, item.HardGrace, OnHardDeadline, WorkerSoftClock);
_pending[item.Request.EvalId] = pending;
batch.Items.Add(item.Request);
pendings[i] = pending;
if (!RefuseOversized(item.Request, pending)) batch.Items.Add(item.Request);
}
if (items.Count > 0 && (!Send(new Envelope { Eval = batch }) || _exited.Task.IsCompleted))
// The writer cuts the batch into frames within the cap (#999 / review K-5); only an item that fits no frame on
// its own is refused above.
if (batch.Items.Count > 0 && (!Send(new Envelope { Eval = batch }) || _exited.Task.IsCompleted))
{
foreach (var pending in pendings)
if (_pending.TryRemove(pending.EvalId, out _)) pending.Complete(null);
@@ -700,6 +703,28 @@ internal sealed class WorkerConnection : IAsyncDisposable
return pendings;
}
/// <summary>
/// #999 / review K-5: an evaluation whose request (its inputs) is too large for any frame fails ALONE, as an
/// unsupported-type result, before it reaches the pipe writer — which would otherwise have to refuse the frame,
/// fault, and take the worker (and every evaluation in flight on it) down with it.
/// </summary>
private bool RefuseOversized(EvalRequest request, PendingEval pending)
{
if (_writer.FitsOneFrame(request)) return false;
if (_pending.TryRemove(request.EvalId, out _))
pending.Complete(new EvalResult
{
EvalId = request.EvalId,
Error = new ScriptError
{
Kind = ScriptError.Types.Kind.UnsupportedType,
Message = $"the evaluation's inputs are {request.CalculateSize()} bytes encoded, over the " +
$"{_writer.MaxFrameBytes}-byte frame cap",
},
});
return true;
}
/// <summary>
/// The compiled form of <paramref name="key"/> in this worker when it is loaded at <paramref name="sourceHashHex"/>
/// with <paramref name="inputPaths"/> and compiled cleanly — the batch fast path, which never waits for a load.
@@ -240,35 +240,130 @@ public sealed class ScriptWorkerFrameWriter
}
}
/// <summary>
/// Room left in a frame for the envelope header (version + sequence number, ≤ 2 × 11 bytes) and the body's own tag
/// and length prefix. Generous on purpose: the merge budget below only needs to be an upper bound.
/// </summary>
private const int FrameHeadroom = 64;
/// <summary>The bytes a merged batch's items and ids may add up to so the frame stays within the cap.</summary>
private int MergeBudget => Math.Max(1, MaxFrameBytes - FrameHeadroom);
/// <summary>
/// Whether <paramref name="item"/> fits a frame on its own (#999 / review K-5). A caller that builds an evaluation
/// checks this first and fails the one evaluation instead of handing the writer a frame it must refuse.
/// </summary>
/// <param name="item">The evaluation request or result.</param>
/// <returns>Whether it fits.</returns>
public bool FitsOneFrame(IMessage item) => ItemBytes(item) <= MergeBudget;
/// <summary>A repeated-message item's encoded size inside its batch: tag (1 byte) + length prefix + body.</summary>
private static int ItemBytes(IMessage item)
{
var size = item.CalculateSize();
return 1 + CodedOutputStream.ComputeLengthSize(size) + size;
}
/// <summary>A packed repeated uint64 id: at most 10 bytes; the per-list tag + length is in the headroom.</summary>
private const int IdBytes = 10;
/// <summary>
/// Builds one pass. Consecutive evaluations / results are merged — but, since #999 / review K-5, only up to the
/// frame cap: the merged batch is cut (and a new one started) before an item would push it over. Before, the merge
/// was unbounded and one oversized frame faulted the writer — the worker exited (host side: killed) with every
/// evaluation in flight. A single RESULT too large for any frame is replaced by an <c>UNSUPPORTED_TYPE</c> error for
/// that evaluation alone; an oversized single evaluation REQUEST is refused before it gets here
/// (<see cref="FitsOneFrame"/>), so reaching <see cref="Append"/> with one is still a protocol fault.
/// </summary>
private void FillPass()
{
EvalBatch? evals = null;
EvalResults? results = null;
var mergedBytes = 0;
var budget = MergeBudget;
void FlushEvals()
{
if (evals is null) return;
Append(new Envelope { Eval = evals });
evals = null;
mergedBytes = 0;
}
void FlushResults()
{
if (results is null) return;
Append(new Envelope { Results = results });
results = null;
mergedBytes = 0;
}
while (_queue.TryDequeue(out var envelope))
{
switch (envelope.BodyCase)
{
case Envelope.BodyOneofCase.Eval:
if (results is not null) { Append(new Envelope { Results = results }); results = null; }
(evals ??= new EvalBatch()).Items.AddRange(envelope.Eval.Items);
FlushResults();
foreach (var item in envelope.Eval.Items)
{
var bytes = ItemBytes(item);
if (evals is not null && mergedBytes + bytes > budget) FlushEvals();
(evals ??= new EvalBatch()).Items.Add(item);
mergedBytes += bytes;
}
break;
case Envelope.BodyOneofCase.Results:
if (evals is not null) { Append(new Envelope { Eval = evals }); evals = null; }
results ??= new EvalResults();
results.Items.AddRange(envelope.Results.Items);
results.StartedEvalIds.AddRange(envelope.Results.StartedEvalIds);
results.DeferredEvalIds.AddRange(envelope.Results.DeferredEvalIds);
results.SoftExpiredEvalIds.AddRange(envelope.Results.SoftExpiredEvalIds);
FlushEvals();
var body = envelope.Results;
// Ids first: an evaluation's "started" notice never trails its own result into a later frame.
foreach (var (id, list) in Ids(body))
{
if (results is not null && mergedBytes + IdBytes > budget) FlushResults();
results ??= new EvalResults();
list(results).Add(id);
mergedBytes += IdBytes;
}
foreach (var original in body.Items)
{
var item = original;
var bytes = ItemBytes(item);
if (bytes > budget)
{
item = new EvalResult
{
EvalId = original.EvalId,
AllocatedBytes = original.AllocatedBytes,
RunMicros = original.RunMicros,
Error = new ScriptError
{
Kind = ScriptError.Types.Kind.UnsupportedType,
Message = $"the script's result is {bytes} bytes encoded, over the {MaxFrameBytes}-byte frame cap",
},
};
bytes = ItemBytes(item);
}
if (results is not null && mergedBytes + bytes > budget) FlushResults();
(results ??= new EvalResults()).Items.Add(item);
mergedBytes += bytes;
}
break;
default:
if (evals is not null) { Append(new Envelope { Eval = evals }); evals = null; }
if (results is not null) { Append(new Envelope { Results = results }); results = null; }
FlushEvals();
FlushResults();
Append(envelope);
break;
}
}
if (evals is not null) Append(new Envelope { Eval = evals });
if (results is not null) Append(new Envelope { Results = results });
FlushEvals();
FlushResults();
}
/// <summary>The id lists of <paramref name="body"/>, each with the accessor for the same list on a merged batch.</summary>
private static IEnumerable<(ulong Id, Func<EvalResults, Google.Protobuf.Collections.RepeatedField<ulong>> List)> Ids(EvalResults body)
{
foreach (var id in body.StartedEvalIds) yield return (id, static r => r.StartedEvalIds);
foreach (var id in body.DeferredEvalIds) yield return (id, static r => r.DeferredEvalIds);
foreach (var id in body.SoftExpiredEvalIds) yield return (id, static r => r.SoftExpiredEvalIds);
}
private void Append(Envelope envelope)
@@ -61,6 +61,21 @@ public static class VariantCodec
/// <returns>The boxed value.</returns>
/// <exception cref="ScriptWorkerProtocolException">An unknown tag, or a payload that does not match the tag.</exception>
public static object? Decode(Variant? variant)
{
try
{
return DecodeCore(variant);
}
catch (Exception ex) when (ex is OverflowException or ArgumentOutOfRangeException)
{
// #999 / review K-9: an out-of-range payload (a Byte carrying 300, DatetimeUtc ticks past DateTime.MaxValue)
// is a protocol fault like any other contradictory payload. OutOfProcessScriptRunner.Complete catches only
// ScriptWorkerProtocolException, so these used to fault the run task of a runner documented "never faults".
throw new ScriptWorkerProtocolException($"variant tagged {variant!.Type} is out of range: {ex.Message}", ex);
}
}
private static object? DecodeCore(Variant? variant)
{
if (variant is null) return null;
return variant.Type switch
@@ -112,7 +127,7 @@ public static class VariantCodec
var item = array.Items[i];
if (item.Type != array.ElementType && item.Type != Variant.Types.TypeTag.Null)
throw new ScriptWorkerProtocolException($"array of {array.ElementType} holds a {item.Type} element");
result.SetValue(Decode(item), i);
result.SetValue(DecodeCore(item), i);
}
return result;
}
@@ -301,11 +301,17 @@ public sealed class ScriptRunGuard
{
result = await runTask.WaitAsync(timeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
catch (TimeoutException tex) when (!ScriptTimeouts.IsScriptOwn(runTask, tex))
{
// WaitAsync's synthesized timeout only (#999 / review K-7): a TimeoutException the SCRIPT threw (incl.
// RegexMatchTimeoutException) faulted runTask with that very instance and falls through to the generic
// handler below — it is the script's failure, not a guard timeout, and must never count as a strike.
// The caller's cancel wins even when it lands a few µs after the timeout fired.
if (ct.IsCancellationRequested) throw new OperationCanceledException(ct);
runCts.Cancel();
// The run may have finished in the instant the timeout fired; its continuation then already disposed
// runCts. Cancelling a finished run is moot, so the dispose race must not replace the timeout.
try { runCts.Cancel(); }
catch (ObjectDisposedException) { }
if (NoteTimeout(key, state, timeout))
throw new ScriptQuarantinedException(key, state.QuarantineReason!);
throw new ScriptTimeoutException(timeout);
@@ -461,3 +467,16 @@ public sealed class ScriptQuarantinedException : Exception
Key = key;
}
}
/// <summary>Shared timeout classification for the script run wrappers (#999 / review K-7).</summary>
internal static class ScriptTimeouts
{
/// <summary>
/// True when <paramref name="caught"/> is the exception the script itself threw (it faulted
/// <paramref name="runTask"/>), false when it is <c>Task.WaitAsync</c>'s synthesized timeout. Both are
/// <see cref="TimeoutException"/>s (a script may throw one directly, or hit a <c>Regex</c> match timeout), so the
/// type alone cannot tell a guard timeout from the script's own failure.
/// </summary>
internal static bool IsScriptOwn(Task runTask, Exception caught)
=> runTask.IsFaulted && runTask.Exception!.InnerExceptions.Contains(caught);
}
@@ -82,8 +82,9 @@ public sealed class TimedScriptEvaluator<TContext, TResult>
{
return await runTask.WaitAsync(Timeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
catch (TimeoutException tex) when (!ScriptTimeouts.IsScriptOwn(runTask, tex))
{
// #999 / review K-7: a TimeoutException the script threw itself faulted runTask and propagates unchanged.
// WaitAsync's synthesized timeout — the inner task may still be running
// on its thread-pool thread (known leak documented in the class summary).
// Wrap so callers can distinguish from user-written timeout logic.
@@ -101,13 +101,22 @@ public static class DriverResilienceOptionsParser
{
foreach (var (capName, overridePolicy) in shape.CapabilityPolicies)
{
if (!Enum.TryParse<DriverCapability>(capName, ignoreCase: true, out var capability))
// #999 / review K-8: Enum.TryParse accepts any NUMERIC string ("42", "-1"), so a name is a capability
// only when it is also a defined member with a base policy; and valid JSON can carry a null policy.
// Both used to throw (KeyNotFound / NullReference) out of the parser and the driver spawn.
if (!Enum.TryParse<DriverCapability>(capName, ignoreCase: true, out var capability)
|| !Enum.IsDefined(capability)
|| !merged.TryGetValue(capability, out var basePolicy))
{
AppendDiagnostic(ref parseDiagnostic, $"Unknown capability '{capName}' in ResilienceConfig; skipped.");
continue;
}
if (overridePolicy is null)
{
AppendDiagnostic(ref parseDiagnostic, $"Capability '{capName}' in ResilienceConfig has a null policy; skipped.");
continue;
}
var basePolicy = merged[capability];
var mergedPolicy = new CapabilityPolicy(
TimeoutSeconds: overridePolicy.TimeoutSeconds ?? basePolicy.TimeoutSeconds,
RetryCount: overridePolicy.RetryCount ?? basePolicy.RetryCount,
@@ -17,6 +17,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Resilience;
/// Per-device isolation. Composition from outside-in:
/// <b>Timeout → Retry (when capability permits) → Circuit Breaker (when tier permits)</b>.
///
/// <para><b>The pipeline's own timeout is a failure (#999 / review K-6).</b> The timeout is the call's TOTAL
/// budget, so it is not retried, but the breaker counts the cancelled attempt as a failure (unless the caller
/// cancelled — told apart by the caller token an outermost pass-through records) and <c>OnTimeout</c> records a
/// tracker failure. Before, both predicates excluded every <see cref="OperationCanceledException"/>: a hung
/// device burned the full timeout on every call forever with the breaker closed and no failure on <c>/hosts</c>.</para>
///
/// <para>Pipeline resolution is lock-free on the hot path: the inner
/// <see cref="ConcurrentDictionary{TKey,TValue}"/> caches a <see cref="ResiliencePipeline"/> per key;
/// first-call cost is one <see cref="ResiliencePipelineBuilder"/>.Build. Thereafter reads are O(1).</para>
@@ -135,10 +141,29 @@ public sealed class DriverResiliencePipelineBuilder
// builder invariant. Three integer ops once per pipeline build (not per call).
var timeoutSeconds = Math.Clamp(
policy.TimeoutSeconds, ResiliencePolicyRanges.MinTimeoutSeconds, ResiliencePolicyRanges.MaxTimeoutSeconds);
builder.AddTimeout(new TimeoutStrategyOptions
// #999 / review K-6: outermost, BEFORE the timeout links its own token in — record the caller's token so the
// inner predicates can tell the pipeline's own timeout (a failure) from a cancellation the caller asked for.
builder.AddStrategy(static _ => CallerTokenStrategy.Instance, CallerTokenStrategyOptions.Instance);
var timeoutOptions = new TimeoutStrategyOptions
{
Timeout = TimeSpan.FromSeconds(timeoutSeconds),
});
};
if (tracker is not null || logger is not null)
{
// The total budget ran out: a failure of the target, like a retried exception (K-6). Without this a
// hung device read ConsecutiveFailures = 0 on /hosts forever.
timeoutOptions.OnTimeout = args =>
{
tracker?.RecordFailure(driverInstanceId, hostName, timeProvider.GetUtcNow().UtcDateTime);
logger?.LogWarning(
"Driver resilience timeout: instance={DriverInstanceId} host={HostName} capability={Capability} timeout={Timeout}",
driverInstanceId, hostName, capability, args.Timeout);
return default;
};
}
builder.AddTimeout(timeoutOptions);
if (policy.RetryCount > 0)
{
@@ -149,6 +174,8 @@ public sealed class DriverResiliencePipelineBuilder
UseJitter = true,
Delay = TimeSpan.FromMilliseconds(100),
MaxDelay = TimeSpan.FromSeconds(5),
// A pipeline timeout is NOT retried: it is the TOTAL budget (the timeout is outermost), so nothing is
// left to retry with. It is still a breaker failure (below) and a tracker failure (OnTimeout).
ShouldHandle = new PredicateBuilder().Handle<Exception>(ex => ex is not OperationCanceledException and not DriverOperationRefusedException),
};
if (tracker is not null || logger is not null)
@@ -173,7 +200,16 @@ public sealed class DriverResiliencePipelineBuilder
MinimumThroughput = Math.Max(ResiliencePolicyRanges.MinEnabledBreakerFailureThreshold, policy.BreakerFailureThreshold),
SamplingDuration = TimeSpan.FromSeconds(30),
BreakDuration = TimeSpan.FromSeconds(15),
ShouldHandle = new PredicateBuilder().Handle<Exception>(ex => ex is not OperationCanceledException and not DriverOperationRefusedException),
// #999 / review K-6: the pipeline's own timeout cancels the attempt, so the breaker sees an
// OperationCanceledException — a failure of the target unless the CALLER cancelled. Excluding every
// OCE meant a hung device never opened the breaker. A refusal stays a non-failure.
ShouldHandle = args => new ValueTask<bool>(args.Outcome.Exception switch
{
null => false,
DriverOperationRefusedException => false,
OperationCanceledException => IsPipelineTimeout(args.Context),
_ => true,
}),
};
if (tracker is not null || logger is not null)
{
@@ -205,5 +241,35 @@ public sealed class DriverResiliencePipelineBuilder
return builder.Build();
}
/// <summary>The caller's token, recorded by <see cref="CallerTokenStrategy"/> before the timeout links its own.</summary>
private static readonly ResiliencePropertyKey<CancellationToken> CallerTokenKey = new("otopcua.caller-token");
/// <summary>
/// True when an attempt's cancellation came from the pipeline's own timeout (the attempt token is cancelled but
/// the caller's is not). Unknown caller token ⇒ false, the pre-#999 behaviour.
/// </summary>
private static bool IsPipelineTimeout(ResilienceContext context)
=> context.CancellationToken.IsCancellationRequested
&& context.Properties.TryGetValue(CallerTokenKey, out var caller)
&& !caller.IsCancellationRequested;
/// <summary>Outermost pass-through that records the caller's cancellation token on the context (#999 / K-6).</summary>
private sealed class CallerTokenStrategy : ResilienceStrategy
{
public static readonly CallerTokenStrategy Instance = new();
protected override ValueTask<Outcome<TResult>> ExecuteCore<TResult, TState>(
Func<ResilienceContext, TState, ValueTask<Outcome<TResult>>> callback, ResilienceContext context, TState state)
{
context.Properties.Set(CallerTokenKey, context.CancellationToken);
return callback(context, state);
}
}
private sealed class CallerTokenStrategyOptions : ResilienceStrategyOptions
{
public static readonly CallerTokenStrategyOptions Instance = new() { Name = "CallerToken" };
}
private readonly record struct PipelineKey(string DriverInstanceId, string HostName, DriverCapability Capability, long Generation);
}
@@ -4665,6 +4665,33 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
StartAcquisitionDemand(ready.DriverInstanceId, desired, ActorRefs.Nobody);
}
/// <summary>
/// #999 / review K-8: the resilience invoker for a spawn, never throwing. A factory throw (a wrong-shaped
/// <c>ResilienceConfig</c> from a restored database, a manual SQL edit or an older build) used to escape
/// <see cref="SpawnChild"/> and the handler hosting every driver on the node — and the same artifact was re-applied
/// afterwards. Like a driver-factory throw it is a CONFIG error: logged at Error, and the driver runs on its tier
/// defaults (no per-instance overrides); only if that throws too does it run with the pass-through invoker.
/// </summary>
private IDriverCapabilityInvoker CreateInvoker(DriverInstanceSpec spec)
{
try { return _invokerFactory.Create(spec.DriverInstanceId, spec.DriverType, spec.ResilienceConfig); }
catch (Exception ex)
{
_log.Error(ex,
"DriverHost {Node}: the ResilienceConfig of {Id} ({Type}) could not be applied — the driver runs on its " +
"tier-default resilience policy until the config is fixed and redeployed",
_localNode, spec.DriverInstanceId, spec.DriverType);
}
try { return _invokerFactory.Create(spec.DriverInstanceId, spec.DriverType, null); }
catch (Exception ex)
{
_log.Error(ex,
"DriverHost {Node}: no resilience invoker could be built for {Id} ({Type}) — its capability calls run " +
"WITHOUT retry/timeout/breaker", _localNode, spec.DriverInstanceId, spec.DriverType);
return NullDriverCapabilityInvoker.Instance;
}
}
private void SpawnChild(DriverInstanceSpec spec, bool deferSubscriptions = false)
{
// An instance id removed by an earlier deployment (StopChild ⇒ Evict, which also holds back late
@@ -4734,7 +4761,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// route through the retry/breaker/telemetry pipeline. The tier defaults are layered
// with the per-instance ResilienceConfig from the artifact; the pass-through factory yields a
// no-op invoker on nodes without the real resilience factory bound.
var invoker = _invokerFactory.Create(spec.DriverInstanceId, spec.DriverType, spec.ResilienceConfig);
var invoker = CreateInvoker(spec);
child = Context.ActorOf(
_dataWriteRuntime is null ? DriverInstanceActor.Props(
driver!,
@@ -574,7 +574,9 @@ internal sealed class WorkerHost
using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(100));
while (await timer.WaitForNextTickAsync())
{
if (_logSink.Drain() is { } batch) Send(new Envelope { Logs = batch });
// #999 / review K-5: cut by BYTES as well as lines — one batch of every buffered line (≤ 1,000 × ~24 KB)
// used to exceed the frame cap, fault the writer and exit the worker.
foreach (var batch in _logSink.Drain(Math.Max(1, _maxFrameBytes - 1024))) Send(new Envelope { Logs = batch });
}
}
@@ -816,17 +818,39 @@ internal sealed class WorkerHost
});
}
public LogBatch? Drain()
/// <summary>
/// Drains every buffered line into batches of at most <paramref name="maxBatchBytes"/> encoded bytes each
/// (#999 / review K-5). A line too large for any batch on its own is counted as dropped.
/// </summary>
public List<LogBatch> Drain(int maxBatchBytes)
{
var batches = new List<LogBatch>();
var dropped = Interlocked.Exchange(ref _dropped, 0);
if (_lines.IsEmpty && dropped == 0) return null;
var batch = new LogBatch { Dropped = (uint)dropped };
if (_lines.IsEmpty && dropped == 0) return batches;
var batch = new LogBatch();
var bytes = 0;
while (_lines.TryDequeue(out var line))
{
Interlocked.Decrement(ref _count);
var size = line.CalculateSize();
var lineBytes = 1 + Google.Protobuf.CodedOutputStream.ComputeLengthSize(size) + size;
if (lineBytes > maxBatchBytes - 16)
{
dropped++;
continue;
}
if (bytes + lineBytes > maxBatchBytes - 16)
{
batches.Add(batch);
batch = new LogBatch();
bytes = 0;
}
batch.Lines.Add(line);
bytes += lineBytes;
}
return batch;
batch.Dropped = (uint)dropped;
batches.Add(batch);
return batches;
}
private static string Truncate(string value, int max) => value.Length <= max ? value : value[..max];
@@ -514,4 +514,48 @@ public sealed class GrpcDataCodecTests
DataProtoMapper.DecodeBrowseResponse(response, new DataDecodeLimits(1, 10000, 100))
);
}
/// <summary>
/// #999 / review K-9: a malformed wire value fails as the codec's documented <see cref="ArgumentException"/> (the
/// gRPC service maps it to <c>InvalidArgument</c>) — never an <see cref="OverflowException"/> /
/// <see cref="FormatException"/> (unmapped: an internal error) or an <see cref="InvalidOperationException"/>
/// (mapped to <c>Unavailable</c>: the client retries or fails over a request that can never succeed).
/// </summary>
[Theory]
[MemberData(nameof(MalformedValues))]
public void Malformed_wire_values_fail_as_ArgumentException(string _, Protos.DataConnection.V1.TypedValue wire)
{
var ex = Should.Throw<Exception>(() => TypedValueCodec.Decode(wire));
ex.ShouldBeAssignableTo<ArgumentException>($"{ex.GetType().Name}: {ex.Message}");
}
/// <summary>K-9: an out-of-range protobuf timestamp is an ArgumentException at the shared timestamp decoder too.</summary>
[Fact]
public void Out_of_range_timestamps_fail_as_ArgumentException()
{
var ex = Should.Throw<Exception>(() => TypedValueCodec.DecodeTimestamp(new Google.Protobuf.WellKnownTypes.Timestamp { Seconds = long.MaxValue }));
ex.ShouldBeAssignableTo<ArgumentException>($"{ex.GetType().Name}: {ex.Message}");
}
public static TheoryData<string, Protos.DataConnection.V1.TypedValue> MalformedValues()
{
var data = new TheoryData<string, Protos.DataConnection.V1.TypedValue>
{
{ "Int8 300", new() { Kind = (Protos.DataConnection.V1.ValueKind)(int)DataValueKind.Int8, Signed = 300 } },
{ "UInt8 300", new() { Kind = (Protos.DataConnection.V1.ValueKind)(int)DataValueKind.UInt8, Unsigned = 300 } },
{ "Int32 overflow", new() { Kind = (Protos.DataConnection.V1.ValueKind)(int)DataValueKind.Int32, Signed = long.MaxValue } },
{ "bad guid", new() { Kind = (Protos.DataConnection.V1.ValueKind)(int)DataValueKind.Guid, Guid = "not-a-guid" } },
{ "timestamp out of range", new() { Kind = (Protos.DataConnection.V1.ValueKind)(int)DataValueKind.Timestamp, Timestamp = new Google.Protobuf.WellKnownTypes.Timestamp { Seconds = long.MaxValue } } },
{ "timestamp bad nanos", new() { Kind = (Protos.DataConnection.V1.ValueKind)(int)DataValueKind.Timestamp, Timestamp = new Google.Protobuf.WellKnownTypes.Timestamp { Seconds = 0, Nanos = -100 } } },
};
var array = new Protos.DataConnection.V1.TypedValue
{
Kind = (Protos.DataConnection.V1.ValueKind)(int)DataValueKind.Array,
Array = new Protos.DataConnection.V1.TypedArray { ElementKind = (Protos.DataConnection.V1.ValueKind)(int)DataValueKind.Int16 },
};
array.Array.Dimensions.Add(1);
array.Array.Elements.Add(new Protos.DataConnection.V1.TypedValue { Kind = (Protos.DataConnection.V1.ValueKind)(int)DataValueKind.Int16, Signed = 1 << 20 });
data.Add("array element overflow", array);
return data;
}
}
@@ -42,6 +42,18 @@ public sealed class ConnectionBackoffTests
public void ComputeDelay_SaturatesAtCap(int failures)
=> ConnectionBackoff.ComputeDelay(Base, failures, Cap).ShouldBe(Cap);
/// <summary>
/// #999 / review K-10: a cap BELOW the base interval never shortens it. The cap used to be an absolute ceiling, so
/// a 60 s subscription behind every poll driver's 30 s cap was polled every 30 s once it started failing — faster
/// than when it was healthy.
/// </summary>
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(1000)]
public void ComputeDelay_CapBelowBase_NeverUndercutsTheBase(int failures)
=> ConnectionBackoff.ComputeDelay(TimeSpan.FromSeconds(60), failures, Cap).ShouldBe(TimeSpan.FromSeconds(60));
/// <summary>A fresh throttle permits the first attempt immediately.</summary>
[Fact]
public void ShouldAttempt_FreshInstance_AllowsImmediately()
@@ -494,6 +494,38 @@ public sealed class PollGroupEngineTests
readCount.ShouldBeLessThan(18);
}
/// <summary>
/// #999 / review K-10: with the backoff cap BELOW the subscription interval, a failing reader is polled no faster
/// than a healthy one — every gap between attempts is at least the interval. Before the fix the cap was an
/// absolute ceiling and the gap was the 50 ms cap.
/// </summary>
[Fact]
public async Task Backoff_CapBelowInterval_NeverPollsAFailingDeviceFasterThanTheInterval()
{
var stamps = new ConcurrentQueue<long>();
Task<IReadOnlyList<DataValueSnapshot>> Reader(IReadOnlyList<string> refs, CancellationToken ct)
{
stamps.Enqueue(System.Diagnostics.Stopwatch.GetTimestamp());
throw new InvalidOperationException("dead device");
}
await using var engine = new PollGroupEngine(
Reader,
(_, _, _) => { },
minInterval: TimeSpan.FromMilliseconds(20),
onError: _ => { },
backoffCap: TimeSpan.FromMilliseconds(50));
var handle = engine.Subscribe(["X"], TimeSpan.FromMilliseconds(200));
await WaitForAsync(() => stamps.Count >= 4, TimeSpan.FromSeconds(5));
engine.Unsubscribe(handle);
var t = stamps.ToArray();
for (var i = 1; i < 4; i++)
System.Diagnostics.Stopwatch.GetElapsedTime(t[i - 1], t[i]).ShouldBeGreaterThanOrEqualTo(
TimeSpan.FromMilliseconds(190), $"gap {i}");
}
/// <summary>A successful poll resets the failure count so the cadence snaps back to the base interval.</summary>
[Fact]
public async Task Backoff_SuccessResetsToInterval()
@@ -174,6 +174,18 @@ public sealed class Part9StateMachineTests
after.State.Comments.Any(c => c.Kind == "AutoUnshelve").ShouldBeTrue();
}
/// <summary>#999 / K-4: ApplyPredicate never expires a timed shelve itself — that would unshelve silently.</summary>
[Fact]
public void ApplyPredicate_does_not_expire_a_timed_shelve()
{
var active = Part9StateMachine.ApplyPredicate(Fresh(), true, T0.AddSeconds(1)).State;
var shelved = Part9StateMachine.ApplyTimedShelve(active, "alice", T0.AddMinutes(5), T0.AddSeconds(2)).State;
var r = Part9StateMachine.ApplyPredicate(shelved, true, T0.AddMinutes(6));
r.State.Shelving.Kind.ShouldBe(ShelvingKind.Timed, "expiry is ApplyShelvingCheck's alone");
r.Emission.ShouldBe(EmissionKind.None);
}
/// <summary>Verifies that unshelving an unshelved alarm is a no-op.</summary>
[Fact]
public void Unshelve_from_unshelved_is_noop()
@@ -0,0 +1,115 @@
using Serilog;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests;
/// <summary>
/// #999 / review K-4 — a timed shelve whose deadline passes is unshelved by a predicate evaluation that
/// arrives before the 5 s shelving timer. It must be the shelving check that expires it, so the evaluation emits
/// exactly one <see cref="EmissionKind.Unshelved"/> and records exactly one <c>AutoUnshelve</c> audit comment
/// (before the fix <c>ApplyPredicate</c> unshelved it silently: no event, no audit, the OPC UA node stayed
/// TimedShelved). Covered on both the in-process path and the <see cref="IScriptRunner"/> batch path.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ScriptedAlarmEngineTimedShelveExpiryTests
{
private sealed class ThresholdRunner : IScriptRunner
{
private static ScriptRunOutcome Answer(ScriptInvocation i) => ScriptRunOutcome.Ok((int)i.Inputs["Temp"].Value! > 100);
public Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
=> Task.FromResult(Answer(invocation));
public IReadOnlyList<Task<ScriptRunOutcome>> RunBatch(IReadOnlyList<ScriptInvocation> invocations, CancellationToken ct = default)
=> invocations.Select(i => Task.FromResult(Answer(i))).ToArray();
public void Reset(ScriptContextKind kind) { }
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => [];
}
private static async Task WaitFor(Func<bool> probe, string what)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (DateTime.UtcNow < deadline)
{
if (probe()) return;
await Task.Delay(10);
}
throw new TimeoutException(what);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task A_predicate_evaluation_after_the_deadline_emits_Unshelved_and_audits_AutoUnshelve(bool outOfProcess)
{
var ct = TestContext.Current.CancellationToken;
var now = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);
var up = new FakeUpstream();
up.Set("Temp", 150);
var logger = new LoggerConfiguration().CreateLogger();
using var eng = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger,
clock: () => now, scriptRunner: outOfProcess ? new ThresholdRunner() : null);
await eng.LoadAsync(
[new ScriptedAlarmDefinition("HighTemp", "Plant/Line1/Reactor", "HighTemp", AlarmKind.AlarmCondition,
AlarmSeverity.High, "condition", """return (int)ctx.GetTag("Temp").Value > 100;""")],
ct);
eng.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Active);
await eng.TimedShelveAsync("HighTemp", "alice", now.AddMinutes(10), ct);
var events = new List<ScriptedAlarmEvent>();
eng.OnEvent += (_, e) => { lock (events) events.Add(e); };
// Past the deadline; the input moves but the predicate stays true, so the only possible transition is the
// expiry. The shelving check is NOT run — the evaluation alone has to surface it.
now = now.AddMinutes(11);
up.Push("Temp", 160);
await WaitFor(() => { lock (events) return events.Any(e => e.Emission == EmissionKind.Unshelved); },
"the evaluation that crossed the deadline emitted Unshelved");
var state = eng.GetState("HighTemp")!;
state.Shelving.Kind.ShouldBe(ShelvingKind.Unshelved);
state.Active.ShouldBe(AlarmActiveState.Active);
state.Comments.Count(c => c.Kind == "AutoUnshelve").ShouldBe(1);
// The shelving timer, running afterwards, finds nothing left to expire: still exactly one event.
eng.RunShelvingCheckForTest();
await WaitFor(() => eng.InFlightCountForTest == 0, "shelving check finished");
// Positive control: a later clear does arrive, so an absent second Unshelved is not just "not processed yet".
up.Push("Temp", 50);
await WaitFor(() => { lock (events) return events.Any(e => e.Emission == EmissionKind.Cleared); }, "clear arrives");
lock (events) events.Count(e => e.Emission == EmissionKind.Unshelved).ShouldBe(1);
eng.GetState("HighTemp")!.Comments.Count(c => c.Kind == "AutoUnshelve").ShouldBe(1);
}
[Fact]
public async Task An_activation_that_crosses_the_deadline_emits_Unshelved_then_Activated()
{
var ct = TestContext.Current.CancellationToken;
var now = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);
var up = new FakeUpstream();
up.Set("Temp", 50);
var logger = new LoggerConfiguration().CreateLogger();
using var eng = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger,
clock: () => now);
await eng.LoadAsync(
[new ScriptedAlarmDefinition("HighTemp", "Plant/Line1/Reactor", "HighTemp", AlarmKind.AlarmCondition,
AlarmSeverity.High, "condition", """return (int)ctx.GetTag("Temp").Value > 100;""")],
ct);
await eng.TimedShelveAsync("HighTemp", "alice", now.AddMinutes(10), ct);
var events = new List<ScriptedAlarmEvent>();
eng.OnEvent += (_, e) => { lock (events) events.Add(e); };
now = now.AddMinutes(11);
up.Push("Temp", 150);
await WaitFor(() => { lock (events) return events.Any(e => e.Emission == EmissionKind.Activated); },
"activation after expiry is not suppressed");
lock (events)
events.Select(e => e.Emission).ShouldBe([EmissionKind.Unshelved, EmissionKind.Activated]);
}
}
@@ -541,6 +541,33 @@ public sealed class ScriptRunGuardTests
guard.QuarantinedCount.ShouldBe(1);
}
/// <summary>
/// #999 / review K-7: a <see cref="TimeoutException"/> the SCRIPT threw (directly, or a
/// <c>RegexMatchTimeoutException</c>) is the script's own failure — it propagates unchanged, is not a guard
/// timeout, and never quarantines. Before the fix the guard's <c>catch (TimeoutException)</c> took it for
/// <c>WaitAsync</c>'s timeout and called <c>Cancel()</c> on the already-disposed run CTS, surfacing
/// <see cref="ObjectDisposedException"/>.
/// </summary>
[Theory]
[InlineData("throw new System.TimeoutException(\"mine\");", typeof(TimeoutException))]
[InlineData(
"return System.Text.RegularExpressions.Regex.IsMatch(new string('a', 40000) + \"!\", \"^(a+)+$\", System.Text.RegularExpressions.RegexOptions.None, System.TimeSpan.FromMilliseconds(20)) ? 1 : 0;",
typeof(System.Text.RegularExpressions.RegexMatchTimeoutException))]
public async Task A_script_thrown_TimeoutException_propagates_and_is_not_a_guard_timeout(string source, Type expected)
{
var guard = new ScriptRunGuard(new ScriptingOptions { QuarantineAfterConsecutiveTimeouts = 2 });
using var evaluator = Compile(source);
for (var i = 0; i < 4; i++)
{
var ex = await Should.ThrowAsync<Exception>(() =>
Run(guard, "own-timeout", source, evaluator, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken));
ex.GetType().ShouldBe(expected, $"run {i}: {ex}");
}
guard.IsQuarantined("own-timeout", out _).ShouldBeFalse("a script's own exception is not a timeout strike");
guard.QuarantinedCount.ShouldBe(0);
}
/// <summary>Releases the held script (signal), waits for the orphan to drain, and re-arms the gate for the next attempt.</summary>
private static async Task ReleaseAndDrain(ScriptRunGuard guard, FakeScriptContext held)
{
@@ -47,6 +47,18 @@ public sealed class TimedScriptEvaluatorTests
result.ShouldBe(42.0);
}
/// <summary>#999 / review K-7: a TimeoutException the script threw itself is not the wrapper's timeout.</summary>
[Fact]
public async Task A_script_thrown_TimeoutException_is_not_reported_as_a_script_timeout()
{
var inner = ScriptEvaluator<FakeScriptContext, double>.Compile("""throw new System.TimeoutException("mine");""");
var timed = new TimedScriptEvaluator<FakeScriptContext, double>(inner, TimeSpan.FromSeconds(5));
var ex = await Should.ThrowAsync<Exception>(() => timed.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken));
ex.GetType().ShouldBe(typeof(TimeoutException));
ex.Message.ShouldBe("mine");
}
/// <summary>Verifies that scripts longer than timeout throw ScriptTimeoutException.</summary>
[Fact]
public async Task Script_longer_than_timeout_throws_ScriptTimeoutException()
@@ -516,6 +516,79 @@ public sealed class DriverResiliencePipelineBuilderTests
attempts.ShouldBe(1, "the new generation must honor optsB (retryCount 0), not the stale optsA re-cache");
}
/// <summary>
/// #999 / review K-6: the pipeline's OWN timeout is a failure the breaker and the status tracker see. Before
/// the fix the hung attempt surfaced inside the pipeline as an <see cref="OperationCanceledException"/>, which
/// both predicates excluded: every call burned the full timeout forever, the breaker never opened and
/// <c>/hosts</c> showed <c>ConsecutiveFailures = 0</c> for a dead device.
/// </summary>
[Fact]
public async Task Pipeline_timeouts_open_the_breaker_and_reach_the_tracker()
{
var tracker = new DriverResilienceStatusTracker();
var builder = new DriverResiliencePipelineBuilder(statusTracker: tracker);
var options = new DriverResilienceOptions
{
Tier = DriverTier.A,
CapabilityPolicies = new Dictionary<DriverCapability, CapabilityPolicy>
{
[DriverCapability.Read] = new(TimeoutSeconds: 1, RetryCount: 3, BreakerFailureThreshold: 2),
},
};
var pipeline = builder.GetOrCreate("drv-hang", "host-h", DriverCapability.Read, options);
var attempts = 0;
async ValueTask Hang(CancellationToken t)
{
Interlocked.Increment(ref attempts);
await Task.Delay(Timeout.Infinite, t); // honours the token, like a blackholed socket read
}
for (var i = 0; i < 2; i++)
{
await Should.ThrowAsync<TimeoutRejectedException>(async () =>
await pipeline.ExecuteAsync(Hang, TestContext.Current.CancellationToken));
tracker.TryGet("drv-hang", "host-h")!.ConsecutiveFailures.ShouldBe(i + 1, "each timeout is a failure");
}
await Should.ThrowAsync<BrokenCircuitException>(async () =>
await pipeline.ExecuteAsync(Hang, TestContext.Current.CancellationToken));
attempts.ShouldBe(2, "the open breaker short-circuits the third call");
tracker.TryGet("drv-hang", "host-h")!.IsBreakerOpen.ShouldBeTrue();
}
/// <summary>
/// #999 / K-6 control: a cancellation the CALLER asked for is still not a failure — it neither counts toward the
/// breaker nor reaches the tracker. Positive control: after more caller cancels than the threshold, the next call
/// still reaches the call site.
/// </summary>
[Fact]
public async Task Caller_cancellation_is_not_a_failure()
{
var tracker = new DriverResilienceStatusTracker();
var builder = new DriverResiliencePipelineBuilder(statusTracker: tracker);
var options = new DriverResilienceOptions
{
Tier = DriverTier.A,
CapabilityPolicies = new Dictionary<DriverCapability, CapabilityPolicy>
{
[DriverCapability.Read] = new(TimeoutSeconds: 30, RetryCount: 3, BreakerFailureThreshold: 2),
},
};
var pipeline = builder.GetOrCreate("drv-cxl", "host-c", DriverCapability.Read, options);
for (var i = 0; i < 4; i++)
{
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(20));
await Should.ThrowAsync<OperationCanceledException>(async () =>
await pipeline.ExecuteAsync(async t => await Task.Delay(Timeout.Infinite, t), cts.Token));
}
var reached = false;
await pipeline.ExecuteAsync(_ => { reached = true; return ValueTask.CompletedTask; }, TestContext.Current.CancellationToken);
reached.ShouldBeTrue("the breaker stayed closed");
(tracker.TryGet("drv-cxl", "host-c")?.ConsecutiveFailures ?? 0).ShouldBe(0);
}
/// <summary>
/// A controllable <see cref="TimeProvider"/> whose clock advances only on <see cref="Advance"/>.
/// Drives both wall-clock (<see cref="GetUtcNow"/>) and monotonic (<see cref="GetTimestamp"/>)
@@ -45,4 +45,33 @@ public sealed class ResilienceConfigBrickTests
var result = await pipeline.ExecuteAsync(_ => ValueTask.FromResult(42), CancellationToken.None);
result.ShouldBe(42);
}
/// <summary>
/// #999 / review K-8: valid JSON of the wrong SHAPE must fall back like malformed JSON does. A numeric capability
/// name passes <c>Enum.TryParse</c> (→ <c>KeyNotFoundException</c>) and a null policy dereferenced null
/// (<c>NullReferenceException</c>) — both escaped <c>ParseOrDefaults</c> and, through the invoker factory, the
/// driver host's spawn.
/// </summary>
[Theory]
[InlineData("{\"capabilityPolicies\":{\"42\":{\"timeoutSeconds\":3}}}")]
[InlineData("{\"capabilityPolicies\":{\"-1\":{\"timeoutSeconds\":3}}}")]
[InlineData("{\"capabilityPolicies\":{\"Read\":null}}")]
public void WrongShapedConfig_FallsBackToTierDefaults_WithADiagnostic(string json)
{
var options = DriverResilienceOptionsParser.ParseOrDefaults(DriverTier.A, json, out var diagnostic);
options.Resolve(DriverCapability.Read).ShouldBe(DriverResilienceOptions.GetTierDefaults(DriverTier.A)[DriverCapability.Read]);
diagnostic.ShouldNotBeNullOrWhiteSpace();
}
/// <summary>K-8 positive control: a well-formed override next to a wrong-shaped entry still applies.</summary>
[Fact]
public void WrongShapedEntry_DoesNotDiscardTheWellFormedOnes()
{
var options = DriverResilienceOptionsParser.ParseOrDefaults(
DriverTier.A, "{\"capabilityPolicies\":{\"42\":{\"timeoutSeconds\":3},\"Read\":{\"timeoutSeconds\":7}}}", out var diagnostic);
options.Resolve(DriverCapability.Read).TimeoutSeconds.ShouldBe(7);
diagnostic!.ShouldContain("42");
}
}
@@ -333,6 +333,46 @@ public sealed class DriverHostActorUnreadableArtifactTests : RuntimeActorTestBas
tracker.TryGet("drv-1", "dev1").ShouldNotBeNull().IsBreakerOpen.ShouldBeTrue();
}
/// <summary>
/// #999 / review K-8 — an invoker factory that throws (a wrong-shaped <c>ResilienceConfig</c> reached it) must
/// not escape <c>SpawnChild</c>: that took down the handler hosting every driver on the node, and the same
/// artifact was re-applied afterwards. The host falls back to the tier defaults and the driver still runs
/// (positive control: it subscribes to its tag), as a driver-factory throw already degrades to a stub.
/// </summary>
[Fact]
public void A_throwing_invoker_factory_falls_back_and_the_driver_still_runs()
{
var db = NewInMemoryDbFactory();
var factory = new SubscribingDriverFactory("Modbus");
var invokerFactory = new ThrowOnceInvokerFactory();
var coordinator = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
driverFactory: factory,
localRoles: new HashSet<string> { "driver" },
invokerFactory: invokerFactory));
actor.Tell(new DispatchDeployment(SeedV3Deployment(db, RevA), RevA, CorrelationId.NewId()));
coordinator.ExpectMsg<ApplyAck>(Timeout, cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
AwaitAssert(() => factory.LastSubscribedRefs.ShouldNotBeNull()!.ShouldContain(SpeedRef),
duration: Timeout, cancellationToken: TestContext.Current.CancellationToken);
invokerFactory.Calls.ShouldBe(2, "the throw was followed by one tier-default retry");
invokerFactory.LastConfig.ShouldBeNull("the fallback drops the per-instance ResilienceConfig");
}
private sealed class ThrowOnceInvokerFactory : IDriverCapabilityInvokerFactory
{
public int Calls;
public string? LastConfig = "unset";
public IDriverCapabilityInvoker Create(string driverInstanceId, string driverType, string? resilienceConfigJson = null)
{
LastConfig = resilienceConfigJson;
if (Interlocked.Increment(ref Calls) == 1) throw new KeyNotFoundException("The given key '42' was not present in the dictionary.");
return NullDriverCapabilityInvoker.Instance;
}
}
private static void PublisherTick(
ZB.MOM.WW.OtOpcUa.Core.Resilience.DriverResilienceStatusTracker t,
ZB.MOM.WW.OtOpcUa.Runtime.Telemetry.TelemetryLocalHub h)
@@ -360,6 +360,52 @@ public sealed class ContainmentTests
await Scripts.Eventually(() => sink.Rendered.Contains("hello 42"), TimeSpan.FromSeconds(5), "the forwarded log line");
}
/// <summary>
/// #999 / review K-5: a script that logs megabytes inside one drain window no longer kills its worker. The worker's
/// log drain put every buffered line (≤ 1,000 × ~24 KB) into ONE LogBatch over the 4 MiB frame cap; the writer
/// faulted and the worker exited — every in-flight evaluation on the shard went BadResourceUnavailable. Now the
/// drain is cut by bytes; the worker survives (same pid) and keeps evaluating.
/// </summary>
[Fact]
public async Task A_script_logging_megabytes_at_once_does_not_kill_its_worker()
{
var sink = new CapturingSink();
await using var runner = Scripts.Runner(Scripts.Options());
(await runner.RunAsync(Scripts.Vt("warm", "return 1;"), Ct)).Value.ShouldBe(1);
var worker = runner.Shards[0].Current.ShouldNotBeNull();
var flood = await runner.RunAsync(Scripts.Vt("flood",
"var s = new string('x', 8000); for (var i = 0; i < 2000; i++) ctx.Logger.Information(s); return 2;",
timeout: TimeSpan.FromSeconds(20), logger: sink.CreateLogger()), Ct);
flood.Status.ShouldBe(ScriptRunStatus.Ok, flood.Reason);
flood.Value.ShouldBe(2);
await Scripts.Eventually(() => sink.Events.Count >= 100 ? sink : null, TimeSpan.FromSeconds(10), "the forwarded lines");
// Positive control: the same worker answers the next evaluation.
(await runner.RunAsync(Scripts.Vt("after", "return 3;"), Ct)).Value.ShouldBe(3);
runner.Shards[0].Current.ShouldNotBeNull().Pid.ShouldBe(worker.Pid, "the worker was not restarted");
}
/// <summary>
/// K-5 host side: an evaluation whose inputs alone exceed the frame cap fails THAT evaluation (unsupported type),
/// instead of faulting the pipe writer and killing the worker with every other evaluation in flight on it.
/// </summary>
[Fact]
public async Task An_evaluation_whose_inputs_exceed_the_frame_cap_fails_alone()
{
await using var runner = Scripts.Runner(Scripts.Options());
(await runner.RunAsync(Scripts.Vt("warm", "return 1;"), Ct)).Value.ShouldBe(1);
var worker = runner.Shards[0].Current.ShouldNotBeNull();
var big = await runner.RunAsync(Scripts.Vt("big", "return ((string)ctx.GetTag(\"t\").Value).Length;",
inputs: Scripts.Input("t", new string('z', 5 * 1024 * 1024))), Ct);
big.Status.ShouldBe(ScriptRunStatus.Failed);
big.Reason!.ShouldContain("frame cap");
(await runner.RunAsync(Scripts.Vt("after", "return 3;"), Ct)).Value.ShouldBe(3);
runner.Shards[0].Current.ShouldNotBeNull().Pid.ShouldBe(worker.Pid, "the worker was not restarted");
}
[Fact]
public async Task An_alarm_predicate_runs_out_of_process()
{
@@ -76,7 +76,15 @@ public sealed class ProtocolTests
{
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Int16, S = "x" }));
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(new Variant { Type = (Variant.Types.TypeTag)99 }));
Should.Throw<OverflowException>(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Int16, I = 1 << 20 }));
// #999 / review K-9: out-of-range payloads are the codec's documented failure too, never an OverflowException /
// ArgumentOutOfRangeException that escapes OutOfProcessScriptRunner.Complete (which catches only this type).
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Int16, I = 1 << 20 }));
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Byte, U = 300 }));
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.DatetimeUtc, DtTicks = long.MaxValue }));
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.DatetimeUtc, DtTicks = -1 }));
var array = new Variant { Type = Variant.Types.TypeTag.Array, Array = new ArrayValue { ElementType = Variant.Types.TypeTag.Byte } };
array.Array.Items.Add(new Variant { Type = Variant.Types.TypeTag.Byte, U = 1000 });
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(array));
}
private static Envelope Sample() => new()
@@ -165,7 +173,7 @@ public sealed class ProtocolTests
// A frame that parses must still decode its variants without an unexpected exception type.
if (envelope.BodyCase == Envelope.BodyOneofCase.Results)
foreach (var r in envelope.Results.Items)
try { VariantCodec.Decode(r.Value); } catch (Exception ex) when (ex is ScriptWorkerProtocolException or OverflowException) { }
try { VariantCodec.Decode(r.Value); } catch (ScriptWorkerProtocolException) { }
}
}
catch (ScriptWorkerProtocolException)
@@ -310,6 +318,103 @@ public sealed class ProtocolTests
stream.Writes.ShouldBe(2, "one write per pass");
}
private const int SmallCap = 64 * 1024;
private static List<Envelope> ReadAll(byte[] bytes, int cap)
{
var reader = new ScriptWorkerFrameReader(new MemoryStream(bytes), cap);
var frames = new List<Envelope>();
while (reader.Read() is { } env) frames.Add(env);
return frames;
}
private static Envelope BigEval(ulong id, int keyChars = 8000)
=> new() { Eval = new EvalBatch { Items = { new EvalRequest { EvalId = id, Key = new string('k', keyChars) } } } };
private static EvalResult BigResult(ulong id, int chars = 8000)
=> new() { EvalId = id, Value = new Variant { Type = Variant.Types.TypeTag.String, S = new string('r', chars) } };
/// <summary>
/// #999 / review K-5: evaluations queued behind a write in progress are merged, but never past the frame cap — the
/// merged batch is cut into several frames, each within the cap, in order. Before the fix the writer merged
/// unboundedly and <c>Append</c> threw, which faults the writer and kills the worker connection.
/// </summary>
[Fact]
public async Task Merged_evaluations_are_cut_at_the_frame_cap_not_faulted()
{
var stream = new GatedStream();
Exception? fault = null;
var writer = new ScriptWorkerFrameWriter(stream, ex => fault = ex, SmallCap, firstSeq: 1);
writer.TryWrite(Eval(1)).ShouldBeTrue(); // blocks on the gate
for (ulong id = 2; id <= 25; id++) writer.TryWrite(BigEval(id)).ShouldBeTrue(); // ≈ 3 × the cap queued
stream.Gate.SetResult();
await Scripts.Eventually(() =>
{
try { return ReadAll(stream.ToArray(), SmallCap).SelectMany(f => f.Eval.Items).Count() == 25; }
catch (ScriptWorkerProtocolException) { return false; }
}, TimeSpan.FromSeconds(5), "every evaluation written");
fault.ShouldBeNull();
var frames = ReadAll(stream.ToArray(), SmallCap);
frames.Count.ShouldBeGreaterThanOrEqualTo(4, "the merged batch was cut, not sent whole");
frames.ShouldAllBe(f => f.CalculateSize() <= SmallCap);
frames.SelectMany(f => f.Eval.Items).Select(i => i.EvalId).ShouldBe(Enumerable.Range(1, 25).Select(i => (ulong)i));
frames.Select(f => f.Seq).ShouldBe(Enumerable.Range(2, frames.Count).Select(i => (ulong)i));
}
/// <summary>K-5: ONE envelope whose items together exceed the cap (an unbounded <c>EvalBatch</c>) is split by item.</summary>
[Fact]
public void One_oversized_batch_is_split_by_item()
{
var stream = new MemoryStream();
Exception? fault = null;
var writer = new ScriptWorkerFrameWriter(stream, ex => fault = ex, SmallCap, firstSeq: 1, synchronous: true);
var batch = new EvalBatch();
for (ulong id = 1; id <= 30; id++) batch.Items.Add(new EvalRequest { EvalId = id, Key = new string('k', 8000) });
writer.TryWrite(new Envelope { Eval = batch }).ShouldBeTrue();
fault.ShouldBeNull();
var frames = ReadAll(stream.ToArray(), SmallCap);
frames.Count.ShouldBeGreaterThan(1);
frames.ShouldAllBe(f => f.CalculateSize() <= SmallCap);
frames.SelectMany(f => f.Eval.Items).Select(i => i.EvalId).ShouldBe(Enumerable.Range(1, 30).Select(i => (ulong)i));
}
/// <summary>
/// K-5: results are cut at the cap the same way, the started / deferred / soft-expired ids still arrive, and a
/// single RESULT too large for any frame fails that one evaluation (unsupported type) instead of the connection.
/// </summary>
[Fact]
public void Results_are_cut_at_the_cap_and_one_oversized_result_fails_alone()
{
var stream = new MemoryStream();
Exception? fault = null;
var writer = new ScriptWorkerFrameWriter(stream, ex => fault = ex, SmallCap, firstSeq: 1, synchronous: true);
var results = new EvalResults { StartedEvalIds = { 100, 101 }, DeferredEvalIds = { 102 }, SoftExpiredEvalIds = { 103 } };
for (ulong id = 1; id <= 20; id++) results.Items.Add(BigResult(id));
results.Items.Add(BigResult(21, chars: SmallCap * 2)); // alone over the cap
results.Items.Add(BigResult(22));
writer.TryWrite(new Envelope { Results = results }).ShouldBeTrue();
fault.ShouldBeNull();
var frames = ReadAll(stream.ToArray(), SmallCap);
frames.Count.ShouldBeGreaterThan(1);
frames.ShouldAllBe(f => f.CalculateSize() <= SmallCap);
var items = frames.SelectMany(f => f.Results.Items).ToList();
items.Select(i => i.EvalId).ShouldBe(Enumerable.Range(1, 22).Select(i => (ulong)i));
var oversized = items.Single(i => i.EvalId == 21);
oversized.OutcomeCase.ShouldBe(EvalResult.OutcomeOneofCase.Error);
oversized.Error.Kind.ShouldBe(ScriptError.Types.Kind.UnsupportedType);
oversized.Error.Message.ShouldContain("frame cap");
items.Single(i => i.EvalId == 22).Value.S.Length.ShouldBe(8000, "the neighbours are untouched");
frames.SelectMany(f => f.Results.StartedEvalIds).ShouldBe([100UL, 101UL]);
frames.SelectMany(f => f.Results.DeferredEvalIds).ShouldBe([102UL]);
frames.SelectMany(f => f.Results.SoftExpiredEvalIds).ShouldBe([103UL]);
}
/// <summary>A failed write completes the writer, reports once, and later frames are refused rather than lost silently.</summary>
[Fact]
public void A_failed_write_completes_the_writer_and_reports_once()
@@ -347,4 +452,26 @@ public sealed class ProtocolTests
spread.Distinct().Count().ShouldBe(4);
OutOfProcessScriptRunner.ShardIndex("abc", 1000).ShouldBe((int)(0x1A47E90Bu % 1000));
}
/// <summary>
/// #999 / review K-11: the shard hash is computed without a per-call byte[] — and over exactly the bytes the old
/// <c>Encoding.UTF8.GetBytes</c> form hashed (non-ASCII and lone surrogates included), so placement is unchanged.
/// </summary>
[Fact]
public void Shard_hash_allocates_nothing_and_keeps_the_utf8_placement()
{
static int Reference(string key, int count)
{
var hash = 2166136261u;
foreach (var b in System.Text.Encoding.UTF8.GetBytes(key)) { hash ^= b; hash *= 16777619u; }
return (int)(hash % (uint)count);
}
foreach (var key in new[] { "1:vt-1", "2:Plant/Linie Ä/Füllstand", "1:€𝄞", "1:\ud800x", "" })
OutOfProcessScriptRunner.ShardIndex(key, 7919).ShouldBe(Reference(key, 7919), key);
OutOfProcessScriptRunner.ShardIndex("1:warm", 4);
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 10_000; i++) OutOfProcessScriptRunner.ShardIndex("1:Plant/Area/Line/Equipment/vt-42", 4);
(GC.GetAllocatedBytesForCurrentThread() - before).ShouldBe(0);
}
}