fix(flow-debugger): final-review remediation — 2000-row trace pull, shared ExceptionHeader parser, surrogate-safe clip, wording, alarm source, register renumber (I1/I2/M1-M8)

This commit is contained in:
Joseph Doherty
2026-09-09 13:30:48 -04:00
parent 0bacc3630e
commit 97f01ae98e
21 changed files with 462 additions and 71 deletions
@@ -0,0 +1,89 @@
using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Actors;
/// <summary>
/// Final review M6: an alarm on-trigger run's <c>ScriptRuntimeContext</c> was built without a
/// <c>sourceScript</c>, so the context's <c>_logTarget</c> — which names the script on every
/// <c>Log.*</c> line and on the run's trace rows — fell back to the INSTANCE name. The launcher now
/// passes the same <c>AlarmActor:{alarmName}</c> source key it already uses for this alarm's site
/// events, from which the context derives the alarm's own name.
/// </summary>
public class AlarmScriptLogTargetTests : TestKit, IDisposable
{
private sealed record Entry(LogLevel Level, string Message);
/// <summary>A minimal recording logger — the alarm path hands its own ILogger down to the script logger.</summary>
private sealed class RecordingLogger<T> : ILogger<T>
{
public List<Entry> Entries { get; } = [];
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel level, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
lock (Entries) Entries.Add(new Entry(level, formatter(state, exception)));
}
}
private readonly SharedScriptLibrary _sharedLibrary = new(
new ScriptCompilationService(NullLogger<ScriptCompilationService>.Instance),
NullLogger<SharedScriptLibrary>.Instance);
void IDisposable.Dispose() => Shutdown();
[Fact]
public void AlarmOnTriggerRun_AttributesItsLogLinesToTheALARM_NotJustTheInstance()
{
var options = new SiteRuntimeOptions
{
ScriptExecutionTimeoutSeconds = 10,
MaxScriptCallDepth = 10,
};
var scriptOptions = ScriptOptions.Default
.WithReferences(typeof(object).Assembly, typeof(Enumerable).Assembly, typeof(ScriptGlobals).Assembly)
.WithImports("System", "System.Threading.Tasks");
var compiled = CSharpScript.Create<object?>("Log.Info(\"alarm handler ran\"); return null;", scriptOptions, typeof(ScriptGlobals));
compiled.Compile();
var logger = new RecordingLogger<AlarmActor>();
using var scheduler = new ScriptExecutionScheduler(1);
var config = new ResolvedAlarm
{
CanonicalName = "HighTemp",
TriggerType = "ValueMatch",
TriggerConfiguration = "{\"attributeName\":\"Status\",\"matchValue\":\"Critical\"}",
PriorityLevel = 100,
};
var alarm = ActorOfAsTestActorRef<AlarmActor>(
Props.Create(() => new AlarmActor(
"HighTemp", "Inst1", CreateTestProbe().Ref, config, compiled, _sharedLibrary, options,
logger, null, null, null, null, null, scheduler, null)),
"alarm-logtarget-" + Guid.NewGuid().ToString("N"));
alarm.Tell(new AttributeValueChanged("Inst1", "Status", "Status", "Critical", "Good", DateTimeOffset.UtcNow));
AwaitAssert(
() =>
{
Entry[] snapshot;
lock (logger.Entries) snapshot = [.. logger.Entries];
// "[script] {Instance}/{Script} {ExecutionId}: {Message}" — the script half is the
// alarm's name because the launcher passed "AlarmActor:HighTemp" as the source.
Assert.Contains(snapshot, e => e.Message.StartsWith("[script] Inst1/HighTemp ", StringComparison.Ordinal)
&& e.Message.EndsWith(": alarm handler ran", StringComparison.Ordinal));
},
TimeSpan.FromSeconds(15));
}
}
@@ -159,7 +159,9 @@ public class ScriptLoggerTests
var closing = rows[^1];
Assert.Equal("warn", closing.Level);
Assert.Equal("runtime", closing.Source);
Assert.Contains("2 line(s)", closing.Message);
// M3: worded identically to the central InboundScriptLogger closing row.
Assert.Contains("2 further log line(s) were not captured", closing.Message);
Assert.Contains("ScadaBridge:SiteRuntime:MaxLogLinesPerRun = 3", closing.Message);
Assert.Null(closing.StepEventId);
logger.FlushDropped();
@@ -302,7 +304,7 @@ public class ScriptLoggerTests
Assert.Equal(2, rows.Count);
logger.FlushDropped();
Assert.Contains("1 line(s)", rows[^1].Message);
Assert.Contains("1 further log line(s) were not captured", rows[^1].Message);
}
[Fact]
@@ -149,7 +149,7 @@ public class ScriptRunLauncherTraceTests : TestKit, IDisposable
// One closing runtime warning naming the three dropped lines.
var closing = Assert.Single(logs, e => Extra(e).LogSource == "runtime");
Assert.Equal("warn", Extra(closing).LogLevel);
Assert.Contains("3 line(s) dropped", Row(closing).RequestSummary);
Assert.Contains("3 further log line(s) were not captured", Row(closing).RequestSummary);
// Every log row — the closing one included — precedes the run's anchor row.
var anchorIndex = rows.ToList().FindIndex(e => Row(e).Kind == AuditKind.ScriptRun);
@@ -701,7 +701,7 @@ public class ScriptRuntimeContextTraceEmissionTests : TestKit
var extra = ScriptTraceExtra.TryParse(closing.Extra)!;
Assert.Equal("warn", extra.LogLevel);
Assert.Equal("runtime", extra.LogSource);
Assert.Contains("1 line(s) dropped", closing.RequestSummary);
Assert.Contains("1 further log line(s) were not captured", closing.RequestSummary);
}
/// <summary>
@@ -780,7 +780,7 @@ public class ScriptRuntimeContextTraceEmissionTests : TestKit
Assert.Equal(["from the caller", "shared"], rows.Select(e => Row(e).RequestSummary));
parent.Log.FlushDropped();
Assert.Contains("2 line(s) dropped", Row(collector.Snapshot()[^1]).RequestSummary);
Assert.Contains("2 further log line(s) were not captured", Row(collector.Snapshot()[^1]).RequestSummary);
}
/// <summary>