diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 386cc7cd2..8d5d6d133 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -182,6 +182,14 @@ processes: evaluation thread is busy is reported back as *deferred*, the host stops its clock, and restarts T and G when the worker reports it *started* — so an item queued behind a runaway sibling is neither timed out nor struck, and at the kill it is a victim (`script worker restarted`), not the culprit. +- **Frames never exceed the cap (#999 / review K-5).** The combining pipe writer merges consecutive evaluations / + results only up to the frame cap (4 MiB) and cuts a larger batch — merged or a single `EvalBatch` — into several frames, + in order; the worker's `ctx.Logger` drain is cut by bytes as well as lines (`LogBatch` per ≤ cap; a line too large for + any batch counts as dropped). One item too large for any frame fails **that evaluation alone** as `unsupported type: … + frame cap` — an oversized input set is refused before it is written (`ScriptWorkerFrameWriter.FitsOneFrame`), an + oversized result is replaced by that error in the worker. Before, any of these faulted the writer: the worker exited + (host side: was killed as a crash), every evaluation in flight on the shard published `BadResourceUnavailable`, and a + script logging megabytes in one 100 ms window repeated that until it was quarantined. - **Scripted alarms** (only when `Scripting:Runner:Seams` lists `ScriptedAlarm`). The engine compiles each predicate at load only to validate it (same Roslyn, sandbox and diagnostics, so a broken predicate still fails the load; no assembly is loaded into the host), the worker compiles and runs it, and each re-evaluation pass submits its dirty set diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs index 4c5894c97..7bfc7eadc 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs @@ -659,6 +659,7 @@ internal sealed class WorkerConnection : IAsyncDisposable var pending = new PendingEval(key, request.EvalId, onFinished, _dispatcher); if (softTimeout is { } soft) pending.Arm(soft, hardGrace, OnHardDeadline, WorkerSoftClock); _pending[request.EvalId] = pending; + if (RefuseOversized(request, pending)) return pending; var batch = new EvalBatch(); batch.Items.Add(request); if (!Send(new Envelope { Eval = batch }) || _exited.Task.IsCompleted) @@ -689,10 +690,12 @@ internal sealed class WorkerConnection : IAsyncDisposable var pending = new PendingEval(item.Key, item.Request.EvalId, item.OnFinished, _dispatcher); pending.Arm(item.SoftTimeout, item.HardGrace, OnHardDeadline, WorkerSoftClock); _pending[item.Request.EvalId] = pending; - batch.Items.Add(item.Request); pendings[i] = pending; + if (!RefuseOversized(item.Request, pending)) batch.Items.Add(item.Request); } - if (items.Count > 0 && (!Send(new Envelope { Eval = batch }) || _exited.Task.IsCompleted)) + // The writer cuts the batch into frames within the cap (#999 / review K-5); only an item that fits no frame on + // its own is refused above. + if (batch.Items.Count > 0 && (!Send(new Envelope { Eval = batch }) || _exited.Task.IsCompleted)) { foreach (var pending in pendings) if (_pending.TryRemove(pending.EvalId, out _)) pending.Complete(null); @@ -700,6 +703,28 @@ internal sealed class WorkerConnection : IAsyncDisposable return pendings; } + /// + /// #999 / review K-5: an evaluation whose request (its inputs) is too large for any frame fails ALONE, as an + /// unsupported-type result, before it reaches the pipe writer — which would otherwise have to refuse the frame, + /// fault, and take the worker (and every evaluation in flight on it) down with it. + /// + private bool RefuseOversized(EvalRequest request, PendingEval pending) + { + if (_writer.FitsOneFrame(request)) return false; + if (_pending.TryRemove(request.EvalId, out _)) + pending.Complete(new EvalResult + { + EvalId = request.EvalId, + Error = new ScriptError + { + Kind = ScriptError.Types.Kind.UnsupportedType, + Message = $"the evaluation's inputs are {request.CalculateSize()} bytes encoded, over the " + + $"{_writer.MaxFrameBytes}-byte frame cap", + }, + }); + return true; + } + /// /// The compiled form of in this worker when it is loaded at /// with and compiled cleanly — the batch fast path, which never waits for a load. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptWorkerFramePipe.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptWorkerFramePipe.cs index a49357986..685607fa6 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptWorkerFramePipe.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptWorkerFramePipe.cs @@ -240,35 +240,130 @@ public sealed class ScriptWorkerFrameWriter } } + /// + /// Room left in a frame for the envelope header (version + sequence number, ≤ 2 × 11 bytes) and the body's own tag + /// and length prefix. Generous on purpose: the merge budget below only needs to be an upper bound. + /// + private const int FrameHeadroom = 64; + + /// The bytes a merged batch's items and ids may add up to so the frame stays within the cap. + private int MergeBudget => Math.Max(1, MaxFrameBytes - FrameHeadroom); + + /// + /// Whether fits a frame on its own (#999 / review K-5). A caller that builds an evaluation + /// checks this first and fails the one evaluation instead of handing the writer a frame it must refuse. + /// + /// The evaluation request or result. + /// Whether it fits. + public bool FitsOneFrame(IMessage item) => ItemBytes(item) <= MergeBudget; + + /// A repeated-message item's encoded size inside its batch: tag (1 byte) + length prefix + body. + private static int ItemBytes(IMessage item) + { + var size = item.CalculateSize(); + return 1 + CodedOutputStream.ComputeLengthSize(size) + size; + } + + /// A packed repeated uint64 id: at most 10 bytes; the per-list tag + length is in the headroom. + private const int IdBytes = 10; + + /// + /// Builds one pass. Consecutive evaluations / results are merged — but, since #999 / review K-5, only up to the + /// frame cap: the merged batch is cut (and a new one started) before an item would push it over. Before, the merge + /// was unbounded and one oversized frame faulted the writer — the worker exited (host side: killed) with every + /// evaluation in flight. A single RESULT too large for any frame is replaced by an UNSUPPORTED_TYPE error for + /// that evaluation alone; an oversized single evaluation REQUEST is refused before it gets here + /// (), so reaching with one is still a protocol fault. + /// private void FillPass() { EvalBatch? evals = null; EvalResults? results = null; + var mergedBytes = 0; + var budget = MergeBudget; + + void FlushEvals() + { + if (evals is null) return; + Append(new Envelope { Eval = evals }); + evals = null; + mergedBytes = 0; + } + + void FlushResults() + { + if (results is null) return; + Append(new Envelope { Results = results }); + results = null; + mergedBytes = 0; + } + while (_queue.TryDequeue(out var envelope)) { switch (envelope.BodyCase) { case Envelope.BodyOneofCase.Eval: - if (results is not null) { Append(new Envelope { Results = results }); results = null; } - (evals ??= new EvalBatch()).Items.AddRange(envelope.Eval.Items); + FlushResults(); + foreach (var item in envelope.Eval.Items) + { + var bytes = ItemBytes(item); + if (evals is not null && mergedBytes + bytes > budget) FlushEvals(); + (evals ??= new EvalBatch()).Items.Add(item); + mergedBytes += bytes; + } break; case Envelope.BodyOneofCase.Results: - if (evals is not null) { Append(new Envelope { Eval = evals }); evals = null; } - results ??= new EvalResults(); - results.Items.AddRange(envelope.Results.Items); - results.StartedEvalIds.AddRange(envelope.Results.StartedEvalIds); - results.DeferredEvalIds.AddRange(envelope.Results.DeferredEvalIds); - results.SoftExpiredEvalIds.AddRange(envelope.Results.SoftExpiredEvalIds); + FlushEvals(); + var body = envelope.Results; + // Ids first: an evaluation's "started" notice never trails its own result into a later frame. + foreach (var (id, list) in Ids(body)) + { + if (results is not null && mergedBytes + IdBytes > budget) FlushResults(); + results ??= new EvalResults(); + list(results).Add(id); + mergedBytes += IdBytes; + } + foreach (var original in body.Items) + { + var item = original; + var bytes = ItemBytes(item); + if (bytes > budget) + { + item = new EvalResult + { + EvalId = original.EvalId, + AllocatedBytes = original.AllocatedBytes, + RunMicros = original.RunMicros, + Error = new ScriptError + { + Kind = ScriptError.Types.Kind.UnsupportedType, + Message = $"the script's result is {bytes} bytes encoded, over the {MaxFrameBytes}-byte frame cap", + }, + }; + bytes = ItemBytes(item); + } + if (results is not null && mergedBytes + bytes > budget) FlushResults(); + (results ??= new EvalResults()).Items.Add(item); + mergedBytes += bytes; + } break; default: - if (evals is not null) { Append(new Envelope { Eval = evals }); evals = null; } - if (results is not null) { Append(new Envelope { Results = results }); results = null; } + FlushEvals(); + FlushResults(); Append(envelope); break; } } - if (evals is not null) Append(new Envelope { Eval = evals }); - if (results is not null) Append(new Envelope { Results = results }); + FlushEvals(); + FlushResults(); + } + + /// The id lists of , each with the accessor for the same list on a merged batch. + private static IEnumerable<(ulong Id, Func> List)> Ids(EvalResults body) + { + foreach (var id in body.StartedEvalIds) yield return (id, static r => r.StartedEvalIds); + foreach (var id in body.DeferredEvalIds) yield return (id, static r => r.DeferredEvalIds); + foreach (var id in body.SoftExpiredEvalIds) yield return (id, static r => r.SoftExpiredEvalIds); } private void Append(Envelope envelope) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs index 74fe496d1..d5a429483 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs @@ -574,7 +574,9 @@ internal sealed class WorkerHost using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(100)); while (await timer.WaitForNextTickAsync()) { - if (_logSink.Drain() is { } batch) Send(new Envelope { Logs = batch }); + // #999 / review K-5: cut by BYTES as well as lines — one batch of every buffered line (≤ 1,000 × ~24 KB) + // used to exceed the frame cap, fault the writer and exit the worker. + foreach (var batch in _logSink.Drain(Math.Max(1, _maxFrameBytes - 1024))) Send(new Envelope { Logs = batch }); } } @@ -816,17 +818,39 @@ internal sealed class WorkerHost }); } - public LogBatch? Drain() + /// + /// Drains every buffered line into batches of at most encoded bytes each + /// (#999 / review K-5). A line too large for any batch on its own is counted as dropped. + /// + public List Drain(int maxBatchBytes) { + var batches = new List(); var dropped = Interlocked.Exchange(ref _dropped, 0); - if (_lines.IsEmpty && dropped == 0) return null; - var batch = new LogBatch { Dropped = (uint)dropped }; + if (_lines.IsEmpty && dropped == 0) return batches; + var batch = new LogBatch(); + var bytes = 0; while (_lines.TryDequeue(out var line)) { Interlocked.Decrement(ref _count); + var size = line.CalculateSize(); + var lineBytes = 1 + Google.Protobuf.CodedOutputStream.ComputeLengthSize(size) + size; + if (lineBytes > maxBatchBytes - 16) + { + dropped++; + continue; + } + if (bytes + lineBytes > maxBatchBytes - 16) + { + batches.Add(batch); + batch = new LogBatch(); + bytes = 0; + } batch.Lines.Add(line); + bytes += lineBytes; } - return batch; + batch.Dropped = (uint)dropped; + batches.Add(batch); + return batches; } private static string Truncate(string value, int max) => value.Length <= max ? value : value[..max]; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs index 8ee57f265..fcc5964da 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ContainmentTests.cs @@ -360,6 +360,52 @@ public sealed class ContainmentTests await Scripts.Eventually(() => sink.Rendered.Contains("hello 42"), TimeSpan.FromSeconds(5), "the forwarded log line"); } + /// + /// #999 / review K-5: a script that logs megabytes inside one drain window no longer kills its worker. The worker's + /// log drain put every buffered line (≤ 1,000 × ~24 KB) into ONE LogBatch over the 4 MiB frame cap; the writer + /// faulted and the worker exited — every in-flight evaluation on the shard went BadResourceUnavailable. Now the + /// drain is cut by bytes; the worker survives (same pid) and keeps evaluating. + /// + [Fact] + public async Task A_script_logging_megabytes_at_once_does_not_kill_its_worker() + { + var sink = new CapturingSink(); + await using var runner = Scripts.Runner(Scripts.Options()); + (await runner.RunAsync(Scripts.Vt("warm", "return 1;"), Ct)).Value.ShouldBe(1); + var worker = runner.Shards[0].Current.ShouldNotBeNull(); + + var flood = await runner.RunAsync(Scripts.Vt("flood", + "var s = new string('x', 8000); for (var i = 0; i < 2000; i++) ctx.Logger.Information(s); return 2;", + timeout: TimeSpan.FromSeconds(20), logger: sink.CreateLogger()), Ct); + flood.Status.ShouldBe(ScriptRunStatus.Ok, flood.Reason); + flood.Value.ShouldBe(2); + await Scripts.Eventually(() => sink.Events.Count >= 100 ? sink : null, TimeSpan.FromSeconds(10), "the forwarded lines"); + + // Positive control: the same worker answers the next evaluation. + (await runner.RunAsync(Scripts.Vt("after", "return 3;"), Ct)).Value.ShouldBe(3); + runner.Shards[0].Current.ShouldNotBeNull().Pid.ShouldBe(worker.Pid, "the worker was not restarted"); + } + + /// + /// K-5 host side: an evaluation whose inputs alone exceed the frame cap fails THAT evaluation (unsupported type), + /// instead of faulting the pipe writer and killing the worker with every other evaluation in flight on it. + /// + [Fact] + public async Task An_evaluation_whose_inputs_exceed_the_frame_cap_fails_alone() + { + await using var runner = Scripts.Runner(Scripts.Options()); + (await runner.RunAsync(Scripts.Vt("warm", "return 1;"), Ct)).Value.ShouldBe(1); + var worker = runner.Shards[0].Current.ShouldNotBeNull(); + + var big = await runner.RunAsync(Scripts.Vt("big", "return ((string)ctx.GetTag(\"t\").Value).Length;", + inputs: Scripts.Input("t", new string('z', 5 * 1024 * 1024))), Ct); + big.Status.ShouldBe(ScriptRunStatus.Failed); + big.Reason!.ShouldContain("frame cap"); + + (await runner.RunAsync(Scripts.Vt("after", "return 3;"), Ct)).Value.ShouldBe(3); + runner.Shards[0].Current.ShouldNotBeNull().Pid.ShouldBe(worker.Pid, "the worker was not restarted"); + } + [Fact] public async Task An_alarm_predicate_runs_out_of_process() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs index dd92a6ec8..9cbc7767b 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs @@ -318,6 +318,103 @@ public sealed class ProtocolTests stream.Writes.ShouldBe(2, "one write per pass"); } + private const int SmallCap = 64 * 1024; + + private static List ReadAll(byte[] bytes, int cap) + { + var reader = new ScriptWorkerFrameReader(new MemoryStream(bytes), cap); + var frames = new List(); + while (reader.Read() is { } env) frames.Add(env); + return frames; + } + + private static Envelope BigEval(ulong id, int keyChars = 8000) + => new() { Eval = new EvalBatch { Items = { new EvalRequest { EvalId = id, Key = new string('k', keyChars) } } } }; + + private static EvalResult BigResult(ulong id, int chars = 8000) + => new() { EvalId = id, Value = new Variant { Type = Variant.Types.TypeTag.String, S = new string('r', chars) } }; + + /// + /// #999 / review K-5: evaluations queued behind a write in progress are merged, but never past the frame cap — the + /// merged batch is cut into several frames, each within the cap, in order. Before the fix the writer merged + /// unboundedly and Append threw, which faults the writer and kills the worker connection. + /// + [Fact] + public async Task Merged_evaluations_are_cut_at_the_frame_cap_not_faulted() + { + var stream = new GatedStream(); + Exception? fault = null; + var writer = new ScriptWorkerFrameWriter(stream, ex => fault = ex, SmallCap, firstSeq: 1); + + writer.TryWrite(Eval(1)).ShouldBeTrue(); // blocks on the gate + for (ulong id = 2; id <= 25; id++) writer.TryWrite(BigEval(id)).ShouldBeTrue(); // ≈ 3 × the cap queued + stream.Gate.SetResult(); + await Scripts.Eventually(() => + { + try { return ReadAll(stream.ToArray(), SmallCap).SelectMany(f => f.Eval.Items).Count() == 25; } + catch (ScriptWorkerProtocolException) { return false; } + }, TimeSpan.FromSeconds(5), "every evaluation written"); + + fault.ShouldBeNull(); + var frames = ReadAll(stream.ToArray(), SmallCap); + frames.Count.ShouldBeGreaterThanOrEqualTo(4, "the merged batch was cut, not sent whole"); + frames.ShouldAllBe(f => f.CalculateSize() <= SmallCap); + frames.SelectMany(f => f.Eval.Items).Select(i => i.EvalId).ShouldBe(Enumerable.Range(1, 25).Select(i => (ulong)i)); + frames.Select(f => f.Seq).ShouldBe(Enumerable.Range(2, frames.Count).Select(i => (ulong)i)); + } + + /// K-5: ONE envelope whose items together exceed the cap (an unbounded EvalBatch) is split by item. + [Fact] + public void One_oversized_batch_is_split_by_item() + { + var stream = new MemoryStream(); + Exception? fault = null; + var writer = new ScriptWorkerFrameWriter(stream, ex => fault = ex, SmallCap, firstSeq: 1, synchronous: true); + var batch = new EvalBatch(); + for (ulong id = 1; id <= 30; id++) batch.Items.Add(new EvalRequest { EvalId = id, Key = new string('k', 8000) }); + + writer.TryWrite(new Envelope { Eval = batch }).ShouldBeTrue(); + + fault.ShouldBeNull(); + var frames = ReadAll(stream.ToArray(), SmallCap); + frames.Count.ShouldBeGreaterThan(1); + frames.ShouldAllBe(f => f.CalculateSize() <= SmallCap); + frames.SelectMany(f => f.Eval.Items).Select(i => i.EvalId).ShouldBe(Enumerable.Range(1, 30).Select(i => (ulong)i)); + } + + /// + /// K-5: results are cut at the cap the same way, the started / deferred / soft-expired ids still arrive, and a + /// single RESULT too large for any frame fails that one evaluation (unsupported type) instead of the connection. + /// + [Fact] + public void Results_are_cut_at_the_cap_and_one_oversized_result_fails_alone() + { + var stream = new MemoryStream(); + Exception? fault = null; + var writer = new ScriptWorkerFrameWriter(stream, ex => fault = ex, SmallCap, firstSeq: 1, synchronous: true); + var results = new EvalResults { StartedEvalIds = { 100, 101 }, DeferredEvalIds = { 102 }, SoftExpiredEvalIds = { 103 } }; + for (ulong id = 1; id <= 20; id++) results.Items.Add(BigResult(id)); + results.Items.Add(BigResult(21, chars: SmallCap * 2)); // alone over the cap + results.Items.Add(BigResult(22)); + + writer.TryWrite(new Envelope { Results = results }).ShouldBeTrue(); + + fault.ShouldBeNull(); + var frames = ReadAll(stream.ToArray(), SmallCap); + frames.Count.ShouldBeGreaterThan(1); + frames.ShouldAllBe(f => f.CalculateSize() <= SmallCap); + var items = frames.SelectMany(f => f.Results.Items).ToList(); + items.Select(i => i.EvalId).ShouldBe(Enumerable.Range(1, 22).Select(i => (ulong)i)); + var oversized = items.Single(i => i.EvalId == 21); + oversized.OutcomeCase.ShouldBe(EvalResult.OutcomeOneofCase.Error); + oversized.Error.Kind.ShouldBe(ScriptError.Types.Kind.UnsupportedType); + oversized.Error.Message.ShouldContain("frame cap"); + items.Single(i => i.EvalId == 22).Value.S.Length.ShouldBe(8000, "the neighbours are untouched"); + frames.SelectMany(f => f.Results.StartedEvalIds).ShouldBe([100UL, 101UL]); + frames.SelectMany(f => f.Results.DeferredEvalIds).ShouldBe([102UL]); + frames.SelectMany(f => f.Results.SoftExpiredEvalIds).ShouldBe([103UL]); + } + /// A failed write completes the writer, reports once, and later frames are refused rather than lost silently. [Fact] public void A_failed_write_completes_the_writer_and_reports_once()