perf(sessions): bound a sparse array write by the worker command limit before expanding it (SES-008, #258)

IWorkerClient gains MaxCommandBytes (the negotiated frame maximum less the
sequence-stamp allowance, the bound its CommandTooLarge pre-check uses).
GatewaySession passes it as a byte budget into SparseArrayExpander, which
charges a lower bound of each expanded array's encoding (default-valued slots)
before allocating, so an oversized sparse write - or a bulk command whose
sparse values together overrun the frame - is rejected with InvalidArgument
without the million-slot allocation.
This commit is contained in:
Joseph Doherty
2026-12-03 13:08:29 -05:00
parent d526b69b0b
commit 0967fe0730
8 changed files with 187 additions and 15 deletions
@@ -1533,7 +1533,11 @@ public sealed class GatewaySession : IAsyncDisposable
IWorkerClient workerClient = await GetReadyWorkerClientAsync(cancellationToken).ConfigureAwait(false);
if (command.Command is not null)
{
NormalizeOutboundCommand(command.Command);
// The client's own CommandTooLarge pre-check is exact but runs after expansion; this
// budget is the same limit, charged with a lower bound of each expanded array's encoding
// so an oversized sparse write is refused before the array is allocated (SES-008).
long expansionBudget = workerClient.MaxCommandBytes ?? long.MaxValue;
NormalizeOutboundCommand(command.Command, ref expansionBudget);
}
TouchClientActivity(_eventStreaming.TimeProvider.GetUtcNow());
@@ -1549,8 +1553,9 @@ public sealed class GatewaySession : IAsyncDisposable
// partial-array write primitive — the worker only ever sees a full MxArray.
// SparseArrayExpander.Expand throws SparseArrayException for an invalid sparse payload; that
// propagates out of InvokeAsync and the gRPC layer maps it to InvalidArgument. It is
// deliberately not caught here.
private void NormalizeOutboundCommand(MxCommand command)
// deliberately not caught here. expansionBudget is the worker command byte limit, shared by
// every sparse value in the command so a bulk write of many sparse arrays is bounded as a whole.
private void NormalizeOutboundCommand(MxCommand command, ref long expansionBudget)
{
switch (command.PayloadCase)
{
@@ -1574,42 +1579,42 @@ public sealed class GatewaySession : IAsyncDisposable
break;
case MxCommand.PayloadOneofCase.Write:
ExpandValue(command.Write.Value);
ExpandValue(command.Write.Value, ref expansionBudget);
break;
case MxCommand.PayloadOneofCase.WriteSecured:
ExpandValue(command.WriteSecured.Value);
ExpandValue(command.WriteSecured.Value, ref expansionBudget);
break;
case MxCommand.PayloadOneofCase.Write2:
ExpandValue(command.Write2.Value);
ExpandValue(command.Write2.Value, ref expansionBudget);
break;
case MxCommand.PayloadOneofCase.WriteSecured2:
ExpandValue(command.WriteSecured2.Value);
ExpandValue(command.WriteSecured2.Value, ref expansionBudget);
break;
case MxCommand.PayloadOneofCase.WriteBulk:
foreach (WriteBulkEntry entry in command.WriteBulk.Entries)
{
ExpandValue(entry.Value);
ExpandValue(entry.Value, ref expansionBudget);
}
break;
case MxCommand.PayloadOneofCase.Write2Bulk:
foreach (Write2BulkEntry entry in command.Write2Bulk.Entries)
{
ExpandValue(entry.Value);
ExpandValue(entry.Value, ref expansionBudget);
}
break;
case MxCommand.PayloadOneofCase.WriteSecuredBulk:
foreach (WriteSecuredBulkEntry entry in command.WriteSecuredBulk.Entries)
{
ExpandValue(entry.Value);
ExpandValue(entry.Value, ref expansionBudget);
}
break;
case MxCommand.PayloadOneofCase.WriteSecured2Bulk:
foreach (WriteSecured2BulkEntry entry in command.WriteSecured2Bulk.Entries)
{
ExpandValue(entry.Value);
ExpandValue(entry.Value, ref expansionBudget);
}
break;
@@ -1623,12 +1628,13 @@ public sealed class GatewaySession : IAsyncDisposable
// MXAccess writes replace the whole array; expand a sparse value in place so the worker only
// ever receives a whole-array MxValue. No-op for null or non-sparse values. The configured
// MxGateway:Events:MaxSparseArrayLength cap is enforced before the full array is allocated.
private void ExpandValue(MxValue? value)
// MxGateway:Events:MaxSparseArrayLength cap and the worker command size budget are both
// enforced before the full array is allocated.
private void ExpandValue(MxValue? value, ref long expansionBudget)
{
if (value is not null)
{
SparseArrayExpander.Expand(value, _eventStreaming.EventOptions.MaxSparseArrayLength);
SparseArrayExpander.Expand(value, _eventStreaming.EventOptions.MaxSparseArrayLength, ref expansionBudget);
}
}
@@ -50,6 +50,30 @@ internal static class SparseArrayExpander
/// element value whose kind does not match the declared element type.
/// </exception>
public static void Expand(MxValue value, int maxSparseArrayLength = int.MaxValue)
{
long unbounded = long.MaxValue;
Expand(value, maxSparseArrayLength, ref unbounded);
}
/// <summary>
/// Expands <paramref name="value"/> as <see cref="Expand(MxValue, int)"/> does, first charging a
/// lower bound of the expanded array's encoded size against <paramref name="remainingCommandBytes"/>.
/// </summary>
/// <param name="value">The value to expand in place.</param>
/// <param name="maxSparseArrayLength">The maximum <c>total_length</c> the sparse array may declare.</param>
/// <param name="remainingCommandBytes">
/// Bytes of the worker command size limit still available to expanded arrays in this command.
/// A sparse value whose expansion needs at least more than this is rejected before the array is
/// allocated; otherwise the lower bound is deducted, so several sparse values in one bulk
/// command share the budget. The bound is the encoding of every slot at its default value, so it
/// never rejects a write that would have fit; the worker client's exact size check still runs
/// on the expanded command.
/// </param>
/// <exception cref="SparseArrayException">
/// Thrown for the same invalid payloads as <see cref="Expand(MxValue, int)"/>, and when the
/// expansion cannot fit <paramref name="remainingCommandBytes"/>.
/// </exception>
public static void Expand(MxValue value, int maxSparseArrayLength, ref long remainingCommandBytes)
{
ArgumentNullException.ThrowIfNull(value);
@@ -84,6 +108,19 @@ internal static class SparseArrayExpander
$"Sparse array total_length {totalLength} exceeds the maximum supported array length {Array.MaxLength}.");
}
// Every slot encodes to at least its default value's size, so this is a lower bound on the
// expanded array. Checked before anything is allocated: a request of a few dozen bytes can
// otherwise declare a million-slot array that the worker frame could never carry (SES-008).
long minimumEncodedBytes = (long)totalLength * MinimumEncodedBytesPerSlot(elementType);
if (minimumEncodedBytes > remainingCommandBytes)
{
throw Invalid(
$"Sparse array total_length {totalLength} of element_data_type '{elementType}' expands to at least "
+ $"{minimumEncodedBytes} bytes, exceeding the {remainingCommandBytes} bytes left in the worker command size limit.");
}
remainingCommandBytes -= minimumEncodedBytes;
int length = (int)totalLength;
HashSet<uint> seenIndices = new();
@@ -260,6 +297,20 @@ internal static class SparseArrayExpander
return array;
}
// Encoded size of one default-valued slot in the expanded array: packed bool and varint 0 are one
// byte, packed float/double are fixed width, and each empty string or empty Timestamp message
// costs at least a tag byte and a zero length byte.
private static int MinimumEncodedBytesPerSlot(MxDataType elementType) => elementType switch
{
MxDataType.Boolean => 1,
MxDataType.Integer => 1,
MxDataType.Float => sizeof(float),
MxDataType.Double => sizeof(double),
MxDataType.String => 2,
MxDataType.Time => 2,
_ => 1,
};
private static bool IsSupportedElementType(MxDataType elementType) => elementType switch
{
MxDataType.Boolean => true,
@@ -35,6 +35,15 @@ public interface IWorkerClient : IAsyncDisposable
/// </summary>
string? RecordInfoPinStatus => null;
/// <summary>
/// Largest command envelope, in bytes, this client will accept for sending — the negotiated
/// worker-frame maximum less the sequence-stamp allowance, i.e. the bound its own
/// <c>CommandTooLarge</c> pre-check enforces. The session uses it to reject a sparse array
/// write whose expansion cannot fit before allocating the expanded array (SES-008). The
/// default implementation returns <see langword="null"/> (no bound known).
/// </summary>
int? MaxCommandBytes => null;
/// <summary>UTC timestamp of the most recent heartbeat from the worker.</summary>
DateTimeOffset LastHeartbeatAt { get; }
@@ -188,6 +188,9 @@ public sealed class WorkerClient : IWorkerClient
/// <inheritdoc />
public string? RecordInfoPinStatus => Volatile.Read(ref _recordInfoPinStatus);
/// <inheritdoc />
public int? MaxCommandBytes => _connection.FrameOptions.MaxMessageBytes - MaxSequenceEncodingBytes;
/// <inheritdoc />
public DateTimeOffset LastHeartbeatAt
{
@@ -144,6 +144,41 @@ public sealed class GatewayArrayWriteWiringTests
Assert.Equal(new[] { 0, 7, 0, 0 }, forwarded.ArrayValue.Int32Values.Values);
}
/// <summary>
/// SES-008: a bulk write whose sparse values together cannot fit the worker's command size
/// limit is rejected before the overrunning value is expanded, and nothing reaches the worker.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task WriteBulk_SparseValuesOverWorkerCommandLimit_RejectedBeforeExpanding()
{
CapturingWorkerClient worker = new() { MaxCommandBytes = 3_000 };
GatewaySession session = CreateReadySession(worker);
MxValue first = new() { SparseArrayValue = new MxSparseArray { ElementDataType = MxDataType.Time, TotalLength = 1_000 } };
MxValue second = new() { SparseArrayValue = new MxSparseArray { ElementDataType = MxDataType.Time, TotalLength = 1_000 } };
WorkerCommand command = new()
{
Command = new MxCommand
{
Kind = MxCommandKind.WriteBulk,
WriteBulk = new WriteBulkCommand
{
ServerHandle = 1,
Entries =
{
new WriteBulkEntry { ItemHandle = 42, Value = first },
new WriteBulkEntry { ItemHandle = 43, Value = second },
},
},
},
};
await Assert.ThrowsAsync<SparseArrayException>(() => session.InvokeAsync(command, CancellationToken.None));
Assert.Null(worker.LastCommand);
Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, second.KindCase);
}
/// <summary>
/// SES-008: a sparse write to a session that cannot take commands fails on readiness before the
/// sparse value is expanded, so a not-ready session never pays for the whole-array allocation.
@@ -824,6 +859,9 @@ public sealed class GatewayArrayWriteWiringTests
/// <summary>Gets or sets the reply returned by the next invocation.</summary>
public WorkerCommandReply NextReply { get; set; } = new();
/// <inheritdoc />
public int? MaxCommandBytes { get; set; }
/// <inheritdoc />
public string SessionId { get; } = "session-array-write-wiring";
@@ -161,6 +161,65 @@ public sealed class SparseArrayExpanderTests
Assert.Equal(0, slots[0].Seconds);
}
/// <summary>
/// SES-008: a sparse write whose expansion cannot fit the worker command limit is rejected
/// before the array is allocated, and the budget is left untouched.
/// </summary>
[Fact]
public void Expand_WhenMinimumEncodingExceedsBudget_ThrowsBeforeExpanding()
{
MxValue value = SparseValue(MxDataType.Time, 1_000_000);
long budget = 1_000_000;
SparseArrayException ex = Assert.Throws<SparseArrayException>(
() => SparseArrayExpander.Expand(value, int.MaxValue, ref budget));
Assert.Contains("at least 2000000 bytes", ex.Message, StringComparison.Ordinal);
Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, value.KindCase);
Assert.Equal(1_000_000, budget);
}
/// <summary>SES-008: several sparse values in one command share the budget.</summary>
[Fact]
public void Expand_SharedBudget_RejectsTheValueThatOverrunsIt()
{
MxValue first = SparseValue(MxDataType.Double, 100);
MxValue second = SparseValue(MxDataType.Double, 100);
long budget = 1_500;
SparseArrayExpander.Expand(first, int.MaxValue, ref budget);
Assert.Equal(700, budget);
Assert.Throws<SparseArrayException>(() => SparseArrayExpander.Expand(second, int.MaxValue, ref budget));
Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, second.KindCase);
}
/// <summary>
/// SES-008: the charged size is a true lower bound on the expanded encoding for every element
/// type, so the budget never refuses a write the worker frame could have carried.
/// </summary>
/// <param name="elementType">The sparse element type.</param>
[Theory]
[InlineData(MxDataType.Boolean)]
[InlineData(MxDataType.Integer)]
[InlineData(MxDataType.Float)]
[InlineData(MxDataType.Double)]
[InlineData(MxDataType.String)]
[InlineData(MxDataType.Time)]
public void Expand_ChargedBytes_DoNotExceedExpandedEncoding(MxDataType elementType)
{
MxValue value = SparseValue(elementType, 1_000);
long budget = long.MaxValue;
SparseArrayExpander.Expand(value, int.MaxValue, ref budget);
long charged = long.MaxValue - budget;
Assert.True(charged > 0);
Assert.True(
charged <= value.ArrayValue.CalculateSize(),
$"charged {charged} > encoded {value.ArrayValue.CalculateSize()}");
}
/// <summary>Verifies that expanding a Double sparse array fills defaults and applies the given element.</summary>
[Fact]
public void Expand_Double_HappyPath()