diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md
index ea741826..3d1be6d9 100644
--- a/docs/MxAccessWorkerInstanceDesign.md
+++ b/docs/MxAccessWorkerInstanceDesign.md
@@ -768,7 +768,10 @@ Parity tests need stable command-specific request and reply shapes.
Both commands set `Hresult` to `0` only after the COM call returns normally.
COM exceptions flow through `StaCommandDispatcher`, which captures the thrown
-HRESULT and converts the reply to `ProtocolStatusCode.MxaccessFailure`.
+HRESULT and converts the reply to `ProtocolStatusCode.MxaccessFailure`. A request
+the worker rejects before calling MXAccess replies `InvalidRequest` with no
+HRESULT, and a work item the STA runtime refuses at shutdown replies
+`WorkerUnavailable`; see the status mapping in `WorkerConversion.md`.
`MxAccessStaSession.GetRegisteredServerHandlesAsync` returns an STA-read
snapshot of tracked server handles for diagnostics and future cleanup logic.
@@ -814,13 +817,20 @@ caches the event sink fills: `RemoveItem` drops the handle pair's
removes the server's items with it, so the per-item eviction never runs for
them). Without this, an `AddItem` → `Write` → `RemoveItem` churn grew the
completion cache by one entry per cycle for the life of the worker.
-`AddItem`, `AddItem2`, and `AddBufferedItem` also drop both cache entries for
-the handle they receive when the registry does not already track it. An
-`OnDataChange` or `OnWriteComplete` that was queued when `RemoveItem` or
-`Unregister` ran is dispatched after the eviction and recreates the entry;
-when MXAccess later reuses that item id, `ReadBulk`'s cached path would
-otherwise serve the stale value as `was_cached = true`. A handle the
-registry still tracks belongs to a live item, so its entries are kept. Failed advice and cleanup calls
+An `OnDataChange` or `OnWriteComplete` that was queued when `RemoveItem` or
+`Unregister` ran is dispatched after the eviction. `MxAccessSession.Create`
+binds the session's handle registry to the production event sink, and the sink
+writes a cache entry only for an item handle the registry still holds; the
+event itself is still forwarded to the gateway. Without the check the late
+callback re-created the entry, and because MXAccess hands out strictly
+increasing item handles within a registration, nothing evicted it again before
+`Unregister`: a `ReadBulk` poll loop or subscribe/unsubscribe churn leaked one
+entry per cycle in the 32-bit worker (MXA-004). As a backstop for a sink that is
+not bound to a registry, `AddItem`, `AddItem2`, and `AddBufferedItem` also drop
+both cache entries for the handle they receive when the registry does not
+already track it, so a reused id never serves a stale value as
+`was_cached = true`. A handle the registry still tracks belongs to a live item,
+so its entries are kept. Failed advice and cleanup calls
leave registry state unchanged so diagnostics continue to reflect the last
successful MXAccess-owned state transition.
diff --git a/docs/WorkerConversion.md b/docs/WorkerConversion.md
index 343f62ea..7aff5cbf 100644
--- a/docs/WorkerConversion.md
+++ b/docs/WorkerConversion.md
@@ -91,29 +91,22 @@ read-modify-write merge.
### Array projection
-`ConvertArray` records the rank and per-dimension lengths so multi-dimensional `SAFEARRAY` shapes survive the round trip. The element type is resolved from the caller-supplied hint or the CLR element type via `ResolveArrayElementDataType`, then dispatched to the matching typed builder (`ConvertBoolArray`, `ConvertInt64Array`, `ConvertTimestampArray`, and so on).
+`ConvertArray` records the rank and per-dimension lengths so multi-dimensional `SAFEARRAY` shapes survive the round trip. The element type is resolved from the caller-supplied hint or the CLR element type via `ResolveArrayElementDataType`, then `TryProjectTypedArray` fills the matching typed list. Nothing is written to the `MxArray` until every element has converted.
-```csharp
-for (int dimension = 0; dimension < array.Rank; dimension++)
-{
- mxArray.Dimensions.Add((uint)array.GetLength(dimension));
-}
+Conversion is total: it never throws for an element it cannot project. It runs on the MXAccess event path, where an exception is recorded as `MxaccessEventConversionFailed` and faults the whole session, so one bad sample in a buffered event would otherwise drop every subscription on the session. When an element does not fit the attempted type, `ConvertArray` falls back in this order:
-System.Type? elementType = array.GetType().GetElementType();
-MxDataType elementDataType = ResolveArrayElementDataType(elementType, expectedElementDataType);
-mxArray.ElementDataType = elementDataType;
-```
+1. The projection the array's own CLR element type gives, when that differs from the hint. A `long[]` with a `Time` hint and an out-of-range FILETIME becomes an `Int64Values` array. `RawDiagnostic` names the element index and CLR type that failed, never its value.
+2. The raw projection: `ElementDataType = Unknown`, `RawElementDataType` set to the original hint, each element serialized as a UTF-8 byte string by `ConvertRawArray`, and the same element diagnostic. An `object[]` (a `SAFEARRAY` of `VARIANT`) has no typed fallback and goes straight here.
-When the element type cannot be classified, `ConvertArray` does not throw. It downgrades the result to `MxDataType.Unknown`, records the original expected type in `RawElementDataType`, and serializes each element via `ConvertRawArray` as a UTF-8 byte string. This satisfies the `gateway.md` requirement to keep both the best typed projection and the raw diagnostic metadata.
+An element type that has no typed projection at all (`ElapsedTime`, `Enum`, an unrecognised CLR type) takes the raw projection with the generic "unsupported variant projection" diagnostic, as before.
-```csharp
-default:
- mxArray.ElementDataType = MxDataType.Unknown;
- mxArray.RawElementDataType = (int)expectedElementDataType;
- mxArray.RawDiagnostic = CreateRawDiagnostic(array);
- mxArray.RawValues = ConvertRawArray(array);
- return mxArray;
-```
+Element rules per typed projection:
+
+- **Integer.** Widened the same way as the scalar path. `uint[]`, `long[]` and `ulong[]` always use `Int64Values`, so a `uint` above `int.MaxValue` no longer overflows. Other arrays, `object[]` included, try `Int32Values` first and retry as `Int64Values` when an element does not fit. A `ulong` above `long.MaxValue` fits neither and takes the raw projection, mirroring the scalar `UInt64 value exceeds Int64 range` fallback.
+- **Time.** A `DateTime` (`VT_DATE`) element goes through `ToTimestamp`. A `long`, or a `ulong` up to `long.MaxValue`, is a FILETIME; one outside the `DateTime` range fails the element. A string is parsed with `MxAccessEventMapper.TryParseSourceTimestamp`, the same culture-aware local-time parse used for the `OnDataChange` timestamp, because MXAccess formats that timestamp as a `VT_BSTR` and a buffered timestamp array may arrive the same way. Any other element (a 32-bit integer, which can only hold the low half of a FILETIME, or a `double`) fails the element instead of being read as a time near 1601.
+- **Null elements** (`VT_EMPTY`/`VT_NULL`) still take the type's default (`false`, `0`, `""`, the Unix epoch). How MXAccess represents a missing element in a buffered array has not been captured live, and no null encoding is invented until it is (WIP-008, decision D8 in the 2026-12-02 review plan).
+
+The scalar FILETIME projection (an `Int64` or `UInt64` value with a `Time` hint) has the same range guard: a value outside the `DateTime` range stays an `Int64Value` with a `RawDiagnostic` instead of throwing.
### Variant type names
@@ -136,38 +129,36 @@ The MXAccess engine returns values whose semantic type only fully resolves after
## HResultConverter and HResultConversion
-`HResultConverter.Convert` wraps any `Exception` thrown across the COM boundary. It prefers `COMException.ErrorCode` over `Exception.HResult` because the runtime sometimes overwrites `Exception.HResult` while marshalling, and the `ErrorCode` field is the value the COM call actually returned.
+`HResultConverter.Convert` turns an exception the command executor threw into a reply status. It prefers `COMException.ErrorCode` over `Exception.HResult` because the runtime sometimes overwrites `Exception.HResult` while marshalling, and the `ErrorCode` field is the value the COM call actually returned.
-```csharp
-public HResultConversion Convert(Exception exception)
-{
- if (exception is null)
- {
- throw new ArgumentNullException(nameof(exception));
- }
+### Status mapping
- int hresult = exception is COMException comException
- ? comException.ErrorCode
- : exception.HResult;
+The reply status says who failed. A client must be able to tell a request it built wrongly, a worker that is going away, and MXAccess rejecting the call apart, and an HRESULT is reported only when MXAccess produced one.
- return new HResultConversion(
- hresult,
- CreateProtocolStatus(hresult, exception),
- CreateSafeDiagnosticMessage(exception));
-}
-```
+| Failure | `ProtocolStatusCode` | `hresult` |
+|---------|----------------------|-----------|
+| `WorkerRequestValidationException`: the worker rejected the request before any MXAccess call (a write value with no kind, a raw payload, an `MxArray` with no values) | `INVALID_REQUEST` | not set |
+| The STA runtime refused or dropped the work item: shut down, disposed, the STA loop died, or a queued item was canceled at shutdown | `WORKER_UNAVAILABLE` | not set |
+| `COMException` from an MXAccess call | `MXACCESS_FAILURE` | `COMException.ErrorCode` |
+| `ArgumentException` from an MXAccess call (the interop raises `E_INVALIDARG`, `0x80070057`, as `ArgumentException`) | `MXACCESS_FAILURE` | `0x80070057` |
+| Any other exception from the executor | `MXACCESS_FAILURE` | `Exception.HResult` |
+
+`WorkerRequestValidationException` derives from `ArgumentException` but is a separate type because a plain `ArgumentException` is ambiguous: the interop raises one for an MXAccess `E_INVALIDARG` (for example `Suspend` on an item that is added but not advised), and that one is MXAccess parity and keeps its HRESULT. Before this split a malformed write reported `MXACCESS_FAILURE` with `0x80070057`, which is the same answer MXAccess gives for a bad argument, so the operator went looking at the Galaxy attribute (WIP-005, decision D9 in the 2026-12-02 review plan). No `.proto` change was needed: both codes already existed, and clients already handle a reply without an HRESULT.
+
+`StaCommandDispatcher` keeps the two failure sources apart structurally. The executor runs inside a wrapper on the STA that converts its exceptions to replies through `HResultConverter`, so any exception the `StaRuntime.InvokeAsync` await itself throws can only come from the runtime, and the dispatcher answers it with `WORKER_UNAVAILABLE`. The dispatcher's own shutdown and queue-full rejections were already `WORKER_UNAVAILABLE`.
`CreateProtocolStatus` maps `0` (`S_OK`) to `ProtocolStatusCode.Ok` and any non-zero HRESULT to `ProtocolStatusCode.MxaccessFailure`. The status `Message` includes the exception type name and the formatted HRESULT (`HRESULT 0x<8 hex digits>`), giving downstream operators the same identifier they would see in COM event logs.
-`HResultConversion` is an immutable carrier with three fields:
+`HResultConversion` is an immutable carrier:
| Field | Purpose |
|-------|---------|
-| `HResult` | Raw signed 32-bit HRESULT, suitable for inclusion in a wire reply |
+| `HResult` | Raw signed 32-bit HRESULT, suitable for inclusion in a wire reply; zero when `HasHResult` is false |
+| `HasHResult` | False for a worker-side validation failure, so the reply leaves `hresult` unset |
| `ProtocolStatus` | The `ProtocolStatus` projection used in command replies |
| `DiagnosticMessage` | A safe, fully-qualified diagnostic string for logs |
-The diagnostic message is built from the exception type's `FullName` and the formatted HRESULT only. It deliberately omits `Exception.Message` so user-supplied or localized strings do not leak into worker log channels that may be shipped to less trusted destinations.
+For an MXAccess failure the diagnostic message is built from the exception type's `FullName` and the formatted HRESULT only. It deliberately omits `Exception.Message` so user-supplied or localized strings do not leak into worker log channels that may be shipped to less trusted destinations. A validation failure's message is the worker's own fixed text and never contains a value, so it is included.
## MxStatusProxyConverter
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/HResultConverterTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/HResultConverterTests.cs
index 892ab29d..12a5ef75 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/HResultConverterTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/HResultConverterTests.cs
@@ -56,4 +56,19 @@ public sealed class HResultConverterTests
Assert.Contains("0x", converted.DiagnosticMessage);
Assert.DoesNotContain("do not include this", converted.DiagnosticMessage);
}
+
+ ///
+ /// WIP-005: a worker-side validation failure maps to INVALID_REQUEST and
+ /// carries no HRESULT.
+ ///
+ [Fact]
+ public void Convert_WithWorkerRequestValidationException_ReturnsInvalidRequestWithoutHResult()
+ {
+ HResultConversion converted = _converter.Convert(
+ new WorkerRequestValidationException("MxValue has no value kind set; nothing to write.", "value"));
+
+ Assert.False(converted.HasHResult);
+ Assert.Equal(ProtocolStatusCode.InvalidRequest, converted.ProtocolStatus.Code);
+ Assert.DoesNotContain("0x80070057", converted.DiagnosticMessage);
+ }
}
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/VariantConverterTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/VariantConverterTests.cs
index 1378bd93..3f8eff10 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/VariantConverterTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/VariantConverterTests.cs
@@ -115,7 +115,17 @@ public sealed class VariantConverterTests
[Fact]
public void ConvertToComValue_WithNoKind_Throws()
{
- Assert.Throws(() => _converter.ConvertToComValue(new MxValue()));
+ Assert.Throws(() => _converter.ConvertToComValue(new MxValue()));
+ }
+
+ /// WIP-005: a raw payload and an empty array are worker-side validation failures too.
+ [Fact]
+ public void ConvertToComValue_WithRawOrEmptyArray_ThrowsValidationException()
+ {
+ Assert.Throws(
+ () => _converter.ConvertToComValue(new MxValue { RawValue = ByteString.CopyFromUtf8("x") }));
+ Assert.Throws(
+ () => _converter.ConvertToComValue(new MxValue { ArrayValue = new MxArray() }));
}
/// Verifies that file time values with expected time data type are converted to protobuf timestamps.
@@ -229,6 +239,117 @@ public sealed class VariantConverterTests
converted.ArrayValue.TimestampValues.Values);
}
+ /// WIP-003: a string element in a Time array is parsed as MXAccess local time, not thrown on.
+ [Fact]
+ public void ConvertArray_WithExpectedTimeAndStringElement_ParsesLocalTime()
+ {
+ DateTime local = new(2026, 3, 26, 13, 38, 22, DateTimeKind.Local);
+ string text = local.ToString(System.Globalization.CultureInfo.CurrentCulture);
+
+ MxArray converted = _converter.ConvertArray(new object[] { text }, MxDataType.Time);
+
+ Assert.Equal(MxDataType.Time, converted.ElementDataType);
+ Assert.Equal(ProtobufTimestamp.FromDateTime(local.ToUniversalTime()), converted.TimestampValues.Values[0]);
+ }
+
+ /// WIP-003: an unparseable string element falls back to the raw projection naming the element.
+ [Fact]
+ public void ConvertArray_WithExpectedTimeAndBadString_FallsBackToRaw()
+ {
+ MxArray converted = _converter.ConvertArray(new object[] { "not a time" }, MxDataType.Time);
+
+ Assert.Equal(MxDataType.Unknown, converted.ElementDataType);
+ Assert.Equal((int)MxDataType.Time, converted.RawElementDataType);
+ Assert.Equal(MxArray.ValuesOneofCase.RawValues, converted.ValuesCase);
+ Assert.Contains("element 0", converted.RawDiagnostic);
+ Assert.DoesNotContain("not a time", converted.RawDiagnostic);
+ }
+
+ /// WIP-003: an out-of-range FILETIME in a long[] falls back to the array's own Integer projection.
+ [Fact]
+ public void ConvertArray_WithExpectedTimeAndNegativeFileTime_FallsBackToInt64()
+ {
+ MxArray converted = _converter.ConvertArray(new[] { -1L, 5L }, MxDataType.Time);
+
+ Assert.Equal(MxDataType.Integer, converted.ElementDataType);
+ Assert.Equal(new[] { -1L, 5L }, converted.Int64Values.Values);
+ Assert.Contains("element 0", converted.RawDiagnostic);
+ }
+
+ /// WIP-003: a double element is not read as a FILETIME near 1601.
+ [Fact]
+ public void ConvertArray_WithExpectedTimeAndDoubleElement_DoesNotProjectFileTime()
+ {
+ MxArray converted = _converter.ConvertArray(new[] { 46107.5d }, MxDataType.Time);
+
+ Assert.Equal(MxDataType.Double, converted.ElementDataType);
+ Assert.Equal(new[] { 46107.5d }, converted.DoubleValues.Values);
+ }
+
+ /// WIP-003: an unconvertible element in a Boolean array falls back to raw rather than throwing.
+ [Fact]
+ public void ConvertArray_WithExpectedBooleanAndBadString_FallsBackToRaw()
+ {
+ MxArray converted = _converter.ConvertArray(new object[] { true, "x" }, MxDataType.Boolean);
+
+ Assert.Equal(MxArray.ValuesOneofCase.RawValues, converted.ValuesCase);
+ Assert.Contains("element 1", converted.RawDiagnostic);
+ }
+
+ /// WIP-003: scalar FILETIMEs outside the DateTime range stay integers instead of throwing.
+ [Fact]
+ public void Convert_WithExpectedTimeAndOutOfRangeFileTime_ProjectsInteger()
+ {
+ MxValue negative = _converter.Convert(-1L, MxDataType.Time);
+ MxValue huge = _converter.Convert((ulong)long.MaxValue, MxDataType.Time);
+
+ Assert.Equal(MxDataType.Integer, negative.DataType);
+ Assert.Equal(-1L, negative.Int64Value);
+ Assert.False(string.IsNullOrEmpty(negative.RawDiagnostic));
+ Assert.Equal(MxDataType.Integer, huge.DataType);
+ Assert.Equal(long.MaxValue, huge.Int64Value);
+ }
+
+ /// WIP-004: a uint[] is widened to Int64 like a scalar uint.
+ [Fact]
+ public void ConvertArray_WithUInt32Array_WidensToInt64()
+ {
+ MxArray converted = _converter.ConvertArray(new[] { uint.MaxValue, 1u });
+
+ Assert.Equal(MxDataType.Integer, converted.ElementDataType);
+ Assert.Equal(new[] { (long)uint.MaxValue, 1L }, converted.Int64Values.Values);
+ }
+
+ /// WIP-004: a VARIANT array with a 64-bit element under an Integer hint widens instead of overflowing.
+ [Fact]
+ public void ConvertArray_WithObjectArrayAndWideInteger_WidensToInt64()
+ {
+ MxArray converted = _converter.ConvertArray(new object[] { 1, 5_000_000_000L }, MxDataType.Integer);
+
+ Assert.Equal(MxDataType.Integer, converted.ElementDataType);
+ Assert.Equal(new[] { 1L, 5_000_000_000L }, converted.Int64Values.Values);
+ }
+
+ /// WIP-004: an object[] of small integers keeps the Int32 projection.
+ [Fact]
+ public void ConvertArray_WithObjectArrayAndNarrowIntegers_KeepsInt32()
+ {
+ MxArray converted = _converter.ConvertArray(new object[] { 1, (short)2 }, MxDataType.Integer);
+
+ Assert.Equal(new[] { 1, 2 }, converted.Int32Values.Values);
+ }
+
+ /// WIP-004: a ulong above long.MaxValue mirrors the scalar raw fallback.
+ [Fact]
+ public void ConvertArray_WithUInt64AboveInt64Range_FallsBackToRaw()
+ {
+ MxArray converted = _converter.ConvertArray(new[] { ulong.MaxValue });
+
+ Assert.Equal(MxDataType.Unknown, converted.ElementDataType);
+ Assert.Equal(MxArray.ValuesOneofCase.RawValues, converted.ValuesCase);
+ Assert.Equal(ByteString.CopyFromUtf8(ulong.MaxValue.ToString(System.Globalization.CultureInfo.InvariantCulture)), converted.RawValues.Values[0]);
+ }
+
/// Verifies that unknown scalar types preserve raw value and diagnostic metadata.
[Fact]
public void Convert_WithUnknownScalar_PreservesRawMetadata()
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessBaseEventSinkTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessBaseEventSinkTests.cs
index a81362ed..9f7628fb 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessBaseEventSinkTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessBaseEventSinkTests.cs
@@ -95,6 +95,62 @@ public sealed class MxAccessBaseEventSinkTests
Assert.Equal(timestamp, cached.SourceTimestamp.ToDateTime());
}
+ ///
+ /// MXA-004: an OnDataChange or OnWriteComplete that MXAccess had already
+ /// queued on the STA is dispatched after RemoveItem evicted the
+ /// handle. The unbound sink (see )
+ /// records such a callback for any handle, which re-creates an entry nothing
+ /// evicts again because item handles are not reused within a registration.
+ /// Once bound to the session's registry, the sink must still forward the
+ /// event but leave both caches untouched for a removed handle.
+ ///
+ [Fact]
+ public void LateCallbacks_ForRemovedItemHandle_AreForwardedButNotCached()
+ {
+ MxAccessEventQueue queue = new();
+ MxAccessValueCache cache = new();
+ MxAccessWriteCompletionCache completionCache = new();
+ MxAccessBaseEventSink sink = new(queue, new MxAccessEventMapper(), cache, completionCache);
+ MxAccessHandleRegistry registry = new();
+ registry.RegisterServerHandle(7, "client");
+ registry.RegisterItemHandle(7, 21, "Tag.A", string.Empty, hasItemContext: false);
+ sink.BindHandleRegistry(registry);
+ MXSTATUS_PROXY[] statuses = Array.Empty();
+
+ registry.RemoveItemHandle(7, 21);
+ sink.OnDataChange(7, 21, 1234, 192, new DateTime(2026, 5, 18, 9, 15, 0, DateTimeKind.Utc), ref statuses);
+ sink.OnWriteComplete(7, 21, ref statuses);
+
+ Assert.Equal(2, queue.Count);
+ Assert.False(cache.TryGet(7, 21, out _));
+ Assert.Equal(0UL, completionCache.CurrentVersion(7, 21));
+ }
+
+ ///
+ /// The registry check must not suppress caching for a handle the session
+ /// still holds.
+ ///
+ [Fact]
+ public void Callbacks_ForLiveItemHandle_AreCachedWhenRegistryBound()
+ {
+ MxAccessEventQueue queue = new();
+ MxAccessValueCache cache = new();
+ MxAccessWriteCompletionCache completionCache = new();
+ MxAccessBaseEventSink sink = new(queue, new MxAccessEventMapper(), cache, completionCache);
+ MxAccessHandleRegistry registry = new();
+ registry.RegisterServerHandle(7, "client");
+ registry.RegisterItemHandle(7, 21, "Tag.A", string.Empty, hasItemContext: false);
+ sink.BindHandleRegistry(registry);
+ MXSTATUS_PROXY[] statuses = Array.Empty();
+
+ sink.OnDataChange(7, 21, 1234, 192, new DateTime(2026, 5, 18, 9, 15, 0, DateTimeKind.Utc), ref statuses);
+ sink.OnWriteComplete(7, 21, ref statuses);
+
+ Assert.True(cache.TryGet(7, 21, out MxAccessValueCache.CachedValue cached));
+ Assert.Equal(1234, cached.Value.Int32Value);
+ Assert.Equal(1UL, completionCache.CurrentVersion(7, 21));
+ }
+
///
/// Verifies that the sink-bound ValueCache is exposed for sharing with
/// the owning so writes and reads see the same
@@ -252,4 +308,38 @@ public sealed class MxAccessBaseEventSinkTests
Assert.Equal(13, mxEvent.ItemHandle);
Assert.Equal(integerDataTypeCode, mxEvent.OnBufferedDataChange.RawDataType);
}
+
+ ///
+ /// WIP-003: a multi-sample OnBufferedDataChange whose timestamp array holds
+ /// BSTR strings (the shape MXAccess uses for the OnDataChange timestamp) and
+ /// whose value array holds a value that does not fit the declared type must
+ /// still produce an event; a conversion throw would fault the session.
+ ///
+ [Fact]
+ public void OnBufferedDataChange_WithStringTimestampsAndBadValue_EnqueuesWithoutFault()
+ {
+ MxAccessEventQueue queue = new();
+ MxAccessBaseEventSink sink = new(queue, new MxAccessEventMapper());
+ MXSTATUS_PROXY[] statuses = Array.Empty();
+ DateTime local = new(2026, 3, 26, 13, 38, 22, 907, DateTimeKind.Local);
+ string timestampText = local.ToString(System.Globalization.CultureInfo.CurrentCulture);
+
+ // Raw MXAccess data-type code 1 == Boolean.
+ sink.OnBufferedDataChange(
+ hLMXServerHandle: 5,
+ phItemHandle: 13,
+ dtDataType: (ComMxDataType)1,
+ pvItemValue: new object[] { true, "not-a-bool" },
+ pwItemQuality: new object[] { 192, 192 },
+ pftItemTimeStamp: new object[] { timestampText, timestampText },
+ ref statuses);
+
+ Assert.False(queue.IsFaulted);
+ Assert.True(queue.TryDequeue(out WorkerEvent? workerEvent));
+ MxEvent mxEvent = workerEvent!.Event;
+ Assert.Equal(MxArray.ValuesOneofCase.TimestampValues, mxEvent.OnBufferedDataChange.TimestampValues.ValuesCase);
+ Assert.Equal(2, mxEvent.OnBufferedDataChange.TimestampValues.TimestampValues.Values.Count);
+ Assert.Equal(MxArray.ValuesOneofCase.RawValues, mxEvent.Value.ArrayValue.ValuesCase);
+ Assert.Contains("element 1", mxEvent.Value.ArrayValue.RawDiagnostic);
+ }
}
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs
index e3dffbef..7f4ad4ba 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs
@@ -6,6 +6,7 @@ using System.Threading;
using System.Threading.Tasks;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Worker.Bootstrap;
+using ZB.MOM.WW.MxGateway.Worker.Conversion;
using ZB.MOM.WW.MxGateway.Worker.Sta;
using ZB.MOM.WW.MxGateway.Worker.Tests.Bootstrap;
using ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport;
@@ -65,6 +66,70 @@ public sealed class StaCommandDispatcherTests
Assert.DoesNotContain("provider detail", reply.DiagnosticMessage);
}
+ ///
+ /// WIP-005: a request the worker rejects before calling MXAccess replies
+ /// INVALID_REQUEST with no HRESULT, so it cannot be mistaken for MXAccess
+ /// returning E_INVALIDARG.
+ ///
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task DispatchAsync_WhenExecutorRejectsRequest_ReturnsInvalidRequestWithoutHResult()
+ {
+ using StaRuntime runtime = CreateRuntime();
+ runtime.Start();
+ StaCommandDispatcher dispatcher = new(
+ runtime,
+ new ThrowingCommandExecutor(new WorkerRequestValidationException("MxValue has no value kind set; nothing to write.", "value")));
+
+ MxCommandReply reply = await dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Write));
+
+ Assert.Equal(ProtocolStatusCode.InvalidRequest, reply.ProtocolStatus.Code);
+ Assert.False(reply.HasHresult);
+ Assert.Equal("correlation-1", reply.CorrelationId);
+ }
+
+ ///
+ /// WIP-005: the interop raises an MXAccess E_INVALIDARG as a plain
+ /// ArgumentException; that stays an MXAccess failure with its HRESULT.
+ ///
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task DispatchAsync_WhenMxAccessRaisesInvalidArg_KeepsMxAccessFailureWithHResult()
+ {
+ using StaRuntime runtime = CreateRuntime();
+ runtime.Start();
+ StaCommandDispatcher dispatcher = new(
+ runtime,
+ new ThrowingCommandExecutor(new ArgumentException("The parameter is incorrect.")));
+
+ MxCommandReply reply = await dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Suspend));
+
+ Assert.Equal(ProtocolStatusCode.MxaccessFailure, reply.ProtocolStatus.Code);
+ Assert.True(reply.HasHresult);
+ Assert.Equal(unchecked((int)0x80070057), reply.Hresult);
+ }
+
+ ///
+ /// WIP-005: when the STA runtime itself refuses the work item (shut down
+ /// underneath the dispatcher), the reply is WORKER_UNAVAILABLE with no
+ /// HRESULT rather than an MXAccess failure carrying a CLR HRESULT.
+ ///
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task DispatchAsync_WhenStaRuntimeShutDown_ReturnsWorkerUnavailableWithoutHResult()
+ {
+ using StaRuntime runtime = CreateRuntime();
+ runtime.Start();
+ StaCommandDispatcher dispatcher = new(runtime, new RecordingCommandExecutor());
+ Assert.True(runtime.Shutdown(TimeSpan.FromSeconds(5)));
+
+ MxCommandReply reply = await dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Register));
+
+ Assert.Equal(ProtocolStatusCode.WorkerUnavailable, reply.ProtocolStatus.Code);
+ Assert.False(reply.HasHresult);
+ Assert.Equal("correlation-1", reply.CorrelationId);
+ }
+
///
/// Verifies cancellation before execution prevents the command from running.
///
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConversion.cs b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConversion.cs
index ea128942..82b7fffe 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConversion.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConversion.cs
@@ -15,13 +15,31 @@ public sealed class HResultConversion
string diagnosticMessage)
{
HResult = hresult;
+ HasHResult = true;
ProtocolStatus = protocolStatus;
DiagnosticMessage = diagnosticMessage;
}
- /// The original HResult value.
+ /// Initializes a conversion result that carries no HResult.
+ /// The converted protocol status.
+ /// Diagnostic message describing the failure.
+ public HResultConversion(
+ ProtocolStatus protocolStatus,
+ string diagnosticMessage)
+ {
+ ProtocolStatus = protocolStatus;
+ DiagnosticMessage = diagnosticMessage;
+ }
+
+ /// The original HResult value; zero when is false.
public int HResult { get; }
+ ///
+ /// Whether the failure carries an HResult. False for a request the worker
+ /// rejected before any MXAccess call, which must not report one.
+ ///
+ public bool HasHResult { get; }
+
/// The converted protocol status.
public ProtocolStatus ProtocolStatus { get; }
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConverter.cs b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConverter.cs
index b46ece0c..dd3c635e 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConverter.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConverter.cs
@@ -16,6 +16,23 @@ public sealed class HResultConverter
throw new ArgumentNullException(nameof(exception));
}
+ if (exception is WorkerRequestValidationException)
+ {
+ // The worker rejected the request before calling MXAccess, so no
+ // MXAccess HRESULT exists. Reporting the CLR one (0x80070057) would
+ // be indistinguishable from MXAccess returning E_INVALIDARG
+ // (WIP-005, decision D9).
+ return new HResultConversion(
+ new ProtocolStatus
+ {
+ Code = ProtocolStatusCode.InvalidRequest,
+ Message = exception.Message,
+ },
+ CreateSafeDiagnosticMessage(exception, includeHResult: false));
+ }
+
+ // A COMException, and an ArgumentException the interop raises for an
+ // MXAccess E_INVALIDARG, are MXAccess failures and keep the HRESULT.
int hresult = exception is COMException comException
? comException.ErrorCode
: exception.HResult;
@@ -43,9 +60,11 @@ public sealed class HResultConverter
};
}
- private static string CreateSafeDiagnosticMessage(Exception exception)
+ private static string CreateSafeDiagnosticMessage(Exception exception, bool includeHResult = true)
{
- return $"{exception.GetType().FullName}: {FormatHResult(exception.HResult)}";
+ return includeHResult
+ ? $"{exception.GetType().FullName}: {FormatHResult(exception.HResult)}"
+ : $"{exception.GetType().FullName}: {exception.Message}";
}
private static string FormatHResult(int hresult)
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/VariantConverter.cs b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/VariantConverter.cs
index 810fc877..26993def 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/VariantConverter.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/VariantConverter.cs
@@ -2,13 +2,18 @@ using System;
using System.Globalization;
using System.Linq;
using Google.Protobuf;
+using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
+using ZB.MOM.WW.MxGateway.Worker.MxAccess;
namespace ZB.MOM.WW.MxGateway.Worker.Conversion;
public sealed class VariantConverter
{
+ private const string FileTimeOutOfRangeDiagnostic =
+ "Value is outside the FILETIME range; projected as an integer.";
+
private readonly TimeZoneInfo? mxAccessLocalTimeZone;
///
@@ -99,48 +104,154 @@ public sealed class VariantConverter
System.Type? elementType = array.GetType().GetElementType();
MxDataType elementDataType = ResolveArrayElementDataType(elementType, expectedElementDataType);
- mxArray.ElementDataType = elementDataType;
+ if (TryProjectTypedArray(mxArray, array, elementDataType, elementType, out string? failure))
+ {
+ return mxArray;
+ }
+ // A typed projection failed on one element (an expected-type hint the
+ // element does not fit, a FILETIME out of range, an integer too wide).
+ // Conversion must stay total: it runs on the MXAccess event path, where
+ // a throw faults the whole session (WIP-003). Fall back to the
+ // projection the array's own CLR element type gives, and failing that
+ // to the raw projection with a diagnostic naming the element.
+ MxDataType actualDataType = ResolveArrayElementDataType(elementType, MxDataType.Unspecified);
+ if (failure is not null
+ && actualDataType != elementDataType
+ && actualDataType != MxDataType.Unknown
+ && TryProjectTypedArray(mxArray, array, actualDataType, elementType, out _))
+ {
+ mxArray.RawDiagnostic = $"{failure} Projected as {actualDataType} from the array's element type.";
+ return mxArray;
+ }
+
+ mxArray.ElementDataType = MxDataType.Unknown;
+ mxArray.RawElementDataType = (int)expectedElementDataType;
+ mxArray.RawDiagnostic = failure ?? CreateRawDiagnostic(array);
+ mxArray.RawValues = ConvertRawArray(array);
+ return mxArray;
+ }
+
+ ///
+ /// Projects into the typed value list for
+ /// . Nothing is written to
+ /// unless every element converts.
+ ///
+ /// Array message to fill on success.
+ /// Source array.
+ /// Element type to project to.
+ /// CLR element type of the source array.
+ ///
+ /// Why an element did not convert, or when the data
+ /// type has no typed projection at all.
+ ///
+ /// when the typed projection was applied.
+ private static bool TryProjectTypedArray(
+ MxArray mxArray,
+ Array array,
+ MxDataType elementDataType,
+ System.Type? elementType,
+ out string? failure)
+ {
switch (elementDataType)
{
case MxDataType.Boolean:
- mxArray.BoolValues = ConvertBoolArray(array);
- return mxArray;
+ {
+ BoolArray values = new();
+ if (!TryConvertElements(array, values.Values, ConvertBoolElement, elementDataType, out failure))
+ {
+ return false;
+ }
+
+ mxArray.ElementDataType = elementDataType;
+ mxArray.BoolValues = values;
+ return true;
+ }
case MxDataType.Integer:
- if (elementType == typeof(long) || elementType == typeof(ulong))
+ {
+ // Widen the same way the scalar path does (WIP-004): uint, long
+ // and ulong never fit an int, and an object[] (SAFEARRAY of
+ // VARIANT) may hold any of them, so a narrow projection that
+ // overflows retries as 64-bit. A ulong above long.MaxValue
+ // fails both and lands on the raw projection, as the scalar does.
+ if (!UsesInt64Projection(elementType))
{
- mxArray.Int64Values = ConvertInt64Array(array);
- }
- else
- {
- mxArray.Int32Values = ConvertInt32Array(array);
+ Int32Array narrow = new();
+ if (TryConvertElements(array, narrow.Values, ConvertInt32Element, elementDataType, out failure))
+ {
+ mxArray.ElementDataType = elementDataType;
+ mxArray.Int32Values = narrow;
+ return true;
+ }
}
- return mxArray;
+ Int64Array wide = new();
+ if (!TryConvertElements(array, wide.Values, ConvertInt64Element, elementDataType, out failure))
+ {
+ return false;
+ }
+
+ mxArray.ElementDataType = elementDataType;
+ mxArray.Int64Values = wide;
+ return true;
+ }
case MxDataType.Float:
- mxArray.FloatValues = ConvertFloatArray(array);
- return mxArray;
+ {
+ FloatArray values = new();
+ if (!TryConvertElements(array, values.Values, ConvertFloatElement, elementDataType, out failure))
+ {
+ return false;
+ }
+
+ mxArray.ElementDataType = elementDataType;
+ mxArray.FloatValues = values;
+ return true;
+ }
case MxDataType.Double:
- mxArray.DoubleValues = ConvertDoubleArray(array);
- return mxArray;
+ {
+ DoubleArray values = new();
+ if (!TryConvertElements(array, values.Values, ConvertDoubleElement, elementDataType, out failure))
+ {
+ return false;
+ }
+
+ mxArray.ElementDataType = elementDataType;
+ mxArray.DoubleValues = values;
+ return true;
+ }
case MxDataType.String:
- mxArray.StringValues = ConvertStringArray(array);
- return mxArray;
+ {
+ StringArray values = new();
+ if (!TryConvertElements(array, values.Values, ConvertStringElement, elementDataType, out failure))
+ {
+ return false;
+ }
+
+ mxArray.ElementDataType = elementDataType;
+ mxArray.StringValues = values;
+ return true;
+ }
case MxDataType.Time:
- mxArray.TimestampValues = ConvertTimestampArray(array);
- return mxArray;
+ {
+ TimestampArray values = new();
+ if (!TryConvertElements(array, values.Values, ConvertTimestampElement, elementDataType, out failure))
+ {
+ return false;
+ }
+
+ mxArray.ElementDataType = elementDataType;
+ mxArray.TimestampValues = values;
+ return true;
+ }
default:
- mxArray.ElementDataType = MxDataType.Unknown;
- mxArray.RawElementDataType = (int)expectedElementDataType;
- mxArray.RawDiagnostic = CreateRawDiagnostic(array);
- mxArray.RawValues = ConvertRawArray(array);
- return mxArray;
+ failure = null;
+ return false;
}
}
@@ -175,9 +286,9 @@ public sealed class VariantConverter
// it as the timestamped-write time argument.
MxValue.KindOneofCase.TimestampValue => value.TimestampValue.ToDateTime(),
MxValue.KindOneofCase.ArrayValue => ConvertToComArray(value.ArrayValue),
- MxValue.KindOneofCase.RawValue => throw new ArgumentException(
+ MxValue.KindOneofCase.RawValue => throw new WorkerRequestValidationException(
"MxValue raw payloads cannot be written to MXAccess.", nameof(value)),
- _ => throw new ArgumentException(
+ _ => throw new WorkerRequestValidationException(
"MxValue has no value kind set; nothing to write.", nameof(value)),
};
}
@@ -257,9 +368,9 @@ public sealed class VariantConverter
MxArray.ValuesOneofCase.StringValues => array.StringValues.Values.ToArray(),
MxArray.ValuesOneofCase.TimestampValues =>
array.TimestampValues.Values.Select(timestamp => timestamp.ToDateTime()).ToArray(),
- MxArray.ValuesOneofCase.RawValues => throw new ArgumentException(
+ MxArray.ValuesOneofCase.RawValues => throw new WorkerRequestValidationException(
"MxArray raw payloads cannot be written to MXAccess.", nameof(array)),
- _ => throw new ArgumentException(
+ _ => throw new WorkerRequestValidationException(
"MxArray has no element values set; nothing to write.", nameof(array)),
};
}
@@ -360,22 +471,35 @@ public sealed class VariantConverter
// 32 bits, which DateTime.FromFileTimeUtc would silently render as a
// timestamp near the 1601 epoch. For uint sources fall through to the integer
// projection rather than producing a bogus timestamp.
+ string? diagnostic = null;
if (expectedDataType == MxDataType.Time && value is long)
{
- return new MxValue
+ Timestamp? timestamp = TryFromFileTimeUtc(longValue);
+ if (timestamp is not null)
{
- DataType = MxDataType.Time,
- VariantType = variantType,
- TimestampValue = Timestamp.FromDateTime(DateTime.FromFileTimeUtc(longValue)),
- };
+ return new MxValue
+ {
+ DataType = MxDataType.Time,
+ VariantType = variantType,
+ TimestampValue = timestamp,
+ };
+ }
+
+ diagnostic = FileTimeOutOfRangeDiagnostic;
}
- return new MxValue
+ MxValue converted = new()
{
DataType = MxDataType.Integer,
VariantType = variantType,
Int64Value = longValue,
};
+ if (diagnostic is not null)
+ {
+ converted.RawDiagnostic = diagnostic;
+ }
+
+ return converted;
}
private static MxValue ConvertUInt64Scalar(
@@ -383,24 +507,37 @@ public sealed class VariantConverter
string variantType,
MxDataType expectedDataType)
{
+ string? diagnostic = null;
if (expectedDataType == MxDataType.Time && value <= long.MaxValue)
{
- return new MxValue
+ Timestamp? timestamp = TryFromFileTimeUtc((long)value);
+ if (timestamp is not null)
{
- DataType = MxDataType.Time,
- VariantType = variantType,
- TimestampValue = Timestamp.FromDateTime(DateTime.FromFileTimeUtc((long)value)),
- };
+ return new MxValue
+ {
+ DataType = MxDataType.Time,
+ VariantType = variantType,
+ TimestampValue = timestamp,
+ };
+ }
+
+ diagnostic = FileTimeOutOfRangeDiagnostic;
}
if (value <= long.MaxValue)
{
- return new MxValue
+ MxValue converted = new()
{
DataType = MxDataType.Integer,
VariantType = variantType,
Int64Value = (long)value,
};
+ if (diagnostic is not null)
+ {
+ converted.RawDiagnostic = diagnostic;
+ }
+
+ return converted;
}
return CreateRawValue(value, expectedDataType, "UInt64 value exceeds Int64 range.");
@@ -439,93 +576,134 @@ public sealed class VariantConverter
};
}
- private static BoolArray ConvertBoolArray(Array array)
+ private static bool TryConvertElements(
+ Array array,
+ RepeatedField target,
+ Func