diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md
index f43bfbd00..8b3bcf179 100644
--- a/.claude/rules/drivers.md
+++ b/.claude/rules/drivers.md
@@ -211,8 +211,11 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
retain handling rides only a 5.0 SUBSCRIBE (MQTTnet refuses it on 3.1.1). Sparkplug metadata rebirths are
capped at 3 per SCOPE and re-armed only by clean data for that scope (never by a birth — a rebirth request
provokes one); gap rebirths escalate to one per 5 min after 3 with no contiguous message. A `Faulted`
- primary-host claim connection is not a held claim (re-claimed); with `clientId` unset the claim id is a
- random `spbhost-<12 hex>`.
+ primary-host claim connection is not a held claim (re-claimed); with `clientId` unset the claim id is
+ `spbhost-<12 hex>` = a STABLE hash of host id + group id — the same on both nodes of a pair, so a cold-starting
+ Secondary's claim takes the Primary's over instead of coexisting (never make it random again). The claim
+ subscribes to its own STATE topic and re-asserts over an OFFLINE it did not publish (older/equal ts ⇒ republish;
+ newer ⇒ fresh claim with a newer ts; ≤ 1 per 2 s).
- **No driver-side history (#655):** `IHistoryProvider`, `DriverCapability.HistoryRead`, `HistoryReadStatusException` and
the OpcUaClient history passthrough are deleted — nothing ever dispatched HistoryRead to a driver; it is served only by the
server-wide `IHistorianDataSource`. `isHistorized` on an OpcUaClient tag means OtOpcUa records it, not that upstream
diff --git a/docs/drivers/Mqtt.md b/docs/drivers/Mqtt.md
index f53fa452d..8a18910fe 100644
--- a/docs/drivers/Mqtt.md
+++ b/docs/drivers/Mqtt.md
@@ -155,8 +155,9 @@ Every key has a default, so nothing is strictly required by the binder. Notable
> nodes reconnect every few seconds while still reporting `Healthy`. Unset (the default) lets MQTTnet
> generate a unique id per connection, which is correct. This was observed live during the P1 gate.
> (The probe and browser already self-uniquify with `-probe-` / `-browse-` suffixes, and with `clientId`
-> unset the Sparkplug primary-host claim presents a random per-instance `spbhost-<12 hex>` — #988 M-3; it was
-> the literal `-spbhost`, so two claiming drivers on one broker evicted each other.) `MqttDriverForm`
+> unset the Sparkplug primary-host claim presents `spbhost-<12 hex>`, a stable hash of the host id + group id —
+> #988 M-3; it was the literal `-spbhost`, so two claiming drivers on one broker evicted each other. It is
+> deliberately the SAME on both nodes of a pair, so a broker client-id takeover keeps the claim single.) `MqttDriverForm`
> defaults the field blank and raises this warning inline the moment a value is typed.
The form validates every knob against the driver's own `[Range]` bounds (port 1–65535, keep-alive /
@@ -393,8 +394,9 @@ warning — the driver does not publish to `spBv1.0/STATE/`, which is a legal to
### The claim is a whole connection, not a message
A Will can only be registered in the **CONNECT packet**. It cannot be added to a live session, changed,
-or withdrawn. So the claim gets its **own** broker connection (client id `{clientId}-spbhost`, or a random
-per-instance `spbhost-<12 hex>` when `clientId` is unset — #988 M-3; forced clean-session) whose lifetime *is* the claim: opened on gaining Primary, closed on losing it. Every leg
+or withdrawn. So the claim gets its **own** broker connection (client id `{clientId}-spbhost`, or
+`spbhost-<12 hex>` — a stable hash of the trimmed host id + group id — when `clientId` is unset; forced
+clean-session) whose lifetime *is* the claim: opened on gaining Primary, closed on losing it. Every leg
then follows from the connection's lifecycle rather than from bookkeeping that could drift.
The ingest session is untouched by a role change — no dropped subscriptions, no lost birth cache, and
@@ -430,6 +432,21 @@ raising events at per-instance drivers outlives every driver it holds a referenc
> members, which is the single-node row: a node cold-starting into a pair whose peer is already Primary
> can open the claim until its join completes (seconds; up to the bootstrap guard's 25 s partner probe),
> so both nodes may briefly hold it (review R6 MINOR-2).
+>
+> **Two mechanisms keep that window from ending on the wrong `STATE` (#988 review round 2):**
+> - **One claim id per pair.** With `clientId` unset the claim id is a pure function of the host id + group id,
+> so both nodes present the same id: the cold-starting node's CONNECT takes the Primary's claim session over
+> (the broker closes the older one), and the Primary's supervisor reconnects and re-asserts. A briefly random
+> per-instance id (the first M-3 fix) let both hold the topic at once, and the Secondary's stand-down `OFFLINE`
+> then sat retained, newer than the Primary's `ONLINE`, with nothing to correct it.
+> - **The claim watches its own `STATE` topic** (as Sparkplug 3.0 asks a host to) and re-asserts over an
+> `OFFLINE` it did not publish — its own stand-down detaches the claim before publishing, so the broker's echo
+> is ignored. An `OFFLINE` no newer than the claim's session (its own Will replayed, a stale death) is answered
+> by republishing the session's `ONLINE`; a **newer** one (another claimant's stand-down or Will) by a **fresh**
+> claim — clean disconnect, new Will + `ONLINE` with a timestamp past the observed one — because conformant
+> edge nodes ignore a `STATE` older than the one they hold. Re-asserts are coalesced, at most one per 2 s. On a
+> reconnect the claim re-subscribes BEFORE republishing, so the retained replay shows what the takeover left
+> behind. A broker ACL that refuses the subscription costs only this safety net (one Warning), never the claim.
> **Accepted trade: a brief edge-visible `OFFLINE` during failover**, while the old Primary stands down
> and the new one connects and republishes. That is a genuine state transition — for that window there
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs
index 346c11ea2..c84da8668 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs
@@ -108,6 +108,26 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable
private int _disposed;
+ /// Re-assert request kinds, in precedence order (a higher one subsumes a lower).
+ private const int ReassertRepublish = 1;
+
+ private const int ReassertFresh = 2;
+
+ /// Floor between two re-asserts, so a burst of foreign OFFLINEs costs one, not one per message.
+ internal static readonly TimeSpan ReassertMinInterval = TimeSpan.FromSeconds(2);
+
+ /// Pending re-assert request (0 = none, else the highest kind requested since the last run).
+ private int _reassertRequest;
+
+ /// 1 while a re-assert worker is running.
+ private int _reassertRunning;
+
+ /// When the last re-assert ran (worker-owned).
+ private DateTimeOffset _lastReassertUtc = DateTimeOffset.MinValue;
+
+ /// A fresh claim's session timestamp is at least this — one past the newest foreign OFFLINE observed.
+ private long _minNextSessionTimestampMs;
+
/// Creates a primary-host claim. Opens nothing — does that.
/// Broker connection settings; the host id comes from its Sparkplug section.
/// Driver instance id, for log correlation.
@@ -158,21 +178,35 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable
/// sharing a configured id already collide on their ingest connections).
///
///
- /// Blank clientId (the documented default): the id used to be the literal
- /// -spbhost — the ONE connection in the driver with a fixed, fleet-wide id (ingest gets a
- /// library-generated id, the probe and browser a random suffix). A plant with two Sparkplug groups
- /// needs two drivers, both claimed with -spbhost, and each CONNECT evicted the other: both
- /// STATE topics flapped ONLINE/OFFLINE about once a second while both drivers reported Healthy. A
- /// random per-instance id fixes it, and nothing depends on the id being stable — the claim session
- /// is forced clean. 20 characters, inside MQTT 3.1.1's guaranteed 23.
+ /// Blank clientId (the documented default): spbhost-{12 hex}, the hex being a
+ /// stable hash of the (trimmed) Sparkplug host id and group id. It used to be the literal
+ /// -spbhost — one fixed, fleet-wide id — so two drivers for two Sparkplug groups evicted each
+ /// other's claim about once a second (#988 M-3). The first fix made it RANDOM per instance, which
+ /// broke the other half of the contract: both nodes of a redundant pair run the same driver config,
+ /// and a Secondary that claims while cold-starting (before its cluster join tells it a Primary
+ /// exists) must present the SAME id as the Primary, so the broker's client-id takeover keeps the
+ /// claim single — the evicted Primary's supervisor reconnects and re-asserts. With two random ids both
+ /// held the topic, and the Secondary's stand-down OFFLINE landed newer than the Primary's ONLINE with
+ /// nothing to correct it (#988 review round 2). Deterministic over (host id, group) gives both: a pair
+ /// shares one id, distinct groups/hosts differ. 20 characters, inside MQTT 3.1.1's guaranteed 23.
///
///
/// The claim connection's options (blank client id already normalised to null).
/// The suffix.
- internal static string BuildClaimClientIdSuffix(MqttDriverOptions claimOptions) =>
- claimOptions.ClientId is null
- ? GeneratedClientIdPrefix + Guid.NewGuid().ToString("N")[..12]
- : ClientIdSuffix;
+ internal static string BuildClaimClientIdSuffix(MqttDriverOptions claimOptions)
+ {
+ if (claimOptions.ClientId is not null)
+ {
+ return ClientIdSuffix;
+ }
+
+ var identity = string.Concat(
+ claimOptions.Sparkplug?.HostId?.Trim() ?? string.Empty,
+ "\n",
+ claimOptions.Sparkplug?.GroupId?.Trim() ?? string.Empty);
+ var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(identity));
+ return GeneratedClientIdPrefix + Convert.ToHexStringLower(hash.AsSpan(0, 6));
+ }
/// Test seam: the client id the claim connection presents.
internal string ClaimClientIdForTests => string.Concat(_claimOptions.ClientId ?? string.Empty, _claimClientIdSuffix);
@@ -495,8 +529,13 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable
// ONE timestamp for both bodies — the Will is built here, before CONNECT, and the birth
// published after CONNACK. See SparkplugStatePayload's remarks on why they must match.
+ //
+ // Never older than a foreign OFFLINE this claim has already observed (see OnOwnStateMessage):
+ // Sparkplug 3.0 edge nodes ignore a STATE older than the one they hold, so a re-claim answering a
+ // newer OFFLINE must out-date it even across a little clock skew between the two claimants.
var session = SparkplugStatePayload.ForSession(
- _hostId, _timeProvider.GetUtcNow().ToUnixTimeMilliseconds());
+ _hostId,
+ Math.Max(_timeProvider.GetUtcNow().ToUnixTimeMilliseconds(), Interlocked.Read(ref _minNextSessionTimestampMs)));
var connection = new MqttConnection(
_claimOptions,
@@ -511,10 +550,19 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable
// single state this whole mechanism exists to make impossible.
cleanSessionOverride: true);
+ // Watch our own STATE topic (Sparkplug 3.0 asks a host to): an OFFLINE this claim did not just
+ // publish — another claimant's stand-down or Will — is re-asserted over. Non-blocking: the
+ // observer runs on MQTTnet's pump and only queues work.
+ connection.MessageReceived += (topic, payload, _) => OnOwnStateMessage(connection, session, topic, payload);
+
// Re-assert on every reconnect. A broker restart drops retained messages; without this the
- // host would be connected and believed offline by every edge node, silently.
+ // host would be connected and believed offline by every edge node, silently. The clean session
+ // lost the STATE subscription, so re-subscribe FIRST: the retained replay then shows what was
+ // there before this ONLINE — e.g. the OFFLINE of a same-id claimant (a cold-starting Secondary)
+ // whose takeover caused this reconnect, which a same-timestamp republish would not out-date.
connection.Reconnected += async ct =>
{
+ await WatchOwnStateAsync(connection, session.Topic, ct).ConfigureAwait(false);
await connection.PublishAsync(
session.Topic, session.OnlineBody, SparkplugStatePayload.StateQos, retain: true, ct)
.ConfigureAwait(false);
@@ -545,6 +593,9 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable
_session = session;
Volatile.Write(ref _connection, connection);
+ // After the commit, so a replayed/live OFFLINE observed from here on finds this claim current.
+ await WatchOwnStateAsync(connection, session.Topic, cancellationToken).ConfigureAwait(false);
+
_logger?.LogInformation(
"MQTT driver '{DriverId}': claimed Sparkplug primary host '{HostId}' — retained ONLINE published on '{Topic}', "
+ "OFFLINE armed as the Last Will.",
@@ -558,6 +609,213 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable
}
}
+ ///
+ /// Subscribes the claim connection to its own STATE topic. Best effort: a broker ACL that refuses it
+ /// costs the re-assert safety net, never the claim.
+ ///
+ private async Task WatchOwnStateAsync(MqttConnection connection, string topic, CancellationToken cancellationToken)
+ {
+ try
+ {
+ var outcomes = await connection
+ .SubscribeAsync([new MqttTopicSubscription(topic, SparkplugStatePayload.StateQos, SeedRetained: true)], cancellationToken)
+ .ConfigureAwait(false);
+ if (outcomes is [{ Granted: false } refused])
+ {
+ _logger?.LogWarning(
+ "MQTT driver '{DriverId}': the broker refused the Sparkplug primary host's subscription to its own STATE "
+ + "topic '{Topic}' ({Reason}); a foreign OFFLINE for '{HostId}' will not be re-asserted over.",
+ _driverId,
+ topic,
+ refused.Reason,
+ _hostId);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger?.LogWarning(
+ ex,
+ "MQTT driver '{DriverId}': could not subscribe the Sparkplug primary host to its own STATE topic '{Topic}'.",
+ _driverId,
+ topic);
+ }
+ }
+
+ ///
+ /// The claim's own-STATE observer (MQTTnet pump thread — classify and queue only). An OFFLINE seen
+ /// while this connection is still the held claim was not published by this claim: its own stand-down
+ /// detaches the connection BEFORE publishing (), so the broker's echo of it is
+ /// ignored here.
+ ///
+ ///
+ ///
+ /// - Timestamp <= this session's: our own Will (replayed after the broker thought we died) or a
+ /// stale death — republishing this session's ONLINE out-dates or pairs with it.
+ /// - Timestamp > this session's: a newer claimant's death (a same-host-id Secondary that claimed
+ /// while cold-starting, then stood down). Conformant edge nodes would ignore our older ONLINE, so the
+ /// claim is re-made with a FRESH, newer session (new Will + ONLINE).
+ ///
+ /// Both are coalesced and rate-limited ().
+ ///
+ private void OnOwnStateMessage(
+ MqttConnection connection, SparkplugStateSession session, string topic, ReadOnlySpan payload)
+ {
+ if (!string.Equals(topic, session.Topic, StringComparison.Ordinal)
+ || !SparkplugStatePayload.TryDecode(payload, out var online, out var timestampMs)
+ || online
+ || !ReferenceEquals(Volatile.Read(ref _connection), connection)
+ || Volatile.Read(ref _disposed) != 0)
+ {
+ return;
+ }
+
+ var kind = ReassertRepublish;
+ if (timestampMs > session.TimestampMs)
+ {
+ kind = ReassertFresh;
+ var floor = timestampMs + 1;
+ long current;
+ while ((current = Interlocked.Read(ref _minNextSessionTimestampMs)) < floor
+ && Interlocked.CompareExchange(ref _minNextSessionTimestampMs, floor, current) != current)
+ {
+ }
+ }
+
+ int pending;
+ while ((pending = Volatile.Read(ref _reassertRequest)) < kind
+ && Interlocked.CompareExchange(ref _reassertRequest, kind, pending) != pending)
+ {
+ }
+
+ TryStartReassertWorker();
+ }
+
+ private void TryStartReassertWorker()
+ {
+ if (Volatile.Read(ref _reassertRequest) == 0 || Interlocked.CompareExchange(ref _reassertRunning, 1, 0) != 0)
+ {
+ return;
+ }
+
+ CancellationToken token;
+ try
+ {
+ token = Volatile.Read(ref _loopCts)?.Token ?? new CancellationToken(canceled: true);
+ }
+ catch (ObjectDisposedException)
+ {
+ token = new CancellationToken(canceled: true);
+ }
+
+ if (token.IsCancellationRequested)
+ {
+ Interlocked.Exchange(ref _reassertRequest, 0);
+ Volatile.Write(ref _reassertRunning, 0);
+ return;
+ }
+
+ _ = Task.Run(() => ReassertLoopAsync(token), CancellationToken.None);
+ }
+
+ private async Task ReassertLoopAsync(CancellationToken ct)
+ {
+ try
+ {
+ while (!ct.IsCancellationRequested)
+ {
+ var wait = _lastReassertUtc == DateTimeOffset.MinValue
+ ? TimeSpan.Zero
+ : _lastReassertUtc + ReassertMinInterval - _timeProvider.GetUtcNow();
+ if (wait > TimeSpan.Zero)
+ {
+ await Task.Delay(wait, _timeProvider, ct).ConfigureAwait(false);
+ }
+
+ var kind = Interlocked.Exchange(ref _reassertRequest, 0);
+ if (kind == 0)
+ {
+ break;
+ }
+
+ _lastReassertUtc = _timeProvider.GetUtcNow();
+ await ReassertAsync(kind, ct).ConfigureAwait(false);
+ }
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested)
+ {
+ // Stand-down / shutdown.
+ }
+ catch (Exception ex)
+ {
+ // The reconcile loop still owns "no claim held → claim"; this only lost promptness.
+ _logger?.LogWarning(
+ ex,
+ "MQTT driver '{DriverId}': could not re-assert the Sparkplug primary host '{HostId}' over a foreign OFFLINE.",
+ _driverId,
+ _hostId);
+ }
+ finally
+ {
+ Volatile.Write(ref _reassertRunning, 0);
+ }
+
+ // A request that landed between the last exchange and the flag reset must not be stranded.
+ if (!ct.IsCancellationRequested)
+ {
+ TryStartReassertWorker();
+ }
+ }
+
+ private async Task ReassertAsync(int kind, CancellationToken ct)
+ {
+ if (!_roleSource.ShouldActAsPrimary)
+ {
+ return; // the reconcile loop is about to release; re-asserting would fight it
+ }
+
+ await _gate.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ if (Volatile.Read(ref _disposed) != 0 || _connection is not { } connection || _session is not { } session
+ || IsDead(connection))
+ {
+ return; // nothing held — the reconcile loop claims afresh on its own
+ }
+
+ if (kind == ReassertFresh && session.TimestampMs < Interlocked.Read(ref _minNextSessionTimestampMs))
+ {
+ _logger?.LogWarning(
+ "MQTT driver '{DriverId}': observed a newer Sparkplug OFFLINE for primary host '{HostId}' than its own claim "
+ + "(another claimant stood down or died); re-claiming with a fresh session.",
+ _driverId,
+ _hostId);
+
+ // A clean DISCONNECT: the broker discards this session's Will, so no OFFLINE of ours lands
+ // between here and the fresh claim's ONLINE.
+ Volatile.Write(ref _connection, null);
+ _session = null;
+ await connection.DisposeAsync().ConfigureAwait(false);
+ }
+ else
+ {
+ await connection.PublishAsync(
+ session.Topic, session.OnlineBody, SparkplugStatePayload.StateQos, retain: true, ct)
+ .ConfigureAwait(false);
+ _logger?.LogInformation(
+ "MQTT driver '{DriverId}': re-published Sparkplug primary-host ONLINE for '{HostId}' over an observed OFFLINE.",
+ _driverId,
+ _hostId);
+ return;
+ }
+ }
+ finally
+ {
+ _gate.Release();
+ }
+
+ await ClaimAsync(ct).ConfigureAwait(false);
+ }
+
private async Task ReleaseAsync(string reason, CancellationToken cancellationToken)
{
if (Volatile.Read(ref _connection) is null)
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs
index 141046998..b21f5ac04 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs
@@ -235,6 +235,59 @@ public sealed class MqttPrimaryHostLiveTests(MqttFixture fixture)
await ClearRetainedAsync(idB, ct);
}
+ ///
+ /// #988 review round 2, live: a redundant pair — same driver config, blank clientId, same host id.
+ /// The Primary holds the claim; the Secondary cold-starts before its cluster join, believes it is alone
+ /// and claims too (same claim id ⇒ the broker takes the Primary's session over), then learns its role and
+ /// stands down, publishing its OFFLINE. The Primary must end up holding the claim with a retained ONLINE a
+ /// late subscriber still sees — with the random per-instance id the Secondary's newer OFFLINE was left
+ /// retained and nothing corrected it.
+ ///
+ [Fact]
+ public async Task A_cold_starting_secondary_that_briefly_claims_leaves_the_primary_online()
+ {
+ SkipIfUnconfigured();
+
+ var ct = TestContext.Current.CancellationToken;
+ var hostId = NewHostId();
+ var pairOptions = Options(hostId) with { ClientId = null };
+ var primaryRole = new MutableRole(true);
+ var secondaryRole = new MutableRole(true); // pre-join: sees no peer, claims
+ await using var primary = new SparkplugPrimaryHost(pairOptions, "live-pair", primaryRole);
+ await using var secondary = new SparkplugPrimaryHost(pairOptions, "live-pair", secondaryRole);
+ primary.ClaimClientIdForTests.ShouldBe(secondary.ClaimClientIdForTests);
+
+ await primary.StartAsync(ct);
+ primary.IsClaimed.ShouldBeTrue();
+ await secondary.StartAsync(ct);
+
+ // Cluster join completes: the secondary stands down (explicit OFFLINE, newer than the primary's ONLINE).
+ await Task.Delay(TimeSpan.FromSeconds(2), ct);
+ secondaryRole.IsPrimary = false;
+ await WaitUntilAsync(() => !secondary.IsClaimed, ct);
+
+ // Settle, then ask the broker what a late-joining edge node would see.
+ long lastOnline = 0;
+ var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30);
+ while (DateTime.UtcNow < deadline)
+ {
+ await Task.Delay(TimeSpan.FromSeconds(3), ct);
+ await using var late = await StateWatcher.StartAsync(fixture, hostId, ct);
+ var retained = await late.WaitForOneAsync(Timeout, ct);
+ if (SparkplugStatePayload.TryDecode(retained, out var online, out var ts) && online && primary.IsClaimed)
+ {
+ lastOnline = ts;
+ break;
+ }
+ }
+
+ lastOnline.ShouldBeGreaterThan(0, "the Primary must re-assert a retained ONLINE after the Secondary's stand-down");
+
+ await secondary.StopAsync(ct);
+ await primary.StopAsync(ct);
+ await ClearRetainedAsync(hostId, ct);
+ }
+
// ---- helpers -----------------------------------------------------------------------------------
/// A per-test host id: the retained STATE outlives the test that wrote it.
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs
index 0a232f642..c04e55820 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs
@@ -36,6 +36,9 @@ internal sealed class MiniBroker : IDisposable
private readonly CancellationTokenSource _cts = new();
private readonly HashSet _live = [];
+
+ /// Per-socket write lock: writes beside the serve loop.
+ private readonly System.Runtime.CompilerServices.ConditionalWeakTable _writeLocks = new();
private readonly TcpListener _listener;
private int _acceptedCount;
@@ -106,6 +109,7 @@ internal sealed class MiniBroker : IDisposable
var topic = System.Text.Encoding.UTF8.GetString(buffer, at + 2, Math.Min(length, Math.Max(0, end - at - 2)));
at += 2 + length;
if (at >= end) return null;
+ Subscribed.Enqueue(topic);
grants.Add(RefuseSubscribe?.Invoke(topic) == true ? (byte)0x80 : (byte)(buffer[at] & 0x03));
at++;
}
@@ -124,13 +128,76 @@ internal sealed class MiniBroker : IDisposable
/// Every PUBLISH received, in arrival order, as (topic, payload).
public System.Collections.Concurrent.ConcurrentQueue<(string Topic, byte[] Payload)> Published { get; } = new();
+ /// Every topic filter a SUBSCRIBE carried, in arrival order (all clients).
+ public System.Collections.Concurrent.ConcurrentQueue Subscribed { get; } = new();
+
+ ///
+ /// Delivers one QoS 0 PUBLISH to every live client — the fake never forwards client publishes, so
+ /// this is how a test plays "another client published on a topic you subscribed to".
+ ///
+ /// The topic.
+ /// The body.
+ /// The retain flag as delivered (true = a retained replay).
+ /// A task completing once written.
+ public async Task InjectPublishAsync(string topic, byte[] payload, bool retain = false)
+ {
+ var topicBytes = System.Text.Encoding.UTF8.GetBytes(topic);
+ var remaining = 2 + topicBytes.Length + payload.Length;
+ var packet = new List { (byte)(0x30 | (retain ? 0x01 : 0x00)) };
+ do
+ {
+ var digit = (byte)(remaining % 128);
+ remaining /= 128;
+ packet.Add(remaining > 0 ? (byte)(digit | 0x80) : digit);
+ }
+ while (remaining > 0);
+
+ packet.Add((byte)(topicBytes.Length >> 8));
+ packet.Add((byte)(topicBytes.Length & 0xFF));
+ packet.AddRange(topicBytes);
+ packet.AddRange(payload);
+ var bytes = packet.ToArray();
+
+ TcpClient[] targets;
+ lock (_live)
+ {
+ targets = [.. _live];
+ }
+
+ foreach (var client in targets)
+ {
+ try
+ {
+ await WriteAsync(client.GetStream(), bytes);
+ }
+ catch (Exception)
+ {
+ // Torn down concurrently.
+ }
+ }
+ }
+
+ private async Task WriteAsync(NetworkStream stream, byte[] bytes)
+ {
+ var gate = _writeLocks.GetValue(stream, _ => new SemaphoreSlim(1, 1));
+ await gate.WaitAsync(_cts.Token);
+ try
+ {
+ await stream.WriteAsync(bytes, _cts.Token);
+ }
+ finally
+ {
+ gate.Release();
+ }
+ }
+
/// Handles one complete packet; returns false when the connection must close.
private async Task HandlePacketAsync(NetworkStream stream, byte[] packet)
{
var packetType = packet[0] & 0xF0;
if (packetType == 0x10)
{
- await stream.WriteAsync(new byte[] { 0x20, 0x02, 0x00, ConnAckReturnCode }, _cts.Token);
+ await WriteAsync(stream, new byte[] { 0x20, 0x02, 0x00, ConnAckReturnCode });
// A real broker closes the socket straight after refusing, which is what drives
// MQTTnet's DisconnectedAsync. Mirroring it keeps the fake honest.
@@ -139,11 +206,11 @@ internal sealed class MiniBroker : IDisposable
if (packetType == 0xC0)
{
- await stream.WriteAsync(PingResp, _cts.Token);
+ await WriteAsync(stream, PingResp);
}
else if (packetType == 0x80 && AnswerSubscribe && TryBuildSubAck(packet, packet.Length) is { } subAck)
{
- await stream.WriteAsync(subAck, _cts.Token);
+ await WriteAsync(stream, subAck);
}
else if (packetType == 0x30)
{
@@ -163,7 +230,7 @@ internal sealed class MiniBroker : IDisposable
Published.Enqueue((topic, packet[at..]));
if (qos == 1 && AckPublish)
{
- await stream.WriteAsync(new byte[] { 0x40, 0x02, idHigh, idLow }, _cts.Token);
+ await WriteAsync(stream, new byte[] { 0x40, 0x02, idHigh, idLow });
}
}
diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs
index fe80256f8..647b47510 100644
--- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs
+++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs
@@ -153,17 +153,19 @@ public sealed class SparkplugPrimaryHostTests
/// #988 review M-3: with the recommended blank clientId the claim id was the literal
/// -spbhost, the one fixed, fleet-wide id — two drivers claiming on one broker (two Sparkplug
/// groups need two drivers) evicted each other about once a second, flapping both STATE topics. Each
- /// claim now presents its own id.
+ /// distinct (host id, group) claim now presents its own id.
///
[Fact]
- public void Claims_with_a_blank_client_id_present_distinct_ids()
+ public void Claims_for_different_groups_or_hosts_present_distinct_ids()
{
var blank = Options() with { ClientId = null };
var a = new SparkplugPrimaryHost(blank, "drv-1", new FixedRole(true));
- var b = new SparkplugPrimaryHost(blank with { Sparkplug = blank.Sparkplug! with { GroupId = "Other" } }, "drv-2", new FixedRole(true));
- var whitespace = new SparkplugPrimaryHost(Options() with { ClientId = " " }, "drv-3", new FixedRole(true));
+ var otherGroup = new SparkplugPrimaryHost(blank with { Sparkplug = blank.Sparkplug! with { GroupId = "Other" } }, "drv-2", new FixedRole(true));
+ var otherHost = new SparkplugPrimaryHost(blank with { Sparkplug = blank.Sparkplug! with { HostId = "other-host" } }, "drv-3", new FixedRole(true));
+ var whitespace = new SparkplugPrimaryHost(Options() with { ClientId = " " }, "drv-4", new FixedRole(true));
- a.ClaimClientIdForTests.ShouldNotBe(b.ClaimClientIdForTests);
+ a.ClaimClientIdForTests.ShouldNotBe(otherGroup.ClaimClientIdForTests);
+ a.ClaimClientIdForTests.ShouldNotBe(otherHost.ClaimClientIdForTests);
a.ClaimClientIdForTests.ShouldNotBe(SparkplugPrimaryHost.ClientIdSuffix);
a.ClaimClientIdForTests.ShouldStartWith("spbhost-");
a.ClaimClientIdForTests.Length.ShouldBeLessThanOrEqualTo(23, "MQTT 3.1.1 servers need only accept 23-character ids");
@@ -174,6 +176,29 @@ public sealed class SparkplugPrimaryHostTests
.ClientId.ShouldBe(a.ClaimClientIdForTests);
}
+ ///
+ /// #988 review (round 2): the M-3 fix made the blank-clientId claim id RANDOM per instance, which
+ /// broke the single-claim exclusivity a redundant pair relied on. A Secondary cold-starting before its
+ /// cluster join claims too; with one shared id its CONNECT evicts the Primary's claim (whose supervisor
+ /// reconnects and re-asserts), with two random ids both hold the topic, and the Secondary's later
+ /// stand-down OFFLINE lands newer than the Primary's ONLINE with nothing to correct it. Both nodes of a
+ /// pair run the same driver config, so the id must be a pure function of it.
+ ///
+ [Fact]
+ public void Both_nodes_of_a_pair_present_the_same_claim_id()
+ {
+ var blank = Options() with { ClientId = null };
+ var nodeA = new SparkplugPrimaryHost(blank, "drv-1", new FixedRole(true));
+ var nodeB = new SparkplugPrimaryHost(blank, "drv-1", new FixedRole(false));
+
+ nodeA.ClaimClientIdForTests.ShouldBe(nodeB.ClaimClientIdForTests);
+
+ // The host id is trimmed everywhere else; the claim id must not depend on padding either.
+ var padded = new SparkplugPrimaryHost(
+ blank with { Sparkplug = blank.Sparkplug! with { HostId = " otopcua-primary " } }, "drv-1", new FixedRole(true));
+ padded.ClaimClientIdForTests.ShouldBe(nodeA.ClaimClientIdForTests);
+ }
+
/// Control: an operator-configured client id keeps its stable, ACL-friendly {clientId}-spbhost.
[Fact]
public void A_configured_client_id_keeps_the_stable_claim_id()
@@ -222,6 +247,122 @@ public sealed class SparkplugPrimaryHostTests
await host.DisposeAsync();
}
+ ///
+ /// #988 review (round 2), part 2: the claim subscribes to its own STATE topic and re-asserts when it sees an
+ /// OFFLINE it did not publish. A NEWER OFFLINE (another claimant's stand-down / Will) is answered with a
+ /// FRESH session — a new, newer timestamp — because Sparkplug 3.0 edge nodes ignore a STATE older than the
+ /// one they hold, so republishing the old ONLINE would be discarded.
+ ///
+ [Trait("Category", "SlowUnit")]
+ [Fact]
+ public async Task A_newer_foreign_offline_is_answered_with_a_fresh_newer_online()
+ {
+ using var broker = new MiniBroker { AckPublish = true };
+ var host = new SparkplugPrimaryHost(LocalBroker(broker), "drv-1", new FixedRole(shouldActAsPrimary: true));
+ await host.StartAsync(TestContext.Current.CancellationToken);
+ host.IsClaimed.ShouldBeTrue();
+ (await WaitUntilAsync(() => broker.Subscribed.Contains(StateTopic), TimeSpan.FromSeconds(10)))
+ .ShouldBeTrue("the claim must subscribe to its own STATE topic");
+ var firstTs = OnlineTimestamps(broker).Single();
+
+ await broker.InjectPublishAsync(StateTopic, SparkplugStatePayload.Encode(online: false, firstTs + 60_000));
+
+ (await WaitUntilAsync(() => OnlineTimestamps(broker).Count >= 2, TimeSpan.FromSeconds(15)))
+ .ShouldBeTrue("a foreign OFFLINE must be answered with a new ONLINE");
+ OnlineTimestamps(broker).Last().ShouldBeGreaterThan(firstTs + 60_000, "the re-asserted ONLINE must out-date the OFFLINE");
+ (await WaitUntilAsync(() => host.IsClaimed, TimeSpan.FromSeconds(10))).ShouldBeTrue();
+
+ await host.DisposeAsync();
+ }
+
+ /// An OFFLINE carrying this session's own timestamp (its Will, replayed) is answered by republishing the same ONLINE.
+ [Trait("Category", "SlowUnit")]
+ [Fact]
+ public async Task An_offline_for_this_session_republishes_the_same_online()
+ {
+ using var broker = new MiniBroker { AckPublish = true };
+ var host = new SparkplugPrimaryHost(LocalBroker(broker), "drv-1", new FixedRole(shouldActAsPrimary: true));
+ await host.StartAsync(TestContext.Current.CancellationToken);
+ (await WaitUntilAsync(() => broker.Subscribed.Contains(StateTopic), TimeSpan.FromSeconds(10))).ShouldBeTrue();
+ var ts = OnlineTimestamps(broker).Single();
+
+ await broker.InjectPublishAsync(StateTopic, SparkplugStatePayload.Encode(online: false, ts), retain: true);
+
+ (await WaitUntilAsync(() => OnlineTimestamps(broker).Count >= 2, TimeSpan.FromSeconds(15))).ShouldBeTrue();
+ OnlineTimestamps(broker).ShouldAllBe(t => t == ts);
+
+ await host.DisposeAsync();
+ }
+
+ ///
+ /// Control: the claim's OWN stand-down OFFLINE (echoed back by the broker — 3.1.1 has no No-Local) must not
+ /// be "re-asserted" over, or a released host would immediately claim itself back.
+ ///
+ [Trait("Category", "SlowUnit")]
+ [Fact]
+ public async Task The_claims_own_stand_down_offline_is_not_reasserted()
+ {
+ using var broker = new MiniBroker { AckPublish = true };
+ var role = new FixedRole(shouldActAsPrimary: true);
+ var host = new SparkplugPrimaryHost(LocalBroker(broker), "drv-1", role);
+ await host.StartAsync(TestContext.Current.CancellationToken);
+ (await WaitUntilAsync(() => broker.Subscribed.Contains(StateTopic), TimeSpan.FromSeconds(10))).ShouldBeTrue();
+ var ts = OnlineTimestamps(broker).Single();
+
+ role.PublishPrimaryRole(false);
+ (await WaitUntilAsync(() => !host.IsClaimed, TimeSpan.FromSeconds(10))).ShouldBeTrue();
+
+ // The echo of the stand-down arrives after release; nothing may react to it.
+ await broker.InjectPublishAsync(StateTopic, SparkplugStatePayload.Encode(online: false, ts));
+ await Task.Delay(TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
+ OnlineTimestamps(broker).Count.ShouldBe(1);
+
+ await host.DisposeAsync();
+ }
+
+ /// A burst of foreign OFFLINEs coalesces rather than producing one re-claim per message.
+ [Trait("Category", "SlowUnit")]
+ [Fact]
+ public async Task A_burst_of_foreign_offlines_coalesces()
+ {
+ using var broker = new MiniBroker { AckPublish = true };
+ var host = new SparkplugPrimaryHost(LocalBroker(broker), "drv-1", new FixedRole(shouldActAsPrimary: true));
+ await host.StartAsync(TestContext.Current.CancellationToken);
+ (await WaitUntilAsync(() => broker.Subscribed.Contains(StateTopic), TimeSpan.FromSeconds(10))).ShouldBeTrue();
+ var ts = OnlineTimestamps(broker).Single();
+
+ for (var i = 1; i <= 20; i++)
+ {
+ await broker.InjectPublishAsync(StateTopic, SparkplugStatePayload.Encode(online: false, ts + i));
+ }
+
+ (await WaitUntilAsync(() => OnlineTimestamps(broker).Count >= 2, TimeSpan.FromSeconds(15))).ShouldBeTrue();
+ await Task.Delay(TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken);
+ OnlineTimestamps(broker).Count.ShouldBeLessThanOrEqualTo(3, "20 OFFLINEs in a burst must not cost 20 re-claims");
+
+ await host.DisposeAsync();
+ }
+
+ private const string StateTopic = "spBv1.0/STATE/otopcua-primary";
+
+ private static MqttDriverOptions LocalBroker(MiniBroker broker) => Options() with
+ {
+ ClientId = null,
+ Host = "127.0.0.1",
+ Port = broker.Port,
+ UseTls = false,
+ ProtocolVersion = MqttProtocolVersion.V311,
+ ConnectTimeoutSeconds = 2,
+ ReconnectMinBackoffSeconds = 1,
+ ReconnectMaxBackoffSeconds = 1,
+ };
+
+ private static List OnlineTimestamps(MiniBroker broker) =>
+ [.. broker.Published
+ .Where(p => p.Topic == StateTopic)
+ .Select(p => SparkplugStatePayload.TryDecode(p.Payload, out var online, out var ts) && online ? ts : -1)
+ .Where(ts => ts >= 0)];
+
private static int OnlinePublishes(MiniBroker broker) =>
broker.Published.Count(p =>
p.Topic == "spBv1.0/STATE/otopcua-primary"