diff --git a/docs/DriverLifecycle.md b/docs/DriverLifecycle.md index 473fba611..d8d6cb47c 100644 --- a/docs/DriverLifecycle.md +++ b/docs/DriverLifecycle.md @@ -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`. --- diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md index 32e04c1ac..554713e66 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -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: diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 386cc7cd2..8d5d6d133 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -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 diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index f75a02274..77afb3695 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -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); + } + + /// + /// A sample whose identity is already decoded and validated; with + /// its value's size was already bounded by the frame preflight (K-11). + /// + 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(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( diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs index 348864839..633ca9920 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs @@ -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); + } + + /// + /// 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 — 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. + /// + 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; } + /// 0001-01-01T00:00:00Z as Unix seconds — the protobuf Timestamp / DateTimeOffset lower bound. + private const long MinTimestampSeconds = -62_135_596_800L; + + /// 9999-12-31T23:59:59Z as Unix seconds — the protobuf Timestamp / DateTimeOffset upper bound. + 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(); } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ConnectionBackoff.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ConnectionBackoff.cs index 3a2f49ff2..3f384d98a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ConnectionBackoff.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ConnectionBackoff.cs @@ -42,7 +42,8 @@ public sealed class ConnectionBackoff /// /// Capped exponential backoff schedule. ≤ 0 returns /// ; each subsequent failure doubles the wait up to - /// . Computed in ticks with an overflow guard so a large failure + /// — or up to 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 ComputeBackoffDelay. /// @@ -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); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/PollGroupEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/PollGroupEngine.cs index 704b8eadd..3f163a387 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/PollGroupEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/PollGroupEngine.cs @@ -107,11 +107,11 @@ public sealed class PollGroupEngine : IAsyncDisposable /// The interval feeding that schedule is the per-subscription interval /// already clamped to in , so /// the first failure's wait equals the clamped interval (shift 0 → 1×) and the floor is - /// honoured for free. One asymmetry worth knowing: ComputeDelay saturates at the cap - /// unconditionally, so a set SMALLER than the clamped - /// interval makes failures retry FASTER than the interval floor — the cap outranks - /// on the failure branch. Configure it above the floor - /// (every driver here uses 30 s against a 100 ms floor). + /// honoured for free. A SMALLER than a subscription's clamped + /// interval never shortens it (#999 / review K-10): ComputeDelay 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.) /// 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 callbacks. The diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs index 10678f1ca..0f2bc981c 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs @@ -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 . +/// next clear; Timed expires at , and only through +/// (#999 / K-4) — never inside . /// /// 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 AppendComment( ImmutableList existing, DateTime ts, string user, string kind, string? text) => existing.Add(new AlarmComment(ts, user, kind, text ?? string.Empty)); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs index 557141ddc..2e65df07a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs @@ -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 's own expiry silently unshelved it /// (no audit entry, no event) and the shelving timer found nothing left to expire. /// - private AlarmConditionState ExpireTimedShelveAtLoad( - AlarmState state, AlarmConditionState seed, List pendingEmissions) + /// + /// #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. no longer + /// expires a timed shelve itself, so the shelving check is the only place one expires. + /// + private AlarmConditionState ExpireTimedShelve( + AlarmState state, AlarmConditionState seed, DateTime nowUtc, List 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; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs index 306a6816f..cc465b4be 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs @@ -278,11 +278,18 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp /// The shard index. 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 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 /// The shard a key's NEXT evaluation goes to (attribution may just have made it a suspect). 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 /// The negative compile cache's key for this source (kind-scoped). public string FailureKey => _failureKey ??= InProcessScriptRunner.ScopedKey(Kind, ShaHex); + private int _shardIndex = -1; + + /// + /// 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. + /// + 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; + } + /// The slot order last used for this key (see ). public string[]? Paths; public readonly List KillStrikes = []; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs index 4c5894c97..7bfc7eadc 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs @@ -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; } + /// + /// #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. + /// + 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; + } + /// /// The compiled form of in this worker when it is loaded at /// with and compiled cleanly — the batch fast path, which never waits for a load. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptWorkerFramePipe.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptWorkerFramePipe.cs index a49357986..685607fa6 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptWorkerFramePipe.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptWorkerFramePipe.cs @@ -240,35 +240,130 @@ public sealed class ScriptWorkerFrameWriter } } + /// + /// 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. + /// + private const int FrameHeadroom = 64; + + /// The bytes a merged batch's items and ids may add up to so the frame stays within the cap. + private int MergeBudget => Math.Max(1, MaxFrameBytes - FrameHeadroom); + + /// + /// Whether 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. + /// + /// The evaluation request or result. + /// Whether it fits. + public bool FitsOneFrame(IMessage item) => ItemBytes(item) <= MergeBudget; + + /// A repeated-message item's encoded size inside its batch: tag (1 byte) + length prefix + body. + private static int ItemBytes(IMessage item) + { + var size = item.CalculateSize(); + return 1 + CodedOutputStream.ComputeLengthSize(size) + size; + } + + /// A packed repeated uint64 id: at most 10 bytes; the per-list tag + length is in the headroom. + private const int IdBytes = 10; + + /// + /// 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 UNSUPPORTED_TYPE error for + /// that evaluation alone; an oversized single evaluation REQUEST is refused before it gets here + /// (), so reaching with one is still a protocol fault. + /// 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(); + } + + /// The id lists of , each with the accessor for the same list on a merged batch. + private static IEnumerable<(ulong Id, Func> 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) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/VariantCodec.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/VariantCodec.cs index d37ffde44..137817b60 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/VariantCodec.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/VariantCodec.cs @@ -61,6 +61,21 @@ public static class VariantCodec /// The boxed value. /// An unknown tag, or a payload that does not match the tag. 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; } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs index 9421b42b7..979e477fd 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs @@ -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; } } + +/// Shared timeout classification for the script run wrappers (#999 / review K-7). +internal static class ScriptTimeouts +{ + /// + /// True when is the exception the script itself threw (it faulted + /// ), false when it is Task.WaitAsync's synthesized timeout. Both are + /// s (a script may throw one directly, or hit a Regex match timeout), so the + /// type alone cannot tell a guard timeout from the script's own failure. + /// + internal static bool IsScriptOwn(Task runTask, Exception caught) + => runTask.IsFaulted && runTask.Exception!.InnerExceptions.Contains(caught); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/TimedScriptEvaluator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/TimedScriptEvaluator.cs index 7a860436e..eac8dbc6d 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/TimedScriptEvaluator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/TimedScriptEvaluator.cs @@ -82,8 +82,9 @@ public sealed class TimedScriptEvaluator { 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. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs index 3d58f1cb0..f1ad841e7 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResilienceOptionsParser.cs @@ -101,13 +101,22 @@ public static class DriverResilienceOptionsParser { foreach (var (capName, overridePolicy) in shape.CapabilityPolicies) { - if (!Enum.TryParse(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(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, diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs index 60b863655..d697a4430 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Resilience/DriverResiliencePipelineBuilder.cs @@ -17,6 +17,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Resilience; /// Per-device isolation. Composition from outside-in: /// Timeout → Retry (when capability permits) → Circuit Breaker (when tier permits). /// +/// The pipeline's own timeout is a failure (#999 / review K-6). 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 OnTimeout records a +/// tracker failure. Before, both predicates excluded every : a hung +/// device burned the full timeout on every call forever with the breaker closed and no failure on /hosts. +/// /// Pipeline resolution is lock-free on the hot path: the inner /// caches a per key; /// first-call cost is one .Build. Thereafter reads are O(1). @@ -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(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(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(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(); } + /// The caller's token, recorded by before the timeout links its own. + private static readonly ResiliencePropertyKey CallerTokenKey = new("otopcua.caller-token"); + + /// + /// 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. + /// + private static bool IsPipelineTimeout(ResilienceContext context) + => context.CancellationToken.IsCancellationRequested + && context.Properties.TryGetValue(CallerTokenKey, out var caller) + && !caller.IsCancellationRequested; + + /// Outermost pass-through that records the caller's cancellation token on the context (#999 / K-6). + private sealed class CallerTokenStrategy : ResilienceStrategy + { + public static readonly CallerTokenStrategy Instance = new(); + + protected override ValueTask> ExecuteCore( + Func>> 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); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index 43b65e213..a19a0a238 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -4665,6 +4665,33 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn StartAcquisitionDemand(ready.DriverInstanceId, desired, ActorRefs.Nobody); } + /// + /// #999 / review K-8: the resilience invoker for a spawn, never throwing. A factory throw (a wrong-shaped + /// ResilienceConfig from a restored database, a manual SQL edit or an older build) used to escape + /// 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. + /// + 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!, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs index 74fe496d1..d5a429483 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs @@ -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() + /// + /// Drains every buffered line into batches of at most encoded bytes each + /// (#999 / review K-5). A line too large for any batch on its own is counted as dropped. + /// + public List Drain(int maxBatchBytes) { + var batches = new List(); 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]; diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs index 1ee96c60d..943f8f368 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs @@ -514,4 +514,48 @@ public sealed class GrpcDataCodecTests DataProtoMapper.DecodeBrowseResponse(response, new DataDecodeLimits(1, 10000, 100)) ); } + + /// + /// #999 / review K-9: a malformed wire value fails as the codec's documented (the + /// gRPC service maps it to InvalidArgument) — never an / + /// (unmapped: an internal error) or an + /// (mapped to Unavailable: the client retries or fails over a request that can never succeed). + /// + [Theory] + [MemberData(nameof(MalformedValues))] + public void Malformed_wire_values_fail_as_ArgumentException(string _, Protos.DataConnection.V1.TypedValue wire) + { + var ex = Should.Throw(() => TypedValueCodec.Decode(wire)); + ex.ShouldBeAssignableTo($"{ex.GetType().Name}: {ex.Message}"); + } + + /// K-9: an out-of-range protobuf timestamp is an ArgumentException at the shared timestamp decoder too. + [Fact] + public void Out_of_range_timestamps_fail_as_ArgumentException() + { + var ex = Should.Throw(() => TypedValueCodec.DecodeTimestamp(new Google.Protobuf.WellKnownTypes.Timestamp { Seconds = long.MaxValue })); + ex.ShouldBeAssignableTo($"{ex.GetType().Name}: {ex.Message}"); + } + + public static TheoryData MalformedValues() + { + var data = new TheoryData + { + { "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; + } } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ConnectionBackoffTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ConnectionBackoffTests.cs index 3af88cf09..2c45e2c1c 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ConnectionBackoffTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ConnectionBackoffTests.cs @@ -42,6 +42,18 @@ public sealed class ConnectionBackoffTests public void ComputeDelay_SaturatesAtCap(int failures) => ConnectionBackoff.ComputeDelay(Base, failures, Cap).ShouldBe(Cap); + /// + /// #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. + /// + [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)); + /// A fresh throttle permits the first attempt immediately. [Fact] public void ShouldAttempt_FreshInstance_AllowsImmediately() diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/PollGroupEngineTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/PollGroupEngineTests.cs index fdd7ed592..942a8801b 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/PollGroupEngineTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/PollGroupEngineTests.cs @@ -494,6 +494,38 @@ public sealed class PollGroupEngineTests readCount.ShouldBeLessThan(18); } + /// + /// #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. + /// + [Fact] + public async Task Backoff_CapBelowInterval_NeverPollsAFailingDeviceFasterThanTheInterval() + { + var stamps = new ConcurrentQueue(); + Task> Reader(IReadOnlyList 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}"); + } + /// A successful poll resets the failure count so the cadence snaps back to the base interval. [Fact] public async Task Backoff_SuccessResetsToInterval() diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/Part9StateMachineTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/Part9StateMachineTests.cs index dd8ea3b7f..3c86346aa 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/Part9StateMachineTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/Part9StateMachineTests.cs @@ -174,6 +174,18 @@ public sealed class Part9StateMachineTests after.State.Comments.Any(c => c.Kind == "AutoUnshelve").ShouldBeTrue(); } + /// #999 / K-4: ApplyPredicate never expires a timed shelve itself — that would unshelve silently. + [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); + } + /// Verifies that unshelving an unshelved alarm is a no-op. [Fact] public void Unshelve_from_unshelved_is_noop() diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTimedShelveExpiryTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTimedShelveExpiryTests.cs new file mode 100644 index 000000000..829610ba4 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTimedShelveExpiryTests.cs @@ -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; + +/// +/// #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 and records exactly one AutoUnshelve audit comment +/// (before the fix ApplyPredicate unshelved it silently: no event, no audit, the OPC UA node stayed +/// TimedShelved). Covered on both the in-process path and the batch path. +/// +[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 RunAsync(ScriptInvocation invocation, CancellationToken ct = default) + => Task.FromResult(Answer(invocation)); + + public IReadOnlyList> RunBatch(IReadOnlyList invocations, CancellationToken ct = default) + => invocations.Select(i => Task.FromResult(Answer(i))).ToArray(); + + public void Reset(ScriptContextKind kind) { } + + public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; + } + + private static async Task WaitFor(Func 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(); + 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(); + 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]); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs index 99ae422ec..2bc92e2dd 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs @@ -541,6 +541,33 @@ public sealed class ScriptRunGuardTests guard.QuarantinedCount.ShouldBe(1); } + /// + /// #999 / review K-7: a the SCRIPT threw (directly, or a + /// RegexMatchTimeoutException) is the script's own failure — it propagates unchanged, is not a guard + /// timeout, and never quarantines. Before the fix the guard's catch (TimeoutException) took it for + /// WaitAsync's timeout and called Cancel() on the already-disposed run CTS, surfacing + /// . + /// + [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(() => + 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); + } + /// Releases the held script (signal), waits for the orphan to drain, and re-arms the gate for the next attempt. private static async Task ReleaseAndDrain(ScriptRunGuard guard, FakeScriptContext held) { diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/TimedScriptEvaluatorTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/TimedScriptEvaluatorTests.cs index 3ae5b2803..78cc3b20a 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/TimedScriptEvaluatorTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/TimedScriptEvaluatorTests.cs @@ -47,6 +47,18 @@ public sealed class TimedScriptEvaluatorTests result.ShouldBe(42.0); } + /// #999 / review K-7: a TimeoutException the script threw itself is not the wrapper's timeout. + [Fact] + public async Task A_script_thrown_TimeoutException_is_not_reported_as_a_script_timeout() + { + var inner = ScriptEvaluator.Compile("""throw new System.TimeoutException("mine");"""); + var timed = new TimedScriptEvaluator(inner, TimeSpan.FromSeconds(5)); + + var ex = await Should.ThrowAsync(() => timed.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken)); + ex.GetType().ShouldBe(typeof(TimeoutException)); + ex.Message.ShouldBe("mine"); + } + /// Verifies that scripts longer than timeout throw ScriptTimeoutException. [Fact] public async Task Script_longer_than_timeout_throws_ScriptTimeoutException() diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs index 246d33460..e5863b23f 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/DriverResiliencePipelineBuilderTests.cs @@ -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"); } + /// + /// #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 , which + /// both predicates excluded: every call burned the full timeout forever, the breaker never opened and + /// /hosts showed ConsecutiveFailures = 0 for a dead device. + /// + [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.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(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(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(); + } + + /// + /// #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. + /// + [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.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(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); + } + /// /// A controllable whose clock advances only on . /// Drives both wall-clock () and monotonic () diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/ResilienceConfigBrickTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/ResilienceConfigBrickTests.cs index 4b1871d93..005decfda 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/ResilienceConfigBrickTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/Resilience/ResilienceConfigBrickTests.cs @@ -45,4 +45,33 @@ public sealed class ResilienceConfigBrickTests var result = await pipeline.ExecuteAsync(_ => ValueTask.FromResult(42), CancellationToken.None); result.ShouldBe(42); } + + /// + /// #999 / review K-8: valid JSON of the wrong SHAPE must fall back like malformed JSON does. A numeric capability + /// name passes Enum.TryParse (→ KeyNotFoundException) and a null policy dereferenced null + /// (NullReferenceException) — both escaped ParseOrDefaults and, through the invoker factory, the + /// driver host's spawn. + /// + [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(); + } + + /// K-8 positive control: a well-formed override next to a wrong-shaped entry still applies. + [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"); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnreadableArtifactTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnreadableArtifactTests.cs index 8ab378328..f033b6573 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnreadableArtifactTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorUnreadableArtifactTests.cs @@ -333,6 +333,46 @@ public sealed class DriverHostActorUnreadableArtifactTests : RuntimeActorTestBas tracker.TryGet("drv-1", "dev1").ShouldNotBeNull().IsBreakerOpen.ShouldBeTrue(); } + /// + /// #999 / review K-8 — an invoker factory that throws (a wrong-shaped ResilienceConfig reached it) must + /// not escape SpawnChild: 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. + /// + [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 { "driver" }, + invokerFactory: invokerFactory)); + + actor.Tell(new DispatchDeployment(SeedV3Deployment(db, RevA), RevA, CorrelationId.NewId())); + coordinator.ExpectMsg(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) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs index 8ee57f265..fcc5964da 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs @@ -360,6 +360,52 @@ public sealed class ContainmentTests await Scripts.Eventually(() => sink.Rendered.Contains("hello 42"), TimeSpan.FromSeconds(5), "the forwarded log line"); } + /// + /// #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. + /// + [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"); + } + + /// + /// 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. + /// + [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() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs index 8887f52c0..06b50dbd8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs @@ -76,7 +76,15 @@ public sealed class ProtocolTests { Should.Throw(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Int16, S = "x" })); Should.Throw(() => VariantCodec.Decode(new Variant { Type = (Variant.Types.TypeTag)99 })); - Should.Throw(() => 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(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Int16, I = 1 << 20 })); + Should.Throw(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Byte, U = 300 })); + Should.Throw(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.DatetimeUtc, DtTicks = long.MaxValue })); + Should.Throw(() => 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(() => 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 ReadAll(byte[] bytes, int cap) + { + var reader = new ScriptWorkerFrameReader(new MemoryStream(bytes), cap); + var frames = new List(); + 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) } }; + + /// + /// #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 Append threw, which faults the writer and kills the worker connection. + /// + [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)); + } + + /// K-5: ONE envelope whose items together exceed the cap (an unbounded EvalBatch) is split by item. + [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)); + } + + /// + /// 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. + /// + [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]); + } + /// A failed write completes the writer, reports once, and later frames are refused rather than lost silently. [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)); } + + /// + /// #999 / review K-11: the shard hash is computed without a per-call byte[] — and over exactly the bytes the old + /// Encoding.UTF8.GetBytes form hashed (non-ASCII and lone surrogates included), so placement is unchanged. + /// + [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); + } }