feat(scripting): out-of-process pre-emptible script runner behind Scripting:Runner (lmxopcua#780 P1)
v2-ci / unit-tests (push) Waiting to run

Opt-in (Scripting:Runner=OutOfProcess; InProcess stays the default and its code path is unchanged). Implements
the P1 slice of docs/plans/2026-11-09-out-of-process-script-runner-design.md with the owner's §14 decisions:

- Options: Scripting:Runner (InProcess | Shadow | OutOfProcess), Scripting:Runner:Seams, Scripting:Worker:*
  (Shards 2, HardGrace max(1 s,T), HeapLimitBytes 512 MiB, QuarantineAfterKills 2, UnavailableGrace 5 s,
  IsolationProbationRuns 20, PeCacheDir validated absolute + outside the content root (fail closed),
  ExecutablePath). Shadow is not implemented yet: runs InProcess with a startup Warning.
- Core.Scripting: IScriptRunner seam + InProcessScriptRunner (today's guard, the parity baseline).
- Core.Scripting.Protocol: protobuf envelopes, 4-byte LE framing (zero/oversize/truncated/garbage refused),
  Variant carrying the exact CLR type; unsupported types are explicit failures.
- ScriptWorker app: compiles in the worker, P-thread scheduler, host-driven soft cancel, fail-fast
  watchdog, heartbeats, ctx.Logger forwarding, exits on pipe EOF / parent gone, forbidden-assembly
  self-check; Akka and Grpc.Core.Api excluded from its folder. Shipped in script-worker/ (Build + Publish).
- Core.Scripting.OutOfProcess: K shards + isolation worker, soft T / hard T+G kill, attribution
  (deadline kill = one key; crash = suspects -> isolation; isolation crash = strike), kill-strike
  quarantine, backoff 250 ms -> 30 s, fail closed, cleared allow-listed env, nonce + pid handshake on a
  current-user pipe, Windows Job Object.
- VirtualTag + Calculation seams use the runner when selected; a runner-side failure (worker restarted /
  runner unavailable) publishes BadResourceUnavailable (0x80040000) — ScadaBridge#112. Script faults keep
  BadInternalError. The scripted-alarm seam stays in process (alarms last).

Tests: new ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests (Category=ScriptWorker, real processes; green on macOS and
on windev/Windows), seam tests in Host/Runtime/Calculation suites; mutation-checked.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 23:31:51 -05:00
parent f5c30ed0ef
commit 69a6e0b4c8
49 changed files with 5107 additions and 25 deletions
@@ -0,0 +1,94 @@
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess;
using SerilogLogger = Serilog.ILogger;
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
/// <summary>
/// Which <see cref="IScriptRunner"/> each script seam uses on this node (lmxopcua#780, <c>Scripting:Runner</c>). Under
/// the <see cref="ScriptRunnerMode.InProcess"/> default every seam gets null and keeps its in-process guard path,
/// unchanged. Under <see cref="ScriptRunnerMode.OutOfProcess"/> the selected seams share one
/// <see cref="OutOfProcessScriptRunner"/>, which starts no worker until the first compiled evaluation, so a node with
/// no scripts (or an admin-only node) never launches one. Disposed with the host's service provider, which stops the
/// workers.
/// </summary>
public sealed class ScriptRunnerSelection : IAsyncDisposable, IDisposable
{
/// <summary>Seams the out-of-process runner can serve in this build. Scripted alarms go last (design §14 #10).</summary>
public static readonly IReadOnlyList<ScriptSeam> SupportedOutOfProcessSeams = [ScriptSeam.VirtualTag, ScriptSeam.Calculation];
private readonly OutOfProcessScriptRunner? _runner;
private readonly HashSet<ScriptSeam> _seams;
private ScriptRunnerSelection(OutOfProcessScriptRunner? runner, IEnumerable<ScriptSeam> seams)
{
_runner = runner;
_seams = [.. seams];
}
/// <summary>The out-of-process runner, when one is configured.</summary>
public IScriptRunner? OutOfProcessRunner => _runner;
/// <summary>The runner <paramref name="seam"/> must use, or null for its in-process path.</summary>
/// <param name="seam">The seam.</param>
/// <returns>The runner, or null.</returns>
public IScriptRunner? ForSeam(ScriptSeam seam) => _runner is not null && _seams.Contains(seam) ? _runner : null;
/// <summary>
/// Startup checks for the runner options: returns the Warnings to log, and throws when the configuration must
/// not start (a <c>PeCacheDir</c> that is relative or inside the content root — fail closed).
/// </summary>
/// <param name="options">The bound, sanitized <c>Scripting</c> options.</param>
/// <param name="contentRootPath">The host's content root.</param>
/// <returns>Warnings for the caller to log.</returns>
/// <exception cref="InvalidOperationException">The worker path options are unacceptable.</exception>
public static IReadOnlyList<string> Validate(ScriptingOptions options, string contentRootPath)
{
ArgumentNullException.ThrowIfNull(options);
var warnings = new List<string>();
if (options.Runner == ScriptRunnerMode.InProcess) return warnings;
if (options.Worker.ValidatePaths(contentRootPath) is { } violation)
throw new InvalidOperationException($"Scripting misconfiguration: {violation}");
if (options.Runner == ScriptRunnerMode.Shadow)
{
warnings.Add("Scripting:Runner=Shadow is not implemented yet (lmxopcua#780 P2); every seam runs InProcess.");
return warnings;
}
foreach (var seam in RequestedSeams(options))
{
if (!SupportedOutOfProcessSeams.Contains(seam))
warnings.Add($"Scripting:Runner=OutOfProcess: the {seam} seam cannot run out of process yet (lmxopcua#780); it stays InProcess.");
}
var workerPath = OutOfProcessScriptRunner.ResolveWorkerPath(options.Worker);
if (!File.Exists(workerPath))
warnings.Add($"Scripting:Runner=OutOfProcess: the script worker '{workerPath}' does not exist; every out-of-process " +
"script reports BadResourceUnavailable (the runner fails closed, it never falls back to in process).");
return warnings;
}
/// <summary>Builds the selection for <paramref name="options"/>.</summary>
/// <param name="options">The bound, sanitized <c>Scripting</c> options.</param>
/// <param name="log">Host diagnostics for the runner.</param>
/// <param name="scriptRoot">The root script logger forwarded <c>ctx.Logger</c> lines fall back to.</param>
/// <returns>The selection.</returns>
public static ScriptRunnerSelection Create(ScriptingOptions options, SerilogLogger log, SerilogLogger? scriptRoot)
{
ArgumentNullException.ThrowIfNull(options);
if (options.Runner != ScriptRunnerMode.OutOfProcess) return new ScriptRunnerSelection(null, []);
var seams = RequestedSeams(options).Where(SupportedOutOfProcessSeams.Contains).ToArray();
if (seams.Length == 0) return new ScriptRunnerSelection(null, []);
return new ScriptRunnerSelection(new OutOfProcessScriptRunner(options, log, scriptRoot), seams);
}
/// <inheritdoc />
public ValueTask DisposeAsync() => _runner?.DisposeAsync() ?? ValueTask.CompletedTask;
/// <inheritdoc />
public void Dispose() => _runner?.Dispose();
private static IEnumerable<ScriptSeam> RequestedSeams(ScriptingOptions options)
=> options.RunnerSeams is { Count: > 0 } seams ? seams.Distinct() : Enum.GetValues<ScriptSeam>();
}
@@ -18,6 +18,11 @@ public static class ScriptingOptionsBinding
{
ArgumentNullException.ThrowIfNull(configuration);
var bound = configuration.GetSection(ScriptingOptions.SectionName).Get<ScriptingOptions>() ?? new ScriptingOptions();
// lmxopcua#780: the seam subset lives under the runner key (Scripting:Runner:Seams), which the binder cannot
// reach because Scripting:Runner is itself a value. Bound explicitly; an unknown seam name is a startup error,
// like an unknown Scripting:Runner value.
var seams = configuration.GetSection($"{ScriptingOptions.SectionName}:Runner:Seams").Get<List<ScriptSeam>>();
if (seams is { Count: > 0 }) bound.RunnerSeams = seams;
return bound.Sanitized(out adjustments);
}
}