diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md
index 2507a5a2f..8c382e090 100644
--- a/docs/ScriptEditor.md
+++ b/docs/ScriptEditor.md
@@ -242,8 +242,10 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`:
`ScriptStackExhaustedException` (Bad, script log) instead of overflowing the
stack, which would terminate the whole server. The runtime compile inserts a
stack check at the entry of the script and of every lambda, anonymous method
- and local function (lmxopcua#779); the editor does not show it and does not
- flag recursion, and bounded recursion still works.
+ and local function (lmxopcua#779), and guards every `catch` / `finally` so a
+ handler that throws on every frame cannot overflow the stack while unwinding
+ (lmxopcua#971 review); the editor does not show it and does not flag
+ recursion, and bounded recursion still works.
- **Configuration keys and their ranges.** All four knobs are node-wide (the
`Scripting` appsettings section, shared by virtual tags, Calculation tags and
scripted alarms) and are clamped when bound, with one startup Warning per
diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md
index 7503ee98c..55b791843 100644
--- a/docs/VirtualTags.md
+++ b/docs/VirtualTags.md
@@ -70,7 +70,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 sandbox exposes no such API); a script can catch the exception, which only unwinds it. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. 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 sandbox exposes no such API); 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`. 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.Abstractions/ScriptStackGuard.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs
index b677ea4cd..9d887418a 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs
@@ -26,6 +26,19 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// that remains, not by a fixed count: the same script may fail at a different depth on a thread with a
/// different stack size (the platform's default thread stack size differs between Windows, Linux and macOS).
///
+///
+/// Exception handlers (lmxopcua#971 review 2026-12-02). Checking frames is not enough on its own: a
+/// catch or finally block runs as a funclet on top of the frames being unwound, so a
+/// handler that throws (throw;, throw new …, a call that fails the check) starts a nested
+/// exception dispatch deeper still — several KB per level. A script that catches-and-rethrows on every frame
+/// therefore overflowed the stack while unwinding from the guard's own exception, and 300 frames that each
+/// rethrow overflowed with no guard involvement at all. The rewrite also guards every script handler with
+/// : a catch gains the filter when (CanHandle() && …) and a
+/// finally body runs only if (CanHandle()). Once the stack is low, script handlers are skipped,
+/// the exception in flight passes to the host in one dispatch (a filter runs and returns without growing the
+/// stack), and the run fails with it. Skipping a finally is only possible on a run that is already
+/// failing on an exhausted stack.
+///
///
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ScriptStackGuard
@@ -38,6 +51,14 @@ public static class ScriptStackGuard
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
throw new ScriptStackExhaustedException();
}
+
+ ///
+ /// True while the current thread has stack to spare for a script exception handler (see the remarks). Called
+ /// by compiled scripts from every catch filter and finally block; not part of the script
+ /// authoring surface.
+ ///
+ /// False when the remaining stack is below the runtime's safety margin.
+ public static bool CanHandle() => RuntimeHelpers.TryEnsureSufficientExecutionStack();
}
///
diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs
index bd9fed528..bf95e4f3e 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs
@@ -33,6 +33,13 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// its exception terminated the host), so none reaches this rewrite.
///
///
+/// Exception handlers (lmxopcua#971 review). Every script catch also gets the filter
+/// when (ScriptStackGuard.CanHandle() && (original filter)), and every finally body is
+/// wrapped in if (ScriptStackGuard.CanHandle()) { … }: a handler runs on top of the frames being
+/// unwound, so one that throws on every frame overflowed the stack while unwinding (see
+/// ). On a healthy stack both are no-ops.
+///
+///
/// Runs after , so the analyzer only ever sees the user's code; the
/// inserted call names a type in Core.Scripting.Abstractions, which the sandbox already references.
///
@@ -40,6 +47,7 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
internal static class ScriptStackGuardInjector
{
private const string CheckCall = "global::ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptStackGuard.Check()";
+ private const string CanHandleCall = "global::ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptStackGuard.CanHandle()";
/// Returns with a stack check at the entry of every script-declared body.
/// The compiled (error-free, analyzer-clean) wrapper compilation.
@@ -65,6 +73,25 @@ internal static class ScriptStackGuardInjector
private sealed class Rewriter(SemanticModel model) : CSharpSyntaxRewriter
{
+ /// catch … when (f) becomes catch … when (CanHandle() && (f)) — see
+ /// 's "Exception handlers" remarks.
+ public override SyntaxNode? VisitCatchClause(CatchClauseSyntax node)
+ {
+ var visited = (CatchClauseSyntax)base.VisitCatchClause(node)!;
+ ExpressionSyntax canHandle = ParseExpression(CanHandleCall);
+ var condition = visited.Filter is { } filter
+ ? BinaryExpression(SyntaxKind.LogicalAndExpression, canHandle, ParenthesizedExpression(filter.FilterExpression))
+ : canHandle;
+ return visited.WithFilter(CatchFilterClause(condition));
+ }
+
+ /// finally { b } becomes finally { if (CanHandle()) { b } }.
+ public override SyntaxNode? VisitFinallyClause(FinallyClauseSyntax node)
+ {
+ var visited = (FinallyClauseSyntax)base.VisitFinallyClause(node)!;
+ return visited.WithBlock(Block(IfStatement(ParseExpression(CanHandleCall), visited.Block)));
+ }
+
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
{
// The only method in the wrapper is the synthesized CompiledScript.Run (ScriptEvaluator enforces that).
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRecursionContainmentTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRecursionContainmentTests.cs
index 1098eccd1..e1ee662dd 100644
--- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRecursionContainmentTests.cs
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRecursionContainmentTests.cs
@@ -43,6 +43,40 @@ public sealed class ScriptRecursionContainmentTests
"System.Action a = null!; System.Func h = n => { a(n); return n; }; a = n => h(n + 1); a(0); return 0;",
["anonymous-method"] =
"System.Func f = null!; f = delegate (int n) { return f(n + 1) + 1; }; return f(0);",
+
+ // lmxopcua#971 review: exception handlers on every frame. 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 on
+ // macOS). Before the fix each of these terminated the process — the unbounded ones after the guard fired
+ // (its margin cannot hold a nested dispatch per frame), the bounded ones with no guard involvement at all:
+ // 300 frames that each catch-and-rethrow are enough.
+ ["catch-rethrow-per-frame"] =
+ "int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { throw; } } return Rec(0);",
+ ["catch-throw-new-per-frame"] =
+ "int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { throw new System.InvalidOperationException(); } } return Rec(0);",
+ ["catch-recurse-again"] =
+ "int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { return Rec(d + 1); } } return Rec(0);",
+ ["finally-throw-per-frame"] =
+ "int Rec(int d) { try { return Rec(d + 1); } finally { if (d >= 0) throw new System.InvalidOperationException(); } } return Rec(0);",
+ ["bounded-catch-rethrow"] =
+ "int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } catch (System.Exception) { throw; } } return Rec(0);",
+ ["bounded-catch-wrap"] =
+ "int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } catch (System.InvalidOperationException) { throw new System.ArgumentException(); } catch (System.ArgumentException) { throw new System.InvalidOperationException(); } } return Rec(0);",
+ ["bounded-finally-throw"] =
+ "int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } finally { if (d >= 0) throw new System.InvalidOperationException(); } } return Rec(0);",
+ ["filter-recurses"] =
+ "int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) when (Rec(d + 1) > 0) { return 0; } } return Rec(0);",
+ };
+
+ ///
+ /// Scenarios whose surviving fault is not : the exception in flight
+ /// when the stack ran low is the script's own, and the run fails with it (null = any exception type).
+ ///
+ private static readonly Dictionary ExpectedFaultOverrides = new(StringComparer.Ordinal)
+ {
+ ["finally-throw-per-frame"] = null,
+ ["bounded-catch-rethrow"] = nameof(InvalidOperationException),
+ ["bounded-catch-wrap"] = null,
+ ["bounded-finally-throw"] = nameof(InvalidOperationException),
};
public static TheoryData ScenarioNames => new(Scenarios.Keys);
@@ -58,9 +92,10 @@ public sealed class ScriptRecursionContainmentTests
var outcome = File.Exists(resultFile) ? await File.ReadAllTextAsync(resultFile, TestContext.Current.CancellationToken) : "";
// Assert the artifact first: what the child itself recorded about the run.
- outcome.ShouldBe(
- $"FAULTED:{nameof(ScriptStackExhaustedException)}",
- $"child exit {exitCode}; stderr head: {Head(stderr)}; stderr tail: {Tail(stderr)}; stdout tail: {Tail(stdout)}");
+ var context = $"child exit {exitCode}; stderr head: {Head(stderr)}; stderr tail: {Tail(stderr)}; stdout tail: {Tail(stdout)}";
+ var expected = ExpectedFaultOverrides.TryGetValue(scenario, out var over) ? over : nameof(ScriptStackExhaustedException);
+ if (expected is null) outcome.ShouldStartWith("FAULTED:", Case.Sensitive, context);
+ else outcome.ShouldBe($"FAULTED:{expected}", context);
exitCode.ShouldBe(0, $"the process must survive the script; stderr tail: {Tail(stderr)}");
}
finally
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs
index 7267ca684..87af7ffe5 100644
--- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs
@@ -38,6 +38,15 @@ public sealed class ScriptStackGuardInjectionTests
// Static lambda and a lambda capturing ctx.
[InlineData("System.Func f = static x => x - 1; return f(9);", 8)]
[InlineData("System.Func known = p => ctx.GetTag(p).StatusCode == 0u; return known(\"missing\") ? 1 : 0;", 0)]
+ // lmxopcua#971 review: guarded handlers keep their meaning on a healthy stack — an existing filter still
+ // decides, a declaration-less catch still catches, pattern variables from the filter stay in scope, and a
+ // finally still runs on both the normal and the exceptional path.
+ [InlineData("try { throw new InvalidOperationException(\"a\"); } catch (InvalidOperationException e) when (e.Message == \"b\") { return 1; } catch (Exception) { return 2; }", 2)]
+ [InlineData("try { throw new InvalidOperationException(); } catch { return 4; }", 4)]
+ [InlineData("try { throw new ArgumentException(\"x\"); } catch (Exception e) when (e is ArgumentException a && a.Message == \"x\") { return a.Message.Length + 2; }", 3)]
+ [InlineData("var n = 0; try { n = 1; } finally { n += 10; } return n;", 11)]
+ [InlineData("var n = 0; try { try { throw new Exception(); } finally { n = 5; } } catch { n += 1; } return n;", 6)]
+ [InlineData("int Rec(int d) { try { if (d >= 50) throw new InvalidOperationException(); return Rec(d + 1); } catch (InvalidOperationException) { throw; } } try { return Rec(0); } catch (InvalidOperationException) { return 50; }", 50)]
public void Rewritten_lambdas_and_local_functions_keep_their_meaning(string source, int expected) =>
Run(source).ShouldBe(expected);