refactor(scripted-alarms): #1101 the alarm load refuses a predicate's tag paths through ScriptCompileRules, not its own copy of the rule
ScriptedAlarmEngine.PreparePredicates called DependencyExtractor and refused on !IsValid — a second copy of the rule ScriptCompileRules owns since #1083 (RefusesNonLiteralTagPaths / TagPathFindings), which the deploy gate and the editor read. Now ScriptCompileRules.PathRefusals(kind, source, extraction?) is the one verdict and text ("dependency extraction rejected — …") for both the gate (RoslynDeployScriptChecker) and the engine. TagPathFindings takes an optional extraction so the engine, which still needs the extraction's Reads, parses once. Behaviour identical: for AlarmPredicate every rejection refuses with its extractor message, joined "; ". ScriptedAlarmEngineTagPathRuleParityTests runs 8 predicates (literal, two literals, variable, concatenated, interpolated, empty, two refusals, dynamic beside a literal) through the gate and a real engine load and asserts refused <=> refused with the gate's exact text; plus a control that the table holds both outcomes. Mutation: an engine rule that refuses only empty paths fails 6 of 8 rows.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<AlarmPredicateContext, bool>.Verify(source);
|
||||
|
||||
@@ -47,8 +47,8 @@ public static class ScriptCompileRules
|
||||
|
||||
/// <summary>
|
||||
/// Whether a tag path that is not a non-empty string literal refuses a script run as <paramref name="kind"/>
|
||||
/// (lmxopcua#1083). Only a scripted-alarm predicate: the alarm load runs <see cref="DependencyExtractor"/> 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 <see cref="PathRefusals"/> (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 <see cref="TagPathFindings"/>). Making the gate refuse it
|
||||
/// there too was declined: it would start rejecting configurations that deploy today.
|
||||
/// </summary>
|
||||
@@ -65,11 +65,16 @@ public static class ScriptCompileRules
|
||||
/// </summary>
|
||||
/// <param name="kind">The seam the script runs as.</param>
|
||||
/// <param name="source">The script source (user coordinates).</param>
|
||||
/// <param name="extraction">
|
||||
/// An extraction the caller already ran on <paramref name="source"/> (the scripted-alarm load needs its <c>Reads</c>
|
||||
/// too, lmxopcua#1101), or null to run one here.
|
||||
/// </param>
|
||||
/// <returns>The findings; empty when every tag path is a non-empty literal.</returns>
|
||||
public static IReadOnlyList<TagPathFinding> TagPathFindings(ScriptContextKind kind, string? source)
|
||||
public static IReadOnlyList<TagPathFinding> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The refusal a script run as <paramref name="kind"/> gets for its tag paths, or null when it gets none — the one
|
||||
/// verdict the deploy gate (<see cref="RoslynDeployScriptChecker"/>) and the scripted-alarm load
|
||||
/// (<c>ScriptedAlarmEngine</c>, lmxopcua#1101) both apply, worded identically: <c>dependency extraction rejected — …</c>
|
||||
/// with every <see cref="TagPathFinding.Refuses"/> finding's message.
|
||||
/// </summary>
|
||||
/// <param name="kind">The seam the script runs as.</param>
|
||||
/// <param name="source">The script source (user coordinates).</param>
|
||||
/// <param name="extraction">An extraction already run on <paramref name="source"/>, or null to run one.</param>
|
||||
/// <returns>The refusal text, or null.</returns>
|
||||
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.
|
||||
|
||||
+79
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1101: the scripted-alarm load refuses a predicate for its tag paths exactly when the deploy gate
|
||||
/// (<see cref="RoslynDeployScriptChecker"/>) does, with the same text. The engine used to call
|
||||
/// <see cref="DependencyExtractor"/> itself — a second copy of the rule <see cref="ScriptCompileRules"/> owns
|
||||
/// (lmxopcua#1083), free to drift from what the gate and the editor enforce. Both now go through
|
||||
/// <see cref="ScriptCompileRules.PathRefusals"/>.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ScriptedAlarmEngineTagPathRuleParityTests
|
||||
{
|
||||
public static TheoryData<string, string> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Positive control: the table above has both outcomes, so it is not vacuous.</summary>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user