diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md
index 6e25a85e1..0b700d0a4 100644
--- a/docs/ScriptEditor.md
+++ b/docs/ScriptEditor.md
@@ -251,7 +251,9 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`:
Arrays, lists, 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)".
+ sequence. See `docs/VirtualTags.md` §"Known resource limits (accepted trade-offs)". The out-of-process
+ worker applies the same rule with the same cap and the same failure text (#1064), so a script behaves
+ identically under `Scripting:Runner=InProcess` and `OutOfProcess`.
- **Out of process (opt-in, lmxopcua#780).** `Scripting:Runner=OutOfProcess` moves the
virtual-tag and Calculation seams' compiled runs — and the scripted-alarm predicates,
when `Scripting:Runner:Seams` lists `ScriptedAlarm` — into `ScriptWorker` processes, where a
diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md
index 23a0d97f6..a084b1df9 100644
--- a/docs/VirtualTags.md
+++ b/docs/VirtualTags.md
@@ -72,7 +72,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). **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); 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".
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs
index d62adadfd..a75a51b39 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs
@@ -764,7 +764,8 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
LoadTimeout: LoadTimeout,
CompileThreads: _compileThreads,
WorkerSid: WorkerSid,
- HeartbeatSilenceLimit: _heartbeatSilenceLimit);
+ HeartbeatSilenceLimit: _heartbeatSilenceLimit,
+ MaxResultElements: _options.MaxResultElements);
return new WorkerShard(label, isolation,
(onExiting, ct) => WorkerConnection.StartAsync(spec, _log, OnLogs, onExiting, ct),
OnWorkerExit, _log);
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs
index fa0eec507..1c10f8d44 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs
@@ -102,6 +102,11 @@ internal sealed record BatchSubmission(string Key, EvalRequest Request, TimeSpan
/// Ask the worker to run the soft clock from each run's start (lmxopcua#827; see ).
/// False (tests only) keeps the pre-#827 host clock, which is also what a worker that does not echo it gets.
///
+///
+/// Scripting:MaxResultElements (lmxopcua#1064): the element cap the worker holds a value script's returned
+/// sequence to while materialising it inside the run — the same rule the in-process guard applies (#1059). 0 = the
+/// worker's default.
+///
internal sealed record WorkerLaunchSpec(
string Shard,
string WorkerPath,
@@ -117,7 +122,8 @@ internal sealed record WorkerLaunchSpec(
string? WorkerSid = null,
bool WorkerSoftClock = true,
TimeSpan? HeartbeatSilenceLimit = null,
- bool TestStallReaderOnDiag = false)
+ bool TestStallReaderOnDiag = false,
+ int MaxResultElements = 0)
{
/// The default compile timeout.
public static readonly TimeSpan DefaultLoadTimeout = TimeSpan.FromSeconds(60);
@@ -448,6 +454,7 @@ internal sealed class WorkerConnection : IAsyncDisposable
CompileThreads = (uint)Math.Max(0, spec.CompileThreads),
WorkerSoftClock = spec.WorkerSoftClock,
TestStallReaderOnDiag = spec.TestStallReaderOnDiag,
+ MaxResultElements = (uint)Math.Max(0, spec.MaxResultElements),
};
///
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 c8463bb4d..6893d0f97 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
@@ -53,6 +53,11 @@ message Hello {
// Test seam (lmxopcua#789): the worker's reader stops reading for good at the first DiagnosticsRequest while its
// heartbeats go on, so the host's write-stall check can be exercised against a real worker. Never set in production.
bool test_stall_reader_on_diag = 12;
+ // lmxopcua#1064: Scripting:MaxResultElements. A value script's returned sequence is materialised inside the run and
+ // held to this element cap, exactly as the in-process ScriptRunGuard does (ScriptResultMaterializer, #1059) — so a
+ // lazy sequence is enumerated in the worker's run (under its deadlines), and an over-cap result fails the script the
+ // same way in both runners. 0 = the worker's default (ScriptingOptions.DefaultMaxResultElements).
+ uint32 max_result_elements = 13;
}
message Ready {
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 b3d2cf357..e055a8a0d 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs
@@ -39,8 +39,14 @@ public sealed class ScriptResultException : InvalidOperationException
/// non-terminating loop are still only contained by the guard's after-the-fact allocation sample and its timeout
/// (an orphaned thread). Only Scripting:Runner=OutOfProcess contains those. See docs/VirtualTags.md.
///
+///
+/// The ONE result rule for both runners (lmxopcua#1064): the in-process and the
+/// out-of-process ScriptWorker both call right after a value script returns,
+/// inside the run, with the node's Scripting:MaxResultElements (the worker receives it in its
+/// Hello). Public for that reason only.
+///
///
-internal static class ScriptResultMaterializer
+public static class ScriptResultMaterializer
{
/// Materialises as described on the type.
/// The script's returned value.
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs
index 26ef5492b..fb8e1c92a 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs
@@ -77,6 +77,7 @@ internal sealed class WorkerHost
private int _maxFrameBytes = ScriptWorkerFrameCodec.DefaultMaxFrameBytes;
private int _queueCapacity = 4096;
private TimeSpan _hardGrace = TimeSpan.FromSeconds(1);
+ private int _maxResultElements = ScriptingOptions.DefaultMaxResultElements;
private TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(1);
///
@@ -160,6 +161,7 @@ internal sealed class WorkerHost
if (hello.HardGraceMs > 0) _hardGrace = TimeSpan.FromMilliseconds(hello.HardGraceMs);
if (hello.HeartbeatIntervalMs > 0) _heartbeatInterval = TimeSpan.FromMilliseconds(hello.HeartbeatIntervalMs);
if (hello.CompileThreads > 0) _compileThreads = (int)Math.Min(hello.CompileThreads, 64);
+ if (hello.MaxResultElements > 0) _maxResultElements = (int)Math.Min(hello.MaxResultElements, int.MaxValue);
_workerSoftClock = hello.WorkerSoftClock;
_testStallReaderOnDiag = hello.TestStallReaderOnDiag;
// lmxopcua#1014: no PE-cache key or directory any more — the host verifies, compiles and signs, and sends a
@@ -458,6 +460,11 @@ internal sealed class WorkerHost
try
{
object? value = script.Run(inputs, logger, clock, cts.Token, out var isPredicate);
+ // lmxopcua#1064: the in-process guard's result rule (#1059), applied here too and still inside the run —
+ // this eval is registered with the watchdog and its allocation sample is still open — so a returned lazy
+ // sequence is enumerated under the run's deadlines and held to Scripting:MaxResultElements, and an
+ // over-cap or open-slot sequence fails the script with the same message in both runners.
+ if (!isPredicate) value = ScriptResultMaterializer.Materialize(value, _maxResultElements);
if (isPredicate)
{
result.Predicate = (bool)value!;
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 7056e5368..c75a2f1d6 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs
@@ -80,6 +80,58 @@ public sealed class ParityTests
Same(actual.Value, expected.Value, typeName);
}
+ ///
+ /// lmxopcua#1064: the result rule of #1059 () holds in both runners — a lazy
+ /// sequence becomes the same typed array, and an over-cap / open-slot sequence fails with the same reason. Before
+ /// the fix the worker answered every lazy sequence "unsupported type" and shipped an over-cap array whole.
+ ///
+ public static TheoryData ResultCases() => new()
+ {
+ { "lazy query", "return System.Linq.Enumerable.Range(0, 3).Select(i => i * 1.5);" },
+ { "iterator", "System.Collections.Generic.IEnumerable F() { for (var i = 0; i < 3; i++) yield return i; } return F();" },
+ { "endless iterator", "System.Collections.Generic.IEnumerable F() { var i = 0.0; while (true) yield return i++; } return F();" },
+ { "over-cap lazy", "return System.Linq.Enumerable.Range(0, int.MaxValue).Select(i => (double)i);" },
+ { "over-cap array", "return new double[5];" },
+ { "at-cap array", "return new double[4];" },
+ { "empty lazy", "return System.Linq.Enumerable.Empty();" },
+ };
+
+ [Theory]
+ [MemberData(nameof(ResultCases))]
+ public async Task Result_materialisation_and_the_element_cap_agree(string name, string source)
+ {
+ const int cap = 4;
+ using var inProcess = new InProcessScriptRunner(new ScriptingOptions { MaxResultElements = cap });
+ var options = Scripts.Options();
+ options.MaxResultElements = cap;
+ await using var outOfProcess = Scripts.Runner(options);
+ var invocation = Scripts.Vt("result-" + name, source);
+
+ var expected = await inProcess.RunAsync(invocation, Ct);
+ var actual = await outOfProcess.RunAsync(invocation, Ct);
+
+ actual.Status.ShouldBe(expected.Status, $"{name}: {actual.Reason} vs {expected.Reason}");
+ actual.Reason.ShouldBe(expected.Reason);
+ Same(actual.Value, expected.Value, name);
+ }
+
+ [Fact]
+ public async Task The_worker_holds_a_lazy_result_to_the_configured_cap()
+ {
+ // Positive control first (the cap is not simply "always fails"): 3 elements under a cap of 3 materialise.
+ var options = Scripts.Options();
+ options.MaxResultElements = 3;
+ await using var runner = Scripts.Runner(options);
+
+ var ok = await runner.RunAsync(Scripts.Vt("cap-ok", "return System.Linq.Enumerable.Range(0, 3).Select(i => (double)i);"), Ct);
+ ok.Status.ShouldBe(ScriptRunStatus.Ok, ok.Reason);
+ ok.Value.ShouldBeOfType().ShouldBe([0.0, 1.0, 2.0]);
+
+ var over = await runner.RunAsync(Scripts.Vt("cap-over", "return System.Linq.Enumerable.Range(0, 4).Select(i => (double)i);"), Ct);
+ over.Status.ShouldBe(ScriptRunStatus.Failed);
+ over.Reason.ShouldNotBeNull().ShouldContain("more than 3 elements");
+ }
+
private static void Same(object? actual, object? expected, string because)
{
if (expected is null)