Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/PipeFaultTests.cs
T
Joseph Doherty 59be7378d6 test(script-worker): #1100 size the remaining tight liveness bounds for ~1 s whole-process stalls, each still failing on its defect
Audit of the heartbeat / silence / liveness-kill bounds in ScriptWorker.Tests after cb5250fac (#1092):
- PipeFaultTests (reader stalls, heartbeats continue): silence 5 x 200 ms = 1 s -> 2 s, write-stall 2 s -> 5 s.
  The silence limit must stay below the write-stall limit or "killed unresponsive, not for silence" proves
  nothing. Mutation (worker stops heartbeating when its reader stalls): KilledHeartbeat at ~2 s, test fails.
- WorkerSoftClockTests.The_progress_ceiling_leaves_a_worker_that_keeps_answering_alone: ceiling 1 s over
  20 x 150 ms -> 2.5 s over 40 x 150 ms. Mutation (no progress stamp on a Results frame): killed
  KilledUnresponsive, queued runs complete null, test fails.
- SupervisionTests burst test: kept at 3 s (production's limit; frames every 50 ms, so only a ~2.95 s stall
  trips it; raising it would stop it catching the 3 s windev defect). Comment records the decision.
- The two #1092 tests (1.5 s) and the never-reports-progress test (lower bound only) are already stall-safe.

Stall check, temporary instrumentation (libc kill SIGSTOP/SIGCONT of the worker pid, not committed): a 1.2 s
stall failed the old PipeFault bounds 3/3 and a 1 s stall failed the old ceiling bounds; the new bounds passed
1.2 s stalls 3/3 each. (A first attempt that spawned /bin/kill measured a 2.5 s stall, not 1 s — process
spawn on the loaded box — and was discarded.)
2026-12-04 17:35:30 -05:00

119 lines
7.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using Serilog;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess;
using ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol.V1;
namespace ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests;
/// <summary>
/// lmxopcua#789 review: the blocking pipe I/O runs the host's reader on a dedicated thread and blocks producers on a
/// full pipe. A fault in the reader's inline completion work must end that worker, not the server process; and a worker
/// that stops reading while it keeps heartbeating must be killed so blocked producers are released.
/// </summary>
[Collection(ScriptWorkerCollection.Name)]
[Trait("Category", "ScriptWorker")]
public sealed class PipeFaultTests
{
private const string Healthy = "return 7;";
private const string Runaway = "while (true) { }";
private static CancellationToken Ct => TestContext.Current.CancellationToken;
/// <summary>
/// The slot release runs on the pipe reader, inline, before the caller resumes. When it throws, the reader must
/// end the worker as a fault: the run in flight beside it answers BadResourceUnavailable ("worker restarted"),
/// the shard restarts, and the next evaluation is served — instead of an unhandled exception on a dedicated thread,
/// which would terminate the host.
/// </summary>
[Fact]
public async Task A_completion_callback_that_throws_on_the_reader_ends_that_worker_as_faulted_not_the_host()
{
await using var runner = Scripts.Runner(Scripts.Options());
(await runner.RunAsync(Scripts.Vt("boom", Healthy), Ct)).Value.ShouldBe(7, "positive control: the hook is not armed yet");
var worker = runner.Shards[0].Current.ShouldNotBeNull();
var spin = runner.RunAsync(Scripts.Vt("spin", Runaway, TimeSpan.FromSeconds(30)), Ct);
await Scripts.Eventually(() => worker.InFlightCount > 0 ? worker : null, TimeSpan.FromSeconds(30), "the sibling in flight");
var armed = 1;
runner.SlotReleasingForTest = key =>
{
if (key.EndsWith("boom", StringComparison.Ordinal) && Interlocked.Exchange(ref armed, 0) == 1)
throw new InvalidOperationException("a completion callback failed");
};
await runner.RunAsync(Scripts.Vt("boom", Healthy), Ct);
var exit = await worker.Exited.WaitAsync(TimeSpan.FromSeconds(15), Ct);
exit.Reason.ShouldBe(WorkerExitReason.ProtocolFault);
var sibling = await spin.WaitAsync(TimeSpan.FromSeconds(15), Ct);
sibling.Status.ShouldBe(ScriptRunStatus.Unavailable);
sibling.Reason.ShouldBe(ScriptRunOutcome.WorkerRestartedReason);
sibling.ToVirtualTagEvalResult().StatusCode.ShouldBe(ZB.MOM.WW.OtOpcUa.Commons.OpcUa.OpcUaStatus.BadResourceUnavailable);
(await runner.RunAsync(Scripts.Vt("after", Healthy), Ct)).Value.ShouldBe(7, "the shard restarted and serves again");
runner.Shards[0].Current.ShouldNotBeNull().Pid.ShouldNotBe(worker.Pid);
}
/// <summary>
/// A worker whose reader stops while its heartbeats go on: the host's writes fill the pipe and the producer (here
/// a deploy loading scripts, the case nothing else would end: no evaluation is outstanding and a compile's timeout
/// starts only when the worker starts it) blocks in the write. The write-stall check must kill the worker within
/// its bound — as unresponsive, not for silence, which proves it kept heartbeating — and that releases the producer.
/// </summary>
/// <remarks>
/// The two bounds are relative: the silence limit must stay well below the write-stall limit, or a worker (or a
/// host reader) that stopped heartbeating along with the reader would also be killed "unresponsive" and the
/// assertion would prove nothing. lmxopcua#1100 sizes them for whole-process stalls of a swapping dev box (see
/// SupervisionTests' #1092 remarks: 290–380 ms late beats measured at the worker, ~1 s observed): the silence
/// limit was 5 × 200 ms = 1 s, which a 1 s stall reaches; it is now 2 s (10 intervals — a stall must exceed ~1.8 s),
/// and the write-stall limit 5 s (was 2 s) so a silent worker is still killed for silence 3 s before the write-stall
/// check could fire. Mutation check: a worker that stops its heartbeat when its reader stalls exits
/// KilledHeartbeat at ~2 s, which releases the producer before the stallLimit / 2 positive control, and the test fails.
/// Stall check (temporary, not committed): the worker SIGSTOPped for 1.2 s right after its reader stopped failed the
/// old bounds 3 of 3 runs (killed for silence) and passed the new ones 3 of 3.
/// </remarks>
[Fact]
public async Task A_worker_that_stops_reading_but_keeps_heartbeating_is_killed_and_the_blocked_producer_returns()
{
var heartbeat = TimeSpan.FromMilliseconds(200);
var spec = new WorkerLaunchSpec("t", OutOfProcessScriptRunner.ResolveWorkerPath(new ScriptWorkerOptions { ExecutablePath = Scripts.WorkerUnderTest }),
256L * 1024 * 1024, EvalThreads: 2, HardGrace: TimeSpan.FromSeconds(60), HeartbeatInterval: heartbeat,
HandshakeTimeout: TimeSpan.FromSeconds(15), HeartbeatSilenceLimit: TimeSpan.FromSeconds(30), TestStallReaderOnDiag: true);
var connection = await WorkerConnection.StartAsync(spec, new LoggerConfiguration().CreateLogger(), _ => { }, _ => { }, Ct);
await using var owned = connection;
var warm = await connection.EnsureLoadedAsync("k", ContextKind.VirtualTag, Healthy,
SHA256.HashData(Encoding.UTF8.GetBytes(Healthy)), []).WaitAsync(TimeSpan.FromSeconds(60), Ct);
warm.Outcome.ShouldNotBeNull().Ok.ShouldBeTrue();
connection.SilenceLimit = heartbeat * 10; // armed once the cold start is over (see SupervisionTests); see remarks (#1100)
var stallLimit = TimeSpan.FromSeconds(5);
connection.WriteStallLimitOverride = stallLimit;
_ = connection.DiagnosticsAsync(TimeSpan.FromSeconds(60)); // the worker's reader stops here for good
var producer = Task.Factory.StartNew(() =>
{
// About 5 MB of loads: far more than the pipe's buffer and the worker reader's own.
for (var i = 0; i < 20; i++)
{
var source = $"return {i}; // " + new string('x', 256 * 1024);
_ = connection.EnsureLoadedAsync($"big{i}", ContextKind.VirtualTag, source,
SHA256.HashData(Encoding.UTF8.GetBytes(source)), []);
}
}, Ct, TaskCreationOptions.LongRunning, TaskScheduler.Default);
var sw = Stopwatch.StartNew();
await Task.Delay(stallLimit / 2, Ct);
producer.IsCompleted.ShouldBeFalse("positive control: the producer is blocked in a write to the full pipe");
connection.IsAlive.ShouldBeTrue("positive control: heartbeats keep the silence check quiet");
var exit = await connection.Exited.WaitAsync(TimeSpan.FromSeconds(20), Ct);
exit.Reason.ShouldBe(WorkerExitReason.KilledUnresponsive, "killed by the write-stall check, not for silence");
await producer.WaitAsync(TimeSpan.FromSeconds(10), Ct);
sw.Elapsed.ShouldBeLessThan(stallLimit + TimeSpan.FromSeconds(8), "the producer was released within the bound");
}
}