diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 67add7d52..789a19e1a 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -331,9 +331,13 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: concatenation, interpolation). Each rejection carries a `TextSpan` in 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), +scripted-alarm predicate only (the alarm load 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** +deploy gate and the scripted-alarm load (`ScriptedAlarmEngine`) both refuse through +`ScriptCompileRules.PathRefusals` — the same findings, the same `dependency extraction +rejected — …` text (#1101: the load used to apply its own copy of the rule; +`ScriptedAlarmEngineTagPathRuleParityTests` pins engine verdict == gate verdict) — 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 diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs index a5039e8f6..4bdb608c6 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs @@ -622,11 +622,15 @@ public sealed class ScriptedAlarmEngine : IDisposable var def = definitions[i]; try { + // lmxopcua#1101: whether a tag path refuses the predicate is ScriptCompileRules' decision — the same one + // the deploy gate (RoslynDeployScriptChecker) and the editor read — not a second copy of the rule here. + // The extraction is still needed for the predicate's declared inputs (Reads), so it is passed in rather + // than parsed twice. var extraction = DependencyExtractor.Extract(def.PredicateScriptSource); - if (!extraction.IsValid) + var refusals = ScriptCompileRules.PathRefusals(ScriptContextKind.AlarmPredicate, def.PredicateScriptSource, extraction); + if (refusals is not null) { - var joined = string.Join("; ", extraction.Rejections.Select(r => r.Message)); - result[i] = new(def, null, $"{def.AlarmId}: dependency extraction rejected — {joined}"); + result[i] = new(def, null, $"{def.AlarmId}: {refusals}"); return; } if (_runner is null) _ = _compileCache.GetOrCompile(def.PredicateScriptSource); 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 0439ff694..fc1f67184 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs @@ -132,11 +132,9 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker 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); + // lmxopcua#1101: PathRefusals is also what the scripted-alarm load applies, so the two cannot disagree. + if (ScriptCompileRules.PathRefusals(request.Kind, source) is { } pathRefusals) + return new CachedVerdict([pathRefusals], Cacheable: true); if (request.Kind == ScriptContextKind.AlarmPredicate) { ScriptEvaluator.Verify(source); 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 cddfb4bca..1e9a4cb4a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs @@ -47,8 +47,8 @@ public static class ScriptCompileRules /// /// 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 + /// (lmxopcua#1083). Only a scripted-alarm predicate: the alarm load refuses the alarm, and so does the deploy gate — + /// both through (lmxopcua#1101; the load used to apply its own copy of the rule). 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. /// @@ -65,11 +65,16 @@ public static class ScriptCompileRules /// /// The seam the script runs as. /// The script source (user coordinates). + /// + /// An extraction the caller already ran on (the scripted-alarm load needs its Reads + /// too, lmxopcua#1101), or null to run one here. + /// /// The findings; empty when every tag path is a non-empty literal. - public static IReadOnlyList TagPathFindings(ScriptContextKind kind, string? source) + public static IReadOnlyList TagPathFindings( + ScriptContextKind kind, string? source, DependencyExtractionResult? extraction = null) { source ??= string.Empty; - var rejections = DependencyExtractor.Extract(source).Rejections; + var rejections = (extraction ?? DependencyExtractor.Extract(source)).Rejections; if (rejections.Count == 0) return []; var refuses = RefusesNonLiteralTagPaths(kind); var findings = new TagPathFinding[rejections.Count]; @@ -81,6 +86,25 @@ public static class ScriptCompileRules return findings; } + /// + /// The refusal a script run as gets for its tag paths, or null when it gets none — the one + /// verdict the deploy gate () and the scripted-alarm load + /// (ScriptedAlarmEngine, lmxopcua#1101) both apply, worded identically: dependency extraction rejected — … + /// with every finding's message. + /// + /// The seam the script runs as. + /// The script source (user coordinates). + /// An extraction already run on , or null to run one. + /// The refusal text, or null. + public static string? PathRefusals(ScriptContextKind kind, string? source, DependencyExtractionResult? extraction = null) + { + var refusing = TagPathFindings(kind, source, extraction) + .Where(f => f.Refuses).ToArray(); + return refusing.Length == 0 + ? null + : "dependency extraction rejected — " + string.Join("; ", refusing.Select(f => f.Message)); + } + // 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. diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTagPathRuleParityTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTagPathRuleParityTests.cs new file mode 100644 index 000000000..d06bf0096 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTagPathRuleParityTests.cs @@ -0,0 +1,79 @@ +using Serilog; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests; + +/// +/// lmxopcua#1101: the scripted-alarm load refuses a predicate for its tag paths exactly when the deploy gate +/// () does, with the same text. The engine used to call +/// itself — a second copy of the rule owns +/// (lmxopcua#1083), free to drift from what the gate and the editor enforce. Both now go through +/// . +/// +[Trait("Category", "Unit")] +public sealed class ScriptedAlarmEngineTagPathRuleParityTests +{ + public static TheoryData Predicates() => new() + { + { "literal", """return (int)ctx.GetTag("Temp").Value > 100;""" }, + { "two literals", """return (int)ctx.GetTag("Temp").Value > (int)ctx.GetTag("Limit").Value;""" }, + { "variable", """var p = "Temp"; return (int)ctx.GetTag(p).Value > 100;""" }, + { "concatenated", """return (int)ctx.GetTag("Te" + "mp").Value > 100;""" }, + { "interpolated", """var n = 1; return (int)ctx.GetTag($"Temp{n}").Value > 100;""" }, + { "empty", """return ctx.GetTag("").Value is null;""" }, + { "two refusals", """var p = "Temp"; return ctx.GetTag(p).Value is null && ctx.GetTag("").Value is null;""" }, + { "dynamic beside a literal", """var p = "Limit"; return (int)ctx.GetTag("Temp").Value > (int)ctx.GetTag(p).Value;""" }, + }; + + [Theory] + [MemberData(nameof(Predicates))] + public async Task The_engine_refuses_a_predicate_for_its_tag_paths_exactly_when_the_deploy_gate_does(string name, string predicate) + { + var gate = new RoslynDeployScriptChecker() + .Check([new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, predicate)], TestContext.Current.CancellationToken) + .Single(); + + var up = new FakeUpstream(); + up.Set("Temp", 50); + up.Set("Limit", 100); + var logger = new LoggerConfiguration().CreateLogger(); + using var engine = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger); + var alarm = new ScriptedAlarmDefinition( + AlarmId: "a1", EquipmentPath: "Plant/Line1/Reactor", AlarmName: "a1", Kind: AlarmKind.AlarmCondition, + Severity: AlarmSeverity.High, MessageTemplate: "condition", PredicateScriptSource: predicate); + + string? engineRefusal = null; + try + { + await engine.LoadAsync([alarm], TestContext.Current.CancellationToken); + } + catch (InvalidOperationException ex) + { + engineRefusal = ex.Message; + } + + if (gate.Passed) + { + engineRefusal.ShouldBeNull($"{name}: the gate accepts it, so the load must too"); + engine.LoadedAlarmIds.ShouldContain("a1"); + } + else + { + gate.Problems.ShouldHaveSingleItem().ShouldStartWith("dependency extraction rejected — ", customMessage: name); + engineRefusal.ShouldNotBeNull($"{name}: the gate refuses it ({gate.Problems[0]}), so the load must too"); + engineRefusal.ShouldContain("a1: " + gate.Problems[0], customMessage: name); + } + } + + /// Positive control: the table above has both outcomes, so it is not vacuous. + [Fact] + public void The_table_holds_accepted_and_refused_predicates() + { + var verdicts = Predicates().Select(row => ScriptCompileRules.PathRefusals(ScriptContextKind.AlarmPredicate, row.Data.Item2) is null).ToArray(); + verdicts.ShouldContain(true); + verdicts.ShouldContain(false); + } +}