fix(scripting): #1092 a returned concrete collection (List<T>, HashSet<T>, ...) 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<double> 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<T> element type; an open element type (List<object>, List<List<int>>) or
none (ArrayList) is refused like the lazy equivalent. Both runners give double[] for a
List<double>.

ParityTests.Result_materialisation_and_the_element_cap_agree gains list / at-cap / over-cap
/ hash set / queue / List<object> / nested-list rows plus a positive control (6 rows + the
control fail against the old materializer). ContainmentTests' "unsupported result type"
example moves from List<int> (now int[]) to KeyValuePair<int,int>.

Behaviour change: a script returning List<object> (or another open element type) now fails
the run (Bad + script log) in process too, as the lazy form already did.
This commit is contained in:
Joseph Doherty
2026-12-04 15:14:16 -05:00
parent bd4fff6444
commit 61546d5aab
6 changed files with 94 additions and 21 deletions
+5 -1
View File
@@ -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<double>`, `HashSet<string>`, `Queue<long>`, …) 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<object>`) — 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
+5 -3
View File
File diff suppressed because one or more lines are too long
@@ -26,13 +26,19 @@ public sealed class ScriptResultException : InvalidOperationException
/// <c>maxElements</c>.
/// </para>
/// <para>
/// What changes: a lazy sequence (an <see cref="IEnumerable"/> that is neither an array, a string nor an
/// <see cref="ICollection"/>) becomes a typed <c>T[]</c> of its <c>IEnumerable&lt;T&gt;</c> element type. A
/// sequence whose element type could itself be a sequence (<c>object</c>, 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 <c>ForbiddenTypeAnalyzer</c>). 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 <c>List&lt;double&gt;</c> or a <c>HashSet&lt;string&gt;</c> — becomes a typed <c>T[]</c> of its
/// <c>IEnumerable&lt;T&gt;</c> element type. A sequence whose element type could itself be a sequence
/// (<c>object</c>, 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 <c>ForbiddenTypeAnalyzer</c>). 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.
/// </para>
/// <para>
/// Concrete collections used to be returned as-is too (lmxopcua#1092): in process the host got the
/// <c>List&lt;T&gt;</c> 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.
/// </para>
/// <para>
/// 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<T> element type; " +
$"The script returned a {what} ({sequence.GetType().Name}) with no IEnumerable<T> 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<object?>();
@@ -117,6 +123,11 @@ public static class ScriptResultMaterializer
return found;
}
// ICollection<T> / IReadOnlyCollection<T> without the non-generic ICollection (HashSet<T>, …): 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));
@@ -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<int> { 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();
}
/// <summary>
/// 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.
/// </summary>
[Fact]
public void A_concrete_collection_becomes_a_typed_array()
{
ScriptResultMaterializer.Materialize(new List<int> { 1, 2 }, 100).ShouldBeOfType<int[]>().ShouldBe([1, 2]);
ScriptResultMaterializer.Materialize(new HashSet<string> { "a" }, 100).ShouldBeOfType<string[]>().ShouldBe(["a"]);
ScriptResultMaterializer.Materialize(new Queue<double>([1.5]), 100).ShouldBeOfType<double[]>().ShouldBe([1.5]);
ScriptResultMaterializer.Materialize(new List<int>(new int[100]), 100).ShouldBeOfType<int[]>().Length.ShouldBe(100);
}
[Fact]
public void A_collection_of_an_open_or_unknown_element_type_is_refused_like_a_lazy_one()
{
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new List<object> { 1 }, 100))
.Message.ShouldContain("collection of 'Object'");
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new List<List<int>> { new() { 1 } }, 100));
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new System.Collections.ArrayList { 1 }, 100))
.Message.ShouldContain("no IEnumerable<T> element type");
}
[Fact]
public void An_oversized_array_or_collection_is_refused_by_the_same_cap()
{
@@ -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<int> { 1 };"), Ct);
var result = await runner.RunAsync(Scripts.Vt("pair", "return new System.Collections.Generic.KeyValuePair<int, int>(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<T> 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<int> { 1 };"), Ct);
list.Status.ShouldBe(ScriptRunStatus.Ok, list.Reason);
list.Value.ShouldBeOfType<int[]>().ShouldBe([1]);
var input = await runner.RunAsync(Scripts.Vt("guid", "return 1;", inputs: Scripts.Input("g", Guid.NewGuid())), Ct);
input.Status.ShouldBe(ScriptRunStatus.Failed);
@@ -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<string>();" },
// 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<double> { 1.5, 2.5 };" },
{ "at-cap list", "return new System.Collections.Generic.List<int> { 1, 2, 3, 4 };" },
{ "over-cap list", "return new System.Collections.Generic.List<double>(new double[5]);" },
{ "hash set", "return new System.Collections.Generic.HashSet<string> { \"a\" };" },
{ "queue", "var q = new System.Collections.Generic.Queue<long>(); q.Enqueue(3); q.Enqueue(4); return q;" },
{ "list of object", "return new System.Collections.Generic.List<object> { 1, \"a\" };" },
{ "nested list", "return new System.Collections.Generic.List<System.Collections.Generic.List<int>> { new() { 1 } };" },
};
[Theory]
@@ -115,6 +124,26 @@ public sealed class ParityTests
Same(actual.Value, expected.Value, name);
}
/// <summary>
/// lmxopcua#1092 positive control for the theory above (it would also pass if both runners refused a List): a
/// returned <c>List&lt;double&gt;</c> is the same <c>double[]</c> in both runners.
/// </summary>
[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<double> { 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<double[]>().ShouldBe([1.5, 2.5]);
}
}
[Fact]
public async Task The_worker_holds_a_lazy_result_to_the_configured_cap()
{