Merge scripting follow-ups: one shared compile rule for editor + gate, CS0161/injection now flagged in the editor (#1063), worker applies the result materialisation cap (#1064), {{equip}} in Calculation scripts refused at gate + editor (#1065)

This commit is contained in:
Joseph Doherty
2026-12-03 16:49:40 -05:00
24 changed files with 729 additions and 191 deletions
@@ -76,13 +76,15 @@ else
<h2 class="panel-head">Source</h2>
<div style="padding:1rem">
@* #1025: the editor analyses the script as the seam that runs it — the deploy gate compiles a scripted-alarm
predicate as `bool Run(AlarmPredicateContext)`, a VirtualTag/Calculation script as a value script.
predicate as `bool Run(AlarmPredicateContext)`, a VirtualTag/Calculation script as a value script, and
refuses {{equip}} in a Calculation script (#1065), which is what Calculation mode adds.
Defaults from the script's current users; the author can switch for a not-yet-used script. *@
<div class="mb-2 d-flex align-items-center gap-2">
<label class="form-label mb-0" for="@(_fieldId + "-mode")">Analyse as</label>
<select id="@(_fieldId + "-mode")" class="form-select form-select-sm w-auto" value="@_mode"
@onchange="e => ChangeMode(e.Value?.ToString(), presentation)">
<option value="@ScriptAnalysisModes.Value">Virtual tag / Calculation value script</option>
<option value="@ScriptAnalysisModes.Value">Virtual tag value script</option>
<option value="@ScriptAnalysisModes.Calculation">Calculation tag script (no {{equip}})</option>
<option value="@ScriptAnalysisModes.AlarmPredicate">Scripted-alarm predicate (must return bool)</option>
</select>
</div>
@@ -140,7 +142,7 @@ else
}
private void ChangeMode(string? value, long generation)
{
if (Current(generation)) _mode = ScriptAnalysisModes.IsPredicate(value) ? ScriptAnalysisModes.AlarmPredicate : ScriptAnalysisModes.Value;
if (Current(generation)) _mode = ScriptAnalysisModes.Normalize(value);
}
private void OnMarkersChanged(ScriptProblemReport report, long generation)
{
@@ -75,7 +75,10 @@
Editing shared script "<span class="mono">@_scriptName</span>" — used by
@_scriptUsageCount virtual tag(s). Changes affect every tag using it.
</div>
<MonacoEditor AriaLabel="Calculation script source" @bind-Value="_scriptSource" Height="300px" />
@* #1065: Calculation mode — a Calculation tag has no equipment, so {{equip}} is refused here exactly as the deploy
gate refuses it. *@
<MonacoEditor AriaLabel="Calculation script source" @bind-Value="_scriptSource" Height="300px"
Mode="@ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis.ScriptAnalysisModes.Calculation" />
@if (!string.IsNullOrWhiteSpace(_scriptError))
{
<div class="text-danger small mt-2">@_scriptError</div>
@@ -1,24 +1,49 @@
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
/// <summary>
/// Which seam the editor analyses a script as (lmxopcua#1025). The deploy gate compiles each script as the seam that
/// uses it, so the editor has to wrap the source the same way: a value script is
/// <c>object Run(ScriptGlobals&lt;VirtualTagContext&gt;)</c> (VirtualTag and Calculation share it); a scripted-alarm
/// predicate is <c>bool Run(ScriptGlobals&lt;AlarmPredicateContext&gt;)</c>. Carried as a string on the wire; null,
/// blank or anything unrecognised means <see cref="Value"/>.
/// predicate is <c>bool Run(ScriptGlobals&lt;AlarmPredicateContext&gt;)</c>. A Calculation script compiles as a value
/// script but is held to one more gate rule — no <c>{{equip}}</c> token (lmxopcua#1065) — so it has its own mode.
/// Carried as a string on the wire; null, blank or anything unrecognised means <see cref="Value"/>.
/// </summary>
public static class ScriptAnalysisModes
{
/// <summary>A VirtualTag / Calculation value script (the default).</summary>
/// <summary>A VirtualTag value script (the default).</summary>
public const string Value = "value";
/// <summary>A scripted-alarm predicate: must return <c>bool</c>.</summary>
public const string AlarmPredicate = "alarmPredicate";
/// <summary>A Calculation-tag script: the value shape, plus the Calculation-only refusal of <c>{{equip}}</c>.</summary>
public const string Calculation = "calculation";
/// <summary>True when <paramref name="mode"/> selects the predicate shape.</summary>
/// <param name="mode">The wire value.</param>
/// <returns>Whether it names <see cref="AlarmPredicate"/>.</returns>
public static bool IsPredicate(string? mode) => string.Equals(mode, AlarmPredicate, StringComparison.OrdinalIgnoreCase);
/// <summary>True when <paramref name="mode"/> selects the Calculation rules.</summary>
/// <param name="mode">The wire value.</param>
/// <returns>Whether it names <see cref="Calculation"/>.</returns>
public static bool IsCalculation(string? mode) => string.Equals(mode, Calculation, StringComparison.OrdinalIgnoreCase);
/// <summary>The deploy-gate seam a mode analyses as — what the gate's checker is asked for the same script.</summary>
/// <param name="mode">The wire value.</param>
/// <returns>The seam.</returns>
public static ScriptContextKind KindOf(string? mode) =>
IsPredicate(mode) ? ScriptContextKind.AlarmPredicate
: IsCalculation(mode) ? ScriptContextKind.Calculation
: ScriptContextKind.VirtualTag;
/// <summary>The canonical wire value for <paramref name="mode"/> (unrecognised means <see cref="Value"/>).</summary>
/// <param name="mode">The wire value.</param>
/// <returns>One of the three constants.</returns>
public static string Normalize(string? mode) =>
IsPredicate(mode) ? AlarmPredicate : IsCalculation(mode) ? Calculation : Value;
}
// EquipmentId (optional) carries the owning-equipment context the {{equip}}/<RefName> completion +
@@ -51,19 +51,14 @@ public sealed class ScriptAnalysisService
/// </summary>
private sealed class Shape
{
public Shape(Type contextType, string returnType)
public Shape(Type contextType, string preamble)
{
Sandbox = ScriptSandbox.Build(contextType);
// Mirrors ScriptEvaluator's wrapper EXACTLY (usings from the sandbox + the Run(ScriptGlobals<TContext>)
// shape). The value shape's return type is `object` so a shared script stays valid regardless of any
// virtual tag's DataType; the predicate shape is `bool`, exactly as the alarm engine compiles it.
var usings = string.Join("\n", Sandbox.Imports.Select(i => $"using {i};"));
var globalsType = $"global::{typeof(ScriptGlobals<>).Namespace}.ScriptGlobals<global::{contextType.FullName}>";
Preamble = usings + "\n\n"
+ "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n"
+ "public static class CompiledScript\n{\n"
+ $" public static {returnType} Run({globalsType} globals)\n {{\n"
+ " var ctx = globals.ctx;\n#line 1\n";
// The runtime's OWN wrapper text (ScriptEvaluator<TContext, TResult>.WrapperPreamble / WrapperSuffix) — the
// usings, the Run(ScriptGlobals<TContext>) signature and #line 1 — never a local copy (lmxopcua#1063). The
// value shape compiles to `object` so a shared script stays valid regardless of any virtual tag's DataType;
// the predicate shape is `bool`, exactly as the alarm engine compiles it.
Preamble = preamble;
var compilation = CSharpCompilation.Create(
"ScriptAnalysis", new[] { Parse("", CancellationToken.None) }, Sandbox.References, CompileOptions);
_ = compilation.GetSpecialType(SpecialType.System_Object);
@@ -75,11 +70,14 @@ public sealed class ScriptAnalysisService
public CSharpCompilation BaseCompilation { get; }
public SyntaxTree Parse(string userSource, CancellationToken ct)
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct);
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + ScriptEvaluator<VirtualTagContext, object?>.WrapperSuffix,
cancellationToken: ct);
}
private static readonly Shape ValueShape = new(typeof(VirtualTagContext), "object");
private static readonly Shape PredicateShape = new(typeof(AlarmPredicateContext), "bool");
private static readonly Shape ValueShape =
new(typeof(VirtualTagContext), ScriptEvaluator<VirtualTagContext, object?>.WrapperPreamble);
private static readonly Shape PredicateShape =
new(typeof(AlarmPredicateContext), ScriptEvaluator<AlarmPredicateContext, bool>.WrapperPreamble);
private static Shape ShapeFor(string? mode) => ScriptAnalysisModes.IsPredicate(mode) ? PredicateShape : ValueShape;
@@ -122,50 +120,62 @@ public sealed class ScriptAnalysisService
private static string Normalize(string? s) => (s ?? "").Replace("\r\n", "\n").Replace("\r", "\n");
/// <summary>Compiles the script and returns compile-error diagnostics plus sandbox-policy violations
/// (forbidden types, disallowed dynamic tag paths).</summary>
/// <param name="req">The diagnose request carrying the script source.</param>
/// <summary>Returns the markers for what the deploy gate would refuse — the runtime compile's own refusals (one
/// shared authority, <see cref="ScriptCompileRules"/>), sandbox-policy violations, disallowed dynamic tag paths and
/// the <c>{{equip}}</c> literal rules — plus advisory warnings.</summary>
/// <param name="req">The diagnose request carrying the script source and the analysis mode.</param>
/// <param name="ct">The request's cancellation token; a cancelled request throws <see cref="OperationCanceledException"/>.</param>
/// <returns>The list of diagnostic markers, empty when the script is clean or analysis fails.</returns>
public DiagnoseResponse Diagnose(DiagnoseRequest req, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(req.Code)) return new DiagnoseResponse(Array.Empty<DiagnosticMarker>());
var code = Normalize(req.Code);
var kind = ScriptAnalysisModes.KindOf(req.Mode);
// A blank / passthrough value script never reaches the compiler at runtime, so nothing the compiler says can
// refuse it (ScriptCompileRules.SkipsCompile — the deploy gate's own shortcut). A blank PREDICATE does compile,
// and is refused (CS0161), so it is analysed.
var compiles = !ScriptCompileRules.SkipsCompile(kind, code);
if (code.Length == 0 && !compiles) return new DiagnoseResponse(Array.Empty<DiagnosticMarker>());
try
{
ct.ThrowIfCancellationRequested();
var code = Normalize(req.Code);
var (tree, compilation, _, preambleLength) = Analyze(code, req.Mode, ct);
var markers = new List<DiagnosticMarker>();
// (1) Roslyn — surface ONLY compile errors, the same severity that actually blocks a
// publish in ScriptEvaluator.Compile (it filters GetDiagnostics() to
// DiagnosticSeverity.Error). Mirroring that here keeps editor markers in lockstep with
// what fails publish: a nullable warning like CS8605 on the canonical passthrough shape
// `return ctx.GetTag("X").Value;` compiles + publishes fine under the evaluator's
// nullable-enabled options, so flagging it in the editor would be misleading noise.
// Restricted to diagnostics physically inside the user source — #line 1 in the preamble
// makes GetMappedLineSpan report user-source coords (GetLineSpan would return the
// physical wrapper line and be wrong); the preambleLength guard also drops phantom
// wrapper diagnostics like CS0161 on Run() when the user hasn't typed `return` yet.
foreach (var d in compilation.GetDiagnostics(ct))
// (1) The runtime compile's own refusals (lmxopcua#1063), from the one authority — ScriptCompileRules — over
// the runtime's own wrapper text: wrapper injection (LMX001/002) and EVERY Error-severity diagnostic. Warnings
// never refuse (a nullable warning like CS8605 on `return ctx.GetTag("X").Value;` publishes fine), so they are
// not shown. This used to drop every diagnostic located in the wrapper as "phantom" — including CS0161 "not
// all code paths return a value", which Roslyn pins on the wrapper's Run and the deploy gate refuses. Such a
// diagnostic is now drawn on the script's last line instead (ToRefusalMarker).
if (compiles)
{
if (d.Severity != DiagnosticSeverity.Error || !d.Location.IsInSource) continue;
if (d.Location.SourceSpan.Start < preambleLength) continue;
var span = d.Location.GetMappedLineSpan(); // honors #line 1 → user coords
markers.Add(ToMarker(span, Sev(d.Severity), d.GetMessage(), d.Id));
if (ScriptCompileRules.WrapperInjection(tree) is { } injection)
markers.Add(ToRefusalMarker(injection, code, preambleLength));
foreach (var d in ScriptCompileRules.CompileErrors(compilation, ct))
markers.Add(ToRefusalMarker(d, code, preambleLength));
// (2) ForbiddenTypeAnalyzer — spans are in the wrapped tree; map via #line.
ct.ThrowIfCancellationRequested();
foreach (var r in ForbiddenTypeAnalyzer.Analyze(compilation))
markers.Add(ToMarker(tree.GetMappedLineSpan(r.Span), 8, r.Message, "OTSCRIPT_FORBIDDEN"));
}
// (2) ForbiddenTypeAnalyzer — spans are in the wrapped tree; map via #line.
ct.ThrowIfCancellationRequested();
foreach (var r in ForbiddenTypeAnalyzer.Analyze(compilation))
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"));
// (3b) lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted —
// the deploy gate refuses it (RoslynDeployScriptChecker runs this same scan), so the editor does too.
foreach (var f in EquipTokenLiteralScanner.Find(code))
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPLITERAL"));
if (kind == ScriptContextKind.Calculation)
{
// (3a) lmxopcua#1065: a Calculation tag has no equipment — {{equip}} in any path literal is refused by the
// deploy gate (RoslynDeployScriptChecker runs this same scan). Covers every literal form, so it subsumes 3b.
foreach (var f in EquipTokenLiteralScanner.FindInCalculation(code))
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPCALC"));
}
else
{
// (3b) lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted —
// the deploy gate refuses it (RoslynDeployScriptChecker runs this same scan), so the editor does too.
foreach (var f in EquipTokenLiteralScanner.Find(code))
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPLITERAL"));
}
// (4) ctx.SetVirtualTag(...) is inert at runtime — a WARNING (severity 4), never an error: publish
// accepts the script, so the editor must too; the marker just puts the hover's caveat in the Problems list.
foreach (var inv in SetVirtualTagCalls(tree.GetRoot(ct), preambleLength))
@@ -186,6 +196,27 @@ public sealed class ScriptAnalysisService
}
}
/// <summary>The message shown for CS0161, which Roslyn words in terms of the synthesized wrapper method.</summary>
internal const string NotAllPathsReturnMessage =
"Not all code paths return a value: every path through the script must end in a `return …;` statement " +
"(the deploy gate refuses the script otherwise).";
// A refusal of the runtime compile, as a marker. Physically inside the user source => its #line-mapped user-source
// position (GetMappedLineSpan honours #line 1; GetLineSpan would give the wrapper line). Anywhere else — on the
// wrapper (CS0161 sits on Run's identifier), or with no location — it is about the script as a whole, so it is drawn
// on the script's last line: never dropped, because the runtime compile refuses it all the same.
private static DiagnosticMarker ToRefusalMarker(Diagnostic d, string code, int preambleLength)
{
var message = d.Id == "CS0161" ? NotAllPathsReturnMessage : d.GetMessage();
if (d.Location.IsInSource && d.Location.SourceSpan.Start >= preambleLength)
return ToMarker(d.Location.GetMappedLineSpan(), 8, message, d.Id);
// The last line with text on it (trailing blank lines would put the squiggle on nothing).
var end = code.TrimEnd().Length;
var lastLineStart = end == 0 ? 0 : code.LastIndexOf('\n', end - 1) + 1;
var (line, _) = LineCol(code, lastLineStart);
return new DiagnosticMarker(8, line, 1, line, Math.Max(1, end - lastLineStart + 1), message, d.Id);
}
/// <summary>Diagnostics plus the v3 equipment-relative <c>{{equip}}/&lt;RefName&gt;</c> resolution check.
/// Runs the synchronous Roslyn/policy <see cref="Diagnose"/> then, when an equipment context + catalog
/// are present, appends a marker for each <c>{{equip}}/&lt;RefName&gt;</c> whose <c>&lt;RefName&gt;</c> is
@@ -24,15 +24,20 @@ public static class ScriptUsage
/// <summary>Which seams use a script.</summary>
/// <param name="UsedAsValue">An (any) VirtualTag or Calculation tag runs it as a value script.</param>
/// <param name="UsedAsPredicate">An (any) scripted alarm runs it as its predicate.</param>
public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate)
/// <param name="UsedAsCalculation">An (any) Calculation tag runs it (implies <paramref name="UsedAsValue"/>).</param>
public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate, bool UsedAsCalculation = false)
{
/// <summary>
/// The editor analysis mode (<c>ScriptAnalysisModes</c>) a script should open in (lmxopcua#1025): the predicate
/// shape only when scripted alarms are its sole users — a script also run as a value script stays a value
/// script (the author can switch), and an unused script is a value script.
/// The editor analysis mode (<c>ScriptAnalysisModes</c>) a script should open in (lmxopcua#1025): Calculation mode
/// whenever a Calculation tag runs it (lmxopcua#1065 — the deploy gate refuses <c>{{equip}}</c> for that use, and
/// Calculation mode is the value shape plus exactly that rule, so it is the mode that shows every refusal a value
/// use can meet); the predicate shape only when scripted alarms are its sole users; otherwise — also run as a
/// virtual tag, or unused — a value script. The author can switch.
/// </summary>
public string DefaultMode =>
UsedAsPredicate && !UsedAsValue ? ScriptAnalysis.ScriptAnalysisModes.AlarmPredicate : ScriptAnalysis.ScriptAnalysisModes.Value;
UsedAsCalculation ? ScriptAnalysis.ScriptAnalysisModes.Calculation
: UsedAsPredicate && !UsedAsValue ? ScriptAnalysis.ScriptAnalysisModes.AlarmPredicate
: ScriptAnalysis.ScriptAnalysisModes.Value;
}
/// <summary>Classifies which seams use <paramref name="scriptId"/> (same rows, same Calculation parser as the delete check).</summary>
@@ -45,16 +50,13 @@ public static class ScriptUsage
ArgumentNullException.ThrowIfNull(db);
ArgumentException.ThrowIfNullOrEmpty(scriptId);
var predicate = await db.ScriptedAlarms.AsNoTracking().AnyAsync(a => a.PredicateScriptId == scriptId, ct);
var value = await db.VirtualTags.AsNoTracking().AnyAsync(v => v.ScriptId == scriptId, ct);
if (!value)
{
var calcCandidates = await db.Tags.AsNoTracking()
.Where(t => t.TagConfig.Contains(scriptId))
.Select(t => t.TagConfig)
.ToListAsync(ct);
value = calcCandidates.Any(c => string.Equals(DraftValidator.ParseScriptId(c), scriptId, StringComparison.Ordinal));
}
return new SeamUsage(value, predicate);
var virtualTag = await db.VirtualTags.AsNoTracking().AnyAsync(v => v.ScriptId == scriptId, ct);
var calcCandidates = await db.Tags.AsNoTracking()
.Where(t => t.TagConfig.Contains(scriptId))
.Select(t => t.TagConfig)
.ToListAsync(ct);
var calculation = calcCandidates.Any(c => string.Equals(DraftValidator.ParseScriptId(c), scriptId, StringComparison.Ordinal));
return new SeamUsage(virtualTag || calculation, predicate, calculation);
}
/// <summary>
@@ -21,7 +21,8 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
/// <item><b>Enabled scripted alarms</b> (a disabled plan is skipped by the alarm host) — predicate source,
/// substituted the same way.</item>
/// <item><b>Calculation tags of enabled Calculation drivers</b> — the source verbatim (the artifact injects it
/// into the tag's TagConfig with no substitution).</item>
/// into the tag's TagConfig with no substitution). A Calculation tag has no equipment, so the checker refuses a
/// <c>{{equip}}</c> token in it outright (lmxopcua#1065).</item>
/// </list>
/// <para>
/// When <see cref="EquipmentScriptPaths.SubstitutionPreservesCompilation"/> proves the substitution cannot
@@ -77,6 +77,7 @@ internal sealed class WorkerHost
private int _maxFrameBytes = ScriptWorkerFrameCodec.DefaultMaxFrameBytes;
private int _queueCapacity = 4096;
private TimeSpan _hardGrace = TimeSpan.FromSeconds(1);
private int _maxResultElements = ScriptingOptions.DefaultMaxResultElements;
private TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(1);
/// <summary>
@@ -160,6 +161,7 @@ internal sealed class WorkerHost
if (hello.HardGraceMs > 0) _hardGrace = TimeSpan.FromMilliseconds(hello.HardGraceMs);
if (hello.HeartbeatIntervalMs > 0) _heartbeatInterval = TimeSpan.FromMilliseconds(hello.HeartbeatIntervalMs);
if (hello.CompileThreads > 0) _compileThreads = (int)Math.Min(hello.CompileThreads, 64);
if (hello.MaxResultElements > 0) _maxResultElements = (int)Math.Min(hello.MaxResultElements, int.MaxValue);
_workerSoftClock = hello.WorkerSoftClock;
_testStallReaderOnDiag = hello.TestStallReaderOnDiag;
// lmxopcua#1014: no PE-cache key or directory any more — the host verifies, compiles and signs, and sends a
@@ -458,6 +460,11 @@ internal sealed class WorkerHost
try
{
object? value = script.Run(inputs, logger, clock, cts.Token, out var isPredicate);
// lmxopcua#1064: the in-process guard's result rule (#1059), applied here too and still inside the run —
// this eval is registered with the watchdog and its allocation sample is still open — so a returned lazy
// sequence is enumerated under the run's deadlines and held to Scripting:MaxResultElements, and an
// over-cap or open-slot sequence fails the script with the same message in both runners.
if (!isPredicate) value = ScriptResultMaterializer.Materialize(value, _maxResultElements);
if (isPredicate)
{
result.Predicate = (bool)value!;