diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 1ef65b1ec..67add7d52 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -268,7 +268,17 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: since #1092 — it is held to the cap by its `Count`, then copied into the same typed array (`double[]`, …), and refused for an open element type (`List`) — because the out-of-process worker's wire carries arrays but no collection type (it used to answer `unsupported type` while the - in-process runner returned the list itself). Arrays, strings and scalars are unchanged. **Still in-process-only limits** (the boundary is + in-process runner returned the list itself). Arrays, strings and scalars are unchanged, provided their + type is one an OPC UA node can carry. **The result's type is checked too (#1100):** a value script may + return null, a `bool`, an integer type, `float`, `double`, `string`, `DateTime` or `Guid`, or a + one-dimensional array of one of them (`ScriptResultMaterializer.PublishableScalarTypes` — exactly what + the server's OPC UA value boundary turns into a built-in Variant). Anything else — a `Dictionary` + (it becomes `KeyValuePair[]`), a `decimal`, an enum, a `TimeSpan`, a `char`, a tuple, a 2-D array — + fails the run (Bad, script log) in both runners with `script threw: The script returned a value of type + '…', which an OPC UA node cannot carry; …`. ⚠️ Behaviour change: in process such a value used to + "succeed" and then fail inside the node write, so the node silently kept its previous value and status + (only a server-log warning); convert first (`Convert.ToDouble(x)`, or a dictionary's keys and values as + two arrays). **Still in-process-only limits** (the boundary is `Scripting:Runner=OutOfProcess`): memory exhaustion inside a run (the sample is after the fact), a non-terminating loop (an orphan thread, then quarantine) and the same two inside an enumerated sequence. See `docs/VirtualTags.md` §"Known resource limits (accepted trade-offs)". The out-of-process diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 7ead34ff2..9e5315b6c 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -73,7 +73,7 @@ Absent, blank or unrecognised values mean `Error` — a typo never silently weak #### Known resource limits (accepted trade-offs) -The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen — the review found BCL members that do exactly that over script-built data (see "Deep or cyclic data" in the sandbox section), and the analyzer now refuses the constructs that build it; a script can catch the exception, which only unwinds it. **Exception handlers (2026-12-02 review, lmxopcua#971):** a `catch` / `finally` runs as a funclet *on top of* the frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level) — `catch { throw; }` on every frame overflowed while unwinding from the guard's own exception, and 300 frames that each rethrow overflowed with no guard involvement. The rewrite therefore also gives every script `catch` the filter `when (ScriptStackGuard.CanHandle() && …)` and wraps every `finally` body in `if (ScriptStackGuard.CanHandle())`: once the stack is low, script handlers are skipped and the exception in flight reaches the host in one dispatch (the run fails with it). On a healthy stack both are no-ops. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. **Returned sequences and the sandbox boundary (lmxopcua#1059).** A script that returns an iterator or an unfinished LINQ query used to hand the host a sequence nothing had run — enumerated later on the host's thread, outside the timeout and allocation sample. `ScriptRunGuard` now materialises a returned lazy sequence into a typed array on the run's own thread (`ScriptResultMaterializer`), capped at `Scripting:MaxResultElements` (default 100 000, also applied to returned arrays/collections; since lmxopcua#1092 a concrete non-array collection such as a `List` is copied into the same typed array — capped by its `Count` first — rather than returned as-is, so both runners give `double[]`; `List` and other open element types are now refused like their lazy equivalents); an over-cap sequence or one whose element type is open (`object`, an interface, another collection) fails the run (Bad + script log, not a timeout strike). **Both runners apply this one rule (lmxopcua#1064):** the `ScriptWorker` calls the same `ScriptResultMaterializer` on a value script's result inside its run (registered with the watchdog, allocation sample open), with the node's `Scripting:MaxResultElements` carried in the worker's `Hello` (`max_result_elements`) — so a lazy sequence becomes the same typed array out of process (it used to answer `unsupported type`), an over-cap array is refused instead of being shipped whole, and the failure reason is the same `script threw: …` text in both (pinned by `ParityTests.Result_materialisation_and_the_element_cap_agree`). **What the in-process runner does NOT contain** — and what `Scripting:Runner=OutOfProcess` does: memory exhaustion inside a run (sampled after the fact), a non-terminating loop (one orphaned pool thread, then quarantine) and the same two inside the enumeration of a returned sequence. Decision: document the boundary rather than add in-process memory accounting — an in-process run cannot be pre-empted, so any in-process "limit" is advisory. **Rule for the allow-list:** the host recurses over script-built data (`OwnedDataSample.CopyLegacy`, `VirtualTagActor.SameValue` over a returned array; a value's `ToString`/`Equals`/`GetHashCode` in logging and dedup), so any type added to `ForbiddenTypeAnalyzer.AllowedTypes` later must be checked for recursive `ToString`/`Equals`/`GetHashCode` over script-built (possibly cyclic or deeply nested) data before it is allowed. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety". +The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen — the review found BCL members that do exactly that over script-built data (see "Deep or cyclic data" in the sandbox section), and the analyzer now refuses the constructs that build it; a script can catch the exception, which only unwinds it. **Exception handlers (2026-12-02 review, lmxopcua#971):** a `catch` / `finally` runs as a funclet *on top of* the frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level) — `catch { throw; }` on every frame overflowed while unwinding from the guard's own exception, and 300 frames that each rethrow overflowed with no guard involvement. The rewrite therefore also gives every script `catch` the filter `when (ScriptStackGuard.CanHandle() && …)` and wraps every `finally` body in `if (ScriptStackGuard.CanHandle())`: once the stack is low, script handlers are skipped and the exception in flight reaches the host in one dispatch (the run fails with it). On a healthy stack both are no-ops. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. **Returned sequences and the sandbox boundary (lmxopcua#1059).** A script that returns an iterator or an unfinished LINQ query used to hand the host a sequence nothing had run — enumerated later on the host's thread, outside the timeout and allocation sample. `ScriptRunGuard` now materialises a returned lazy sequence into a typed array on the run's own thread (`ScriptResultMaterializer`), capped at `Scripting:MaxResultElements` (default 100 000, also applied to returned arrays/collections; since lmxopcua#1092 a concrete non-array collection such as a `List` is copied into the same typed array — capped by its `Count` first — rather than returned as-is, so both runners give `double[]`; `List` and other open element types are now refused like their lazy equivalents); an over-cap sequence or one whose element type is open (`object`, an interface, another collection) fails the run (Bad + script log, not a timeout strike); so does, since lmxopcua#1100, a result whose type an OPC UA node cannot carry (only null, `bool`, the integer types, `float`, `double`, `string`, `DateTime`, `Guid` and one-dimensional arrays of them pass — a returned `Dictionary`, `decimal` or enum is refused in both runners instead of silently failing the node write in process). **Both runners apply this one rule (lmxopcua#1064):** the `ScriptWorker` calls the same `ScriptResultMaterializer` on a value script's result inside its run (registered with the watchdog, allocation sample open), with the node's `Scripting:MaxResultElements` carried in the worker's `Hello` (`max_result_elements`) — so a lazy sequence becomes the same typed array out of process (it used to answer `unsupported type`), an over-cap array is refused instead of being shipped whole, and the failure reason is the same `script threw: …` text in both (pinned by `ParityTests.Result_materialisation_and_the_element_cap_agree`). **What the in-process runner does NOT contain** — and what `Scripting:Runner=OutOfProcess` does: memory exhaustion inside a run (sampled after the fact), a non-terminating loop (one orphaned pool thread, then quarantine) and the same two inside the enumeration of a returned sequence. Decision: document the boundary rather than add in-process memory accounting — an in-process run cannot be pre-empted, so any in-process "limit" is advisory. **Rule for the allow-list:** the host recurses over script-built data (`OwnedDataSample.CopyLegacy`, `VirtualTagActor.SameValue` over a returned array; a value's `ToString`/`Equals`/`GetHashCode` in logging and dedup), so any type added to `ForbiddenTypeAnalyzer.AllowedTypes` later must be checked for recursive `ToString`/`Equals`/`GetHashCode` over script-built (possibly cyclic or deeply nested) data before it is allowed. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety". @@ -130,10 +130,17 @@ processes: (512 MiB), a Windows Job Object (kill-on-close, one process, a commit backstop), a random pipe (current-user-only on Linux; an explicit host + worker-identity ACL on Windows) with a launch nonce in its environment, and no Akka / gRPC assemblies in its folder. It exits on pipe end of stream or when its parent pid disappears. Results cross as protobuf `Variant`s carrying the exact CLR type, so - `(short)ctx.GetTag(x).Value` behaves as in process; an input or result type with no tag (a `Guid`, an array of - `KeyValuePair`) is an explicit `unsupported type: …` failure rather than a conversion — a behaviour change from in - process. A returned collection (`List`) is not one of those since lmxopcua#1092: both runners copy it into a - typed array first. + `(short)ctx.GetTag(x).Value` behaves as in process; an INPUT type with no tag (a `decimal`, a `TimeSpan`) is an + explicit `unsupported type: …` failure rather than a conversion — a behaviour change from in process. A `Guid` (scalar + or array) has a tag since lmxopcua#1100 (`GUID`, additive; it used to be `unsupported type` although the in-process + runner's Guid reached the client as an OPC UA Guid). A RESULT whose type no OPC UA node can carry (a + `KeyValuePair[]` — what a returned `Dictionary` becomes — a `decimal`, an enum, a `TimeSpan`, …) is refused by + `ScriptResultMaterializer` inside the run in BOTH runners, with the same `script threw: … which an OPC UA node cannot + carry …` reason (lmxopcua#1100: in process it used to pass and then fail in the node write, leaving the node on its + previous value and status with only a server-log warning). The one remaining result divergence is a jagged array + (`int[][]`): the publish path carries it (as an array of Variants) and the in-process runner returns it, but the wire + has no nested-array tag, so the worker answers `unsupported type`. A returned collection (`List`) is copied + into a typed array by both runners first (lmxopcua#1092). - **Attribution happens before release.** The worker's exit path runs attribution (strike, quarantine, suspect marks) synchronously **before** it completes any evaluation the worker held, so a script killed for its deadline is already quarantined when its single-flight slot is released — no trigger can re-run it in the restart gap. A worker diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/Protos/script_worker.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/Protos/script_worker.proto index 6893d0f97..2e7212c0a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/Protos/script_worker.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/Protos/script_worker.proto @@ -220,6 +220,7 @@ message Variant { STRING = 12; DATETIME_UTC = 13; ARRAY = 14; + GUID = 15; // lmxopcua#1100 (additive): System.Guid, carried in `g` as its 16 ToByteArray() bytes } TypeTag type = 1; // the exact CLR type: (short)ctx.GetTag(x).Value must keep working oneof v { @@ -231,6 +232,7 @@ message Variant { string s = 7; int64 dt_ticks = 8; ArrayValue array = 9; + bytes g = 10; // GUID payload (exactly 16 bytes) } } 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 137817b60..1916db429 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 @@ -38,6 +38,12 @@ public static class VariantCodec variant.Type = Variant.Types.TypeTag.DatetimeUtc; variant.DtTicks = ToUtc(v).Ticks; return true; + case Guid v: + // lmxopcua#1100: a Guid is an OPC UA built-in (the publish path serves it as one), so it crosses the wire + // rather than failing "unsupported type" where the in-process runner gave the client a Guid. + variant.Type = Variant.Types.TypeTag.Guid; + variant.G = Google.Protobuf.ByteString.CopyFrom(v.ToByteArray()); + return true; case Array array when array.Rank == 1 && TryElementTag(array.GetType().GetElementType()!, out var elementTag): { var av = new ArrayValue { ElementType = elementTag }; @@ -94,6 +100,7 @@ public static class VariantCodec Variant.Types.TypeTag.Double => Expect(variant, Variant.VOneofCase.D).D, Variant.Types.TypeTag.String => Expect(variant, Variant.VOneofCase.S).S, Variant.Types.TypeTag.DatetimeUtc => new DateTime(Expect(variant, Variant.VOneofCase.DtTicks).DtTicks, DateTimeKind.Utc), + Variant.Types.TypeTag.Guid => DecodeGuid(Expect(variant, Variant.VOneofCase.G)), Variant.Types.TypeTag.Array => DecodeArray(Expect(variant, Variant.VOneofCase.Array).Array), _ => throw new ScriptWorkerProtocolException($"unknown variant type tag {(int)variant.Type}"), }; @@ -117,6 +124,15 @@ public static class VariantCodec return variant; } + private static Guid DecodeGuid(Variant variant) + { + // An absent payload is the default value, as for every other tag (see Expect); a present one is exactly 16 bytes. + if (variant.VCase == Variant.VOneofCase.None || variant.G.IsEmpty) return Guid.Empty; + if (variant.G.Length != 16) + throw new ScriptWorkerProtocolException($"variant tagged {variant.Type} carries {variant.G.Length} bytes, not 16"); + return new Guid(variant.G.Span); + } + private static Array DecodeArray(ArrayValue? array) { if (array is null) throw new ScriptWorkerProtocolException("array variant without an array payload"); @@ -149,6 +165,7 @@ public static class VariantCodec _ when elementType == typeof(double) => Variant.Types.TypeTag.Double, _ when elementType == typeof(string) => Variant.Types.TypeTag.String, _ when elementType == typeof(DateTime) => Variant.Types.TypeTag.DatetimeUtc, + _ when elementType == typeof(Guid) => Variant.Types.TypeTag.Guid, _ => Variant.Types.TypeTag.Null, }; return tag != Variant.Types.TypeTag.Null; @@ -169,6 +186,7 @@ public static class VariantCodec Variant.Types.TypeTag.Double => typeof(double), Variant.Types.TypeTag.String => typeof(string), Variant.Types.TypeTag.DatetimeUtc => typeof(DateTime), + Variant.Types.TypeTag.Guid => typeof(Guid), _ => throw new ScriptWorkerProtocolException($"array element type {tag} is not supported"), }; } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs index 10d105118..abed06467 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs @@ -32,7 +32,15 @@ public sealed class ScriptResultException : InvalidOperationException /// (object, an interface, another collection) is refused — the host copies and compares returned arrays /// recursively, so an open-slot array can nest or contain itself (see ForbiddenTypeAnalyzer). Arrays are /// returned as-is (fully built by the run) but are still held to the element cap. Everything else — scalars, -/// strings, null — is untouched. +/// strings, null — is untouched, provided its type is publishable. +/// +/// +/// The result's TYPE is checked too (lmxopcua#1100): only what the OPC UA publish path can represent passes — +/// see / . Anything else (a +/// KeyValuePair<K,V>[], which is what a returned dictionary becomes, a decimal, an enum, a +/// TimeSpan, a tuple) fails the run with a in both runners. Before, the +/// in-process runner handed it on and the node write threw, leaving the node on its previous value and status +/// with only a server-log warning, while the worker answered "unsupported type". /// /// /// Concrete collections used to be returned as-is too (lmxopcua#1092): in process the host got the @@ -66,6 +74,7 @@ public static class ScriptResultMaterializer case null or string: return value; case Array array: + EnsurePublishable(array.GetType()); EnforceCap(array.Length, maxElements); return array; case ICollection collection: @@ -74,10 +83,61 @@ public static class ScriptResultMaterializer case IEnumerable sequence: return MaterializeSequence(sequence, maxElements, IsGenericCollection(sequence.GetType()) ? "collection" : "lazy sequence"); default: + EnsurePublishable(value.GetType()); return value; } } + /// + /// The scalar CLR types a script result may have, alone or as the element type of a one-dimensional array + /// (lmxopcua#1100): exactly the types the server's OPC UA value boundary (SdkValueBoundary.FromClr) turns + /// into a built-in Variant — Boolean, the eight integer types, Float, Double, String, DateTime and Guid — and, + /// with them, the types the out-of-process wire (VariantCodec) carries. Pinned against both by tests. + /// + public static IReadOnlyList PublishableScalarTypes { get; } = + [ + typeof(bool), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), + typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(string), typeof(DateTime), typeof(Guid), + ]; + + /// + /// Whether a returned value of can reach an OPC UA client (lmxopcua#1100): a + /// scalar, or a one-dimensional array whose element type is publishable + /// (a jagged array of them included — the publish path carries it as an array of Variants). + /// + /// The runtime type of the returned value. + /// true when the publish path can represent the value. + public static bool IsPublishable(Type type) + { + if (type.IsArray) + return type.GetArrayRank() == 1 && !type.IsVariableBoundArray && IsPublishable(type.GetElementType()!); + return PublishableScalarTypes.Contains(type); + } + + // lmxopcua#1100: a value the OPC UA publish path cannot represent (a KeyValuePair[] — what a returned Dictionary + // becomes — a decimal, an enum, a TimeSpan, …) used to "succeed" in process and then fail inside the node write + // (SdkValueBoundary.FromClr throws; OpcUaPublishActor logs it), so the node silently kept its previous value under its + // previous status, while the worker refused the same script "unsupported type". Refused here, inside the run, it is + // the same Bad + script-log failure in both runners. + private static void EnsurePublishable(Type type) + { + if (IsPublishable(type)) return; + throw new ScriptResultException( + $"The script returned a value of type '{Describe(type)}', which an OPC UA node cannot carry; return null, " + + "a bool, an integer type, float, double, string, DateTime or Guid, or a one-dimensional array of one of them " + + "(convert first, e.g. Convert.ToDouble(x) for a decimal, or the keys and values of a dictionary as two arrays)."); + } + + private static string Describe(Type type) + { + if (type.IsArray) return Describe(type.GetElementType()!) + (type.GetArrayRank() == 1 ? "[]" : $"[{new string(',', type.GetArrayRank() - 1)}]"); + if (!type.IsGenericType) return type.Name; + var name = type.Name; + var tick = name.IndexOf('`'); + if (tick >= 0) name = name[..tick]; + return $"{name}<{string.Join(", ", type.GetGenericArguments().Select(Describe))}>"; + } + private static object MaterializeSequence(IEnumerable sequence, int maxElements, string what) { var elementType = ElementTypeOf(sequence.GetType()) @@ -88,6 +148,9 @@ public static class ScriptResultMaterializer throw new ScriptResultException( $"The script returned a {what} of '{elementType.Name}', which can contain another sequence or itself; " + "return a typed array of a concrete type (double[], string[], …)."); + // Checked before anything is enumerated: a sequence that could only become an unpublishable array is refused + // without running it. + EnsurePublishable(elementType.MakeArrayType()); var items = new List(); foreach (var item in sequence) diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs index 5464d5545..11d5bfa5b 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs @@ -79,6 +79,53 @@ public sealed class ScriptResultMaterializerTests .Message.ShouldContain("no IEnumerable element type"); } + /// + /// lmxopcua#1100: a result the OPC UA publish path cannot represent is refused inside the run. In process it used + /// to pass and then fail in the node write (the node silently kept its previous value and status). + /// + [Fact] + public void A_value_no_OPC_UA_node_can_carry_is_refused() + { + object[] refused = + [ + 1.5m, DayOfWeek.Monday, TimeSpan.FromSeconds(1), 'a', DateTimeOffset.UnixEpoch, new KeyValuePair(1, 2), + (1, 2), new[] { new KeyValuePair(1, 2) }, new[] { 1.5m }, new double[1, 1], new Guid?[] { null }, + new Dictionary { [1] = 1.5 }, + ]; + foreach (var value in refused) + Should.Throw(() => ScriptResultMaterializer.Materialize(value, 100), value.GetType().Name) + .Message.ShouldContain("which an OPC UA node cannot carry"); + + Should.Throw(() => ScriptResultMaterializer.Materialize(new Dictionary { ["a"] = 1 }, 100)) + .Message.ShouldStartWith("The script returned a value of type 'KeyValuePair[]'"); + } + + [Fact] + public void An_unpublishable_lazy_sequence_is_refused_before_it_runs() + { + var ran = 0; + var lazy = Enumerable.Range(0, 3).Select(i => { ran++; return (decimal)i; }); + Should.Throw(() => ScriptResultMaterializer.Materialize(lazy, 100)); + ran.ShouldBe(0); + } + + [Fact] + public void Every_publishable_type_passes_scalar_and_array_positive_controls() + { + var guid = Guid.NewGuid(); + ScriptResultMaterializer.Materialize(guid, 100).ShouldBe(guid); + ScriptResultMaterializer.Materialize(new[] { guid }, 100).ShouldBeOfType(); + ScriptResultMaterializer.Materialize(new List { guid }, 100).ShouldBeOfType().ShouldBe([guid]); + // A jagged array is publishable too (the OPC UA boundary carries it as an array of Variants). + ScriptResultMaterializer.Materialize(new[] { new[] { 1 } }, 100).ShouldBeOfType(); + foreach (var type in ScriptResultMaterializer.PublishableScalarTypes) + { + var scalar = type == typeof(string) ? "s" : Activator.CreateInstance(type)!; + ScriptResultMaterializer.Materialize(scalar, 100).ShouldBe(scalar); + ScriptResultMaterializer.Materialize(Array.CreateInstance(type, 1), 100)!.GetType().ShouldBe(type.MakeArrayType()); + } + } + [Fact] public void An_oversized_array_or_collection_is_refused_by_the_same_cap() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/SdkValueBoundaryScriptResultTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/SdkValueBoundaryScriptResultTests.cs new file mode 100644 index 000000000..4f7632a92 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/SdkValueBoundaryScriptResultTests.cs @@ -0,0 +1,61 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests; + +/// +/// lmxopcua#1100: the script-result rule (, applied by both +/// script runners) must agree with what the publish path really takes — , which +/// every node value write goes through. A value the rule passes but FromClr refuses is the defect #1100 found (the +/// node write threw, the node silently kept its previous value and status); a value FromClr takes but the rule refuses +/// would take a working result away from clients. +/// +[Trait("Category", "Unit")] +public sealed class SdkValueBoundaryScriptResultTests +{ + public static TheoryData Values() => new() + { + // publishable + { "bool", true }, { "sbyte", (sbyte)1 }, { "byte", (byte)1 }, { "short", (short)1 }, { "ushort", (ushort)1 }, + { "int", 1 }, { "uint", 1u }, { "long", 1L }, { "ulong", 1UL }, { "float", 1f }, { "double", 1.0 }, + { "string", "s" }, { "DateTime", DateTime.UtcNow }, { "Guid", Guid.NewGuid() }, + { "int[]", new[] { 1 } }, { "byte[]", new byte[] { 1 } }, { "string[]", new[] { "a", null! } }, + { "DateTime[]", new[] { DateTime.UtcNow } }, { "Guid[]", new[] { Guid.NewGuid() } }, { "int[][]", new[] { new[] { 1 } } }, + // not publishable + { "decimal", 1.5m }, { "decimal[]", new[] { 1.5m } }, { "enum", DayOfWeek.Monday }, { "enum[]", new[] { DayOfWeek.Monday } }, + { "TimeSpan", TimeSpan.FromSeconds(1) }, { "char", 'a' }, { "char[]", new[] { 'a' } }, + { "DateTimeOffset", DateTimeOffset.UnixEpoch }, { "KeyValuePair", new KeyValuePair(1, 2) }, + { "KeyValuePair[]", new[] { new KeyValuePair(1, 2) } }, { "tuple[]", new[] { (1, 2) } }, + { "double[,]", new double[1, 1] }, { "Guid?[]", new Guid?[] { Guid.Empty } }, + }; + + [Theory] + [MemberData(nameof(Values))] + public void The_script_result_rule_is_what_the_publish_path_takes(string name, object value) + { + var publishable = ScriptResultMaterializer.IsPublishable(value.GetType()); + bool taken; + try + { + SdkValueBoundary.FromClr(value); + taken = true; + } + catch (Exception) + { + taken = false; + } + publishable.ShouldBe(taken, name); + } + + [Fact] + public void Every_publishable_scalar_type_and_its_array_reach_the_publish_path() + { + foreach (var type in ScriptResultMaterializer.PublishableScalarTypes) + { + var scalar = type == typeof(string) ? "s" : Activator.CreateInstance(type)!; + Should.NotThrow(() => SdkValueBoundary.FromClr(scalar), type.Name); + Should.NotThrow(() => SdkValueBoundary.FromClr(Array.CreateInstance(type, 1)), type.Name + "[]"); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj index 92869a9a4..09c8e0966 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj @@ -20,6 +20,8 @@ + + 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 1c349b0f3..db0bfb00c 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs @@ -421,9 +421,16 @@ public sealed class ContainmentTests public async Task Unsupported_input_and_result_types_are_explicit_failures() { await using var runner = Scripts.Runner(Scripts.Options()); - var result = await runner.RunAsync(Scripts.Vt("pair", "return new System.Collections.Generic.KeyValuePair(1, 2);"), Ct); + // The one result shape the materializer passes (the OPC UA publish path carries it as an array of Variants) but + // the wire does not: a jagged array. Every other unpublishable result is refused by ScriptResultMaterializer in + // both runners alike since lmxopcua#1100 ("script threw: … cannot carry …", see ParityTests). + var result = await runner.RunAsync(Scripts.Vt("jagged", "return new[] { new[] { 1 } };"), Ct); result.Status.ShouldBe(ScriptRunStatus.Failed); - result.Reason!.ShouldStartWith("unsupported type: script returned a value of unsupported type System.Collections.Generic.KeyValuePair"); + result.Reason!.ShouldStartWith("unsupported type: script returned a value of unsupported type System.Int32[][]"); + + var pair = await runner.RunAsync(Scripts.Vt("pair", "return new System.Collections.Generic.KeyValuePair(1, 2);"), Ct); + pair.Status.ShouldBe(ScriptRunStatus.Failed); + pair.Reason!.ShouldStartWith("script threw: The script returned a value of type 'KeyValuePair', which an OPC UA node cannot carry"); // lmxopcua#1092: a returned List is no longer one of these — both runners copy it into a typed array first // (ScriptResultMaterializer), so it crosses the wire as int[] (this used to be the "unsupported type" example). @@ -431,8 +438,11 @@ public sealed class ContainmentTests list.Status.ShouldBe(ScriptRunStatus.Ok, list.Reason); list.Value.ShouldBeOfType().ShouldBe([1]); - var input = await runner.RunAsync(Scripts.Vt("guid", "return 1;", inputs: Scripts.Input("g", Guid.NewGuid())), Ct); + // lmxopcua#1100: a Guid input crosses now (GUID tag); a decimal one still has no tag. + var guid = await runner.RunAsync(Scripts.Vt("guid", "return 1;", inputs: Scripts.Input("g", Guid.NewGuid())), Ct); + guid.Status.ShouldBe(ScriptRunStatus.Ok, guid.Reason); + var input = await runner.RunAsync(Scripts.Vt("decimal", "return 1;", inputs: Scripts.Input("d", 1.5m)), Ct); input.Status.ShouldBe(ScriptRunStatus.Failed); - input.Reason!.ShouldStartWith("unsupported type: input 'g' has a value of unsupported type System.Guid"); + input.Reason!.ShouldStartWith("unsupported type: input 'd' has a value of unsupported type System.Decimal"); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs index a817e633d..cf1321634 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs @@ -58,6 +58,8 @@ public sealed class ParityTests { "bool", true }, { "sbyte", (sbyte)-2 }, { "byte", (byte)2 }, { "short", (short)-3 }, { "ushort", (ushort)3 }, { "int", -4 }, { "uint", 4u }, { "long", -5L }, { "ulong", 5UL }, { "float", 1.25f }, { "double", 2.5 }, { "string", "s" }, { "System.DateTime", new DateTime(2026, 11, 9, 0, 0, 0, DateTimeKind.Utc) }, + // lmxopcua#1100: a Guid input used to fail "unsupported type" out of process. + { "System.Guid", new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }, }; /// @@ -103,6 +105,24 @@ public sealed class ParityTests { "queue", "var q = new System.Collections.Generic.Queue(); q.Enqueue(3); q.Enqueue(4); return q;" }, { "list of object", "return new System.Collections.Generic.List { 1, \"a\" };" }, { "nested list", "return new System.Collections.Generic.List> { new() { 1 } };" }, + // lmxopcua#1100: both runners return what the OPC UA publish path can represent. A Guid (scalar, array, collection) + // is an OPC UA built-in: in process it always reached the client, and the wire now carries it (it was "unsupported + // type" out of process). A KeyValuePair[] — what a returned Dictionary becomes — a decimal, an enum, a TimeSpan or a + // char has no OPC UA representation: in process the node write threw and the node silently kept its old value and + // status, out of process it was "unsupported type"; now both refuse it with the same script-threw reason. + { "guid", "return new System.Guid(\"0f8fad5b-d9cb-469f-a165-70867728950e\");" }, + { "guid array", "return new[] { System.Guid.Empty, new System.Guid(\"0f8fad5b-d9cb-469f-a165-70867728950e\") };" }, + { "guid list", "return new System.Collections.Generic.List { System.Guid.Empty };" }, + { "dictionary", "return new System.Collections.Generic.Dictionary { [1] = 1.5 };" }, + { "key-value pair array", "return new[] { new System.Collections.Generic.KeyValuePair(\"a\", 1) };" }, + { "lazy key-value pairs", "return new System.Collections.Generic.Dictionary { [1] = 2 }.Where(p => p.Key > 0);" }, + { "key-value pair", "return new System.Collections.Generic.KeyValuePair(1, 2);" }, + { "decimal", "return 1.5m;" }, + { "decimal array", "return new[] { 1.5m };" }, + { "enum", "return System.DayOfWeek.Monday;" }, + { "time span", "return System.TimeSpan.FromSeconds(1);" }, + { "char array", "return new[] { 'a' };" }, + { "two-dimensional array", "return new double[1, 1];" }, }; [Theory] @@ -144,6 +164,35 @@ public sealed class ParityTests } } + /// + /// lmxopcua#1100 controls for the rows above, which would also pass if both runners refused everything or returned + /// everything: a Guid array is the same Guid[] in both runners, and a dictionary is refused in both with the + /// reason that says what to return instead. + /// + [Fact] + public async Task A_guid_array_crosses_and_a_dictionary_is_refused_in_both_runners() + { + using var inProcess = new InProcessScriptRunner(); + await using var outOfProcess = Scripts.Runner(Scripts.Options()); + var guid = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e"); + var guids = Scripts.Vt("result-guid-control", $"return new[] {{ System.Guid.Empty, new System.Guid(\"{guid}\") }};"); + var dictionary = Scripts.Vt("result-dictionary-control", "return new System.Collections.Generic.Dictionary { [1] = 1.5 };"); + + foreach (var outcome in new[] { await inProcess.RunAsync(guids, Ct), await outOfProcess.RunAsync(guids, Ct) }) + { + outcome.Status.ShouldBe(ScriptRunStatus.Ok, outcome.Reason); + outcome.Value.ShouldBeOfType().ShouldBe([Guid.Empty, guid]); + } + foreach (var outcome in new[] { await inProcess.RunAsync(dictionary, Ct), await outOfProcess.RunAsync(dictionary, Ct) }) + { + outcome.Status.ShouldBe(ScriptRunStatus.Failed); + outcome.Reason.ShouldBe( + "script threw: The script returned a value of type 'KeyValuePair[]', which an OPC UA node cannot carry; " + + "return null, a bool, an integer type, float, double, string, DateTime or Guid, or a one-dimensional array of one of " + + "them (convert first, e.g. Convert.ToDouble(x) for a decimal, or the keys and values of a dictionary as two arrays)."); + } + } + [Fact] public async Task The_worker_holds_a_lazy_result_to_the_configured_cap() { 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 06b50dbd8..a7a91c75d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs @@ -20,6 +20,8 @@ public sealed class ProtocolTests 1.5f, double.NaN, 3.25, "text", string.Empty, new DateTime(2026, 11, 9, 1, 2, 3, DateTimeKind.Utc), new[] { 1, 2, 3 }, new short[] { -1, 1 }, new[] { "a", "b" }, new[] { true, false }, Array.Empty(), new[] { new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc) }, (short)0, 0, 0L, 0.0, + // lmxopcua#1100: GUID tag (additive). + new Guid("0f8fad5b-d9cb-469f-a165-70867728950e"), Guid.Empty, new[] { Guid.Empty, new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") }, ]; return values.Select(v => new[] { v }); } @@ -54,13 +56,38 @@ public sealed class ProtocolTests [Fact] public void Unsupported_types_are_refused_not_converted() { - foreach (var value in new object[] { new List { 1 }, 1.5m, Guid.NewGuid(), new { A = 1 }, new int[1, 1], new object[] { 1 } }) + foreach (var value in new object[] + { + new List { 1 }, 1.5m, TimeSpan.FromSeconds(1), new { A = 1 }, new int[1, 1], new object[] { 1 }, + new[] { new KeyValuePair(1, 2) }, + }) { VariantCodec.TryEncode(value, out _, out var type).ShouldBeFalse(value.GetType().Name); type.ShouldNotBeNullOrEmpty(); } } + /// + /// lmxopcua#1100: the wire carries every type a script result may have (, + /// scalar and one-dimensional array), so nothing the materializer passes can fail "unsupported type" in the worker + /// alone — the divergence this issue was about (a Guid gave a value in process, "unsupported type" out of process). + /// + [Fact] + public void The_wire_carries_every_publishable_result_type_scalar_and_array() + { + foreach (var type in Core.Scripting.ScriptResultMaterializer.PublishableScalarTypes) + { + var scalar = type == typeof(string) ? "s" : Activator.CreateInstance(type)!; + var array = Array.CreateInstance(type, 2); + array.SetValue(scalar, 0); + foreach (var value in new[] { scalar, array }) + { + VariantCodec.TryEncode(value, out var variant, out var unsupported).ShouldBeTrue($"{value.GetType().Name}: {unsupported}"); + VariantCodec.Decode(Variant.Parser.ParseFrom(variant.ToByteArray()))!.GetType().ShouldBe(value.GetType()); + } + } + } + [Fact] public void Local_datetime_crosses_as_utc() { @@ -85,6 +112,8 @@ public sealed class ProtocolTests 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)); + Should.Throw(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Guid, G = ByteString.CopyFrom(new byte[15]) })); + Should.Throw(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Guid, S = "x" })); } private static Envelope Sample() => new()