diff --git a/docs/drivers/FOCAS.md b/docs/drivers/FOCAS.md index 34f7a0635..1d433f668 100644 --- a/docs/drivers/FOCAS.md +++ b/docs/drivers/FOCAS.md @@ -640,7 +640,7 @@ test fixtures (`tests/.../Driver.FOCAS.Tests/Fixtures/v3/`). Client-visible chan | What | Before | Now | |------|--------|-----| -| `cnc_rdmacro` decimal | read at payload offset 4 — a constant `10` length field — so `#500 = 1.0` published `0.01` | `dec_val` at offset 6; `mantissa / 10^dec`. Vacant variable → `BadNoData`; fractional value on an integer tag → `BadTypeMismatch`; integer tags receive the exact whole value | +| `cnc_rdmacro` decimal | read at payload offset 4 — a constant `10` length field — so `#500 = 1.0` published `0.01` | `dec_val` at offset 6; `mantissa / 10^dec`. Vacant variable → `BadNoData`; fractional value on an integer tag → `BadTypeMismatch`; integer tags receive the exact whole value. A reply too short to decode (macro, parameter) is `BadTypeMismatch` on that tag with no health impact: the CNC answered and the session is intact (#1036, `FocasWirePayloadException`) | | Axis positions | scaled by `cnc_getfigure` (0x00D3), which does not exist — on hardware: raw counts | scaled by each block's own `base^exponent`; undescribable block → `BadNoData` | | Axis / spindle names | first 2 of 4 record bytes — `AA6`/`AA7` collapsed to `AA` | whole record up to the first NUL (residue after it discarded) — ⚠️ `Axes/AA_1`→`Axes/AA6` on such a machine | | `ServoLoad` | `value / 10^base` (offset 4 is the base, 10) — always ~0 | `value / base^exponent`, a direct percentage | diff --git a/docs/drivers/Mqtt.md b/docs/drivers/Mqtt.md index 8a18910fe..1572a2ba7 100644 --- a/docs/drivers/Mqtt.md +++ b/docs/drivers/Mqtt.md @@ -560,7 +560,7 @@ every MQTT node materialized read-only regardless of what the operator authored. | Mode | Destination | Payload | |---|---|---| -| **Plain** | the tag's `writeTopic` | the value as UTF-8 text (`Raw`/`Scalar`; a Boolean is `true`/`false`, lower-case — #988 M-15, it was .NET's `True`/`False`) or a bare JSON literal (`Json`) | +| **Plain** | the tag's `writeTopic` | the value as UTF-8 text (`Raw`/`Scalar`; a Boolean is `true`/`false`, lower-case — #988 M-15, it was .NET's `True`/`False`; a DateTime/DateTimeOffset is ISO-8601 UTC round-trip form, `2026-08-10T12:30:45.1230000Z`, an Unspecified kind read as UTC — #1044, it was `08/10/2026 12:30:45`) or a bare JSON literal (`Json`) | | **Sparkplug B** | `spBv1.0/{group}/DCMD/{node}/{device}` for a device metric, `spBv1.0/{group}/NCMD/{node}` for an edge-node metric | a Sparkplug `Payload` carrying the metric **by name**, with an explicit `Datatype` and no `seq` | Both publish with `retain: false`. A **Plain** write goes at **QoS 1** (STAB-26): the publish completes only diff --git a/docs/drivers/Sql.md b/docs/drivers/Sql.md index d25a5b960..c79f1b4fe 100644 --- a/docs/drivers/Sql.md +++ b/docs/drivers/Sql.md @@ -236,7 +236,11 @@ row: as one extended-protocol statement; the server rejects anything after a `;` itself. Oracle (ODP.NET) refuses a second statement anyway. SQL Server and MySQL execute a multi-statement batch — there the guard is the line (on SQL Server its T-SQL parse, above), and MySQL's read-only session is defence in depth - that hidden text could undo. + that hidden text could undo. **On MySQL the read-only session is NOT a boundary (#1042):** MySqlConnector + cannot disable multi-statement execution, so a statement that got past the guard runs as a batch in which a + later statement may re-enable writes for the session (or `COMMIT` out of the transaction). A MySQL / MariaDB + driver — read-only above all — must connect with a **`SELECT`-only login**; treat that grant, not the session + mode, as the only enforcement. - None of this replaces the grant: a non-transactional side effect (an e-mail procedure, a call out to another system, an autonomous transaction) is outside every layer — which is why a read-only driver **must** connect with a `SELECT`-only login (see [Database login](#database-login-required)). @@ -464,7 +468,7 @@ both and is rolled back (`BadConfigurationError`). |---|---| | Committed | `Good` | | `Update` (or a non-MySQL `Upsert`) touched no row — the key is absent; nothing is inserted | `BadNoData` | -| More rows than the mode allows — the key is not unique; rolled back. The count is the **target statement's own**: on SQL Server the driver reads `@@ROWCOUNT` right after it (an `OUTPUT` parameter), because SqlClient's command-level count also sums trigger DML — an audit trigger that inserts a history row used to make every single-row write "touch 2 rows" and roll back (#987). PostgreSQL, MySQL and Oracle already report the statement alone. Odbc reports whatever its backend's driver does (an ODBC link to SQL Server keeps the trigger-summed count). | `BadConfigurationError` | +| More rows than the mode allows — the key is not unique; rolled back. The count is the **target statement's own**: on SQL Server the driver reads `@@ROWCOUNT` right after it (an `OUTPUT` parameter), because SqlClient's command-level count also sums trigger DML — an audit trigger that inserts a history row used to make every single-row write "touch 2 rows" and roll back (#987). PostgreSQL, MySQL and Oracle already report the statement alone. Odbc reports whatever its backend's driver does (an ODBC link to SQL Server keeps the trigger-summed count, #1043 — the backend is unknown so the driver cannot append `@@ROWCOUNT`, and ODBC has no output parameters outside a procedure call; to write to SQL Server use the native `SqlServer` provider, or keep the trigger from counting with `SET NOCOUNT ON` as its first statement). | `BadConfigurationError` | | The provider could not report a row count; rolled back | `BadNotSupported` | | Unique / primary-key violation — e.g. an `Insert` of a key that exists (SQLSTATE 23505, SQL Server 2627/2601, MySQL 1062, ORA-00001) | `BadEntryExists` | | Another integrity rule — NOT NULL, foreign key, CHECK (SQLSTATE class 23, SQL Server 515/547, ORA-01400/02290/02291) — or a data exception: overflow, truncation, an unconvertible value (SQLSTATE class 22, SQL Server 8115/8152/245, ORA-01438/12899/01722) | `BadOutOfRange` | @@ -509,7 +513,8 @@ The driver's own guards are not a substitute for the database's grants: per-dialect keyword check plus an always-rolled-back (read-only where the provider has one) transaction; none of that can stop a **non-transactional** side effect — a function that sends mail or calls out, autonomous transactions — and on SQL Server and MySQL a statement that got past the guard would run as a - batch. Only the grant is a boundary. + batch. Only the grant is a boundary. This applies with particular force to **MySQL**, whose read-only + *session* is not a boundary either (MySqlConnector cannot disable multi-statement execution, #1042). - **A writable driver must connect with a login limited to its write targets** — `SELECT` as above, plus exactly what its modes need on exactly the tables / procedures its writable tags name: `UPDATE` (Update), `INSERT` (Insert), `INSERT` + `UPDATE` (Upsert; SQL Server's `MERGE` also needs diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport/Cip/RequestScheduler.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport/Cip/RequestScheduler.cs index 585963850..9ec23d2b9 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport/Cip/RequestScheduler.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport/Cip/RequestScheduler.cs @@ -51,6 +51,13 @@ public sealed class RequestScheduler : IAsyncDisposable /// This request's node in the scheduler queue, or null once dequeued. public LinkedListNode? Node { get; set; } + /// The scheduler this request was queued on; the cancellation callback's state (P-24: passing + /// this object as the state avoids boxing a tuple per cancellable request). + public RequestScheduler? Owner { get; init; } + + /// The caller's token, reported as the cancellation cause. + public CancellationToken Token { get; init; } + /// Stores the waiter's registration; disposes it at once if the waiter already completed. /// The cancellation registration to track. /// The scheduler whose live-registration count is maintained. @@ -171,7 +178,11 @@ public sealed class RequestScheduler : IAsyncDisposable ArgumentNullException.ThrowIfNull(request); if (ct.IsCancellationRequested) return Task.FromCanceled(ct); - var p = new Pending(request, exclusive || expectedReplyBytes < 0, Math.Max(expectedReplyBytes, UnknownReply)); + var p = new Pending(request, exclusive || expectedReplyBytes < 0, Math.Max(expectedReplyBytes, UnknownReply)) + { + Owner = this, + Token = ct, + }; lock (_lock) { ObjectDisposedException.ThrowIf(_disposed, this); @@ -183,14 +194,15 @@ public sealed class RequestScheduler : IAsyncDisposable Interlocked.Increment(ref _liveRegistrations); var registration = ct.Register(static state => { - var (self, pending, token) = ((RequestScheduler, Pending, CancellationToken))state!; + var pending = (Pending)state!; + var self = pending.Owner!; Interlocked.Increment(ref self._cancellationCallbacksRun); lock (self._lock) { if (pending.Node?.List is not null) self._queue.Remove(pending.Node); } - pending.Cancel(token, self); - }, (this, p, ct)); + pending.Cancel(pending.Token, self); + }, p); p.SetRegistration(registration, this); } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport/Logix/LogixTagClient.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport/Logix/LogixTagClient.cs index 85987cce0..86f2fc245 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport/Logix/LogixTagClient.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport/Logix/LogixTagClient.cs @@ -50,7 +50,7 @@ public sealed class LogixTagClient(RequestScheduler scheduler, ICipChannel chann byte[] path, ushort elements, CancellationToken ct, int elementBytes = 0) { ArgumentNullException.ThrowIfNull(path); - var reply = await _scheduler.SendAsync(LogixServices.ReadTagFragmented(path, elements, 0), ct, + var reply = await _scheduler.SendAsync(FirstReadRequest(path, elements), ct, expectedReplyBytes: ExpectedReadReplyBytes(elements, elementBytes, 0)).ConfigureAwait(false); var (type, handle, first) = LogixServices.ParseReadReply(reply); // throws on any status but 0x00/0x06 @@ -96,6 +96,27 @@ public sealed class LogixTagClient(RequestScheduler scheduler, ICipChannel chann } } + /// One cached offset-0 read request: the constant bytes a steady poll resends every cycle (P-24). + private sealed record FirstRead(byte[] Path, ushort Elements, byte[] Request); + + private volatile FirstRead? _firstRead; + + /// + /// The offset-0 Read Tag Fragmented request for . A tag's runtime reads the same encoded + /// path (the same array instance) with the same element count every poll, so the request is built once and + /// reused; a different path instance or count rebuilds it. The request bytes are never mutated after queueing + /// (the scheduler only reads them), so sharing one array across successive reads is safe. + /// + private byte[] FirstReadRequest(byte[] path, ushort elements) + { + var cached = _firstRead; + if (cached is not null && ReferenceEquals(cached.Path, path) && cached.Elements == elements) + return cached.Request; + var request = LogixServices.ReadTagFragmented(path, elements, 0); + _firstRead = new FirstRead(path, elements, request); + return request; + } + /// Appends to a pooled buffer, growing it (rent bigger, copy, return) as needed. private static void Append(ref byte[] buffer, ref int count, ReadOnlySpan chunk) { diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs index 36420911f..23b8f5c04 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriver.cs @@ -535,7 +535,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadConfigurationError, null, now); continue; } - var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily); + var parsed = device.ParseAddress(def); if (parsed is null) { WarnMalformedOnce(device, def); @@ -686,6 +686,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag { var def = item.Def; var reference = item.Reference; + IAbLegacyTagRuntime? usedRuntime = null; // the handle this call actually used (identity-checked eviction) try { if (item.Parsed.IsIndirect) @@ -733,9 +734,10 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag return (OpVerdict.Neutral, null); } runtime = live; + usedRuntime = live; await runtime.ReadAsync(ct).ConfigureAwait(false); status = runtime.GetStatus(); - var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily); + var parsed = device.ParseAddress(def); if (status != 0) value = null; else if (IsArrayTag(def)) @@ -771,8 +773,9 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag WarnRefusalOnce(device, def, "read", $"unclassifiable reply {(AbStatus)status}", results[item.Index].StatusCode); return (OpVerdict.Opaque, $"unclassifiable reply {(AbStatus)status} reading {reference}"); } - // Evict the stale handle so the next call re-creates it (mirrors AbCip). - EvictRuntime(device, def.Name); + // Evict the stale handle so the next call re-creates it (mirrors AbCip) — identity-checked: a sibling + // that reconnected under the gate after we released it must not lose its fresh handle. + EvictUsedRuntime(device, def.Name, usedRuntime); if (!device.FirstNonZeroStatusLogged) { device.FirstNonZeroStatusLogged = true; @@ -828,7 +831,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag catch (Exception ex) { // Transport exception — evict so the next read creates a fresh handle (mirrors AbCip). - EvictRuntime(device, def.Name); + EvictUsedRuntime(device, def.Name, usedRuntime); results[item.Index] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadCommunicationError, null, now); return (OpVerdict.Fault, ex.Message); } @@ -920,9 +923,10 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag continue; } + IAbLegacyTagRuntime? usedRuntime = null; // the handle this write actually used try { - var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily); + var parsed = device.ParseAddress(def); // A malformed address is a config error, not a comms fault (BadNodeIdUnknown, warned once per tag). if (parsed is null) @@ -1052,6 +1056,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag continue; // the index moved under us (N3): not written, no health evidence } runtime = live; + usedRuntime = live; if (arrayValue is not null) runtime.EncodeArray(arrayFileType, arrayValue); else runtime.EncodeValue(def.DataType, parsed.BitIndex, w.Value); await runtime.WriteAsync(cancellationToken).ConfigureAwait(false); @@ -1064,7 +1069,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag results[i] = new WriteResult(status == 0 ? AbLegacyStatusMapper.Good : AbLegacyStatusMapper.MapStatus(status)); // A no-reply status evicts the stale handle so the next call re-creates it (mirrors AbCip). - if (IsNoReply((AbStatus)status) && status != 0) EvictRuntime(device, def.Name); + if (IsNoReply((AbStatus)status) && status != 0) EvictUsedRuntime(device, def.Name, usedRuntime); RecordWriteStatus(device, def, status, ref outcome); } catch (OperationCanceledException) { throw; } @@ -1111,7 +1116,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag catch (Exception ex) { // Transport exception — evict so the next write/read creates a fresh handle (mirrors AbCip). - EvictRuntime(device, def.Name); + EvictUsedRuntime(device, def.Name, usedRuntime); device.RecordCommsFault(Clock()); results[i] = new WriteResult(AbLegacyStatusMapper.BadCommunicationError); outcome.FaultMessage ??= ex.Message; @@ -1371,14 +1376,12 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag device.IndirectLastParent[indirectName] = parentName; if (previous is not null && !string.Equals(previous, parentName, StringComparison.OrdinalIgnoreCase)) { - var oldGate = device.GetRmwLock(previous); - await oldGate.WaitAsync(ct).ConfigureAwait(false); - try { EvictParentRuntime(device, previous); } finally { oldGate.Release(); } + var oldHold = await device.EnterRmwAsync(previous, ct).ConfigureAwait(false); + try { EvictParentRuntime(device, previous); } finally { oldHold.Dispose(); } } } - var rmwLock = device.GetRmwLock(parentName); - await rmwLock.WaitAsync(ct).ConfigureAwait(false); + var rmwHold = await device.EnterRmwAsync(parentName, ct).ConfigureAwait(false); try { var parentRuntime = await EnsureParentRuntimeAsync(device, parentName, ct).ConfigureAwait(false); @@ -1410,7 +1413,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag } finally { - rmwLock.Release(); + rmwHold.Dispose(); } } @@ -1501,8 +1504,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag // A bit-addressed index reads its parent word and decodes the bit, like the RMW path does. var runtimeName = (inner with { BitIndex = null }).ToLibplctagName(); - var gate = device.GetRmwLock(runtimeName); - await gate.WaitAsync(ct).ConfigureAwait(false); + var gate = await device.EnterRmwAsync(runtimeName, ct).ConfigureAwait(false); try { IAbLegacyTagRuntime runtime; @@ -1562,7 +1564,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag } finally { - gate.Release(); + gate.Dispose(); } } @@ -1741,7 +1743,11 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag private void WarnRefusalOnce(DeviceState device, AbLegacyTagDefinition def, string operation, string reason, uint status = AbLegacyStatusMapper.BadNotSupported) { - if (!device.RefusalLogged.TryAdd($"{operation}:{def.Name}", 0)) return; + // Keyed by the AUTHORED tag: an indirect resolution's name ("tag=>N7:42") changes with the index value, so + // keying on it grew the set (and re-warned) per value a sweeping index took (review 2026-12-02 P-23, L7). + var arrow = def.Name.IndexOf("=>", StringComparison.Ordinal); + var authored = arrow > 0 ? def.Name[..arrow] : def.Name; + if (!device.RefusalLogged.TryAdd($"{operation}:{authored}", 0)) return; // The status the operation is actually answered with (review 07 r0 M8) — not always BadNotSupported. _logger.LogWarning( "AbLegacy {Operation} refused (0x{Status:X8}). Driver={DriverInstanceId} Device={DeviceHostAddress} Reference={Reference} Address={Address} Reason={Reason}", @@ -1764,7 +1770,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag { if (device.Runtimes.TryGetValue(def.Name, out var existing)) return existing; - var parsed = AbLegacyAddress.TryParse(def.Address, device.Options.PlcFamily) + var parsed = device.ParseAddress(def) ?? throw new InvalidOperationException( $"AbLegacy tag '{def.Name}' has malformed Address '{def.Address}' for PLC family {device.Options.PlcFamily}."); var createParams = CreateParamsFor(device, def, parsed); @@ -1813,6 +1819,16 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag } } + /// + /// Evicts the handle an operation used and saw fail — by identity when the operation got as far as holding one + /// (a sibling's fresh reconnect is left alone), by name only when it failed before it held any (#1031). + /// + private static void EvictUsedRuntime(DeviceState device, string tagName, IAbLegacyTagRuntime? used) + { + if (used is not null) EvictRuntime(device, tagName, used); + else EvictRuntime(device, tagName); + } + /// /// , but only if the cached runtime for /// is still — the one the caller actually used and saw fail. Without the identity @@ -1976,15 +1992,102 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag } } - private readonly System.Collections.Concurrent.ConcurrentDictionary _rmwLocks = new(); + internal sealed class RmwGate + { + public readonly SemaphoreSlim Semaphore = new(1, 1); + public int Users; // holders + waiters, under _rmwGatesLock + } + + private readonly Dictionary _rmwGates = new(StringComparer.Ordinal); + private readonly object _rmwGatesLock = new(); /// - /// Gets or creates the read-modify-write lock for the specified parent name. + /// Takes the read-modify-write gate of a parent word. The gate is reference-counted (holders + waiters) and + /// removed the moment its last user leaves, so a sweeping indirect bit-write index no longer leaves one + /// behind per word it ever resolved (review 2026-12-02 P-23, residual L7). + /// Removal at zero users is safe: nobody holds or awaits the gate, so a later caller's fresh gate cannot + /// race another RMW of the same word — the gate a waiter already counted on is never removed. /// - /// The parent name. - /// The semaphore slim for the parent. - public SemaphoreSlim GetRmwLock(string parentName) => - _rmwLocks.GetOrAdd(parentName, _ => new SemaphoreSlim(1, 1)); + /// The parent word's runtime key. + /// Cancels the wait. + /// The held gate; dispose it to release. + public async Task EnterRmwAsync(string parentName, CancellationToken ct) + { + RmwGate gate; + lock (_rmwGatesLock) + { + if (!_rmwGates.TryGetValue(parentName, out gate!)) _rmwGates[parentName] = gate = new RmwGate(); + gate.Users++; + } + try + { + await gate.Semaphore.WaitAsync(ct).ConfigureAwait(false); + } + catch + { + Leave(parentName, gate); + throw; + } + return new RmwHold(this, parentName, gate); + } + + private void Leave(string parentName, RmwGate gate) + { + lock (_rmwGatesLock) + { + if (--gate.Users == 0 + && _rmwGates.TryGetValue(parentName, out var current) && ReferenceEquals(current, gate)) + _rmwGates.Remove(parentName); + } + } + + /// A held read-modify-write gate; releases it (once). + public sealed class RmwHold + { + private DeviceState? _owner; + private readonly string _name; + private readonly RmwGate _gate; + + internal RmwHold(DeviceState owner, string name, RmwGate gate) + { + _owner = owner; + _name = name; + _gate = gate; + } + + /// Releases the gate; further calls are no-ops. + public void Dispose() + { + var owner = Interlocked.Exchange(ref _owner, null); + if (owner is null) return; + _gate.Semaphore.Release(); + owner.Leave(_name, _gate); + } + } + + // Parsed address per AUTHORED tag (P-24): every poll used to re-parse each address two or three times. + // Bounded by the authored tag set — an indirect resolution's synthetic name never enters it. A cached + // entry is honoured only while it was parsed from the same address text and family. + private readonly System.Collections.Concurrent.ConcurrentDictionary _parsedAddresses + = new(StringComparer.Ordinal); + + /// + /// The parsed form of 's address under this device's PLC family, memoised per + /// authored tag. A resolved indirect definition (its name carries =>) is parsed afresh, uncached. + /// + /// The tag definition. + /// The parsed address, or when it is malformed for the family. + public AbLegacyAddress? ParseAddress(AbLegacyTagDefinition def) + { + var family = Options.PlcFamily; + if (def.Name.Contains("=>", StringComparison.Ordinal)) return AbLegacyAddress.TryParse(def.Address, family); + if (_parsedAddresses.TryGetValue(def.Name, out var c) && c.Family == family + && string.Equals(c.Address, def.Address, StringComparison.Ordinal)) + return c.Parsed; + var parsed = AbLegacyAddress.TryParse(def.Address, family); + _parsedAddresses[def.Name] = (def.Address, family, parsed); + return parsed; + } private readonly System.Collections.Concurrent.ConcurrentDictionary _runtimeLocks = new(); @@ -2069,7 +2172,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag } /// The number of per-key gates currently held (runtime + RMW). Tests only. - internal int GateCount => _runtimeLocks.Count + _rmwLocks.Count; + internal int GateCount { get { lock (_rmwGatesLock) return _runtimeLocks.Count + _rmwGates.Count; } } /// Test seam: invoked with the runtime key just before an operation waits on its gate (after the /// handle was fetched), so a test can act at exactly that point instead of sleeping. @@ -2129,6 +2232,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag if (ParentRuntimes.TryRemove(key, out var r)) try { r.Dispose(); } catch { /* best-effort */ } IndirectLastName.Clear(); + _parsedAddresses.Clear(); } } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireClient.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireClient.cs index ad59440e3..de237a35e 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireClient.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireClient.cs @@ -1362,7 +1362,7 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable private static void RequireLength(byte[] payload, int length, string call) { if (payload.Length < length) - throw new FocasWireException($"{call} returned {payload.Length} bytes; expected at least {length}.", rc: null); + throw new FocasWirePayloadException($"{call} returned {payload.Length} bytes; expected at least {length}."); } private static bool IsTransientException(Exception exception) diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireException.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireException.cs index 37e493caa..2ac954229 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireException.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireException.cs @@ -62,3 +62,19 @@ public class FocasWireException : Exception IsTransient = isTransient; } } + +/// +/// A well-formed reply whose payload is too short to decode (#1036). The CNC answered and the session is +/// intact, so this is a decode refusal for the one tag - not a comms fault - and maps to +/// BadTypeMismatch rather than BadCommunicationError (which would degrade driver health and feed +/// the #527 watchdog over a shape problem that no reconnect can fix). +/// +public sealed class FocasWirePayloadException : FocasWireException +{ + /// Initializes a new short/malformed-payload exception. + /// The exception message. + public FocasWirePayloadException(string message) + : base(message, rc: null) + { + } +} diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/WireFocasClient.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/WireFocasClient.cs index 918a1d195..f5ed42987 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/WireFocasClient.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/WireFocasClient.cs @@ -403,7 +403,7 @@ public sealed class WireFocasClient : IFocasClient } catch (FocasWireException ex) { - return (null, ex.Rc is short rc ? FocasStatusMapper.MapFocasReturn(rc) : FocasStatusMapper.BadCommunicationError); + return (null, MapWireFailure(ex)); } } @@ -419,7 +419,7 @@ public sealed class WireFocasClient : IFocasClient } catch (FocasWireException ex) { - return (null, ex.Rc is short rc ? FocasStatusMapper.MapFocasReturn(rc) : FocasStatusMapper.BadCommunicationError); + return (null, MapWireFailure(ex)); } } @@ -460,6 +460,20 @@ public sealed class WireFocasClient : IFocasClient }; } + /// + /// The status a wire failure publishes: the CNC's own rc when it sent one; BadTypeMismatch for a reply + /// whose payload is too short to decode (#1036 - the session is intact and the CNC answered, so a shape problem + /// is a per-tag refusal, never a comms fault); otherwise BadCommunicationError. + /// + /// The wire failure. + /// The OPC UA status to publish for the tag. + internal static uint MapWireFailure(FocasWireException ex) + => ex.Rc is short rc + ? FocasStatusMapper.MapFocasReturn(rc) + : ex is FocasWirePayloadException + ? FocasStatusMapper.BadTypeMismatch + : FocasStatusMapper.BadCommunicationError; + private async Task<(object? value, uint status)> ReadMacroAsync( FocasAddress address, FocasDataType type, CancellationToken cancellationToken) { @@ -472,7 +486,7 @@ public sealed class WireFocasClient : IFocasClient } catch (FocasWireException ex) { - return (null, ex.Rc is short rc ? FocasStatusMapper.MapFocasReturn(rc) : FocasStatusMapper.BadCommunicationError); + return (null, MapWireFailure(ex)); } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttWriteEncoder.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttWriteEncoder.cs index 2a4dfe17e..9910430f1 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttWriteEncoder.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttWriteEncoder.cs @@ -192,6 +192,14 @@ public static class MqttWriteEncoder text = value switch { bool b => b ? "true" : "false", + // #1044: a DateTime through IFormattable published "08/10/2026 12:30:45" (month-first, no + // zone) — ambiguous and unparseable by most devices. ISO-8601 UTC round-trip form, with the + // same Unspecified-is-UTC rule the Sparkplug DateTime encode uses so two nodes of a + // redundant pair publish the same text for the same authored value. + DateTime dt => (dt.Kind == DateTimeKind.Unspecified + ? DateTime.SpecifyKind(dt, DateTimeKind.Utc) + : dt.ToUniversalTime()).ToString("O", CultureInfo.InvariantCulture), + DateTimeOffset dto => dto.UtcDateTime.ToString("O", CultureInfo.InvariantCulture), IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), _ => value.ToString() ?? "", }; diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.Tests/Logix/LogixTagClientTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.Tests/Logix/LogixTagClientTests.cs index d54f270c2..5c5d7c3ed 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.Tests/Logix/LogixTagClientTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.Tests/Logix/LogixTagClientTests.cs @@ -46,6 +46,23 @@ public sealed class LogixTagClientTests ch.Sent[0].ShouldBe(LogixServices.ReadTagFragmented(Path, 1, 0)); // libplctag's wire shape (golden captures) } + [Fact] + public async Task Repeated_reads_reuse_the_offset_zero_request_and_a_changed_count_rebuilds_it() + { + var (ch, client, s) = Create(); + await using var _ = s; + ch.RespondPerService = r => FakeCipChannel.Reply(r[0], 0x00, TypedData(LogixTypeCode.DInt, [1, 0, 0, 0])); + + await client.ReadAsync(Path, 1, Ct); + await client.ReadAsync(Path, 1, Ct); + await client.ReadAsync(Path, 2, Ct); + + ch.Sent.Count.ShouldBe(3); + ch.Sent[0].ShouldBe(LogixServices.ReadTagFragmented(Path, 1, 0)); + ch.Sent[1].ShouldBe(LogixServices.ReadTagFragmented(Path, 1, 0)); + ch.Sent[2].ShouldBe(LogixServices.ReadTagFragmented(Path, 2, 0)); // not the stale cached request + } + [Fact] public async Task Fragmented_read_keeps_the_first_partial_and_continues() { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyIndirectAddressingTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyIndirectAddressingTests.cs index bd0348220..248393e34 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyIndirectAddressingTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.Tests/AbLegacyIndirectAddressingTests.cs @@ -156,4 +156,95 @@ public sealed class AbLegacyIndirectAddressingTests // Only the live resolution's handle (plus the index word's parent runtime) remains cached. state.Runtimes.Keys.Count(k => k.StartsWith("Ind=>", StringComparison.Ordinal)).ShouldBe(1); } + + /// + /// #1031 (review 2026-12-02 P-23, residual L7): an indirect BIT write resolves to a different parent word per + /// index value, and each word used to leave its read-modify-write gate behind. The gates are reference-counted + /// and dropped when their last user leaves, so the table does not grow with the index. + /// + [Fact] + public async Task Sweeping_index_bit_writes_leave_no_rmw_gates_behind() + { + var (drv, f) = await NewDriverAsync(new AbLegacyTagDefinition("IndBit", Host, "N7:[N7:0]/3", AbLegacyDataType.Bit, Writable: true)); + short index = 10; + f.Customise = p => new FakeAbLegacyTag(p) { Value = p.TagName == "N7:0" ? index : (short)0 }; + var state = drv.GetDeviceState(Host)!; + + for (short i = 10; i < 60; i++) + { + index = i; + if (f.Tags.TryGetValue("N7:0", out var idx)) idx.Value = i; + (await drv.WriteAsync([new WriteRequest("IndBit", true)], CancellationToken.None))[0] + .StatusCode.ShouldBe(AbLegacyStatusMapper.Good); // positive control: every sweep step really wrote + } + + // The sweep really touched many distinct words ... + f.Tags.Keys.Count(k => k.StartsWith("N7:", StringComparison.Ordinal)).ShouldBeGreaterThan(10); + // ... and no RMW gate outlives its last user (the runtime gates for the live resolution remain, bounded). + state.GateCount.ShouldBeLessThan(6); + } + + [Fact] + public async Task The_rmw_gate_serialises_users_of_one_word_and_is_removed_with_its_last_user() + { + var (drv, _) = await NewDriverAsync(new AbLegacyTagDefinition("T", Host, "N7:1", AbLegacyDataType.Int)); + var state = drv.GetDeviceState(Host)!; + var baseline = state.GateCount; + + var first = await state.EnterRmwAsync("N7:5", CancellationToken.None); + state.GateCount.ShouldBe(baseline + 1); + var second = state.EnterRmwAsync("N7:5", CancellationToken.None); + await Task.Delay(50, TestContext.Current.CancellationToken); + second.IsCompleted.ShouldBeFalse(); // serialised behind the holder + + first.Dispose(); + first.Dispose(); // idempotent: must not release the waiter's turn twice + var held = await second; + state.GateCount.ShouldBe(baseline + 1); // still one gate: the waiter took over the same one + var third = state.EnterRmwAsync("N7:5", CancellationToken.None); + await Task.Delay(50, TestContext.Current.CancellationToken); + third.IsCompleted.ShouldBeFalse(); // the double dispose did not free a second slot + + held.Dispose(); + (await third).Dispose(); + state.GateCount.ShouldBe(baseline); + } + + [Fact] + public async Task A_cancelled_rmw_wait_does_not_leak_its_gate() + { + var (drv, _) = await NewDriverAsync(new AbLegacyTagDefinition("T", Host, "N7:1", AbLegacyDataType.Int)); + var state = drv.GetDeviceState(Host)!; + var baseline = state.GateCount; + var holder = await state.EnterRmwAsync("N7:9", CancellationToken.None); + using var cts = new CancellationTokenSource(); + var waiting = state.EnterRmwAsync("N7:9", cts.Token); + cts.Cancel(); + await Should.ThrowAsync(async () => await waiting); + + holder.Dispose(); + state.GateCount.ShouldBe(baseline); + } + + /// #1031 P-24: an authored tag's address is parsed once, and re-parsed only when its text changes. + [Fact] + public async Task Authored_addresses_are_parsed_once_per_tag_and_reparsed_on_change() + { + var (drv, _) = await NewDriverAsync(new AbLegacyTagDefinition("T", Host, "N7:1", AbLegacyDataType.Int)); + var state = drv.GetDeviceState(Host)!; + var def = new AbLegacyTagDefinition("T", Host, "N7:1", AbLegacyDataType.Int); + + var a = state.ParseAddress(def); + a.ShouldNotBeNull(); + ReferenceEquals(state.ParseAddress(def), a).ShouldBeTrue(); + + var changed = state.ParseAddress(def with { Address = "N7:2" }); + changed!.WordNumber.ShouldBe(2); + state.ParseAddress(def with { Address = "not-an-address" }).ShouldBeNull(); // a malformed address caches too + + // A resolved indirect definition (synthetic "tag=>concrete" name) never enters the cache. + var resolved = def with { Name = "T=>N7:7", Address = "N7:7" }; + state.ParseAddress(resolved)!.WordNumber.ShouldBe(7); + ReferenceEquals(state.ParseAddress(resolved), state.ParseAddress(resolved)).ShouldBeFalse(); + } } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasMacroDecodeTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasMacroDecodeTests.cs index 15bcdaab6..1b35d595b 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasMacroDecodeTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/FocasMacroDecodeTests.cs @@ -95,6 +95,27 @@ public sealed class FocasMacroDecodeTests Should.Throw(() => FocasWireClient.ParseMacro(1, new byte[length])); } + // #1036: a short payload is a decode refusal on a live session, not a comms fault. + [Theory] + [InlineData(0)] + [InlineData(7)] + public void A_short_macro_payload_publishes_BadTypeMismatch_not_BadCommunicationError(int length) + { + var ex = Should.Throw(() => FocasWireClient.ParseMacro(1, new byte[length])); + WireFocasClient.MapWireFailure(ex).ShouldBe(FocasStatusMapper.BadTypeMismatch); + } + + [Fact] + public void Wire_failures_without_a_payload_shape_problem_keep_their_comms_mapping() + { + WireFocasClient.MapWireFailure(new FocasWireException("link down", rc: null)) + .ShouldBe(FocasStatusMapper.BadCommunicationError); + WireFocasClient.MapWireFailure(new FocasWireException("closed", new System.IO.IOException(), isTransient: true)) + .ShouldBe(FocasStatusMapper.BadCommunicationError); + WireFocasClient.MapWireFailure(new FocasWireException("refused", rc: 7)) + .ShouldBe(FocasStatusMapper.MapFocasReturn(7)); + } + // ---- published value / quality ---- [Fact] diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MqttReview20261202Tests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MqttReview20261202Tests.cs index 55b3a16e4..e0d8d6edf 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MqttReview20261202Tests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MqttReview20261202Tests.cs @@ -422,6 +422,46 @@ public sealed class MqttReview20261202Tests Encoding.UTF8.GetString(encoded.Payload).ShouldBe(expected); } + // --------------------------------------------------------------------------------- + // #1044 — Plain Scalar/Raw DateTime writes publish ISO-8601 UTC, not the culture-style "MM/dd/yyyy HH:mm:ss" + // --------------------------------------------------------------------------------- + + [Theory] + [InlineData("Scalar", DateTimeKind.Utc)] + [InlineData("Raw", DateTimeKind.Utc)] + [InlineData("Scalar", DateTimeKind.Unspecified)] + public void DateTime_writes_publish_iso8601_utc(string format, DateTimeKind kind) + { + MqttTagDefinitionFactory.FromTagConfig( + $$"""{"topic":"t/d","writeTopic":"t/d/set","payloadFormat":"{{format}}","dataType":"DateTime"}""", + "P/d", + out var def).ShouldBeTrue(); + + var value = new DateTime(2026, 8, 10, 12, 30, 45, 123, kind); + MqttWriteEncoder.TryEncode(MqttMode.Plain, def, value, out var encoded).ShouldBe(MqttWriteEncodeError.None); + + var text = Encoding.UTF8.GetString(encoded.Payload); + text.ShouldBe("2026-08-10T12:30:45.1230000Z"); + DateTime.Parse(text, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind) + .ShouldBe(DateTime.SpecifyKind(value, DateTimeKind.Utc)); + } + + [Fact] + public void DateTimeOffset_and_local_datetime_writes_publish_the_same_utc_instant() + { + MqttTagDefinitionFactory.FromTagConfig( + """{"topic":"t/d","writeTopic":"t/d/set","payloadFormat":"Scalar","dataType":"DateTime"}""", + "P/d", + out var def).ShouldBeTrue(); + + var offset = new DateTimeOffset(2026, 8, 10, 14, 30, 45, TimeSpan.FromHours(2)); + MqttWriteEncoder.TryEncode(MqttMode.Plain, def, offset, out var a).ShouldBe(MqttWriteEncodeError.None); + Encoding.UTF8.GetString(a.Payload).ShouldBe("2026-08-10T12:30:45.0000000Z"); + + MqttWriteEncoder.TryEncode(MqttMode.Plain, def, offset.LocalDateTime, out var b).ShouldBe(MqttWriteEncodeError.None); + Encoding.UTF8.GetString(b.Payload).ShouldBe("2026-08-10T12:30:45.0000000Z"); + } + /// /// A fake SUBSCRIBE transport that throws a client-side protocol violation for any batch carrying /// poison — the shape MQTTnet produces for a malformed filter — or a session failure.