Merge fix/review-2026-12-phase4 (2026-12-02 review fix plan)

This commit is contained in:
Joseph Doherty
2026-12-03 10:18:43 -05:00
13 changed files with 783 additions and 178 deletions
+18 -8
View File
@@ -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.
+30 -39
View File
@@ -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