diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 7d896e49e..6e25a85e1 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -239,6 +239,19 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: `Scripting:MaxAllocBytesPerRun` (64 MB) is quarantined. This is sampled after the run returns, so a run that OOMs the process first is not stopped — that needs an out-of-process runner (→ #750). +- **A returned sequence is materialised inside the run, bounded (#1059).** A script can return an + iterator (`yield`) or an unfinished LINQ query: nothing has run when `Run` returns, so the host used + to enumerate it on its own thread — outside the timeout and the allocation sample, with no element + bound. The guard now enumerates a lazy sequence into a typed array (`double[]` for an + `IEnumerable`) on the run's own thread, so the work is charged to the timeout, the orphan slot + and the allocation budget, and refuses one past `Scripting:MaxResultElements` (default 100 000; also + 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 + `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)". - **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 @@ -254,7 +267,7 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: 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 +- **Configuration keys and their ranges.** The numeric 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 clamped value: @@ -263,6 +276,7 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: |---|---|---| | `Scripting:RunTimeout` | `00:00:02` (2 s) | zero or negative becomes the default; above `00:01:00` becomes 60 s. The per-run budget of virtual tags and scripted-alarm predicates (lmxopcua#779 — alarms used to fall back to 250 ms). Calculation tags keep their per-driver `runTimeoutMs`. | | `Scripting:MaxAllocBytesPerRun` | `67108864` (64 MB) | `0` (or negative) disables the budget; a positive value below `1048576` (1 MB) becomes 1 MB | + | `Scripting:MaxResultElements` | `100000` | most elements a returned array / collection / materialised sequence may hold (#1059); zero or negative becomes the default | | `Scripting:QuarantineAfterConsecutiveTimeouts` | `3` | `1`–`1000` | | `Scripting:StuckOrphanQuarantineFactor` | `10` | `0` (or negative) disables the rule; above `1000` becomes `1000`; `NaN` becomes the default. In-process runner only (lmxopcua#780 P4) | diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 9d05abdef..a416d5716 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`. 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). **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/ForbiddenTypeAnalyzer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs index 501b59490..1629b3096 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs @@ -85,6 +85,12 @@ public static class ForbiddenTypeAnalyzer /// Func<…>). A nested type is allowed when its containing type is. Every System.Exception /// subclass declared in the System namespace is allowed in addition to this list. /// + /// + /// lmxopcua#1059: before adding a type here, check its ToString / Equals / GetHashCode for + /// recursion over script-built data — the host copies and compares a returned value recursively + /// (OwnedDataSample.CopyLegacy, VirtualTagActor.SameValue) and formats it into logs, so a type that + /// recurses over a cyclic or deeply nested value a script can build would overflow the HOST's stack after the run. + /// public static readonly IReadOnlyList AllowedTypes = [ // Primitives and core value types. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs new file mode 100644 index 000000000..b3d2cf357 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs @@ -0,0 +1,117 @@ +using System.Collections; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; + +/// Thrown when a script's returned value is a sequence that is too large, or of a shape the host cannot take (lmxopcua#1059). +public sealed class ScriptResultException : InvalidOperationException +{ + /// Initializes a new instance of the class. + /// What was wrong with the returned value. + public ScriptResultException(string message) : base(message) + { + } +} + +/// +/// Forces a script's returned sequence to be a bounded, concrete value INSIDE the guarded run (lmxopcua#1059). +/// +/// +/// +/// A script can return an iterator (yield) or an unfinished LINQ query. Nothing has run yet when +/// Run returns: the host then enumerates it on ITS thread — outside the guard's timeout and +/// allocation sampling, with no bound on the element count — so a while(true) yield return or an +/// Enumerable.Range(0, int.MaxValue) would hang or exhaust the publish path rather than the script's own +/// run. The guard therefore materialises the result right after the script returns, on the same pool thread, so +/// the enumeration is charged to the run (timeout, orphan slot, allocation budget) and is capped at +/// maxElements. +/// +/// +/// What changes: a lazy sequence (an that is neither an array, a string nor an +/// ) becomes a typed T[] of its IEnumerable<T> element type. A +/// sequence whose element type could itself be a sequence (object, 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 ForbiddenTypeAnalyzer). 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. +/// +/// +/// This does NOT make the in-process runner a hard sandbox: memory exhaustion inside the run and a +/// 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. +/// +/// +internal static class ScriptResultMaterializer +{ + /// Materialises as described on the type. + /// The script's returned value. + /// The element cap; zero or negative disables the cap (a lazy sequence is still materialised, unbounded). + /// The value the host should see. + /// The sequence exceeds the cap, or its element type is an open slot. + public static object? Materialize(object? value, int maxElements) + { + switch (value) + { + case null or string: + return value; + case Array array: + EnforceCap(array.Length, maxElements); + return array; + case ICollection collection: + EnforceCap(collection.Count, maxElements); + return value; + case IEnumerable sequence: + return MaterializeLazy(sequence, maxElements); + default: + return value; + } + } + + private static object MaterializeLazy(IEnumerable sequence, int maxElements) + { + var elementType = ElementTypeOf(sequence.GetType()) + ?? throw new ScriptResultException( + $"The script returned a lazy sequence ({sequence.GetType().Name}) with no IEnumerable 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; " + + "return a typed array of a concrete type (double[], string[], …)."); + + var items = new List(); + foreach (var item in sequence) + { + if (maxElements > 0 && items.Count >= maxElements) + throw new ScriptResultException( + $"The script returned a sequence of more than {maxElements} elements (Scripting:MaxResultElements); " + + "it was cut off while being materialised."); + items.Add(item); + } + var result = Array.CreateInstance(elementType, items.Count); + for (var i = 0; i < items.Count; i++) result.SetValue(items[i], i); + return result; + } + + private static void EnforceCap(int count, int maxElements) + { + if (maxElements > 0 && count > maxElements) + throw new ScriptResultException( + $"The script returned a collection of {count} elements, over the {maxElements}-element limit (Scripting:MaxResultElements)."); + } + + private static Type? ElementTypeOf(Type type) + { + Type? found = null; + foreach (var i in type.GetInterfaces().Append(type)) + { + if (!i.IsGenericType || i.GetGenericTypeDefinition() != typeof(IEnumerable<>)) continue; + var arg = i.GetGenericArguments()[0]; + if (found is not null && found != arg) return null; // ambiguous + found = arg; + } + return found; + } + + private static bool IsOpenSlot(Type t) => + t == typeof(object) || t.IsInterface || t.IsAbstract + || (t != typeof(string) && typeof(IEnumerable).IsAssignableFrom(t)); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs index 979e477fd..576b76adf 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs @@ -85,6 +85,7 @@ public sealed class ScriptRunGuard private readonly long _maxAllocBytesPerRun; private readonly int _quarantineThreshold; private readonly double _stuckFactor; + private readonly int _maxResultElements; private readonly ILogger _logger; private int _inFlight; private long _started; @@ -102,6 +103,7 @@ public sealed class ScriptRunGuard _maxAllocBytesPerRun = options.MaxAllocBytesPerRun; _quarantineThreshold = options.QuarantineAfterConsecutiveTimeouts; _stuckFactor = options.StuckOrphanQuarantineFactor; + _maxResultElements = options.MaxResultElements; _logger = logger ?? Log.Logger; } @@ -251,8 +253,13 @@ public sealed class ScriptRunGuard // ScriptEvaluator.RunAsync executes the compiled delegate synchronously and returns a completed // task, so the after-sample is taken on the same thread, right after the script returned. var pending = evaluator.RunAsync(context, runToken); - slot.AllocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before; var value = await pending.ConfigureAwait(false); + // lmxopcua#1059: a returned iterator / unfinished LINQ query has run nothing yet. Enumerate it HERE, on the + // run's own thread, so the work is charged to the timeout + allocation sample and bounded — never on the + // host's publish path. (Only a reference-typed result can be a sequence.) + if (!typeof(TResult).IsValueType) + value = (TResult)ScriptResultMaterializer.Materialize(value, _maxResultElements)!; + slot.AllocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before; succeeded = true; return value; } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptingOptions.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptingOptions.cs index 3e141e10d..f5449f19e 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptingOptions.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptingOptions.cs @@ -28,6 +28,9 @@ public sealed class ScriptingOptions /// Default : 64 MB. public const long DefaultMaxAllocBytesPerRun = 64L * 1024 * 1024; + /// Default : 100 000. + public const int DefaultMaxResultElements = 100_000; + /// Default : 3. public const int DefaultQuarantineAfterConsecutiveTimeouts = 3; @@ -53,6 +56,15 @@ public sealed class ScriptingOptions /// public long MaxAllocBytesPerRun { get; set; } = DefaultMaxAllocBytesPerRun; + /// + /// The most elements a script's returned array / collection / sequence may hold (lmxopcua#1059). A lazy sequence + /// (iterator, unfinished LINQ query) the script returns is enumerated into an array INSIDE the guarded run — so the + /// enumeration is charged to the run's timeout and allocation budget instead of happening unbounded on the + /// host's publish path — and cut off with a past this count. Zero or negative + /// becomes the default. Default 100 000. + /// + public int MaxResultElements { get; set; } = DefaultMaxResultElements; + /// /// Consecutive timeouts after which the script is quarantined: no further runs are dispatched, every /// evaluation reports Bad, and the quarantine lifts only on a source change, a redeploy or an explicit @@ -174,6 +186,13 @@ public sealed class ScriptingOptions alloc = MinMaxAllocBytesPerRun; } + var maxResultElements = MaxResultElements; + if (maxResultElements <= 0) + { + notes.Add($"{SectionName}:{nameof(MaxResultElements)} {maxResultElements} is not positive; using the default {DefaultMaxResultElements}."); + maxResultElements = DefaultMaxResultElements; + } + var runTimeout = RunTimeout; if (runTimeout <= TimeSpan.Zero) { @@ -196,6 +215,7 @@ public sealed class ScriptingOptions { RunTimeout = runTimeout, MaxAllocBytesPerRun = alloc, + MaxResultElements = maxResultElements, QuarantineAfterConsecutiveTimeouts = threshold, StuckOrphanQuarantineFactor = factor, Runner = Runner, diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriverFactoryExtensions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriverFactoryExtensions.cs index 3bc8dac64..54c24b6ea 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriverFactoryExtensions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriverFactoryExtensions.cs @@ -136,6 +136,7 @@ public static class CalculationDriverFactoryExtensions resolved.MaxAllocBytesPerRun = nodeScripting.MaxAllocBytesPerRun; resolved.QuarantineAfterConsecutiveTimeouts = nodeScripting.QuarantineAfterConsecutiveTimeouts; resolved.StuckOrphanQuarantineFactor = nodeScripting.StuckOrphanQuarantineFactor; + resolved.MaxResultElements = nodeScripting.MaxResultElements; } if (maxAllocBytesPerRun is { } alloc) resolved.MaxAllocBytesPerRun = alloc; if (quarantineAfterConsecutiveTimeouts is { } n) resolved.QuarantineAfterConsecutiveTimeouts = n; diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs new file mode 100644 index 000000000..4b03c8eac --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs @@ -0,0 +1,121 @@ +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests; + +/// +/// lmxopcua#1059 — a script that returns an iterator or an unfinished LINQ query used to hand the host a sequence +/// nothing had run yet; the host then enumerated it on its own thread, outside the guard's timeout / allocation sample +/// and with no element bound. The guard now materialises the result inside the guarded run, bounded. +/// +[Trait("Category", "Unit")] +public sealed class ScriptResultMaterializerTests +{ + private static IEnumerable Endless() { var i = 0.0; while (true) yield return i++; } + + [Fact] + public void A_lazy_sequence_becomes_a_typed_array_and_runs_now() + { + var ran = 0; + var lazy = Enumerable.Range(0, 4).Select(i => { ran++; return (double)i; }); + ran.ShouldBe(0); + + var result = ScriptResultMaterializer.Materialize(lazy, 100).ShouldBeOfType(); + + result.ShouldBe([0.0, 1.0, 2.0, 3.0]); + ran.ShouldBe(4); + } + + [Fact] + public void A_sequence_past_the_cap_is_cut_off_not_enumerated_forever() + { + var ex = Should.Throw(() => ScriptResultMaterializer.Materialize(Endless(), 1000)); + ex.Message.ShouldContain("1000"); + } + + [Fact] + public void A_sequence_of_exactly_the_cap_is_accepted_boundary() + => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 5).Select(i => (long)i), 5) + .ShouldBeOfType().Length.ShouldBe(5); + + [Fact] + public void A_lazy_sequence_of_an_open_slot_type_is_refused() + { + Should.Throw(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (object)i), 100)); + Should.Throw(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => new List { i }), 100)); + Should.Throw(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (IComparable)i), 100)); + } + + [Fact] + public void Arrays_collections_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 { 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(); + } + + [Fact] + public void An_oversized_array_or_collection_is_refused_by_the_same_cap() + { + Should.Throw(() => ScriptResultMaterializer.Materialize(new double[101], 100)); + Should.Throw(() => ScriptResultMaterializer.Materialize(new List(new int[101]), 100)); + } + + [Fact] + public void A_zero_cap_disables_the_bound_but_still_materialises() + => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => i), 0).ShouldBeOfType(); + + [Fact] + public void The_options_clamp_a_non_positive_cap_to_the_default() + { + var sanitized = new ScriptingOptions { MaxResultElements = 0 }.Sanitized(out var notes); + sanitized.MaxResultElements.ShouldBe(ScriptingOptions.DefaultMaxResultElements); + notes.ShouldContain(n => n.Contains("MaxResultElements")); + new ScriptingOptions().Sanitized(out var none).MaxResultElements.ShouldBe(ScriptingOptions.DefaultMaxResultElements); + none.ShouldBeEmpty(); + } + + // ---- through the guard, with a real compiled script ---- + + private static ScriptEvaluator Compile(string source) => + ScriptEvaluator.Compile(source); + + [Fact] + public async Task The_guard_hands_the_host_a_materialised_array_not_a_live_query() + { + var guard = new ScriptRunGuard(); + using var eval = Compile("return System.Linq.Enumerable.Range(0, 3).Select(i => (double)i * 2);"); + var result = await guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + result.ShouldBeOfType().ShouldBe([0.0, 2.0, 4.0]); + } + + [Fact] + public async Task The_guard_cuts_off_an_endless_lazy_sequence_inside_the_run_and_does_not_strike_the_script() + { + var guard = new ScriptRunGuard(new ScriptingOptions { MaxResultElements = 1000, QuarantineAfterConsecutiveTimeouts = 1 }); + using var eval = Compile("return System.Linq.Enumerable.Range(0, int.MaxValue).Select(i => (double)i);"); + var ct = TestContext.Current.CancellationToken; + + await Should.ThrowAsync(() => guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), ct)); + await Should.ThrowAsync(() => guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), ct)); + guard.IsQuarantined("k", out _).ShouldBeFalse("a refused result is a failed run, not a timeout strike"); + guard.InFlightCount.ShouldBe(0); + } + + [Fact] + public async Task The_guard_charges_the_enumeration_to_the_allocation_budget() + { + // 2 MB budget; the sequence materialises ~100k strings — the allocation happens during enumeration, which used to + // be outside the sample entirely. + var guard = new ScriptRunGuard(new ScriptingOptions { MaxAllocBytesPerRun = 1024 * 1024 }); + using var eval = Compile("return System.Linq.Enumerable.Range(0, 90000).Select(i => new string('x', 64) + i);"); + await Should.ThrowAsync(() => + guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); + guard.IsQuarantined("k", out var reason).ShouldBeTrue(); + reason!.ShouldContain("allocated"); + } +}