From 61546d5aab353c77d1e22da53c4634aff1787607 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Fri, 4 Dec 2026 15:14:16 -0500 Subject: [PATCH] fix(scripting): #1092 a returned concrete collection (List, HashSet, ...) is materialised into the same typed array in both runners ScriptResultMaterializer returned a non-array ICollection as-is (capped by Count only), so in process the host got the List itself while the out-of-process worker, whose wire carries arrays but no collection type, answered "unsupported type" for the same script. Every non-array, non-string sequence now goes through the one materialisation: a collection is held to Scripting:MaxResultElements by its Count before it is copied, then becomes T[] of its IEnumerable element type; an open element type (List, List>) or none (ArrayList) is refused like the lazy equivalent. Both runners give double[] for a List. ParityTests.Result_materialisation_and_the_element_cap_agree gains list / at-cap / over-cap / hash set / queue / List / nested-list rows plus a positive control (6 rows + the control fail against the old materializer). ContainmentTests' "unsupported result type" example moves from List (now int[]) to KeyValuePair. Behaviour change: a script returning List (or another open element type) now fails the run (Bad + script log) in process too, as the lazy form already did. --- docs/ScriptEditor.md | 6 +++- docs/VirtualTags.md | 8 +++-- .../ScriptResultMaterializer.cs | 35 ++++++++++++------- .../ScriptResultMaterializerTests.cs | 27 ++++++++++++-- .../ContainmentTests.cs | 10 ++++-- .../ParityTests.cs | 29 +++++++++++++++ 6 files changed, 94 insertions(+), 21 deletions(-) diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index b17eb4778..1ef65b1ec 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -264,7 +264,11 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: caps a returned array / collection) with a failed run (Bad, script log) — not a timeout strike. A lazy sequence whose element type is `object`, an interface or another collection is refused: the host copies and compares a returned array recursively, so an open-slot array can nest or contain itself. - Arrays, lists, strings and scalars are unchanged. **Still in-process-only limits** (the boundary is + A concrete collection (`List`, `HashSet`, `Queue`, …) gets the same treatment + 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 `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 4f363c940..7ead34ff2 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); 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). **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,8 +130,10 @@ 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 `List`, a `Guid`) - is an explicit `unsupported type: …` failure rather than a conversion — a behaviour change from in process. + `(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. - **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/ScriptResultMaterializer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs index e055a8a0d..10d105118 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs @@ -26,13 +26,19 @@ public sealed class ScriptResultException : InvalidOperationException /// maxElements. /// /// -/// What changes: a lazy sequence (an that is neither an array, a string nor an -/// ) becomes a typed T[] of its IEnumerable<T> element type. A -/// sequence whose element type could itself be a sequence (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 and already-concrete collections are returned as-is (they -/// were fully built by the run) but are still held to the element cap. Everything else — scalars, strings, -/// null — is untouched. +/// What changes: every sequence that is not an array or a string — a lazy one, or a concrete collection such as +/// a List<double> or a HashSet<string> — becomes a typed T[] of its +/// IEnumerable<T> element type. A sequence whose element type could itself be a sequence +/// (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. +/// +/// +/// Concrete collections used to be returned as-is too (lmxopcua#1092): in process the host got the +/// List<T> itself, while the out-of-process worker, whose wire carries arrays but no collection +/// type, answered "unsupported type" for the same script. Copying a collection into an array is the one value +/// both runners can give; a collection that reports its size is held to the cap BEFORE it is copied. /// /// /// This does NOT make the in-process runner a hard sandbox: memory exhaustion inside the run and a @@ -64,23 +70,23 @@ public static class ScriptResultMaterializer return array; case ICollection collection: EnforceCap(collection.Count, maxElements); - return value; + return MaterializeSequence(collection, maxElements, "collection"); case IEnumerable sequence: - return MaterializeLazy(sequence, maxElements); + return MaterializeSequence(sequence, maxElements, IsGenericCollection(sequence.GetType()) ? "collection" : "lazy sequence"); default: return value; } } - private static object MaterializeLazy(IEnumerable sequence, int maxElements) + private static object MaterializeSequence(IEnumerable sequence, int maxElements, string what) { var elementType = ElementTypeOf(sequence.GetType()) ?? throw new ScriptResultException( - $"The script returned a lazy sequence ({sequence.GetType().Name}) with no IEnumerable element type; " + + $"The script returned a {what} ({sequence.GetType().Name}) with no IEnumerable element type; " + "return an array of a concrete type (double[], string[], …)."); if (IsOpenSlot(elementType)) throw new ScriptResultException( - $"The script returned a lazy sequence of '{elementType.Name}', which can contain another sequence or itself; " + + $"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[], …)."); var items = new List(); @@ -117,6 +123,11 @@ public static class ScriptResultMaterializer return found; } + // ICollection / IReadOnlyCollection without the non-generic ICollection (HashSet, …): only the wording. + private static bool IsGenericCollection(Type type) => + type.GetInterfaces().Any(i => i.IsGenericType + && (i.GetGenericTypeDefinition() == typeof(ICollection<>) || i.GetGenericTypeDefinition() == typeof(IReadOnlyCollection<>))); + private static bool IsOpenSlot(Type t) => t == typeof(object) || t.IsInterface || t.IsAbstract || (t != typeof(string) && typeof(IEnumerable).IsAssignableFrom(t)); 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 4b03c8eac..5464d5545 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 @@ -47,17 +47,38 @@ public sealed class ScriptResultMaterializerTests } [Fact] - public void Arrays_collections_strings_scalars_and_null_pass_through_unchanged_positive_controls() + public void Arrays_strings_scalars_and_null_pass_through_unchanged_positive_controls() { var array = new[] { 1.0, 2.0 }; ScriptResultMaterializer.Materialize(array, 100).ShouldBeSameAs(array); - var list = new List { 1, 2 }; - ScriptResultMaterializer.Materialize(list, 100).ShouldBeSameAs(list); ScriptResultMaterializer.Materialize("abc", 100).ShouldBe("abc"); ScriptResultMaterializer.Materialize(42, 100).ShouldBe(42); ScriptResultMaterializer.Materialize(null, 100).ShouldBeNull(); } + /// + /// lmxopcua#1092: a concrete collection becomes the same typed array a lazy sequence does — the out-of-process + /// worker's wire has no collection type, so returning the collection as-is made the two runners disagree. + /// + [Fact] + public void A_concrete_collection_becomes_a_typed_array() + { + ScriptResultMaterializer.Materialize(new List { 1, 2 }, 100).ShouldBeOfType().ShouldBe([1, 2]); + ScriptResultMaterializer.Materialize(new HashSet { "a" }, 100).ShouldBeOfType().ShouldBe(["a"]); + ScriptResultMaterializer.Materialize(new Queue([1.5]), 100).ShouldBeOfType().ShouldBe([1.5]); + ScriptResultMaterializer.Materialize(new List(new int[100]), 100).ShouldBeOfType().Length.ShouldBe(100); + } + + [Fact] + public void A_collection_of_an_open_or_unknown_element_type_is_refused_like_a_lazy_one() + { + Should.Throw(() => ScriptResultMaterializer.Materialize(new List { 1 }, 100)) + .Message.ShouldContain("collection of 'Object'"); + Should.Throw(() => ScriptResultMaterializer.Materialize(new List> { new() { 1 } }, 100)); + Should.Throw(() => ScriptResultMaterializer.Materialize(new System.Collections.ArrayList { 1 }, 100)) + .Message.ShouldContain("no IEnumerable element type"); + } + [Fact] public void An_oversized_array_or_collection_is_refused_by_the_same_cap() { 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 fcc5964da..1c349b0f3 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,15 @@ 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("list", "return new System.Collections.Generic.List { 1 };"), Ct); + var result = await runner.RunAsync(Scripts.Vt("pair", "return new System.Collections.Generic.KeyValuePair(1, 2);"), Ct); result.Status.ShouldBe(ScriptRunStatus.Failed); - result.Reason!.ShouldStartWith("unsupported type: script returned a value of unsupported type System.Collections.Generic.List"); + result.Reason!.ShouldStartWith("unsupported type: script returned a value of unsupported type System.Collections.Generic.KeyValuePair"); + + // 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). + var list = await runner.RunAsync(Scripts.Vt("list", "return new System.Collections.Generic.List { 1 };"), Ct); + 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); input.Status.ShouldBe(ScriptRunStatus.Failed); 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 c75a2f1d6..a817e633d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs @@ -94,6 +94,15 @@ public sealed class ParityTests { "over-cap array", "return new double[5];" }, { "at-cap array", "return new double[4];" }, { "empty lazy", "return System.Linq.Enumerable.Empty();" }, + // lmxopcua#1092: a concrete non-array collection. In process it used to come back as the List itself (capped by + // Count, but not an array), while the worker answered "unsupported type" — now both return the same typed array. + { "list", "return new System.Collections.Generic.List { 1.5, 2.5 };" }, + { "at-cap list", "return new System.Collections.Generic.List { 1, 2, 3, 4 };" }, + { "over-cap list", "return new System.Collections.Generic.List(new double[5]);" }, + { "hash set", "return new System.Collections.Generic.HashSet { \"a\" };" }, + { "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 } };" }, }; [Theory] @@ -115,6 +124,26 @@ public sealed class ParityTests Same(actual.Value, expected.Value, name); } + /// + /// lmxopcua#1092 positive control for the theory above (it would also pass if both runners refused a List): a + /// returned List<double> is the same double[] in both runners. + /// + [Fact] + public async Task A_returned_list_is_the_same_typed_array_in_both_runners() + { + using var inProcess = new InProcessScriptRunner(new ScriptingOptions { MaxResultElements = 4 }); + var options = Scripts.Options(); + options.MaxResultElements = 4; + await using var outOfProcess = Scripts.Runner(options); + var invocation = Scripts.Vt("result-list-control", "return new System.Collections.Generic.List { 1.5, 2.5 };"); + + foreach (var outcome in new[] { await inProcess.RunAsync(invocation, Ct), await outOfProcess.RunAsync(invocation, Ct) }) + { + outcome.Status.ShouldBe(ScriptRunStatus.Ok, outcome.Reason); + outcome.Value.ShouldBeOfType().ShouldBe([1.5, 2.5]); + } + } + [Fact] public async Task The_worker_holds_a_lazy_result_to_the_configured_cap() {