Merge #1109 code items: proxy-fabricated Unimplemented no longer flips the gateway alarm writer to single sends (and no longer dead-letters a single send); sink-path test for the #1102 in-flight re-consider; byte[][] script results get a dedicated refusal reason; worker result-type check kept as tested defence-in-depth

This commit is contained in:
Joseph Doherty
2026-12-04 22:23:09 -05:00
9 changed files with 286 additions and 19 deletions
+1 -1
View File
@@ -140,7 +140,7 @@ processes:
previous value and status with only a server-log warning). A jagged array
(`int[][]`, `byte[][]`) is refused the same way since lmxopcua#1104 (`… cannot carry: an array of arrays …`, with a
flatten hint): it used to be the one result divergence — in process it was published as an array of Variants on a node
whose DataType is a scalar type, while the wire has no nested-array tag and the worker answered `unsupported type`. A returned collection (`List<double>`) is copied
whose DataType is a scalar type, while the wire has no nested-array tag and the worker answered `unsupported type`. `byte[][]` is not read as an array of ByteStrings (a script result has no ByteString-array form); its reason says so and also offers a `string[]` of Base64 blobs (lmxopcua#1109). A returned collection (`List<double>`) is copied
into a typed array by both runners first (lmxopcua#1092).
- **Attribution happens before release.** The worker's exit path runs attribution (strike, quarantine, suspect
marks) synchronously **before** it completes any evaluation the worker held, so a script killed for its deadline is
@@ -62,6 +62,36 @@ public static class VariantCodec
}
}
/// <summary>
/// Puts a value script's (already materialised) result on <paramref name="result"/>: the encoded value, or an
/// <c>UNSUPPORTED_TYPE</c> error naming the CLR type the wire has no tag for. The worker's only result-encoding path.
/// </summary>
/// <remarks>
/// lmxopcua#1109 — DEFENCE IN DEPTH, deliberately kept. Since lmxopcua#1100/#1104 the shared result rule
/// (<c>ScriptResultMaterializer.Materialize</c>, which the worker runs first, inside the run) refuses every type the
/// wire cannot carry with a "script threw: … cannot carry …" reason, so no script reaches the error branch today. It
/// stays because the two type lists are separate code: if <c>PublishableScalarTypes</c> ever gains a type without a
/// wire tag here (or a tag is dropped), this branch turns the gap into a reported <c>UNSUPPORTED_TYPE</c> run failure
/// instead of a value silently missing from the frame. Pinned directly by <c>ProtocolTests</c>, since no script can
/// reach it.
/// </remarks>
/// <param name="result">The eval result to fill.</param>
/// <param name="value">The script's returned value, after the shared result rule.</param>
public static void SetScriptResult(EvalResult result, object? value)
{
ArgumentNullException.ThrowIfNull(result);
if (TryEncode(value, out var variant, out var unsupported))
{
result.Value = variant;
return;
}
result.Error = new ScriptError
{
Kind = ScriptError.Types.Kind.UnsupportedType,
Message = $"script returned a value of unsupported type {unsupported}",
};
}
/// <summary>Decodes <paramref name="variant"/> back to the boxed CLR value it was encoded from.</summary>
/// <param name="variant">The variant.</param>
/// <returns>The boxed value.</returns>
@@ -128,6 +128,18 @@ public static class ScriptResultMaterializer
private static void EnsurePublishable(Type type)
{
if (IsPublishable(type)) return;
// lmxopcua#1109: byte[][] reads like "an array of ByteStrings", which OPC UA does have (the OpcUaClient driver even
// surfaces a ByteString[] as byte[][]). But a script result has no ByteString-array form: the result rule's only
// byte shape is a one-dimensional Byte array, and the out-of-process wire (VariantCodec) has no ByteString or
// nested-array tag — adding one is deliberately out of scope. So byte[][] stays refused with every other jagged
// array; the reason just says so explicitly and offers the string[] form, which does publish.
if (type == typeof(byte[][]))
throw new ScriptResultException(
"The script returned a value of type 'Byte[][]', which an OPC UA node cannot carry: an array of arrays has " +
"no representation on a node whose DataType is a scalar type, and a script result cannot be an array of " +
"ByteStrings either (its only byte shape is one flat Byte array); return one flat byte[] " +
"(e.g. a.SelectMany(x => x).ToArray()) or a string[] of encoded blobs " +
"(e.g. a.Select(Convert.ToBase64String).ToArray()).");
if (type.IsArray && type.GetElementType()!.IsArray)
throw new ScriptResultException(
$"The script returned a value of type '{Describe(type)}', which an OPC UA node cannot carry: an array of " +
@@ -35,7 +35,8 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway;
/// which the sink counts toward <c>MaxAttempts</c> on that Ack'd drain and dead-letters alone. If NO single send
/// Acks, it was not the event: later chunks are RetryPlease as for an outage (so such an outage costs at most one
/// chunk of single sends per drain);</item>
/// <item><c>Unimplemented</c> (a gateway older than the RPC) ⇒ the writer stops trying batches for its lifetime and
/// <item><c>Unimplemented</c> SENT BY the gateway (one older than the RPC — a proxy's client-fabricated 404
/// "Unimplemented" is an outage, above, #1103) ⇒ the writer stops trying batches for its lifetime and
/// sends every event individually;</item>
/// <item>any other refusal (<c>InvalidArgument</c> — a poison event or an over-limit batch, nothing sent — and the
/// other permanent codes) ⇒ that call's events are sent individually, so the poison event dead-letters alone.</item>
@@ -232,6 +233,15 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
catch (Exception exception)
{
NoteAnswered(exception);
// #1109/#1103: the outage check runs FIRST. A proxy's non-gRPC 404 surfaces as a client-FABRICATED
// Unimplemented ("Bad gRPC response. HTTP status code: 404"): a broken path, not a gateway that lacks
// SendEvents — it must not flip the writer to single sends for its lifetime.
if (IsSystemicFailure(exception))
{
_logger.LogDebug("Alarm SendEvents transiently failed ({Exception}); the batch will retry.", exception.GetType().Name);
foreach (var i in indexes) outcomes[i] = HistorianWriteOutcome.RetryPlease;
return false;
}
if (StatusOf(exception) == StatusCode.Unimplemented)
{
_batchUnsupported = true;
@@ -242,13 +252,6 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
}
if (Classify(exception) == HistorianWriteOutcome.RetryPlease)
{
if (IsSystemicFailure(exception))
{
_logger.LogDebug("Alarm SendEvents transiently failed ({Exception}); the batch will retry.", exception.GetType().Name);
foreach (var i in indexes) outcomes[i] = HistorianWriteOutcome.RetryPlease;
return false;
}
// #976 review: a RetryPlease the writer cannot vouch for as an outage (Unknown — the gateway handler threw —
// Internal, DataLoss, an unlisted code, a non-transport client exception) may be ONE event's fault. Retrying
// the whole chunk tied every sibling to it, and the sink counts a RetryPlease only on a drain with an Ack, so
@@ -424,7 +427,11 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
/// one is a transport-level fault and retries. Never dead-letter on what might be an outage (lmxopcua#976 G-8).
/// </summary>
private static HistorianWriteOutcome Classify(Exception exception) =>
StatusOf(exception) is { } code ? ClassifyStatus(code) : HistorianWriteOutcome.RetryPlease;
FirstRpc(exception) is { } rpc && !IsClientFabricated(rpc)
? ClassifyStatus(rpc.StatusCode)
// No status, or one Grpc.Net.Client fabricated (a proxy 404 => "Unimplemented", a reset => "Internal"): the
// gateway never judged the event, so it must not dead-letter (#1109/#1103).
: HistorianWriteOutcome.RetryPlease;
/// <summary>
/// Only the codes that prove the EVENT is bad dead-letter; every other code — transient, auth, <c>Cancelled</c>
@@ -469,17 +469,11 @@ internal sealed class WorkerHost
{
result.Predicate = (bool)value!;
}
else if (VariantCodec.TryEncode(value, out var variant, out var unsupported))
{
result.Value = variant;
}
else
{
result.Error = new ScriptError
{
Kind = ScriptError.Types.Kind.UnsupportedType,
Message = $"script returned a value of unsupported type {unsupported}",
};
// lmxopcua#1109: its UNSUPPORTED_TYPE branch is unreachable from a script since the shared rule above
// refuses first — kept as defence in depth against the two type lists drifting (see SetScriptResult).
VariantCodec.SetScriptResult(result, value);
}
}
catch (Exception ex)
@@ -120,6 +120,32 @@ public sealed class ScriptResultMaterializerTests
.Message.ShouldStartWith("The script returned a value of type 'Int32[][]'");
}
/// <summary>
/// lmxopcua#1109: <c>byte[][]</c> stays refused (a script result has no ByteString-array form and the worker wire has
/// no tag for one — none was added), but its reason says so and offers the two forms that do publish. A lazy /
/// collection sequence of byte[] is refused earlier (its element type is itself a sequence), before it runs.
/// </summary>
[Fact]
public void A_byte_array_of_arrays_is_refused_with_a_ByteString_specific_reason()
{
ScriptResultMaterializer.IsPublishable(typeof(byte[][])).ShouldBeFalse();
var message = Should.Throw<ScriptResultException>(
() => ScriptResultMaterializer.Materialize(new[] { new byte[] { 1, 2 }, new byte[] { 3 } }, 100)).Message;
message.ShouldStartWith("The script returned a value of type 'Byte[][]', which an OPC UA node cannot carry: an array of arrays");
message.ShouldContain("cannot be an array of ByteStrings");
message.ShouldContain("SelectMany");
message.ShouldContain("Convert.ToBase64String");
var ran = 0;
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new List<byte[]> { new byte[] { 1 } }, 100));
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(
Enumerable.Range(0, 2).Select(i => { ran++; return new[] { (byte)i }; }), 100));
ran.ShouldBe(0);
// The flat forms the reason offers do publish.
ScriptResultMaterializer.Materialize(new byte[] { 1, 2, 3 }, 100).ShouldBeOfType<byte[]>();
ScriptResultMaterializer.Materialize(new[] { "AQI=" }, 100).ShouldBeOfType<string[]>();
}
[Fact]
public void An_unpublishable_lazy_sequence_is_refused_before_it_runs()
{
@@ -151,6 +151,65 @@ public sealed class GatewayAlarmWriterReachabilityTests
w.LastReachableUtc.ShouldNotBeNull();
}
// #1109/#1103: a proxy's non-gRPC 404 is fabricated client-side as Unimplemented. It is an outage of the path, NOT a
// gateway lacking SendEvents: the writer must stay on batches, retry the whole batch and send nothing singly.
[Fact]
public async Task A_proxy_fabricated_Unimplemented_on_SendEvents_is_systemic_and_does_not_flip_to_single_sends()
{
var proxy404 = WrappedRpc(StatusCode.Unimplemented, "Bad gRPC response. HTTP status code: 404");
var batchCalls = 0;
var fake = new FakeHistorianGatewayClient
{
SendEventsSource = (_, _) =>
{
Interlocked.Increment(ref batchCalls);
return Task.FromException<SendEventsReply>(proxy404);
},
};
using var w = Writer(fake);
var outcomes = await w.WriteBatchAsync([Evt(0), Evt(1)], Ct);
outcomes.ShouldBe([HistorianWriteOutcome.RetryPlease, HistorianWriteOutcome.RetryPlease]);
w.BatchUnsupported.ShouldBeFalse();
fake.SendEventCallCount.ShouldBe(0);
w.LastReachableUtc.ShouldBeNull();
// Next drain still tries the batch RPC (and the path is healthy again).
fake.SendEventsSource = (events, _) =>
{
Interlocked.Increment(ref batchCalls);
var reply = new SendEventsReply();
foreach (var e in events) reply.Results.Add(new EventWriteResult { Id = e.Id, Success = true });
return Task.FromResult(reply);
};
await w.WriteBatchAsync([Evt(2)], Ct);
batchCalls.ShouldBe(2);
fake.SendEventCallCount.ShouldBe(0);
}
[Fact]
public void A_proxy_fabricated_Unimplemented_is_systemic_but_a_gateway_sent_one_is_not()
{
GatewayAlarmHistorianWriter.IsSystemicFailure(
WrappedRpc(StatusCode.Unimplemented, "Bad gRPC response. HTTP status code: 404")).ShouldBeTrue();
GatewayAlarmHistorianWriter.IsSystemicFailure(Wrapped(StatusCode.Unimplemented)).ShouldBeFalse();
}
// #1109/#1103: on the single-send path a fabricated Unimplemented (a PermanentFail code when the gateway sends it) must
// retry, never dead-letter — the gateway never judged the event.
[Theory]
[InlineData(StatusCode.Unimplemented, "Bad gRPC response. HTTP status code: 404")]
[InlineData(StatusCode.InvalidArgument, "Error starting gRPC call. HttpRequestException: reset")]
public async Task A_client_fabricated_permanent_code_on_a_single_send_retries(StatusCode code, string detail)
{
var fake = new FakeHistorianGatewayClient { SendEventThrows = WrappedRpc(code, detail) };
using var w = Writer(fake);
UseSingleSends(w);
var outcomes = await w.WriteBatchAsync([Evt()], Ct);
outcomes.ShouldBe([HistorianWriteOutcome.RetryPlease]);
}
private static Exception Wrapped(StatusCode code) =>
new HistorianGatewayException(code.ToString(), new RpcException(new Status(code, code.ToString())));
@@ -117,4 +117,113 @@ public sealed class GrpcData1102FilterBaselineTests
private static int ValueOf(DataSubscriptionValues values) =>
(int)values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar()!;
// #1109: the same race through the SINK delivery path (RunDeliveryAsync -> DeliverAsync), which commits after an awaited
// transport write rather than at the direct reader's pre-commit seam. v2 is parked inside sink.WriteAsync — past its
// eligibility and publication checks, not yet committed — while a whole tick considers v3.
[Theory(Timeout = 30000)]
[InlineData(false)]
[InlineData(true)]
public async Task Sink_path_a_newer_value_equal_to_the_old_baseline_is_delivered_after_an_in_flight_write_commits(bool deadband)
{
var values = await RunSinkInFlightRaceAsync(newerValue: 1, deadband ? 0.5 : null);
values.ShouldBe([2, 1]);
}
[Fact(Timeout = 30000)]
public async Task Sink_path_a_newer_value_queued_behind_an_in_flight_write_is_delivered_once()
{
var values = await RunSinkInFlightRaceAsync(newerValue: 3, null);
values.ShouldBe([2, 3]);
}
private static async Task<int[]> RunSinkInFlightRaceAsync(int newerValue, double? deadband)
{
var ct = TestContext.Current.CancellationToken;
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
HubTest.Publish(fixture.Hub, fixture.Ticket, 1, 1); fixture.Hub.ProcessPending();
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(ct);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var sink = new BaselineRaceSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().RunDeliveryAsync(sink, ct);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, deadband);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), ct);
await sink.SnapshotEnd.Task.WaitAsync(Wait, ct);
var armed = 0; var started = 0;
var considered = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.BeforeTickForTests = () => { if (Volatile.Read(ref armed) == 1) Volatile.Write(ref started, 1); };
session.AfterTickForTests = () => { if (Volatile.Read(ref started) == 1) considered.TrySetResult(true); };
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.FirstLiveWriteEntered.Task.WaitAsync(Wait, ct);
// v2 is inside the transport write: the committed baseline is still v1.
HubTest.Publish(fixture.Hub, fixture.Ticket, 3, newerValue); fixture.Hub.ProcessPending();
Volatile.Write(ref armed, 1);
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await considered.Task.WaitAsync(Wait, ct);
sink.LiveValues.ShouldBeEmpty(); // positive control: v2 has not committed yet
sink.ReleaseFirstLive();
// The commit's re-consideration (if any) is queued on the worker before this probe's ack.
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe", TimeSpan.FromSeconds(10), []), ct);
await sink.AckFor("probe").WaitAsync(Wait, ct);
// Nothing is left behind the probe either: a later tick must not deliver a duplicate.
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe-2", TimeSpan.FromSeconds(10), []), ct);
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.AckFor("probe-2").WaitAsync(Wait, ct);
writer.IsCompleted.ShouldBeFalse(); // the stream is still healthy
return [.. sink.LiveValues];
}
}
/// <summary>Records committed live values; holds the FIRST live value's transport write until released.</summary>
private sealed class BaselineRaceSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource<bool> SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> FirstLiveWriteEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly System.Collections.Concurrent.ConcurrentQueue<int> LiveValues = new();
private readonly TaskCompletionSource<bool> _releaseFirst = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly System.Collections.Concurrent.ConcurrentDictionary<string, TaskCompletionSource<bool>> _acks = new();
private int _firstLive;
internal Task AckFor(string commandId) => Ack(commandId).Task;
private TaskCompletionSource<bool> Ack(string commandId) =>
_acks.GetOrAdd(commandId, _ => new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously));
internal void ReleaseFirstLive() => _releaseFirst.TrySetResult(true);
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame));
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
var frame = ((Prepared)prepared).Frame;
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult(true);
if (frame is DataSubscriptionAck ack) Ack(ack.CommandId).TrySetResult(true);
if (frame is not DataSubscriptionValues { IsSnapshot: false } values) return;
if (Interlocked.Exchange(ref _firstLive, 1) == 0)
{
FirstLiveWriteEntered.TrySetResult(true);
await _releaseFirst.Task; // the transport write v2 is parked in
}
LiveValues.Enqueue(ValueOf(values));
}
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}
}
@@ -67,6 +67,36 @@ public sealed class ProtocolTests
}
}
/// <summary>
/// lmxopcua#1109: the worker's result-encoding step. Its UNSUPPORTED_TYPE branch is unreachable from a script (the
/// shared result rule refuses first) and is kept as defence in depth, so it is called directly here: a value with no
/// wire tag — including one the shared rule also refuses, like a jagged array or a decimal — is a reported
/// UnsupportedType error naming the type, never a missing value; a supported value is encoded and carries no error.
/// </summary>
[Fact]
public void SetScriptResult_reports_an_unencodable_value_as_UnsupportedType()
{
foreach (var value in new object[] { 1.5m, new[] { new[] { 1 } }, new[] { new byte[] { 1 } }, TimeSpan.FromSeconds(1) })
{
var result = new EvalResult { EvalId = 7 };
VariantCodec.SetScriptResult(result, value);
result.Value.ShouldBeNull(value.GetType().Name);
result.Error.ShouldNotBeNull(value.GetType().Name);
result.Error.Kind.ShouldBe(ScriptError.Types.Kind.UnsupportedType);
result.Error.Message.ShouldBe($"script returned a value of unsupported type {value.GetType().FullName}");
}
var ok = new EvalResult { EvalId = 8 };
VariantCodec.SetScriptResult(ok, new[] { 1.0, 2.0 });
ok.Error.ShouldBeNull();
VariantCodec.Decode(ok.Value).ShouldBe(new[] { 1.0, 2.0 });
var nothing = new EvalResult { EvalId = 9 };
VariantCodec.SetScriptResult(nothing, null);
nothing.Error.ShouldBeNull();
nothing.Value.Type.ShouldBe(Variant.Types.TypeTag.Null);
}
/// <summary>
/// lmxopcua#1100: the wire carries every type a script result may have (<see cref="Core.Scripting.ScriptResultMaterializer.PublishableScalarTypes"/>,
/// scalar and one-dimensional array), so nothing the materializer passes can fail "unsupported type" in the worker