fix(script-runner): #999 K-5 script-worker frames are cut at the frame cap; one oversized evaluation fails alone instead of killing the worker

This commit is contained in:
Joseph Doherty
2026-12-03 10:56:40 -05:00
parent c42eeb3c69
commit 8e91d6503d
6 changed files with 314 additions and 19 deletions
@@ -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;
}
/// <summary>
/// #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.
/// </summary>
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;
}
/// <summary>
/// The compiled form of <paramref name="key"/> in this worker when it is loaded at <paramref name="sourceHashHex"/>
/// with <paramref name="inputPaths"/> and compiled cleanly — the batch fast path, which never waits for a load.
@@ -240,35 +240,130 @@ public sealed class ScriptWorkerFrameWriter
}
}
/// <summary>
/// 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.
/// </summary>
private const int FrameHeadroom = 64;
/// <summary>The bytes a merged batch's items and ids may add up to so the frame stays within the cap.</summary>
private int MergeBudget => Math.Max(1, MaxFrameBytes - FrameHeadroom);
/// <summary>
/// Whether <paramref name="item"/> 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.
/// </summary>
/// <param name="item">The evaluation request or result.</param>
/// <returns>Whether it fits.</returns>
public bool FitsOneFrame(IMessage item) => ItemBytes(item) <= MergeBudget;
/// <summary>A repeated-message item's encoded size inside its batch: tag (1 byte) + length prefix + body.</summary>
private static int ItemBytes(IMessage item)
{
var size = item.CalculateSize();
return 1 + CodedOutputStream.ComputeLengthSize(size) + size;
}
/// <summary>A packed repeated uint64 id: at most 10 bytes; the per-list tag + length is in the headroom.</summary>
private const int IdBytes = 10;
/// <summary>
/// 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 <c>UNSUPPORTED_TYPE</c> error for
/// that evaluation alone; an oversized single evaluation REQUEST is refused before it gets here
/// (<see cref="FitsOneFrame"/>), so reaching <see cref="Append"/> with one is still a protocol fault.
/// </summary>
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();
}
/// <summary>The id lists of <paramref name="body"/>, each with the accessor for the same list on a merged batch.</summary>
private static IEnumerable<(ulong Id, Func<EvalResults, Google.Protobuf.Collections.RepeatedField<ulong>> 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)
@@ -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()
/// <summary>
/// Drains every buffered line into batches of at most <paramref name="maxBatchBytes"/> encoded bytes each
/// (#999 / review K-5). A line too large for any batch on its own is counted as dropped.
/// </summary>
public List<LogBatch> Drain(int maxBatchBytes)
{
var batches = new List<LogBatch>();
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];