From bd4fff6444ed465e33a0b7ab12fccedc35b58991 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Fri, 4 Dec 2026 15:02:41 -0500 Subject: [PATCH 1/3] fix(scripting): #1083 a dynamic tag path is an editor error only where the gate refuses it (predicate), a warning in value/Calculation mode; #1093 Calculation-mode {{equip}} hover says it is refused MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #1083: OTSCRIPT_DYNPATH was an error in every editor mode while the deploy gate refuses a non-literal tag path only for a scripted-alarm predicate (editor stricter than the gate). Decision: do not make the gate stricter (it would reject configurations that deploy today). ScriptCompileRules now owns the split — RefusesNonLiteralTagPaths(kind) and TagPathFindings(kind, source), each finding carrying Refuses — the gate refuses on exactly those findings and the editor draws them as errors (8) and the rest as warnings (4), whose text says what the path does at runtime (not a declared input: not subscribed, does not re-trigger, reads BadNodeIdUnknown unless also read literally). DependencyRejection gains Kind + MethodName for that wording. EditorGateParityTests carries dynamic / concatenated / interpolated / empty paths in all three modes (14 rows fail with the old always-error severity). #1093: hovering a {{equip}} path literal in Calculation mode showed the VirtualTag "resolves ... when deployed" text, contradicting the OTSCRIPT_EQUIPCALC marker on the same span. It now says the token is refused in a Calculation script and why (no owning equipment, never substituted, the gate refuses it). The {{equip}} hover no longer needs a tag catalog. --- docs/ScriptEditor.md | 33 +++++--- .../DependencyExtractor.cs | 35 ++++++++- .../RoslynDeployScriptChecker.cs | 15 ++-- .../ScriptCompileRules.cs | 76 +++++++++++++++++++ .../ScriptAnalysis/ScriptAnalysisService.cs | 41 +++++++--- .../ScriptAnalysis/DiagnoseTests.cs | 4 +- .../ScriptAnalysis/EditorGateParityTests.cs | 37 ++++++++- .../ScriptAnalysis/EquipTokenEditorTests.cs | 26 +++++++ 8 files changed, 234 insertions(+), 33 deletions(-) diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 727c62250..b17eb4778 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -124,7 +124,7 @@ the `ConfigEditor` authorization policy (`AdminUiPolicies.ConfigEditor`: Adminis | Route | Request DTO | Response DTO | Purpose | |-------|-------------|--------------|---------| -| `POST /api/script-analysis/diagnostics` | `DiagnoseRequest(Code)` | `DiagnoseResponse(Markers)` | Roslyn + ForbiddenType + dynamic-path error markers | +| `POST /api/script-analysis/diagnostics` | `DiagnoseRequest(Code)` | `DiagnoseResponse(Markers)` | Roslyn + ForbiddenType + dynamic-path markers (error for a predicate, warning otherwise — #1083) | | `POST /api/script-analysis/completions` | `CompletionsRequest(CodeText, Line, Column)` | `CompletionsResponse(Items)` | Scope, dot-member, and tag-path completions | | `POST /api/script-analysis/hover` | `HoverRequest(CodeText, Line, Column)` | `HoverResponse(Markdown?)` | Type + XML doc markdown | | `POST /api/script-analysis/signature-help` | `SignatureHelpRequest(CodeText, Line, Column)` | `SignatureHelpResponse(Label?, Parameters?, ActiveParameter)` | Parameter help | @@ -212,9 +212,10 @@ scripted alarms are the script's only users, and to *value* otherwise; pick whic seam you are authoring for. The per-equipment VirtualTag editor is value mode and the Calculation tag editor is Calculation mode. A body that lacks a `return` on some path (CS0161) is flagged while you type since #1063 (it used to be filtered as a "phantom" -wrapper diagnostic while the gate refused it). Known remaining divergence: a dynamic -tag path (`OTSCRIPT_DYNPATH`) is an editor error in every mode but a gate refusal only -for a predicate. See `docs/VirtualTags.md` §"Deploy-time script compile gate" for +wrapper diagnostic while the gate refused it). A dynamic tag path (`OTSCRIPT_DYNPATH`) +is an editor **error** only in predicate mode, where the gate refuses it, and a +**warning** in value and Calculation mode, where it deploys (#1083 — it used to be an +error in every mode). See `docs/VirtualTags.md` §"Deploy-time script compile gate" for modes, caching and the upgrade note. ### Runtime safety (what happens after publish) @@ -314,11 +315,20 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: `DependencyExtractor.Extract(code).Rejections` enumerates every `ctx.GetTag` / `ctx.SetVirtualTag` call whose first argument is NOT a string literal (variable, concatenation, interpolation). Each rejection carries a `TextSpan` in -user-source coordinates, emitted as code `OTSCRIPT_DYNPATH`. This is the exact -check the deploy gate (and the scripted-alarm load) enforces for a scripted-alarm -predicate — the editor shows the squiggle where the literal must appear. In value -and Calculation mode the editor marks it an error too, but the gate does not refuse -it there: a known editor-stricter divergence, excluded from `EditorGateParityTests`. +user-source coordinates, emitted as code `OTSCRIPT_DYNPATH`. Which seams it refuses is +decided in `ScriptCompileRules` (#1083): `RefusesNonLiteralTagPaths(kind)` is true for a +scripted-alarm predicate only (the alarm load runs the extractor and refuses the alarm), +and `TagPathFindings(kind, source)` returns each rejection with a `Refuses` flag. The +deploy gate refuses on exactly those findings, and the editor draws them as an **error** +(severity 8) where `Refuses` and a **warning** (severity 4) otherwise — so the two cannot +drift. In value and Calculation mode the warning says what the path does at runtime: +those seams read only their *declared* inputs (the literal `ctx.GetTag` paths, which +are what gets subscribed and what re-triggers the script), so a dynamic read returns +Bad (`BadNodeIdUnknown`, null value) unless the same path is also read with a literal +elsewhere in the script; an empty literal path always reads Bad (and an empty +`SetVirtualTag` path throws). Making the gate refuse these in value/Calculation scripts +was declined — it would reject configurations that deploy today. `EditorGateParityTests` +carries dynamic, concatenated, interpolated and empty paths in all three modes. --- @@ -520,7 +530,10 @@ inline script panel): - **Hover** — hovering a `{{equip}}/` path literal shows an *"Equipment-relative path — resolved through the equipment's tag reference at - deploy"* note. + deploy"* note. In **Calculation** mode it instead says the token is refused there and + why — a Calculation tag is raw/device-level with no owning equipment, so nothing + substitutes it and the deploy gate refuses the script (#1093, matching the + `OTSCRIPT_EQUIPCALC` marker on the same span). This hover needs no tag catalog. - **Completions** — typing `{{equip}}/` inside a `GetTag`/`SetVirtualTag` literal offers the owning equipment's **reference effective names** (needs an equipment context; inert on the shared ScriptEdit page). diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/DependencyExtractor.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/DependencyExtractor.cs index 2f9f5290b..a3e0d1896 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/DependencyExtractor.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/DependencyExtractor.cs @@ -103,7 +103,9 @@ public static class DependencyExtractor _rejections.Add(new DependencyRejection( Span: node.Span, Message: $"Call to ctx.{methodName} has no arguments. " + - "The tag path must be the first argument.")); + "The tag path must be the first argument.", + Kind: DependencyRejectionKind.NoArguments, + MethodName: methodName)); return; } @@ -122,7 +124,9 @@ public static class DependencyExtractor Message: $"Tag path passed to ctx.{methodName} must be a string literal. " + $"Dynamic paths (variables, concatenation, interpolation, method " + $"calls) are rejected at publish so the dependency graph can be " + - $"built statically. Got: {pathArg.Kind()} ({pathArg})")); + $"built statically. Got: {pathArg.Kind()} ({pathArg})", + Kind: DependencyRejectionKind.NotALiteral, + MethodName: methodName)); return; } @@ -131,7 +135,9 @@ public static class DependencyExtractor { _rejections.Add(new DependencyRejection( Span: literal.Span, - Message: $"Tag path passed to ctx.{methodName} is empty or whitespace.")); + Message: $"Tag path passed to ctx.{methodName} is empty or whitespace.", + Kind: DependencyRejectionKind.EmptyPath, + MethodName: methodName)); return; } @@ -154,4 +160,25 @@ public sealed record DependencyExtractionResult( } /// A single non-literal-path rejection with the exact source span for UI pointing. -public sealed record DependencyRejection(TextSpan Span, string Message); +/// The offending source span (the path argument, or the whole call when it has no arguments). +/// The refusal text (worded for a seam that refuses it — see ). +/// What is wrong with the path. +/// GetTag or SetVirtualTag. +public sealed record DependencyRejection( + TextSpan Span, + string Message, + DependencyRejectionKind Kind = DependencyRejectionKind.NotALiteral, + string MethodName = nameof(ScriptContext.GetTag)); + +/// What a found wrong with a tag-path argument. +public enum DependencyRejectionKind +{ + /// The path is not a string literal (a variable, concatenation, interpolation, a method call). + NotALiteral, + + /// The path is an empty or whitespace string literal. + EmptyPath, + + /// The call has no arguments at all (also a compile error). + NoArguments, +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs index c0c4c1a56..0439ff694 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs @@ -14,7 +14,8 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// blank source never reach Roslyn at runtime, so they pass; anything else goes through /// as VirtualTagContext → object?. /// AlarmPredicate — first (the scripted-alarm load rejects a -/// non-literal tag path before compiling), then as +/// non-literal tag path before compiling; which seams refuse one is +/// , lmxopcua#1083), then as /// AlarmPredicateContext → bool. No passthrough shortcut: the alarm engine always compiles. /// /// builds its compilation through the same private factory @@ -129,13 +130,15 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker return new CachedVerdict( ["equip token not substituted — " + string.Join("; ", unsubstituted.Select(f => f.Message))], Cacheable: true); + // lmxopcua#1083: which seams a non-literal tag path refuses (only the predicate — the alarm load runs the + // extractor) is ScriptCompileRules' decision, read by the editor too, so its error/warning split matches this. + var pathRefusals = ScriptCompileRules.TagPathFindings(request.Kind, source).Where(f => f.Refuses).ToArray(); + if (pathRefusals.Length > 0) + return new CachedVerdict( + ["dependency extraction rejected — " + string.Join("; ", pathRefusals.Select(f => f.Message))], + Cacheable: true); if (request.Kind == ScriptContextKind.AlarmPredicate) { - var extraction = DependencyExtractor.Extract(source); - if (!extraction.IsValid) - return new CachedVerdict( - ["dependency extraction rejected — " + string.Join("; ", extraction.Rejections.Select(r => r.Message))], - Cacheable: true); ScriptEvaluator.Verify(source); } else diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs index 5060d56b9..cddfb4bca 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs @@ -1,6 +1,7 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; using ZB.MOM.WW.OtOpcUa.Core.VirtualTags; namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; @@ -23,6 +24,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// The third refusal leg, , is already one shared analyzer and is called /// directly by both sides. /// +/// +/// The fourth is a seam rule rather than a compile rule: a NON-LITERAL tag path (ctx.GetTag(variable)) +/// refuses a scripted-alarm predicate only (, lmxopcua#1083). The gate +/// refuses what marks Refuses, and the editor draws exactly those as errors +/// and the rest as warnings — so the editor's severity cannot drift from the gate's verdict. +/// /// public static class ScriptCompileRules { @@ -38,6 +45,69 @@ public static class ScriptCompileRules kind is ScriptContextKind.VirtualTag or ScriptContextKind.Calculation && (string.IsNullOrWhiteSpace(source) || PassthroughScript.TryMatch(source, out _)); + /// + /// Whether a tag path that is not a non-empty string literal refuses a script run as + /// (lmxopcua#1083). Only a scripted-alarm predicate: the alarm load runs and + /// refuses the alarm, so the deploy gate does too. A VirtualTag or Calculation script with such a path deploys and + /// runs — the path is simply not a declared input (see ). Making the gate refuse it + /// there too was declined: it would start rejecting configurations that deploy today. + /// + /// The seam the script runs as. + /// True for . + public static bool RefusesNonLiteralTagPaths(ScriptContextKind kind) => kind == ScriptContextKind.AlarmPredicate; + + /// + /// Every ctx.GetTag / ctx.SetVirtualTag whose path is not a non-empty string literal + /// (), with what it means for : a refusal (the original + /// extractor text) where , otherwise an advisory that says what the path + /// does at runtime. The deploy gate refuses on the Refuses findings; the editor shows them as errors and the + /// others as warnings. + /// + /// The seam the script runs as. + /// The script source (user coordinates). + /// The findings; empty when every tag path is a non-empty literal. + public static IReadOnlyList TagPathFindings(ScriptContextKind kind, string? source) + { + source ??= string.Empty; + var rejections = DependencyExtractor.Extract(source).Rejections; + if (rejections.Count == 0) return []; + var refuses = RefusesNonLiteralTagPaths(kind); + var findings = new TagPathFinding[rejections.Count]; + for (var i = 0; i < rejections.Count; i++) + { + var r = rejections[i]; + findings[i] = new TagPathFinding(r.Span, refuses ? r.Message : AdvisoryFor(r, source), refuses); + } + return findings; + } + + // The text for a path the seam accepts: what actually happens at runtime. A VirtualTag / Calculation seam reads from + // its DECLARED inputs only (the literal ctx.GetTag paths, EquipmentScriptPaths.ExtractDependencyRefs) — those are + // what the mux subscribes and what re-triggers the script — so any other path reads as unknown. + private static string AdvisoryFor(DependencyRejection r, string source) + { + const string accepted = "The deploy accepts this in a VirtualTag or Calculation script (a scripted-alarm predicate refuses it)."; + var call = "ctx." + r.MethodName; + var text = r.Span.End <= source.Length ? source.Substring(r.Span.Start, r.Span.Length) : ""; + var isRead = r.MethodName == nameof(ScriptContext.GetTag); + return r.Kind switch + { + DependencyRejectionKind.NotALiteral when isRead => + $"Dynamic tag path `{text}`: it is not a string literal, so it is not a declared input of this script. " + + "Only literal paths are subscribed, so this read returns Bad (BadNodeIdUnknown, null value) unless the same " + + "path is also read with a literal elsewhere in the script, and a change to that tag does not re-run the script. " + + accepted, + DependencyRejectionKind.NotALiteral => + $"Dynamic tag path `{text}` passed to {call}: it is not a string literal, so dependency analysis cannot see " + + "the target. " + accepted, + DependencyRejectionKind.EmptyPath when isRead => + $"Empty tag path passed to {call}: the read always returns Bad (BadNodeIdUnknown, null value). " + accepted, + DependencyRejectionKind.EmptyPath => + $"Empty tag path passed to {call}: the call throws when it runs, failing the script. " + accepted, + _ => r.Message, + }; + } + /// /// The compiler diagnostics that make the runtime refuse a wrapped script: every /// diagnostic, wherever it is located (user source, wrapper, or none). @@ -103,3 +173,9 @@ public static class ScriptCompileRules return null; } } + +/// One finding of (lmxopcua#1083). +/// The offending span, in user-source coordinates. +/// What is wrong, worded for the seam (a refusal, or an advisory of what it does at runtime). +/// Whether the seam — and so the deploy gate — refuses the script for it. +public sealed record TagPathFinding(TextSpan Span, string Message, bool Refuses); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs index ff414262e..e00ab65a7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs @@ -121,8 +121,9 @@ public sealed class ScriptAnalysisService private static string Normalize(string? s) => (s ?? "").Replace("\r\n", "\n").Replace("\r", "\n"); /// Returns the markers for what the deploy gate would refuse — the runtime compile's own refusals (one - /// shared authority, ), sandbox-policy violations, disallowed dynamic tag paths and - /// the {{equip}} literal rules — plus advisory warnings. + /// shared authority, ), sandbox-policy violations, dynamic tag paths where the seam + /// refuses them (a predicate; a warning elsewhere, lmxopcua#1083) and the {{equip}} literal rules — plus + /// advisory warnings. /// The diagnose request carrying the script source and the analysis mode. /// The request's cancellation token; a cancelled request throws . /// The list of diagnostic markers, empty when the script is clean or analysis fails. @@ -159,9 +160,12 @@ public sealed class ScriptAnalysisService markers.Add(ToMarker(tree.GetMappedLineSpan(r.Span), 8, r.Message, "OTSCRIPT_FORBIDDEN")); } ct.ThrowIfCancellationRequested(); - // (3) DependencyExtractor — spans are offsets in the normalized user source; map directly. - foreach (var r in DependencyExtractor.Extract(code).Rejections) - markers.Add(ToUserMarker(code, r.Span, r.Message, "OTSCRIPT_DYNPATH")); + // (3) Non-literal tag paths (DependencyExtractor) — spans are offsets in the normalized user source; map + // directly. lmxopcua#1083: an ERROR only where the deploy gate refuses it (a scripted-alarm predicate), a + // WARNING in value / Calculation mode, where the script deploys and the path is just not a declared input. + // The split is ScriptCompileRules' (Refuses), the same flag the gate refuses on. + foreach (var f in ScriptCompileRules.TagPathFindings(kind, code)) + markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_DYNPATH", f.Refuses ? 8 : 4)); if (kind == ScriptContextKind.Calculation) { // (3a) lmxopcua#1065: a Calculation tag has no equipment — {{equip}} in any path literal is refused by the @@ -311,11 +315,11 @@ public sealed class ScriptAnalysisService sev, span.StartLinePosition.Line + 1, span.StartLinePosition.Character + 1, span.EndLinePosition.Line + 1, span.EndLinePosition.Character + 1, msg, code); - private static DiagnosticMarker ToUserMarker(string userSource, Microsoft.CodeAnalysis.Text.TextSpan span, string msg, string code) + private static DiagnosticMarker ToUserMarker(string userSource, Microsoft.CodeAnalysis.Text.TextSpan span, string msg, string code, int severity = 8) { var (sl, sc) = LineCol(userSource, span.Start); var (el, ec) = LineCol(userSource, span.End); - return new DiagnosticMarker(8, sl, sc, el, ec, msg, code); + return new DiagnosticMarker(severity, sl, sc, el, ec, msg, code); } private static (int Line, int Col) LineCol(string code, int offset) @@ -445,6 +449,19 @@ public sealed class ScriptAnalysisService return new CompletionItem(symbol.Name, symbol.Name, symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), kind); } + /// + /// The hover for a {{equip}} path literal in a Calculation script (lmxopcua#1093): it says the token is + /// refused there and why, matching the OTSCRIPT_EQUIPCALC marker on the same span (lmxopcua#1065). + /// + /// The literal's path, already backtick-escaped for markdown. + /// The hover markdown. + internal static string CalculationEquipHover(string escapedPath) => + $"**`{{{{equip}}}}` is refused in a Calculation script** `{escapedPath}`\n\n" + + "A Calculation tag is a raw, device-level tag: it has no owning equipment, so `{{equip}}` has nothing to " + + "resolve to, and the Calculation seam never substitutes it. The deploy gate refuses the script " + + "(`equip token in a Calculation script`). Read the source by its literal RawPath instead; " + + "`{{equip}}/` is for VirtualTags, which belong to an equipment."; + /// Computes hover information (tag-path info or C# symbol info) for the position under the caret. /// The hover request carrying the script source and caret position. /// The request's cancellation token; a cancelled request throws . @@ -463,21 +480,27 @@ public sealed class ScriptAnalysisService // Tag-path hover takes priority over C# symbol resolution: when the caret sits on a // ctx.GetTag("…")/ctx.SetVirtualTag("…") path literal, show the resolved tag's info // (or note it's not a known configured tag path) instead of the string-literal symbol. - if (_catalog is not null && TryGetTagPathLiteral(token, out var tagPath, out var isSetVirtualTag) && !string.IsNullOrEmpty(tagPath)) + if (TryGetTagPathLiteral(token, out var tagPath, out var isSetVirtualTag) && !string.IsNullOrEmpty(tagPath) + && (_catalog is not null || tagPath.Contains(EquipmentScriptPaths.EquipToken, StringComparison.Ordinal))) { static string Code(string s) => s.Replace("`", "\\`"); // Equipment-relative literal (contains the {{equip}} token): it cannot resolve to a // configured path as-typed (the token is only substituted at deploy), so short-circuit // before GetTagInfoAsync and explain the token instead of warning "not a known path". + // Needs no catalog, so it is answered even where none is wired. if (tagPath.Contains(EquipmentScriptPaths.EquipToken, StringComparison.Ordinal)) { + // lmxopcua#1093: in a Calculation script the token is refused (OTSCRIPT_EQUIPCALC, #1065), so the + // VirtualTag explanation ("resolves … when deployed") would contradict the marker on the same span. + if (ScriptAnalysisModes.KindOf(req.Mode) == ScriptContextKind.Calculation) + return new HoverResponse(CalculationEquipHover(Code(tagPath))); return new HoverResponse( $"**Equipment-relative path** `{Code(tagPath)}`\n\n" + "`{{equip}}/` resolves through the owning equipment's tag reference " + "(by effective name) to the backing raw tag's path when the VirtualTag is deployed."); } - var info = await _catalog.GetTagInfoAsync(tagPath, ct); + var info = await _catalog!.GetTagInfoAsync(tagPath, ct); var tagMd = info is null ? $"**Tag path** `{Code(tagPath)}`\n\n⚠ Not a known configured tag path." : $"**Tag path** `{Code(info.Path)}`\n\n{info.Kind} · Type **{info.DataType}**" diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs index cfa43f049..2dcc9d379 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs @@ -101,9 +101,11 @@ public sealed class DiagnoseTests Diag(code).Any(x => x.Severity == 8).ShouldBe(publishRefuses); } + // lmxopcua#1083: flagged as a WARNING in the (default) value mode — the deploy gate accepts it there; only a + // scripted-alarm predicate refuses it (EditorGateParityTests pins the per-mode split). [Fact] public void Dynamic_tag_path_is_flagged() => Diag("""var p = "A"; return ctx.GetTag(p).Value;""") - .ShouldContain(x => x.Message.Contains("literal")); + .ShouldContain(x => x.Code == "OTSCRIPT_DYNPATH" && x.Severity == 4 && x.Message.Contains("literal")); // lmxopcua#1063: this used to assert the OPPOSITE ("does not produce a phantom preamble marker"). CS0161 is not a // phantom: Roslyn pins it on the wrapper's Run, and the runtime compile / deploy gate refuse the script. It is now diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EditorGateParityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EditorGateParityTests.cs index f8c9340ad..b10853a89 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EditorGateParityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EditorGateParityTests.cs @@ -13,9 +13,10 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis; /// forever. Both sides now share and . /// /// -/// Excluded on purpose: a DYNAMIC tag path (ctx.GetTag(variable)) in a value or Calculation script. The editor -/// marks it an error in every mode while the gate refuses it only for a scripted-alarm predicate — a known, -/// editor-stricter divergence tracked separately (it is not a compile rule, and either fix changes behaviour). +/// A DYNAMIC tag path (ctx.GetTag(variable), OTSCRIPT_DYNPATH) is in the corpus since lmxopcua#1083: the +/// editor used to mark it an error in every mode while the gate refuses it only for a scripted-alarm predicate. The +/// split is now 's — an error where the gate refuses, a warning +/// elsewhere — so it gets the same verdict per mode. /// public sealed class EditorGateParityTests { @@ -57,6 +58,15 @@ public sealed class EditorGateParityTests """return ctx.GetTag("Plant/{{equip}}/Speed").Value;""", """ctx.SetVirtualTag("{{equip}}/Out", 1); return 1;""", """ctx.Logger.Information("{{equip}} is only a log string"); return 1;""", + // Dynamic / empty tag paths (#1083): refused for a predicate only. Bool-returning forms too, so the predicate's + // refusal is the path's, not a non-bool return. + """var p = "A"; return ctx.GetTag(p).Value;""", + """var p = "A"; return ctx.GetTag(p).Value is null;""", + """return ctx.GetTag("A" + "B").Value is null;""", + """return ctx.GetTag($"A{1}").Value is null;""", + """return ctx.GetTag("").Value is null;""", + """var p = "Out"; ctx.SetVirtualTag(p, 1); return true;""", + """var p = "A"; return ctx.GetTag(p).Value is null && ctx.GetTag("A").Value is null;""", ]; string[] modes = [ScriptAnalysisModes.Value, ScriptAnalysisModes.Calculation, ScriptAnalysisModes.AlarmPredicate]; var data = new TheoryData(); @@ -103,6 +113,27 @@ public sealed class EditorGateParityTests Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], ct)[0].Passed.ShouldBeTrue(); } + /// + /// lmxopcua#1083: a dynamic tag path is an editor ERROR exactly where the gate refuses it (a predicate) and a + /// WARNING where the gate accepts it (value, Calculation) — and the warning still shows, so the author learns the + /// path is not a declared input. Positive control for the corpus rows: the predicate really is refused by both. + /// + [Theory] + [InlineData(ScriptAnalysisModes.Value, 4, true)] + [InlineData(ScriptAnalysisModes.Calculation, 4, true)] + [InlineData(ScriptAnalysisModes.AlarmPredicate, 8, false)] + public void A_dynamic_tag_path_is_an_error_only_where_the_gate_refuses_it(string mode, int severity, bool gatePasses) + { + const string source = """var p = "A"; return ctx.GetTag(p).Value is null;"""; + var ct = TestContext.Current.CancellationToken; + var dynpath = Svc.Diagnose(new DiagnoseRequest(source, Mode: mode), ct).Markers.Single(m => m.Code == "OTSCRIPT_DYNPATH"); + dynpath.Severity.ShouldBe(severity); + (dynpath.StartLineNumber, dynpath.StartColumn).ShouldBe((1, 32)); // on the `p` argument + if (severity == 4) dynpath.Message.ShouldContain("not a declared input"); + Gate.Check([new DeployScriptCheckRequest(ScriptAnalysisModes.KindOf(mode), source)], ct)[0].Passed.ShouldBe(gatePasses); + ScriptCompileRules.RefusesNonLiteralTagPaths(ScriptAnalysisModes.KindOf(mode)).ShouldBe(!gatePasses); + } + [Fact] public void The_editor_wraps_scripts_in_the_runtimes_own_wrapper_text() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipTokenEditorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipTokenEditorTests.cs index 1a1c3a6fd..78cea5e4d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipTokenEditorTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipTokenEditorTests.cs @@ -73,6 +73,32 @@ public sealed class EquipTokenEditorTests md.ShouldNotContain("Not a known"); } + /// + /// lmxopcua#1093: in Calculation mode the token is refused (OTSCRIPT_EQUIPCALC on the same span, #1065), so the + /// hover says so instead of the VirtualTag "resolves … when deployed" text that contradicted the marker. Also + /// answered without a catalog (the hover needs none for this literal). The value-mode hover above is the control. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task Hover_on_equip_token_literal_in_calculation_mode_says_it_is_refused(bool withCatalog) + { + var svc = withCatalog ? Svc : new ScriptAnalysisService(); + const string code = """return ctx.GetTag("{{equip}}/Speed").Value;"""; + var md = (await svc.Hover(new HoverRequest(code, 1, 24, Mode: ScriptAnalysisModes.Calculation), TestContext.Current.CancellationToken)).Markdown; + md.ShouldNotBeNull(); + md!.ShouldContain("refused in a Calculation script"); + md.ShouldContain("no owning equipment"); + md.ShouldContain("{{equip}}/Speed"); + md.ShouldNotContain("resolves through the owning equipment"); + // The marker on the same span agrees. + svc.Diagnose(new DiagnoseRequest(code, Mode: ScriptAnalysisModes.Calculation), TestContext.Current.CancellationToken) + .Markers.ShouldContain(m => m.Code == "OTSCRIPT_EQUIPCALC" && m.Severity == 8); + // Value mode on the same service keeps the VirtualTag explanation. + (await svc.Hover(new HoverRequest(code, 1, 24, Mode: ScriptAnalysisModes.Value), TestContext.Current.CancellationToken)) + .Markdown.ShouldNotBeNull().ShouldContain("Equipment-relative"); + } + [Fact] public async Task Diagnostic_flags_unresolved_equip_reference() { // "Missing" is not one of the equipment's references (Speed/Temp) → a diagnostic, matching the From 61546d5aab353c77d1e22da53c4634aff1787607 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Fri, 4 Dec 2026 15:14:16 -0500 Subject: [PATCH 2/3] fix(scripting): #1092 a returned concrete collection (List, HashSet, ...) is materialised into the same typed array in both runners ScriptResultMaterializer returned a non-array ICollection as-is (capped by Count only), so in process the host got the List itself while the out-of-process worker, whose wire carries arrays but no collection type, answered "unsupported type" for the same script. Every non-array, non-string sequence now goes through the one materialisation: a collection is held to Scripting:MaxResultElements by its Count before it is copied, then becomes T[] of its IEnumerable element type; an open element type (List, List>) or none (ArrayList) is refused like the lazy equivalent. Both runners give double[] for a List. ParityTests.Result_materialisation_and_the_element_cap_agree gains list / at-cap / over-cap / hash set / queue / List / nested-list rows plus a positive control (6 rows + the control fail against the old materializer). ContainmentTests' "unsupported result type" example moves from List (now int[]) to KeyValuePair. Behaviour change: a script returning List (or another open element type) now fails the run (Bad + script log) in process too, as the lazy form already did. --- docs/ScriptEditor.md | 6 +++- docs/VirtualTags.md | 8 +++-- .../ScriptResultMaterializer.cs | 35 ++++++++++++------- .../ScriptResultMaterializerTests.cs | 27 ++++++++++++-- .../ContainmentTests.cs | 10 ++++-- .../ParityTests.cs | 29 +++++++++++++++ 6 files changed, 94 insertions(+), 21 deletions(-) diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index b17eb4778..1ef65b1ec 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -264,7 +264,11 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: 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 + A concrete collection (`List`, `HashSet`, `Queue`, …) gets the same treatment + since #1092 — it is held to the cap by its `Count`, then copied into the same typed array + (`double[]`, …), and refused for an open element type (`List`) — because the out-of-process + worker's wire carries arrays but no collection type (it used to answer `unsupported type` while the + in-process runner returned the list itself). Arrays, 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)". The out-of-process diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 4f363c940..7ead34ff2 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -73,7 +73,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). **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". +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; since lmxopcua#1092 a concrete non-array collection such as a `List` is copied into the same typed array — capped by its `Count` first — rather than returned as-is, so both runners give `double[]`; `List` and other open element types are now refused like their lazy equivalents); 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". @@ -130,8 +130,10 @@ processes: (512 MiB), a Windows Job Object (kill-on-close, one process, a commit backstop), a random pipe (current-user-only on Linux; an explicit host + worker-identity ACL on Windows) with a launch nonce in its environment, and no Akka / gRPC assemblies in its folder. It exits on pipe end of stream or when its parent pid disappears. Results cross as protobuf `Variant`s carrying the exact CLR type, so - `(short)ctx.GetTag(x).Value` behaves as in process; an input or result type with no tag (a `List`, a `Guid`) - is an explicit `unsupported type: …` failure rather than a conversion — a behaviour change from in process. + `(short)ctx.GetTag(x).Value` behaves as in process; an input or result type with no tag (a `Guid`, an array of + `KeyValuePair`) is an explicit `unsupported type: …` failure rather than a conversion — a behaviour change from in + process. A returned collection (`List`) is not one of those since lmxopcua#1092: both runners copy it into a + typed array first. - **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 already quarantined when its single-flight slot is released — no trigger can re-run it in the restart gap. A worker 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 e055a8a0d..10d105118 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs @@ -26,13 +26,19 @@ public sealed class ScriptResultException : InvalidOperationException /// 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. +/// What changes: every sequence that is not an array or a string — a lazy one, or a concrete collection such as +/// a List<double> or a HashSet<string> — 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 are +/// returned as-is (fully built by the run) but are still held to the element cap. Everything else — scalars, +/// strings, null — is untouched. +/// +/// +/// Concrete collections used to be returned as-is too (lmxopcua#1092): in process the host got the +/// List<T> itself, while the out-of-process worker, whose wire carries arrays but no collection +/// type, answered "unsupported type" for the same script. Copying a collection into an array is the one value +/// both runners can give; a collection that reports its size is held to the cap BEFORE it is copied. /// /// /// This does NOT make the in-process runner a hard sandbox: memory exhaustion inside the run and a @@ -64,23 +70,23 @@ public static class ScriptResultMaterializer return array; case ICollection collection: EnforceCap(collection.Count, maxElements); - return value; + return MaterializeSequence(collection, maxElements, "collection"); case IEnumerable sequence: - return MaterializeLazy(sequence, maxElements); + return MaterializeSequence(sequence, maxElements, IsGenericCollection(sequence.GetType()) ? "collection" : "lazy sequence"); default: return value; } } - private static object MaterializeLazy(IEnumerable sequence, int maxElements) + private static object MaterializeSequence(IEnumerable sequence, int maxElements, string what) { var elementType = ElementTypeOf(sequence.GetType()) ?? throw new ScriptResultException( - $"The script returned a lazy sequence ({sequence.GetType().Name}) with no IEnumerable element type; " + + $"The script returned a {what} ({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; " + + $"The script returned a {what} of '{elementType.Name}', which can contain another sequence or itself; " + "return a typed array of a concrete type (double[], string[], …)."); var items = new List(); @@ -117,6 +123,11 @@ public static class ScriptResultMaterializer return found; } + // ICollection / IReadOnlyCollection without the non-generic ICollection (HashSet, …): only the wording. + private static bool IsGenericCollection(Type type) => + type.GetInterfaces().Any(i => i.IsGenericType + && (i.GetGenericTypeDefinition() == typeof(ICollection<>) || i.GetGenericTypeDefinition() == typeof(IReadOnlyCollection<>))); + private static bool IsOpenSlot(Type t) => t == typeof(object) || t.IsInterface || t.IsAbstract || (t != typeof(string) && typeof(IEnumerable).IsAssignableFrom(t)); 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 index 4b03c8eac..5464d5545 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs @@ -47,17 +47,38 @@ public sealed class ScriptResultMaterializerTests } [Fact] - public void Arrays_collections_strings_scalars_and_null_pass_through_unchanged_positive_controls() + public void Arrays_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(); } + /// + /// lmxopcua#1092: a concrete collection becomes the same typed array a lazy sequence does — the out-of-process + /// worker's wire has no collection type, so returning the collection as-is made the two runners disagree. + /// + [Fact] + public void A_concrete_collection_becomes_a_typed_array() + { + ScriptResultMaterializer.Materialize(new List { 1, 2 }, 100).ShouldBeOfType().ShouldBe([1, 2]); + ScriptResultMaterializer.Materialize(new HashSet { "a" }, 100).ShouldBeOfType().ShouldBe(["a"]); + ScriptResultMaterializer.Materialize(new Queue([1.5]), 100).ShouldBeOfType().ShouldBe([1.5]); + ScriptResultMaterializer.Materialize(new List(new int[100]), 100).ShouldBeOfType().Length.ShouldBe(100); + } + + [Fact] + public void A_collection_of_an_open_or_unknown_element_type_is_refused_like_a_lazy_one() + { + Should.Throw(() => ScriptResultMaterializer.Materialize(new List { 1 }, 100)) + .Message.ShouldContain("collection of 'Object'"); + Should.Throw(() => ScriptResultMaterializer.Materialize(new List> { new() { 1 } }, 100)); + Should.Throw(() => ScriptResultMaterializer.Materialize(new System.Collections.ArrayList { 1 }, 100)) + .Message.ShouldContain("no IEnumerable element type"); + } + [Fact] public void An_oversized_array_or_collection_is_refused_by_the_same_cap() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs index fcc5964da..1c349b0f3 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs @@ -421,9 +421,15 @@ public sealed class ContainmentTests public async Task Unsupported_input_and_result_types_are_explicit_failures() { await using var runner = Scripts.Runner(Scripts.Options()); - var result = await runner.RunAsync(Scripts.Vt("list", "return new System.Collections.Generic.List { 1 };"), Ct); + var result = await runner.RunAsync(Scripts.Vt("pair", "return new System.Collections.Generic.KeyValuePair(1, 2);"), Ct); result.Status.ShouldBe(ScriptRunStatus.Failed); - result.Reason!.ShouldStartWith("unsupported type: script returned a value of unsupported type System.Collections.Generic.List"); + result.Reason!.ShouldStartWith("unsupported type: script returned a value of unsupported type System.Collections.Generic.KeyValuePair"); + + // lmxopcua#1092: a returned List is no longer one of these — both runners copy it into a typed array first + // (ScriptResultMaterializer), so it crosses the wire as int[] (this used to be the "unsupported type" example). + var list = await runner.RunAsync(Scripts.Vt("list", "return new System.Collections.Generic.List { 1 };"), Ct); + list.Status.ShouldBe(ScriptRunStatus.Ok, list.Reason); + list.Value.ShouldBeOfType().ShouldBe([1]); var input = await runner.RunAsync(Scripts.Vt("guid", "return 1;", inputs: Scripts.Input("g", Guid.NewGuid())), Ct); input.Status.ShouldBe(ScriptRunStatus.Failed); 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 c75a2f1d6..a817e633d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ParityTests.cs @@ -94,6 +94,15 @@ public sealed class ParityTests { "over-cap array", "return new double[5];" }, { "at-cap array", "return new double[4];" }, { "empty lazy", "return System.Linq.Enumerable.Empty();" }, + // lmxopcua#1092: a concrete non-array collection. In process it used to come back as the List itself (capped by + // Count, but not an array), while the worker answered "unsupported type" — now both return the same typed array. + { "list", "return new System.Collections.Generic.List { 1.5, 2.5 };" }, + { "at-cap list", "return new System.Collections.Generic.List { 1, 2, 3, 4 };" }, + { "over-cap list", "return new System.Collections.Generic.List(new double[5]);" }, + { "hash set", "return new System.Collections.Generic.HashSet { \"a\" };" }, + { "queue", "var q = new System.Collections.Generic.Queue(); q.Enqueue(3); q.Enqueue(4); return q;" }, + { "list of object", "return new System.Collections.Generic.List { 1, \"a\" };" }, + { "nested list", "return new System.Collections.Generic.List> { new() { 1 } };" }, }; [Theory] @@ -115,6 +124,26 @@ public sealed class ParityTests Same(actual.Value, expected.Value, name); } + /// + /// lmxopcua#1092 positive control for the theory above (it would also pass if both runners refused a List): a + /// returned List<double> is the same double[] in both runners. + /// + [Fact] + public async Task A_returned_list_is_the_same_typed_array_in_both_runners() + { + using var inProcess = new InProcessScriptRunner(new ScriptingOptions { MaxResultElements = 4 }); + var options = Scripts.Options(); + options.MaxResultElements = 4; + await using var outOfProcess = Scripts.Runner(options); + var invocation = Scripts.Vt("result-list-control", "return new System.Collections.Generic.List { 1.5, 2.5 };"); + + foreach (var outcome in new[] { await inProcess.RunAsync(invocation, Ct), await outOfProcess.RunAsync(invocation, Ct) }) + { + outcome.Status.ShouldBe(ScriptRunStatus.Ok, outcome.Reason); + outcome.Value.ShouldBeOfType().ShouldBe([1.5, 2.5]); + } + } + [Fact] public async Task The_worker_holds_a_lazy_result_to_the_configured_cap() { From cb5250facea4921d7f7c9e33ff1f81ceda057f41 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Fri, 4 Dec 2026 15:40:40 -0500 Subject: [PATCH 3/3] =?UTF-8?q?test(script-worker):=20#1092=20the=20two=20?= =?UTF-8?q?"slow=20caller=20does=20not=20starve=20the=20reader"=20tests=20?= =?UTF-8?q?use=20a=201.5=20s=20silence=20limit=20(3.5=20s=20block)=20?= =?UTF-8?q?=E2=80=94=20measured=20worker-side=20whole-process=20stalls,=20?= =?UTF-8?q?not=20heartbeat=20starvation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SupervisionTests.A_caller_that_blocks_after_its_result_does_not_starve_the_reader and its WorkerSoftClockTests sibling killed a healthy worker for "sent nothing for ~344 ms" at a 300 ms limit (3 x 100 ms) on a loaded macOS box. Investigated before loosening, with send-stamped heartbeats (temporary instrumentation, not committed): - the late beats were late at the WORKER (290-380 ms between sends, 1-150 ms transit), mid run, not during startup; - a cold worker beat every 100 +/- 8 ms from its first beat in 50 isolated runs at load 60-200, with and without 28 CPU burners, and in full-suite runs under 40 burners, with the heartbeat on the thread pool or on a dedicated thread alike (A/B) — no JIT / Roslyn / pool-injection starvation to fix; - the stalls appeared only in a full-suite run under the real load of other agents, with the box 24 of 25.6 GB into swap: whole-process stalls no worker change removes. So the tests take a 1.5 s limit (production: 3 s) and block the caller 3.5 s. Mutation still caught: with callers resumed inline on the reader both fail (the Supervision test by the heartbeat kill itself). 20/20 runs of the pair pass. --- .../SupervisionTests.cs | 19 ++++++++++++++--- .../WorkerSoftClockTests.cs | 21 +++++++++++++++---- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/SupervisionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/SupervisionTests.cs index 1fdceb1d3..9ef339c0e 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/SupervisionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/SupervisionTests.cs @@ -546,11 +546,23 @@ public sealed class SupervisionTests /// /// lmxopcua#789: callers resume on the connection's result dispatcher, never on the pipe reader — so a consumer /// that blocks after its await (the Calculation pump publishes to OPC UA subscribers there) cannot stop the reader - /// from taking heartbeats and get a healthy worker killed for silence. Here a 100 ms heartbeat (kill after 300 ms - /// of silence) and a continuation that blocks for 1.5 s. Mutation check: resume callers inline on the reader (a + /// from taking heartbeats and get a healthy worker killed for silence. Here a 100 ms heartbeat (kill after 1.5 s + /// of silence) and a continuation that blocks for 3.5 s. Mutation check: resume callers inline on the reader (a /// synchronous-continuation TaskCompletionSource completed by the reader, no dispatcher) and the worker is killed /// (KilledHeartbeat). /// + /// + /// lmxopcua#1092: the limit used to be three 100 ms intervals (300 ms), and this pair of tests failed + /// intermittently on a loaded macOS dev box (about 1 full-suite run in 3–5), the worker killed for "sent nothing + /// for 344 ms" while the reader and the dispatcher worked correctly. Measured with send-stamped heartbeats: the + /// WORKER sent a beat 290–380 ms late (1–150 ms in transit), mid-run, not at startup — a cold worker beat every + /// 100 ± 8 ms from its first beat in 50 isolated runs at load 60–200, with and without 28 CPU burners, and no + /// run outside that real-load full suite (24 of 25.6 GB into swap at the time) stalled at all, whether the + /// heartbeat ran on the thread pool or on a dedicated thread. Those are whole-process stalls of the box, not + /// starvation a worker change can remove. So the limit is 1.5 s (production's is 3 s) and the block 3.5 s: a + /// reader held by the caller still goes silent 2 s past the limit, so the mutation is still killed, and the + /// resumedOn assertion pins the thread outright. + /// [Fact] public async Task A_caller_that_blocks_after_its_result_does_not_starve_the_reader() { @@ -558,6 +570,7 @@ public sealed class SupervisionTests var heartbeat = TimeSpan.FromMilliseconds(100); await using var runner = TightHeartbeatRunner(heartbeat, TimeSpan.FromSeconds(60), sink); var worker = WarmTight(runner, await runner.RunAsync(Scripts.Vt("warm", Healthy), Ct), heartbeat, sink); + worker.SilenceLimit = TimeSpan.FromMilliseconds(1_500); // see remarks (#1092) string? resumedOn = null; await runner.RunAsync(Scripts.Vt("warm", Healthy), Ct).ContinueWith(t => @@ -565,7 +578,7 @@ public sealed class SupervisionTests // Runs wherever RunAsync's own continuation completed it: the thread that resumed the caller. resumedOn = Thread.CurrentThread.Name; t.Result.Value.ShouldBe(7); - Thread.Sleep(1_500); + Thread.Sleep(3_500); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); // Behaviour first: the worker was not killed for silence while the caller blocked. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/WorkerSoftClockTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/WorkerSoftClockTests.cs index 926ecbe33..2a7fa4dd8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/WorkerSoftClockTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/WorkerSoftClockTests.cs @@ -271,9 +271,22 @@ public sealed class WorkerSoftClockTests /// /// Review F1: the soft notice is handled on the pipe READER, and the caller's resumption is the caller's code. It /// must go through the result dispatcher like a result does: a continuation that blocks for 1.5 s must not hold up - /// the reader, or the next heartbeats sit unread and a healthy worker is killed for silence (300 ms here). Before - /// the fix the continuation ran inline on the reader and the worker was killed (KilledHeartbeat). + /// the reader, or the next heartbeats sit unread and a healthy worker is killed for silence (1.5 s here, with a + /// 3.5 s block). Before the fix the continuation ran inline on the reader and the worker was killed (KilledHeartbeat). /// + /// + /// Same limit as SupervisionTests.A_caller_that_blocks_after_its_result_does_not_starve_the_reader: + /// lmxopcua#1092: the limit used to be three 100 ms intervals (300 ms), and this pair of tests failed + /// intermittently on a loaded macOS dev box (about 1 full-suite run in 3–5), the worker killed for "sent nothing + /// for 344 ms" while the reader and the dispatcher worked correctly. Measured with send-stamped heartbeats: the + /// WORKER sent a beat 290–380 ms late (1–150 ms in transit), mid-run, not at startup — a cold worker beat every + /// 100 ± 8 ms from its first beat in 50 isolated runs at load 60–200, with and without 28 CPU burners, and no + /// run outside that real-load full suite (24 of 25.6 GB into swap at the time) stalled at all, whether the + /// heartbeat ran on the thread pool or on a dedicated thread. Those are whole-process stalls of the box, not + /// starvation a worker change can remove. So the limit is 1.5 s (production's is 3 s) and the block 3.5 s: a + /// reader held by the caller still goes silent 2 s past the limit, so the mutation is still killed, and the + /// resumedOn assertion pins the thread outright. + /// [Fact] public async Task A_slow_continuation_of_a_soft_timeout_does_not_stall_the_reader() { @@ -286,7 +299,7 @@ public sealed class WorkerSoftClockTests var entry = await connection.EnsureLoadedAsync("k", ContextKind.VirtualTag, Runaway, SHA256.HashData(Encoding.UTF8.GetBytes(Runaway)), []).WaitAsync(TimeSpan.FromSeconds(60), Ct); entry.Outcome.ShouldNotBeNull().Ok.ShouldBeTrue(); - connection.SilenceLimit = heartbeat * 3; // armed only once the cold start is over (see SupervisionTests) + connection.SilenceLimit = TimeSpan.FromMilliseconds(1_500); // armed once the cold start is over; see remarks (#1092) var softT = TimeSpan.FromMilliseconds(200); var pending = connection.Submit("k", @@ -297,7 +310,7 @@ public sealed class WorkerSoftClockTests { resumedOn = Thread.CurrentThread.Name; t.Result.ShouldBeSameAs(PendingEval.SoftTimedOut); - Thread.Sleep(1_500); + Thread.Sleep(3_500); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); await slowConsumer.WaitAsync(TimeSpan.FromSeconds(10), Ct);