fix(scripting): #1104 a jagged-array script result is refused identically in both runners

int[][] / byte[][] used to be the one result divergence left after #1100: in process
ScriptResultMaterializer passed it (SdkValueBoundary.FromClr carries it as an array of Variants),
while the worker's wire has no nested-array tag and answered "unsupported type". A script-fed node
has a scalar DataType, so a Variant-of-arrays value is not what it declares either; not documented as
a feature anywhere (only noted as the known divergence). Decision: refuse, via the shared rule.

- IsPublishable: a 1-D array's element must be a PublishableScalarTypes scalar (no recursion).
- EnsurePublishable: a nested array gets its own reason, still "... which an OPC UA node cannot
  carry: an array of arrays ...", with a flatten hint (SelectMany). Same "script threw: ..." text in
  both runners.
- SdkValueBoundaryScriptResultTests: int[][] leaves the rule==FromClr theory; a separate fact pins
  the one deliberate difference (FromClr takes it, the rule refuses).
- ParityTests: "jagged array" + "jagged byte array" rows. ShadowModeTests census: the jagged script
  now MATCHES; the unsupported_type mismatch is exercised by a decimal INPUT (design §14 #11), the
  real remaining worker-only refusal.
- ContainmentTests.Unsupported_input_and_result_types: jagged now expects the materializer reason.

Mutation: restoring the recursive element check fails 4 tests (2 parity rows, shadow census,
containment unsupported-type).

Behaviour change: a value script returning a jagged array now fails (Bad + script log) in process
too, instead of publishing a Variant array onto a scalar-typed node.
This commit is contained in:
Joseph Doherty
2026-12-04 20:31:25 -05:00
parent ce0133b03c
commit d81990bcbf
7 changed files with 76 additions and 17 deletions
+2 -1
View File
@@ -273,7 +273,8 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`:
return null, a `bool`, an integer type, `float`, `double`, `string`, `DateTime` or `Guid`, or a 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 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` the server's OPC UA value boundary turns into a built-in Variant). Anything else — a `Dictionary`
(it becomes `KeyValuePair<K,V>[]`), a `decimal`, an enum, a `TimeSpan`, a `char`, a tuple, a 2-D array — (it becomes `KeyValuePair<K,V>[]`), a `decimal`, an enum, a `TimeSpan`, a `char`, a tuple, a 2-D array, a
jagged array (`int[][]` — #1104; it used to publish in process only, flatten it with `SelectMany`) —
fails the run (Bad, script log) in both runners with `script threw: The script returned a value of type 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 '…', 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 "succeed" and then fail inside the node write, so the node silently kept its previous value and status
+4 -3
View File
@@ -137,9 +137,10 @@ processes:
`KeyValuePair<K,V>[]` — what a returned `Dictionary` becomes — a `decimal`, an enum, a `TimeSpan`, …) is refused by `KeyValuePair<K,V>[]` — 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 `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 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 previous value and status with only a server-log warning). A jagged array
(`int[][]`): the publish path carries it (as an array of Variants) and the in-process runner returns it, but the wire (`int[][]`, `byte[][]`) is refused the same way since lmxopcua#1104 (`… cannot carry: an array of arrays …`, with a
has no nested-array tag, so the worker answers `unsupported type`. A returned collection (`List<double>`) is copied flatten hint): it used to be the one result divergence — in process it was published as an array of Variants on a node
whose DataType is a scalar type, while the wire has no nested-array tag and the worker answered `unsupported type`. A returned collection (`List<double>`) is copied
into a typed array by both runners first (lmxopcua#1092). into a typed array by both runners first (lmxopcua#1092).
- **Attribution happens before release.** The worker's exit path runs attribution (strike, quarantine, suspect - **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 marks) synchronously **before** it completes any evaluation the worker held, so a script killed for its deadline is
@@ -102,15 +102,21 @@ public static class ScriptResultMaterializer
/// <summary> /// <summary>
/// Whether a returned value of <paramref name="type"/> can reach an OPC UA client (lmxopcua#1100): a /// Whether a returned value of <paramref name="type"/> can reach an OPC UA client (lmxopcua#1100): a
/// <see cref="PublishableScalarTypes"/> scalar, or a one-dimensional array whose element type is publishable /// <see cref="PublishableScalarTypes"/> scalar, or a one-dimensional array whose element type is one.
/// (a jagged array of them included — the publish path carries it as an array of Variants).
/// </summary> /// </summary>
/// <remarks>
/// A jagged array (<c>int[][]</c>, <c>byte[][]</c>) is refused (lmxopcua#1104), although
/// <c>SdkValueBoundary.FromClr</c> would take it as an array of Variants: a script-fed node has a scalar DataType
/// (Int32 with ValueRank one dimension, say), so a Variant-of-arrays value is not what its DataType declares, and
/// the out-of-process wire has no nested-array tag — the in-process runner published it while the worker answered
/// "unsupported type". Refused here, inside the run, both runners fail it with the same reason.
/// </remarks>
/// <param name="type">The runtime type of the returned value.</param> /// <param name="type">The runtime type of the returned value.</param>
/// <returns><c>true</c> when the publish path can represent the value.</returns> /// <returns><c>true</c> when the publish path can represent the value.</returns>
public static bool IsPublishable(Type type) public static bool IsPublishable(Type type)
{ {
if (type.IsArray) if (type.IsArray)
return type.GetArrayRank() == 1 && !type.IsVariableBoundArray && IsPublishable(type.GetElementType()!); return type.GetArrayRank() == 1 && !type.IsVariableBoundArray && PublishableScalarTypes.Contains(type.GetElementType()!);
return PublishableScalarTypes.Contains(type); return PublishableScalarTypes.Contains(type);
} }
@@ -122,6 +128,11 @@ public static class ScriptResultMaterializer
private static void EnsurePublishable(Type type) private static void EnsurePublishable(Type type)
{ {
if (IsPublishable(type)) return; if (IsPublishable(type)) return;
if (type.IsArray && type.GetElementType()!.IsArray)
throw new ScriptResultException(
$"The script returned a value of type '{Describe(type)}', which an OPC UA node cannot carry: an array of " +
"arrays has no representation on a node whose DataType is a scalar type; return one flat one-dimensional " +
"array (e.g. a.SelectMany(x => x).ToArray()) or publish each inner array from its own tag.");
throw new ScriptResultException( throw new ScriptResultException(
$"The script returned a value of type '{Describe(type)}', which an OPC UA node cannot carry; return null, " + $"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 " + "a bool, an integer type, float, double, string, DateTime or Guid, or a one-dimensional array of one of them " +
@@ -100,6 +100,26 @@ public sealed class ScriptResultMaterializerTests
.Message.ShouldStartWith("The script returned a value of type 'KeyValuePair<String, Int32>[]'"); .Message.ShouldStartWith("The script returned a value of type 'KeyValuePair<String, Int32>[]'");
} }
/// <summary>
/// lmxopcua#1104: an array of arrays is refused in both runners (the in-process runner used to publish it as an
/// array of Variants, the worker answered "unsupported type"), with a reason that says to flatten it — a
/// <c>byte[][]</c> included. The scalar-array positive controls are in
/// <see cref="Every_publishable_type_passes_scalar_and_array_positive_controls"/>.
/// </summary>
[Fact]
public void A_jagged_array_is_refused_with_a_flatten_hint()
{
foreach (var value in new object[] { new[] { new[] { 1 } }, new[] { new byte[] { 1 } }, new[] { new[] { "a" } }, new[] { new[] { new[] { 1.0 } } } })
{
ScriptResultMaterializer.IsPublishable(value.GetType()).ShouldBeFalse(value.GetType().Name);
var message = Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(value, 100), value.GetType().Name).Message;
message.ShouldContain("which an OPC UA node cannot carry: an array of arrays");
message.ShouldContain("SelectMany");
}
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new[] { new[] { 1 } }, 100))
.Message.ShouldStartWith("The script returned a value of type 'Int32[][]'");
}
[Fact] [Fact]
public void An_unpublishable_lazy_sequence_is_refused_before_it_runs() public void An_unpublishable_lazy_sequence_is_refused_before_it_runs()
{ {
@@ -116,8 +136,6 @@ public sealed class ScriptResultMaterializerTests
ScriptResultMaterializer.Materialize(guid, 100).ShouldBe(guid); ScriptResultMaterializer.Materialize(guid, 100).ShouldBe(guid);
ScriptResultMaterializer.Materialize(new[] { guid }, 100).ShouldBeOfType<Guid[]>(); ScriptResultMaterializer.Materialize(new[] { guid }, 100).ShouldBeOfType<Guid[]>();
ScriptResultMaterializer.Materialize(new List<Guid> { guid }, 100).ShouldBeOfType<Guid[]>().ShouldBe([guid]); ScriptResultMaterializer.Materialize(new List<Guid> { guid }, 100).ShouldBeOfType<Guid[]>().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<int[][]>();
foreach (var type in ScriptResultMaterializer.PublishableScalarTypes) foreach (var type in ScriptResultMaterializer.PublishableScalarTypes)
{ {
var scalar = type == typeof(string) ? "s" : Activator.CreateInstance(type)!; var scalar = type == typeof(string) ? "s" : Activator.CreateInstance(type)!;
@@ -21,7 +21,7 @@ public sealed class SdkValueBoundaryScriptResultTests
{ "int", 1 }, { "uint", 1u }, { "long", 1L }, { "ulong", 1UL }, { "float", 1f }, { "double", 1.0 }, { "int", 1 }, { "uint", 1u }, { "long", 1L }, { "ulong", 1UL }, { "float", 1f }, { "double", 1.0 },
{ "string", "s" }, { "DateTime", DateTime.UtcNow }, { "Guid", Guid.NewGuid() }, { "string", "s" }, { "DateTime", DateTime.UtcNow }, { "Guid", Guid.NewGuid() },
{ "int[]", new[] { 1 } }, { "byte[]", new byte[] { 1 } }, { "string[]", new[] { "a", null! } }, { "int[]", new[] { 1 } }, { "byte[]", new byte[] { 1 } }, { "string[]", new[] { "a", null! } },
{ "DateTime[]", new[] { DateTime.UtcNow } }, { "Guid[]", new[] { Guid.NewGuid() } }, { "int[][]", new[] { new[] { 1 } } }, { "DateTime[]", new[] { DateTime.UtcNow } }, { "Guid[]", new[] { Guid.NewGuid() } },
// not publishable // not publishable
{ "decimal", 1.5m }, { "decimal[]", new[] { 1.5m } }, { "enum", DayOfWeek.Monday }, { "enum[]", new[] { DayOfWeek.Monday } }, { "decimal", 1.5m }, { "decimal[]", new[] { 1.5m } }, { "enum", DayOfWeek.Monday }, { "enum[]", new[] { DayOfWeek.Monday } },
{ "TimeSpan", TimeSpan.FromSeconds(1) }, { "char", 'a' }, { "char[]", new[] { 'a' } }, { "TimeSpan", TimeSpan.FromSeconds(1) }, { "char", 'a' }, { "char[]", new[] { 'a' } },
@@ -48,6 +48,20 @@ public sealed class SdkValueBoundaryScriptResultTests
publishable.ShouldBe(taken, name); publishable.ShouldBe(taken, name);
} }
/// <summary>
/// lmxopcua#1104: the one deliberate difference — the rule is STRICTER than <see cref="SdkValueBoundary.FromClr"/>
/// for an array of arrays. FromClr takes it (an array of Variants), but a script-fed node's DataType is a scalar
/// type, so that value is not what the node declares, and the worker's wire cannot carry it; both runners refuse
/// it. Pinned here so a FromClr change that stopped taking it shows this exception can go.
/// </summary>
[Fact]
public void A_jagged_array_is_refused_by_the_rule_although_the_boundary_would_take_it()
{
var jagged = new[] { new[] { 1 } };
Should.NotThrow(() => SdkValueBoundary.FromClr(jagged));
ScriptResultMaterializer.IsPublishable(jagged.GetType()).ShouldBeFalse();
}
[Fact] [Fact]
public void Every_publishable_scalar_type_and_its_array_reach_the_publish_path() public void Every_publishable_scalar_type_and_its_array_reach_the_publish_path()
{ {
@@ -123,6 +123,10 @@ public sealed class ParityTests
{ "time span", "return System.TimeSpan.FromSeconds(1);" }, { "time span", "return System.TimeSpan.FromSeconds(1);" },
{ "char array", "return new[] { 'a' };" }, { "char array", "return new[] { 'a' };" },
{ "two-dimensional array", "return new double[1, 1];" }, { "two-dimensional array", "return new double[1, 1];" },
// lmxopcua#1104: an array of arrays — in process it used to publish (as an array of Variants) while the worker
// answered "unsupported type"; both now refuse it with the same flatten hint.
{ "jagged array", "return new[] { new[] { 1, 2 }, new[] { 3 } };" },
{ "jagged byte array", "return new[] { new byte[] { 1 } };" },
}; };
[Theory] [Theory]
@@ -102,18 +102,28 @@ public sealed class ShadowModeTests
["quality"] = "return ctx.GetTag(\"i\").StatusCode;", ["quality"] = "return ctx.GetTag(\"i\").StatusCode;",
["throws"] = "if ((int)ctx.GetTag(\"i\").Value >= 0) throw new InvalidOperationException(\"boom \" + ctx.GetTag(\"i\").Value); return 0;", ["throws"] = "if ((int)ctx.GetTag(\"i\").Value >= 0) throw new InvalidOperationException(\"boom \" + ctx.GetTag(\"i\").Value); return 0;",
["divergent"] = $"return {InWorker} ? 2 : 1;", ["divergent"] = $"return {InWorker} ? 2 : 1;",
// lmxopcua#1100: a decimal is refused by both runners alike now (no OPC UA node can carry it), so it MATCHES; // lmxopcua#1100: a decimal RESULT is refused by both runners alike (no OPC UA node can carry it), so it MATCHES;
// the one result shape left that only the worker refuses is a jagged array (no nested-array wire tag). // lmxopcua#1104: so is a jagged array now (it used to be the one result only the worker refused).
["decimal"] = "return 1.5m;", ["decimal"] = "return 1.5m;",
["jagged"] = "return new[] { new[] { (int)ctx.GetTag(\"i\").Value } };", ["jagged"] = "return new[] { new[] { (int)ctx.GetTag(\"i\").Value } };",
// What only the worker refuses is an INPUT with no wire tag (design §14 #11): in process a decimal input is
// read and converted, the worker answers "unsupported type". Fed only to this script (see InputsFor).
["decimalInput"] = "return Convert.ToDouble(ctx.GetTag(\"m\").Value);",
}; };
Dictionary<string, DataValueSnapshot> InputsFor(string key, int i)
{
var inputs = Inputs(i);
if (key == "decimalInput")
inputs["m"] = new DataValueSnapshot(1.5m + i, 0u, DateTime.UtcNow, DateTime.UtcNow);
return inputs;
}
for (var i = 0; i < 3; i++) for (var i = 0; i < 3; i++)
{ {
foreach (var (key, source) in scripts) foreach (var (key, source) in scripts)
{ {
var published = await shadowed.EvaluateAsync(key, source, Inputs(i), Ct); var published = await shadowed.EvaluateAsync(key, source, InputsFor(key, i), Ct);
var expected = await reference.EvaluateAsync(key, source, Inputs(i), Ct); var expected = await reference.EvaluateAsync(key, source, InputsFor(key, i), Ct);
Same(published, expected).ShouldBeTrue($"{key}: Shadow publishes exactly what InProcess publishes ({published} vs {expected})"); Same(published, expected).ShouldBeTrue($"{key}: Shadow publishes exactly what InProcess publishes ({published} vs {expected})");
} }
(await shadow.WaitIdleAsync(TimeSpan.FromSeconds(60))).ShouldBeTrue(); (await shadow.WaitIdleAsync(TimeSpan.FromSeconds(60))).ShouldBeTrue();
@@ -125,12 +135,12 @@ public sealed class ShadowModeTests
stats.Compared.ShouldBe(scripts.Count * 3); stats.Compared.ShouldBe(scripts.Count * 3);
stats.Mismatched.ShouldBe(6, string.Join(Environment.NewLine, shadow.Mismatches.Select(m => $"{m.Key}: {m.LastReason} — {m.LastSummary}"))); stats.Mismatched.ShouldBe(6, string.Join(Environment.NewLine, shadow.Mismatches.Select(m => $"{m.Key}: {m.LastReason} — {m.LastSummary}")));
var mismatches = shadow.Mismatches.ToDictionary(m => m.Key); var mismatches = shadow.Mismatches.ToDictionary(m => m.Key);
mismatches.Keys.ShouldBe(["jagged", "divergent"], ignoreOrder: true); mismatches.Keys.ShouldBe(["decimalInput", "divergent"], ignoreOrder: true);
mismatches["divergent"].LastReason.ShouldBe("value"); mismatches["divergent"].LastReason.ShouldBe("value");
mismatches["divergent"].LastSummary.ShouldBe("published Ok Int32 1; shadow Ok Int32 2"); mismatches["divergent"].LastSummary.ShouldBe("published Ok Int32 1; shadow Ok Int32 2");
mismatches["divergent"].Count.ShouldBe(3); mismatches["divergent"].Count.ShouldBe(3);
mismatches["jagged"].LastReason.ShouldBe("unsupported_type"); mismatches["decimalInput"].LastReason.ShouldBe("unsupported_type");
mismatches["jagged"].LastSummary.ShouldContain("System.Int32[][]"); mismatches["decimalInput"].LastSummary.ShouldContain("System.Decimal");
var lines = log.Events.Where(e => e.MessageTemplate.Text.StartsWith("Script shadow mismatch", StringComparison.Ordinal)).ToArray(); var lines = log.Events.Where(e => e.MessageTemplate.Text.StartsWith("Script shadow mismatch", StringComparison.Ordinal)).ToArray();
lines.Length.ShouldBe(2, "one line per script and reason"); lines.Length.ShouldBe(2, "one line per script and reason");