Merge #1104: jagged-array script results refused identically by both runners (flatten hint); ContainmentTests bounds assert ordering and are sized for ~1 s whole-process stalls
This commit is contained in:
@@ -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
|
||||
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<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
|
||||
'…', 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
|
||||
|
||||
+4
-3
@@ -137,9 +137,10 @@ processes:
|
||||
`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
|
||||
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<double>`) is copied
|
||||
previous value and status with only a server-log warning). A jagged array
|
||||
(`int[][]`, `byte[][]`) is refused the same way since lmxopcua#1104 (`… cannot carry: an array of arrays …`, with a
|
||||
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).
|
||||
- **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
|
||||
|
||||
@@ -102,15 +102,21 @@ public static class ScriptResultMaterializer
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// (a jagged array of them included — the publish path carries it as an array of Variants).
|
||||
/// <see cref="PublishableScalarTypes"/> scalar, or a one-dimensional array whose element type is one.
|
||||
/// </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>
|
||||
/// <returns><c>true</c> when the publish path can represent the value.</returns>
|
||||
public static bool IsPublishable(Type type)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -122,6 +128,11 @@ public static class ScriptResultMaterializer
|
||||
private static void EnsurePublishable(Type type)
|
||||
{
|
||||
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(
|
||||
$"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 " +
|
||||
|
||||
@@ -100,6 +100,26 @@ public sealed class ScriptResultMaterializerTests
|
||||
.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]
|
||||
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(new[] { guid }, 100).ShouldBeOfType<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)
|
||||
{
|
||||
var scalar = type == typeof(string) ? "s" : Activator.CreateInstance(type)!;
|
||||
|
||||
+15
-1
@@ -21,7 +21,7 @@ public sealed class SdkValueBoundaryScriptResultTests
|
||||
{ "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 } } },
|
||||
{ "DateTime[]", new[] { DateTime.UtcNow } }, { "Guid[]", new[] { Guid.NewGuid() } },
|
||||
// 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' } },
|
||||
@@ -48,6 +48,20 @@ public sealed class SdkValueBoundaryScriptResultTests
|
||||
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]
|
||||
public void Every_publishable_scalar_type_and_its_array_reach_the_publish_path()
|
||||
{
|
||||
|
||||
@@ -52,12 +52,19 @@ public sealed class ContainmentTests
|
||||
/// the caller gets the usual timeout at T, the worker is killed at T + G, the host burns no CPU on it, and the
|
||||
/// sibling on the same shard keeps working. Mutation check: with the hard-deadline kill disabled the worker is
|
||||
/// never killed and the Exited wait times out.
|
||||
/// <para>
|
||||
/// lmxopcua#1104: every wall-clock bound here is sized so a ~1 s whole-process stall (the loaded-box failure
|
||||
/// mode #1100 audited for the heartbeat bounds) cannot fail it, and the soft answer is checked as an ORDERING
|
||||
/// fact — it arrives while the worker is still alive, i.e. before the hard kill — rather than as T + 400 ms.
|
||||
/// The grace is therefore wide (2.5 s): the soft answer must beat T + G by more than a stall, and a stall that
|
||||
/// delayed the worker's soft-timeout notice past T + G would turn it into "script worker unresponsive".
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_runaway_script_is_killed_at_its_hard_deadline_and_its_sibling_keeps_working()
|
||||
{
|
||||
var softT = TimeSpan.FromMilliseconds(400);
|
||||
var grace = TimeSpan.FromMilliseconds(500);
|
||||
var grace = TimeSpan.FromMilliseconds(2500);
|
||||
await using var runner = Scripts.Runner(Scripts.Options(hardGrace: grace, quarantineAfterKills: 2));
|
||||
|
||||
(await runner.RunAsync(Scripts.Vt("sibling", Healthy), Ct)).Value.ShouldBe(7);
|
||||
@@ -70,23 +77,36 @@ public sealed class ContainmentTests
|
||||
var sw = Stopwatch.StartNew();
|
||||
var outcome = await runner.RunAsync(Scripts.Vt("runaway", runaway, softT, Scripts.Input("spin", 1)), Ct);
|
||||
var softElapsed = sw.Elapsed;
|
||||
var killedBeforeAnswer = worker.Exited.IsCompleted;
|
||||
outcome.Status.ShouldBe(ScriptRunStatus.Failed);
|
||||
// The soft timeout, not the transport deadline ("script worker unresponsive") and not the kill's fallout.
|
||||
outcome.Reason!.ShouldStartWith("script timed out after ");
|
||||
softElapsed.ShouldBeLessThan(softT + TimeSpan.FromMilliseconds(400), "the caller is answered at the soft deadline");
|
||||
// Ordering, not a tight bound: the caller is answered at the soft deadline, before the hard kill. A defect that
|
||||
// only answered the caller once the worker was killed would see Exited already completed here.
|
||||
killedBeforeAnswer.ShouldBeFalse("the caller is answered at the soft deadline, before the hard kill");
|
||||
softElapsed.ShouldBeLessThan(softT + grace, "the caller is answered before the hard deadline");
|
||||
|
||||
var exit = await worker.Exited.WaitAsync(TimeSpan.FromSeconds(10), Ct);
|
||||
var killElapsed = sw.Elapsed;
|
||||
exit.Reason.ShouldBe(WorkerExitReason.KilledDeadline);
|
||||
exit.CulpritKey.ShouldBe(InProcessScriptRunner.ScopedKey(ScriptContextKind.VirtualTag, "runaway"));
|
||||
// Not before the hard deadline (a stall only makes the kill later, so this lower bound is stall-proof)…
|
||||
killElapsed.ShouldBeGreaterThanOrEqualTo(softT + grace - TimeSpan.FromMilliseconds(50));
|
||||
// Design budget is T + G + 100 ms; the slack here is for a loaded CI box (process reap + exit notification).
|
||||
killElapsed.ShouldBeLessThan(softT + grace + TimeSpan.FromMilliseconds(1500));
|
||||
// …and AT it, not at some later backstop. Design budget is T + G + 100 ms; the slack covers process reap + exit
|
||||
// notification on a loaded box plus a ~1 s stall, and stays well under the 10 s Exited wait and under 2 × G, so a
|
||||
// kill driven by a second deadline period (or never) still fails.
|
||||
killElapsed.ShouldBeLessThan(softT + grace + TimeSpan.FromMilliseconds(2000));
|
||||
|
||||
// No orphan in the host: an in-process while(true) would burn one host core for the whole window.
|
||||
// No orphan in the host: an in-process while(true) would burn one host core for the whole window, i.e. CPU time
|
||||
// ≈ the wall time it ran. Asserted relative to the MEASURED window (a stall that stretches the window cannot fail
|
||||
// it, and gives a spinning orphan more CPU, not less), over a window long enough that ordinary host background
|
||||
// work (GC, JIT, the runner's timers) stays far below half of it.
|
||||
var cpuBefore = Process.GetCurrentProcess().TotalProcessorTime;
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(1500), Ct);
|
||||
var window = Stopwatch.StartNew();
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(3000), Ct);
|
||||
var cpuUsed = Process.GetCurrentProcess().TotalProcessorTime - cpuBefore;
|
||||
cpuUsed.ShouldBeLessThan(TimeSpan.FromMilliseconds(1000), "the runaway's thread died with its worker");
|
||||
var wall = window.Elapsed;
|
||||
cpuUsed.ShouldBeLessThan(wall / 2, $"the runaway's thread died with its worker ({cpuUsed.TotalMilliseconds:F0} ms CPU in {wall.TotalMilliseconds:F0} ms)");
|
||||
|
||||
// The sibling recovers on a fresh worker.
|
||||
(await runner.RunAsync(Scripts.Vt("sibling", Healthy), Ct)).Value.ShouldBe(7);
|
||||
@@ -291,11 +311,13 @@ public sealed class ContainmentTests
|
||||
var worker = runner.Shards[0].Current.ShouldNotBeNull();
|
||||
using var process = Process.GetProcessById(worker.Pid);
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
worker.SeverPipeForTest();
|
||||
await process.WaitForExitAsync(Ct).WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
||||
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(2));
|
||||
var exit = await worker.Exited.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
||||
// lmxopcua#1104: no tight wall-clock bound (it was 2 s, exposed to a ~1 s whole-process stall). What this test
|
||||
// means is carried by the exit CODE: ExitPipeClosed is only the worker's own EOF exit, so a worker that ignored
|
||||
// the EOF would either never exit (the wait times out) or be killed by the host (another code). The wait is
|
||||
// generous for the same reason; nothing else ends the process in that window.
|
||||
await process.WaitForExitAsync(Ct).WaitAsync(TimeSpan.FromSeconds(10), Ct);
|
||||
var exit = await worker.Exited.WaitAsync(TimeSpan.FromSeconds(10), Ct);
|
||||
exit.ExitCode.ShouldBe(ScriptWorkerEnvironment.ExitPipeClosed, "it noticed the EOF; the host did not have to kill it");
|
||||
}
|
||||
|
||||
@@ -421,12 +443,12 @@ public sealed class ContainmentTests
|
||||
public async Task Unsupported_input_and_result_types_are_explicit_failures()
|
||||
{
|
||||
await using var runner = Scripts.Runner(Scripts.Options());
|
||||
// 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).
|
||||
// An unpublishable RESULT is refused by ScriptResultMaterializer in both runners alike (lmxopcua#1100), so it is a
|
||||
// "script threw: … cannot carry …" failure, not "unsupported type" — since lmxopcua#1104 a jagged array too (it
|
||||
// was the one result shape the materializer passed and the wire could not 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.Int32[][]");
|
||||
result.Reason!.ShouldStartWith("script threw: The script returned a value of type 'Int32[][]', which an OPC UA node cannot carry: an array of arrays");
|
||||
|
||||
var pair = await runner.RunAsync(Scripts.Vt("pair", "return new System.Collections.Generic.KeyValuePair<int, int>(1, 2);"), Ct);
|
||||
pair.Status.ShouldBe(ScriptRunStatus.Failed);
|
||||
|
||||
@@ -123,6 +123,10 @@ public sealed class ParityTests
|
||||
{ "time span", "return System.TimeSpan.FromSeconds(1);" },
|
||||
{ "char array", "return new[] { 'a' };" },
|
||||
{ "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]
|
||||
|
||||
@@ -102,18 +102,28 @@ public sealed class ShadowModeTests
|
||||
["quality"] = "return ctx.GetTag(\"i\").StatusCode;",
|
||||
["throws"] = "if ((int)ctx.GetTag(\"i\").Value >= 0) throw new InvalidOperationException(\"boom \" + ctx.GetTag(\"i\").Value); return 0;",
|
||||
["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;
|
||||
// the one result shape left that only the worker refuses is a jagged array (no nested-array wire tag).
|
||||
// lmxopcua#1100: a decimal RESULT is refused by both runners alike (no OPC UA node can carry it), so it MATCHES;
|
||||
// lmxopcua#1104: so is a jagged array now (it used to be the one result only the worker refused).
|
||||
["decimal"] = "return 1.5m;",
|
||||
["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++)
|
||||
{
|
||||
foreach (var (key, source) in scripts)
|
||||
{
|
||||
var published = await shadowed.EvaluateAsync(key, source, Inputs(i), Ct);
|
||||
var expected = await reference.EvaluateAsync(key, source, Inputs(i), Ct);
|
||||
var published = await shadowed.EvaluateAsync(key, source, InputsFor(key, 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})");
|
||||
}
|
||||
(await shadow.WaitIdleAsync(TimeSpan.FromSeconds(60))).ShouldBeTrue();
|
||||
@@ -125,12 +135,12 @@ public sealed class ShadowModeTests
|
||||
stats.Compared.ShouldBe(scripts.Count * 3);
|
||||
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);
|
||||
mismatches.Keys.ShouldBe(["jagged", "divergent"], ignoreOrder: true);
|
||||
mismatches.Keys.ShouldBe(["decimalInput", "divergent"], ignoreOrder: true);
|
||||
mismatches["divergent"].LastReason.ShouldBe("value");
|
||||
mismatches["divergent"].LastSummary.ShouldBe("published Ok Int32 1; shadow Ok Int32 2");
|
||||
mismatches["divergent"].Count.ShouldBe(3);
|
||||
mismatches["jagged"].LastReason.ShouldBe("unsupported_type");
|
||||
mismatches["jagged"].LastSummary.ShouldContain("System.Int32[][]");
|
||||
mismatches["decimalInput"].LastReason.ShouldBe("unsupported_type");
|
||||
mismatches["decimalInput"].LastSummary.ShouldContain("System.Decimal");
|
||||
|
||||
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");
|
||||
|
||||
Reference in New Issue
Block a user